DETAILED ENGLISH NOTES Paragraph numbering restarts in each numbered subsection. Each numbered entry corresponds to the source paragraph or a closely related adjacent paragraph, following the grouping logic of the original notebook. ============================================================================== Volume I - Foundations of Programming English study notes for progintro_2_92_v1 (edition 2.92) ------------------------------------------------------------------------------ 1. Preliminary information 1.1 Computer: what it is 1 computer originally = a device for carrying out calculations - even a calculator application spends much of its work on the interface - history explains the change from arithmetic machines to general information processing 1.1.1 A little history 1 Schickard's calculating clock (1623): mechanical arithmetic - addition / subtraction of six-digit integers; bell signals overflow - original lost; working reconstruction made in 1960 - Leonardo's earlier drawings do not establish that a machine was built 2 Pascal's calculator: work started in 1642; surviving machine from 1645 - intended to help his father with tax calculations - decimal wheels; first five digits, later machines with more digits - addition directly; subtraction through complements 3 fixed five-digit arithmetic: carry beyond the last digit disappears - 00500 - 00134 = 00500 + 99866 -> 00366 - replace x - y with x + (100000 - y); overflow supplies the final subtraction 4 100000 - y = 99999 - y + 1 - replace every digit by its complement to 9, then add 1 - 00134 -> 99865 -> 99866; no borrowing needed 5 Pascal's actual subtraction method: - display both ordinary digits and their complements to 9 - enter complement of x, add y, read the complementary display - 99499 + 00134 = 99633 -> complementary reading 00366 6 complements are relevant beyond mechanical calculators - complement followed by adding 1 returns in machine representation of negative integers 7 Leibniz's machine: addition, subtraction, multiplication and division - multiplication through repeated additions; division through repeated subtractions - did not itself calculate square / cube roots, although multiplication helps with them 8 mechanical calculators lasted into the twentieth century - each individual operation automated - human still chose operations, recorded intermediate results and entered them again 9 Babbage's difference engine: proposed in 1822; work began in 1823 - finite differences -> automatic tables of polynomial approximations - expensive project remained unfinished - Babbage turned toward a universal machine instead of one special calculation 10 Scheutz built a working difference engine in 1843 - later sold machines to governments - modern reconstructions from Babbage's drawings demonstrated that the design could work 11 Babbage's analytical engine: proposed universal programmable machine - program controls operations - move intermediate results between storage locations - choose actions according to comparisons / analysis of data - design exceeded the practical engineering possibilities of its time 12 Ada Lovelace translated Menabrea's account of Babbage's lecture - added extensive notes, including instructions for Bernoulli numbers - commonly described as the first computer program - recognized possible manipulation of information beyond numbers, including music 13 book corrects a Russian quotation falsely attributed to Lovelace - author had reproduced it in earlier editions - checking the original revealed a much more specific discussion of music -> repetition in many sources does not establish authenticity 14 origin of the false quotation is uncertain - circulated before easy access to original sources - book warns against treating this Russian wording as Lovelace's statement 15 Zuse's Z1 (1938): mechanically implemented binary programmable machine - motor supplied motion; shaped metal plates implemented logical operations - illustrates that binary logic does not require electronic components 16 Zuse's successive machines: - Z1 unreliable; Z2 used relays for computation and mechanical memory - Z1 / Z2 read punched tape without rewinding -> no program loops - Z3 used relays and allowed loops, but lacked conditional jumps - Z4 added branching; completed in 1944 and survived the war 17 Zuse's work remained little known outside Germany - wartime research also produced relay and vacuum-tube computers elsewhere 18 vacuum-tube diode: - heated cathode emits electrons; anode attracts them - vacuum contains no ions carrying a reverse current -> current passes in only one direction 19 triode adds a control grid between cathode and anode - negative grid potential obstructs electrons - a small varying signal controls a larger current -> amplification 20 two cross-coupled triodes form a flip-flop - one conducts and keeps the other closed - pulse changes their roles -> two stable states -> one stored bit - other connections implement AND, OR and NOT 21 vacuum tubes remove mechanical delays but have limited reliability - ENIAC contained about 18000 tubes - failure of one component could require repair before computation continued 22 book's account of ENIAC / Colossus: - Mauchly and Eckert's ENIAC project became public after the war - secrecy and destruction of Colossus equipment / documentation delayed recognition of Flowers's work 23 book discusses conflicting accounts linking wartime secrecy to Coventry - treats the proposed explanation for destroying equipment as disputed 24 Colossus and Bombe are different machines - Colossus: Flowers's electronic work against Lorenz ciphers - Bombe: electromechanical machine associated with Turing and Enigma - book rejects attributing the Colossus project directly to Turing 25 Turing had worked with Flowers and recommended him for the Lorenz project 26 first computer generation = electronic computers using vacuum tubes - mechanical / relay machines fall outside this classification 27 stored-program principle: - instructions and data occupy the same uniform memory - instruction codes are representable as ordinary data -> associated with the name von Neumann architecture 28 EDVAC report and attribution: - Mauchly, Eckert, von Neumann and others discussed the design - von Neumann wrote the draft; circulated copies carried his name - book stresses collective origins of the architectural ideas 29 IAS was built under von Neumann's direction - not the first stored-program machine - book discusses Manchester Baby, EDVAC and MESM as earlier implementations 30 Feynman's account of fascination with computing: - experimenting with what a machine can do can distract from assigned work - author sees this curiosity as an important motivation for becoming a programmer 31 before stored programs, preparing a computation could require days of rewiring - ENIAC program embodied connections / switch settings - machine spent substantial time being configured between short calculations 32 stored instructions change both preparation and possibilities: - prepare a program separately, then load it quickly - process programs as data -> compilers and operating systems become possible 33 von Neumann architecture includes further principles beyond storing programs - fuller treatment appears in 3.1.1 34 early memory was very small - ENIAC initially used twenty ten-digit accumulator registers - Manchester Baby: 32 words of 32 bits - IAS word: one 40-bit number or two 20-bit instructions 35 LEO I: business information processing at J. Lyons & Co. - payroll, accounting and financial analysis - punched-tape input and printed documents - arithmetic only one part of the overall information processing 36 transistor provides electronic control analogous to a triode - small input controls current through another path - useful both for amplification and switching - two suitably connected transistors can store a bit 37 book traces the transistor to Bell Labs work in 1947 - improving manufacture made components smaller and more reliable - no heated cathode -> much lower power consumption than tubes 38 magnetic-core memory: ferrite rings store individual bits - transistor circuits + improved memory -> second computer generation - smaller size, lower cost / power, larger memory and better reliability 39 integrated circuits place many components on one crystal - third generation: computers assembled from integrated circuits - increasing integration eventually puts a whole CPU on one chip - Intel 4004 is identified as the first commercially available microprocessor - book also discusses the competing historical claim concerning MP944 40 microprocessor -> affordable desktop / personal computer - book calls this the fourth generation - treats the Japanese fifth-generation project as a different software direction 41 computers process any information with a usable representation - texts, databases, sound, images and video - book discusses tactile devices and limitations of recording taste / smell 42 computation is broader than arithmetic - supercomputers still serve large numerical tasks - a mathematical function may map objects of arbitrary kinds - digital information becomes strings over an alphabet -> information processing = computing a function from strings to strings 1.1.2 CPU, RAM, bus 1 bus: parallel lines carrying signals between components - address bus: which location / controller responds - data bus: transferred information - control bus: operation to perform connected to CPU, RAM and external-device controllers - RAM / controllers respond only when their address is selected 2-3 RAM: uniform addressable memory locations - each location has its own address - N address lines -> 2^N possible addresses - these addresses form the physical address space virtual address space: addresses presented to a program; introduced later 4-5 memory access: read or write - CPU selects address and sends operation signal - read: selected location places its value on data bus - write: selected location takes new value from data bus; old value lost - several adjacent locations can hold one value RAM is volatile: contents disappear when power is removed 6 RAM != disk storage - CPU accesses RAM directly - disks require controller operations performed by driver programs 7-8 ROM: retains contents without power; ordinary CPU writes cannot change it - startup program checks hardware, finds and loads the OS OS is a program: - receives privileged access and controls later programs - user programs work in allocated memory and request other actions from OS - drivers organize work with external devices 9 files: OS organization of information in long-term storage - names allow users to find saved information RAM allocation changes with running programs - OS tracks assigned regions - each program accesses its own allocated memory - memory regions do not need user-facing file names 1.1.3 CPU principles 1 CPU executes primitive operations specified by a program - registers hold information being processed - memory read / write transfers information between RAM and CPU 2 instruction set: operations implemented by a particular CPU - arithmetic, register copying, logical operations and jumps - some CPUs also operate directly on memory operands 3 machine instruction has an operation code - program = machine instructions stored in RAM instruction pointer stores address of next instruction CPU execution cycle: - fetch instruction at that address - advance instruction pointer by instruction size - decode and execute instruction - repeat 4 jump instructions explicitly change the instruction pointer - conditional: transfer only if condition holds - unconditional: transfer without a test - subroutine call: transfer while remembering return point 1.1.4 External devices 1 computer needs devices for input, output and long-term storage - direct CPU connections become inconvenient as device types multiply -> common bus and controllers separate CPU from device details 2 controller connects its device to the bus - CPU communicates through read / write operations - controller addresses may share memory address space or occupy I/O space - one controller can expose several I/O ports port write: issue command / data port read: obtain device status / results 3 driver knows the particular controller's ports and command meanings - normally part of the OS file-write example: - application requests OS to write a file - OS determines disk location - disk driver issues controller commands - controller performs operation - driver checks status and reports result to OS 1.1.5 Storage hierarchy 1 storage choices balance access speed, capacity and retention time registers: fastest access; small fixed capacity determined by CPU design - adding registers increases CPU complexity and cost 2 cache contains copies of information from RAM - keeps frequently needed data close to CPU - avoids slower communication with main memory - faster access requires more complex / expensive hardware 3 cache may have several levels - farther levels generally trade speed for capacity - book's particular level count / chip arrangement describes its hardware context 4 RAM holds executing programs and their working data - larger capacity than registers / cache, but still finite - RAM, cache and registers lose contents without power 5 disks / flash storage: persistent storage with access to arbitrary blocks - larger capacity and lower cost per unit than RAM - slower I/O through controllers - program code and working data must be loaded into RAM for CPU use - files normally reside here 6 magnetic tape: archival storage with sequential access - data normally copied to disk before use - drive expensive; many inexpensive cartridges reduce total cost per unit - appropriate storage conditions permit long retention - reading old media still requires compatible working equipment 1.1.6 Summary 1 CPU and RAM communicate through bus; external devices through controllers - drivers operate controllers - persistent files hold programs / data - load programs / data into RAM before processing 2 OS starts first and controls the machine - ordinary programs receive restricted access - operations beyond transforming assigned memory require OS services 3 these principles are prerequisites for programming - reread unclear material and resolve misunderstandings before proceeding 1.2 How to use a computer correctly 1.2.1 Operating systems and user interfaces 1 OS manages programs and peripheral devices - application requests a file by name and reads data into memory - OS handles device-specific work, including local / removable / network storage 2 book surveys Windows and the Unix family - Linux distributions, BSD systems, Android and Apple systems - describes relationships in the computing landscape of its edition 3 user interface can be an ordinary program outside the kernel - Unix separates interface programs from core OS responsibilities - book contrasts this with tighter Windows integration 4 many servers do not need a local graphical interface - machines run in equipment rooms; administrators manage them remotely - some have no video hardware at all 5 computer use does not inherently require graphics - text-mode file managers and even text-mode windows existed before widespread GUIs 6 widget interfaces arrange buttons, menus, input fields and other controls command-line interface: - user enters commands; computer executes them and reports results - interactive dialogue differs from submitting batches of jobs 7 teleprinter: keyboard input travels through a communication line - received characters are printed on paper - originally used for remote written communication 8 connecting teleprinters to computers enabled interactive command entry - commercially available devices avoided designing a new terminal 9 alphanumeric screen terminals replace printed output with display output - keyboard still sends characters through a line - removes continual paper consumption 10 escape sequences control terminal display - move cursor, change attributes / colours, alter existing screen contents 11 terminal emulation reproduces terminal behaviour in software - serial connection can configure a server before network access exists - later administration normally uses the network 12 command interpreter / shell: - displays prompt, reads a command line, executes it - first word identifies command; following words are arguments - built-in commands handled by shell; others found as executable files - one line can combine several cooperating commands 13 Unix does not force users to avoid a GUI - book uses macOS as an example of Unix foundations with a graphical environment - professionals can also choose its terminal / shell 14 window manager controls window appearance and behaviour - Unix users can choose different managers independently of applications 15 Unix offers icon-based and two-panel file managers - author prefers shell commands for frequent file operations 16 book contrasts Unix shells with the Windows command interpreter of its period - notes availability of Unix-derived tools on Windows 17 both graphical and command interfaces require learning - familiar GUI gestures can conceal how much was learned - author argues that habit with one interface is not universal intuitiveness 18 command editing, history and filename completion reduce typing photo-copy example: - enter destination year directory; create trip directory - mount card; copy photos; unmount card - Tab completes paths; history recalls commands / previous arguments 19 repeated command sequence can become a shell script - trip directory supplied as argument: ./getphotos Milan - improved version checks missing argument and reuses a destination variable -> explicit commands allow the procedure to be parameterized and repeated 20 graphical applications can also start from a shell - program name followed by document / URL and other arguments - trailing & permits continued shell use 21 shell composition: - insert command output into another command - pipe one program's output into another program's input - combine existing tools in ways their authors did not anticipate 22 author treats command-line competence as essential professional preparation - also uses it as a teaching tool throughout the book 23 book assumes a Unix system and regular command-line work - remaining chapter introduces the required everyday skills 1.2.2 History of Unix 1 Bell Labs participation in MULTICS preceded Unix - after leaving the project, Ken Thompson developed a smaller system on a PDP-7 - book relates the development to his interest in games and available hardware 2 UNICS name proposed by Kernighan; spelling later became Unix - Thompson and Ritchie moved system to PDP-11 - B was too limited for desired system implementation - Ritchie's extension of B became C 3 Unix rewritten in C in 1973 - challenged the assumption that an OS must be written in low-level language - linked the later development of Unix and C 4 1974 paper attracted users, especially at universities - AT&T's legal position encouraged noncommercial source distribution - port to Interdata 8/32 completed in 1977 - portable C compiler helped separate system implementation from one CPU 5 Berkeley contributed the BSD branch - BSD = Berkeley Software Distribution - research began in the 1970s; Bill Joy produced first distribution in 1977 6 AT&T commercialization brought licensing disputes - Berkeley worked to remove AT&T-owned code - book describes eventual settlement after Unix business passed to Novell 7 legal uncertainty delayed freely available Unix on inexpensive Intel machines - 80386 had suitable hardware capabilities before widespread free ports appeared 8 Stallman's free-software movement developed tools for a free system - lacked a complete free kernel - Torvalds began an independent Unix-like kernel for i386 in 1991 9 Torvalds's initial terminal-emulator project expanded - scheduler handled incoming / outgoing streams - file-transfer needs led to disk support -> growing set of components became an operating-system kernel 10 publishing intermediate source attracted volunteer developers 11 Linux name supplied by another participant; Torvalds had considered Freax - first public code in 1991; version 1.0 in 1994 - BSD disputes helped Linux gain an early audience - kernel plus existing free tools provided a usable free system 12 Linux has many copyright holders - book explains distribution under GNU GPL v2 - one company cannot simply purchase all contributors' rights as one owner's asset 13 Unix now denotes a broad family and shared approach - book distinguishes free Linux / BSD systems from commercial Unix variants 14 Unix foundations survived major changes in hardware and interfaces - graphical environments can be added without replacing core principles - Android uses Linux; Apple systems have BSD-related ancestry 1.2.3 Unix on a home computer 1 book introduces freely distributed Unix systems and their application packages - installation instructions and software available from their communities 2 author recommends a Linux distribution for the first installation - BSD variants can be explored after gaining experience 3 transition can be gradual; immediate abandonment of the previous environment unnecessary 4 separate spare computer is one possible installation target - lightweight systems can make older hardware useful - very old hardware may restrict available application versions 5 another option: allocate disk space alongside an existing OS - preserve needed files before repartitioning / replacing a filesystem - book's quoted capacity is an example from its period 6 author prefers a lightweight window manager - distinguishes window management from a complete desktop environment - this preference supports the book's emphasis on shell use 7 find and configure a terminal emulator - book suggests an 80-column layout and comfortably readable character size - background / text colour recommendations reflect the author's preference 8 make opening a terminal easy - keyboard shortcut or readily accessible launcher - save suitable font / window settings -> comfortable setup reduces friction during study 9 install applications needed for ordinary work - browser, office documents, PDF / image viewing, audio / video - learn the equivalents of familiar tasks in the new environment 10 book's programming tools: - text editors: Vim, JOE, nano - Free Pascal, NASM, GCC with C / C++ support - make and GDB - package names can differ between systems 11 use an unprivileged account for ordinary work - administrative access reserved for system changes - book additionally expresses its own preference for separate root sessions over sudo - console-switch key examples depend on system configuration 1.2.4 First session in a computer classroom 1 classroom Unix may run locally or on a shared remote server - basic user workflow remains similar 2 log in with assigned username and password - letter case matters; Login incorrect can mean either value is wrong 3 obtain a shell - remote terminal / text console normally provides it after login - graphical session: open xterm or another terminal emulator - book uses startx for starting an X session where configured 4 change an initially assigned password using passwd - current password, then new password twice; characters are not echoed - book gives a mnemonic phrase method and period-specific composition advice - keep account credentials private; do not let others work under your identity 1.2.5 Directory tree and file operations 1 example prompt: user@host:directory$ - prompt is printed by shell; do not type it as part of command - ~ represents home directory; # conventionally marks administrator prompt 2 Unix path conventions: - one directory tree; no drive letters - / separates directory components 3 login starts in home directory - pwd: print current directory - ls: list names; ls -a includes names beginning with . - ls -F marks types, including / for directories - . = current directory; .. = parent directory 4 cd changes current directory - cd tmp: child directory; cd ..: parent - cd /usr/include: specified absolute path; cd /: root - cd without argument: home directory 5 each process has its own current directory - changing directory in one shell does not change another shell's directory 6 basic file operations: - cp: copy; mv: move / rename; rm: remove - mkdir / rmdir: create / remove directory - touch: create empty file or update timestamps; less: view contents - options modify commands; rm -r removes a directory tree recursively 7 absolute path starts with / and is independent of current directory - /home/vasya/photos/mars.jpg identifies each component from root 8 short name refers to an entry in current directory - mars.jpg works when current directory is /home/vasya/photos 9 relative path starts from current directory - photos/mars.jpg from /home/vasya - ../vasya/photos/mars.jpg from /home/anya - each .. ascends one directory level 10 paths can include redundant descents / ascents - system resolves these components rather than requiring a shortest spelling - useful when a program constructs a path from separate pieces 11 . can appear inside a path - ./photos/./mars.jpg refers through the current directory at each . component 12 file path = name including directory components - commands generally accept absolute / relative paths wherever a filename is expected 13 book recommends simple portable filenames - letters, digits, . and _; - acceptable except as initial character - spaces / punctuation require quoting; leading - can be mistaken for an option 1.2.6 Commands and arguments 1 ; separates commands executed one after another - separator belongs to shell syntax, not to either command's arguments 2 first word = command name; remaining words = arguments - shell supplies strings; command decides their meaning - echo prints its arguments 3 unquoted spaces separate words; extra separator spaces do not become argument data - interactive Tab normally requests completion - filenames containing spaces require a way to preserve those spaces 4 three ways to protect special characters: - backslash before character - single quotes around text - double quotes around text - quoting / escape syntax removed before arguments reach the program - protected ; is literal data rather than a command separator 5 single quotes preserve every enclosed character literally - a single quote cannot be escaped inside that quoted region - use another quoting / escaping context to include it double quotes retain some special processing - variable / command substitution and selected backslash escapes still work - interactive history behaviour depends on shell 6 quoted and unquoted adjacent fragments form one word - "abra"schwabra'kadabra' -> abraschwabrakadabra - "" or '' supplies an empty argument 1.2.7 Filename patterns 1 shell expands unquoted filename patterns before running command - ? matches one character; * matches any string, including empty - ??? = three-character name; ???* = at least three characters - *.txt = names ending in .txt - one pattern can become many separate arguments 2 command receives expanded names, not instructions to expand a pattern - echo * prints names even though echo itself does not operate on files - patterns also work in paths, such as /etc/*.conf 3 [...] matches one member of a character set - img_27[234]?.jpg selects specified third digits - [!_]*.c excludes names beginning with _ 4 brace alternatives generate several candidate patterns in shells supporting them - *.{jpg,png,gif} supplies patterns for three suffixes 5 unmatched patterns depend on shell behaviour - Bourne-style behaviour described here leaves the word unchanged - do not assume all shells / settings do the same 1.2.8 Command history and filename completion 1 modern shells avoid repeatedly typing entire commands 2 Tab completes a uniquely determined name - ambiguous prefix: request possible completions, then type enough to distinguish - some shells complete command-specific arguments too 3 history stores previous commands, often across sessions - Up / Down select earlier / later commands - ordinary cursor / editing keys modify recalled text 4 history | less displays numbered history - !137: command 137; !!: previous command - !:0: previous command word; !:1: its first argument - !137:2: word 2 from command 137, numbering from zero - !abc: latest command beginning with abc 5 Ctrl-R searches history backward by substring - type search text; repeat Ctrl-R for earlier matches 6 Ctrl-C cancels a confused / unwanted input line 7 practice completion and history as ordinary working habits - author stresses their cumulative saving of typing time 1.2.9 Controlling task execution 1 programs may run for a long time - distinguish normal completion from requesting / forcing termination 2 many programs read standard input until end of file - input stream can originate at keyboard, file or elsewhere 3 stream is the English term for a sequence of input / output data 4 Ctrl-D on an empty terminal input line produces an end-of-input indication - tells the reading program that current input has ended - at shell prompt, normally ends the shell session 5 remember Ctrl-D for completing keyboard input in later examples 6 EOF does not require a program to terminate - program may handle it differently, read elsewhere or be stuck 7 Ctrl-C normally interrupts the foreground program - Ctrl-\ requests a quit signal and may produce a core dump - core files contain debugging information and can occupy much space 8 Ctrl-Z does not mean terminate or end input in Unix 9 terminal flow control can look like a hang - Ctrl-S pauses output; Ctrl-Q resumes it 10 closing a terminal window does not guarantee that every associated program has ended - determine what happened to the task itself 11 process: running instance of a program, initially simplified here - a program can also create further processes - locating a stuck task requires identifying its process 12 PID uniquely identifies an existing process - ps lists processes; ps ax includes all in the book's Linux / BSD examples - ps axu adds ownership and other information - option conventions vary between systems 13 top displays and refreshes information about active processes - q exits 14 signal: notification identified by name / number - program can handle or ignore many signals - some signals cannot be intercepted 15 Ctrl-C -> SIGINT; Ctrl-\ -> SIGQUIT - kill PID normally sends SIGTERM - kill -KILL PID / kill -9 PID sends uncatchable SIGKILL - identify correct PID from process listing before signalling it zombie: process has already finished but parent has not collected its status - cannot be killed again; remains as an entry in process table 16 uninterruptible sleep: process waiting inside a kernel operation - pending signal cannot take effect until that wait ends - unexpectedly prolonged waits may indicate storage / hardware trouble 17 book illustrates such a wait with removing storage during active copying - device removal before finishing / unmounting can disrupt pending I/O 18 ps state distinguishes cases - Z / defunct: zombie - D: uninterruptible sleep - investigate unexpectedly persistent waits 1.2.10 Background execution 1 background execution allows continued shell use while another task runs - useful when task needs no interactive terminal input 2 append & to start a background job - shell reports job number and PID; these are different identifiers - jobs lists shell's jobs - completion reports distinguish success, nonzero exit and signal termination - %2 identifies job 2 in shell job-control commands 3 Ctrl-Z suspends foreground job - bg resumes it in background - fg brings background / suspended job into foreground 4 Ctrl-Z pauses execution; it does not kill the program 5 background execution is useful for graphical applications - application uses its own window while shell remains available 1.2.11 Redirecting input and output 1 I/O streams carry bytes between program and outside world - terminal, file, device, another process or network peer - numeric descriptors distinguish a process's open streams 2 standard stream convention: - 0: standard input; 1: standard output; 2: diagnostics / standard error - program can use these without knowing underlying source / destination shell redirection: - > file: create / truncate output file; >> file: append - < file: read standard input from file - cmd1 | cmd2: first output becomes second input - 2> file: redirect diagnostics; 2>&1: direct descriptor 2 to descriptor 1's destination 3 less pages through a file or standard input - ls -lR | less allows reading a long recursive listing 4 diagnostics use a separate stream and do not enter an ordinary pipe automatically - gcc ... 2>&1 | less combines output and diagnostics before paging - redirect unwanted output to /dev/null to discard it - /dev contains device-file interfaces, explained later 1.2.12 Text editors 1 Unix offers many editors; section introduces several terminal editors 2 programming editor requirements in the book: - plain text files; no automatic paragraph reformatting - monospaced display keeps code columns aligned - equal runs of m and i should occupy equal width 3 Vim = improved clone of vi - modal interface initially unfamiliar - efficient text operations become useful after practice 4 emergency Vim exit without saving: Escape, then :qa! and Enter 5 vim filename opens file; missing file created when first saved - begins in command mode - insert mode accepts text; command mode interprets keystrokes as operations 6 command-mode cursor movement: h left, j down, k up, l right - arrow keys usually available too 7 arrow keys transmit multibyte escape sequences - slow connections can make these ambiguous with pressing Escape followed by commands 8 enter insert mode with i / a, or o / O for a new line below / above - Escape returns to command mode - ^ / $ move to line start / end; x, dw, dd, d$ delete different units - J joins lines; . repeats change; u undoes; U restores line changes 9 /text followed by Enter searches forward - / followed by Enter repeats previous search 10 :number followed by Enter jumps to a line file commands: - :w save; :w name save under another name - :wq save and exit; :q exit if unchanged; :q! discard changes and exit - :r name insert file; :e name edit another file - :ls list buffers; :b N select buffer N 11 Ctrl-^ switches between recent buffers - :set hidden permits leaving a modified buffer without saving - ~/.vimrc stores startup settings 12 V selects whole lines; v selects characters - movement extends selected region 13 d cuts selection; y copies it; p / P pastes after / before cursor - deletion commands also place removed text in a register - yy, yw, y$ copy line, word, or remainder of line 14 vimtutor provides guided practice 15 GNU nano: free reimplementation of Pico, originally related to Pine mail editing - nano filename; ordinary typing immediately inserts text - arrow keys / navigation keys behave conventionally - Ctrl-F/B/P/N provide single-character movement alternatives 16 nano's help strip uses ^ to mean Ctrl - Ctrl-C reports current position - Ctrl-O writes file; Ctrl-X exits, offering to save changes 17 watch nano's prompt line above the help strip - saving asks for filename; confirm with Enter or supply a different name 18 nano's go-to-position command accepts line and optional column - book presents the Ctrl-_ shortcut 19 Ctrl-K cuts line(s); Ctrl-U inserts the cut text - restore at original position then insert elsewhere to copy 20 Ctrl-G / F1 displays nano help 21 JOE = Jonathan's Own Editor - joe filename opens file; normal typing / cursor keys edit text - Ctrl-K h shows help; Ctrl-K D saves; Ctrl-K X saves and exits - Ctrl-C exits without saving; Ctrl-Y deletes line - Ctrl-K B / K mark block; Ctrl-K C / M / Y copy / move / delete it - Ctrl-K L goes to line; Ctrl-K F searches; Ctrl-L repeats search 22 Midnight Commander: mc opens file manager - F4 edits selected file; Shift-F4 creates a new file 23 book recommends configuring its editor to fill tabs with spaces - editor Options / General controls this - save configuration from Midnight Commander to retain it 1.2.13 File permissions 1 bits and octal notation help explain permissions - return after 1.3.2 if these representations are unfamiliar 2 permission word contains three rwx groups plus three special bits - owner, group, others each receive read / write / execute permissions - ls -l shows type followed by these permissions - -rwxr-xr-x: ordinary file; owner can modify; others can read / execute 3 octal digit represents one rwx group - r = 4, w = 2, x = 1; add granted values - 6 = rw-, 5 = r-x, 7 = rwx - 0755 grants owner rwx, group / others r-x 4 leading 0 follows C's convention for writing an octal integer 5 directory permissions concern names / traversal - r lists names; x allows lookup / traversal - w with x permits creating, renaming and removing directory entries - deleting a name depends on directory permissions, not file-content write permission 6 common directory modes combine r and x - x without r allows access to a known name without listing all names 7 w and x without r allow depositing entries without listing directory - book describes a shared drop directory with hard-to-guess names - known names remain subject to permitted entry operations 8 special bits: - setuid 04000: executable uses file owner's effective identity - setgid 02000: analogous group identity; on directory, group inheritance - sticky 01000: restricts removal in shared directories such as /tmp - behaviour on other object types is system-dependent 9 chmod sets access mode - chmod 644 myfile.c -> owner rw-, group / others r-- 10 symbolic chmod: - u/g/o/a select owner / group / others / all - + adds, - removes, = replaces selected permissions - r/w/x ordinary bits; s/t special bits; X conditional execute / directory traversal - -R applies recursively - book's recursive home-directory example also grants others read access 1.2.14 Online documentation: man 1 Unix distributions include local documentation; man displays manual pages 2 manual covers commands, system calls, library functions, file formats and concepts - man ls describes ls; man waitpid describes that interface - scroll with arrows / Space; q exits viewer 3 / searches forward for text; repeat search without retyping text - ? searches backward 4 manual section disambiguates names - man 2 write selects system call rather than user command - 1 commands; 2 system calls; 3 library functions; 4 devices - 5 file formats; 6 games; 7 general concepts; 8 administration - additional installed software can introduce other section names 1.2.15 Bourne Shell scripts 1 script: text executed by a named interpreter - initial #! followed by interpreter path identifies executable script - #!/bin/sh selects Bourne-compatible shell - execute permission required for direct execution - simplest script is a sequence of commands, one per line 2 poem example uses echo commands in a file - chmod +x humpty.sh makes executable - ./humpty.sh explicitly identifies script in current directory 3 command names containing / are treated as paths - names without / are resolved as built-ins or searched in command directories - this permits vim / ls without spelling their full paths 4 ./ converts a local short filename into an explicit relative path - absolute path or work/humpty.sh works too - current directory is not automatically searched for bare command names 5 shebang length and interpreter-argument handling have system-dependent limits - book warns that some systems permit only one interpreter argument 6 shell also has variables, conditions and loops - author advises beginners to return after learning programming fundamentals - shell language is mainly suited here to short command-combining programs 7 variables associate names with string values - assignment has no spaces around =: MYSTRING="several words" - quotes preserve spaces inside the value 8 $NAME substitutes variable value - ${NAME} separates name from following literal text 9 $((expression)) evaluates shell integer arithmetic - I=$((I+7)) increases I by seven 10 positional parameters describe script invocation - $0 invocation name; $1, $2, ... arguments; $# argument count - braces needed for multi-digit parameter numbers, e.g. ${12} - example prints its name, argument count, then three arguments in reverse order 11 inside a shell function, positional parameters refer to that function's arguments 12 $ substitution works in double quotes but not single quotes 13 exit status supplies shell truth value - 0 means success / true; nonzero means failure / false - conditions run commands and inspect their status 14 test evaluates a condition; [ is its alternative command name - closing ] is a required argument; spaces separate command / operands - -f tests regular file; -lt / -le / -gt / -ge compare integers - = / != compare strings if command; then ... else ... fi selects branch - any command can serve as condition, including mkdir while condition; do ... done repeats while command succeeds - example prints 1 through 100 and increments counter 15 for NAME in words; do ... done iterates over words - especially useful with expanded filename lists 16 short-circuit command combinations: - cmd1 && cmd2: run second only after first succeeds - cmd1 || cmd2: run second only after first fails 17 && and || have equal precedence and associate left to right - pipelines / redirections bind more tightly - pipeline's status normally comes from last command in this shell model - parentheses group commands, e.g. pipe output of a grouped combination 18 these constructs also work at an interactive prompt - dedicated shell documentation covers further features 1.2.16 Environment variables 1 environment: collection of NAME=value strings available to a program 2 each process has its own environment - can add, change or remove entries - child normally inherits environment from parent 3 common variables: - PATH: command-search directories - HOME: user's home directory; LANG: language / locale setting - EDITOR: preferred editor - env displays environment entries 4 shell imports environment entries as shell variables - export marks a variable for inclusion in child environments - ordinary new shell variables are not automatically exported - export NAME=value combines assignment with export 5 unset removes a variable - changing shell environment affects subsequently launched children - NAME=value command supplies a setting for one invocation - EDITOR=joe chfn illustrates choosing an editor for a particular command 1.2.17 Recording a session 1 script filename starts a terminal-session transcript - records displayed input / output while commands run - Ctrl-D ends the nested shell and finishes recording - resulting file includes session start / end information and dialogue 1.2.18 Unix graphical subsystem 1 section describes the X Window System architecture used in the book - graphical facilities supplied by user programs above the OS 2 correct name: X Window System; Window is singular 3 X server manages display service - graphical applications send requests as X clients 4 window manager is a special X client - handles borders, titles, placement and resizing - application draws its own content area 5 window manager can be replaced while applications remain running 6 xterm is an X client emulating a text terminal - several windows can host separate shells for editing, compiling and testing 7 startx normally invokes xinit to start a graphical session 8 book also describes remote sessions through xdm - applications run on server machine; local machine provides X display 9 startup configuration determines which window manager runs 10 ~/.xinitrc is a startup shell script for xinit - xinit starts X server, prepares environment and runs script - script completion ends session - xterm & starts terminal without waiting; foreground twm keeps session alive 11 graphical login may use ~/.xsession - unlike startx from an existing shell, login must establish session environment - sourcing ~/.profile and ~/.xinitrc can share configuration 12 window managers differ from full desktop environments - desktop environments add desktop metaphor and supporting services - book lists both categories as choices 13 a desktop environment may contain a separate window-manager program - its components need not work independently 14 book traces desktop metaphor to Xerox PARC research and Xerox Alto 15 book's historical survey follows later adoption in personal computers - graphical usability depended partly on improving hardware speed 16 many distributions provide a desktop environment by default - book links this to familiar interfaces for migrating users 17 author objects to desktop environments consuming resources needed by applications 18 desktop environments may create conventional user directories automatically - desktop directory contents can appear as icons - localized / spaced names require appropriate handling in shell commands 19 author recommends trying lightweight managers to support command-line study - IceWM offered as initial example; experimentation encouraged 20 graphical login may expose a session-type selector - otherwise configure appropriate startup file - example starts xterm in background and IceWM in foreground 21 book calls twm / fvwm-style managers classical - contrasts their behaviour with click-to-focus / raise interfaces 22 focus can follow pointer without raising window - type into a partly obscured window without rearranging all windows 23 behaviour is configurable; exact gestures depend on chosen configuration 24 find root-window menu and start a terminal - xterm & starts another terminal while preserving current shell availability 25 xterm options configure appearance - -bg black -fg gray is the book's colour example 26 title / frame gestures raise, lower, move and resize windows - corners commonly resize; title commonly moves 27 window-list menu helps locate hidden windows 28 virtual screens organize larger sets of windows - some managers treat them as adjacent regions of one larger desktop - a window may extend beyond one physical-screen region 29 X selection provides text transfer between applications - select text; middle-click pastes selection - clipboard copy / paste may be a separate parallel mechanism - mouse wheel press often acts as middle button; Shift-Insert may paste 1.3 Some mathematics 1 discrete mathematics supplies prerequisites for later programming material - chapter develops the needed reasoning rather than assuming school coverage 1.3.1 Elements of combinatorics 1 combinatorics counts possible choices / arrangements of finite sets lamp example: fixed lamps independently on or off - one lamp gives two distinguishable signals - three lamps will give eight; explanation matters more than memorized answer 2 second lamp doubles possibilities - first lamp's two states with second off - same two states with second on -> four distinct combinations 3 each additional independent two-state lamp doubles count again - three lamps: 8; four: 16 - N existing signals -> 2N after adding one lamp 4 zero-lamp case clarifies what is being counted - a signal groups many real situations rather than describing every detail 5 no lamps gives one distinguishable configuration - all situations look the same; there are not zero possible configurations 6 n lamps -> 2^n configurations, including 2^0 = 1 7 choosing which of five ornaments to wear is the same problem - each item independently present / absent -> 2^5 = 32 choices 8 abstract form: n-element set has 2^n subsets - does not solve problems where order matters - towers of distinct cubes distinguish arrangements of the same selected cubes 9 four distinct cubes give 64 nonempty ordered towers of heights 1–4 - three cubes give 15; five give 325 - these counts are not obtained by simply taking all subsets 10 add a lamp with three states to three two-state lamps - each new state accompanies eight old configurations -> 3 × 8 = 24 - derive count from choices instead of applying a familiar formula blindly 11 flag example: three shapes and four decorations - each shape permits four decorations -> 3 × 4 = 12 flags 12 arrange possibilities as rows and columns - one cell per shape / decoration pair - multiplication counts independent choices 13 unlimited cubes of four colours, towers of heights 1–4 - each position independently has four choices - 4 + 4^2 + 4^3 + 4^4 = 340 14 permutations: arrange all distinct objects in order - one ball: one arrangement; two balls: two arrangements 15 three balls: three choices for first, two arrangements of the remainder -> six - lexicographic ordering sorts by first element, then second, and so on 16 k balls: choose first in k ways, arrange remaining k-1 - M(k) = k M(k-1), starting with M(1) = 1 -> k! = k(k-1)...2·1 17 seven distinct balls -> 7! = 5040 permutations 18 alternative derivation: fill positions successively - 7 choices, then 6, then 5, ..., then 1 - product gives same factorial 19 ordered selection of k distinct objects from n: - n choices, n-1 choices, ..., n-k+1 choices - count = n!/(n-k)!, also called falling factorial (n)_k - three of seven on a shelf -> 7 × 6 × 5 = 210 20 return to four distinct cubes - height 4: 24; height 3: 24; height 2: 12; height 1: 4 -> total 64 21 unordered selection: put three of seven balls into a bag - permutations of the same three balls now represent one outcome - each triple appears six times among 210 ordered choices 22 every three-element choice has 3! orderings -> 210 / 6 = 35 unordered choices 23 general combination count: C(n,k) = n!/[k!(n-k)!] - first count ordered selections, then divide by k! duplicate orderings - book warns against applying the formula without checking what is counted 24 reconstruct formula from reasoning when needed - discard unused positions from n! through division by (n-k)! - discard order of selected elements through division by k! 25 alternative derivation: arrange all n objects, then split into two bags - order within first bag irrelevant -> divide by k! - order within second bag irrelevant -> divide by (n-k)! 26 symmetry: C(n,k) = C(n,n-k) - selecting objects to take is equivalent to selecting objects to leave 27 boundary cases: C(n,0) = C(n,n) = 1 - exactly one empty choice and one choice containing everything 28 combination counts are binomial coefficients - (a+b)^n = sum of C(n,k) a^(n-k) b^k - connection comes from counting contributions to each term 29 question is which coefficient multiplies each power combination 30 distributive law multiplies every term of one sum by every term of another - n terms times m terms -> nm products before collecting like terms 31 expanding n factors (a+b) gives 2^n uncollected terms - choose a or b from each factor independently 32 term a^k b^(n-k) appears once for each choice of k factors supplying a -> coefficient C(n,k) - a^2 b^2 appears six times in expansion of (a+b)^4 33 Pascal's triangle computes coefficients using addition - first / last entry in each row = 1 - inner entry = sum of two entries above - C(n+1,k) = C(n,k-1) + C(n,k) combinatorial reason: - choices including new object select k-1 old objects - choices excluding it select k old objects 34 sum of row n is 2^n - classifies all subsets by their sizes 35 round-robin tournament with seven players - each plays six others, but each game counted for both players -> 7 × 6 / 2 = 21 games 36 score-sheet explanation: - seven players prepare six sheets each -> 42 sheets - two sheets submitted per game -> 21 games 37 tournament grid has one row and one column per player - diagonal unused; each game recorded in two opposite cells 38 49 total cells minus seven diagonal cells = 42 - two entries per game -> 21 games 39 complete graph: every pair of distinct vertices joined by one edge - n vertices, n-1 incident edges per vertex - n(n-1) edge ends; two ends per edge -> n(n-1)/2 edges 1.3.2 Positional numeral systems 1 position determines a digit's weight - radix / base n uses n digits and successive weights differing by factor n - decimal is the familiar base-10 instance 2 k independent positions with n possible states give n^k combinations 3 k base-n digits represent integers 0 through n^k-1 - unused higher positions may be regarded as zero 4 adding 1 to n^k-1 exhausts k positions - next position becomes 1; lower positions become 0 - its weight must therefore equal n^k 5 decimal's familiarity is historical habit - book stresses the relative simplicity of binary arithmetic 6 ordinary positional systems can use any integer base at least 2 - digits have values 0 through n-1 - 1000 in base n means n^3 - changing representation does not change the number or its properties 7 two decimal properties generalize: - value = sum of digit × corresponding power of base - repeated division by base yields digits as remainders, least significant first 8 base-7 example: 1532 = 1·7^3 + 5·7^2 + 3·7 + 2 = 611 decimal - repeated division of 611 by 7 gives remainders 2,3,5,1 9 weighted sum converts from a representation to numerical value - repeated division constructs representation in another base 10 Horner form avoids calculating separate powers - process left to right: accumulated value × base + next digit - ((1·7+5)·7+3)·7+2 = 611 11 most-significant-first notation requires knowing total length to interpret first digit's weight - repeated division naturally produces digits in the opposite order 12 book relates the historical notation to Arabic writing direction - historical explanation presented as the book's account 13 binary is central to computer representation - octal abbreviates groups of three bits; hexadecimal groups of four - hexadecimal A–F stand for values 10–15 14 eight-bit byte -> exactly two hexadecimal digits - values 00 through FF = 0 through 255 15 octal fits three-bit groups rather than bytes - byte range 000–377; three octal digits can represent up to 511 - octal uses only decimal digit symbols and was historically convenient 16 binary-to-decimal conversion adds powers of two at set-bit positions - 1001101 binary = 64 + 8 + 4 + 1 = 77 17 decimal-to-binary by repeated halving - record remainder at each step; read remainders in reverse - 103 -> 1100111; 76 -> 1001100 18 alternative: repeatedly subtract largest fitting power of two - mark its bit as 1; unselected powers get 0 - 757 = 512+128+64+32+16+4+1 -> 1011110101 - 260 = 256+4 -> 100000100 19 if one radix is the kth power of another, one digit corresponds to k smaller-base digits 20 octal / hexadecimal to binary: - replace each octal digit with three bits, each hexadecimal digit with four - preserve internal zeros; discard only unnecessary leading zeros 21 binary to octal / hexadecimal: - group from right into threes / fours - pad only leading incomplete group with zeros - replace each group with one digit 22 digit-group correspondences can be calculated until practice makes them familiar 23 fractional positions have weights 1/2, 1/4, 1/8, ... - 101.01101 binary = 5 + 13/32 = 5.40625 - k binary fractional digits can be treated as integer numerator over 2^k 24 book uses a point to separate integer and fractional parts - matches notation used in programming languages 25 construct binary fractional digits by repeated multiplication by 2 - record integer part (0 or 1), remove it, continue with remaining fraction - process integer part separately 26 5.40625 example: - integer part -> 101 - successive fractional digits -> 01101; zero remainder ends procedure - trailing fractional zeros do not change value 27 a rational number has a finite base-N expansion iff its reduced denominator divides some N^k - decimal requires denominator with only prime factors 2 and 5 - binary requires a power-of-two denominator 28 finite decimal fractions often become repeating binary fractions - detect repetition when the working remainder repeats - 0.35 decimal = 0.01(0110) binary 29 finite decimal fraction -> integer formed by fractional digits divided by 10^k - 17.325 = 17 + 325/1000 = 693/40 30 same method uses base^k in any positional system - binary fraction ending in 1 has odd numerator over a power of two -> already reduced 31 repeating fraction: multiply by base^(period length), then subtract original - identical infinite tails cancel - solve remaining linear equation for the fraction 32 7.3(327) example: - separate 7.3; let x = 0.0(327) - 1000x - x = 32.7 -> x = 327/9990 - restore 7.3 -> total 12209/1665 33 binary repeating example uses same procedure - 0.01(0110) = 1/4 + 1/10 = 7/20 = 0.35 - multiplying repeating tail by 16 cancels a four-bit period on subtraction 34 binary addition / subtraction work column by column - two ones -> write 0, carry 1; three ones -> write 1, carry 1 - borrowing from next position supplies two units in current position 35 multiplying by a power of radix appends zeros to an integer representation - useful when finding common denominators and adjusting numerators 36 binary multiplication simplifies ordinary long multiplication 37 each multiplier digit is 0 or 1 - add either zero or appropriately shifted multiplicand - keep shifts aligned even when omitting zero rows 38 example: 110001 × 1101 binary - shifted copies at positions 0,2,3 - result 1001111101 binary = 49 × 13 = 637 decimal 1.3.3 Binary logic 1 conditions in programs evaluate to true or false - file exists, value is in range, sufficient memory remains, etc. 2 Boolean algebra is a small part of mathematical logic 3 Boolean values: 0 false, 1 true - NOT reverses value: NOT 0 = 1, NOT 1 = 0 - unary operation has one operand 4 binary operations have two operands - OR true if at least one operand true, including both - AND true only if both operands true 5 usual notation: OR written ∨; AND written & or ∧ 6 XOR true when operands differ - unlike OR, false when both operands true 7 implication x -> y is false only for x true and y false - false premise makes material implication true regardless of consequent - book illustrates why a true conclusion alone does not establish true premises 8 Boolean function maps combinations of Boolean inputs to Boolean output - two inputs give four possible argument pairs - truth table specifies output for every pair 9 four independently chosen output bits -> 2^4 = 16 two-input functions - constants 0 / 1; projections x / y and negations - AND, OR, XOR, equivalence and implications - NOR = NOT OR; NAND = NOT AND - equivalence true exactly when operands equal 10 n inputs -> 2^n argument combinations - choose one output bit per combination -> 2^(2^n) functions - three inputs: 256; four: 65536 11 basic identities follow from operation meanings - x AND 0 = 0; x AND 1 = x - x OR 0 = x; x OR 1 = 1 - AND sometimes written by juxtaposition, like multiplication 12 both distributive laws hold - (x OR y) AND z = (x AND z) OR (y AND z) - (x AND y) OR z = (x OR z) AND (y OR z) 13 idempotence, complements and double negation - x AND x = x; x OR x = x - x AND NOT x = 0; x OR NOT x = 1 - NOT NOT x = x 14 De Morgan's laws: - NOT (x OR y) = (NOT x) AND (NOT y) - NOT (x AND y) = (NOT x) OR (NOT y) - derive by asking when original expression is false 15 reduce unfamiliar Boolean operations to AND, OR and NOT - implication: NOT x OR y - XOR: (x AND NOT y) OR (NOT x AND y) truth-table construction of disjunctive normal form: - take every row with output 1 - AND all variables, negating those that are 0 in that row - OR resulting terms - each term recognizes exactly its own input combination 1.3.4 Kinds of infinity 1 section prepares for computability discussion - author distinguishes intuitive algorithm concept from particular formal models 2 countably infinite set: elements can be numbered by natural numbers - naturals, even naturals and all integers are countable - integer enumeration: 0,1,-1,2,-2,... - countable cardinality denoted aleph-zero 3 rationals are countable too - enumerate integer numerator / positive denominator pairs in finite expanding layers - skip reducible fractions and repeated representations of zero -> each rational gets one number 4 enumeration need not finish an infinite task - any specified rational appears after finitely many steps 5 irrational != any infinite decimal expansion - rational expansions can repeat forever - terminating / repeating behaviour depends on radix - irrational number cannot be written as integer ratio 6 Cantor diagonal argument shows real numbers are uncountable - assume a list of fractional expansions - construct a new expansion differing from item n at position n - choose digits avoiding ambiguous terminating / repeating-nine representations -> new number missing from every proposed complete list 7 continuum denotes cardinality of real numbers finite alphabet A; A* = all finite strings, including empty string - enumerate by length, then fixed order within each length -> A* is countable 8 even an alphabet containing all symbols used in books is finite in this thought experiment 9 all finite books over that alphabet remain countable - includes unwritten, nonsensical and unimaginably large finite books - no upper length bound is needed 10 all infinite strings over an alphabet with at least two symbols form an uncountable set - one huge finite book differs fundamentally from the collection of infinite books 11 Graham's number illustrates magnitude without infinity - finite number may be far beyond practical representability - its finite numeral still belongs to the set of finite strings 12 infinite strings are conceptually different from even these enormous finite strings 13 author's constructive viewpoint: - practical finite procedures access finite portions / descriptions - countable enumeration promises another element, not completion of infinity 14 set theory also studies cardinalities beyond the continuum - power set of reals supplies an example - author distinguishes mathematical objects from directly executable constructions 15 continuum hypothesis: no cardinality strictly between countable infinity and continuum - book discusses independence from the usual set-theoretic axioms - answer depends on adopted axiomatic framework 1.3.5 Algorithms and computability 1 information processing can be represented as a function on finite strings - choose finite alphabet A; input / result belong to A* -> transformation A* -> A* 2 finite descriptions are countable; all string-to-string functions are uncountable - computation rules need finite descriptions -> most mathematical functions have no such computable rule 3 even functions from naturals to decimal digits form an uncountable set - each function specifies an infinite sequence of digits - allowing arbitrary natural outputs does not remove the disparity 4 Boolean-valued functions on naturals correspond to subsets of naturals - true means membership; false means nonmembership -> power set of naturals is uncountable 5 program embodies a constructive procedure / algorithm - programmer supplies rules precise enough for independent execution - a function is computable when such a rule computes it 6 author objects to school definitions treating a short verbal description as a complete account - emphasizes distinction between informal effective procedure and a fixed formal definition 7 computability theory grew from questions of algorithmic solvability - Hilbert's problems, especially the tenth problem, motivated formal investigation - Gödel, Kleene, Church and Turing contributed central models 8 book narrows its treatment to discrete representations - arbitrary real values cannot all be supplied as finite input descriptions 9 natural-number functions suffice for encoded countable domains - replace each finite object by its enumeration number 10 uncountably many natural-number functions still exceed countably many finite procedures 11 partial recursive functions: - start from simple functions: constants, successor and projections - build through composition, primitive recursion and minimization - partial functions may be undefined for some inputs - recursive here describes the formal construction, not only self-calling procedures 12 many proposed computation formalisms yield the same class - extra-looking operations can be simulated by existing ones 13 Church's thesis identifies effectively computable functions with partial recursive functions - a thesis connecting informal effectiveness to a formal class - not a theorem about two already formalized definitions 14 author emphasizes the distinction between evidence for a thesis and formal proof - hypothetical stronger effective model would challenge the thesis 15 book compares this thesis with an empirical hypothesis - author's philosophical interpretation invokes Popper's falsifiability criterion 16 algorithm theory similarly studies effective transformations of finite words - finite descriptions constrain the class of procedures - distinct algorithms may compute the same function 17 Turing machine model: - unbounded tape, finite alphabet and finite control states - transition chosen from current state and scanned symbol - write symbol, change state, move left / right / remain - initial input on tape; halting state leaves output representation 18 Turing thesis connects effective algorithms with Turing-machine computation - Markov algorithms, register machines, multiple-tape machines and other standard models can simulate each other 19 formal equivalence of particular models is provable - claim covering every intuitive effective procedure remains a thesis 20 encoding strings as natural numbers connects both approaches - Turing-computable and partial-recursive functions coincide under suitable encodings 21 function identity depends on input / output behaviour - algorithm identity also concerns method - same computed function does not force same algorithm 22 Towers of Hanoi: - three pegs; differently sized disks initially stacked largest below smallest - move one top disk at a time; never put larger disk on smaller - transfer entire stack to target with minimum moves 23 recursive solution for N disks: - N=0: do nothing - move N-1 from source to spare - move largest from source to target - move N-1 from spare to target -> 2^N-1 moves 24 input = disk count; output = pairs of source / destination peg numbers - detailed programs appear later 25 recursive core is short - input parsing / validation adds surrounding program text 26 iterative Hanoi solution: - odd moves: smallest disk goes around pegs in fixed direction - even N: 1->2->3->1; odd N: 1->3->2->1 - even moves: unique legal move between pegs not holding smallest disk 27 iterative description is short for a human but needs more state in a program - track each peg's stack to determine legal move - recursive procedure knows required moves without storing full configuration 28 two implementations produce same move sequence for same input - equivalent behaviour, different procedures 29 computability and algorithm theory study closely related effective transformations - encodings connect string and natural-number formulations - combined statement often called Church–Turing thesis 30 author reiterates objection to presenting informal algorithm as completely captured by a school definition 31 absence of one universal informal definition does not prevent useful work - formal models provide precise mathematical treatment - remember role of Church–Turing thesis when relating them to effective computation 1.3.6 Algorithms and their properties 1 book distinguishes properties assumed of its algorithm model from properties particular procedures may have 2 objective finite representation: - algorithm can be written as finite text - finite description does not imply finite execution on every input 3 discreteness: computation proceeds through distinguishable steps / representations - symbolic expressions can represent irrational answers - quadratic solver may output (1 ± sqrt(5))/2 without storing an infinite decimal expansion 4 geometric / physical representation of sqrt(5) differs from finite symbolic encoding - book contrasts continuous quantities with the discrete model being discussed 5 analog computers manipulate continuous physical quantities - author keeps them outside this chapter's discrete algorithm model 6 determinism in the book's model: - complete input determines permitted next steps - same complete input gives same result when computation finishes 7 random values used by a program can be regarded as additional input 8 finite representation, discreteness and determinism are assumptions of this treatment - intelligibility concerns representation relative to executor - renaming variables can change text without changing algorithm 9 generality, termination, correctness and usefulness are separate characteristics - book does not require every procedure to possess all of them 10 generality means handling a family of inputs - constant-output procedure still an algorithm - Hello, world illustrates a useful teaching example without varying input 11 analogy: a property of a special class of triangles need not hold for all triangles 12 confusing universal assumptions with optional properties leads to misleading claims 13 book rejects treating guaranteed termination with a correct result as prerequisite for discussing a procedure 14 correctness must be judged against intended behaviour / requirements - author stresses disagreements between programmer and user and limits of testing - section's sweeping claims about verification express the author's position 15 halting / applicability problem: - given program and input, determine whether execution finishes - no algorithm decides this correctly for every possible pair 16 self-halting problem is sufficient for contradiction - ask whether a program halts on its own description 17 proof assumes a universal decider and derives an impossibility - A(W) denotes running A on input W 18 assume S(X) decides whether X(X) halts construct D(X): - if S(X) says halts, loop forever - otherwise stop 19 apply D to its own description - if S(D) says halts, D(D) loops - if S(D) says loops, D(D) stops -> either answer wrong; assumed S cannot exist 20 general halting decider would also solve self-halting -> general problem undecidable 21 formal proof must distinguish program from its encoding and fix computation model - simplified presentation keeps main diagonal argument visible 22 termination for all inputs is also not universally decidable - particular programs can still have established termination proofs - author argues against excluding partial procedures from algorithm theory 23 undefined results are essential to the general model - cannot generally turn every nonterminating computation into a default output 24 diagonal argument for total functions: - suppose all total computable functions had an effective universal enumeration f1,f2,... - g(n)=fn(n)+1 would be total computable yet differ from every listed function -> such an effective complete enumeration cannot exist 25 partial functions avoid that contradiction - if fk(k) undefined, diagonal construction also undefined there - resulting function need not differ from fk at its diagonal position 26 primitive recursive functions omit unbounded minimization - constructed through composition and primitive recursion - guaranteed to be defined for every natural input 27 Ackermann function gives a total computable function outside primitive-recursive class - grows extremely rapidly 28 book connects unrestricted loops / recursion with general partial computation - control-flow capability is broader than fixed bounded iteration 29 bounded loops with suitably bounded nested computation allow finite execution bounds - no unrestricted search / repetition remains 30 author emphasizes usefulness of unrestricted while loops and recursion - their availability removes automatic termination guarantees - individual uses can still compute total or primitive-recursive functions 31 general effective-computation models therefore admit procedures undefined on some inputs - distinguish this theoretical possibility from correctness requirements of a particular program 1.3.7 A sequence of actions is not the whole idea 1 algorithm need not be written as an explicit sequence of imperative actions 2 equivalent formal models have different representations - state-transition table, recursive functions, string-rewriting rules, lambda terms, register instructions - same computable transformations despite different notation 3 functional programming expresses values through functions - lazy evaluation can defer work until result required - written expression need not specify a straightforward execution order 4 declarative programming describes required relations / properties - Prolog example: facts and rules used in a proof / search process 5 object-oriented viewpoint emphasizes objects and messages - imperative languages such as Pascal / C describe state-changing actions - dominant hardware architecture helps explain popularity of imperative style 6 programs in executable languages still express effective computations - non-imperative does not mean nonalgorithmic - author's comments about heuristics / neural networks are opinions in this discussion 7 recursion even in imperative languages can obscure a direct action sequence - therefore surface syntax is a poor test of algorithmic character 8 use imperative / non-imperative for the intended distinction - reserve algorithmic for computability rather than action-list notation 9 terminology disputes should not obscure substantive mathematical results 10 a universal tool correctly detecting every nonterminating program would solve halting problem -> impossible under the model just discussed 11 undecidability limits general automatic reasoning about arbitrary programs - does not rule out proofs about particular programs or restricted classes 12 author notes that programmers may recognize diagonal halting proof without knowing formal computability vocabulary 13 bounded versus unrestricted computation connects theory with programming practice - partial recursive / Turing-computable class models general programs - primitive-recursive constructions provide a useful restricted total class 1.4 Programs and data 1.4.1 Measuring information 1 bit = binary digit - computer represents information using combinations of zeros and ones 2 information reduces uncertainty - one bit corresponds to halving an equally likely set of possibilities - distinguishing one of 1000 numbers needs at most ten well-chosen yes/no questions 3 divide remaining possibilities into two equal or nearly equal groups - ask which group contains answer; discard other group - at most 1000 -> 500 -> 250 -> 125 -> ... -> 1 4 ordered interval makes the same procedure easier - ask whether number lies in lower or upper half - retain corresponding interval and repeat 5 information amount need not be an integer number of bits - card trick repeatedly asks which of three rows contains chosen card 6 27-card trick: - deal into three rows; place indicated row between other two - deal cyclically again; candidates now middle three cards of each row - repeat; third answer identifies middle card - gathering indicated row in middle puts chosen card fourteenth in deck 7 each three-way answer reduces candidates by factor 3 - one trit = log2(3) bits 8 treasure-search example: - area shrinks from 60 × 80 to 30 × 20 - eightfold reduction under uniform-location assumption -> log2(8) = 3 bits 9 probability example assumes independent matches - win probabilities 1/4 and 1/2 -> both wins probability 1/8 - information in this outcome = -log2(1/8) = 3 bits 10 both losses probability 3/8 - information = log2(8/3) = 3 - log2(3) bits - more probable event conveys less surprise 11 byte usually means eight bits; historical machine usage varied - octet unambiguously means exactly eight bits 12 eight bits give 256 patterns - can represent unsigned 0–255 or signed -128–127 - one-byte character codes suffice for limited alphabets, not all writing systems 13 adjacent memory locations form a region for larger values - same storage also holds program instructions 14 memory does not record the intended interpretation of bytes - 41 4E 4E 41 hexadecimal can be read as ANNA, integer, float or instructions - operation / program context determines interpretation 15 large information units have historically ambiguous decimal / binary usage - KB, MB, GB etc. require attention to convention 16 N binary address lines distinguish 2^N memory locations 17 installed memory can be smaller than address space - bank selection and location selection divide address bits 18 memory capacities naturally relate to powers of two - several banks need not themselves total one power of two 19 historical K meant 1024 locations / words, close to decimal thousand - 8192-location bank = 8 K; three such banks = 24 K 20 smaller addressable bytes allowed multiple characters per machine word - byte-based capacity notation later became common 21 binary usage extended to 2^20, 2^30, 2^40 bytes - storage manufacturers also used decimal powers consistent with SI prefixes 22 difference between decimal and binary interpretations increases with exponent - small at kilo scale, substantially larger at tera scale 23 communication rates conventionally use decimal multiples of bits per second - link transmission does not inherently follow memory's binary capacities 24 binary prefixes remove ambiguity - Ki = 2^10, Mi = 2^20, Gi = 2^30, Ti = 2^40 - B denotes byte; bit denotes bit - GiB means 2^30 bytes 25 book describes slow adoption and continued historical usage - especially when discussing RAM 26 unambiguous meaning is the advantage of KiB / MiB / GiB notation 1.4.2 Machine representation of integers 1 mathematical integers have no largest value - any fixed physical representation has finite capacity 2 machine integer commonly allocated fixed width: 8,16,32 or 64 bits - decimal mechanical counter illustrates limited positions and carry 3 fixed-width counter eventually wraps - 99999 + 1 -> 00000 in five decimal positions - carry goes beyond available positions 4 unsigned n-bit integer range: 0 through 2^n-1 - eight bits: 0–255; 255+1 discards carry in fixed-width hardware result - general radix-N, k-digit maximum: N^k-1 5 arbitrary-precision arithmetic allocates more storage as needed - limited by resources; extra software work compared with fixed-width operations 6 multibyte values require a byte-order convention - little-endian: least significant byte at lowest address - big-endian: most significant byte first - 7500 = 0x00001D4C - big-endian bytes 00 00 1D 4C; little-endian 4C 1D 00 00 7 endian names allude to Swift's dispute over which end of an egg to open 8 signed interpretation assigns some bit patterns to negative integers - differs from unsigned interpretation of same storage 9 separate sign-and-magnitude complicates arithmetic - two's complement permits simpler common operations 10 subtract 1 from all zeros -> all ones in fixed width - assign all-ones pattern value -1 - adding 1 then gives zero as required 11 n-bit two's-complement interpretation: - high bit 0: ordinary nonnegative value - high bit 1: unsigned value minus 2^n - range -2^(n-1) through 2^(n-1)-1 - eight bits: -128 through 127 - crossing signed boundary causes signed overflow 12 overflow means mathematical result does not fit representation - positive plus positive may appear negative after truncation, or reverse - wider arithmetic / explicit checks needed to preserve intended result 13 negation in two's complement: invert all bits, then add 1 - 00000101 (5) -> 11111010 -> 11111011 (-5) - applying again restores 5; zero stays zero 14 most-negative value has no positive counterpart in same signed width - negating eight-bit -128 leaves same hardware bit pattern and overflows 15 two's-complement addition / subtraction use same bit operations as unsigned arithmetic - subtraction can be performed by adding negated subtrahend 16 75-19 example: - 75 = 01001011; -19 = 11101101 - sum = 100111000; discard ninth bit -> 00111000 = 56 17 arithmetic explanation: invert x then add 1 gives 2^n-x modulo 2^n - y + (2^n-x), after discarded carry, represents y-x 1.4.3 Floating-point numbers 1 normalized binary floating point: N = (-1)^s M·2^P - sign s, significand / mantissa M, exponent P - ordinary normalized nonzero values use 1 <= M < 2 - book discusses common IEEE-754 binary formats 2 leading 1 of normalized significand need not be stored - stored exponent uses bias - binary64: 1 sign bit, 11 exponent bits with bias 1023, 52 fraction bits - special cases / subnormal numbers deferred here 3 addition / subtraction aligns exponents by shifting smaller significand - calculate result, then normalize by adjusting significand and exponent together - multiplication / division also require normalization 4 finite precision introduces rounding - shifts or conversion can discard significant bits - values such as 1/10 have infinite repeating binary representations - computations generally approximate real arithmetic - exact equality after rounded computation may not match mathematical expectation 5 integer calculations within representable range remain exact - do not generalize floating-point rounding to all computer arithmetic 1.4.4 Texts and languages 1 natural-language text can describe a very wide range of information 2 natural-language analysis distinguishes morphology, syntax and semantics - ambiguous word forms require context - book describes semantic understanding as particularly difficult 3 author argues that neural-network language behaviour differs from explicit semantic analysis - discussion expresses the book's interpretation of contemporary AI 4 author stresses difficulty of explaining / correcting unexpected learned-system behaviour - his assessment is a viewpoint, not a programming-language definition 5 formal constraints make automatic analysis more manageable - users express information according to specified rules 6 formal language: language governed by explicit construction rules - mathematical notation and musical notation predate computers 7 for syntactic analysis, language can be viewed as a set of accepted strings - this abstraction does not by itself describe meaning / semantics 8 language design balances expressive needs and analysis complexity - measurement file might allow only numbers and separators - programming languages need richer constructions 9 storing / transmitting / displaying natural-language text does not require understanding its subject - editors, email and typesetting illustrate this distinction 10 ELIZA illustrates conversation produced through pattern manipulation - uses structure and words of input to construct replies - apparent conversational ability does not by itself reveal underlying method 11 many programming languages have been created; active communities maintain only some 12 markup languages describe document structure / presentation - HTML is the book's example; distinguish markup from general programming 13 any text-input program implicitly determines a language of accepted inputs - this language may be simple and unnamed 14 classification as programming can have disputed boundaries - SQL queries illustrate dependence on what is meant by a program 15 Turing-complete language can express a simulator of a Turing machine - provides a precise notion of computational expressive power - some languages designed for other purposes, such as TeX, are also Turing-complete 1.4.5 Text as a data format; encodings 1 text content and its stored representation are different - editors may save the same content in different formats 2 plain text uses character encodings without a document application's private formatting structures - ASCII originated as a code for interchange / teleprinter use - includes letters, digits, punctuation and control codes 3 ASCII uses seven bits -> 128 codes - 0–31 controls; 9 tab, 10 line feed, 13 carriage return - 32 space; decimal digits occupy 48–57 - digit code minus 48 gives its numerical value 4 uppercase A–Z: 65–90; lowercase a–z: 97–122 - corresponding ASCII letter cases differ by bit value 32 5 printable ASCII ends at 126 (~); 127 is DEL / RUBOUT - all-one punched-tape pattern could erase an existing character by punching remaining holes 6 eight-bit storage encouraged one-byte-per-character encodings - upper 128 codes used for incompatible national extensions - KOI8 Cyrillic order differs from alphabetic order 7 KOI8 positions preserve rough Latin transliteration if high bit is lost - explains unusual ordering and historical communication use - ё placed outside main contiguous Cyrillic region 8 CP866: DOS-era Cyrillic encoding - pseudographic symbols interrupt lowercase range - existing legacy data / interfaces can still use it 9 CP1251: another Cyrillic mapping associated with Windows - includes several Slavic alphabets; not every Cyrillic-using language 10 MacCyrillic and ISO 8859-5 are further distinct mappings - book's statements about their prevalence reflect its historical discussion 11 properties motivating simple byte-oriented text: - easy concatenation / splitting, direct byte indexing, human readability - no machine-word size or integer-byte-order dependency Unicode separates character repertoire / code points from particular encodings - UCS-2, UTF-32, UTF-8 and UTF-16 represent this repertoire differently 12 UCS-2 uses fixed two-byte values and cannot represent whole Unicode repertoire - UTF-32 uses four-byte code units; storage overhead is author's main objection 13 multibyte code-unit formats require attention to byte order and boundaries - BOM may identify byte order - arbitrary byte slices / concatenations need not be valid encoded text 14 UTF-8 is byte-oriented and preserves ASCII codes 0–127 - non-ASCII Unicode code points use multibyte sequences - current Unicode UTF-8 uses one to four bytes; book also mentions obsolete longer forms 15 UTF-8 prefixes identify sequence structure - 110xxxxx: two-byte lead; 1110xxxx: three-byte lead; 11110xxx: four-byte lead - following bytes start 10xxxxxx - payload capacities: 11,16,21 bits respectively 16 UTF-8 has no integer-byte-order dependency - slicing must respect character boundaries - variable byte length prevents direct character indexing by byte offset - correct display also needs suitable font glyphs 17 UTF-16 uses one or two 16-bit code units per Unicode scalar value - combines variable length with byte-order concerns - book strongly prefers UTF-8 and discusses historical Windows use 18 author recommends ASCII for portable program text in this course - broader encodings require attention to decoding, tooling and display support 1.4.6 Binary and textual data 1 text representation is directly readable by humans - binary representation uses another agreed encoding, often close to in-memory values 2 example writes 100 integers: 1000,2001,...,100099 - four-byte binary values -> 400 bytes - decimal text, one value per line -> 592 bytes - 9 four-digit + 90 five-digit + 1 six-digit values + 100 newlines - text size depends on number of digits, so need not always exceed binary size 3 text file can be inspected with cat or edited with an ordinary text editor 4 printing binary bytes as characters produces meaningless output - embedded terminal control sequences may alter terminal behaviour - reset can restore terminal settings 5 hexdump -C shows offsets, hexadecimal byte values and printable-character view - offsets advance by 16 bytes per displayed row - unprintable bytes represented by dots in character view 6 decode example using agreed four-byte little-endian format - e8 03 00 00 -> 0x000003e8 -> 1000 - 03 87 01 00 -> 0x00018703 -> 100099 7 hexdump of text shows digit codes rather than binary integer values - 31 30 30 30 0a = characters 1000 followed by newline 8 computation requires converting numeric text to the machine's numeric representation - keep track of which representation each value currently has 1.4.7 Machine code, compilers and interpreters 1 computer consists of CPU, memory and peripheral devices - introductory model connects them through bus / controllers 2 memory locations have addresses and fixed-width stored patterns - eight-bit location has 256 possible states 3 registers provide fast, limited CPU-local storage - CPU transfers data between registers and RAM and performs operations 4 machine word describes natural processor data width - often spans several addressable bytes - book's Pentium example uses 32-bit words and eight-bit bytes 5 instruction pointer and fetch / decode / execute cycle control execution 6 machine code consists of CPU instruction encodings - 01 D8 on the book's x86 example adds EBX to EAX - operand bits encode register choices and addressing form 7 manually constructing / decoding large streams of numeric instruction codes is impractical 8 high-level source expresses operations in a form convenient for humans - execution requires an implementation such as compiler or interpreter 9 compiler translates source to another representation - course example: Pascal source -> executable machine code - compiler reports syntax errors or produces executable - OS loads executable and transfers control to its code 10 compiler itself is a program - self-hosting compiler can be compiled by an earlier version of itself 11 interpreter reads a program and performs its prescribed operations - may first build a convenient internal representation - need not generate machine code for interpreted program 12 JIT compilation generates machine code during execution - distinct implementation technique, not definition of ordinary interpretation - executable-memory management adds implementation work 13 Bourne Shell is an already encountered interpreter - shell command files are programs 14 implementations can combine compilation and interpretation - compile to bytecode, then execute through a runtime / virtual machine - standalone executable may bundle interpreter plus intermediate program 15 book's practical distinction: - ordinary compiler can finish before resulting program runs - interpreter participates while interpreted program executes - mixed implementations and terminology make boundary less sharp 16 high-level language may not expose required processor operation / exact implementation -> assembly language can specify low-level instructions 17 assembler translates symbolic instruction notation to machine code - add eax, ebx is a mnemonic representation of example encoding - names replace manual opcode / operand-bit calculations 18 high-level compiler chooses instruction sequences, registers and optimizations - assembly source specifies concrete machine instructions much more directly 19 readable mnemonics still leave substantial low-level work - one high-level statement may require many assembly instructions - assembler does not provide all high-level language's ready-made constructions 20 several assembly syntaxes can target same instruction set - Intel-style add eax, ebx versus AT&T-style addl %ebx, %eax - assembler directives control storage, symbols, sections and assembly-time processing - directive sets / syntax also vary 21 assembler is ordinary software; different authors can implement different tools - NASM is the x86 assembler used later in this book 2. Pascal and the beginnings of programming 1 Pascal: - introduced by Niklaus Wirth in 1970 for teaching programming - used here to move from discussing computers to writing programs 2 Pascal dialects: - different implementations added extensions and changed the language - the name alone does not identify one precise set of rules - distinguish the original language, standards, and implementation dialects 3 Free Pascal: - compiler begun by Florian Paul Klaempfl in 1993 - supports several Pascal dialects and operating systems - supplies many facilities beyond those used in this book 4 limited teaching subset: - learn imperative programming through Pascal examples - practise structured programming, recursion, pointers, and other basics - prepare for C and C++; learning every Free Pascal extension is unnecessary 5 further study and choice of professional tools: - readers can study other Pascal facilities independently - the author's preference for other languages is a later practical question 6 main subject = programming - Pascal supplies the examples and a way to experiment 2.1 First programs 1 CPU executes machine code - writing it directly is laborious - source code: text following a programming language's rules - compiler: translates the program into another representation - interpreter: carries out the actions described by the program 2 Pascal workflow used here: - write plain source text in a text editor - save with a .pas suffix - compile with fpc - run the resulting executable 3 experiment directory: - mkdir firstprog; cd firstprog - ls checks its contents - shell prompt identifies user, host, and current directory 4 start an editor with the intended filename: - vim hello.pas, joe hello.pas, or nano hello.pas - a new file appears when its contents are first saved 5 first program: print Hello, world! - program hello; introduces the program and its name - identifiers name program entities - header ends with a semicolon - the book keeps the header even where the compiler permits omission 6 begin: - starts the main body - later programs also contain declarations and subprograms outside it 7 writeln('Hello, world!'): - prints its arguments - ln means a newline follows the output 8 terminology of built-in I/O: - the author calls writeln a statement because of its special syntax - arbitrary argument counts and formatting directives need compiler support - its identifier status also explains the common name built-in procedure 9 string literal: - characters enclosed in apostrophes represent themselves - without quotes, words are interpreted as program identifiers/syntax 10 end.: - end closes the main body - final dot terminates the program 11 save and inspect the source: - ls checks that hello.pas exists - cat hello.pas displays this short file - Tab completion can supply its filename 12 compile: fpc hello.pas - Error / Fatal: compilation cannot produce the requested program - warning: valid syntax may still describe suspicious behavior - note: a less severe observation - the book's particular old linker warning is specific to its environment 13 example errors: - writenl: unknown identifier - omitted final dot: compiler reaches the end while expecting '.' - Fatal stops further processing 14 diagnostic position: - filename(row,column) identifies where the problem was detected - unexpected end-of-file can be reported after the last written row 15 learn the editor's jump-to-number command: - diagnostic positions make locating errors much faster 16 compilation products: - hello.pas: source text - hello.o: object module used by the linker - hello: executable; ls -l shows execute permission - runtime support explains why a tiny source can produce a larger executable 17 run the local executable: ./hello - '.' means the current directory - a command without a slash is searched through PATH - current directory need not be in PATH 18 sequential statements: - execute in their written order - semicolon separates neighboring Pascal statements - end is a delimiter; a semicolon before it is unnecessary 19 write versus writeln: - two writeln calls produce two output lines - write prints without adding a newline - after write, the next shell prompt can appear immediately after the text - source changes require recompilation before rerunning 20 mixed output example: - write('First'); writeln('Second') -> FirstSecond, then newline - write('Third'); writeln('Fourth') -> ThirdFourth, then newline - output does not insert separators unless requested 21 English terminology: - statement: a language construction prescribing an action - operator: an operation such as +, *, or a comparison - Russian 'оператор' usually means statement in programming 22 mathematical terminology differs: - Russian mathematical 'оператор' retains the meaning of English operator 23 keep the programming terms distinct: - this becomes especially relevant to the C++ keyword operator 24 source layout in the examples: - program header and outer begin/end start at the left margin - statements inside the body are indented by four spaces - major elements occupy separate lines 25 compiler generally ignores these layout choices: - many untidy arrangements compile identically - confusing layout makes even one's own unfinished code difficult to follow 26 readability: - programmers spend much time reading and modifying existing code - source must communicate its structure and behavior to people 27 structural indentation: - shift nested constructions right relative to their containing construction - expose the nesting at a glance 28 indent width in the book = four spaces - different projects use different conventions - width should make nesting visible without wasting horizontal space 29 consistency: - keep one indentation convention throughout the program - apply the same consistency to other formatting decisions 2.2 Expressions, variables, and statements 2.2.1 Arithmetic operations and the idea of type 1 write / writeln also print computed values: - writeln(175*113) prints 19775 - comma-separated arguments can combine labels and expressions - '175*113' prints those characters; 175*113 computes their product 2 arithmetic and precedence: - + addition; - subtraction; * multiplication - multiplication binds more tightly than addition/subtraction - 10 + 5 * 7 = 45; (10 + 5) * 7 = 105 3 unary operators: - - changes the sign of one operand - + leaves its operand unchanged 4 ordinary division /: - produces a floating-point result even for two integer operands - writeln(14/7) therefore uses floating-point output formatting 5 numeric types specify distinct representations: - integer 2 and floating-point 2.0 need different representations/operations - signed integer families: shortint, integer, longint, int64 - unsigned families: byte, word, longword, qword - real: a floating-point type - the book uses a mode with 16-bit integer; widths depend on type and mode 6 type describes: - possible values - representation - operations defined for those values 7 non-numeric types: - boolean: true / false; logical operations - string: text; + concatenates strings - comparing strings produces boolean - char: one character 8 result type depends on the operation and operands: - integer addition/multiplication ordinarily yield integer results - floating-point arithmetic yields floating-point results - / always gives a floating-point result 9 floating-point output: - default display may use mantissa E exponent: m * 10^p - explicit formatting: value:field_width:decimal_places - writeln(14/7:7:3) prints two spaces followed by 2.000 10 integer division: - div: integer quotient - mod: remainder - 27 div 4 = 6; 27 mod 4 = 3 2.2.2 Variables, initialization, and assignment 1 fixed literals limit a program to one particular set of inputs - more useful programs solve the same task for different data 2 general solution needs values supplied at run time: - read input, store it in memory, then process it - Pascal provides variables for this purpose 3 variables across languages: - imperative languages use broadly similar mutable storage - other paradigms can use variables differently or omit them 4 variable names are identifiers: - letters, digits, underscore; cannot start with a digit - Pascal ignores letter case in identifiers - use consistent spelling despite this case insensitivity 5 variable holds a value: - referring to it in an expression supplies its current value 6 typed variables: - each Pascal variable has a declared type - its stored values and expressions referring to it have that type - in the book's mode, integer ranges from -32768 to 32767 7 declaration and initialization: - var x, y: integer; flag: boolean; - declarations precede the main body - x: integer = 500 supplies an initial value in this dialect - explicitly establish a value before reading a variable - compiler warnings do not detect every uninitialized read 8 assignment: x := expression - evaluate the right-hand side, then store its value in x - the old value is replaced - successive assignments 25, 36, 49 produce those values when printed - x := x + 5 uses the old x to calculate its new value 2.2.3 Identifiers and reserved words 1 one naming syntax for different entities: - program, variables, and later user-defined entities use identifiers - letter/underscore followed by letters, digits, or underscores 2 language also supplies existing words: - program, var, begin, end, div, mod - write, writeln, integer, boolean 3 reserved words: - part of the language grammar - cannot be reused as names for program entities 4 predefined identifiers: - some built-in names can be hidden by a declaration - declaring a variable named integer can hide the type name - such reuse makes code confusing and should be avoided 5 classification depends on dialect: - historical Pascal and Free Pascal do not classify every built-in word alike - do not infer reserved-word status merely from frequent built-in use 2.2.4 Input for later processing 1 input changes variables: - obtains data from an external source - stores the received values for subsequent processing 2 read(x): - reads a value of x's type into x - terminal input normally becomes available after Enter - square example first reads an integer 3 read -> calculate -> print: - x := x*x replaces the input with its square - writeln(x) prints the result - waiting for input is different from a hung program 4 standard input need not be a keyboard: - echo 37 > num.txt creates input data - ./square < num.txt reads it and prints 1369 - changing the file changes the data without changing the program 5 pipes and redirection: - echo 37 | ./square supplies another program's output as input - > result.txt sends the result to a file - shell arranges streams before starting the program - program uses standard input/output without needing to know their endpoints 2.2.5 Beware insufficient range 1 fixed-width integer overflow: - in the book's 16-bit integer mode, 200*200 does not fit - the unchecked example produces -25536 instead of 40000 2 bit-level explanation: - 40000 - 65536 = -25536 - the same 16 bits are interpreted as a signed result - overflow behavior and checks depend on compiler settings 3 choose a type with enough range: - 181^2 fits a signed 16-bit integer; 182^2 does not - longint: signed 32-bit, -2^31 through 2^31-1 - changing the declaration and recompiling extends the usable range - 46340^2 fits; 46341^2 exceeds it 4 wider and unsigned types still have limits: - int64: signed 64-bit; 3037000499^2 fits - qword: unsigned 64-bit, 0 through 2^64-1 - gains one positive-value bit by giving up negative values - (2^32-1)^2 fits qword; (2^32)^2 does not - the unchecked example wraps the latter result to zero 2.2.6 A simple statement sequence 1 statements finish before the next one begins: - writeln('First'); readln; writeln('Second') - readln without arguments consumes the rest of an input line - on the terminal it can wait for Enter 2 two pauses in sequence: - first Enter permits Second to be printed - second Enter permits Third and program termination 3 final readln in some teaching examples: - historically used to keep a separately opened console window visible - it performs real input; it is not required Pascal boilerplate 4 address window lifetime in the execution environment: - launch from an existing terminal or configure the development environment - a pause should have an explicit purpose 5 author's concern about teaching through an IDE: - one-key execution can conceal compilation and executable files - compilation produces a program, as well as reporting errors 6 exercise: - print a poem one line at a time - wait for Enter between successive lines 7 flowcharts: - rectangle: action - small circle: start/end in these diagrams - diamond: condition - arrows show execution order 2.2.7 Branching 1 useful control flow depends on conditions: - select actions, repeat actions, or call other parts of a program 2 branching tests a condition at run time: - full branch: one action for true, another for false - incomplete branch: action for true, nothing for false 3 if is a statement containing other statements: - absolute-value example prints x when x > 0, otherwise -x - zero is handled by the second branch 4 whole if/then/else construction = one statement - its branch statements are nested inside it 5 condition after if must be boolean: - comparison such as x > 0 computes true or false 6 syntax: - if condition then statement1 - optionally add else statement2 - then separates the condition from its action 7 incomplete-branch version of absolute value: - if x < 0 then x := -x; - writeln(x) executes afterward in either case - mathematical absolute value of the minimum signed integer needs a wider type 8 indent branch contents one level beyond the if: - nesting becomes visible without tracing the syntax character by character 9 no semicolon before else: - semicolon ends/separates the preceding statement - else belongs to the same if and cannot stand alone 2.2.8 Compound statements 1 one syntactic statement slot may need several actions - for example, an if branch 2 swap example: - ensure a <= b by swapping only when a > b - temporary t preserves a while its storage is overwritten - requires three assignments 3 begin ... end groups statements into one compound statement: - t := a; a := b; b := t - put this block in the conditional branch 4 book's block layout: - begin on the next line, aligned with if - body indented one level - end aligned with the construction it closes 5 another permitted layout: - begin on the same line as then - end still aligns with the start of the if - matching indentation exposes the full construction 6 third layout: - indent begin/end beneath if and the body one level farther - author regards this as permissible but does not recommend it 2.2.9 Boolean expressions and the boolean type 1 comparison operators: - >, <, =, <>, >=, <= - each computes a boolean result 2 boolean expressions are evaluated like arithmetic expressions: - x + 1 produces a number - x > 1 produces true or false 3 boolean variable: - stores a logical value - can be assigned a boolean expression - referring to the variable itself supplies a condition 4 example: - negative := x < 0; - if negative then x := -x 5 logical operators: - not: negation; and: conjunction; or: disjunction; xor: exclusive or - flag := not flag toggles a boolean - parenthesize comparisons: (k >= 0) and (k <= 9) - Pascal's logical connectives bind more tightly than comparisons 6 combine conditions: - ((c >= 'A') and (c <= 'Z')) or ((c >= 'a') and (c <= 'z')) - tests ASCII Latin-letter ranges - some redundant parentheses can improve readability 7 avoid comparing a boolean to true/false: - B instead of B = true - not B instead of B = false - meaningful names make conditions read naturally: if found then 2.2.10 Loops; while 1 loop: - repeated sequence of actions = body - one execution of the body = iteration - iteration count may be known in advance, data-dependent, zero, or unbounded 2 loop condition can express: - continuation: repeat while true - termination: stop when true 3 condition can be implicit: - counted loop specifies a control variable and endpoint 4 progress toward termination: - some relevant state usually changes between iterations - a deliberate infinite loop can use true as its continuation condition 5 while = precondition loop: - test before every iteration - false ends the loop immediately - body may execute zero times 6 syntax: while condition do statement - to print twenty lines, count completed iterations - initialize i := 0; continue while i < 20 7 compound loop body: - print the message, then increment i - prepare the first iteration immediately before the loop - prepare the next iteration at the end of its body 8 counter invariant: - i equals the number of lines already printed - printing precedes incrementing because increment records completed work 9 use the counter in the body: - start i at 1, continue through i <= 100, print i*i - write alone does not separate successive numbers 10 readable output and data-dependent repetition: - write(i*i, ' ') inserts a separator - writeln after the loop finishes the output line - a validation loop may need an unknown number of retries - example birth-year bounds are chosen for the book's scenario 11 input validation with while: - read year before the loop - while outside the accepted interval: report error and read again - valid first input gives zero iterations - number of invalid attempts has no fixed bound 2.2.11 Postcondition loops; repeat 1 while tests before the first iteration 2 repeat ... until condition: - executes body before testing - body runs at least once - condition true ends the loop; false repeats it - repeat/until delimit multiple statements without begin/end 3 examples: - read a year until it falls within the accepted interval - sum := 0; repeatedly read x and add x until sum > 1000 - choose repeat when the task requires at least one iteration 2.2.12 Counted loops; for 1 counted loop: - iteration count known on entry - control variable enumerates successive values 2 for i := 1 to 20 do statement: - visits 1 through 20, inclusive - prints the greeting twenty times with a compact loop 3 control-variable rules: - body may read i, e.g. write(i*i, ' ') - body must not assign to i - do not depend on its value after normal completion 4 descending loop: - for i := 10 downto 1 do ... - to advances; downto retreats by one ordinal value - initial/final expressions are evaluated once before iteration - later changes to variables used in those expressions do not change the bounds 5 empty interval: - to with initial > final performs zero iterations - downto with initial < final also performs zero iterations 6 control variable can have an ordinal type: - integers, characters, boolean, enumerations, subranges - bounds must be compatible with that type 2.2.13 Nested loops 1 diagonal of stars: - output 24 lines - line n contains n-1 spaces followed by '*' 2 outer loop selects the line: - for n := 1 to 24 - inner loop prints its n-1 spaces - then print the star and newline 3 use different control variables: - inner loop must not alter outer loop's variable - inner m ranges from 1 to n-1; first line needs zero iterations - next example: outline of a diamond with user-specified height 4 diamond dimensions: - height h must be positive and odd - h = 2*n+1; top including widest row has n+1 lines 5 analyze top and bottom separately: - top: leading spaces decrease, inner spaces increase - bottom: reverse those changes 6 leading spaces on top row k: - n+1-k; decreases from n to zero 7 spaces between stars: - none needed on the first row, which has one star - for k > 1: 2*k-3 inner spaces - handle k = 1 explicitly 8 row algorithm: - print n+1-k spaces and first star - if k > 1: print 2*k-3 spaces and second star - print newline - top uses k = 1 through n+1 9 bottom reuses the same row geometry: - visit k from n down to 1 - widest row is not repeated 10 whole program: - repeat input until h > 0 and h mod 2 = 1 - set n := h div 2 - print upper and lower portions with their respective outer loops - identical row bodies duplicate code - corrections would have to be repeated consistently; subprograms will remove this 2.2.14 Bitwise operations 1 remaining arithmetic facilities: - bit operations, named constants, and alternative numeric notation 2 bitwise operations treat integers as fixed-width bit patterns: - 16-bit 75 = 0000000001001011 3 not inverts each bit: - inversion of that pattern = 1111111110110100 - signed interpretation: -76; unsigned 16-bit interpretation: 65460 4 and / or / xor act on corresponding pairs of bits: - 42 and 166 = 34 - 42 or 166 = 174 - 42 xor 166 = 140 5 left shift shl: - discard bits leaving the high end; insert zero bits at the low end - 1 shl 5 = 32; 21 shl 3 = 168 - multiplication by 2^k agrees when the result fits the relevant width 6 right shift shr: - discard low bits and fill high positions with zero - for unsigned/nonnegative values, divides by 2^k and discards remainder - negative signed values require care; zero-fill does not preserve their sign - Free Pascal supplies separate arithmetic-shift helpers 2.2.15 Named constants 1 constant expression has an unchanging value: - literal: 37.0 - compound expression: 6*7 2 compile-time constant: - compiler can determine its value while compiling - constant arithmetic can be folded to its result 3 run-time constant: - logically unchanged, but its value is established at execution time - which expressions are accepted at compile time depends on the compiler 4 built-in function does not automatically mean compile-time evaluation: - the book's const declaration using copy is rejected 5 named constant: - associates an identifier with a compile-time value - const declarations belong before the program body - keeping configuration constants near the beginning makes them easy to find 6 generalize the repeated-greeting example: - message text and repetition count are independent choices - changing their literals is easy in a tiny program, harder in a large one 7 give each adjustable value a name: - const message = 'Hello, world!'; count = 20; - body uses for i := 1 to count do writeln(message) - declaration uses =, not := - each name can itself be used in later constant expressions 8 one conceptual value can occur many times: - locker count affects allocation, availability totals, and interface bounds - editing every repeated literal is error-prone 9 equal numbers may represent unrelated concepts: - 26 lockers and 26 printer columns need different names - changing one must not silently change the other 10 single source of the value: - LockerBoxCount appears numerically only in its declaration - all dependent uses follow that definition 11 names also explain meaning: - an unexplained 80 gives little information to a reader 12 DefaultHttpPortNumber communicates the role directly: - saves readers from reconstructing the meaning from distant code 13 author's style recommendation: - name meaningful numeric constants instead of scattering magic numbers - simple structural 0, 1, and sometimes -1 commonly remain literal - some projects also name all message strings 14 typed constants are a different Pascal facility: - const count: integer = 20 specifies storage/type explicitly - in some modes they are writable and resemble initialized variables - they are not interchangeable with untyped compile-time constants 2.2.16 Alternative numeric notation 1 ordinary notation: - decimal integers - decimal point in floating-point literals 2 hexadecimal integer literal: - prefix $; letters A-F are case-insensitive - $1A7 = 423 3 Free Pascal also provides: - binary %110100111 = 423 - octal &647 = 423 - these extensions are not universal across Pascal dialects 4 scientific notation in source: - mantissa followed by E and a decimal exponent - 7E3 = 7000.0 - 2.5E-5 = 0.000025 2.3 Subprograms 1 subprogram: - separate part of a program solving a subtask - has its own body and can have local variables - call names the subprogram and supplies parameters 2 reuse: - one implementation can be called from many places - different parameters adapt it to related cases 3 abstraction matters even for a single call: - a meaningful name hides secondary details - reader can understand the main algorithm without holding all details in mind 4 Pascal distinguishes: - procedure: performs a coherent action; call is a statement - function: computes a result; call is an expression 5 dialects and other languages differ: - Turbo/Free Pascal permit ignoring a function result in a statement - other languages need not make the same procedure/function distinction 6 author's teaching preference: - keep actions and value computations visibly separate - use this distinction to reason about side effects 2.3.1 Procedures 1 procedure declarations precede the main body: - SayHello contains writeln('Hello, world!') - main body calls SayHello - call preserves a return address, transfers control, then resumes after the call 2 procedure structure: - header, local declarations, begin ... end body - ends with a semicolon, unlike the program's final dot - header may declare parameters 3 trivial extraction can add clutter: - SayHello illustrates mechanics but gains little clarity over one output statement 4 PrintSpaces(count: integer): - count specifies how many spaces to print - local i controls for i := 1 to count do write(' ') - i and count are private names; outside entities may use the same names 5 procedure call: - PrintSpaces(k) prints k spaces - name followed by actual arguments in parentheses 6 diamond row needs only two inputs: - k: row position in the upper-half geometry - n: half-height - rendering does not depend on whether the caller is drawing top or bottom 7 PrintLineOfDiamond(k, n): - PrintSpaces(n+1-k), first star - when k > 1: PrintSpaces(2*k-3), second star - newline - both outer loops call the same procedure, removing duplicated row code 8 parameter declarations: - group same-type names with commas - separate groups of different types with semicolons - PrintChars(ch: char; count: integer) generalizes PrintSpaces 9 parameterless subprogram: - Pascal permits omitting the parameter list and its parentheses 10 terminology: - formal parameters: names/types in the declaration - actual parameters: arguments supplied at a call 2.3.2 Functions 1 function is a subprogram returning a value: - has header, optional local declarations, and body - call can occur within a larger expression 2 Cube example: - function Cube(x: real): real; - body assigns Cube := x*x*x - type after the parameter list specifies the result type 3 function call is a typed expression: - Cube(b+3.5) evaluates its argument, runs the function, supplies its result - a := Cube(b+3.5) - 17.1 then subtracts and stores the result 4 arguments can be variables or other expressions: - a := Cube(a) computes from the old a before replacing it - avoid unnecessary run-time work for already known constant results 5 Free Pascal allows discarding a function result: - author deliberately avoids this style in the course 6 returning value and control: - function must establish the result on every path that returns normally - caller receives that result when execution resumes 7 assign to the function's name to set its result: - iterative Fibonacci example uses q = 0 and r = 1 initially - each iteration: p := q; q := r; r := p+q - r holds the current Fibonacci number, q its predecessor - iterate from 2 through n; return r; n = 1 needs no iterations 8 separate exceptional/base input: - example returns zero for n <= 0 - author recommends one result-setting assignment on each execution path - multiple assignments are permitted by Pascal; this is a style restriction - Fibonacci values still must fit the chosen integer type 2.3.3 Boolean functions and conditions 1 boolean-returning function: - call itself is a boolean expression - can directly serve as an if/while condition - a meaningful predicate name can replace a long condition 2 IsLatinLetter(ch): - returns membership in 'A'..'Z' or 'a'..'z' - use if IsLatinLetter(c) then - reusable and clearer than repeated range comparisons - comparing the call to true adds nothing 3 return the boolean expression directly: - IsDigit := (ch >= '0') and (ch <= '9') - if condition then true else false merely reconstructs condition 2.3.4 Variable parameters 1 value parameter: - local variable initialized with the evaluated argument - p(2*a+7) passes the result, not the expression's constituent storage - changing local x does not alter caller's a 2 passing a variable by value still copies its value: - p(a) does not create a lasting connection between x and a 3 need for output parameters: - one subprogram may calculate several results together - x^2, x^3, x^4, x^5 need four successive multiplications - independent functions could repeat work 4 variable parameter: - formal name refers to the actual variable itself - updates through that name change caller's storage 5 var in a parameter declaration: - applies to that group up to the next semicolon/closing parenthesis - procedure p(var x, y: integer; z: integer; var k: real) - x, y, k by reference; z by value 6 powers example: - powers(x: real; var quad, cube, fourth, fifth: real) - quad := x*x; cube := quad*x; fourth := cube*x; fifth := fourth*x - actual output arguments must be variables of the required type - arbitrary expressions cannot supply assignable storage 7 call powers(17.5, p, q, r, t): - p, q, r, t receive the second through fifth powers 8 variable does not necessarily mean a simple identifier: - an array element, record field, or dereferenced pointer can also denote storage 9 passing large objects: - a variable parameter avoids copying the whole object - useful where copying would be costly 10 file variables have special restrictions: - no ordinary assignment, value passing, or function return - pass them through variable parameters 2.3.5 Global variables 1 scope: - local declarations are visible within their subprogram - program-level declarations are visible from their declaration onward - declare main-body-only data immediately before that body where dialect permits 2 global communication is possible but usually undesirable: - subprogram can read/write an earlier program-level variable - prefer explicit input parameters, function results, and output parameters 3 hidden state makes calls harder to understand: - arguments are visible at the call; global dependencies are not - previous activity can change later behavior unexpectedly 4 many potential writers complicate debugging: - finding who corrupted a global value can require searching the whole program 5 global singleton data obstructs multiple instances: - one game board/database today may become several tomorrow - pass the relevant object's state explicitly to support independent instances 2.3.6 Functions and side effects 1 Pascal functions can perform more than calculation: - read time/input, write output, change globals or variable arguments - expression evaluation can therefore alter observable state 2 side effect in the author's expression-focused terminology: - observable change occurring during evaluation, beyond its resulting value - examples: external variable changes and I/O - broader terminology also calls such effects in procedures side effects 3 NegotiateSize function example: - prompts until a positive odd height is entered - returns height - n := NegotiateSize div 2 embeds interactive I/O in an expression 4 make the action explicit with a procedure: - NegotiateSize(var res: integer) performs the same dialogue - NegotiateSize(n); n := n div 2 - separates interaction from arithmetic in the caller 5 author's distinction concerns how actions are expressed: - ordinary assignment/I/O statements are explicit actions - his narrower use of side effect concerns actions hidden inside expressions - it does not mean a procedure performing I/O is pure 6 C/C++ make this distinction less syntactically visible: - assignment is an expression operation - their subprogram syntax does not provide Pascal's procedure category 7 course rule: - use expressions primarily to obtain values - consciously justified exceptions exist - learn to distinguish necessary effects from confusing hidden behavior 2.3.7 Recursion 1 recursive call: - direct: a subprogram calls itself - indirect: a chain of calls returns to a subprogram already active 2 each invocation has its own locals: - allocated for the call, discarded when it returns - suspended callers keep their own values 3 termination needs: - a simpler instance at each recursive step - base case requiring no further recursive call - unbounded recursion consumes call storage and can exhaust it 4 recursive PrintChars: - count <= 0: do nothing - otherwise print one character, call PrintChars(ch, count-1) - count 3 produces calls for 3, 2, 1, 0, then returns through them 5 work during unwinding: - n mod 10 gives the last digit; n div 10 removes it - printing before recursion displays digits backward - recurse on n div 10 first, then print n mod 10 to restore normal order - zero requires an explicit wrapper case if it must print '0' 6 recursive functions can carry accumulated state: - ReverseNumber calls helper with remaining n and accumulator m = 0 - step: (n div 10, m*10 + n mod 10) - base n = 0 returns m - 752 -> 257; leading zeroes of the reversed numeral disappear - input/result must fit the intended nonnegative integer domain 2.4 Constructing programs 1 small examples can conceal organizational problems: - a screenful of code is comparatively easy to hold in mind 2 larger programs exceed human working memory: - experience raises the limit but does not remove it - growing software complexity motivated disciplined program structure 2.4.1 Structured programming 1 unrestricted jumps entangle control flow: - difficult to reconstruct execution paths, even for the author 2 structured-programming foundations: - Dijkstra criticized uncontrolled goto use - Boehm-Jacopini: sequence, conditional selection, and iteration suffice - practical structured constructs have one entry and one exit 3 composition and abstraction: - refinement replaces one action by a detailed structured fragment - generalization treats such a fragment as one action - one entry/exit makes this substitution possible 4 top-down stepwise refinement: - begin with the main structure - use comments or skeletal subprograms for not-yet-implemented actions - replace them progressively, introducing finer subtasks as necessary 5 connection to flowcharts: - each temporary action represents a rectangle awaiting refinement - the earlier StarSlash example already used this approach 2.4.2 Early exits 1 clarity is the goal of structural rules: - a limited departure can be justified when it makes the program easier to understand 2 early-exit facilities: - end a subprogram, program, loop, or iteration - modern Pascal dialects provide specific constructs for these purposes 3 exit leaves the current subprogram: - handle n <= 0 in Fibonacci, set result, then exit - ordinary case follows without enclosing it in else 4 quadratic solver interface: - inputs a, b, c - outputs success flag and two real roots - repeated root can be returned twice 5 guard exceptional cases before normal work: - initialize ok := false - if a = 0 then exit - compute d := b*b-4*a*c; if d < 0 then exit - otherwise calculate roots and set ok := true - example deliberately rejects linear equations; only read roots when ok 6 guard clauses avoid increasing nesting: - normal case stays prominent - each rejected special case no longer needs to be considered afterward 7 halt terminates the whole program: - callable from inside subprograms - use deliberately; a recoverable user mistake should not automatically end everything 8 halt(status): - supplies process exit status - zero conventionally means success; nonzero indicates failure - Unix shell-visible status is normally limited to the low eight bits 9 bare halt: - the example treats it as a successful termination - explicit status communicates intent more clearly 10 loop exits: - break leaves the innermost loop - continue skips the remainder of its current iteration - useful where they simplify a more complex loop body 2.4.3 Unconditional jumps 1 goto label transfers control to a labeled statement: - labels can be identifiers or legacy numeric labels - meaningful names communicate their destination better 2 declare labels in a label section: - label Quit, AllDone, SecondStage; - keep labels local to the body where they are used - do not use jumps as substitutes for subprogram calls/returns 3 label syntax: - point: statement - goto point - author recommends restricting goto to two particular patterns 4 leave several nested constructs: - one forward jump can be clearer than flags checked throughout multiple loops 5 shared cleanup: - acquired resources must be released on every relevant exit path - early exits otherwise duplicate cleanup code - place a cleanup label near the end and jump to it when required 6 both recommended patterns jump forward and outward: - backward repetition belongs in a loop - jumping into the middle of a construct defeats its entry assumptions 2.4.4 Decomposing a program into subprograms 1 decomposition reduces the amount of detail considered at once 2 one growing main body or subprogram becomes difficult to navigate/change: - small coherent subprograms can simplify even a longer overall source 3 complexity depends on simultaneous mental load: - understand one small implementation plus the overall call structure - other subprograms can be remembered by their contracts 4 author's size guideline: - aim for a body understandable at a glance, often around 25 source rows - longer case analysis can be reasonable - a growing body is a prompt to look for meaningful subtasks 5 historical basis of the guideline: - a conventional terminal displayed about 24/25 rows - fitting more text on a larger screen does not remove cognitive limits 6 one subprogram = one identifiable task: - split genuinely separable subtasks when they appear 7 false decomposition: - moving an arbitrary stretch of code into a new routine adds navigation - many shared variables/var parameters can preserve all the original coupling 8 finding boundaries requires practice: - two practical rules help test a proposed split 9 one-phrase rule: - describe the routine's purpose in one simple phrase - purpose plus parameter names should explain its inputs/outputs 10 keep interfaces manageable: - author recommends roughly five or fewer parameters as a heuristic - long parameter lists increase the effort and error risk of each call 11 independence rule: - caller should be understandable without callee's implementation - callee should be understandable without caller's implementation - constantly reading both bodies together indicates poor separation 12 optional reuse test: - imagine using the unchanged routine in a different program - plausible reuse is evidence of a coherent independent task - inability to reuse it alone does not prove the design bad 2.5 Characters, character codes, and text 1 text representation: - sequences of character codes - encoding assigns numeric representations to characters 2 chapter's simplified model: - one byte per character; ASCII and byte-oriented extensions - some byte-stream transformations also work on UTF-8 - general Unicode character processing needs more than this model 2.5.1 Character facilities in Pascal 1 char stores a single character/code unit in this model: - printable characters and control codes - useful ASCII codes: NUL 0, BEL 7, BS 8, HT 9, LF 10, CR 13, ESC 27 - rendering/control behavior depends on the terminal 2 keyboard input and terminal processing: - Ctrl combinations can generate control codes - terminal driver may interpret them instead of delivering them as data - Ctrl-C normally requests interruption, rather than supplying character #3 - programs can change terminal settings 3 character notation: - '7' denotes the digit character - #55 denotes the same ASCII code - #10 denotes LF; supported caret notation ^J also denotes LF 4 outputting control characters explicitly: - write('Hello, world!', #10) supplies a Unix-style newline - adjacent literal components can form one string: 'Hello, world!'#10 5 apostrophe inside a literal: - double it: 'That''s fine!' - four apostrophes denote one apostrophe character 6 character comparisons use ordinal code order: - ASCII letter/digit ranges are contiguous - (c >= 'a') and (c <= 'z') tests lowercase Latin letters 7 ord and chr: - ord(c) obtains a character's numeric code - chr(n) constructs the character for a valid code - unlike a literal, chr can use a value calculated at run time - ASCII display example nests row i and column j loops - chr(i*16+j) converts each hexadecimal row/column position to its character 2.5.2 Character-by-character input 1 numeric read can fail on malformed text: - default runtime error gives little useful context to a non-programmer 2 {$I-} disables automatic I/O-error handling: - IOResult = 0 means success; nonzero reports an I/O error - check it promptly; reading IOResult also clears the stored error status - a generic parse error still cannot identify the offending input precisely 3 structured input needs informative diagnostics: - explain what is wrong and where 4 character-by-character parsing provides control: - read raw characters and implement the conversion yourself 5 ReadLongint procedure: - isolate the parsing task - printing diagnostics inside it simplifies this example but reduces reuse 6 outputs through variable parameters: - success: whether a number was read - result: meaningful only on success - failure leaves result unchanged so caller must test success 7 convert a digit character to its value: - ord(c) - ord('0') - valid only after checking c is in '0'..'9' 8 decimal accumulation: - res starts at zero - res := res*10 + digit for each digit, left to right - '257' accumulates 0 -> 2 -> 25 -> 257 9 parser mechanics: - read(c) with char reads a character - skip leading spaces/newlines; track the input position - validate each following nonseparator as a digit, then accumulate - on invalid character: report position, discard the rest of the line, fail - on success: copy res to result, set success true - simplified example does not yet handle signs, overflow, every whitespace kind, or EOF 10 caller retries when necessary: - read each factor in repeat ... until ok - multiply only after both inputs succeeded - author contrasts interactive prompts with quiet Unix filter conventions 11 function version can hide work in a loop condition: - while not ReadLongint(x) do ; has an empty body - input, diagnostics, and output-parameter writes all occur during the test 12 author advises explicit action structure here: - compact side-effecting conditions are not automatically clearer 13 general lesson: - character-level input and analysis provide the most control over text parsing 2.5.3 Reading to EOF; filters 1 redirected input and pipes eventually run out of data 2 eof tests end-of-file state: - false: another character can be read - true: no more data available - no argument means standard input 3 EOF is a condition, not an ordinary character in the file: - regular-file length is tracked separately by the filesystem 4 no extra data byte must be read as an end marker: - eof asks about the stream's state - application formats can have sentinels, but those are a different concept 5 filter: - reads standard input and produces transformed/analyzed output - examples: grep, sort, cut, wc - stream interface makes filters composable in pipelines 6 FilterOk: - while not eof: read one character - on LF, print Ok - after the loop, print Good bye - counts line terminators; no whole-line storage needed - Ctrl-D at an empty terminal input line can signal EOF; Ctrl-C interrupts instead 7 line-length filter: - initialize count to zero - non-LF increments count - LF prints count and resets it - example handles newline-terminated lines; an unterminated final fragment needs extra handling - next example keeps/discards lines according to their first character 8 three logical states for line selection: - undecided, keep, discard - an enumeration would express them directly; example uses two booleans 9 on newline: - print it only if the current line was selected - reset know := false for the next line 10 on the first non-newline character: - print := (c <> ' ') and (c <> #9) - set know := true 11 after classification: - print the character only if print is true - remaining characters use the existing decision 12 initial state and self-test: - know := false; print := false - feeding the program its source retains only unindented nonempty lines 13 terminal buffering: - normal terminal mode supplies completed input lines - character-by-character processing does not imply one-keystroke-at-a-time interaction 14 storage needs depend on the task: - some filters need only a few state variables - others need complete lines or much larger datasets - sorting can also use external storage when data exceeds memory 2.5.4 Reading numbers to EOF 1 character EOF loop cannot be copied blindly for numeric input 2 example task: - count and sum all input integers - input length unknown; EOF ends it - chosen numeric types must accommodate values and their sum 3 naive pattern: - while not eof do read(n), add n, increment count - may attempt an extra numeric read after the final actual number 4 numeric reading has several stages: - skip leading separators - parse the number's characters - stop when the representation ends 5 trailing whitespace explains the problem: - after the last number, newline/spaces may still remain - eof is false although no further number exists - the book's runtime example then counts a spurious zero - do not equate remaining characters with a valid next number 6 terminal EOF can be transient: - later reads may accept more terminal input - this differs from repeatedly reading an exhausted ordinary file 7 SeekEof: - skips whitespace before testing for exhaustion - leaves the next nonwhitespace character available to read 8 use while not SeekEof for whitespace-separated numbers: - then read, accumulate, and count - malformed numeric tokens still require separate error handling 9 historical Free Pascal problem described by the author: - older SeekEof implementations failed on streams such as pipes 10 author's account of its origin: - behavior was documented as a limitation rather than promptly corrected 11 2020 investigation: - author compared the intended semantics and historical Borland implementation - emphasizes testing stream behavior, not only disk-file behavior 12 reported follow-up regression: - author says related output buffering changed during the fix 13 version context in the book: - corrected SeekEof included in Free Pascal 3.2.2, released in 2021 - recommendations about available distribution versions reflect the book's date 14 author's conclusion about tool choice: - this experience reduced his confidence in Free Pascal for professional work - it remains his teaching implementation 15 SeekEoln: - skips horizontal whitespace while testing for end of the current line - useful for variable-length groups of numbers separated by line boundaries 2.6 Pascal's type system 2.6.1 Built-in and user-defined types 1 built-in types: - compiler already knows integer, real, boolean, and similar types 2 user-defined types: - programmer introduces a type, usually with a name - unnamed types are called anonymous - user here means the compiler's user: the programmer 3 type declaration section: - starts with type - may be global or local to a subprogram - scope follows the same broad rules as other declarations 4 type alias: - type MyNumber = real; - new name for the existing type, compatible with it - changing representations separately throughout a large program is error-prone 5 choosing the widest type for everything has costs: - may still be insufficient later - wastes storage in large structures and can affect performance 6 name a type by its role: - type SimObjectId = integer; - use SimObjectId wherever an object's identifier is required - change its definition once if the identifier range must grow 2.6.2 Subranges and enumerations 1 aliases add names; subranges/enumerations introduce more specific types 2 subrange: - type digit10 = 0..9; - restricts values to that interval - enable appropriate range checks when run-time validation is needed 3 subrange representation: - Free Pascal normally uses an integer representation able to hold its bounds - 15000..15010 does not become an offset encoded in a single byte - direct representation avoids extra conversion during arithmetic 4 other ordinal subranges: - LatinCaps = 'A'..'Z' - boundaries must be compile-time constants 5 enumeration: - names its possible values explicitly in declaration order - RainbowColors = (red, orange, yellow, green, blue, indigo, violet) - values can be assigned and compared - pred(yellow) = orange; succ(blue) = indigo - do not step before the first or after the last value 6 pred/succ also apply to other ordinal types 7 ord gives an enumeration value's ordinal: - ordinary enumeration starts at zero and advances by one 8 explicit-number enumeration extensions: - dialects can permit them, with additional restrictions - author excludes these extensions from the teaching subset 9 value names must not conflict in the same scope: - red in both RainbowColors and Signals is ambiguous in the ordinary model - prefixes such as RcRed and SigRed distinguish the meanings 2.6.3 Ordinal types 1 ordinal type has: - ordered values with integer ordinal numbers - minimum and maximum - successor/predecessor except at the respective endpoint - ord, succ, pred expose these relationships 2 examples: - boolean: false then true - char: ordered by codes - integer types, enumerations, and ordinal subranges - floating-point types do not support this Pascal ordinal interface - restrictions on particular constructs/types depend on the dialect 3 ordinal types form a useful language category: - subrange definitions and several later constructs require an ordinal type - an arbitrary real interval cannot be substituted for one 2.6.4 Arrays 1 structured variable contains component variables: - main examples: arrays and records 2 array: - elements all have one type - index selects an element: a[3] - index may be an expression evaluated at run time 3 named array type: - real100 = array [1..100] of real - a, b: real100 creates two arrays of that type - a[1] := 1; a[i] := a[i-1]/2 builds powers of one half - b[i] := sin(a[i]) builds corresponding sine values - whole-array assignment copies all components; account for its cost - use a shared named type when compatible arrays are required 4 anonymous array declarations: - a and b declared together share their anonymous type - a separately repeated declaration can create a distinct type - structural similarity does not guarantee compatibility in every Pascal dialect 5 index specification is an ordinal type: - 1..100 is an anonymous subrange - a named subrange or enumeration can be used instead - array [RainbowColors] counts objects by color - array [char] counts byte characters - array [boolean] gives two entries for a condition's two outcomes 6 initialization and component variables: - array initializer lists values in parentheses - each a[i] is a real variable, usable as a var argument - components also have addresses 7 olympiad example: - many counters of the same type, one per school - card number's leading digits identify school; last two identify pupil - input line holds card number plus name; names are irrelevant to the count - readln reads the number and discards the rest of the line - redirect olymp.txt to standard input 8 data and first pass: - MaxSchool = 67; MaxGroup = 100; Counters[1..MaxSchool] - initialize every counter to zero - read each record with I/O checking handled explicitly - school number n := card div MaxGroup 9 validate index before indexing: - require 1 <= n <= MaxSchool - invalid input must not access nonexistent array storage - checked builds detect range errors; unchecked access may corrupt memory 10 failure and result computation: - report invalid data/school and stop with a failure status - valid record increments Counters[n] - second pass keeps index n of the largest counter seen so far - initialize n := 1; update when Counters[i] > Counters[n] - third pass prints every i whose count equals Counters[n] - prints ties, not just the first winning school - with no participants, all zero counters tie under this algorithm 2.6.5 Records 1 record: - named fields, potentially of different types - array elements instead share one type and are selected by index 2 CheckPoint example: - n and penalty: integers - latitude and longitude: real numbers - hidden: boolean - record ... end declares the fields - cp.latitude selects a field using a dot - whole-record assignment copies the record - fields are variables and can be assigned/passed by reference - storage may include alignment padding as well as the field contents 2.6.6 Combining data structures 1 nest records and arrays: - record may contain arrays or records - CheckPointArray = array [1..MaxCheckPoint] of CheckPoint - track[7].latitude selects one field of one array element - corresponds to a row/column cell in a conceptual table 2 multidimensional array = array of arrays: - array [1..5, 1..7] of integer - equivalent nesting: array [1..5] of array [1..7] of integer - a[2,6] and a[2][6] select the same component - matrices are a natural application - large nested structures consume real storage; local arrays can exhaust stack space 2.6.7 User-defined types and subprogram parameters 1 user-defined parameters require attention to type identity and copying 2 name ordinary parameter/result types first: - type MyRange = 1..100; then procedure p1(b: MyRange) - an inline 1..100 in that ordinary parameter position is rejected - special open-array facilities have their own syntax outside this discussion 3 large value parameters/results can be expensive: - copying takes time - call-local storage can place pressure on the stack 4 variable parameters avoid copying the object: - callee receives access to the original storage through its address - requires only pointer-sized call information 5 author's recommendation: - avoid unnecessary transfers of large structures - when passing them, consider reference-based interfaces - where available, read-only reference parameters express nonmutation more accurately 6 size guideline is heuristic: - a few machine words differ from hundreds of bytes or kilobytes - frequency, target architecture, and compiler behavior determine actual cost 2.6.8 Type conversion 1 integer value can be assigned to real: - r := 15 gives floating-point 15.0 2 conversion changes representation: - integer bits cannot simply be copied as a floating-point encoding - compiler generates the required representation conversion 3 implicit conversions: - occur without an explicit request in source - supported numeric assignments and value arguments may convert types - narrowing range/precision still needs care 4 floating-point to integer requires a chosen operation: - trunc discards the fraction toward zero - round rounds to an integer according to the rounding behavior - example: 15.75 -> trunc 15, round 16 - default nearest-even behavior resolves exact halfway cases in the discussed environment 5 values can be converted; var arguments cannot be silently replaced by converted copies: - callee operates on the original object's representation - actual variable type must meet the declared var-parameter requirements 6 explicit cast syntax: TypeName(expression) - e.g. byte('5') obtains an ordinal representation - some casts reinterpret equal-sized storage, others convert ordinal values - writable reinterpretations require compatible storage sizes 7 prefer purpose-specific operations: - ord for character code, chr for code-to-character - use casts only when their exact representation effect is understood 2.6.9 String literals and char arrays 1 string literals appeared first as immediately printed text 2 text is a broadly useful representation of information: - author emphasizes its suitability for many structured datasets - sampled images/audio/video often use more suitable binary encodings 3 whole-string operations can be clearer than manual character processing 4 char arrays can hold text: - Pascal permits certain special operations, including assignment from a literal - assigning a 13-character greeting to char[30] leaves zero padding - printing the array can emit all 30 bytes, including invisible NULs 5 padding explains the unexpected output: - useful characters occupy the initial elements - remaining elements receive zero characters in the example 6 manual output can stop at #0: - inspect elements in a bounded loop; break at the terminator - works here but makes a simple string action cumbersome 7 strings need a current length distinct from capacity: - actual input length is unknown when the program is written - concatenation and appending characters are common operations 8 later Pascal dialects supply dedicated string types for these tasks 9 literal components can include control codes: - 'one'#9'two' contains a tab between the words - alternate quoted text and # codes to construct one literal - supported caret notation can represent corresponding control characters too 2.6.10 The string type 1 short strings used in the book: - string[15] holds at most 15 characters - plain string in the selected mode means capacity 255 - one byte records current length - plain string can mean a different string family under other compiler modes/settings 2 short-string storage: - capacity plus one byte - meaningful characters indexed 1 through length(s) - s[0] is the length byte viewed as char; prefer length(s) over ord(s[0]) - positions beyond current length are not meaningful string contents 3 assignment between capacities: - permitted for these string types - assigning a longer value to a smaller capacity truncates it 4 copying uses the meaningful contents: - maximum reserved capacity and current useful data are different quantities 5 short-string var parameters have special compatibility rules: - differently declared capacities can be accepted in some interfaces/settings - caller's actual capacity must still be respected 6 + concatenates strings: - 'abra' + 'kadabra' = 'abrakadabra' 7 empty string: - '' has length zero - ' ' contains one space and has length one 8 char can become a one-character string: - s := ''; then s := s+c appends each character - looping c from 'A' to 'Z' builds the alphabet 9 other Free Pascal string families: - managed long strings and Unicode-related representations exist - their limits/storage behavior differ from these short strings 2.6.11 Built-in string operations 1 built-ins simplify common tasks: - character-level processing remains sufficient to implement the basic operations 2 length and SetLength: - length(s) returns current length - shortening 'abrakadabra' to four characters gives 'abra' - when extending a short string, initialize the newly meaningful characters - changing its length does not increase its declared capacity 3 course exercise: - understand how the operations below work on characters before relying on them 4 LowerCase / UpCase: - return corresponding lowercase/uppercase Latin-letter forms in this discussion - full locale/Unicode case conversion requires more care 5 copy(source, start, count): - returns the requested substring, shortened at the end if necessary - copy('abrakadabra', 3, 4) = 'raka' 6 delete(s, start, count): - removes characters in place - delete(s, 5, 4) changes 'abrakadabra' to 'abrabra' 7 insert(piece, s, position): - modifies destination s - inserting 'PQR' at position 4 of 'abcdef' gives 'abcPQRdef' 8 pos(piece, source): - first matching position; zero means absent - pos('kada', 'abrakadabra') = 5 9 val(text, number, error_position): - converts a numeric representation - error_position = 0 indicates success - otherwise reports the offending position; do not use number as a valid result 10 str(number, destination): - writes formatted numeric text into a string - formatting resembles write: str(12.5:9:3, s) - result is three spaces followed by 12.500 11 BinStr / OctStr / HexStr: - integer-to-string functions for binary, octal, hexadecimal - arguments specify the number and desired output width 2.6.12 Command-line arguments 1 program can receive arguments at startup: - ./demo abra schwabra kadabra supplies three arguments 2 ParamCount and ParamStr: - ParamCount excludes the program's own name - ParamStr(i) obtains argument i, numbered from 1 - ParamStr(0) provides the runtime's program-name/path value 3 display example: - loop i := 0 to ParamCount and print ParamStr(i) - shell quoting such as "one two three" passes one argument - grouping is performed by the shell before Pascal receives the arguments 2.7 The case statement 1 case generalizes conditional selection: - evaluate an ordinal expression - select a branch according to its value 2 syntax: - case expression of ... end - each branch: value_set: statement - statement may be compound - optional else handles values absent from the other branches 3 branch labels: - one constant, comma-separated constants, or a constant range - values must be determined at compile time 4 character-classification example: - letter ranges, digit range, arithmetic signs, comparison signs - separate cases for spaces, control characters, brackets, and quotes - else handles unclassified input 5 unexplained numeric alternatives obscure meaning: - case nv of 1, 2, 3 ... forces readers to reconstruct each number's role - easy to select the wrong number elsewhere in the program 6 prefer a meaningful enumeration for conceptual alternatives: - names convey which state/category each branch handles 7 keep branch implementations manageable: - case may justify a somewhat longer subprogram - extract complex alternatives into coherent routines - author's style discourages deeply nested case constructions 2.8 Full-screen programs 1 optional practical detour: - these terminal facilities are not prerequisites for later chapters 2 self-chosen projects matter: - more available techniques make personally interesting projects possible 3 full-screen text interfaces: - use terminal positions and immediate key input - go beyond ordinary line-oriented dialogue 4 text interfaces can support substantial applications: - editors, mail/chat clients, and games such as NetHack 5 dynamic terminal games are one possible application - usefulness is broader than games 6 reading strategy: - skip if already working on an interesting project that does not need these tools - otherwise experiment for possible project ideas 2.8.1 Background 1 escape sequences control terminals: - byte sequences commonly beginning with ESC, code 27 - move cursor, set attributes, scroll, and perform other screen actions 2 full-screen input also needs terminal-mode changes: - canonical mode delivers completed lines - Ctrl-C/Ctrl-D normally receive special driver treatment - applications can configure these behaviors 3 terminal differences motivate libraries: - libraries hide differing control sequences/capabilities - ncurses is a common C example 4 crt history: - originated in Borland Pascal's DOS environment - Free Pascal implements a compatible interface using host-system facilities 5 crt is the simpler interface chosen for these teaching examples 6 import it with uses crt: - placed after the program header - startup changes terminal behavior - provide an explicit way to exit; familiar interrupt keys may behave differently 7 crt assumes an interactive terminal: - do not treat these examples as ordinary redirectable stream filters 2.8.2 Output at arbitrary screen positions 1 clrscr: - clears the screen and moves cursor to the upper-left corner 2 GotoXY(x, y): - horizontal position first, vertical position second - upper-left cell is (1,1) - ScreenWidth / ScreenHeight provide terminal dimensions known to crt 3 centered greeting example: - clear, position cursor, print message - move cursor out of the way, delay, clear again - delay takes milliseconds; 5000 means five seconds 4 centering uses integer arithmetic: - horizontal unused width = screen width - message length - distribute that space around the message - with one-based coordinates, add 1 to the left/top margin count - handle messages wider than the available screen 5 complete sequence and position queries: - keep message/delay as named constants - WhereX / WhereY return current cursor position - output itself advances the cursor - do not pass coordinates outside the available cells 6 resize limitation described for this crt interface: - dimensions established at startup may not track later window resizing 2.8.3 Immediate keyboard input 1 KeyPressed: - true when an unread key code is available - false when no input is waiting 2 ReadKey: - removes and returns the next key code - blocks until input exists if none is available - consumes input, so its call has an observable effect 3 ordinary keys return char codes: - letters/digits/punctuation usually return their characters - Enter is #13 in the illustrated crt implementation - Escape #27, Tab #9, Backspace #8 - terminal/platform differences should be checked 4 extended key protocol: - first ReadKey returns #0 - second ReadKey returns the special-key code - arrows: left 75, right 77, up 72, down 80 - a small key-code display program reveals the actual environment's behavior 5 historical implementation irregularities: - author observed some unexpected multi-code sequences - these observations belong to the version/environment used for the book 6 GetKey wrapper isolates the protocol: - one place calls ReadKey and handles the optional second read - caller sees one explicit input operation - wrapping changes interface clarity, not the underlying fact that input is consumed 7 GetKey(var code: integer): - ordinary key -> ord(c) - extended key -> negative ordinal of the second code - negative/positive values distinguish categories - use it to build a greeting moved by arrow keys 8 separate drawing operations: - ShowMessage prints at current coordinates - HideMessage replaces it with the same number of spaces - MoveMessage hides, adds dx/dy to coordinates, then redraws - use named constants for arrow codes 9 input loop for the greeting: - ordinary key exits - arrow selects the corresponding movement; other extended keys do nothing - initial example omits bounds checks; add them to prevent off-screen coordinates 10 moving-star example: - arrow starts/changes continuous movement - space stops; Escape exits 11 wrap at screen edges: - beyond right -> left; beyond left -> right - analogous wrapping vertically 12 timing: - 100 ms between steps gives roughly ten moves per second 13 group star state in one record: - position CurX/CurY and direction dx/dy - ShowStar, HideStar, MoveStar operate on that state - MoveStar erases, advances, wraps, and redraws - SetDirection changes the velocity components 14 main loop: - initialize centered position and zero direction - no waiting key: move, delay, continue to next iteration - waiting key: read and dispatch it - space sets both direction components to zero - Escape breaks the loop; clear the screen before finishing 2.8.4 Color control 1 terminals can choose foreground and background colors 2 crt exposes a historically limited attribute model: - sixteen foreground colors, eight background colors, blink flag - inherited from the DOS text-screen interface 3 compatibility explains the limits: - other interfaces can expose wider terminal capabilities - author keeps crt here because it is easy to learn 4 TextColor / TextBackground: - named color constants select subsequent output attributes - TextColor(Yellow); TextBackground(Blue) gives yellow text on blue - TextColor(Blue or Blink) requests blinking blue text where supported 5 restore attributes before exit: - save TextAttr before changing colors - restore it at the end, then perform output such as clrscr to apply it 6 terminal escape reset: - write(#27'[0m') requests default display attributes - this is direct terminal control rather than a crt color call 7 color demonstration: - foreground varies by row - background varies across groups of columns - alternating positions request blink 8 decomposition: - AllColors stores named color values - MakeScreen chooses row foreground and calls MakeLine - MakeLine computes background groups and outputs stars - keep group width at least one; avoid final bottom-right cell to prevent scrolling 9 pause so the result remains visible: - readln waits for Enter in this demonstration 10 main sequence and indexing: - save attributes, draw, wait, restore, clear - mod cycles through foreground entries - div maps columns to background groups - bound the background index for widths not divisible by eight - the printed sample's simple division formula needs that edge-case correction 2.8.5 Random and pseudorandom numbers 1 terminal tools make simple games feasible 2 author encourages projects that make programming enjoyable: - his claim linking interest in games to suitability for programming is a personal view 3 random choices provide variety: - even a deterministic game can vary equivalent choices between sessions 4 security-sensitive randomness needs unpredictability: - operating systems provide facilities drawing on entropy and maintained state - ordinary demonstration generators are unsuitable for secret keys 5 ordinary visual/game demonstrations often need only pseudorandom variation - security, adversarial, or money-related uses require stronger requirements 6 pseudorandom generator: - maintains internal state - deterministic update produces the next state and result 7 seed controls repeatability: - same initial state and call sequence reproduce the results - useful for debugging - varying startup seed changes the demonstration between runs 8 randomize initializes generator state: - call once near startup when varying runs is wanted - repeatedly reseeding can repeat or correlate results 9 random forms: - random -> floating-point value in [0,1) - random(n) -> integer in 0..n-1 for positive n - obtaining a value advances generator state 10 random-stars demonstration: - choose x := random(ScreenWidth)+1 and analogous y - skip bottom-right cell to avoid scrolling - select a random color, draw '*', delay 20 ms - continue until a key is waiting - restore original text attributes and clear on exit 2.9 Files 2.9.1 General principles 1 programs can open files themselves: - not limited to streams arranged by shell redirection - operating-system permissions still apply 2 opening a file: - identify its path and intended access mode - obtain an associated stream for subsequent operations 3 file variables identify active streams: - special types with restricted operations - no ordinary assignment or independent file-value expressions - pass file variables through var parameters 4 three interfaces: - text: textual input/output - file: untyped block I/O - file of T: fixed-size values represented as T - selected interface reflects the operation the program needs 5 assign(f, filename): - associates a path with a file variable - does not open/create the file or check existence - filename may be calculated at run time - Unix leading / means absolute path; otherwise relative to current directory 6 filename belongs to the filesystem: - program may obtain it from arguments, input, or another file 7 file-variable name belongs to source code: - arbitrary identifier, independent of disk filename 8 assign establishes the association: - a closed file variable can later be assigned another path 9 opening operations: - reset: open existing file from its beginning - rewrite: create or truncate to an empty file - append: open text output at its end - actual read/write access for typed/untyped files also depends on FileMode 10 expect opening failures: - handle I/O status explicitly with {$I-} and IOResult when useful - report errors in terms meaningful to the user 11 read/write with a file variable first: - read(f, x), write(f, x) - text interface converts to/from textual representation - typed-file interface transfers a fixed-size value representation - readln/writeln apply to text; eof(f) tests a specified stream 12 untyped files use BlockRead / BlockWrite 13 close(f) ends work with the open stream: - afterward f may be reopened for the same path or assigned a different one 14 HelloFile example: - assign, rewrite, writeln(f, message), close - Unix output contains greeting plus newline - check opening, writing, and final close/flush failures when correctness matters - successful open does not guarantee successful later writes 15 current position: - ordinary reading/writing advances it by transferred data - successive reads obtain successive portions - some file interfaces allow explicit repositioning 2.9.2 Text files 1 text file: - data represented as characters, usually organized into lines - same broad representation used by standard textual streams 2 text file variables support line operations: - readln, writeln, eoln - these operations have no equivalent line meaning in arbitrary binary records 3 numeric text I/O converts representations: - output: machine value -> digit characters - input: digit characters -> machine value 4 number-file example: - write 100 values starting at 1000, incrementing by 1001 - text version uses writeln(f, n), one numeral per line - Pascal's text interface is sequential - reset opens for reading; rewrite/append for writing - editing variable-length content commonly means writing a replacement file 5 numeric EOF/EOL tests: - SeekEof(f) skips whitespace before checking whether meaningful input remains - SeekEoln(f) checks whether the current line has another nonspace token 6 sum of line products: - get filename from argument; open and check success - sum := 0 - for each nonempty group: mul := 1; read/multiply numbers until end of line - consume the line boundary with readln(f), then sum := sum+mul - 2*3*5 + 0.5*12 = 36 - malformed-number and read-error checks are needed beyond the simplified example 7 SeekEof / SeekEoln depend on text conventions: - whitespace and line boundaries are not generic binary-record separators 8 standard streams have file-variable names: - input and output are text variables - writeln(output, 'Hello') is explicit standard output - a var text parameter can accept an opened text file or output 9 additional Free Pascal names: - stdin / stdout - ErrOutput / stderr for diagnostics 2.9.3 Typed files 1 typed file = sequence of fixed-size representations: - file of longint stores longint values directly - same generating loop as text example, but write replaces writeln - representation depends on type/compiler/platform; it is not a portable text encoding 2 element-type restrictions: - file variables cannot be stored as file elements - pointer values generally have no useful persistent meaning in another execution - file of char can access a byte-oriented file one element at a time 3 record elements: - NamedPoint combines coordinates and a bounded name - file of NamedPoint stores a sequence of those records - rewrite creates/truncates; reset opens existing data 4 seek(f, index) selects a zero-based record position: - fixed size makes direct positioning possible - to change record 705: seek, read, alter field, seek back, write - second seek is necessary because read advanced to record 706 5 positioning requires a seekable stream: - regular files support it - terminal/pipe streams do not provide ordinary random-access file semantics 6 default typed-file access in the described runtime: - reset normally requests reading and writing - rewrite creates/truncates, while reset preserves existing contents 7 FileMode controls reset's access mode: - 0: read only; 1: write only; 2: read/write - select read-only mode when only reading is needed - write-only reset still preserves previous contents - FileMode does not give rewrite the same mode behavior 2.9.4 Block I/O 1 untyped files transfer arbitrary chunks: - practical interface close to operating-system byte/block I/O 2 transfer data between file and memory buffer: - opening specifies block size - each transfer specifies a number of blocks - block size 1 makes those counts byte counts 3 declare f: file: - assign as usual - reset(f, 1) or rewrite(f, 1) explicitly chooses one-byte blocks - omitted block size defaults to 128 in the discussed interface 4 opening modes: - FileMode affects reset as with typed files 5 BlockRead / BlockWrite arguments: - file variable - buffer variable - requested block count - variable receiving actual transferred count - block_count * block_size must fit the buffer - short read may simply mean fewer bytes remain - zero bytes read without an I/O error indicates EOF 6 keep the actual-count result: - omitting it can turn ordinary short reads into runtime errors - check I/O status as well when an actual error must be distinguished from EOF 7 copy-file example: - source/destination paths come from arguments - source opened read-only; destination created/truncated - transfer buffer = 4096 bytes; block size = one byte 8 copy loop: - read a chunk and inspect actual count/status - stop at EOF before attempting a write - write exactly the bytes read, including a partial final chunk - compare actual written count with actual read count - close both files; send diagnostics to ErrOutput - sample's write-error branch only breaks; a complete version must also return failure - read and final close errors also require checks for reliable copying 2.9.5 Operations on whole files 1 whole-file operations: - erase deletes a file - rename changes its filesystem name 2 use an assigned, closed file variable: - assign(f, path) before erase(f) - assign(f, old_path) before rename(f, new_path) - any of the file-variable categories can be used - if it was open, close it first - examples validate command-line arguments and check IOResult - report failure through ErrOutput and a nonzero exit status 2.10 Addresses, pointers, and dynamic memory 1 variables declared in the program: - their types and sizes determine memory requirements before execution 2 memory requirements may depend on the input: - fixed teaching limits do not necessarily suit real tasks - sort accepts arbitrary line lengths and counts, within available resources - allocate the memory needed by the particular input 3 dynamic variables: - created during execution; accessed through addresses and pointers - let the program determine its memory needs at runtime - pointers also have uses beyond dynamic allocation 4 pointers may take considerable effort to understand 5 preparation for C: - Pascal permits substantial programming before introducing pointers - C requires a clear understanding of addresses from an early stage 6 do not leave pointers unresolved before proceeding: - seek help, practise with familiar tools, or study the assembly material - return after gaining experience if necessary 2.10.1 What a pointer is 1 address: - information uniquely identifying a memory cell - often an integer; some architectures use more complex representations 2 memory region: - consecutive cells; a variable occupies such a region - address of the region = address of its first cell 3 pointer: - a variable containing an address - one region of memory can contain the address of another 4 A points to B = A contains B's address - pointer: variable; address: value stored in it - informal expressions such as 'return a pointer' usually mean return an address 2.10.2 Pointers in Pascal 1 typed pointers: - pointed-to type tells the compiler how to interpret the addressed region - p: ^integer; q: ^real - ^ replaces the upward arrow used in Wirth's original notation 2 address-of operation: @x - p := @r makes p contain r's address - applies to any variable, including array elements and record fields 3 original Pascal lacked address-of: - pointer use was largely restricted to dynamic variables - the dialect used here supplies @ 4 dereference: p^ - denotes the variable at the address contained in p - after p := @r, p^ and r denote the same variable - p^ := 25.7 changes r; writeln(p^) prints its value 5 untyped pointer: pointer - can hold an address without specifying the stored value's type - assignments to typed pointers can bypass useful type checks - interpreting a string's address as ^integer does not make an integer exist there 6 @ produces an untyped address by default in the dialect discussed - {$T+} enables typed addresses 7 nil: - special invalid address; indicates that a pointer currently points nowhere - often called a null pointer, although nil itself is a value 8 pointer notation: - ^t: pointer-to-t type - @x: address of x - p^: variable reached through p - nil: no addressed variable 2.10.3 Dynamic variables 1 dynamic variable: - memory region created during execution - has no identifier of its own; accessed through an address 2 heap: - supplies storage for dynamic variables - disposing of a variable makes its region available for reuse - the allocation model described retains acquired heap memory until exit - freeing obsolete storage before allocating replacements can reduce peak use 3 new(p): - requires a typed pointer - allocates enough storage for the pointed-to type - stores the new region's address in p 4 p: ^string; new(p) - creates a string variable in the heap - the short-string representation used here occupies 256 bytes - p^ := 'This is a string, which resides in the heap' fills it 5 dispose(p): - releases the variable addressed by p - does not change p itself - p still contains the old address, which must no longer be dereferenced 6 allocation belongs to an address, not to one particular pointer: - q := p copies the address; p^ and q^ denote the same variable - p can subsequently be reused while q retains access - dispose(q) releases that same allocation 7 losing the only address: - a second new(p) overwrites p without disposing of its previous allocation - the first variable remains allocated but can no longer be reached 8 garbage: - unreachable allocated memory - distinct from junk: meaningless/uninitialized data - some languages reclaim garbage automatically; collection can pause execution 9 memory leak: - allocated storage is lost without being released - this Pascal model has no automatic garbage collection - retain ownership information and dispose of unneeded variables 10 why use dynamic storage: - large temporary objects can exceed practical stack limits - allocate and release objects according to when they are needed - the main applications here are linked structures built from records containing pointers 2.10.4 Singly linked lists 1 singly linked list: - each node contains data and a pointer to the next node - last node's next = nil - a pointer to the first node makes the whole chain reachable 2 one chain of links: - one next field per node - each node is reached through the preceding link or the head pointer 3 node type for integer data: - data: integer; next: pointer to the same record type - naming the record inside its own declaration is restricted in older Pascal implementations 4 forward pointer type: - declare itemptr = ^item before declaring item - item contains data: integer and next: itemptr - first^ = first record; first^.next = pointer to the second - first^.next^ = second record; first^.next^.data = its value - explicit new calls can build 25 -> 36 -> 49 -> nil 5 understand each dereference and field selection before continuing 6 usual construction methods: - prepend through a temporary pointer - or maintain first and last, and append - try implementing the exercises before reading the solutions 7 exercises: - read integers to EOF and print them in reverse order - read integers to EOF and print them twice in their original order - no fixed limit on the number of integers - a working, tested program is required; an imagined solution is insufficient 8 initialize an empty list: first := nil - an uninitialized pointer does not represent a valid empty list 9 prepend in three stages: - allocate a node through tmp - set its data and make tmp^.next point to the old first node - assign first := tmp 10 prepending 25 to 36 -> 49: - new(tmp) - tmp^.data := 25; tmp^.next := first - first := tmp - allocation alone leaves the original list unchanged and the new fields uninitialized 11 empty-list case needs no separate prepend algorithm: - the old first is nil, so the new node's next becomes nil - requires correct initial first := nil 12 reverse-order program: - read with while not SeekEof; prepend each value - traverse from first while tmp <> nil; print tmp^.data; advance tmp := tmp^.next list disposal: - save first^.next, dispose(first), then replace first with the saved address - or save first, advance first, then dispose the saved node - never read a node's next after disposing of that node - exit releases the example's storage; repeated work in a longer program needs explicit disposal 13 preserve input order by appending: - reversing an already built list is possible, but unnecessary here 14 append with first and last: - empty list: both nil; allocate first and assign last := first - nonempty list: new(last^.next); last := last^.next - fill last^.data and set last^.next := nil alternative using tmp: - allocate and fill tmp, with tmp^.next := nil - if empty, first := tmp; otherwise last^.next := tmp - finish with last := tmp - draw and check both the empty and nonempty cases 15 complete the second exercise independently: - append during input, then traverse the completed list twice 2.10.5 Stack and queue 1 stack and queue describe behavior: - can be implemented using lists, arrays, circular buffers, or external storage - their identity is determined by operations and retrieval order 2 both store values and support insertion/extraction: - queue = FIFO: first in, first out - stack = LIFO: last in, first out 3 queue returns the oldest remaining value stack returns the newest remaining value 4 singly linked implementations: - stack: insert and remove at the beginning - queue: append at the end; remove at the beginning 5 hide implementation behind subprograms: - clients use operations without depending on the representation - changing list storage to array storage should affect those subprograms alone 6 interface: - available procedures/functions plus the rules for using them - a good interface remains usable when implementation details change 7 design interface first: - start with the operations the user needs - choose a representation afterward 8 StackOfLongints: - one variable represents each independent stack - its eventual type can be a record or another suitable representation - give the type a name before committing to its contents 9 stack operations: - SOLPush(var stack; n): insert a longint - SOLPop(var stack; var n): remove the top value and return it through n - both receive the stack by reference because they change it 10 SOLIsEmpty(var stack): boolean - check before popping unless nonemptiness is already certain - by-reference parameter also avoids copying a potentially large representation - the contract excludes popping an empty stack 11 SOLInit makes a newly declared variable a valid empty stack implementation: - StackOfLongints = pointer to the first LongItem - init: nil; push: prepend; pop: extract data, unlink first, dispose it - empty: stack = nil - reverse-input example pushes all numbers, then pops and prints until empty 12 alternative boolean SOLPop: - returns false for an empty stack; otherwise extracts n and returns true - permits while SOLPop(s, n) do writeln(n) - combines a result with a side effect; the book postpones this style 13 QueueOfLongints interface: - QOLInit, QOLPut, QOLGet, QOLIsEmpty - represent a queue with a record containing first and last - init sets both nil; put appends, handling the initially empty queue - get copies first^.data, advances first, and disposes the old node - when removal empties the queue, also set last := nil - check emptiness through first = nil; never get from an empty queue 2.10.6 Traversing a list with a pointer to a pointer 1 remove every negative value: - removing the first node changes first - removing another node changes its predecessor's next 2 ordinary traversal loses the predecessor: - a predecessor-based loop needs separate handling for negative head nodes - an additional prev pointer reduces duplication but still needs a head special case 3 pointer to the incoming link: pp: ^itemptr - can contain @first or the address of any node's next field - pp^ = pointer to the current node; pp^^ = current node - start pp := @first - advance pp := @(pp^^.next) 4 advance only when keeping the current node: - after removal, the same incoming link already points to the next candidate 5 traverse while pp^ <> nil removal: - tmp := pp^; pp^ := pp^^.next; dispose(tmp) - otherwise advance pp to the current node's next field - identical handling for first, interior, and consecutive removed nodes - empty lists need no separate branch 6 insertion at the link held by pp: - new(tmp); tmp^.next := pp^; tmp^.data := n; pp^ := tmp - works before any node and at the end where pp^ = nil - every list tail is itself a list, with its incoming link acting as a head pointer 7 sorted list: - locate the insertion position that preserves the ordering 8 ascending insertion: - begin at @first; advance while a next candidate exists and its value is smaller than n - insert before the first value >= n, or at the end 9 stop comparison: - pp^^.data >= n means the correct position has been found 10 nil protection: - pp^^.data is invalid when pp^ = nil - separate checks prevent dereferencing a nonexistent node 11 short-circuit evaluation: - while (pp^ <> nil) and (pp^^.data < n) do ... - if the first operand is false, the second need not be evaluated - permits the compact condition without dereferencing nil 12 dialect differences: - original Pascal evaluated all boolean operands and lacked break and @ - neither the compact guarded condition nor this pointer-to-pointer technique transfers unchanged to it 13 Free Pascal evaluation directives: - {$B+}: full boolean evaluation; {$B-}: short-circuit evaluation - the examples depend on short-circuit evaluation where conditions guard dereferences 14 dummy head alternative: - an extra node can supply an incoming next field for the first real node - the pointer-to-pointer method handles first directly, without that extra node 2.10.7 Doubly linked lists; deques 1 doubly linked lists extend the one-way list structure 2 each node contains two links: - prev points to the predecessor; next points to the successor - forward and backward chains connect the same nodes - first and last commonly identify the two ends 3 item2 record: - data: integer; prev, next: item2ptr - use conventional prev and next names to make the roles clear 4 cost and benefit: - extra pointer storage and more link updates on insertion/removal - traversal can proceed in either direction 5 any node gives access to the whole chain: - its prev finds the predecessor and hence the incoming next link - at the beginning update first; at the end update last - both neighboring links must agree after insertion/removal 6 insert beside current: - left: tmp.prev := current.prev; tmp.next := current - reconnect predecessor.next or first to tmp; set current.prev := tmp - right: symmetric changes to next, successor.prev, and last remove current: - reconnect predecessor.next or first to current.next - reconnect successor.prev or last to current.prev - dispose current only after saving the address needed for continuing traversal 7 insert at the ends: - prepend: tmp.prev := nil; tmp.next := first - update old first.prev, or last if empty; then first := tmp - append is symmetric generalized insertion: - insertion before current = nil can mean append - insertion after current = nil can mean prepend - initialize both new links, then update each neighbor or corresponding end pointer 8 deque: - insert and extract at either end - extracting at the insertion end gives the newest value first - extracting at the opposite end gives the oldest value first 9 operation names: - pushfront, pushback, popfront, popback - selected pairs provide stack or queue behavior - use simpler stack/queue implementations when only those operations are needed 10 LongDeque exercise: - record containing first and last pointers to doubly linked nodes - implement Init, PushFront, PushBack, PopFront, PopBack, IsEmpty - require a nonempty deque before either extraction 2.10.8 Other dynamic data structures 1 search key: - data used to find a record, such as inventory number, name, or address - record also contains the associated information returned by the search 2 linear list search: - follow links one by one until finding the key - work grows proportionally to the number of records - a sorted list still lacks direct access to its middle 3 scaling: - repeated linear searches become increasingly expensive as the collection grows 4 binary search tree: - nodes contain left and right child pointers - nil child pointer = empty subtree 5 search-tree invariant: - smaller keys belong in the left subtree; larger keys in the right - applies recursively at every node - searching follows one branch per comparison; work depends on height - height h can accommodate up to 2^h - 1 nodes - a densely filled tree of height 20 holds over a million nodes 6 unbalanced tree: - can have substantial height despite few nodes - sorted insertion can produce a single chain, with linear search cost - balancing reduces height but needs additional algorithms 7 tree variations: - recursive code naturally expresses binary-tree operations - nodes may have more than two children - a character trie selects a child using the next character; height depends on key length 8 search costs: - list: proportional to record count - balanced binary tree: proportional to log2(record count) - hash tables aim at constant expected lookup cost under suitable loading/distribution 9 hash function and table: - same key always gives the same hash; different keys should spread well - bucket/index = hash(key) mod table size - the example uses a generously sized array, commonly with prime length 10 collision: - different keys select the same position - empty position means absent key in the basic lookup scheme - chaining stores a list of colliding records at each table position - lists add allocation, linking, and traversal overhead 11 linear probing: - continue through successive positions until finding the key or an empty slot - insert in the first available slot - deleting an entry must preserve reachability of later entries in its probe chain - one method removes and reinserts the following cluster up to its first empty slot 12 load factor and resizing: - crowded tables spend more time resolving collisions - the book suggests staying below roughly two-thirds occupancy - grow the array and reinsert every record using the new modulus - resizing requires substantial work; old positions cannot simply be retained 13 dynamically sized arrays: - needed when the table capacity is chosen or changed during execution - available in modern Pascal dialects, beyond the subset covered here 2.11 More about recursion 1 strings, lists, and trees provide more substantial uses of recursion - revisit the technique with a larger set of programming tools 2.11.1 Mutual recursion 1 mutual recursion: - one subprogram calls another, which calls the first - the earlier definition needs information about the later subprogram 2 forward declaration: - header followed by forward; gives the name, parameters, and result type - contains no local declarations or body - lets the compiler check calls and generate argument conversions before seeing the implementation 3 declaration order: - declare the first subprogram forward - define the second, then provide the first subprogram's complete definition - both bodies can then refer to both names 4 every forward declaration requires a later matching definition 2.11.2 Towers of Hanoi 1 implement the recursive algorithm introduced with the idea of an algorithm 2 task: - three rods; N differently sized disks initially stacked largest to smallest - move one disk at a time; never place a larger disk on a smaller one - transfer the whole stack using the fewest moves 3 recursive decomposition: - move n-1 disks from source to transit - move disk n from source to target - move n-1 disks from transit to target - base case n = 0: nothing to do 4 solve(source, target, transit, n): - recursive calls exchange rod roles as required - output identifies the disk and its source/target rods - validate the command-line disk count with val and require n >= 1 - start solve(1, 3, 2, n) 5 alternative iterative algorithm: - odd moves: move the smallest disk around the rods - even disk count: 1 -> 2 -> 3 -> 1; odd count: reverse direction - even moves: perform the sole legal move excluding the smallest disk 6 apparently simple physical actions need explicit program state: - track which disks occupy each rod - compare top disks and handle empty rods 7 hanoi2 representation: - three singly linked lists, one per rod; array of head pointers - continue until rods 1 and 2 are empty - compute smallest-disk moves from the turn number - other moves find its rod, exclude it, then choose the legal direction between the remaining rods 8 iterative implementation is much longer: - bookkeeping dominates the concise recursive description 9 recursion can also be replaced by an explicit task stack: - preserve the original recursive decomposition - a loop processes stored unfinished tasks 10 task record: - disk count, source rod, target rod, state, and next pointer - StClearing: prepare to move the smaller disks away - StLargest: move the largest disk, then bring the smaller disks onto it - StFinal: task complete; remove it processing: - start with one task transferring all disks from 1 to 3 - in StClearing, change the current task to StLargest - if more than one disk remains, push the task for clearing n-1 disks - tasks remember where suspended work must resume 11 StLargest: - print the move of disk amount from src to dst - change the current task to StFinal - if needed, push a task moving smaller disks from transit to target - when a StFinal task returns to the front, unlink and dispose it 12 IntermRod(src, dst): - returns the rod number different from both src and dst - supplies the intermediate rod for each newly created subtask 13 hanoi3: - explicit task management is shorter than the first iterative approach - still substantially more code than the recursive solution 2.11.3 Pattern matching 1 match an entire string against a pattern: - ordinary character: matches itself - ?: matches one arbitrary character - *: matches any sequence, including an empty sequence - a?c matches abc; a* matches any string beginning with a 2 work with unprocessed suffixes: - previously removed prefixes have already matched - when the pattern ends, succeed only if the string has also ended 3 ordinary character or ?: - require an available string character - fail if an ordinary pattern character differs - otherwise advance both positions and continue 4 * introduces alternatives: - try consuming zero, one, two, ... remaining string characters - recursively match the remaining pattern after the * against each resulting suffix - return true on the first success; false when all alternatives fail 5 MatchIdx(var str, pat; idxs, idxp): boolean - indexes identify suffixes without allocating shortened strings - pass strings by reference to avoid copies on every recursive call 6 Match(str, pat): boolean - public wrapper starts MatchIdx with both indexes equal to 1 - value parameters accept literals and other string expressions - copy once at the interface, then recurse using references to those local copies 7 test program: - receive string and pattern as command-line arguments - print yes or no according to Match - quote arguments with apostrophes so the shell does not expand * or ? - abc / a?c -> yes; abc / a??c -> no; abc / ***a***c*** -> yes 2.11.4 Recursion with lists 1 recursive list structure: - either empty, or a first node followed by another list sum: - empty list -> 0 - otherwise p^.data + ItemListSum(p^.next) - recursion uses stack space proportional to list length; deep lists can overflow it 2 dispose recursively: - empty list -> return - dispose the tail first, then dispose the current node - preserves access to next until the recursive call has used it 3 sorted insertion: - empty list or first value > n: prepend n - otherwise recursively insert into p^.next - receive p as a var parameter so insertion can replace the incoming link - identical code handles the whole list and any tail - short-circuit evaluation protects p^.data when p = nil 2.11.5 Working with a binary search tree 1 recursive structure makes tree operations natural to express 2 TreeNode: - data: longint; left and right: pointers to TreeNode - root := nil represents an empty tree sum: - empty tree -> 0 - otherwise SumTree(left) + data + SumTree(right) insertion: - pass the root pointer by reference - empty subtree: allocate a node and initialize both children to nil - smaller value: recurse left; larger: recurse right - duplicate value: report ok := false; successful insertion sets ok := true membership: - same branch choices; nil means absent, equality means present - a function suits this operation because it does not change the tree shared search operation: - TreeNodePos = ^TreeNodePtr - SearchTree(var p, val) returns the address of the link where val is or should be - return @p when p = nil or p^.data = val; otherwise recurse into the appropriate child - var p ensures @p denotes the caller's actual root/child link using the returned position: - pos^ <> nil -> value already exists - pos^ = nil -> insert through new(pos^) and initialize pos^^ - shared search removes duplicated traversal logic - these procedures do not prevent imbalance from unfavorable insertion order 3 further tree study in the source: - Wirth: Algorithms and Data Structures - Cormen, Leiserson, and Rivest: broader algorithm coverage - Knuth, volume 3: sorting and searching structures 4 nonrecursive exercise: - search needs only a loop following the appropriate child - full traversal must remember ancestors and unfinished work - an explicit stack can store the node and its processing state, as in Hanoi 5 full iterative traversal is a harder exercise and is revisited with C 2.12 More about program layout 1 source code is read by people: - unclear layout makes both maintenance and writing the program harder 2 consistent formatting rules make structure visible 2.12.1 ASCII and English 1 the book's source-code convention uses English names and comments 2 readers work in different environments: - operating systems, editors, encodings, display sizes, and languages differ - avoid assuming that a program will never leave its original setting 3 portability assumptions adopted by the book: - ASCII characters, English text, and an 80-column display 4 ASCII-only source convention: - plain Latin letters, digits, punctuation, underscore, and whitespace - excludes national alphabets, accented letters, and typographic punctuation - the author applies this convention even to comments and literals - compiler acceptance alone does not establish portability across the intended tools 5 common professional language: - the author requires English throughout source text - transliteration does not solve the problem of shared understanding 6 a shared specialist language serves the same purpose across national boundaries 7 English provides access to specifications, library documentation, protocols, and technical literature 8 three source conventions: - identifiers: English words or abbreviations - comments: English - user interface: English or designed for translation into multiple languages 9 develop enough English to read technical material and write understandable program text 10 localization: - keep translated messages in external resource files - load and display them as data - source-language conventions do not restrict which languages the program can process 11 Free Pascal has facilities for internationalized programs - omitted from this introduction; the book later demonstrates the topic with C 2.12.2 Structural indentation styles 1 nested code shifts right; matching boundaries align - book's allowed choices: two, three, or four spaces, or one tab - choose once and use it throughout the program 2 tab character: - ASCII 9; advances to the next tab stop - with default width 8, one-based stops are 9, 17, 25, ... - one tab does not always advance exactly eight positions 3 terminal tab stops can be configured with tabs - the book recommends default stops so the same file displays consistently 4 editor convention prescribed here: - keep literal spaces and tabs distinct; avoid automatic interchange - tab width 8 should match ordinary terminal display - choose spaces if an eight-column structural indent is too wide 5 three begin/end layouts: - begin on its own line, aligned with the controlling statement - begin on the statement's line; end aligned with the statement's start - begin/end both shifted right, with body shifted farther - the book's Pascal examples use the first 6 subprogram and main-body boundaries: - outer begin and end each occupy their own line - the book places them at the left margin 2.12.3 if with an else branch 1 if/else layout: - put each branch's statement on a separate indented line - align else with its if - for compound branches, apply the selected begin/end convention consistently - with same-line begin, either end else begin or a separate else begin is possible mixed simple/compound branches: - an optional convention encloses both branches when either needs begin/end - preserves visual symmetry even if one branch contains only one statement 2.12.4 Layout of case statements 1 case has end without its own begin: - branch bodies may nevertheless require begin/end 2 case labels: - either align with case or indent one level - choose consistently for the whole program 3 same-line begin in branch bodies: - the book recommends indenting labels 4 begin on a new line without additional delimiter indentation: - the book again recommends indenting labels 5 begin/end with their own extra indentation: - unindented case labels avoid excessive horizontal displacement 2.12.5 Chains of mutually exclusive if statements 1 case limitations: - selects by equality with ordinal constants - arbitrary conditions and string comparisons need if / else if / ... / else - mechanically increasing indentation at every else would waste width and obscure equal-rank alternatives 2 an else-if chain generalizes case: - its alternatives should appear at the same indentation level 3 treat else if as one layout unit: - same line, or consecutive lines beginning in the same column - apply the chosen begin/end placement consistently - this exception applies only when else consists of a single if - other nested branches use the ordinary indentation rules 2.12.6 Labels and goto 1 goto uses ordinary statement layout - label placement needs an explicit convention 2 a label marks a statement, including an empty statement - choose its indentation and whether its statement shares the line 3 common layout: - label aligned with the containing structure's boundary - labeled statement on the next line, with ordinary body indentation - a nested label need not be at the file's left margin - a same-line statement can work when a short label leaves normal alignment intact 4 alternative: - indent the label together with its statement - either keep both on one line or put the statement below 5 outdented labels are easier to recognize as special control-flow destinations 2.12.7 Maximum source width 1 80-column convention: - historical continuity from punched cards through printers and terminals 2 line length affects readability: - very narrow lines leave insufficient room for structural indentation - very long lines require more horizontal eye movement 3 use wide displays for larger text or multiple source windows - extra display width need not become extra source-line width 4 narrow tools still matter: - terminal editors, remote sessions, and source comparison tools 5 printing long source lines: - shrinking, clipping, or automatic wrapping can all reduce readability 6 book's width rule: - up to 75 columns: preferred - 76–79: allowed but undesirable - 80 or more: excluded by the chosen convention - margin leaves space for numbering and avoids ambiguity at the display edge 7 some project conventions allow exceptions for message literals: - keeping a message intact makes searching for its source easier 8 exceptions require judgment: - keep significant program behavior visible within the normal width - the author recommends avoiding exceptions by simplifying expressions, messages, or nesting 9 height also matters: - aim for subprograms readable within roughly 24–25 lines - modest exceptions are possible; do not rely on an unusually tall display 2.12.8 Breaking a long line 1 common problem: a long if, while, or case header 2 first simplify the condition: - replace a long chain of punctuation comparisons with IsPunctuation(a) - a well-chosen helper can express the intent and shorten the header 3 some multiline headers remain necessary - establish a readable convention for them 4 multiline control header: - break at top-level operations, usually and or or - indent continuation lines one level - use a compound body even when it contains one statement - put begin on its own line to separate the condition visually from the body - with separately indented delimiters, moving then/do/of to its own line can mark that boundary 5 same-line-begin alternative: - place the closing header keyword and begin together on a separate line - or use the ordinary standalone-begin exception for multiline headers 6 choose conventions for other long statements too - prevent ad hoc, inconsistent wrapping within one program 7 long assignment: - first try breaking after := and indenting the right-hand expression - break further at low-precedence operations - extra nesting in subexpressions gets additional indentation - several short terms may share a continuation line 8 short left-hand side: - continuation may use one extra indent or align with the first expression term - exact alignment is clearer but depends on the left-hand expression's length - the book avoids mixing tabs and spaces to obtain that alignment 9 consistent alternative: always break after := when an assignment needs wrapping long calls: - break between arguments, after commas - continuation lines use one indent or align with the first argument 10 another call layout: - procedure name and opening parenthesis form the first line - arguments occupy indented lines; closing parenthesis returns to the original column long declarations: - reconsider a subprogram needing many parameters before merely wrapping it - too many arguments may indicate a poor decomposition 11 parameter names are local: - shorten them when their meaning remains clear - explain necessary details in the subprogram's interface comment 12 long subprogram header: - procedure/function may occupy a separate unindented line - a function's result type can move to a separate line near the right end of the parameter list - otherwise wrap between parameter groups, preferably after semicolons - use continuation indentation, aligned groups, or a fully multiline parenthesized list 13 long string literal: - avoid a literal continued across physical lines with an escaped newline - concatenating shorter literals is possible, but makes searching for the complete message harder 14 first try shortening the message without losing its meaning 15 named string constant: - move a long message to a const declaration with less indentation - use its short name at the deeply nested call site 2.12.9 Delimiters and optional spaces 1 delimiter: - a token recognized independently of surrounding whitespace - a+b and a + b mean the same thing - and is different: aandb is one identifier, not a and b 2 optional spaces should support readability consistently 3 readers already have habits from ordinary prose and mathematics 4 use those habits when a program symbol serves a comparable role 5 punctuation-like separators: - no space before; a space after unless the line ends 6 Pascal commas, semicolons, and declaration colons: - follow that separator rule - examples: a, b; n: integer 7 dot depends on its role: - end. has no intervening space - record selection list.first has no space on either side 8 assignment := is one token: - surround it with spaces 9 ! and ? have no operator role in the Pascal subset discussed 10 the same character may have a different role in another language: - C conditional colon separates expression branches - Lisp comma can act as an unquote operator - spacing should reflect that role 11 choose spacing by meaning, not merely by the printed character 12 no padding inside parentheses or brackets: - MyProcedure(a, b[idx + 5], c) 13 outside-parenthesis spacing in prose depends on adjacent punctuation 14 Pascal parentheses resemble mathematical notation: - no space between a subprogram name and its opening parenthesis - no space between a symbolic unary operator and its operand - use spaces after control keywords and before then/do/of - keep a closing parenthesis attached to following comma or semicolon 15 C control statements require parentheses: - style guides differ over spacing before them - the source favors the conventional space after if/while/for 16 common operator rule: - spaces on both sides of binary operators - symbolic unary operators remain attached to their operands - record-field dot follows its own selection notation - other consistent precedence-based conventions also exist 17 trailing whitespace: - spaces or tabs immediately before a newline are invisible clutter - remove them, especially when maintaining versioned source 18 splitting a statement can accidentally leave its former separating space at the line end 19 check periodically: - Vim search: /\s$ - shell: grep '\s$' *.pas 2.12.10 Choosing identifiers 1 name according to role and scope: - short local names are useful when context makes the meaning immediate - i for a loop counter; p/ptr for a pointer; str, tmp, res, sum for familiar local roles - conventional physical quantities may use established letters 2 globally visible names need more context: - a bare t could conflict between temperature and time subsystems 3 test a public name for ambiguity: - GetTemperature could mean reading a sensor, file, or cached value - ScanTemperatureSensor states the action more specifically - distinguish the cabin sensor from other sensors where necessary 4 length also has a cost: - local names usually need only a letter, abbreviation, or one/two words - public names commonly need two/three words - remove redundant words when the remaining name stays unambiguous 5 avoid excessively long identifiers with five or more words 2.12.11 Letter case 1 Pascal is case-insensitive: - alternate capitalization does not create distinct identifiers or keywords 2 book's default: lowercase keywords - uppercase outer BEGIN/END is a known optional convention 3 other capitalization conventions are possible - choose explicit rules and follow them throughout 4 all-uppercase keywords and arbitrary mixed case make reading harder 5 identifier convention: - short local names and abbreviations: lowercase - multiple words: capitalized word starts, as in UserListItem - choose a consistent rule for single-word names 2.12.12 Declaration sections 1 modern Pascal implementations permit repeated declaration sections and flexible ordering 2 separate program-main variables from shared globals: - declare main-only variables/types immediately before the main begin, after subprograms - declare shared variables before the subprograms that need them - top-level placement alone does not mean a variable should serve as shared state 3 labels belong to the body in which they are used: - subprogram labels are declared locally - main-program labels belong immediately before the main body 2.12.13 Keep the rules continuously 1 maintain readable formatting from the first source line onward 2 'fix the layout later' postpones help needed while writing the program 3 code is repeatedly read during development: - clear indentation reduces the effort of reconstructing its structure - neglecting layout creates errors and wastes debugging time 4 consistent practice makes formatting habitual 5 the author's rule: restore readability before judging or extending the program 6 repair indentation immediately after moving code or adding/removing control structures - learn the editor's block-indent and block-unindent commands - adjust the whole selected block instead of inserting spaces individually 2.13 Testing and debugging 2.13.1 Debugging in a programmer's work 1 debugging: - locating and correcting errors in a program - substantial newly written programs usually require it 2 debugging maxims: - execution follows the written program, not the author's intentions - a successful run does not establish correctness - a visible failure provides evidence that can help locate a hidden defect - expect mistakes, including in places that initially seem beyond suspicion 3 incorrect behavior calls for investigating what the program actually says 4 successful compilation is only one step: - the resulting program must still solve the requested problem 5 'finished except for debugging' can mean much work remains 6 beginners may find this discouraging after the effort of writing the first version 7 programming includes more than typing code: - debugging may require more time and skill than initial implementation 8 reserve time and energy for failures discovered during execution 9 plan for a working result, including debugging: - the author's analogy: reaching the summit is only part of returning safely 10 test individual parts as they are written: - recent, small pieces are easier to investigate - reduce dependencies so subprograms can be checked independently - consider how to observe and debug the code while designing it 11 localize the defect using evidence: - intuition is a hypothesis, not proof that one particular fragment is wrong 12 observe execution: - use diagnostic output and debugger stepping - repeatedly rereading familiar code can reproduce the same mistaken assumptions 13 rewriting without understanding the failure can reproduce the defect 14 investigate your own code before attributing a failure to the compiler or operating system 15 take responsibility for investigation: - a broad 'why does it not work?' provides little information - gather a reproducible failure and observations before seeking outside diagnosis 16 debugging can become an engaging problem-solving activity - treat each observation as evidence narrowing the search 2.13.2 Tests 1 running a program and observing a failure begins testing 2 ad hoc manual trials are difficult to reproduce after changes 3 retyping the same inputs wastes effort and introduces variation 4 reuse input: - redirect standard input or pipe data from echo - shell history and Ctrl-R can repeat simple trials 5 persistent test suites: - store cases in files instead of relying only on shell history 6 test = enough information to execute and judge a case: - input, invocation/setup, expected result, and a way to compare actual behavior - may use data files, a subprogram harness, or a separate test-driving program 7 example: reduce a fraction - input: integer numerator and denominator - output: equivalent numerator and denominator in lowest terms 8 positive examples are insufficient: - 25/15 -> 5/3; 7/12 -> 7/12; 100/2000 -> 1/20 - negative operands expose assumptions hidden by those cases - a correction can break cases that previously worked 9 echo pipelines improve repeatability - manually finding commands and inspecting every result still costs time 10 four-value test record: - input numerator, input denominator, expected numerator, expected denominator - a script can execute and compare all records automatically 11 shell test driver: - read a b c d obtains one case at a time - pipe a and b into ./frcancel; capture its output in res - compare res with the expected c and d - print input, expected output, and actual output on mismatch - a here-document supplies the cases to the loop 12 automated suite: - add a case by adding a data record - one command runs all cases; the example reports only failures - tests may require effort to create but should be easy to execute 13 regression testing: - retain tests and rerun them after meaningful changes - passing old cases provides evidence against introducing old or related failures 14 simplify a failing test: - keep the original and create smaller variants - find the smallest case that still exposes the failure - compare failing and passing variants to isolate relevant factors 15 test first: - write a failing test before the implementation or correction - change the code until it and the previous tests pass 16 test first often targets subprograms and subsystems: - coverage supports safer changes - an unnoticed regression indicates a missing or inadequate test 17 test first is an available approach, not a requirement for every task 2.13.3 Diagnostic output 1 when tests expose a failure, inspect what execution actually does 2 add temporary diagnostic statements: - did execution reach this point? - what value did this variable acquire? 3 make diagnostics recognizable: - prefix with DEBUG, XXX, or another distinctive marker - finish messages with newlines - buffering can otherwise hide a message, especially before a crash 4 output buffering: - output may wait until the buffer fills, the program exits, or it is explicitly flushed - flush(output) forces pending standard output out - terminal output has additional newline/input-related flushing behavior in the model described 5 debug statements follow the same structural indentation rules as ordinary code 6 keep reusable diagnostics under conditional compilation: - {$DEFINE DEBUG} defines a compilation symbol - {$IFDEF DEBUG} ... {$ENDIF} includes the enclosed code only when it is defined - alternatively compile with fpc -dDEBUG myprog.pas - enables/disables diagnostics without editing the source each time 7 complex structures need purposeful diagnostic routines: - print the state of a list, tree, or table clearly - conditionally compile the entire diagnostic routine if appropriate 2.13.4 The gdb debugger 1 debugger: - pauses execution, steps through code, and shows current values 2 debug information connects executable code with source concepts: - variable/subprogram names, source files, and source positions - without it, the debugger mostly sees machine-level information 3 compile the example with fpc -g myprog.pas - executable grows because it contains debugging information 4 gdb has its own command interpreter: - command editing, completion, and history - can launch a program, attach to a process, or analyze a crash dump 5 start gdb: - gdb ./myprog - gdb --args ./myprog abra schwabra kadabra supplies program arguments 6 start versus run: - start begins execution and stops at the main entry - run executes until termination, a breakpoint, or another stopping event - Ctrl-C interrupts the debugged program for inspection - a crash under the debugger exposes the current execution state 7 single-step commands: - next: advance at source level, running calls without entering them - step: enter called subprograms - Enter repeats the previous stepping command 8 list: - display source around the current position or another specified location - repeated listing allows inspection of a larger region 9 breakpoints: - break accepts a source location or subprogram name - stop before executing the corresponding operation - continue / cont resumes a paused program until the next stopping event 10 Pascal name handling: - the compiler/debugger combination used by the author exposes subprogram names in uppercase - use those names when setting breakpoints or referring to routines 11 breakpoint controls: - disable 3 / enable 3 toggles breakpoint 3 - ignore 3 550 skips its next 550 hits - cond 5 I < 100 restricts breakpoint 5 to that condition - info breakpoints shows the current set and their properties 12 variable inspection and modification: - inspect displays a value - set var x:=50 changes x in the suspended program 13 backtrace / bt: - shows active calls, arguments, and where each call originated - helps reconstruct how execution reached the current routine 14 frame selection: - frame 1 selects the caller's context in the example - subsequent source listing and variable inspection use that frame 15 call: - invoke a program subroutine from the debugger - Pascal-specific value support can be limited; a string variable may work where a literal does not 16 quit or Ctrl-D exits; help describes debugger commands 17 attach to an existing process: - gdb ./myprogram 2765 in the source's example - executable supplies symbols; process supplies the live state - inspect calls/values, set breakpoints, and resume as needed 18 core-file analysis: - revisited with C - the Free Pascal runtime described handles many failures itself, so those failures do not produce an ordinary core dump 2.14 Modules and separate compilation 1 splitting a growing program into files: - makes navigation and focused work easier - supports reuse and correction of shared components 2 textual inclusion: - {$I myfile.pas} inserts that file's contents at the directive 3 inclusion alone leaves one translation unit: - all included text is compiled together - repeated whole-program compilation wastes time - large global name sets increase collision risks 4 separate compilation: - divide code into modules, usually source files with related subprograms - compile each independently to object code - linker combines object files into the executable 5 module visibility: - export names clients need; hide internal names - different modules can reuse private names without exposing a conflict to clients 2.14.1 Pascal units 1 main module versus unit: - main program uses program; other modules begin with unit myunit; - uses myunit imports its interface - the main program's uses follows its header and lists multiple units with commas - follow the filename convention mymodule.pp for unit mymodule 2 interface section: - exported constants, types, variables, and subprogram headers - subprogram bodies do not belong here 3 implementation section: - definitions of exported subprograms - private helpers, types, constants, and variables 4 interface is a contract: - document every exported facility and the rules for using it - changing existing interface behavior can break clients 5 implementation is hidden from client use: - may be changed while preserving the contract - internal design details need not enter user-facing interface documentation 6 limit exported names: - lowers collision risk as modules are reused in larger programs 7 private visibility also prevents accidental misuse: - clients cannot directly call hidden helpers or mutate hidden variables 8 encapsulation: - hide implementation details behind a stable, functioning interface 9 unit ends with end. - an optional begin ... end. initialization section runs before the main program - useful when unit state requires initialization 10 lngtree example: - export TreeNode, TreeNodePtr, AddToTree, and IsInTree - keep TreeNodePos and SearchTree private in implementation client: - uses lngtree; initialize root := nil - '+' requests insertion; '?' requests membership testing compilation: - fpc unitdemo.pas compiles required units automatically - lngtree.pp produces lngtree.ppu and lngtree.o - unchanged compiled units can be reused; changed source is rebuilt - fpc lngtree.pp also compiles the unit directly 2.14.2 Units using other units 1 implementation dependency: - put uses immediately after implementation - imported facilities become available to internal code 2 interface dependency: - an exported declaration may need another unit's type or constant - examples: parameter/result type, array bound, or exported record-based type 3 put such uses immediately after interface - interface dependencies must not form a cycle 4 avoid unnecessary cross-dependencies: - where reciprocal use is needed, keep it in implementation sections when possible - interface dependencies expose more coupling to clients 2.14.3 A module as an architectural unit 1 module boundaries should follow deliberate rules 2 one module's facilities should be logically related: - larger programs need a comprehensible division into subsystems 3 responsibility test: - explain what the module/subsystem does in one phrase - two unrelated responsibilities suggest splitting the module 4 public name prefixes: - a shared subsystem prefix helps distinguish exported identifiers - examples: ComplexAddition, ComplexMultiplication, ComplexRealPart 2.14.4 Reducing coupling 1 coupling = dependence between modules - weaker dependence generally makes modules easier to reuse and change 2 kinds of coupling: - one-way versus mutual dependency - calls: using another module's operations - variables: accessing its global state - data: multiple modules sharing the same in-memory structure - returning a pointer can expose shared data even without exporting a global variable 3 preferred design: - one-way dependencies through operations - avoid shared globals - each allocated structure has one identifiable owner responsible for its lifetime 4 practical exceptions: - clearly distinct subsystems can reasonably need reciprocal calls - merging them merely to remove the cycle may make responsibilities less clear 5 exported mutable globals spread risk: - any client can change them - failure diagnosis may require investigating the entire program - state private to one module limits the area that can modify it 6 representation and invariant problems: - exposed Cartesian coordinates make changing internal storage to polar coordinates difficult - operation-based interfaces can preserve client behavior through such changes - related state values must change together to maintain consistency - direct external writes bypass that control 7 dynamic shared data creates lifetime hazards: - one module can free a structure while another retains its address - assign exactly one owner to each dynamic structure - the owner may be a module, subsystem, or containing structure 8 ownership transfer: - a creator may hand a structure to its caller and retain no references - responsibility then belongs to the new owner borrowing: - a subroutine called by the owner may use the structure during the call - it must not assume the structure survives afterward or retain pointers into it 9 ownership is a design convention in this Pascal model: - document it when the code does not make it clear - especially document transfers of ownership 10 coupling rules: - avoid mutual dependencies when doing so is straightforward - avoid global variables unless their benefit justifies the cost - minimize shared data and preserve one clear owner whenever sharing is necessary 3. Processor capabilities and assembly language 1 assembly in ordinary software: - most code is written in high-level languages, including C - kernels and microcontroller firmware still contain small assembly parts 2 assembly remains useful when hardware access or severe resource limits require it - example: ATtiny4 has 16 bytes of RAM and 512 bytes for program code - such constraints are exceptional, even among microcontrollers 3 main reason to study assembly: understand what high-level operations cost - a scalar assignment can take one instruction - copying a large array or a complex object can require many instructions - identical source notation does not imply identical work 4 professional understanding should connect all levels of the computer - electronics, instructions, operating system, application programs - the machine contains mechanisms designed by people, not unexplained magic 5 learning one instruction set teaches the way to reason about other processors - concrete mnemonics change - understanding execution and data representation carries over 6 book uses 32-bit i386 instructions under Unix - x86_64 processors can execute compatible 32-bit programs - only a useful subset of the instruction set is needed here 7 32-bit examples expose the complete stack frame - parameters, return address, local variables - register-based parameter passing in x86_64 hides part of this arrangement 8 NASM uses Intel syntax - Intel: mov eax, [a+edx] - AT&T: movl a(%edx), %eax - same operation, different operand notation and ordering - NASM and FASM support Intel syntax; this book chooses NASM 3.1 Introduction 1 review instruction execution and the distinction between assembler and assembly language 2 before systematic instruction study: - understand the execution environment - review the processor family's history - assemble and run a small program 3.1.1 Von Neumann architecture 1-2 computer = CPU + RAM RAM: - linear, uniform memory consisting of equally sized locations - each location has its own address - CPU can read from / write to locations directly program: - sequence of machine instructions stored in RAM - RAM itself does not distinguish code from data binary representation is customary, but separate from these architectural principles 3 programs can be treated as data - one program can process another program - self-modifying code is possible in principle; modern protection restricts it 4 general-purpose registers: temporary storage for calculations - much faster to access than RAM, but much smaller total capacity - hold current operands and intermediate results - completed results can be moved to RAM to free registers 5 special-purpose registers include the instruction pointer - stores address of the next machine instruction to execute 6-7 CPU execution cycle: - fetch instruction using the instruction pointer - increase instruction pointer by the instruction's length - decode and execute instruction - repeat CPU follows instructions; it does not understand the program's purpose control is at the location currently addressed by the instruction pointer 8 branches and loops explicitly replace the instruction pointer - the new address replaces the already advanced sequential address 9 jumps: - unconditional: always replace instruction pointer - conditional: replace it only when the tested condition holds - otherwise execution continues with the next instruction 10 subroutine call: - save the already advanced instruction pointer as return address - jump to the subroutine - return restores that address, continuing after the call 11 transfer of control = explicitly changing the instruction pointer 3.1.2 Programming under multitasking operating systems 1-2 Unix runs several tasks concurrently - assembly exposes restrictions also present for other languages - reliable multitasking needs hardware support 3 memory protection: - prevents a task from damaging another task or the OS - a program may access only memory assigned to it 4 CPU modes: - privileged / supervisor mode: all instructions available - user mode: privileged instructions forbidden privileged operations include: - direct device access - configuring memory protection - other actions affecting the whole system user task: - transforms data in its assigned memory - requests outside services through system calls - even termination requires OS work: release memory and stop scheduling return to privileged mode also transfers control to the OS 5 physical address = number of a real memory location - embedding physical addresses would tie a program to one memory region - that region might already belong to another running task 6 virtual address = address used by a program - i386: 32 bits, 00000000 through ffffffff - some addresses are mapped to physical memory; others are not - MMU translates virtual addresses according to OS settings 7 each task can have its own address space - the same virtual address can refer to different physical memory in different tasks 8 book studies user-mode instructions in Unix's flat memory model - unused segmentation features are omitted - stud_io.inc temporarily supplies I/O and termination macros - macros expand into instruction sequences during assembly 3.1.3 History of the i386 platform 1 Intel family before x86: - 4004: 4-bit microprocessor, 1971 - 8008: 8-bit, 1972; 8080: 1974 - 8086: 16-bit, 1978; 8088: similar CPU with an 8-bit external data bus - IBM PC used 8088 - early compatibility sometimes meant reassembling the same source, not reusing machine code 2 8086, 8088 and 80186: - no memory protection or separation of privileged instructions - 20-bit address bus -> at most 1 MB directly addressable - 80186 improved speed, integrated support circuitry and added instructions 3 80286: - protected mode, segment-based virtual memory and four protection rings - 24-bit address bus -> 16 MB 4 80386 / i386: - 32-bit general-purpose registers and addresses - up to 4 GB directly addressable physical memory - paging supports multitasking - compatibility retains AX as the low 16 bits of EAX, similarly for other registers 5 x86 development and 64-bit extensions: - earlier successors mainly increased speed and added instructions - Intel Itanium used a different architecture with slow i386 emulation - AMD Opteron introduced the compatible x86_64 extension in 2003 - Intel subsequently adopted x86_64 too 6 author's performance aside: - more cores do not remove disk and bus bottlenecks - usefulness depends on whether the workload can occupy the cores 7 x86_64 processors can run the book's 32-bit instruction sequences - the OS and toolchain also need the corresponding execution support 3.1.4 First assembly program 1 learn instruction notation and assembler syntax together through a working example 2 goal: print Hello followed by a newline five times - printing and termination require the OS - macros initially hide the system-call details 3 stud_io.inc supplies the example's macros 4 choose the file's OS configuration: - Linux: enable %define STUD_IO_LINUX - FreeBSD: enable %define STUD_IO_FREEBSD instead - semicolon starts a comment; comment out the unused definition 5 assembly source contains: - mnemonics: processor instructions - directives: instructions to the assembler - macro calls: requests to substitute predefined source text %include "stud_io.inc": insert the macro definitions into the source - PRINT prints a literal string - PUTCHAR 10 prints a newline - FINISH terminates the task 6 include definitions before their first use - assembler reads source from top to bottom 7 global _start exports the entry-point label 8 sections in a file become memory regions when the OS loads the program - code, initialized data and information about uninitialized storage - OS also creates a stack 9 section names: - .text: machine code - .data: initialized data - .bss: reserved uninitialized storage - example needs only an explicit .text section 10 mov eax, 0: - first operand = destination; second = source - EAX becomes the loop counter, initially zero 11-12 _start is a label attached to that instruction 13 mov eax, 0 becomes five bytes: b8 00 00 00 00 - opcode selects operation and register - four following bytes encode the immediate value - labels let us refer to instruction addresses without writing numeric addresses 14 label = identifier associated with a number - usually an address, but can also be an ordinary constant - defining a label records the current address - using it as an operand substitutes its value 15 labels belong to assembly/linking information - CPU executes machine code containing numeric operands, not label names 16 NASM permits labels with or without a colon - usual style: colon on code labels; no colon on data labels 17 _start marks the entry point - loader starts execution there even though our program never jumps to it 18 again labels the loop's first operation - PRINT "Hello" expands the macro with the literal string as argument 19 PRINT is not a CPU instruction - expansion includes real instructions and a write system call - expansion depends on the chosen operating system 20 PUTCHAR 10 emits the newline - ordinary sequential instructions do not need their own labels 21 inc eax records one more printed line - increment instruction adds 1 22 cmp eax, 5 records comparison results in the flags register jl again: - repeat while the signed counter is less than 5 - jump reads the comparison flags 23 when EAX reaches 5, jl falls through - FINISH requests process termination 24 global _start makes entry-point information available to the linker 25 whole algorithm: - initialize counter - print line, increment counter, compare, repeat if needed - finish 26 save assembly source in hello5.asm 27 building has two stages: - assembler: source -> object module - linker: combine modules/libraries, resolve addresses -> executable 28 even a one-module program still needs linking - global causes _start information to be recorded in the object file 29 historical i386 build commands: - nasm -f elf hello5.asm -> hello5.o - ld hello5.o -o hello5 -> executable - on a 64-bit Linux toolchain: ld -m elf_i386 hello5.o -o hello5 - FreeBSD example uses -m elf_i386_fbsd - source and stud_io.inc must both be available uname -a helps identify the architecture - these instruction examples target x86, not ARM or another instruction set 30 -o selects output filename - ./hello5 runs the executable and prints five Hello lines 3.1.5 Macros in stud_io.inc 1 four macros: PRINT, PUTCHAR, GETCHAR and FINISH 2 PRINT: - accepts a literal string in single or double quotes - does not format arbitrary values 3 PUTCHAR: - prints one character - accepts character code, quoted character, byte register or memory operand - byte registers: AL/AH, BL/BH, CL/CH, DL/DH - larger registers are not valid arguments 4 GETCHAR: - no arguments; reads one character from standard input - character code returned in EAX, with upper bits zero - AL therefore contains the character - end of input -> EAX = -1 / ffffffff - Unix terminal EOF can be entered with Ctrl-D 5 FINISH: - terminates the process - optional numeric argument specifies the exit status 3.1.6 Formatting assembly programs 1 assembly formatting differs from Pascal formatting 2 one source line is the main syntactic unit - layout tradition comes partly from early Fortran 3 fixed-format Fortran reflected punched cards - separate columns for labels, continuation marker and statement text 4 assembly source describes a linear memory image - structural indentation does not represent nested statements here - detailed comments explain algorithms and control flow 5 align code in columns: - labels at the left - instructions after a tab; optional separate comment column - long labels can occupy their own line - one or two tab stops may be reserved for labels - an optional mnemonic column aligns operands too - unusually long macro names may require a layout exception 6 general source-formatting principles still apply 7 book's source convention: ASCII characters and English comments - comments remain essential even when writing them takes extra effort 8 keep source lines within 79 characters 9 use meaningful labels and sensible decomposition - subroutines, modules and subsystems matter in assembly too 3.2 Basic i386 instructions 1 basic user-mode instruction set: - registers, data movement, integer arithmetic and control flow - subroutines and floating-point arithmetic follow separately 2 privileged instructions are outside this introduction - ordinary user programs cannot execute them 3.2.1 Registers 1 register = CPU storage for a fixed number of bits - general-purpose, segment and special-purpose registers - register names identify hardware storage, not program variables 2 segment registers: CS, DS, SS, ES, FS, GS - OS initializes them for the book's flat-address-space examples - examples leave them unchanged 3 code/data/stack memory regions are not simply the hardware segments - Unix builds its memory organization using other protection mechanisms 4 32-bit general-purpose registers: - EAX, EBX, ECX, EDX, ESI, EDI, EBP, ESP - low 16 bits accessible as AX, BX, CX, DX, SI, DI, BP, SP - these names overlap the same physical storage 5 AX, BX, CX and DX also have byte parts - AL/BL/CL/DL: low byte - AH/BH/CH/DH: high byte of the low 16 bits - SI, DI, BP and SP have no byte-register names in i386 mode 6 EAX / AX: accumulator - implicit operand/result register for multiplication and division 7 EBX / BX: base - historical role does not prevent ordinary 32-bit use 8 ECX / CX / CL: counter - implicit count for several repeated operations and shifts 9 EDX / DX: data - upper product or dividend; division remainder 10 ESI and EDI: source and destination indices - implicit addresses used by string instructions 11 EBP: base pointer - normally anchors a subroutine's stack frame 12 ESP: stack pointer - addresses the current stack top - arithmetic instructions can use it, but its stack role must be preserved 13 special registers considered here: EIP and the flags register 14 EIP: address of next instruction - fetching an instruction advances it by that instruction's length 15 i386 instruction length varies from 1 to 15 bytes - optional prefixes are part of the instruction - encoding length cannot be inferred just from the mnemonic 16 flags are individual bits, not one ordinary numeric value - ZF: result is zero - CF: unsigned carry or borrow - SF: most significant result bit / sign - OF: signed overflow - DF: string direction; cld clears it, std sets it - PF: parity; AF: auxiliary carry - IF and TF concern interrupts/debugging; outside these examples arithmetic sets status flags; conditional jumps test them 17 EFLAGS is the 32-bit extension of FLAGS - this introduction mainly uses the older flag bits 3.2.2 Task memory and segments 1 registers hold temporary results; larger and longer-lived data belongs in RAM 2 instructions and data share the virtual address space - byte-sized locations; 32-bit addresses in these examples 3 memory protection assigns access rights to regions - readable, writable and executable are distinct properties - an address can exist without permitting every kind of access 4 principal task regions: code, data and stack - loader builds code/data from executable sections - initial Unix stack contains arguments and environment information - a segment may combine sections; some file sections are not loaded 5 code region: - executable and readable; ordinarily not writable - physical code pages can be shared by instances of the same program - immutable constants can share this region too 6 .text supplies the machine code - leading dot is part of the section name 7 data region: - readable and writable; ordinarily non-executable - .data stores explicit initial values in the executable - .bss records required storage size without storing all its bytes - dynamic allocation may enlarge data memory or create another region 8 historical Unix examples of requesting memory: - Linux brk changes the data-segment boundary - mmap creates a mapping; used for the FreeBSD example 9 stack region: - writable storage for return addresses and local variables - grows as needed within OS limits - initial contents depend on arguments and environment - created by the OS, without a corresponding stack-data section - executable-stack behavior depends on OS/version; book discusses older systems 3.2.3 Reserving memory 1 storage directives belong to NASM syntax, not the processor instruction set 2 assembling instructions creates a memory image of their machine-code bytes 3 the assembler can also construct an image of data - specify required storage and, when needed, initial contents 4 section selects which image subsequent source contributes to - .text: instructions; .data: initialized bytes; .bss: required storage size - may switch between sections repeatedly - linker combines section information into the executable 5 storage directives either reserve uninitialized storage or provide initial values - preceding label names the first byte's address 6-7 NASM size terminology preserves the older x86 convention - byte = 1 byte - word = 2 bytes - dword = 4 bytes - qword = 8 bytes - word in this syntax does not mean the i386 CPU's 32-bit machine word 8 reserve uninitialized elements: - resb N: N bytes - resw N: N two-byte words - resd N: N four-byte double words - string resb 20 -> 20 bytes - count resw 256 -> 512 bytes - x resd 1 -> 4 bytes, enough for a 32-bit integer or address 9 define initialized elements: - db, dw, dd: 1, 2, 4 bytes per value - comma-separated values determine the number of elements - fibon dw 1,1,2,3,5,8,13,21 -> 16 bytes 10 numeric literals: - hexadecimal: 2af3h, $2af3 or 0x2af3 - h/$ notation needs an initial digit: 0a21h, $0f9 - octal: suffix o or q; binary: suffix b 11 quoted characters stand for their codes - db '7' stores 55, the ASCII code for digit 7 - db accepts a whole string as consecutive bytes - single and double quotes are alternatives - split the data into adjacent arguments when both quote characters are needed 12 strings can also be supplied to dw/dd - packing/padding rules then need additional care 13 usual placement: - db/dw/dd initial values in .data - resb/resw/resd reservations in .bss - large .bss reservations increase memory needs without storing those bytes in the file 14 unchanging data can be placed in the code region - permits physical sharing between program instances - writing to that protected region causes a fault 15 assembler can accept instructions/directives in inappropriate sections - machine code in data remains data unless memory permits execution - reservations in .data waste file space - initialized values in .bss have nowhere to be stored - warnings should prompt correction, even when assembly continues 3.2.4 mov and operand kinds 1 mov illustrates copying, operand sizes and addressing 2 mov destination, source: - copies bits without converting their meaning - mov eax, ebx copies EBX to EAX 3 register operand: names a register immediate operand: value encoded directly in the instruction - mov ecx, 5 places the constant 5 in ECX 4 one mnemonic can describe different machine encodings - register-to-register and immediate-to-register mov differ in opcode/length 5 memory operand in NASM always uses square brackets - mov [count], eax stores EAX at address count - mov edx, [count] reads the value stored there - mov edx, count puts the address itself in EDX label without brackets is a number substituted by the assembler brackets request access to memory at that number 3.2.5 Indirect addressing and effective addresses 1 array traversal needs a different element address on each iteration 2 indirect addressing: - compute an address during execution - use the computed value to access memory 3 mov ebx, [eax]: read four bytes from the address held in EAX mov ebx, eax: copy the register value itself 4 fill 256 bytes with '@': - ECX = 256 remaining elements - EDI = array address; AL = '@' - store AL through [EDI] - increment EDI; decrement ECX - repeat with jnz until ECX becomes zero 5-6 example favors familiar instructions over minimizing registers - later size qualifiers allow storing an immediate byte directly - a different loop could combine position and count 7 effective address = address actually used by an instruction - may be fixed or computed as part of instruction execution 8 i386 address form: displacement + base register + index register * scale - scale = 1, 2, 4 or 8; terms may be omitted - [array+ebx+2*edi] combines all three terms 9 address expression has hardware limits - no three-register sum, register subtraction or arbitrary multiplication - ESP may be a base, but cannot be the scaled index 10 NASM can rearrange equivalent expressions - constant terms are combined at assembly time - [eax*5] becomes [eax+eax*4] - [eax+ebx*5] needs three register terms and is invalid 11 matrix example: 10 rows of 15 four-byte elements - row N starts at offset N*60 - with that offset in EAX and column in EBX: * [matrix+eax+4*ebx] addresses the element 12 lea destination, [address expression]: - computes the effective address and stores it in a register - performs no memory read - 16-bit destination keeps only the low 16 bits - lea eax, [1000+ebx+8*ecx] computes 1000+EBX+8*ECX 13 lea also performs useful ordinary arithmetic - multiplication by 3, 5 or 9 can use the addressing hardware - same restrictions apply even when the result is not an address 3.2.6 Operand sizes and combinations 1 operand kinds: immediate, register and memory 2 mov destination must be writable storage - immediate destination is impossible - two explicit memory operands are not supported - copy memory through a register: mov eax,[x]; mov [y],eax 3 valid mov combinations: - register -> register; register -> memory; memory -> register - immediate -> register; immediate -> memory both operands describe the same data width - a register normally determines the width - AL -> CX is not a valid plain mov memory plus immediate needs an explicit size when otherwise ambiguous - mov dword [x], 25 stores four bytes - byte / word / dword mean 1 / 2 / 4 bytes mnemonic alone does not determine the machine encoding - mov eax,17 and mov eax,x both use immediate source values 3.2.7 Integer addition and subtraction 1 add / sub destination, source: - read destination, add/subtract source, write result to destination - operand combinations follow mov rules - memory plus immediate needs a size: add dword [x], 12 2 signed and unsigned addition/subtraction use the same bit operations - programmer supplies the interpretation 3 ZF = 1 when the result is zero - useful for both signed and unsigned arithmetic 4 signed interpretation: - SF copies the result's most significant bit - OF reports signed overflow - overflow can make SF differ from the mathematical result's sign 5 unsigned interpretation: - CF reports a carry beyond the width or a borrow in subtraction 6 CPU sets flags without knowing which interpretation the programmer intends - choose the flags appropriate to the data 7 adc / sbb include the old carry flag - adc: destination + source + CF - sbb: destination - source - CF - then update flags from the new result 8 multiword example: EDX:EAX and EBX:ECX - add eax,ecx; adc edx,ebx -> propagate carry into upper half - sub eax,ecx; sbb edx,ebx -> propagate borrow inc / dec add or subtract 1 - set ZF/SF/OF but preserve CF - memory operand needs its size specified 9 neg replaces its operand with 0 - operand - updates arithmetic flags, including CF 10 cmp performs subtraction only for its flags - does not store the subtraction result - usually followed by a conditional jump - first operand still cannot be immediate 3.2.8 Integer multiplication and division 1 multiplication/division require more complicated hardware than addition 2 signed and unsigned versions need different instructions 3 multiplication can require twice the operand width division: - accepts a double-width dividend - produces both quotient and remainder 4 one-operand forms use implicit accumulator registers - explicit operand supplies multiplier/divisor - explicit operand must be register or memory, not an immediate - imul also has other forms, outside this discussion 5 mul = unsigned; imul = signed - byte operand: AL * operand -> AX - word operand: AX * operand -> DX:AX - dword operand: EAX * operand -> EDX:EAX 6 multiplication sets CF and OF together - clear when the low half contains the complete result - unsigned: upper half is zero - signed: upper half is sign extension of the lower half - other flags are undefined; do not test them for a result 7 div = unsigned; idiv = signed - byte divisor: AX -> quotient AL, remainder AH - word divisor: DX:AX -> quotient AX, remainder DX - dword divisor: EDX:EAX -> quotient EAX, remainder EDX - quotient rounds toward zero - nonzero signed remainder has the dividend's sign - absolute remainder is smaller than absolute divisor - arithmetic flags are undefined afterwards 8 division exception: - divisor is zero, or quotient does not fit its destination - OS receives control and normally terminates the erroneous task - clearing/preparing the upper dividend half is essential 9 signed extension before division: - cbw: AL -> AX - cwd: AX -> DX:AX - cwde: AX -> EAX - cdq: EAX -> EDX:EAX - added bits copy the original sign bit - instructions have fixed implicit operands 10 unsigned extension: clear AH, DX or EDX as appropriate 3.2.9 Conditional and unconditional jumps 1 jump explicitly changes EIP - conditional jump falls through when its condition is false 2 jump forms: - far: changes hardware segment; unused in these flat-model examples - near: arbitrary location within current segment - short: signed byte displacement, -128 through +127 from following instruction - short / near qualifiers select the intended form - default selection depends on assembler/version 3 author prefers explicitly chosen encodings over assembler optimization 4 jmp targets: - jmp cycle: direct jump to label - jmp eax: address held in EAX - jmp [addr]: address read from memory at addr - jmp [eax]: address read from memory at the address held in EAX 5 direct relative jump encoding stores target minus following-instruction address - indirect jump instead takes the absolute destination from register/memory 6 short jump can reduce code size - macros may expand to more bytes than expected - out-of-range short displacement is an assembly error 7 conditional jumps test flags or, for some instructions, a register 8 ordinary conditional jumps take a direct target - register/memory indirect targets are not supported - conditional indirect transfer: invert condition to skip an ordinary indirect jmp - older x86/NASM defaults explain the book's emphasis on short versus near 9 conditional direct jumps also encode relative displacements 10 single-flag jumps: - jz/jnz: ZF set/clear - js/jns: SF set/clear - jc/jnc: CF set/clear - jo/jno: OF set/clear - jp/jnp: PF set/clear 11 cmp eax,ebx followed by jz branches when the two values are equal 12 ordering needs more than the zero flag - cmp a,b sets flags from a-b 13 signed a < b: SF differs from OF - jl / jnge test this combination - testing SF alone fails when subtraction overflows 14 unsigned a < b: subtraction needs a borrow - CF = 1; jb / jnae / jc are equivalent 15 greater-than and less-than-or-equal also need ZF 16 comparison jump families: - equal: je/jz; unequal: jne/jnz - signed: jl, jle, jg, jge - unsigned: jb, jbe, ja, jae - signed <=: SF != OF or ZF = 1 - signed >: SF = OF and ZF = 0 - unsigned <=: CF = 1 or ZF = 1 - unsigned >: CF = 0 and ZF = 0 - corresponding negated mnemonics express the complementary condition 3.2.10 Building branches and loops 1 usually jump when the source-level condition is false - while a=0: compare with zero, then jnz to exit 2 while loop: - condition -> jump to exit if false - body -> unconditional jump back to condition if/else: - condition -> jump to else if false - then branch -> jump over else to end - else branch -> end true case naturally falls through into its body 3 negated jump names can make the source condition clearer - jnb, jna, jnge, jnle emphasize skipping when the condition fails 3.2.11 ECX and counted loops 1 ECX has dedicated counter instructions 2 loop target: - decrement ECX - jump if the new value is nonzero - target must fit a short displacement 3 sum 1000 dwords: - ECX = 1000; ESI = array; EAX = 0 - add [ESI] to EAX; advance ESI by 4; loop 4 dec register / jnz can implement a similar countdown - loop has a smaller encoding, but is not necessarily faster - loop preserves flags; dec changes arithmetic flags except CF 5 one-register array traversal: - start ECX at 1000 - add [array+4*ecx-4] - visits indices 999 down to 0 - assembler combines array-4 into one constant displacement 6 jecxz / jcxz test ECX / CX directly, without flags - short jumps only - guard a counted loop when initial count may be zero - otherwise first loop decrement wraps zero to ffffffff loope/loopz: - decrement ECX, then jump if ECX != 0 and ZF = 1 loopne/loopnz: - decrement ECX, then jump if ECX != 0 and ZF = 0 - decrement happens regardless of ZF 3.2.12 Bitwise operations 1 register/memory contents can represent independent bits instead of integers 2 and / or / xor combine corresponding bits - result replaces first operand; ordinary two-operand restrictions apply - set ZF/SF/PF from result; clear CF/OF not inverts every bit of its one operand - unlike and/or/xor, not leaves flags unchanged 3 useful identities: - xor eax,eax clears EAX with a compact instruction - not of zero produces all ones - unsigned x AND (2^n-1) = x modulo 2^n - and eax,3 -> remainder modulo 4 4 test performs AND for flags without storing a result - test eax,eax checks for zero - test value,mask checks whether any masked bit is set 5 shl / shr destination, count: - count is immediate or CL; no other register may supply it - i386 uses only the low five count bits - memory destination needs a size qualifier 6 logical one-bit shift: - shl: highest bit -> CF; insert zero at low end - shr: lowest bit -> CF; insert zero at high end 7 shl / sal multiply by powers of two, subject to finite-width overflow shr divides unsigned values by powers of two sar copies the sign bit while shifting right - rounds negative results toward minus infinity - therefore differs from idiv's rounding toward zero for negative odd values 8 shifts can avoid accumulator setup and expensive multiplication/division - valid substitution still depends on signedness and rounding 9 other bit instructions mentioned: - shld/shrd: double-width shifts - rol/ror: rotations; rcl/rcr: rotate through carry - bt/bts/btr/btc: test or alter a bit - bsf/bsr: locate a set bit 10 bitset represents a subset of a finite universe - one bit per possible element: 1 = present, 0 = absent - 512 possible elements need 512 bits / 64 bytes 11 store the set as 16 dwords - object X belongs to word X/32, bit X mod 32 - X >> 5 gives word index; X AND 31 gives bit index - object 37 -> word 1, bit 5; object 510 -> word 15, bit 30 packing index results for 0 <= X < 512: - shl ebx,3; shr bl,3 leaves word index in BH and bit index in BL clear the set: - EAX = 0; ECX = 16 - store EAX at [set512+4*ecx-4], repeat with loop 12 insert X: - CL = X AND 31 - mask = 1 << CL - EDX = X >> 5 - OR mask into [set512+4*edx] remove X: - invert the mask; AND it into the same word test membership: - TEST the word with the one-bit mask - ZF = 1: absent; ZF = 0: present count present elements: - EBX = total, initially 0; ECX = word index, initially 15 - load word into EAX - test lowest bit; increment EBX when set; shift EAX right - repeat inner loop until EAX = 0 - jecxz finishes after word 0; otherwise decrement index and repeat 3.2.13 String instructions 1 string instructions operate on contiguous memory - ESI: source; EDI: destination - AL/AX/EAX: implicit byte/word/dword accumulator - addresses advance by the element size after each operation 2 DF controls direction - cld -> increasing addresses - std -> decreasing addresses 3 stosb/stosw/stosd: accumulator -> [EDI], then adjust EDI - clear AL, set EDI to buffer, repeat stosb to zero byte storage lodsb/lodsw/lodsd: [ESI] -> accumulator, then adjust ESI - lodsd plus add ebx,eax can sum dwords combine lodsd / inc eax / stosd to increment every array element movsb/movsw/movsd: [ESI] -> [EDI], then adjust both pointers 4 rep stosX / rep movsX: - repeat ECX times, decrementing ECX - initial ECX = 0 performs no operation - rep stosb replaces an explicit zero-fill loop 5 rep applies to one instruction, not to a whole lods/process/stos sequence copy buffer: - set ESI, EDI, ECX and DF; use rep movsb overlapping copy: - when moving data to higher overlapping addresses, copy backwards - otherwise early writes destroy bytes still needed as input insert "long " before "string": - set DF; move the six bytes of "string" five places right, starting at the end - EDI then points at the last insertion position - copy the five inserted bytes backwards from their source too 6 scasb/scasw/scasd: - compare accumulator with [EDI]; set comparison flags; adjust EDI cmpsb/cmpsw/cmpsd: - compare [ESI] with [EDI]; set flags; adjust both pointers 7 repe/repz: continue while count remains and comparison is equal repne/repnz: continue while count remains and comparison is unequal 8 rep and repe share an encoding - instruction determines whether ZF matters - repne has a separate encoding 9 find 'a' in a nonempty bounded buffer: - AL = 'a'; EDI = start; ECX = length; cld - repne scasb stops on match or exhausted count - test ZF afterwards to distinguish those cases - handle a zero initial length separately because no comparison then sets ZF 10 pointer/count updates also occur on the final comparison - after a forward successful scan, EDI points one byte past the match 3.2.14 Other useful instructions 1 stc / clc set/clear CF - can use CF to communicate a condition - cli / sti control interrupt enable and are unavailable to ordinary user code 2 lahf copies selected flags into AH - CF bit 0; PF bit 2; AF bit 4; ZF bit 6; SF bit 7 3 movsx / movzx combine copying with widening - destination is a register; source is a smaller register or memory operand - movsx extends the sign; movzx fills upper bits with zero - byte -> word/dword and word -> dword forms exist 4 cpuid reports processor identity and supported features - available on later members of the family, not the original i386 5 other examples: - xlat: byte translation through a lookup table - bswap: reverse byte order of a 32-bit register, introduced with i486 - aaa/aad/aam/aas: decimal-adjust operations 6 xchg exchanges two equal-sized operands - one must be a general-purpose register - register-memory form performs an atomic exchange - useful for coordination between concurrent activities 7 lock prefix makes supported memory read-modify-write instructions atomic - examples: lock inc dword [x], lock sub [m],eax - stronger coordination can be costly - memory xchg already has the required locking semantics 8 nop: no operation 3.3 Stack, subroutines and recursion 3.3.1 The stack and its purpose 1 stack = last in, first out - push adds; pop removes the most recently added value hardware stack: - contiguous memory with a stack-pointer register - on i386, occupied space extends from current top toward higher addresses - push moves top toward lower addresses; pop moves it back 2 growth direction is architecture-dependent - downward growth is common, but not universal 3 uses: - temporary register saves - return addresses - subroutine parameters and local variables - separate storage for each recursive invocation 3.3.2 The i386 stack 1 push/pop support words and dwords, not individual bytes - use dwords in these 32-bit examples to preserve alignment 2 ESP points to the most recently pushed value - decreases on push; increases on pop 3 push source: - register, memory or immediate pop destination: - register or memory - use explicit word/dword size when required 4 [esp] accesses the current top without removing it - mov eax,[esp] copies the top dword but does not change ESP 5 other occupied stack locations are ordinary memory too - do not store live data below ESP in these i386 programs - asynchronous signal handling can use that unreserved space 6 push eax / pop eax preserve a value across temporary register use string reversal example: - input ESI points at a zero-terminated string - push its characters, then pop them back into the string - terminating zero stays in place 7 first pass: - clear EBX and ECX - read [ESI+ECX] into BL - stop at zero; otherwise push EBX and increment ECX - each character occupies one stack dword - ECX becomes the string length 8 second pass: - jecxz skips an empty string - EDI starts at ESI - pop EBX; store BL through EDI; increment EDI - loop exactly ECX times - LIFO order reverses characters and restores the original stack depth 3.3.3 More stack instructions 1 pushad saves EAX, ECX, EDX, EBX, original ESP, EBP, ESI, EDI popad restores in reverse order - skips the saved ESP slot instead of loading ESP from it 2 pushfd / popfd save and restore EFLAGS - user mode cannot thereby change protected flag bits 3 16-bit counterparts: pushaw/popaw and pushfw/popfw - historical compatibility forms - avoid mixing two-byte stack entries into these dword-based frames 3.3.4 Subroutine principles 1 subroutine call temporarily transfers control - subroutine later returns to the instruction following the call 2 each call needs storage for return address, parameters and local variables - one fixed storage area per subroutine would suffice only without overlapping calls 3 recursion requires a fresh instance for every active call - later calls finish first -> natural LIFO lifetime 4 stack frame contains information belonging to one invocation - caller places parameters - call saves return address - callee reserves local storage 3.3.5 Calling and returning 1 call saves the following instruction's address on the stack, then transfers control - direct label, register target or target read from memory - direct form uses a relative displacement - these examples use near calls; no short-call form 2 ret pops the return address into EIP - before ret, ESP must again point at that address 3 fill_memory example uses register parameters - EDI = buffer; ECX = byte count; AL = fill byte - jecxz returns immediately for zero length - store AL, advance EDI, repeat with loop, then ret caller sets EDI=my_array, ECX=256, AL='@' and calls the routine - routine changes EDI and ECX; this simple interface explicitly relies on that 3.3.6 Stack frames 1 register parameters alone become inconvenient in larger routines - limited registers; parameters may stay live for a long time - nested calls need the same registers 2 stack parameters and locals keep each invocation's data together - on entry: [ESP] = return address - first nearby argument slot is [ESP+4] - local space must be reserved below the entry ESP before use 3 ESP changes during pushes and nested calls - a stable frame pointer gives fixed offsets to arguments and locals 4 callee preserves the caller's EBP prologue: - push ebp - mov ebp,esp - sub esp,N to reserve N local bytes frame layout: - [EBP]: saved EBP - [EBP+4]: return address - [EBP+8], [EBP+12], ...: argument slots - [EBP-4], [EBP-8], ...: local dwords 5 epilogue reverses frame setup - mov esp,ebp discards local storage - pop ebp restores caller's frame pointer - ret consumes return address enter N,0 / leave offer special frame-management instructions - book favors explicit instructions; performance depends on processor and instruction 6 Unix creates the initial stack and supplies backing memory as it grows - growth still has configured limits - book's 8 MB example is a historical/common limit, not a universal fixed size 3.3.7 Calling conventions 1 calling convention settles choices that the CPU does not decide - parameter order, cleanup and returned values 2 classic Pascal convention: push parameters left to right - last parameter is nearest the return address - first parameter's offset depends on total parameter count - fixed-arity routines fit this arrangement 3 classic i386 C convention: push parameters right to left - first parameter always at [EBP+8] with the standard prologue - later fixed offsets permit variadic interfaces - argument-count knowledge comes from the interface, e.g. format string 4 stack cleanup: - Pascal-style fixed arguments: callee can discard them - C-style: caller discards its own arguments C example with three dwords: - push a3, a2, a1; call proc1; add esp,12 ret 12: - pops return address, then discards another 12 argument bytes - immediate operand specifies byte count, not number of arguments 5 returned values in the conventions discussed: - small integer: EAX - 64-bit integer: EDX:EAX - floating point: top arithmetic-coprocessor register - larger aggregate may use caller-provided memory and a hidden pointer argument 3.3.8 Local labels 1 subroutine internals should not require remembering other routines' label names 2 NASM local label starts with a dot - belongs to the preceding nonlocal label - first_proc's .cycle and second_proc's .cycle do not conflict - begin each routine with a nonlocal label; use local labels inside it 3 NASM effectively expands .cycle into first_proc.cycle - avoid manually chosen dotted names that collide with this mechanism 3.3.9 Example: pattern matching 1 recursive example: match a string against a wildcard pattern 2 both inputs are zero-terminated strings - '?' matches exactly one arbitrary character - '*' matches an arbitrary substring, including empty - other characters match themselves - entire string must match; return 0 or 1 3 each invocation handles remaining suffixes - already-consumed prefixes are assumed matched 4 empty pattern matches only an empty string 5 non-star pattern character: - input must be nonempty - accept '?' or an equal literal - advance both pointers and continue; otherwise return false 6 star case: - try assigning 0,1,2,... input characters to '*' - recursively match remaining input against pattern after '*' - return true as soon as one alternative succeeds - after failure, stop only when no longer input suffix remains 7 zero termination permits two pointer arguments - earlier Pascal representation needed additional indices 8 match frame/register layout: - [EBP+8]: string pointer -> ESI - [EBP+12]: pattern pointer -> EDI - [EBP-4]: local alternative length I - EAX: scratch and Boolean result 9 advance a string suffix by incrementing its pointer - no copying of character data is required 10 recursive calls share physical CPU registers - each invocation must protect values needed after nested calls 11 register-saving convention balances caller and callee work - saving every register at every call wastes work - letting every routine destroy all registers burdens every caller 12 i386 CDECL convention used here: - EAX, ECX, EDX may be overwritten by the callee - EBX, ESI, EDI, EBP must be preserved when used - EAX is both frequently needed scratch space and result register 13 match saves EBP, ESI and EDI - EAX intentionally changes to return the result - choosing ECX/EDX instead would still require saves around recursion 14 implementation: - build frame; reserve I; push ESI and EDI - ordinary matching advances pointers in a loop, avoiding unnecessary recursive calls - star loop pushes pattern+1, then string+I, calls match, removes 8 argument bytes - EAX != 0 -> success - on failure EAX is zero, so adding I produces the index for the end-of-string check - increment local I and try next suffix when possible - common exits set EAX to 1/0 - restore EDI/ESI, discard frame, restore EBP, return caller pushes pattern then string and removes both arguments afterwards 15 long conditional branch to .false needs a near form when short range is exceeded 3.4 NASM features 1 earlier examples introduced only the NASM features needed at each step - includes, storage directives and local labels 2 now examine command-line options and syntax systematically - macro processing follows in its own chapter 3.4.1 Command-line options 1 nasm takes a source filename and options - -f selects output format; book uses elf for i386 object files - raw binary output lacks the OS executable structure - raw output can be appropriate for boot-sector code 2 -o selects output filename - usual ELF default replaces .asm with .o 3 -d defines a preprocessor symbol from the command line - -dSYMBOL corresponds to %define SYMBOL - -dSIZE=1024 supplies a value too 4 -l filename creates an assembly listing - source, offsets and generated bytes can be compared - nasm -f elf -l prog.lst prog.asm 5 -g includes debugging information - allows debugger to relate instructions to source - increases file contents without changing the program's algorithm 6 -e performs preprocessing only - writes expanded source to standard output - useful when diagnosing a macro's generated text 7 NASM has further options documented in its reference manual 3.4.2 Syntax 1 logical source line is the basic syntax unit 2 backslash at the end of a physical line joins the following line - permits readable source without exceeding the preferred line width 3 line fields: label, instruction, operands, comment - optional fields may be absent - operands must match the instruction when one is present - empty lines are ignored by the assembler but help readability 4 label names: - letters, digits and permitted punctuation - cannot start with a digit - initial dot makes a local label - names are case-sensitive - $ prefix can disambiguate an external symbol that resembles a keyword - colon is optional; conventional on code labels 5 instruction field can contain: - machine mnemonic, possibly with prefix - pseudo-instruction - multiline macro name machine mnemonics are case-insensitive; user macro names normally are not 6 multiple operands are comma-separated - register names are case-insensitive 7 general rule: - NASM's own words ignore case - programmer-defined names distinguish case 8 memory operands always use square brackets 9 semicolon starts a comment extending to the end of the line 3.4.3 Pseudo-instructions 1 pseudo-instructions look like instructions but direct assembly work - db/dw/dd and resb/resw/resd allocate data - dq/resq: 8-byte items; dt/rest: 10-byte items - dd/dq/dt can encode 4/8/10-byte floating-point values 2 name equ expression binds a label to an explicit constant - four equ 4 reserves no storage - using four substitutes the number 4 3 $ means the current assembly position - msglen equ $-msg computes bytes emitted since msg - includes explicitly stored newline/zero bytes in the example 4 times N repeats the following instruction or pseudo-instruction - stars times 4096 db '*' emits 4096 initialized bytes 5 incbin includes external binary-file contents in the memory image 3.4.4 Constants 1 constant categories: integers, characters, strings and floating-point values 2 integer notation supports decimal, binary, octal and hexadecimal 3 short quoted character sequences can act as integer constants - in the book's 32-bit examples, up to four characters fit a dword - longer sequences are strings - choose single or double quotes to include the other quote character 4 i386 integer byte order is little-endian - 'abcd' as an integer corresponds to 64636261h - storing it puts 'a' first in memory - shorter numeric character constants have zero upper bytes - context such as db may treat the same quoted text as a byte string 5 floating-point constants have a different bit representation from integers - 1 differs from 1.0 - single-precision 1.0 has bits 3f800000h - exponential notation example: 1.0e-5 - use an explicit decimal point in the syntax discussed here 3.4.5 Assembly-time expressions 1 assembler can evaluate an expression before program execution - generated code contains the result, not instructions performing that calculation - necessary values must be known at assembly time 2 integer expression operations: - +, -, * - / and %: unsigned division/remainder - // and %%: signed division/remainder - &, |, ^: bitwise AND/OR/XOR - <<, >>: shifts; unary ~: complement - unary + and -: retain/change sign - whitespace after remainder operators avoids confusion with macro syntax 3 seg operator is irrelevant to these flat-model examples 4 precedence, highest first: - unary; multiplication/division/remainder; addition/subtraction - shifts; AND; XOR; OR - parentheses override the order 3.4.6 Critical expressions 1 two-pass model of assembly: - first determine sizes and label values - then generate bytes with resolved operands - permits ordinary forward references 2 forward references become problematic when they determine layout itself - times (label-$) db 0 followed by label leaves its own size undetermined 3 critical expression = value required when establishing layout - constants and already-defined values can be used - later unresolved labels cannot determine earlier storage sizes 4 examples: times counts and resb/resw sizes instruction encodings can also depend on displacement width - [ebx], [ebx+10], [ebx+10000] need different sizes - explicit displacement width fixes the encoding even before value resolution - mov eax,[ebx+dword label] requests the long displacement form 3.5 Macros and the macro processor 3.5.1 Basic concepts 1 macro processor transforms source text into new source text - assembler subsequently translates the resulting ordinary source 2 powerful macros compensate for assembly language's limited expressive syntax - NASM's preprocessor can perform substantial source generation 3 macro = transformation rule associated with a macro name - PRINT and FINISH are earlier examples 4 macro definition establishes the name and replacement rule macro call supplies name and arguments macro expansion substitutes generated text 5 expansion need not make the text longer - a macro may generate a shorter fragment or nothing 6 macro directives can act without a macro call - %include replaces itself with a file's contents 3.5.2 Simple macro examples 1 pcallN abbreviates a C-style subroutine call - macro arguments: procedure name, then its parameters - %macro pcall1 2 ... %endmacro defines a two-argument multiline macro - %1 = procedure name; %2 = first procedure argument - expansion: push argument, call procedure, add esp,4 pcall2 / pcall3: - push parameters in reverse order - remove 8 / 12 argument bytes after call - pcall0 expands to call alone for uniform notation %0 is the number of macro arguments 2 single-line macros can replace part of an instruction - %define arg1 ebp+8 - %define arg(n) ebp+(4*n)+4 - %define local(n) ebp-(4*n) - assumes every parameter/local occupies four bytes keep brackets visible at use: mov eax,[arg1] - hiding brackets inside the macro obscures whether an operand accesses memory 3.5.3 Single-line macros and macro variables 1 single-line macros can be redefined - later source uses the most recent definition - %undef removes a definition 2 %define expands nested macro names when the outer macro is used - nested definitions may change between definition and use 3 example: mkvar expands to dd thenumber - thenumber=25 -> first use emits dd 25 - redefine thenumber=36 -> later use emits dd 36 %xdefine expands nested names immediately - freezes dd 25 at definition time - later changes to thenumber do not affect that saved replacement 4 %assign evaluates an integer expression immediately - %assign var 25 followed by %assign var var+1 -> 26 - unsuitable expressions produce an error 5 %assign names are macro variables - hold state for a program that generates assembly source 3.5.4 Conditional compilation 1 one source can produce program variants - avoids maintaining duplicate almost-identical source trees 2 NASM implements conditional assembly through its preprocessor - useful for optional debugging output 3 %ifdef DEBUG_PRINT ... %endif: - retain enclosed source only if DEBUG_PRINT is defined - remove its definition to omit diagnostic code 4 command-line -dDEBUG_PRINT enables the same code without editing source 5 %elifdef and %else choose alternative configurations - %error reports an unsupported/missing selection - example selects FOR_PETROV or FOR_SIDOROV 6 %ifndef tests absence; %elifndef supplies the corresponding alternative branch 7 %if evaluates a compile-time condition - comparisons: =/==, !=/<>, <, >, <=, >= - logical &&, ||, ^^ - values must be known during preprocessing - %elif supplies another condition 8 other tests: - %ifidn: exact token/string comparison after expansion - %ifidni: ignore case - %ifmacro: multiline macro exists - %ifid / %ifstr / %ifnum: argument kind - corresponding negated and %elif forms are available 9 %ifctx checks preprocessor context; outside this introduction 3.5.5 Macro repetition 1 %rep N ... %endrep processes its body N times at preprocessing time - %exitrep stops early - generates repeated source, not a runtime loop 2 generate initialized bytes 50 through 149: - %assign n 50 - repeat 100 times: emit db n; assign n=n+1 3 generate a Fibonacci-like table bounded by 100000: - maintain i and j; stop before emitting j when it exceeds the limit - emit dd j; update k=j+i, i=j, j=k - fib_count equ ($-fibonacci)/4 counts emitted dwords - as printed, initialization i=j=1 emits 1,2,3,...; emit an extra initial 1 for the usual 1,1,2,... sequence 4 macro repetition can generate instructions too - 128 inc word [array+a] instructions, increasing a by 2 each time - explicit runtime loop needs much less code space - unrolling trades code size for reduced loop-control work 3.5.6 Multiline macros and local labels 1 a normal label inside a macro is duplicated on every expansion - two zeromem calls would define lp twice 2 %%lp is a macro-local label - each expansion receives a unique generated name - references within that expansion remain consistent 3 macro arguments may refer to registers its expansion overwrites - zeromem ecx,eax with mov ecx,eax; mov eax,ecx loses the original address 4 preserve both argument values before assigning working registers - push length; push address; pop eax; pop ecx - then use %%lp for the byte-clearing loop - the printed loop still requires a positive length; add a zero-count guard if allowing empty regions - stack-relative arguments need care because pushes change ESP 3.5.7 Variable-argument macros 1 %macro mymacro 1-3 accepts one through three arguments %macro mymacro 2-* accepts two or more - %0 contains actual argument count 2 %rotate 1 cyclically changes argument positions - former %2 becomes %1; former %1 moves to the end - %0 remains unchanged 3 %rotate -1 rotates the other way - last argument becomes %1 4 general pcall macro: - first argument = procedure; remaining arguments = dword parameters - repeat %0-1 times: rotate -1, emit push dword %1 - rotate once more to recover procedure name - emit call %1; add esp,(%0-1)*4 pcall myproc,eax,myvar,27 expands to: - push 27, myvar, eax in that order - call myproc - remove 12 parameter bytes 3.5.8 String macro directives 1 preprocessor can inspect literal strings when generating source 2 %strlen sl 'my string' assigns 9 to macro variable sl 3 %substr extracts characters using one-based positions in these examples - 'abcd',1 -> 'a'; position 2 -> 'b'; position 3 -> 'c' - especially useful with macro arguments 4 all such work happens before assembly and execution - it cannot examine a string that will only exist at runtime 3.6 Interaction with the operating system 1 direct system calls replace the temporary stud_io.inc macros 2 understanding the i386 interface first requires: - multitasking and hardware support - interrupts, exceptions and controlled kernel entry - then Linux and FreeBSD calling conventions 3.6.1 Multitasking and its main types 1 one CPU can support multitasking by switching between programs 2 tasks execute concurrently when their start-to-finish intervals overlap 3 at any instant one CPU executes one task, but several tasks can remain in progress 4 I/O is much slower than CPU computation - waiting for disk mechanics/controller completion can waste CPU time 5 multitasking uses that waiting time for other tasks - OS starts or queues requested I/O - requester becomes blocked - another ready task receives the CPU 6 batch scheduling in the book's model: - current task runs until termination or blocking - completed I/O makes a task ready, without immediately switching to it - reduces switching overhead for long numerical work 7 interactive work needs prompt responses - a user should not wait for another task's entire computation 8 time sharing: - tasks receive time slices - expiry can preempt the current task in favor of another ready task - preempted task returns to the ready queue - blocked tasks receive no CPU slices until their blocking cause disappears 9 priority example: - static priority expresses assigned importance - dynamic priority rises while ready/waiting and falls while running - scheduler chooses highest combined priority 10 non-preemptive / cooperative historical systems: - switch only when the program enters the OS or yields - long computation or infinite loop can prevent other programs running 11 some applications require completion by an external deadline - delayed control output can be useless even if eventually correct 12 real-time scheduling focuses on predictable completion - meeting deadlines matters more than aggregate throughput - needs specialized scheduling analysis 3.6.2 Hardware support for multitasking 1 essential starting points: memory protection and CPU privilege modes 2 memory protection isolates programs from accidental or deliberate corruption - software-only checking of native instructions would be impractical 3 protection settings and direct device access must themselves be protected - otherwise a task could disable restrictions or conflict with other tasks 4 kernel / supervisor mode: all relevant instructions available user / restricted mode: cannot perform privileged system-wide actions 5 user tasks modify their permitted memory and request other work from the OS - privilege separation alone is not all the required hardware support 6 busy waiting repeatedly polls a device controller - consumes CPU time without doing useful computation 7 when another task runs during I/O, OS still needs notification of completion - may need to transfer data, update task state or start queued I/O 8 hardware interrupt: - device requests attention - CPU transfers control to OS interrupt handler - interrupted execution can resume after handling 9 timer interrupts give the scheduler regular opportunities to run - needed for enforcing time slices and deadlines 10 hardware requirements: - interrupts - memory protection - privileged and user modes - timer for preemption/time tracking - only the timer is a separate device in this simplified list 11 timer-only polling of all other devices is possible in principle - generally wastes work and complicates timely response 3.6.3 Interrupts and exceptions 1 interrupt terminology covers mechanisms with different causes 2 hardware interrupt originates outside the CPU - notifies it that an independently operating device needs service 3 simplified interrupt sequence: - device raises request - CPU reaches a resumable point and acknowledges - interrupt vector identifies the handler - CPU saves instruction pointer and flags - switches privilege as required and enters the OS handler - handler saves any additional registers it uses ordinary user instructions cannot simply enable privileged execution 4 timer repeatedly generates interrupt requests at configured intervals 5 integer division by zero cannot produce a valid integer result - normal instruction execution cannot simply continue with meaningful data 6 CPU reports exceptional situations to OS - division error, invalid instruction, protection violation - saves enough execution state for handling/diagnosis - OS decides how to treat the responsible task 7 exceptions arise inside instruction execution - no external request/acknowledgement exchange is needed - handler-entry mechanism resembles interrupts 8 exception handling has a responsible task and runs in its context - task may be suspended and later resumed - external interrupt need not belong to the interrupted task 9 i386 Interrupt Descriptor Table: - 256 numbered entries, 8 bytes each - entry identifies handler address/segment and entry behavior - configuring handler entry points is privileged 10 x86 terminology sometimes calls exceptions internal interrupts - other architectures commonly retain the word exception/trap 11 exception is caused by the task's own execution - unlike an asynchronous hardware interruption - common handler machinery does not make their execution contexts identical 3.6.4 System calls and software interrupts 1 system call = request from a user task to the kernel for a service - cannot be an arbitrary jump into kernel memory 2 CPU must change privilege and enter an OS-defined handler - architectures provide mechanisms such as trap, svc or syscall 3 i386 example uses int to enter an interrupt-table handler - user mode can invoke only entries configured to permit it 4 three causes in the terminology used here: - hardware interrupt: external device - exception: instruction execution - software interrupt: explicit instruction, used here for a syscall 5 software-interrupt name describes the mechanism - task deliberately requests the service 6 privilege increase and entry into a predefined handler are inseparable - only privileged code configures those entry points - user code cannot continue arbitrarily with kernel privileges 7 syscall numbers, arguments and results depend on OS and architecture - Linux/i386 and FreeBSD/i386 differ despite using the same CPU 8 C libraries provide ordinary function wrappers - wrapper hides syscall number and machine-level calling sequence - same function name can map to different syscall numbers 9 direct assembly must supply OS-specific numbers and constants - conditional assembly can select the correct implementation 3.6.5 Linux syscall convention 1 historical Linux i386 int 80h interface: - EAX = syscall number - arguments in EBX, ECX, EDX, ESI, EDI, EBP - EAX returns result or negative errno on failure - raw errors occupy the high unsigned range; ordinary wrappers translate them 2 write is syscall 4 - arguments: descriptor, data address, byte count 3 write to standard output: - EAX=4; EBX=1; ECX=message address; EDX=message length - execute int 80h 4 _exit is syscall 1 - EBX supplies exit status - convention: 0 success; nonzero failure 5 Hello example: - message includes newline; length calculated with $-msg - perform write, then _exit(0) - no stud_io.inc required 6 some system calls involve wider/special argument arrangements - general register summary does not replace each syscall's specific interface 3.6.6 FreeBSD syscall convention 1 historical FreeBSD i386 int 80h interface: - EAX = syscall number - arguments pushed right to left - EAX = result; CF clear indicates success - CF set indicates error code in EAX 2 kernel expects the stack layout produced by calling a small wrapper - stack top contains wrapper return address - first real argument at [ESP+4], then [ESP+8], ... 3 direct int 80h can supply a dummy dword instead of a wrapper return address - afterwards discard dummy plus all argument bytes 4 Hello example: - push length, message pointer, stdout descriptor, dummy - EAX=4; int 80h; discard 16 bytes - push exit status and dummy; EAX=1; int 80h - _exit does not return, so no later cleanup is needed test CF before an instruction such as add destroys it - ignored write failures are a simplification of the example 3.6.7 System-call examples 1 _exit(1) terminates; write(4) sends buffer bytes to a descriptor 2 read(3): descriptor, destination buffer, maximum byte count - standard input normally uses descriptor 0 - buffer must be large enough - successful result is actual bytes read, which may be fewer than requested 3 read returning zero for a nonzero request means end of input - terminal Ctrl-D can indicate EOF 4 always inspect read's result - only the returned number of buffer bytes contains newly read data 5 check error convention after every fallible call - Linux: negative errno in EAX - FreeBSD: CF and EAX 6 usual initial descriptors: - 0 stdin; 1 stdout; 2 stderr open(5) creates a new descriptor - pathname is zero-terminated - flags select access mode and creation/truncation behavior - creation mode supplies requested permission bits, subject to process umask i386 examples: - O_RDONLY = 0 on both systems - write/create/truncate flags: Linux 241h; FreeBSD 601h - 666q requests ordinary read/write permissions; 600q restricts them to owner 7 open can fail for reasons outside the program's control - check first; on success save returned descriptor for later read/write 8 close(6) releases a descriptor - later open may reuse the same number 9 getpid(20) returns current PID getppid returns parent PID - Linux i386 number 64; FreeBSD i386 number 39 - no arguments; result in EAX 10 kill(37) sends a signal to the selected process - SIGTERM=15 requests termination and can be handled - SIGKILL=9 cannot be caught or ignored 11 Unix provides many more calls - documentation generally describes C interfaces - some library services emulate behavior without a single corresponding kernel call - assembly examples are for understanding the mechanism 3.6.8 Command-line arguments 1 command-line arguments are the same interface already used in Pascal examples 2 initial stack at _start in these i386 examples: - [ESP]: argc, including program name - [ESP+4]: pointer to argv[0] - [ESP+8]: pointer to argv[1], and so on - each argument is a separate zero-terminated string 3 argument-printing example supports both OS conventions - select OS_LINUX or OS_FREEBSD with -d strlen helper: - one pointer argument through stack - count bytes up to zero; return length in EAX - uses EAX/ECX and preserves EBP according to CDECL 4 print_str calls strlen, then write - save string pointer in EBX across the nested call - preserve caller's EBX on entry/return - do not rely on strlen accidentally preserving caller-clobbered registers 5 print newline using the same helper and a two-byte string: 10,0 6 more efficient output could collect all text and issue fewer syscalls - example favors a short, understandable implementation 7 nlstr can live in .text because it is immutable 8 main loop: - EBX = remaining argument count - ESI = pointer to current argv slot - print [ESI], then newline - add ESI,4; decrement EBX; repeat - EBX/ESI survive helper calls under CDECL - after loop, perform OS-specific _exit(0) 3.6.9 Example: copying a file 1 copy source to destination named by two command-line arguments - open input for reading and output for writing - read at most 4096 bytes; write the bytes actually received - repeat until EOF 2 a kernel macro centralizes Linux/FreeBSD differences - first macro argument = syscall number - remaining arguments = syscall parameters - Linux variant permits at most six parameters 3 macro follows the CDECL preservation rule - EAX/ECX/EDX may change - Linux version saves EBX and, when needed, ESI/EDI/EBP 4 error interfaces differ - FreeBSD CF must be tested before flags are changed - Linux result must be checked for encoded negative error 5 normalized macro result: - success: EAX = result, ECX = 0 - failure: EAX = -1, ECX = positive error number 6 push argument values before assigning syscall registers - avoids overwriting a register that still supplies another argument - %rotate pushes all values in reverse order 7 FreeBSD keeps parameters on stack, with syscall number serving as dummy top dword Linux pops number and parameters into EAX/EBX/ECX/EDX/ESI/EDI/EBP - nested preprocessor conditions select the required registers 8 post-call handling also differs enough to justify separate macro branches - name kernel avoids conflicting with the syscall instruction mnemonic 9 indent preprocessor conditions separately from generated machine instructions - FreeBSD branch checks CF, normalizes result, discards stack arguments - Linux branch recognizes error, normalizes result, restores saved registers - macro-local labels prevent collisions between expansions - kernel 4,1,msg,msg_len and kernel 1,0 now express Hello and exit 10 openwr_flags depends on selected OS - Linux 241h; FreeBSD 601h - both mean write/create/truncate in the book's interfaces .bss storage: - buffer: 4096 bytes; bufsize calculated from labels - fdsrc/fddest: descriptors - argc/argvp: argument count and pointer-vector address diagnostic messages go to descriptor 2 - usage error - cannot open source - cannot open destination entry setup: - pop argc, then save current ESP as argvp - require argc=3: program name plus two filenames - bad count -> print usage and exit status 1 open source: - [argvp] holds vector address; its +4 slot points to source pathname - open with O_RDONLY=0 - failure -> diagnostic and exit 2 - success -> save EAX in fdsrc open destination: - pathname pointer at vector +8 - use openwr_flags and requested mode 666q - failure -> diagnostic and exit 3 - success -> save descriptor in fddest copy loop: - read(fdsrc,buffer,bufsize) - printed example exits loop when signed EAX <= 0 - positive EAX supplies exact byte count to write - repeat after write - example merges read error with EOF and omits short-write/error recovery - therefore demonstrates the mechanism, not a complete reliable cp implementation finish by closing both descriptors and exiting with status 0 internal main-program labels are local to _start - reduces accidental conflicts in larger programs 11 complete example is supplied as copy.asm 3.7 Separate compilation 1 compile each module separately, then link object files into an executable - rebuild changed modules; reuse unchanged objects - linking is normally cheaper than recompiling all source 2 assembly and C toolchains use object-file formats understood by the linker - ld can combine any required number of compatible objects 3 module owns its internal namespace - global exports selected labels - identical private names in different modules need not conflict - only exported names form the externally visible interface 4 encapsulation permits changing internal details without breaking callers - private symbols need not become part of the public documentation 3.7.1 Module support in NASM 1 global myproc exports a definition from this module extern myproc declares a definition expected from elsewhere - assembler sees only the current module - records an external reference for the linker to resolve 3.7.2 Example 1 greeting program asks for a name and prints a personalized greeting - all strings use terminating zero bytes 2 separate modules: putstr, getstr, strlen and quit - putstr depends on strlen - main module calls putstr/getstr/quit 3 kernel.inc contains the syscall macro - included during preprocessing, not linked as an object module - macro definitions must be visible when their calls are expanded 4 strlen.asm exports strlen - pointer argument through stack; EAX counts until the first zero byte - global/extern declarations near the top make interfaces visible 5 putstr.asm exports putstr and imports strlen - calls strlen, removes its argument, then uses kernel macro for write - string pointer comes from [EBP+8] getstr accepts buffer address and capacity - reads one byte at a time for simplicity - avoids a large I/O implementation, but uses many syscalls 6 getstr state: - EDX = next output address; ECX = count - increment count before capacity test to reserve one byte for terminating zero - read byte; stop on EOF/error or newline - overwrite newline with zero; EOF writes zero at the unfilled position - caller must provide a positive buffer capacity 7 getstr uses caller-clobbered registers - save ECX/EDX around kernel macro because both hold loop state - read result must equal 1 before inspecting the character - place final zero, dismantle frame, return quit.asm exports quit and invokes _exit(0) - no ret is needed after a nonreturning exit syscall greet.asm: - exports _start; imports putstr/getstr/quit - initialized zero-terminated message strings in .data - 512-byte input buffer in .bss - prompt, read name, print greeting prefix/name/suffix, quit - caller removes each helper's stack arguments assemble the five .asm modules separately - kernel.inc is not a sixth module 8 OS-selection definition is required where kernel.inc is used - passing it consistently to every module simplifies build commands 9 link the five object files with ld - select elf_i386 on the book's 64-bit GNU toolchain - resulting greet executable prompts and prints the supplied name 3.7.3 Object code and machine code 1 object module supplies exported symbols and requests imported symbols 2 assembler cannot know every final address - external definitions are elsewhere - placement of this module among others is not yet known 3 object file supplies code plus relocation information - linker learns where address-dependent values must be filled in or adjusted - linker does not need original source or its programming language 4 nm displays object-file symbols - useful for inspecting exports and unresolved references 3.7.4 Libraries 1 programs reuse collections of prepared subroutines - linker libraries differ from source-only macro libraries 2 static library = archive of object modules with symbol-index information 3 in the model discussed, object module is the unit of inclusion - one required function can pull in other code in the same object - small, coherent modules reduce unnecessary inclusion 4 ar crs libgreet.a strlen.o getstr.o putstr.o quit.o builds an archive - library name greet -> filename libgreet.a - link by filename, or use -l greet with -L . - -L adds a library search directory 5 library remains a collection of selectable modules - linker extracts required members instead of treating archive as one indivisible object 3.7.5 How the linker works 1 linker receives an ordered list of objects and libraries - objects named directly - library may be named directly or selected with -l - -L adds directories searched for library files 2 two conceptual symbol sets: - resolved: definitions already accepted - unresolved: referenced symbols without accepted definitions - NASM global supplies exports; extern supplies imports 3 book's linking model begins with entry point _start unresolved for each ordinary object: - include its contents - add exports to resolved; remove matching unresolved references - add imports still lacking a definition to unresolved 4 for each static archive: - extract a member if its exports satisfy current unresolved references - update both sets - repeat within the archive while another member is needed - then advance to next command-line input greet example: - main requires getstr/putstr/quit - accepting putstr adds requirement for strlen, also extracted 5 principal errors: - undefined reference: required symbol remains unresolved at end - duplicate definition: conflicting accepted exports share a name 6 ordinary archive search does not automatically return to earlier archives - put referring objects before libraries that satisfy them - cyclic library dependencies make this simple order insufficient - book recommends restructuring or combining tightly coupled libraries 7 dependencies between libraries constrain their order too - prefer clear, limited dependencies and coherent library responsibilities 8 linking principles also matter for C/C++ programs - affect program size and organization of reusable code 9 ld also supports detailed options and linker scripts - scripts can control layout beyond the introductory examples 10 common options: - -l: library name; -L: search directory - -o: output filename - -m: emulation/platform, e.g. elf_i386 11 additional options: - -nostdlib: restrict ordinary default library search - -e name: choose an entry symbol other than _start - -y name: report references/definitions of a selected symbol 12 -static requests static library selection -s strips symbol/debug information from the result - assembly can also include debugger information with nasm -g 3.8 Floating-point arithmetic 1 floating-point values approximate quantities using finite bits - operations introduce rounding error - representation and arithmetic differ from integers 2 historical x86 floating-point support used separate 8087/80287/80387 chips - later processors integrated the hardware - x87 programming model still has its own registers, flags and instructions 3.8.1 Floating-point formats 1 ordinary normalized value = (-1)^sign * 2^(exponent-bias) * significand - single: 32 bits, 8 exponent bits, bias 127, 23 stored fraction bits - double: 64 bits, 11 exponent bits, bias 1023, 52 stored fraction bits - extended: 80 bits, 15 exponent bits, bias 16383, 64 significand bits - normalized significand is in [1,2) - single/double omit the leading 1; extended stores it explicitly 2 exponent patterns of all zeros/all ones encode special cases - zero cannot use an ordinary normalized significand - these encodings include useful values as well as exceptional results 3 signed zero: - zero exponent/significand with sign bit set represents -0 - tiny negative results can round to -0 - signed zero also arises from exact operations; it is not necessarily evidence of an error 4 subnormal value: - zero exponent field, nonzero fraction, no implicit leading 1 - effective exponents -126 / -1022 / -16382 for the discussed formats - provides gradual underflow below the normal range - scaling quantities can help avoid extreme magnitudes in an algorithm 5 author's units example illustrates the enormous available exponent range - even very small physical lengths in very large units may remain normal - criticism of subnormal support is the author's view 6 all-ones exponent represents infinities or NaNs, depending on significand encoding - sign distinguishes positive/negative infinity - NaNs represent invalid/unordered results; signaling and quiet forms differ - masked exceptions can continue with such values - whether an exception traps depends on control-word masks 7 NASM sizes: - qword = 8 bytes; tword = 10 bytes - dq/dt initialize; resq/rest reserve corresponding elements 8 dd/dq distinguish integer and floating initializers by notation - 1000.0 = 1.0e3; 0.001 = 1.0e-3 - integer 1 and floating 1.0 do not have the same bits 9 x87 registers hold extended-format values - loads/stores convert other memory formats - control settings can reduce arithmetic significand precision 3.8.2 Arithmetic-coprocessor organization 1 x87 has eight physical 80-bit data registers organized as a circular stack - names ST0 through ST7 are relative to TOP - pushing decrements TOP; old ST0 becomes ST1 - values stay in their physical registers while logical names change - pop advances TOP 2 NASM uses ST0, ST1, ... - other assemblers/reference texts may write ST(0), ST(1), ... 3 control word, status word and tag word contain flags and small fields 4 status word: - TOP in bits 11–13 identifies physical top register - C0/C2/C3 hold condition results used like CF/PF/ZF - C1 supplies additional operation-specific status 5 status exception bits: - IE invalid, DE denormal operand, ZE divide by zero - OE overflow, UE underflow, PE inexact/precision - SF identifies a stack fault associated with invalid operation 6 summary/busy status records pending exceptional work and coprocessor state - mainly relevant to low-level handling and historical asynchronous operation 7 control word: - exception-mask value 1 means masked; value 0 means unmasked - RC chooses nearest, downward, upward or toward-zero rounding 8 precision-control field selects significand precision for applicable arithmetic - 24, 53 or 64 significant bits - default initialized x87 state uses extended precision - old IC/IEM fields are not used on later processors 9 tag word: two bits per physical register - 00 valid; 01 zero; 10 special; 11 empty - tracks occupancy and detects stack overflow/underflow 10 instruction/data pointers retain information useful for exception diagnosis 11 x87 mnemonics begin with f - operands are stack registers or memory - arbitrary immediate floating-point operands are not encoded in instructions 3.8.3 Moving data to and from x87 1 fld pushes a floating-point value - memory source: dword/qword/tword - register source: STn - fld st0 duplicates the top - fld qword [matrix+ecx*8] pushes one double-precision array element 2 fst stores ST0 without popping; fstp stores then pops - fst memory form supports 32/64-bit formats - fstp also supports 80-bit memory storage - register destination can receive the copied value - fstp st0 discards the top value 3 integer conversion: - fild loads signed word/dword/qword integer and converts it to x87 format - fist rounds ST0 into word/dword integer memory - fistp also supports qword and removes the top - rounding follows the control word 4 fxch stN exchanges ST0 with another occupied stack register - no-operand fxch means exchange with ST1 5 constant-loading instructions push a new value - fld1: 1.0; fldz: +0.0; fldpi: pi - fldl2e: log2(e); fldl2t: log2(10) - fldln2: ln(2); fldlg2: log10(2) - rounding mode affects approximations of irrational constants 3.8.4 Arithmetic instructions 1 memory-source arithmetic uses ST0 and 32/64-bit floating memory - fadd/fmul: add/multiply - fsub: ST0-source; fsubr: source-ST0 - fdiv: ST0/source; fdivr: source/ST0 - result remains in ST0 2 two-register forms require ST0 as one operand - first operand is destination - reversed forms reverse arithmetic order, not destination 3 p forms store result in first register, then pop ST0 - faddp, fsubp, fsubrp, fmulp, fdivp, fdivrp - second operand is ST0 - fsubp st1,st0 leaves old ST1 minus old ST0 at the new top 4 no-operand p form uses ST1 and ST0 - consume two values, leave one result - ordinary subtraction/division uses old ST1 as left operand and old ST0 as right 5 reverse Polish notation evaluates naturally on the register stack - (x+y)*(1-z) -> x y + 1 z - * - push x/y, faddp; push 1/z, fsubp; fmulp - shorter form can use fadd/fsub with memory operands - expression depth must fit available stack space or spill intermediate values 6 Dijkstra's conversion uses an auxiliary operator stack - scan infix expression from left to right - emit operands directly - stack holds operators and opening parentheses 7 conversion rules for the left-associative arithmetic discussed: - '(' -> push - ')' -> emit operators until matching '('; discard that parenthesis - operator -> emit preceding operators of equal/higher precedence, then push it - at end, emit remaining operators - unmatched parentheses are errors 8 example a-b+c*d -> a b - c d * + - '+' first releases preceding '-' - '*' stays above '+' until the expression ends mark unary operators distinctly before conversion - postfix position alone cannot distinguish unary minus from binary subtraction - account for their higher precedence 9 avoid ambiguous assembler-specific no-operand ordinary arithmetic forms - explicit register operands state the intended order 10 fiadd/fisub/fisubr/fimul/fidiv/fidivr: - combine ST0 with a signed integer memory operand of word/dword size 11 unary operations on ST0: - fabs: absolute value - fchs: change sign - frndint: round to integer value while retaining floating representation 12 fprem/fprem1, fscale and fxtract are mentioned for further study 3.8.5 Mathematical functions 1 fsin/fcos/fsqrt replace ST0 with sine/cosine/square root fsincos produces two values - cosine in new ST0; sine in ST1 - stack depth increases by one 2 fptan leaves 1.0 in ST0 and tangent in ST1 - fdivrp then computes cotangent - fstp st0 discards the extra 1 if tangent is wanted 3 fpatan consumes x=ST0 and y=ST1 - returns quadrant-aware arctangent of y/x, like atan2(y,x) - result in new ST0; stack depth decreases by one 4 f2xm1, fyl2x and fyl2xp1 support numerically useful combined operations 5 fyl2x computes y*log2(x), consumes both operands and pushes result - load y=1/log2(a) to compute logarithm base a 6 fyl2xp1 computes y*log2(1+x) - intended for a limited interval around zero - book gives |x| <= 1-sqrt(2)/2 7 useful when 1+x would round to 1 before ordinary logarithm evaluation - x itself can remain representable even when adding it to 1 loses all its bits - direct combined operation preserves a meaningful small result 8 f2xm1 computes 2^x-1 for -1 <= x <=1 - small x gives a result near zero - computing the difference directly avoids losing it by first rounding 2^x to 1 9 these instructions use implicit stack operands 3.8.6 Comparisons and their results 1 x87 comparison flags must reach the CPU flags before ordinary conditional jumps 2 fcom compares ST0 with memory operand/STn; omitted operand means ST1 - fcomp also pops ST0 - fcompp compares ST0/ST1 and pops both 3 ordered comparison status: - equal: C3=1, C0=0 - less: C3=0, C0=1 - greater: C3=0, C0=0 4 C2 indicates unordered comparison when applicable - NaNs are unordered; equal signed infinities compare equal - invalid-operation masking determines whether handling traps 5 fstsw ax; sahf transfers status bits - C3 -> ZF; C2 -> PF; C0 -> CF - use unsigned-integer-style jumps such as ja/jb/jae/jbe - this follows flag placement, not unsigned floating-point semantics 6 minimum example: - load b, then a -> ST0=a, ST1=b - compare and transfer flags - if a>b, leave order; otherwise exchange - larger value is now ST0; discard it - store/pop remaining minimum into m - assumes ordered operands 7 ffree st0 plus fincstp can also discard the top 8 ficom/ficomp compare ST0 with signed word/dword integer memory - ficomp pops afterwards - ftst compares ST0 with zero 3.8.7 Exceptional situations 1 six exception classes may indicate an error or ordinary rounding behavior 2 invalid operation: - invalid mathematical operation, e.g. square root of a negative number - invalid operand or empty/full stack misuse - SF distinguishes stack fault 3 denormal-operand exception concerns a subnormal input - includes loading smaller-format subnormal data into the register stack 4 divide-by-zero exception concerns a nonzero finite dividend divided by zero - zero divided by zero is invalid operation instead 5 overflow: result too large for destination format - can occur when storing extended value to a smaller format 6 underflow: result too tiny for normal representation, with relevant precision loss - concerns result rather than an already-subnormal input 7 precision/inexact: exact result does not fit available significand bits - normal for many computations 8 control-word mask bits correspond to status exception bits - mask clear: exceptional handling can be raised - mask set: continue with defined default result/rounding where possible - exceptions include different cases; infinity is not the result of every invalid division 9 status flags are sticky - record exceptional situations until explicitly cleared - masked exceptions can therefore be checked later - fclex clears exception status 3.8.8 Exceptions and wait 1 x87 can defer reporting a pending unmasked exception until a later checking instruction - modifying a memory operand in between can destroy diagnostic information - example: fimul [k], integer store to k, then fsqrt - ordering the next x87 check before modifying k avoids that issue fwait / wait checks pending unmasked x87 exceptions - useful after the final possibly exceptional x87 operation 2 some waiting mnemonics represent wait plus a nonwaiting instruction - fstsw = wait + fnstsw - fclex = wait + fnclex - nonwaiting forms need deliberate use because they bypass the preliminary check 3.8.9 Controlling x87 1 control word sets operating modes; status word reports state; tag word tracks registers 2 fstcw/fnstcw store control word to 16-bit memory fldcw loads it from 16-bit memory set rounding toward zero: - reserve four stack bytes to preserve alignment - store control word; set RC bits 10 and 11 - reload control word; release temporary stack space fstsw/fnstsw store status to AX or 16-bit memory - no simple load-status-word counterpart - fincstp/fdecstp adjust TOP without changing register tags - changing TOP alone does not push a value or free an occupied register - fclex/fnclex clear exception status 3 changing masks can expose an already-pending exception - clear/handle outstanding status deliberately before changing control settings 4 ffree STn marks that physical register empty without moving TOP - ffree st0; fincstp discards the current top finit/fninit establish initial x87 state - control word 037fh: nearest rounding, extended precision, all exceptions masked - status cleared; TOP=0 - tags mark every register empty, without erasing their raw data bits - use only when no live x87 values need preserving 5 fsave/fnsave save complete legacy x87 state - 108-byte area in the discussed 32-bit mode - saving also initializes x87 afterwards - frstor restores the saved state 6 fstenv/fnstenv/fldenv save/load the environment without the data registers - 28-byte area in this mode 7 fnop: floating-point no operation 3. Concluding remarks 1 the covered subset is enough to write assembly programs - main purpose: understand execution beneath high-level languages 2 full i386 architecture includes many additional features and historical complications - especially beyond user mode and flat addressing 3 other architectures such as ARM or SPARC offer further low-level perspectives - technical references permit deeper study of either them or x86 ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ============================================================================== Volume II - C programming, operating systems, networks, parallel programs, and the kernel English study notes for progintro_2_92_v2 ------------------------------------------------------------------------------ 4. C programming 4.1 The C language: background and design 1 C shares familiar concepts with Pascal: - typed variables, expressions, statements, branches, loops, subprograms - every subprogram is called a function, including procedure-like functions - braces { } group statements as begin / end do in Pascal 2 surface notation is not the main difference between languages - := versus = and begin/end versus braces are easy to learn - conceptual differences require experience writing programs in both languages - ask why language features work as they do, not just how to spell them - understanding design tradeoffs helps evaluate a language's limitations 3 author presents C as an important but imperfect systems-programming tool - learning its origins helps explain its unusual choices - claims about popularity, indispensable uses, and professional status are the author's position 4 C developed alongside Unix - Ken Thompson initially implemented Unix in PDP-7 assembly - sought a simple higher-level language that was inexpensive to implement - derived B from BCPL 5 rewriting Unix in a higher-level language aimed to simplify porting - a new processor architecture otherwise required extensive assembly changes 6 B was too limited for that task - operations largely worked with machine words rather than a rich type system - Dennis Ritchie extended the approach into C 7 Ritchie is credited with creating C - Brian Kernighan coauthored the well-known book, rather than the language - this author also emphasizes Thompson's B and early Unix work as influences 8 three design pressures explain many C features: - replace much assembly programming - keep implementation relatively simple - solve immediate practical systems problems - later longevity was not the original design requirement 9 kernels and embedded firmware illustrate C's low-level role - express most work more compactly than assembly - compiler optimization reduces the need for hand-written machine-level code - retain assembly for operations unavailable directly in C - book's claim that only C/assembly are possible is its historical design viewpoint 10 C can also support portable software with few runtime dependencies - isolate platform-specific details explicitly - high-level abstractions depend on their own implementations and libraries - portability involves those dependencies as well as the application's source 11 learn C without treating every language feature as an ideal design - experience with other languages provides a basis for comparison 12 author criticizes later C standards and corporate influence on standardization - chooses a deliberately restricted language subset for this book - this is an opinion about design and governance, not a ban imposed by C 13 interoperability needs shared specifications - every standard is a specification - a specification need not be an officially adopted standard 14 specification can describe an existing implementation - lets others choose to implement compatible behavior - author favors this practical, voluntary model 15 author contrasts that model with officially endorsed standards - discusses authority attributed to governments, experts, and participating organizations 16 committees are one mechanism for producing standards - author introduces a strongly critical discussion of their decision-making 17 author argues that committee incentives can favor accepting proposals over careful review - objections and consensus-building require time and effort - these broad judgments are the author's commentary 18 author also criticizes organizational representation and commercial influence - concern: standards may favor large vendors over independent implementers 19 early Internet RFCs are the author's preferred example of practical specifications - emphasizes simplicity, clarity, and Jon Postel's contribution - contrasts these with later, more complex documents 20 author uses Pascal to illustrate divergence between a standard and implementations - book follows the practical dialect being taught 21 author rejects much of standardized C++ - later C++ material will deliberately use a small, older subset 22 author likewise excludes selected newer C facilities - examples include variable-length arrays and complex-number facilities - exclusion expresses the book's coding approach, not universal unsuitability 23 examples use compiler options and a restricted C subset - check the selected language mode when compiling older-style source 4.2 First impressions 1 C is case-sensitive - keywords use lowercase - wordcount, WordCount, and WORDCOUNT are different identifiers - book's convention: lowercase names with underscores, e.g. word_count 2 block comments use /* ... */ and do not nest - first */ closes the comment - an inner /* has no nesting effect - use conditional preprocessing to disable code that may contain comments 3 // comments end at the newline - author prefers block comments for this book's C style - // is also part of standardized C from C99 onward 4.2.1 Hello, world 1 first example: - include - define int main(void) - printf("Hello, world\n"); - return 0; - main is a function; int specifies its returned value's type 2 empty parameter lists require attention to the language version - older C distinguishes a non-prototype declaration f() from f(void) - use (void) when explicitly declaring a function with no parameters 3 C has no separate Pascal-style main-program statement block - executable statements occur inside functions - declarations can occur outside functions - hosted-program execution enters the user's code through main 4 main is normally called by startup code - executable entry point is commonly _start in the Unix examples - startup support prepares the environment, calls main, and handles termination - later examples provide their own startup code without the standard library 5 standard library supplies commonly available facilities alongside the implementation - compiler driver normally arranges its inclusion during linking - C can also be used without the normal hosted library/runtime 6 braces group statements into a compound statement - also delimit a function body 7 printf is a library-function call - C's core syntax has no special input/output statement - language constructs and library facilities are separate layers 8 printf is provided by a library, not by a dedicated language statement - compilers may nevertheless recognize standard-library calls for diagnostics/optimization 9 printf performs formatted output - print values of different types - choose numerical bases, widths, precision, and other formatting 10 printf also returns a value - on success, number of characters written - "Hello, world\n" has 13 characters - a call can ignore its result and be used for its output side effect 11 expression statements commonly perform work through side effects - assignments and function calls are central examples 12 string literal uses double quotes - "Hello, world\n" includes a newline escape - \n represents the newline character - outputting it provides the line break that writeln supplied in Pascal 13 Pascal can also put the newline into the string itself - examples use #10 or ^J - C's \n is a mnemonic spelling rather than a numeric character code 14 semicolon is part of statement syntax in C - Pascal normally uses it to separate statements - keep the semicolon on printf(...) even immediately before } 15 return expression; ends the current function - supplies its result - can terminate the function early - return 0; makes main return zero 16 main's result becomes the program's termination status - 0 conventionally indicates success - startup/termination support passes the result to the OS 17 #include makes header declarations available to this translation unit - : implementation's standard-header search - "mymodule.h": customary spelling for a project header - header declares printf's interface, not its full implementation - compiler produces object code with an unresolved reference - linker resolves that reference using library code 18 dynamic linking can keep library code outside the executable file - runtime loader arranges access to the shared library - static linking is another possibility 19 including a header and linking a library are different operations - header supplies declarations used during compilation - linking supplies definitions needed by the object code - #include does not itself tell the linker to add a library 20 save the C source as hello.c - gcc is the compiler driver used in the book - GCC supports several languages through different front ends 21 other C implementations exist, including Clang - GCC is the book's chosen tool, not a language requirement 22 book's normal development options: - -Wall: enable a useful group of warnings, not literally every warning - -g: include debugging information - investigate diagnostics while developing the program 23 -o selects the output name - gcc -Wall -g hello.c -o hello - driver compiles source, invokes linking, and normally supplies standard libraries - without -o, the traditional default executable name is a.out - temporary object files may be removed after the combined operation 24 successful build normally prints no diagnostics - run ./hello - expected output: Hello, world followed by a newline 4.2.2 Program termination 1 exit status communicates the program's outcome - 0: success - nonzero: failure or another documented outcome - traditional Unix wait status exposes the low eight bits, 0..255 - different nonzero values can identify different failures 2 minimal true / false programs return 0 / 1 from main - no library call -> no header needed - useful when shell scripts need a command with a known success/failure result 3 return finishes one function invocation - usually returns control to that function's caller - returning from the initial invocation of main ends the program - in C, recursively calling main does not make every return terminate the process 4 exit(status), declared in , terminates from any function - performs normal library cleanup, including flushing buffered output - _exit requests OS-level termination without flushing user-space stdio buffers - direct _exit can therefore lose pending text or file output 5 buffering and process operations interact - later sections explain effects involving fork, exit, and copied buffers 4.2.3 Quadratic equation 1 example solves a quadratic equation over the real numbers - coefficients must actually define a quadratic equation - negative discriminant -> report no real roots 2 new features needed: - double variables and a function with parameters - formatted input and output - passing addresses to let a function modify caller-owned objects - linking mathematical library functions such as sqrt 3 headers and discriminant function: - declares standard I/O functions - declares sqrt and other mathematical functions - double discrim(double a, double b, double c) - return b*b - 4*a*c; - parameter and function declarations put type before name - storing the result in a temporary double before returning is optional 4 main needs local doubles for the three coefficients and discriminant - also an int for checking the input result 5 any compound statement can introduce local variables - scope is confined to that block - book declares locals at the beginning of each block - double p, q, r, d; int n; - comma-separated variables can share a declaration's base type - each function parameter still needs its own type declaration 6 printf accepts a format string followed by values to format - ordinary format characters are copied to output - conversion directives beginning with % consume additional arguments 7 conversion directives describe the argument and representation: - %d: signed decimal integer - %x: unsigned hexadecimal integer - %05d: decimal with minimum width five, padded with zeros - printf("%d times %d is %d\n", x, x, x*x) - width is a minimum, not a limit on the printed number 8 %f prints a floating-point value in fixed-point notation - %.5f requests five digits after the decimal point - float arguments are promoted to double in variadic calls such as printf 9 scanf uses a format string to describe input conversions - %lf reads a double; %f reads a float - receives addresses of destination objects - C arguments are passed by value; no implicit Pascal-style var parameter 10 variable occupies memory that can also be accessed through its address - scanf receives that address and stores the converted value there 11 Pascal implementations also commonly pass addresses for var parameters - language hides that mechanism; C exposes it explicitly 12 address-of operator: &variable - scanf("%lf %lf %lf", &p, &q, &r) - three conversion directives and three double destinations 13 scanf's result must be checked before using the coefficients - reports the number of assignments successfully performed - input can stop matching before all three values are assigned - untouched uninitialized variables still contain indeterminate values 14 n = scanf("%lf %lf %lf", &p, &q, &r); - if (n != 3) { report input error; return 1; } - != means unequal - if requires parentheses around its condition; there is no then keyword 15 invalid input prevents solving the problem - report the failure and return nonzero status 16 p == 0 means the equation is not quadratic - == tests equality; = assigns - return 2 distinguishes this failure from malformed input 17 compute d = discrim(p, q, r) - d < 0: report no real roots, return 0 - absence of real roots is a valid answer, not a program failure - otherwise replace d by sqrt(d), since the discriminant is no longer needed 18 print (-q-d)/(2*p) and (-q+d)/(2*p), each with %.5f - repeated root is printed twice in this simple example - terminate with return 0 - a first build without the math library can fail with undefined reference to sqrt - compilation accepted its declaration; linking could not find its definition 19 linker diagnostic can identify the driver's temporary object file - confirms separate compilation and linking stages 20 ld is the linker invoked by the compiler driver - linker reports the unresolved reference and returns failure - driver reports that unsuccessful exit status 21 on the Unix setup in this example, sqrt comes from libm - build with gcc -Wall -g qe.c -lm -o qe - supplies the declaration; -lm requests the library 22 place libraries after the source/object files that need them - one-pass archive resolution and linker options can make command order significant - do not rely on permissive behavior from an older toolchain 23 simple checks: - 1 -2 1 -> repeated root 1 - 1 2 1 -> repeated root -1 - 1 -5 6 -> roots 2 and 3 - 1 1 1 -> no real roots - 1 -1 -4 -> approximately -1.56155 and 2.56155 4.2.4 Finding the required header 1 missing declarations produce diagnostics such as implicit declaration - historical C allowed implicit function declarations - modern C requires appropriate declarations; diagnostic severity depends on mode/toolchain - using the actual declaration permits argument and result type checking 2 look up the function with man, e.g. man malloc - synopsis lists the required headers and declaration - follow documented header requirements 3 function names can collide with shell-command names - man 3 printf selects the C library function - section 2 documents system-call interfaces, e.g. man 2 close - documentation also identifies extra link options such as -lm 4.3 Basic C language facilities 1 move from introductory examples to a systematic survey of C's core features 4.3.1 Function declarations and definitions 1 translation units are compiled separately - compiler need not know the contents of other units - linker combines resulting object modules into a program 2 file scope contains declarations and definitions - introduce function, variable, constant, and type names - a name is normally visible from its declaration onward in that scope - linkage determines whether other translation units can refer to an object 3 declaration supplies information about an entity - definition additionally provides the entity itself, e.g. a function body - another translation unit can supply the definition used by a declaration 4 function definition = declarator/header plus body - return type, function name, typed parameter list - body contains declarations and statements within braces - case_up example maps ASCII 'a'..'z' to corresponding uppercase letters - && combines its two range comparisons 5 case_up's definition supplies enough information to generate its code - return type char; parameter char c - body tests the range and returns converted or unchanged code 6 char case_up(char c); declares the function without defining it - compiler can check calls using its parameter and result types - function body may appear later or in another translation unit - linker resolves the external definition 7 void return type expresses a procedure-like function - no result value; call exists for its side effect - print_n_chars(c, n) loops n times and prints c with %c - loop counter ranges from 0 through n-1 4.3.2 Variables and their definitions 1 variables defined within a function/block are local - a definition outside functions introduces a file-scope object - external linkage may let other modules refer to it - author recommends avoiding unnecessary global state 2 initializer gives an object its initial value - int local_var = 42; - distinct from assignment to an object that already exists - some objects, including arrays, can be initialized but not assigned as wholes 3 default initialization depends on storage duration - static-duration objects are zero-initialized if no explicit initializer is given - ordinary automatic locals have indeterminate values without initialization - local static variables are an important exception to the local/global shorthand 4 usual implementation model: - initialized static data in .data; zero-initialized storage in .bss - loader/startup arranges the initial data image and zero filling - ordinary locals occupy registers or stack-frame storage - reused stack storage is not implicitly cleared on every function call - reading an uninitialized automatic object is a programming error 5 static initial values can be encoded in the executable's data image - automatic initialization is performed when execution reaches the declaration - avoid unnecessary duplicate initialization followed immediately by assignment - actual generated work depends on optimization 4.3.3 Built-in types 1 book's core C subset emphasizes integer and floating-point types - characters use integer codes; strings use arrays - later C versions also provide boolean and other facilities outside this subset 2 C exposes much of the machine's numerical representation - zero means false in a condition - nonzero means true - if(a) tests the same condition as if(a != 0) for an integer 3 character constant denotes a code - 'a' has the ASCII value 97 in the examples - character arithmetic is ordinary integer arithmetic - adding two arbitrary letter codes is legal but usually meaningless 4 integer type families: - char, short, int, long, long long - signed / unsigned variants provide different ranges 5 sizeof(char) is exactly one C byte - byte width is CHAR_BIT, commonly 8 - plain char has implementation-defined signedness - signed char and unsigned char select it explicitly - these are distinct types even when plain char shares a representation 6 ASCII's 0..127 range fits both signed and unsigned eight-bit char - helps explain the historical lack of a single plain-char signedness rule 7 short, int, long, and long long are signed unless unsigned is written - signed may be explicit but is normally redundant for these types 8 short / unsigned short are commonly 16-bit - exact width is implementation-dependent - do not infer a portable binary format from that common convention 9 short int and short are equivalent type spellings - unsigned short int can be written unsigned short 10 int has historically followed practical machine/compiler conventions - often 16 bits on older targets, 32 bits on the book's i386 target - old implicit-int rules are not valid modern C practice - function results commonly travel in registers according to the ABI 11 many 64-bit systems still use 32-bit int - Unix LP64 systems commonly use 64-bit long and pointers - 64-bit hardware alone does not determine the C data model 12 long and unsigned long have the same width - long int and long are equivalent - commonly 32 bits on i386 and 64 bits on Unix LP64 systems 13 long long / unsigned long long commonly provide 64-bit integers - standard C requires at least that much range - exact width and availability in older dialects depend on the implementation 14 long is not universally large enough to store a pointer - book assumes a common Unix data model here - portable code must not generalize that assumption to every platform 15 portable size ordering: - sizeof(char) <= sizeof(short) <= sizeof(int) - sizeof(int) <= sizeof(long) <= sizeof(long long) - adjacent types may have equal sizes - exact bit widths require implementation information 16 floating types: float, double, long double - no unsigned variants - commonly single, double, and extended precision on the discussed x86 systems - precision and storage size are separate: 80-bit values may occupy 12/16 bytes - implementations can give some types the same representation 17 sqrt and many unsuffixed math functions operate on double - float is promoted to double for variadic/default-promoted arguments - this does not mean every float operation is necessarily computed as double - book generally chooses double; float can reduce storage for large arrays 18 sizeof reports object/type size in C bytes - sizeof(char) == 1 - sizeof(int), sizeof(variable), sizeof(expression) - sizeof(1) == sizeof(int) - result type is size_t 19 sizeof is an operator, not a function - type operand requires parentheses - expression operand may omit them, though parentheses can improve clarity 4.3.4 Literals 1 literal = a value written directly in source code 2 integer spellings in the subset discussed: - decimal: 29 - leading zero selects octal: 035 = 29 - 0x selects hexadecimal: 0x1d = 29, 0x7E5 = 2021 3 integer-literal type depends on base, suffix, value, and language version - octal/hexadecimal literals are not automatically unsigned 4 unsuffixed decimal integer chooses a type that can represent its value - in modern C: int, long, then long long - do not rely on the source's historical mixed signed/unsigned sequence 5 unsuffixed octal/hexadecimal candidates include signed and unsigned types - int, unsigned int, long, unsigned long, long long, unsigned long long - first suitable type is selected 6 suffixes constrain integer type selection - U: unsigned - L: long; LL: long long - 15ULL: unsigned long long - uppercase L avoids confusion with the digit 1 7 ordinary C character constants such as 'a' have type int - no ordinary literal suffix selects short or unsigned short 8 floating literals can use decimal point and exponent e/E - 1500.0, 15E2, .15e4, 15000e-1 denote the same value - default type: double - F suffix: float; L suffix: long double 9 author considers detailed numeric-literal variants less central to this course 10 character constants use single quotes - ASCII examples: 'A' = 65; '1' = 49 - character '1' is different from the integer 1 11 common escape sequences: - \n newline; \r carriage return; \t tab - \a alert; \b backspace; \f form feed; \v vertical tab - \\ backslash; \' single quote; \" double quote - numeric codes in the book assume ASCII-compatible execution characters 12 string literals use double quotes and the same escapes - apostrophe can appear directly inside a string - embedded double quote needs escaping: "Never say \"never\"" 13 'M' and "M" are different: - 'M': integer character code - "M": array containing 'M' followed by a zero byte - array commonly converts to a pointer when used in an expression 14 numeric character escapes: - '\115' and '\x4d' represent ASCII M - octal escape consumes at most three octal digits - hexadecimal escape consumes all following hexadecimal digits - separate adjacent literals when needed to stop a hexadecimal escape 15 '\0' explicitly denotes the zero character - same integer value as 0 - spelling helps show that code is dealing with character data 16 adjacent string literals concatenate during translation - "This " "is" " a string" becomes one string - useful for splitting long text over source lines 4.3.5 Operators and expressions 1 expressions have a broad role in C - assignment itself is an operator with a result value - pointer arithmetic is also part of the expression system 2 basic arithmetic: +, -, *, /, % - integer / performs integer division: 32/5 = 6 - floating / retains a fractional result: 32.0/5.0 is approximately 6.4 - % gives the remainder of integer division 3 mixed types and negative operands require knowing the conversion/arithmetic rules - % does not accept floating operands 4 author recommends making intended types explicit and keeping arithmetic easy to read - this is a style policy, not a prohibition on valid mixed/negative arithmetic 5 comparisons: <, >, <=, >=, ==, != - == compares; = assigns - if(a = 3) changes a and tests the assigned nonzero value - useful warnings help detect accidental assignment in conditions 6 extra parentheses can mark an intentional assignment in a condition - author prefers separate assignment and test for an ordinary if - assignment within some loop conditions is discussed later 7 comparison result has integer value 0 or 1 - arbitrary nonzero values count as true in conditions - avoid obscure arithmetic combinations of comparison results 8 logical operators: &&, ||, ! - && evaluates the right operand only if the left is true - || evaluates the right operand only if the left is false - short-circuiting matters when an operand has side effects 9 bitwise & and | work independently on corresponding bits - 25 & 62 = 24 - 12 | 56 = 60 - do not confuse these with && and || 10 Pascal can select logical/bitwise behavior from operand types - C uses different operator spellings 11 ~ complements bits; ^ is bitwise exclusive OR - on the discussed two's-complement targets, ~0 has value -1 - there is no separate logical-XOR operator 12 shift operators: value << count and value >> count - unsigned left shift inserts low zero bits; unsigned right shift inserts high zeros - signed negative shifts and signed overflow require care - negative signed right shift has historically been implementation-defined - arithmetic right shift of a negative value is not always C division by a power of two - shift count must be within the valid width of the promoted operand 13 x86 distinction behind the examples: - SHL/SAL share an encoding - SHR shifts zeros in; SAR replicates the sign bit 14 assignment expression has the newly assigned value - x = (y = 17) + 1 sets y to 17 and x to 18 15 assignment associates right-to-left - a = b = c = d = e + 5 propagates the calculated value through d, c, b, a 16 historical explanation: assignment leaves a useful value in a machine register - chained assignments helped simple compilers reuse that value - modern optimizers can remove redundant loads without such spelling - assignment expressions also support useful loop idioms 17 compound assignment updates an object using its previous value - a += 7 adds 7 and stores the result back in a 18 compound assignment evaluates its left-side object expression once - v[f(x)] += 10 calls f once - v[f(x)] = v[f(x)] + 10 spells two calls - difference matters for cost, side effects, and choosing the same element 19 other compound assignments: - -=, *=, /=, %=, &=, |=, ^=, <<=, >>= - apply the indicated operation and store back into the left operand 20 ++ and -- modify their operand by one - prefix forms ++i and --i return the updated value 21 postfix forms i++ and i-- also modify the object - prefix/postfix distinction concerns the expression result 22 prefix result = new value; postfix result = previous value - modification still occurs in either form 23 x = 7; y = ++x; -> x = 8, y = 8 - p = 7; q = p++; -> p = 8, q = 7 - decrement follows the same old/new distinction 24 book relates these operators to machine addressing modes that update registers - machine-level convenience helped shape C's expression syntax 25 function call and array subscript are expression operations - f() invokes a function even when it takes no arguments - function name without () normally supplies a function pointer instead - array[index] selects an array element 26 f(a, b, c) includes both the callable expression and its arguments - call syntax is not just punctuation added to a special statement 27 conditional operator: condition ? when_true : when_false - evaluate condition first - evaluate only the selected alternative - max = a > b ? a : b; 28 conditional expressions can occur inside function arguments - printf("Maximum value is %d\n", a > b ? a : b) - array-printing example selects ", " or "\n" after each element comma operator evaluates left expression, then right expression - result is the right expression's value - distinct from commas separating function arguments or declarations 29 cast syntax: (type)expression - (double)(n+1)/3.0 converts the numerator before floating division - converting after integer division cannot recover a discarded fraction 30 casts also appear with pointer expressions - their meaning and validity depend on the involved types 31 address/member operators introduced later: - &x: address of x - *p: object designated by pointer p - object.member: select a member - p->member: same member access as (*p).member - unary & / * differ from binary bitwise-AND / multiplication 32 use parentheses when precedence is not obvious - multiplication/division bind before addition/subtraction - comparisons bind before && and ||; && binds before || - postfix call/subscript/increment bind tightly - prefix unary operators bind before ordinary arithmetic binary operators - conditional operator is below logical operators - assignment is lower; comma is lowest - precedence determines grouping, not the general order of evaluation 4.3.6 Statements 1 C's statement vocabulary is small - many tasks are library calls rather than built-in statements - this subsection surveys expression statements, blocks, control flow, and jumps 2 semicolon belongs to particular statement syntax - required even before a closing brace when that statement requires it - compound/control statements do not all have an extra trailing semicolon 3 parentheses delimit control expressions - C uses no then / of delimiter after them 4 expression statement: expression; - compute an expression, normally for its side effects - discard its result value 5 x + 5; or 5; is syntactically possible but normally useless - compiler may warn that it has no effect - x = 17; is useful because evaluating assignment modifies x - assignment statement is an expression statement built from the assignment operator 6 function call used as an expression statement: - printf("Hello, world\n"); - output happens; returned character count is discarded 7 empty statement is a lone semicolon - can be used when a loop's header performs all its work - author prefers visible empty braces {} where a deliberately empty body is needed 8 compound statement groups several statements within { } - also creates a block scope for local names 9 book's style places local declarations at the start of the block - C99 and later also allow declarations among statements - scope remains confined to the enclosing block 10 swap example declares temporary t inside the if body - t is visible only where it is needed - exchange adjacent out-of-order array elements and set the change flag 11 if (condition) statement1; else statement2; - else is optional - scalar zero / null pointer means false; nonzero means true - use braces for multiple statements in either branch 12 if adds no semicolon of its own - semicolons belong to its contained statements - an expression statement before else still needs its semicolon 13 while (condition) body - test first; false exits without executing the body - after the body, test again 14 do body while (condition); - executes body at least once - condition means continue, unlike Pascal repeat-until's termination condition 15 do-while body is one statement, commonly a braced block - write the final } while(condition); together for clarity - final semicolon is required 16 C for is more general than a Pascal counted loop - its three expression slots can implement many iteration patterns 17 for(i = 1; i <= 25; i++) prints squares from 1 through 25 - first expression: execute once before looping - second: continuation test before each body execution - third: execute after the body, before the next test - all three may be omitted; the two semicolons remain - absent condition acts as true; for(;;) is an indefinite loop 18 example puts input and summation entirely in the for header - for(s = 0; scanf("%lf", &k) == 1; s += k) {} - stops when a conversion does not succeed - author shows this to explain flexibility, not as preferred formatting 19 comma expressions allow several initialization/update actions - reversing an array: i starts at 0, j at length-1 - while i < j, swap arr[i] and arr[j] - update i++, j-- - keep complex loop headers readable rather than using every possible trick 20 break; exits the innermost enclosing loop or switch 21 continue; skips the remaining loop body - while / do-while: proceed to the condition - for: perform the update expression, then test the condition 22 return ends the current function invocation - can also provide its result 23 return expression; supplies a result - return; exits a void function early - a void function can finish normally by reaching its closing brace 24 a value-returning function must supply the result its caller needs - investigate warnings about control reaching the end - main has a special implicit-success rule in modern hosted C 25 book relates return to ABI result locations - i386 integer results commonly use EAX - floating results in the discussed ABI use the x87 stack top - final result placement must survive until control returns - compiler chooses the actual register/memory schedule 26 Pascal implementations can preserve a function-result variable until return - some older conventions used caller-provided stack storage - C can also use hidden result pointers for values too large for result registers - language semantics and a particular calling convention are separate matters 27 goto transfers control to a label within the same function - no separate forward label declaration is needed - do not jump into the middle of structured logic or bypass required setup 28 label syntax in the book's C subset: name: statement - at a block end, name: ; supplies an empty statement - goto name; - author permits goto for leaving several nested constructs or centralized cleanup 29 switch(expression) selects a case label according to an integer value - case constant_expression: starts a possible entry point - default: handles unmatched values - case labels require integer constant expressions - an ordinary const-qualified object is not such a constant expression 30 case labels do not end earlier cases - execution continues through subsequent labels until a jump or switch end - example starting at case 4 prints Fourth, Fifth, then More -> fallthrough 31 use explicit transfer to keep cases independent - break exits switch - return exits the containing function - goto can transfer outside; continue refers to an enclosing loop - deliberate fallthrough should be obvious to readers 32 keep switches manageable: - choose a consistent case-label indentation - isolate a large switch in its own function - move substantial case bodies into helper functions - author advises against nested switches 4.3.7 Enumerations 1 enum introduces an enumeration - resembles Pascal's named set of values - C gives enumeration constants a close relationship to integers 2 enum colors { red, orange, yellow, green, blue, violet }; - type name is enum colors, not colors alone - enum colors one_color; declares an object of that type 3 C also uses struct tag and union tag as two-part type names - a typedef can introduce a separate one-word alias - C++ has different rules for using tags as type names 4 traditional enum constants are integer constants - first unspecified value is 0; each following unspecified value increments by 1 - red = 0 through violet = 5 in the example - integer operations on the constants are possible - enum object representation is implementation-dependent, not necessarily int 5 using enum types can improve intent and compiler diagnostics - replacing every enum-typed object with int loses that information - anonymous enum declarations can still be useful solely to name constants 6 enumeration constants can have explicit values - RGB example: red = 0xff0000, green = 0x00ff00, blue = 0x0000ff - names then carry both domain meaning and useful numeric representation 7 several enumeration constants may have the same value - aqua and cyan can both be 0x00ffff 8 explicit and implicit enum values can be mixed - unspecified value is previous value + 1 - constant expressions may refer to earlier enumeration constants - aliases need not have distinct numeric values 9 enum declaration ends with a semicolon after } - array declarations with braced initializers also end with }; - closing braces alone do not finish these declarations 10 type definition can also declare objects: - enum states { running, blocked, ready } new_state, last_state; - omitting objects still requires the declaration's semicolon - function definitions have different termination syntax 11 missing declaration semicolon can produce confusing later diagnostics - inspect the preceding type definition when an apparently unrelated line fails 4.3.8 Naming constants with enum 1 replace unexplained numeric literals with meaningful names - obvious counters/sentinels such as 0 and 1 are common exceptions 2 macros historically supplied named constants - preprocessing substitution does not obey C block scope - this can make macros inconvenient as ordinary program names 3 enum can introduce scoped integer constant expressions - enum { max_buffer_size = 1024 }; - documents meaning and gives one place to change the value - not intended here to model a useful one-value domain 4 enum naming is limited to integer constants - cannot use this mechanism for floating or string constants - choose other declarations/macros according to the intended use 5 author reserves uppercase constant-like names for macros - uses ordinary lowercase naming for enum constants - separates macro conventions from ordinary scoped identifiers 4.3.9 Enumerations and switch 1 enumeration constants are suitable case labels - switching on an enum-typed expression can enable missing-case diagnostics 2 example enum greek { alpha, beta, gamma = beta, delta } - cases for alpha and beta cover gamma's numeric value too - missing delta can be diagnosed with suitable warning options 3 adding a default can hide a forgotten new enumeration value - first investigate why a case is missing - explicitly list intentionally inactive alternatives - this documents coverage and preserves useful enum-switch warnings 4 avoid unexplained numbered cases for named application states - enum gives each state a descriptive identity 5 names make review easier than anonymous numbers such as 12 and 13 - reduce accidental disagreement between producers and consumers of state values - reader can understand a case without searching for a hidden numbering scheme 4.3.10 Local static variables 1 scope determines where a variable's name is visible - file-scope name: from declaration onward in the translation unit - block-scope name: from declaration to end of the block 2 storage duration determines how long its object exists - ordinary automatic local belongs to an active block/function invocation - static-duration storage exists throughout program execution 3 local static combines block scope with static storage duration - static int zz = 75; - one object, initialized once, not a fresh object for each call - without explicit initializer it is zero-initialized - ordinary int tt = 25 is initialized for each invocation - recursive calls have separate tt objects but share zz 4 local static preserves changes between calls - static int n = 0; print n; increment n - successive calls print 0, 1, 2, ... 5 local static hides persistent shared state behind a local name - has many of the same reentrancy/testing problems as global state - use only when persistence is intentional 6 static at file scope has a different role - gives objects/functions internal linkage within the translation unit - does not mean a function-local persistent variable 4.3.11 Addresses and pointers 1 pointers are central to C - functions receive addresses to modify caller-owned objects - array access also relies on pointer expressions and arithmetic 2 machine model: memory is a linear sequence of addressable cells - an object can occupy several consecutive cells - its address identifies the beginning of its storage 3 compiler may keep values in registers or eliminate storage when unobservable - taking an object's address requires preserving the language's addressable-object behavior 4 addresses are values that can be stored and processed - typed pointers record the type of object they can designate 5 pointer variable stores an address - "p points to x" means p holds x's address - pointer variable and pointed-to object are different objects 6 int *p; declares a pointer to int - double *q; declares a pointer to double - each declarator needs its own * - char *s1, *s2, *s3; declares three pointers - char *s1, s2, s3; declares only s1 as a pointer - one pointer declaration per line avoids that ambiguity 7 &x obtains x's address; *p designates the object addressed by p - int x; int *p; p = &x; - *p = 27 stores 27 into x 8 pointer assignment versus pointed-value assignment: - p = &x; q = &y; r = p; - p and r now point to x; q points to y - *r = *q copies y's value into x - pointed-value assignment does not change the pointers themselves 9 understand the difference before continuing - later arrays, strings, and output parameters depend on it 10 one explanation of declarators follows how a name is used - int *p declares p so that dereferencing it yields an int 11 another reading treats * in a declaration as "pointer to" - declaration syntax describes a type - unary * in an expression performs dereferencing - these related spellings occur in different grammatical contexts 12 void* is a generic object-pointer type - object pointers can convert to void* and back in C - recover an appropriate object-pointer type before dereferencing - this guarantee does not generally include function pointers 13 null pointer represents no object/function - NULL is a macro suitable for spelling a null pointer constant - representation need not be an all-zero machine address - never dereference it 14 pointer expressions can be conditions - null pointer -> false - any non-null pointer -> true - non-null alone does not prove a pointer is valid to dereference 4.3.12 Output parameters 1 C arguments are passed by value - to change a caller's object, pass its address explicitly 2 swap(int *a, int *b): - temporary t receives *a - *a = *b; *b = t; - caller uses swap(&x, &y) - a and b are local pointer copies; their targets are the caller's x and y 4.3.13 Arrays 1 int m[20] defines an array of 20 ints, indexed 0..19 - arrays do exist as C objects, despite the book's provocative opening claim - in most expressions an array converts to a pointer to its first element - int *p = m; then p[i] and m[i] access the same elements - *m designates the first element 2 pointer arithmetic advances in elements, not arbitrary bytes - m + k points to element k - adding 1 advances by sizeof(*m) bytes - m[k] equals *(m + k) - permitted arithmetic stays within one array or its one-past position - one-past pointers may not be dereferenced 3 subscript definition: a[b] == *(a+b) - therefore 17[m] can mean m[17] - use conventional array[index] spelling for readability 4 sizeof on an actual array reports its whole size - sizeof(m) == 20 * sizeof(int) - array does not convert to a pointer in this context - &m also preserves the array type, yielding a pointer to the whole array 5 whole-array assignment is not supported - array-backed strings cannot be assigned as wholes either - copying elements requires an explicit operation 6 subtract pointers into the same array to obtain element distance - p = m + 13; then p - m == 13 - result type is ptrdiff_t - unrelated-object pointer subtraction is not meaningful portable C 4.3.14 Dynamic memory 1 malloc and free are library facilities - malloc(size) requests size bytes and returns void*, or NULL on failure - actual size parameter type is size_t - double *k = malloc(360 * sizeof(*k)); - check success before using k[0] through k[359] - example fills elements with sine values at one-degree intervals - free(k) releases the allocation; no size argument is needed - pass the allocation's original pointer, not an interior address - free(NULL) is valid; double-free and use after free are errors 2 calloc and realloc provide additional allocation operations - discussed later in 4.10 3 include for allocation declarations 4.3.15 const qualification 1 const qualifies a type to restrict modification through it - does not generally turn a C object into a compile-time constant expression 2 const int iteration_count = 78; - normally initialize an object that cannot subsequently be assigned - ordinary const objects do not qualify as integer constant expressions for case labels 3 variable-length arrays use runtime size expressions in supported C modes - different from compile-time array bounds - author avoids them in this course - runtime stack requirements and implementation support must be considered 4 const int *p points to const-qualified int - p itself may change - *p cannot be modified through that pointer 5 int * const q = &x makes the pointer object constant - q cannot be reassigned - pointed-to x may still be modified 6 const-qualified pointer parameters document read-only access - function(const int *a) promises no modification through a - compiler can diagnose attempts to write through that interface 7 casts can remove a pointer's const qualification - changing an object originally defined const is still undefined behavior - qualification is a checked interface contract, not physical write protection 4.3.16 lvalues 1 x and literal 22 can yield the same value without being equivalent expressions - x can designate an object to modify - 22 is just a value, not a writable object 2 object-designating expressions can provide a location as well as a value - assignment needs the destination object - address-of needs its address - ordinary value use reads the object's stored value 3 array elements and record members also behave like variables - object-designating expressions can be much more complex than a simple name 4 example: int *ptrvec[20]; ptrvec[5] = &x; - *ptrvec[5] designates x - value use finds the pointer in element 5, then reads x through it 5 assignment/address-taking need the object's location, not merely its old value - *ptrvec[5] = value stores through the computed address - increment/compound assignment need both the existing value and destination 6 x + 1 produces a value but does not designate an assignable object - cannot use it as the destination of ordinary assignment 7 lvalue is the traditional term for an object-designating expression - name originated from left-hand side of assignment - value-only expressions are informally called rvalues 8 not every lvalue is modifiable - const-qualified object still has identity/storage - arrays are another nonassignable lvalue case - distinguish lvalue from modifiable lvalue - address-taking also has exceptions, such as bit-fields 9 C++ has additional value categories such as xvalue - they are not needed for this C discussion 4.3.17 Array initialization 1 array initializer lists elements inside braces - int m[3] = { 2, 3, 5 }; - declaration ends with a semicolon - static-duration initializers require constant expressions - automatic arrays can also use runtime initializer expressions in applicable C versions 2 omitted array bound can be inferred from its initializer - int m[] = { 2, 3, 5 }; - element count = sizeof(m) / sizeof(m[0]) for an actual array - initialization is not whole-array assignment - this formula does not determine a dynamically allocated array's length from a pointer 3 automatic local arrays can be initialized on entry - their contents must be established for each relevant execution - consider object lifetime and initialization work 4.3.18 Strings 1 text length is often unknown when the program is written - allocated capacity and currently used length are different - representation needs a way to identify the current end 2 classic Pascal short strings store length in a leading byte - that representation limits content to 255 characters - this is not a limit on every Pascal string representation 3 C string is a sequence of chars ending at the first zero byte - terminator is not part of the string's length - unused bytes after it are irrelevant to ordinary string operations - a char array without a reachable terminator is not a valid C string 4 null termination permits arbitrary length subject to storage limits - finding length requires scanning for the terminator - embedded zero cannot be part of this string representation - binary data needs a separate length; encoded text can also require other representations 5 length function receives a pointer to the first char - does not need to modify the string - parameter should therefore be const char * 6 read-only parameters accept data already exposed through const-qualified interfaces - avoids falsely promising or requiring write access 7 string literals must not be modified - C++ encodes this directly in their const-qualified array type - const char * lets one read-only interface accept such strings 8 C string literals have char array type for historical compatibility - attempts to modify them still have undefined behavior - compiler options such as -Wwrite-strings can help diagnose unsuitable interfaces 9 use pointer-to-const parameters when the pointed-to objects will not be changed 10 first string_length implementation scans by index - start i = 0; while str[i] != '\0', increment i - first zero's index equals the byte length - empty string has its terminator at index 0 11 equivalent loop forms: - for(i = 0; str[i]; i++) {} - pointer scan: start p = str; advance while *p != 0; return p - str - compiler optimization matters more than manually counting source additions - while(*p++); advances past the terminator - returning p-str afterward gives length + 1: the compact example is wrong - keep empty bodies and side effects visually explicit 12 strlen from provides standard byte-length calculation - returns size_t - implement it while learning, then normally use the recognizable library function 13 string_copy(char *dest, const char *src): - caller supplies enough destination space, including the final zero - source is read-only; destination is writable - copy nonzero characters, then explicitly store dest[i] = 0 - otherwise destination may not be terminated 14 pointer version advances dest and src while copying - parameters are local pointer copies, so advancing them does not move caller pointers - append the zero after the loop - author prefers preserving parameter values when it makes intent clearer 15 compact idiom: while((*dest++ = *src++)) {} - copies each character, including the terminating zero - assignment result determines whether to continue - pointer increments are side effects - understand the idiom, but prefer readable explicit control flow 16 strcpy from performs this kind of copying - caller is responsible for destination capacity 17 these copy routines assume source and destination do not overlap - overlap may require copying in a different direction - memmove provides overlap-safe byte copying 4.3.19 String literals 1 "Hello" supplies six char elements: five letters and a terminating zero - literal has static storage duration - implementation commonly places it in read-only storage 2 read-only literal storage can be shared between executing program instances - no private mutable copy is needed for each process 3 in most expression contexts, a string literal converts to a pointer to its first char - literal itself is an array, not inherently a pointer object 4 C and C++ differ in literal element qualification - C char array versus C++ const char array - neither permits modifying literal contents 5 literal indexing follows normal array/pointer rules - "Abrakadabra"[4] yields 'k' - *"Abrakadabra" yields 'A' - use direct or named expressions where they communicate the purpose better 6 char str[] = "Hello" initializes a separate six-element array - equivalent contents: { 'H', 'e', 'l', 'l', 'o', 0 } - mutable unless the array is const-qualified - char *ptr = "Hello" instead initializes a pointer to literal storage 7 array and pointer have different operations and sizes - ptr can be reassigned; array str cannot be assigned as a whole - sizeof(str) is 6; sizeof(ptr) is pointer size - str[4] = 0 changes the mutable array into "Hell" - modifying ptr[4] when ptr addresses the literal is undefined behavior 4.3.20 Command-line arguments 1 main can receive int argc, char **argv - argc: argument count, conventionally including invocation name - argv: array of pointers to NUL-terminated argument strings - argv[argc] is NULL - argv[0] conventionally identifies how the program was invoked - user arguments normally occupy indices 1 through argc-1 - %s prints a string supplied by pointer - shell quoting determines which spaces are inside one argument - iterate by argc or by the final NULL pointer 4.3.21 Sequencing side effects 1 several side effects in one expression require attention to sequencing - source appearance alone does not establish execution order 2 f(h1(), h2(), h3()) evaluates the arguments before entering f - order among argument evaluations is not generally specified - calling-convention stack order does not determine C evaluation order 3 ordinary arithmetic operands also lack a general left-to-right guarantee - a[i] = i++ has an unsequenced read/modification conflict in C - this is undefined behavior, not merely a choice between writing a[7] or a[8] 4 b = (a += 5) + (a *= 2) modifies a without the required sequencing - undefined behavior; no computed result is a portable prediction 5 reversing a guessed operand order does not repair that expression - analyzing possible machine schedules cannot give undefined code a guarantee 6 book reports one compiler producing a = 12, b = 24 - illustrates why observations from one build cannot establish language semantics - a warning should prompt rewriting the expression 7 full-expression boundaries complete preceding side effects - expression statement - control expressions in if / loops / switch - return expression - separately evaluated expressions in a for header 8 sequencing also occurs within selected operators - && / ||: left operand completes before evaluating the right, if needed - ?: condition completes before the chosen alternative - comma operator: left completes before right - function arguments finish before the called function body begins 9 author recommends limiting side effects in each expression - separate steps when their order matters - even one modification can be unsafe if mixed with an unsequenced read - precedence and parentheses alone do not create sequencing 4.3.22 Selected examples 1 two worked programs connect the C facilities to earlier Pascal/assembly examples 2 recursive Tower of Hanoi: - solve(source, target, intermediate, n) - n == 0: return - move n-1 from source to intermediate - print the move of disk n from source to target - move n-1 from intermediate to target - main requires a positive disk count from argv[1] - example uses atoi; robust numeric validation needs a checked conversion 3 fprintf(stderr, ...) sends diagnostics to the error stream - same formatting approach as printf with an extra stream argument - keeps failures separate from the program's ordinary output 4 wildcard match(str, pat) uses pointer advancement - pattern ends: success only if input also ends - ?: require one input character - ordinary character: require equality - *: recursively try remaining pattern against every remaining input suffix, including the empty suffix - stop the search on success or after exhausting the input alternative splits star handling into starmatch - match handles one pattern case and recurses on remaining characters - starmatch tries successive input suffixes - mutual recursion requires a declaration before the first cross-call 4.4 Standard input/output functions 1 high-level standard I/O is provided through - library facilities sit above the core language and OS interfaces 4.4.1 Character input/output 1 standard input/output need not be keyboard and screen - caller can redirect them to files, pipes, or other streams 2 getchar() reads one byte from stdin - returns int, not char - must represent both a successful byte and a no-byte result - end of file is a normal possible input outcome 3 successful byte is returned as unsigned char converted to int - on an eight-bit-byte target, values 0..255 - every byte value can occur in binary input - EOF must therefore be distinguishable from those 256 values 4 EOF is a negative integer macro, commonly -1 - use EOF rather than assuming a particular numeric value 5 example reads until EOF and prints OK for each newline - int c; while ((c = getchar()) != EOF) { ... } - assignment in the condition avoids duplicating getchar calls - parentheses ensure comparison uses the assigned character value 6 line-length counter: - initialize n = 0 - newline: print n and reset it - other byte: increment n - this example reports only lines terminated by newline - keep c as int so a byte such as 255 is not confused with EOF 7 check the int result before converting it to char - premature narrowing loses the distinction between data and EOF 8 putchar(c) writes one byte to stdout - argument is converted to unsigned char - do not treat out-of-range integers as additional character values 9 putchar returns the written character on success or EOF on error - checking output errors matters when successful delivery is required 10 untilspace example prints each line's prefix before the first space - pr flag starts true - space clears pr - other characters print only while pr is true - newline always prints and resets pr for the next line 4.4.2 Formatted input/output 1 printf(const char *format, ...) is variadic - format describes the additional arguments - arguments must match the required types after default promotions 2 printf interprets ordinary characters and % conversion directives - d/i: signed decimal; u: unsigned decimal; o: octal; x/X: hexadecimal - f/F: fixed-point; e/E: scientific notation; g/G: precision-dependent choice - c: character; s: string; p: void* pointer representation - %% prints one percent sign without consuming an argument 3 conversion layout: % flags width .precision length specifier - width: minimum field size - -: left align; 0: numeric zero padding - +: always show sign; space: reserve a position for a positive sign - #: alternative representation, e.g. base prefixes or retained decimal point - default padding is spaces on the left 4 width does not truncate a number - %3d applied to 1234 still prints all four digits 5 precision depends on conversion - f/e: digits after decimal point - g: significant digits - s: maximum number of bytes printed from the string - [%7.5s] with abrakadabra -> [ abrak] 6 integer precision gives a minimum number of digits - width can add spaces outside those zero-padded digits - [%6.4d] with 12 -> [ 0012] 7 length modifiers select the expected numeric type - l: long; ll: long long; L: long double - h / hh: short / char conversion after integer argument promotion - variadic float arguments promote to double - small integer arguments undergo integer promotion - this is not a claim that all prototyped function parameters are promoted 8 % #7.4Lg combines: - space and # flags - width 7, precision 4 - long double with g representation 9 printf can obtain width/precision from int arguments - printf("%*.*f", width, precision, value) - each * consumes its own argument before the formatted value 10 scanf is also variadic, but its formatting rules differ from printf - additional arguments are destination pointers, not values to print 11 scanf conversion directive contains %, optional *, width, length, specifier - width is a maximum input width - no printf-style precision field - * suppresses assignment and consumes no destination argument 12 whitespace in a scanf format skips input whitespace - can match spaces, tabs, and newlines - may keep waiting for a later non-whitespace character 13 ordinary format characters must match input literally - mismatch stops processing - unsuccessful conversions also stop; caller must decide how to recover 14 scanf pointers must match the destination type exactly - float* and double* are not interchangeable - integer promotions of values do not resize pointed-to storage 15 scanf distinctions: - %d: decimal integer; %i: infer decimal/octal/hexadecimal from prefix - %f: float*; %lf: double* - printf uses double for both corresponding floating conversions 16 numeric scanf lengths: - h: short; hh: signed/unsigned char - l: long; ll: long long - do not use the book's nonportable L-for-integer spelling - floating L: long double - %c reads characters without appending a zero terminator - %s reads a whitespace-delimited word - %[set] and %[^set] use included/excluded character sets - include ] first when it is a member of the scan set 17 string input requires an explicit bound - char buf[100] needs width at most 99 for %s or %[...] - remaining byte holds the terminating zero - missing width permits writing beyond the destination array 18 scanf cannot receive width through a separate * argument - its * means assignment suppression - dynamically building a format string is possible but complicates input handling 19 author limits scanf to simple programs - detailed validation and useful error recovery often need explicit parsing 20 scanf returns successful assignments, not bytes consumed - expected three numbers: require result 3 - 0: matching failed before any assignment - 1 or 2: partial success - EOF: input failure before the first conversion/assignment succeeds - always inspect the return value before using destination objects 4.4.3 Working with streams 1 opening a file creates another I/O stream - standard streams are only three predefined instances 2 FILE* identifies library-managed stream state - FILE's internals are implementation-specific - use the documented functions rather than accessing its internal fields 3 copying a FILE* copies a reference to stream state, not the state itself - pointers can be assigned, passed by value, and returned - duplicate references still designate the same stream 4 stdio has separate function names for operations on an explicitly supplied stream 5 fopen(name, mode) returns a FILE* - both arguments are read-only strings - in Unix, leading / gives an absolute path; otherwise resolve from current directory 6 fopen modes: - r: read existing file - r+: read/write existing file - w / w+: create or truncate, with write / read-write access - a / a+: create if needed; writes append, with optional reading - use positioning/flush rules when changing direction on an update stream - do not assume identical initial read-position behavior for a+ on every system 7 b selects binary mode where text/binary streams differ - normally has no effect on Unix - can matter for byte preservation on other systems 8 NULL means opening failed - reasons include missing paths, permissions, and other resource failures - check before performing any stream operation 9 real input/output failures are part of normal program design - decide both how to identify the cause and how to respond 10 error policy depends on the caller's context - main may report an error and exit unsuccessfully - reusable library code should normally return failure to its caller - library should not arbitrarily print or terminate the whole application 11 errno records errors for interfaces that document using it - include - ENOENT: missing file/path component - EACCES: insufficient permission - EROFS: attempted write to read-only filesystem - inspect errno after the operation reports failure 12 function documentation lists possible errors - handle important special cases explicitly - strerror(error_code) supplies a corresponding diagnostic string 13 perror(context) prints a contextual errno diagnostic to stderr - example: fopen failed -> perror(filename) - output includes context, colon, and error description - locale can affect message language 14 author prefers English diagnostics while developing programs - locale selection is a tooling preference, not an I/O requirement 15 fprintf(stderr, ...) prints a custom diagnostic - error reporting need not be limited to errno-based messages fclose(stream) closes the stream and releases its library resources - 0 on success; EOF on failure - stream must not be used afterward 16 check fclose after writing - earlier output may have succeeded only in filling a library buffer - flushing during close may reveal the actual write failure 17 kernel buffering can similarly delay errors until a low-level close/writeback operation - library buffering and kernel buffering are distinct layers 18 fgetc(stream) / fputc(character, stream) generalize getchar / putchar - same byte-versus-EOF distinction - example copies up to ten newline-terminated lines between named files - validate arguments and both opens - close the input if opening the output fails - count newlines while copying; close both streams afterward - complete code also checks read, write, and close failures ungetc(character, stream) pushes a character back for a later read - at least one character of pushback is guaranteed - need not be identical to the character previously read - larger pushback capacity is implementation-dependent; check failure 19 lexical scanner may read one character beyond a token - after reading 756 from 756+27, the + belongs to the next token - pushback lets a separate token-reading function leave it for its caller 20 an explicit lookahead buffer is an alternative to ungetc - author treats pushback as a convenient small-program technique 21 fprintf / fscanf add a FILE* before the format string - formatting/conversion rules remain those of printf / scanf - example writes angle, sine, and cosine for 0..359 degrees - convert degrees to radians; link the math library as needed intfilesum reads integers from an already opened stream - output pointers receive sum and count - initialize both to zero - continue while fscanf assigns one number - add n and increment *count; parentheses in (*count)++ matter stdin, stdout, stderr identify the standard streams - they can be passed to functions accepting FILE* - the same helper can therefore work on a file or on standard input 22 ungetc(c, stdin) supplies standard-input pushback - a separately named standard-input-only function is unnecessary 4.4.4 Reading and writing lines 1 text streams commonly contain newline-separated lines - library provides line-oriented operations alongside byte-oriented ones 2 fputs(s, stream) outputs a string without interpreting a format - does not add a newline - percent signs are ordinary characters - nonnegative result on success; EOF on error - successful result is not guaranteed to equal string length 3 fgets(buffer, size, stream) needs the destination capacity - user input can be longer than any fixed buffer - capacity is a bound on storage, not a prediction of the input length 4 with a usable positive capacity, fgets reads at most size-1 bytes - stops after newline, at EOF/error, or at the capacity limit - retains a newline if read - appends zero on a successful read and returns buffer - NULL means failure/EOF before a successful result; inspect stream status - do not assume valid buffer contents after a read error 5 string50 example reads into char buf[51] - searches each chunk for newline - newline present: treat it as a complete line - newline absent: reject the chunk as overlong/incomplete - source's label "50 characters" includes the newline in the accepted chunk - a final line without newline needs a separate policy 6 rejected line handling: - output a blank line - consume remaining input through newline or EOF - avoids treating the remainder as another independent line 7 accepted line handling: - replace its newline with zero - print the content inside brackets, then a newline 8 puts(s) outputs to stdout and adds a newline - unlike fputs, caller need not include \n for this purpose - historical gets had no capacity parameter 9 do not use gets for input - modern standard C removed this unsafe interface 10 gets cannot know the destination's bounds - input length is controlled externally - arbitrarily large allocation does not establish an upper bound on input 11 writing beyond a local array can corrupt nearby stack state - in the book's conventional stack layout, this may include return addresses - a crash is only one possible consequence 12 crafted overlong input can redirect program control flow - illustrates why unchecked input is a security problem, not just a reliability issue - actual exploitability depends on layout and platform protections 13 memory corruption can make a program act outside its intended function - consequences depend on the privileges and role of the program 14 buffer overflow exploit is the name for exploiting an out-of-bounds write - preventing the invalid write is the fundamental requirement 15 terminology aside: hacker also has a longstanding noncriminal programming meaning - author emphasizes that software security extends beyond cryptography 16 use bounded input interfaces instead of gets - historical availability is not a reason to retain an unsafe call 17 passing an uninitialized pointer does not create input storage - pointer must first refer to an adequately allocated object 18 storage always has a size, whether static or dynamically allocated - omitting a size argument only prevents the callee from enforcing that size 19 arbitrary-length input needs managed growth - read chunks/characters and expand a buffer or another data structure - portable ISO C and POSIX provide different sets of library facilities - POSIX getline can manage a growing buffer; the book develops the mechanism manually 4.4.5 I/O buffering 1 stdio input can fetch a block from the OS and return one requested byte - subsequent getchar/fgetc calls consume the remaining library buffer - avoids a system call for every byte 2 stdio output accumulates data before larger writes to the OS - reduces system-call overhead even when the program uses fputc repeatedly 3 input buffering is often transparent to a simple stream-processing program 4 output buffering can hide diagnostic messages before a crash - absence of visible text does not prove the print call was never reached 5 fflush(output_stream) explicitly sends pending library output onward - check failure when output integrity matters - flushing stdio does not itself guarantee durable storage on disk 6 fflush(stdin) is not a portable way to discard interactive input - input-stream extensions and their semantics vary 7 output is also flushed when required by a full buffer and by normal termination - abrupt termination need not flush library buffers 8 terminal output is commonly line-buffered rather than fully buffered - terminal identity is different from a promise of a physical keyboard/screen 9 line buffering flushes on newline - terminal input can also trigger flushing of line-buffered output - helps display prompts before waiting for input 10 precise automatic flushing conditions depend on the stream setup - explicitly fflush a prompt when immediate visibility is required 11 stderr is normally unbuffered and initially not fully buffered - its buffering mode can be changed - use explicit flushing when the program's required behavior depends on it 12 setbuf / setvbuf configure buffering before ordinary stream operations - full buffering, line buffering, or unbuffered mode - setvbuf can also specify a buffer and its size - supplied buffer must remain valid for the stream's use 13 BUFSIZ and actual system-call transfer sizes are implementation details - book's 8 KB / 4 KB / 1 KB observations describe a particular library setup - do not hard-code those observations as universal stdio behavior 4.4.6 Formatting into and scanning from strings 1 sprintf(buffer, format, ...) writes formatted text into memory - same format interpretation as printf - caller must ensure enough room for the entire output and final zero - bounding each %s alone does not bound other parts of the complete output 2 snprintf also receives destination capacity - bounds writes and supports detecting truncation through its result - preferred when formatting into a finite buffer 3 availability of declarations depends on language mode and library interfaces - old strict-C environments may lack snprintf - check target requirements rather than assuming all libraries are identical 4 format a number or record before sending it through a lower-level interface - first build its textual representation in a buffer - then pass those bytes to an OS write operation 5 sprintf's successful return is output length excluding the final zero - related formatting functions return an error indication on failure 6 sscanf(source_string, format, ...) parses existing text - destinations and conversion rules follow scanf - source terminator supplies the end-of-input boundary - inspect successful-assignment count and distinguish input failure 7 author prefers more explicit parsing when scanf-style diagnostics are inadequate 4.4.7 Block input/output 1 C programs can process both textual and binary files 2 fgetc/fputc also handle arbitrary bytes - binary record files often need fixed-size blocks and random positioning - fixed record sizes let offsets be computed like array indices - pipes/sockets remain streams and do not acquire random access merely from binary encoding 3 book often prefers low-level OS I/O for binary random-access workloads - this is a design choice; stdio also supports binary data 4 stdio's main conveniences are formatting and buffering - formatting is valuable for text - buffering helps sequential streams - frequent seeking can reduce that benefit 5 fread/fwrite provide block operations within the FILE* interface - next part studies corresponding OS-level services 6 fread(ptr, size, count, stream) / fwrite(ptr, size, count, stream) - size: bytes per element; count: requested elements - buffer must hold at least size * count bytes - size/count and result use size_t, not the simplified int signatures in the book 7 result counts complete elements transferred, not bytes - short result can reflect EOF or an error - partial progress can occur before failure; result need not be zero 8 feof(stream) reports an encountered EOF condition - ferror(stream) reports an I/O error indicator - check the read's result first; feof does not predict whether another read will succeed 9 fseek(stream, offset, whence) changes a seekable stream's position - SEEK_SET: relative to start - SEEK_CUR: relative to current position - SEEK_END: relative to end - returns 0 on success, nonzero on failure - terminals and pipes are not ordinary seekable files - text-stream positioning can have additional portability restrictions 10 using size = 1 makes the transferred-element count a byte count - often convenient for general-purpose block copying 4.5 Structures and linked data structures 1 linked lists and trees need compound objects as well as pointers - C struct corresponds to the Pascal record - this chapter adapts earlier dynamic-data-structure techniques to C 4.5.1 Structures 1 structure combines named fields that can have different types - array elements instead all have the same element type 2 structure declaration: - struct tag { field declarations } optional_object_names; - full type name is struct tag - object.field selects a member - semicolon terminates the declaration 3 student example combines: - name and group as bounded char arrays - sex code, birth year, major code, year of study - floating-point average mark - fields are assigned individually, with string data copied into their arrays - a braced initializer can initialize all fields in declaration order - unlike arrays, structures of the same type can be assigned as wholes 4 structure tags use a separate C namespace from ordinary identifiers - a tag and variable/typedef can share a spelling - choose names that remain understandable to readers 5 structure size can exceed the sum of its field sizes - fields must satisfy implementation/architecture alignment requirements - misaligned access may be slow or unsupported on a target 6 compiler inserts padding between fields where needed - a char followed by int may require intervening bytes - padding is not another user-declared field 7 alignment affects both total size and member offsets - do not infer either simply by adding source-level type sizes 8 use sizeof to allocate storage for the actual compiled structure - struct student *ptr; - ptr = malloc(sizeof(*ptr)); - equivalent size expression: sizeof(struct student) - check allocation failure before accessing fields 9 members retain declaration order, but padding and ABI details vary - first ordinary member begins at the structure's start - raw structure bytes are not a portable persistent/network representation - recompilation for another data model can change layout 10 serialize explicitly when exchanging data across implementations - text is one option - binary formats need defined field positions, widths, and byte order - decode bytes into native values instead of treating them as an arbitrary struct image 11 structures can be assigned, passed, and returned by value - copies include the values of contained fields - pointer parameters avoid copying large structures - an output-structure parameter is another interface choice 12 book discusses using memcpy to make structural copying conspicuous - ordinary structure assignment is also valid C - both mechanisms make shallow copies of pointer fields - neither duplicates owned dynamic objects automatically - choose an explicit ownership policy before copying 13 field access through a pointer can be written (*p).year - parentheses are needed because . binds more tightly than unary * - *p.year instead tries member access on p itself 14 p->year is the concise equivalent of (*p).year - left operand must point to an appropriate structure/union 15 bit-fields assign a width to an integer member - unsigned io_error:1; stores a one-bit flag - unsigned count:4; can represent 0..15 - consecutive fields may share an allocation unit 16 bit-field layout is implementation-dependent - allocation-unit size, bit order, alignment, and boundary crossing can vary - plain int bit-field signedness can also vary - do not infer a portable packet layout from these declarations 17 implementations may support additional bit-field base types - example uses unsigned char fields to obtain byte-sized packing on its target - verify actual size rather than assuming the extension behaves identically elsewhere 18 understand bit-fields when reading code - explicit masks and shifts are another way to represent flags - author's preference for masks is a design/style choice 4.5.2 Singly linked lists 1 C examples assume the earlier Pascal list algorithms are understood - main change is how structures and pointers are expressed 2 node contains payload and pointer to next node - struct item { int data; struct item *next; }; - last next = NULL - head = NULL represents an empty list build a list from an integer array by appending: - first and last start NULL - allocate node, set data, set next = NULL - nonempty list: link old last->next to new node - empty list: make new node first - update last; return first after processing the array - real code must handle allocation failure and release any partial result 3 alternative: scan array backward and prepend each element - new->next = first; first = new - preserves the array's original order in the final list - no separate empty-list branch is needed recursive construction: - length 0 -> NULL - create a node holding the first array element - next = recursive result for arr+1 and len-1 - arr+1 denotes the remaining array starting at its second element 4 summing a list: - iterate p from head through p->next until NULL - accumulate p->data - const struct item * expresses read-only node access - recursive equivalent: empty -> 0; otherwise data + sum(next) - concise recursive form does not remove its stack-depth requirements delete nodes without reading freed memory: - save current node, advance head, then free saved node - or save next pointer, free current, then advance to saved next - otherwise either the next address or the current allocation can be lost 5 recursive deletion: - empty list -> return - delete the tail, then free the current node - iterative deletion avoids recursion depth on a long list filter example removes every negative-valued node - must also work when the first or several consecutive nodes are removed 6 deletion changes the pointer that leads to the current node - that pointer may be the head variable or a previous node's next member - store its address to handle both cases uniformly 7 struct item **pcur tracks the incoming link - initialize pcur = &first - while *pcur is non-NULL: * negative: save *pcur, replace *pcur with its next, free saved node * retained: advance pcur to &(*pcur)->next - after deletion do not advance: the next node is already current function delete_negatives(struct item **pcur) can use that same loop - caller passes &first because the head may change - parameter directly supplies the first link to examine recursive filter first processes the tail through &node->next - then unlinks/frees the current node if its value is negative - an empty link is the base case alternative API returns a replacement head - first = delete_negatives(first) - recursively replace next, then return current node or its successor - caller must install the returned pointer 8 author dislikes this replacement-head convention despite its popularity - distinguishes a valid C interface from his preferred decomposition style 9 author prefers the pointer-to-pointer form because the function completes the update - caller is not required to perform a separate head assignment afterward - later section examines output parameters and result values more broadly 4.5.3 Doubly linked lists 1 node contains previous and next links - first/last identify the ends - a known node gives access in either direction - insertions/deletions must maintain both links and the endpoint pointers 2 struct dbl_item contains double data plus prev and next pointers - first = last = NULL initially - prepend: new prev = NULL, next = old first * old first exists -> update its prev * otherwise set last to new node * set first to new node - append is the mirror operation using last conditional expressions can select which pointer field to update - *(first ? &first->prev : &last) = tmp; - author shows this compact form for recognition, not as recommended style 3 remove first only after checking it exists - save node, advance first - new first exists -> set its prev = NULL - otherwise clear last too - free the saved node - removing last is symmetric - repeating removal deletes the whole list - alternative traversal can free each predecessor, then the final saved last node 4 insertion relative to an existing current node: - before current: new next = current, prev = current->prev - update current->prev and previous neighbor's next, or first - after current is symmetric, updating next neighbor or last - current must be valid; allocation must succeed before links are changed unlink current by repairing both directions - previous neighbor's next, or first, receives current->next - next neighbor's prev, or last, receives current->prev - node is now detached even though its own fields still contain old links if traversal position is no longer needed: - free(current); current = NULL; to continue traversal, save the successor/predecessor before freeing current - forward scan uses next - backward scan uses prev - never read a field after its node has been freed 4.5.4 Binary search trees 1 binary-tree node contains payload and left/right child pointers - NULL represents an empty subtree 2 struct node contains int val and left/right pointers - recursive inorder traversal: * empty -> return * traverse left * print current value * traverse right iterative traversal must store the information recursion would remember - explicit stack entry: node pointer, state, next stack entry - start: left subtree still to visit - left_visited: print value, then visit right - completed: pop and free the traversal frame - update state before pushing a child so resumption happens at the right step explicit stack models recursive function frames - node parameter corresponds to the saved node pointer - return address implicitly records which subtree has already been processed - recursion hides this bookkeeping rather than eliminating it 3 explicit traversal state is useful for pausing and resuming between requested values - recursive traversal is simpler when the whole walk occurs in one call - performance and space depend on the concrete stack implementation 4 search-tree ordering: - smaller values in left subtree, larger values in right subtree - insertion receives struct node **root so it can replace an empty subtree link - recurse using &node->left or &node->right 5 insertion base case: *root is NULL - allocate and initialize a node - assign the incoming link - both child links start NULL - handle allocation failure in complete code 6 equal value: example does nothing - alternative policies may report a duplicate or maintain a frequency count 7 smaller value -> recursively insert left - larger value -> recursively insert right - recursion eventually finds the appropriate empty child link 8 plain BST shape depends on insertion order - sorted input can turn it into a chain - lookup then loses the expected logarithmic advantage - balanced alternatives include red-black and AVL trees 9 some workloads produce acceptable shapes without balancing - another alternative for strings is a trie - each level follows the next character - path length follows key length rather than a binary comparison-tree shape 4.5.5 Unions and tagged variants 1 union members overlap the same storage - syntax resembles struct, but uses union - access through . or -> - writing one member replaces the representation held in that shared storage 2 conceptual interpretation: values can belong to one of several alternative member types 3 union sample_un can hold an int, a double, or char str[16] - type name includes union - all members begin at the same address - size accommodates the largest member and any required alignment/padding 4 unions can save storage for mutually exclusive alternatives - program must know which member currently represents meaningful data - confusing members is a source of subtle errors - author's dismissal of memory savings is a design opinion 5 union can illustrate an integer's underlying byte representation - store an int, examine an unsigned-char array of sizeof(int) bytes - observed byte order depends on the platform placing a union inside a struct allows a separate discriminator/tag - surrounding fields indicate which union member to use 6 expression-token example: - op_type describes integer, double, variable name, or operator - union stores int i, double d, or name array - next links tokens into a list - enum constants name the payload variants - operator-character tags need no union payload - keep tag and selected member consistent 7 anonymous union can expose its members directly within the enclosing structure - union has neither a tag nor a named enclosing member - example accesses i, d, or var directly - these fields still share storage - standardized in C11; earlier availability depended on extensions 8 author avoids anonymous unions in this course - still useful to recognize their syntax in other code 4.5.6 typedef 1 typedef introduces an alias for a type rather than a new object - typedef int *intptr; names pointer-to-int type - typedef int integral_number; aliases int - libraries use aliases for implementation-dependent types - intptr_t, where supplied, is an integer type capable of pointer round-trip conversion 2 structure aliases can avoid repeating struct in declarations - typedef struct tag_mystruct { ... } mystruct; - mystruct *ptr; uses the alias - during the definition, a self-link can use struct tag_item *next - alias declared after the closing brace is not available earlier inside that definition - tag and typedef may share a name because C gives them separate namespaces - typedef struct item { struct item *next; } item; is also valid in C++ - the book's claimed C++ conflict for that matching alias is not a general restriction 4.6 The macroprocessor 4.6.1 Preliminary information 1 macroprocessor / preprocessor: - transforms source text before the compiler analyzes C constructs - directives: built-in commands such as #include - macro calls: uses of macros defined by the programmer - output: source with directives processed and macro calls expanded 2 preprocessor directive: - written on a separate logical line - first non-whitespace character must be # - convention: place # at the beginning of the line - directive itself does not become an instruction in the compiled program 3 macro names: - identifiers associated with programmer-defined macros - processed in addition to explicit # directives 4 preprocessing works with tokens before C syntax, types, and scopes are analyzed: - tokens: identifiers, keywords, operators, punctuation, literals - count++ -> identifier count and operator ++ - a string literal is one token; its contents are not macro-expanded - comments do not contain active macro calls - macro substitution matches whole identifiers, not parts of names -> macros do not obey C block / function scope 4.6.2 Macro definitions and calls 1 #define NAME replacement: - introduces a macro name and its replacement tokens - #define BUFFERSIZE 1024 -> buffer[BUFFERSIZE] becomes buffer[1024] - #define HELLOMSG "Hello, world\n" -> name expands to a string literal - #define MALLOCITEM malloc(sizeof(struct item)) -> name expands to a call - later occurrences of these names are macro calls / expansions 2 macro replacement need not be a complete expression or statement: - IF -> if( - THEN -> ) { - ELSE -> } else { - FI -> } -> several macros can assemble one C construct book discourages disguising ordinary C syntax this way - more complicated code generation can sometimes justify partial constructs 4.6.3 Naming conventions 1 macros ignore scope: - a header defines count as 35 - later local declaration int count; becomes int 35; - compiler reports that an identifier was expected - original source visibly contains an identifier, which makes diagnosis confusing - adding a macro in a shared header can break previously valid functions 2 convention: uppercase macro names, lowercase ordinary identifiers - uppercase makes potentially surprising substitution visible - distinct naming conventions reduce collisions with variables / types / functions 3 uppercase is a programmer convention - C itself allows any valid macro identifier 4 book's historical explanation for uppercase constants: - named integer constants originally commonly used #define - enum later provided integer constants that obey scope - uppercase naming carried over from macros to enum constants - book criticizes treating this inherited convention as a language requirement 5 enum constants behave as ordinary scoped identifiers: - enum { absolutely_safe_constant = 756 }; - lowercase with underscores fits the book's ordinary identifier convention - replacing a macro with an enum can remove unintended textual substitution public interfaces may require keeping an existing uppercase name: - other programs / documentation already use that name - enum { VERY_DANGEROUS_MACRO = 756 }; keeps the name without a macro - such replacement also changes preprocessor availability: enum names cannot substitute for macros in #if / #ifdef use 6 mixed historical naming creates another consideration: - some constants must retain uppercase public names - uniform naming can justify uppercase for newly introduced enum constants too -> uppercase enum names are not inherently incorrect 7 follow an existing project's conventions - for a new project, choose a consistent rule deliberately - distinguish the naming convention from macro behavior / language rules 4.6.4 More advanced macro facilities 1 function-like macro: - #define MAX(A, B) ((A) > (B) ? (A) : (B)) - MAX(x, 15) substitutes x for A and 15 for B - in the definition, no space between MAX and ( - otherwise (A, B) becomes part of an object-like macro's replacement 2 parentheses protect an expression macro from surrounding precedence: - square(x) defined as x * x -> square(z+1) becomes z + 1 * z + 1 - BADMAX(A, B) defined as A > B ? A : B -> BADMAX(100, 10) * 5 becomes 100 > 10 ? 100 : 10 * 5 -> 100 - enclose each argument occurrence in parentheses - enclose the whole replacement expression in parentheses parentheses do not prevent repeated evaluation: - MAX(f(x), g(x)) calls both functions for the comparison - then calls the selected function again -> arguments with side effects can change behavior unexpectedly 3 book recommends avoiding macros when ordinary C facilities suffice multiline macro: - end each continued physical line with \ immediately before newline - adjacent string literals join into one string - HELP_TEXT can contain several usage-message lines, each ending in \n - missing command-line argument -> fputs(HELP_TEXT, stderr), return 1 macros can generate families of similar functions: - array sum: start at zero, add *a, advance a, decrease remaining count - copying this function for int / double / long duplicates its logic - MAKE_ARRAY_SUM_FUNCTION(FUNNAME, TYPE) generates one typed function - invocations choose int_array_sum / int, double_array_sum / double, etc. token pasting with ##: - TYPE ## _array_sum joins tokens into a generated function name - int -> int_array_sum - multiword types do not make suitable pasted identifiers -> use a one-word typedef name or pass the function name separately 4 multiline macro difficulties: - trailing whitespace after \ is nonportable and can break continuation - macro errors can be reported at the expansion site - inspect the definition and expanded tokens when the call looks correct 5 compiler option -E: - stop after preprocessing - write expanded source to standard output - output also contains included headers, so it can be large 6 stringification with # before a macro parameter: - #define VAR_PRINT(x) printf("%s = %d\n", #x, x) - VAR_PRINT(abrakadabra) prints its name and integer value - #x supplies "abrakadabra"; x supplies the expression's value adjacent string literals allow a shorter replacement: - printf(#x " = %d\n", x) 4.6.5 (*) Macros and do { } while(0) 1 statement-like macro should work wherever one statement is allowed: - may contain several operations, local variables, or an if / else - caller should write MYMACRO(argument); as with an ordinary function call - f(arg); g(); expands to several statements - { f(arg); g(); } followed by the caller's semicolon can break if / else solution: #define MYMACRO(arg) do { f(arg); g(); } while(0) - loop body executes once because the condition is checked afterward - zero condition prevents another iteration - caller's semicolon completes the do / while statement -> expansion behaves syntactically as one statement 2 book treats this idiom as a workaround made possible by existing C syntax - do / while supplies both grouping and the required final semicolon 4.6.6 Conditional compilation directives 1 conditional compilation selects which source fragments reach the compiler: - exclude code temporarily - choose features or alternative algorithms - build different program variants without editing source files 2 same general mechanism appeared in the Pascal and NASM examples - book relates their conditional directives to the C preprocessor tradition 3 #if 0 ... #endif temporarily excludes a source fragment: - useful when the fragment already contains /* ... */ comments - C block comments do not nest - excluded C statements may be syntactically incomplete - lexical structure must remain valid: no unterminated strings / comments - change 0 to 1 to include the fragment again 4 #if ... #else ... #endif selects one of two implementations: - string_copy example: array indexing versus advancing pointers - both copy the terminating zero after the character loop - #if USE_INDEX_IN_STRING_COPY selects by a macro value - undefined identifiers left in a #if expression evaluate as zero - variables, functions, and enum constants cannot supply #if values set the option externally: - gcc -Wall -g -D USE_INDEX_IN_STRING_COPY=1 prog.c -o prog - source does not need temporary changes to switch builds -> configuration changes need not clutter source history / reviews 5 #ifndef can provide a default without overriding a supplied option: - #ifndef USE_INDEX_IN_STRING_COPY - #define USE_INDEX_IN_STRING_COPY 1 - #endif - prior header / command-line definition keeps its value - otherwise the source supplies the default #ifdef / #ifndef also commonly control debugging output 6 #if requires an integer expression evaluable during preprocessing: - arithmetic, remainder, comparisons, logical / bitwise operations, ?: allowed - no assignments, ++ / --, function calls, address operations, casts, comma, or sizeof - macro replacement supplies values before expression evaluation 7 defined(NAME) tests whether a macro exists: - parentheses optional, but useful for readability - #if defined(DEBUG_PRINT) && DEBUG_PRINT > 7 - #ifdef NAME -> #if defined(NAME) - #ifndef NAME -> #if !defined(NAME) 8 #elif adds another conditional branch: - FOR_PETROV defined -> first customer's implementation - otherwise FOR_SIDOROV defined -> second customer's implementation - otherwise -> default implementation macros can serve only as presence / absence flags: - #define MYSYMBOL defines a macro with an empty replacement - gcc -D MYSYMBOL defines it with value 1 by default - either works with defined / #ifdef tests 4.6.7 A few more useful directives 1 #undef MYMACRO: - removes the macro definition from that point onward 2 #error message: - requests a compilation diagnostic - useful inside #if / #ifndef for invalid or missing configuration - examples: no customer variant selected; BUFFER_SIZE not supplied #line: - changes the presumed source filename / line for diagnostics - useful when another language is translated into generated C - diagnostics can point back to the original input 3 predefined macros: - __LINE__: current source line, integer constant - __FILE__: current source filename, string literal - __DATE__ / __TIME__: translation date / time, string literals - __STDC__: indicates the implementation's standard C conformance mode - these names are supplied by the implementation; do not redefine them 4.6.8 The #include directive 1 two common inclusion forms: - #include - #include "mymodule.h" - distinction concerns how the implementation finds the header 2 book's intended convention: - quotes for this project's headers - angle brackets for library headers - author objects to blurring the distinction between language syntax and libraries 3 kernel code illustrates that C can be used without the ordinary hosted library - author uses this to argue for separating language and library concepts - a library may itself be implemented in C - standardized library interfaces and freestanding C implementations can coexist 4 standard headers need not correspond to physical files: - implementation may provide their declarations by another mechanism - #include requests that header's facilities - book strongly criticizes this implementation freedom 5 third-party library headers raise the practical inclusion question too: - they belong neither to the project nor to the standard library - ordinary C toolchains also accept them with angle brackets - book's broad criticism of standards here is the author's opinion 6 usual GCC search behavior: - : search configured include paths and system header directories - -I adds search directories before the ordinary system locations - "name": first search relative to the directory of the including file - if absent there, continue through the configured header search paths -> including file's directory is not necessarily the shell's current directory 7 installed third-party headers commonly share system include locations: - often under /usr/include on Linux - otherwise supply the library's include directory to the compiler - they need not live beside the project's own source files 8 practical rule used in this book: - own project header -> "..." - external library header -> <...> - external includes need not belong to the standard C library 4.6.9 Formatting macro directives 1 preprocessor nesting and C statement nesting are separate structures: - preprocessing takes place before C syntax / scope are analyzed - directives can change the source structure itself book's formatting convention: - place # at the left edge even inside a C function / if / loop - keep ordinary statements indented according to C nesting - for nested preprocessor conditions, indent the directive after # - #ifdef ... / # if ... / # else ... / # endif / #endif example: selecting a sorting implementation: - fixed array -> #if tests ARRAY_SIZE against MAX_ARRAY_FOR_BUBBLE - dynamic array -> ordinary if tests arrsize at runtime - large array -> quick sort; small array -> bubble sort -> formatting makes compile-time and runtime choices distinguishable 4.7 Separate compilation 4.7.1 General arrangement of separate compilation in C 1 C separate compilation resembles the earlier assembly approach: - functions / global objects can have external or internal linkage - one translation unit can refer to symbols defined in another - linker resolves those references - headers and preprocessing organize interfaces - no Pascal-style unit declaration supplies the module structure here 2 divide functions and global objects among .c files: - main is defined in one file - gcc -Wall -g -c mod.c -> compile to mod.o without linking - compile the other modules in the same way linking options: - gcc -Wall -g prog.c mod1.o mod2.o -o prog -> compile the main source and link all modules - or compile prog.c separately, then gcc prog.o mod1.o mod2.o -o prog - pass every required object file to the final link - using gcc as the linker driver supplies ordinary startup / library details -> invoking ld directly requires arranging these details yourself 4.7.2 Visibility of objects from other modules 1 NASM comparison: - global exports a symbol for other modules - extern declares a symbol supplied elsewhere - other labels are local to the translation unit by default 2 C functions / file-scope objects normally have external linkage: - static on a function or file-scope variable gives internal linkage - other translation units cannot refer directly to that private name - private state is less widely coupled than an exported global variable calling a function defined elsewhere: - include its declaration, e.g. int cube(int x); - compiler checks calls against the declaration - object file records an unresolved external reference - linker connects it to the function's definition - caller need not compile the function body again incremental rebuild: - recompile changed source / affected dependencies - reuse unchanged object files - link the resulting objects again 3 declaring an external variable: - extern int very_bad_global_variable; - tells the compiler its type and name - storage is defined in another translation unit 4 book discourages communication through mutable global variables: - hidden shared state can affect otherwise unrelated functions shared read-only tables avoid that particular problem: - one module defines const int prime_numbers[] = { 2, 3, 5, ... }; - clients declare extern const int prime_numbers[]; - all use the same table without duplicating it or changing its contents 4.7.3 Header files for modules 1 copying external declarations into every client is difficult to maintain: - number of copies grows with the project - changing parameters / return type requires changing every declaration - inconsistent declarations in separately compiled files may escape diagnosis 2 example: func changes from two int parameters to three: - updated declarations make the compiler reject outdated calls - one forgotten declaration still permits a two-argument call - actual function expects a third argument that the caller did not supply -> undefined behavior; details depend on the calling convention 3 changing an argument from int to double creates a similar mismatch - changing the return type can also disagree with how the caller receives it - successful compilation / linking does not establish interface consistency 4 module header keeps exported declarations in one place: - m1.c implementation -> m1.h interface - exported function: prototype in .h, body in .c - exported variable: extern declaration in .h, definition in .c - private implementation details remain outside the public header 5 clients use #include "m1.h": - preprocessing supplies the same declarations to every client - interface changes require editing one shared header - rebuild affected modules so compiler checks calls against the new interface 6 implementation must include its own header: - compiler sees both public declarations and actual definitions - mismatch between the interface and implementation becomes diagnosable 7 mark private functions and file-scope variables static: - exported names belong in the header - internal names should have internal linkage - otherwise an undocumented external name can collide with another module 8 main is the usual exception: - normally omitted from the project's public headers - must remain available to the program's startup code 4.7.4 Protection against repeated inclusion 1 shared user-defined types belong in a header: - several modules may use one struct / union / enum - another header may need this type for its own exported declarations -> headers sometimes include other headers 2 shared macros also belong in headers - dependencies on macros can likewise require including another header 3 basic division between implementation and interface: - functions / global storage: definitions in .c - exported functions: prototypes in .h - exported variables: extern declarations in .h - private functions / global objects: static in .c - shared types / macros: definitions in .h - private types / macros: definitions in .c 4 repeated inclusion can happen indirectly: - module includes bbb.h and ddd.h - ddd.h also includes bbb.h -> compiler processes bbb.h twice within one translation unit 5 consequences depend on the header contents: - compatible repeated function / extern declarations are allowed - repeated structure definitions cause errors - conflicting macro redefinitions require a diagnostic - identical permitted macro redefinitions need not produce warnings 6 removing a direct include is a fragile solution: - dependency may change inside another header later - previously valid modules can then acquire duplicate definitions - each client should be able to include the interfaces it directly needs 7 header guard / sentry macro: - choose a unique name such as MYMODULE_H_SENTRY - begin header with #ifndef MYMODULE_H_SENTRY - next line: #define MYMODULE_H_SENTRY - place header contents inside; finish with #endif first inclusion: - macro absent -> contents processed and macro defined later inclusion in the same translation unit: - macro already defined -> contents skipped -> repeated inclusion no longer repeats the guarded declarations / definitions 8 book describes guards as a practical use of conditional compilation - they supply inclusion protection using existing preprocessor facilities 9 a declaration-only header may not strictly need protection yet - later additions can change that - adding guards at creation avoids having to reconsider every future edit 10 new-module routine: - create newmod.c and newmod.h - put #include "newmod.h" in newmod.c - put NEWMOD_H_SENTRY guards around the contents of newmod.h - register both files with version control and the build - document the module's purpose / interface 4.7.5 Type declarations; incomplete types 1 struct item; declares a type without defining its members: - compiler knows that struct item names a structure - layout and size are not known yet -> incomplete type - unions can also be declared incompletely 2 incomplete object type cannot provide storage / layout for an object definition - pointers to it can be declared - compiler need not know the pointed-to structure's members to store a pointer 3 incomplete types allow recursive links: - two structures can contain pointers to each other - struct item can contain struct item *next; - its own definition is still incomplete when next is declared - embedding a pointer is possible; embedding another complete copy is not 4 using struct item * can introduce the tag without a preceding definition - a separate struct item; declaration still helps establish the intended scope - especially useful before public function prototypes using that pointer type 5 forward declarations reduce header dependencies: - a declaration using only struct item * may not need the full structure header - fewer nested includes -> less source to process / fewer rebuild dependencies - useful when types refer to one another and inclusion order would be awkward 6 opaque type interface: - public header declares the structure and functions accepting its pointer - implementation keeps the full structure definition private - client stores / passes handles but cannot access hidden members - FILE * is a familiar example of an interface intended for library-managed use 7 enum forward declarations are a different case: - book warns against relying on compiler extensions in its C dialect - rules depend on the selected language version / implementation - structure forward-declaration rules should not simply be assumed for enum 4.8 C language and coding style 1 formatting principles have appeared throughout the book - accumulated programming experience makes subtler style decisions easier to assess - this section revisits general principles and their application to C 4.8.1 General principles revisited 1 source code is read by people as well as processed by computers - make its structure easy to recognize - author gives readability priority and insists on fixing poor formatting first 2 book's source-text conventions: - ASCII characters and English comments - English identifier names that express their purpose - short local names only when their role is obvious from context - choose clear names / structure before adding explanatory comments - these are the book's style rules, not universal language restrictions 3 indentation displays nesting: - nested text shifts right by one consistent indentation unit - choose spaces or tabs consistently throughout the program - matching opening / closing structural boundaries should align brace styles discussed: - opening brace on next line, aligned with the statement header - opening brace beside the header, closing brace aligned with its beginning - indented braces: possible, but not recommended by the author 4 book's function formatting: - opening brace on a separate line - both function braces at the left edge - indent the contents, not the entire brace pair - function header also has an independent role as a declaration -> separate header and body visually 5 preferred shape for a function: - float cube(float a) - opening brace on its own line - indented return a * a * a; - closing brace on its own line - do not compress a whole function body onto one line in this style 4.8.2 C-specific style features 1 C is case-sensitive: - if is a keyword - If, iF, IF are three different identifiers 2 book's usual identifier convention: - MACRO_NAMES in uppercase - ordinary_names in lowercase, words separated by underscores - avoid mixedCase / CamelCase in this style - naming traditions differ across projects and languages 3 mixed-case type names do appear in some C libraries - author acknowledges that they need not reduce clarity - still recommends consistent lowercase naming for the book's own code 4 avoid inventing identifiers beginning with _: - many such names are reserved for the implementation - a name that works today can collide with another toolchain / platform / header -> this conservative naming rule helps portability 5 C declarations can have substantial internal structure: - struct / union / enum definitions - array / structure initializers - format their contents to expose that structure 6 struct / union formatting: - opening brace beside the type name or on the following line - closing brace aligned with the start of the declaration - members on separate indented lines - avoid compressing a structure definition into one line enum formatting: - short list without explicit values can fit on one line - long list / explicitly assigned values -> one member per line - align = signs when doing so improves readability - keep brace placement consistent with structure declarations initializer formatting: - short initializer may occupy one line - long / commented initializer -> one value per line or aligned rows - for a matrix, usually one row initializer per source line - split overlong matrix rows consistently 7 while(condition); is visually ambiguous: - may end a do / while loop - may instead begin a while loop with an empty body -> formatting should make the intended structure immediately visible 8 book recommends braces for every do / while body: - even when the body contains one statement - keep } while(condition); together - this visually connects the final test to the preceding body - C permits an unbraced body; the recommendation is a style rule - heavily indented brace styles make this arrangement awkward 9 indent a final return just like every other statement: - return can also occur inside a branch / loop - ending the function does not make it exempt from normal indentation 10 indent local declarations inside the function too - keeping declarations at the left edge makes the opening brace hard to see - declaration syntax differs from statements, but both belong to the body 4.8.3 Side effects 1 book's explanation of a side effect: - expression evaluation produces a value and also changes something observable - examples: modifying state, reading input, producing output 2 book distinguishes this expression-centered meaning from ordinary actions: - uses Pascal procedures versus functions to explain its terminology - random updates generator state while returning a number - readkey consumes input while returning a character code - other programming literature also uses side effect more broadly 3 C makes assignments and increments expressions: - writing the new value is the assignment's side effect - expression statements commonly discard the value and keep the effect - void functions also perform actions even though they return no value -> side effects are central to ordinary C programming 4 author connects the wider terminology to the influence of C-like languages - main practical warning: combining hidden state changes can obscure a program - compact syntax does not automatically make behavior easier to understand 5 string-copy idioms illustrate the readability problem: - assignment and two pointer increments can all occur in a while condition - valid code still needs sufficient destination space and a terminated source - superficially similar expressions can contain subtle mistakes 6 array[array_filled++] = x combines two actions: - store x at the old array_filled index - increase array_filled clearer separation in the book's style: - array[array_filled] = x; - array_filled++; - reader need not reason about the value of postfix ++ inside indexing - compact notation alone does not establish a performance advantage 7 banning every side effect would rule out ordinary useful C programs - evaluate cases by clarity and purpose input loop example: - read once before while, then read again at the end -> duplicated retrieval - while((c = getchar()) != EOF) -> retrieval written once - latter uses a side effect in the condition but can express the loop clearly 8 common loop pattern: retrieve -> test -> process - obtain next item - stop if retrieval failed / items exhausted - otherwise process it and repeat - test belongs between retrieval and processing 9 another implementation uses for(;;) or while(1): - retrieve inside the body - if finished, break - then process - author objects that the termination condition is less visible in the header 10 condition-side retrieval has a reasonable purpose in this pattern - alternatives duplicate retrieval or move the test inside the body - choose the form that makes the retrieve / test / process structure clear 11 book restricts that exception to retrieval loops: - discourages assignments / effectful calls inside an if condition - discourages consuming ++ / -- values inside larger expressions - these are the author's readability rules, not C syntax restrictions 12 many C functions perform an action and return its status: - scanf reports how many conversions succeeded - I/O functions report success / failure using their documented conventions - many Unix system-call wrappers return -1 on failure - some return zero on success; others return useful results such as a count - inspect each interface instead of assuming one universal convention 13 author considers action-plus-status an established C idiom - regardless of that criticism, callers must follow existing library interfaces 14 book's practical rules for effectful code: - function's externally visible effect should be its stated purpose - write assignments / ++ / -- as their own top-level operations - call an effectful function as f(arguments); or result = f(arguments); - exception: retrieval in a while condition for retrieve / test / process loops examples accepted by this style: - x = 17; i++; f(x); result = f(x); - while((c = getchar()) != EOF) followed by character processing examples discouraged by this style: - a = b = c; array[i++] = value; - assignments embedded in ?: or an if condition - f(x) + 1, array[f(x)], g(f(x)) when f changes external state - pure computations can be composed without those hidden state changes 4.8.4 Return values and output parameters 1 output parameter sends information back to the caller: - caller passes the address of an object to receive the result - callee writes through that pointer - useful when producing several results - C can also return a structure containing several values 2 inout parameter carries information both ways: - caller supplies an initial value - function reads / changes it - caller receives the updated value in the same object - mechanism is the same as an output parameter: pass the object's address 3 one inout value can instead be passed by value and returned: - delete_negatives(&first) with a struct item ** parameter updates first directly - first = delete_negatives(first) returns the replacement head pointer - adding an input parameter does not change that choice - add_to_int_list(&first, 27) versus first = add_to_int_list(first, 27) return-value form is more flexible for an ordinary calculation: - logbase(arg, base) -> log(arg) / log(base) - caller may assign the result back, combine it, or pass it to another function - arguments may be expressions rather than existing writable variables - a pointer-based logbase that overwrites its argument unnecessarily limits use -> calculating a value and deciding where to store it are separate responsibilities 4 a list head pointer is not the whole list: - copying a double produces an independent numeric value - copying first only copies access to the same nodes - modifying the list through one pointer can affect users of the other pointer -> returning a pointer does not imply creating an independent list 5 distinguish computing a value from modifying an existing object: - logbase computes a result from its inputs - add_to_int_list changes an existing list - making a fresh independent list would require a different implementation book prefers a pointer-to-pointer interface for that mutation: - function updates the caller's head pointer as part of its stated action - avoids relying on the caller to assign a returned head to the correct variable 6 book criticizes realloc's return-value interface on similar grounds - successful realloc can move the allocation and return a new pointer - for a nonzero requested size, failure leaves the original allocation valid -> preserve the original pointer until success is known 7 several outputs raise an interface choice: - which result, if any, belongs in the function's return value? - do not choose an arbitrary result merely for presumed register efficiency - actual calling conventions / optimization vary 8 book's recommendation for action-oriented functions: - if there is a success / failure indicator, return that indicator - deliver the other results through output parameters - if no result has that special status role, use void and output parameters - this is an interface-design preference, not a restriction imposed by C 9 standard interfaces do not always follow that recommendation: - strtol, strtoll, strtof return a parsed value and report other information separately - author uses these functions while criticizing their interface design 10 pointer parameters intended only for reading should point to const data: - const makes the absence of writes through that parameter visible - mutable pointer suggests the function may update the pointed-to object -> declarations should communicate input versus output / inout intent 4.8.5 (*) Programs that speak Russian 1 English source-code conventions do not determine the user's interface language - a program may need Russian, German, Chinese, or other localized messages 2 separate translatable messages from program logic: - developers and users may speak different languages - translations can be supplied by people who did not write the program - runtime selects translated strings from external message files 3 gettext provides message lookup: - write printf(_("Hello, world\n")); - _ expands to a gettext call - original message is the lookup key - available translation -> use translated string - missing translation / catalog -> retain the original message 4 localization can be disabled by changing the wrapper: - #define _(STR) (STR) - existing marked call sites continue using the original text 5 marking user-visible messages prepares a program for translation: - book recommends English original messages as a common working language - easier for a broad translator community to use one shared source language - English is a project convention here; gettext keys are not restricted to English 6 book's rule: provide localization or at least keep a consistent English baseline - when Russian output is required, put Russian translations in the message catalog - make it possible to add further languages without rewriting program logic 7 following example demonstrates that arrangement with gettext - it follows the author's preference for English / ASCII handwritten C source - localized message files contain the other languages 8 starting program prints a greeting and a farewell: - "Hello, world!\n" - "Good bye, world!\n" first preparation step: - define _(STR) as (STR) - wrap the two displayed messages in _() - behavior stays the same until the macro is connected to gettext N_(STR) can mark text for translation later without calling gettext immediately: - useful in static initializers where a runtime call cannot be used - translate that stored string when it is actually displayed - genuinely nontranslatable strings should be distinguished from deferred messages - book uses N_ more broadly; it is conventionally a deferred-translation marker 9 headers needed for the localized version: - locale.h -> setlocale - libintl.h -> gettext, bindtextdomain, textdomain - initialize locale settings before expecting localized messages 10 gettext configuration identifies: - base directory containing catalogs for different locales - text domain: usually the program / package name - together with the selected locale, these determine the catalog path 11 example domain: hellobye - installed catalogs often live below /usr/share/locale or /usr/local/share/locale - demonstration uses "." as the base directory - this works only when run from the expected working directory - real programs need a reliable installed / configured location 12 configuration constants and wrappers: - LOCALEBASEDIR -> "." - TEXTDOMAIN -> "hellobye" - _(STR) -> gettext(STR) - N_(STR) -> (STR) startup sequence: - setlocale(LC_CTYPE, "") selects character settings from the environment - setlocale(LC_MESSAGES, "") selects message-language settings - bindtextdomain(TEXTDOMAIN, LOCALEBASEDIR) sets the catalog base - textdomain(TEXTDOMAIN) selects the default message domain - then print the two _()-wrapped messages create the translation template: - xgettext --keyword="_" hellobye.c -o hellobye.pot - --keyword tells the extractor which wrapper marks messages - .pot = portable object template - entries contain msgid with original text and an initially empty msgstr prepare a language catalog: - copy the template to ru.po - describe the package / version, translator, language, and catalog encoding - keep the declared encoding consistent with the file's actual bytes - book's example uses KOI8-R; UTF-8 can be used instead - maintain revision metadata; compiling a catalog does not supply missing translations 13 fill each msgstr with the corresponding Russian message: - preserve meaningful newlines and format placeholders - review / clear fuzzy status for translations that are ready for use compile catalogs: - msgfmt ru.po -o ru.mo - .mo = compiled catalog suitable for efficient runtime lookup - prepare de.po similarly, then msgfmt de.po -o de.mo catalog placement follows base / language / category / domain.mo: - ./ru/LC_MESSAGES/hellobye.mo - ./de/LC_MESSAGES/hellobye.mo - both languages use the same domain filename in different directories build and try the program: - gcc -Wall -g hellobye.c -o hellobye - some systems require linking the separate intl library with -lintl - selected locale / LANGUAGE controls the translated messages - LANGUAGE=de ./hellobye or LANGUAGE=ru ./hellobye with a working locale - LANGUAGE=en ./hellobye uses the English messages - missing translations / unsuitable locale configuration can leave English output 14 when source messages change: - regenerate hellobye.pot with xgettext - msgmerge -U --backup=numbered ru.po hellobye.pot - repeat for de.po - existing translations are retained where applicable - numbered backup preserves the previous .po file - translate new entries and review any changed / fuzzy matches - rebuild .mo files with msgfmt and install them in the catalog directories 15 example covers only the simplest gettext facilities - consult the gettext documentation for further features - gettext can be used without adopting Autoconf / Automake - author's broader rejection of those build tools is an opinion 16 gettext is one possible localization mechanism: - another library or a simple custom catalog loader can provide translations - book's central requirement: keep non-English messages outside handwritten source - load external message files at runtime - alternatively generate C arrays from message files during the build - generated numeric byte initializers can represent localized text -> translation resources and program logic remain separately maintainable 4.9 Complicated pointer types 1 array and function pointers can make declarations difficult to read - nested parentheses and stars express several levels of type structure - typedef gives a meaningful name to an intermediate type - use it when the complete declaration becomes hard to understand 4.9.1 Multidimensional arrays and pointers to arrays 1 int m[3][4]: - array of 3 elements, each an array of 4 ints - rows occupy consecutive memory locations - m[0][0] ... m[0][3], then m[1][0] ... m[1][3], then the last row 2 one pair of square brackets for each dimension: - m[2][1]: row 2, column 1; both indices start at 0 - m[i][j] applies indexing twice - nested loops can assign m[i][j] = i * j - nested initializer braces group the elements by row - comma-separated indices do not express multidimensional indexing in C 3 array-pointer relationships can take time to understand - return to the rules and work through concrete addresses and types 4 question behind multidimensional indexing: what is the type of m? 5 in most expressions an array converts to a pointer to its first element - m's first element is a complete row, not a single int - m[1] designates the second row - that row in turn converts to int* when used for the second indexing step - sizeof and unary & are important cases where array conversion does not happen 6 m[1] = *(m + 1): - m + 1 advances by one complete row: 4 * sizeof(int) - dereferencing selects that row; ordinary expression use converts it to int* - int** cannot describe this arrangement * it points to a stored int* object * its increment advances by sizeof(int*), not by the size of a row 7 int (*p)[4]: pointer to an array of 4 ints - p = m; p[i][j] accesses the same elements as m[i][j] - parentheses make * bind to p before the array suffix is applied int *q[4]: array of 4 pointers to int - a different type and memory arrangement - arrays are real C types, although whole-array assignment is not supported 8 int z[10][15][20]: array of 10 two-dimensional slices - corresponding pointer: int (*zptr)[15][20] - zptr + 1 advances by 15 * 20 * sizeof(int) - 1200 bytes on the example machine where sizeof(int) is 4 4.9.2 Pointers to functions 1 compiled functions have callable addresses - a function pointer stores such an address - C can call a function through a pointer - its representation is determined by the implementation 2 functions can share a profile while performing different operations: - dbl_sum: recursively add an array's elements - dbl_min: compare the first element with the minimum of the remainder - dbl_average: sum divided by element count - minimum and average require a nonempty array common profile: double result, const double* array, int size - double (*fptr)(const double *, int): pointer to such a function - parameter and return types are part of the pointer type - double *fn(const double *, int): function returning double*, not a pointer variable 3 assign a function address: - fptr = &dbl_min; or fptr = dbl_min; call through the pointer: - (*fptr)(arr, count); or fptr(arr, count); - sizeof(arr) / sizeof(*arr) gives count while arr is an actual array 4 function designators usually convert to function pointers automatically - this explains why direct calls through a pointer and explicit dereferencing both work - repeated dereferencing can still produce a function designator - repeated address-of operators are not generally valid; use the simple forms 5 the original C notation distinguished a function from its address explicitly - calling through a pointer traditionally used (*fptr)(arguments) - naming a function could already supply its address without & 6 standard C allows fptr(arguments) - automatic conversion makes explicit dereferencing unnecessary for a call - this does not make functions ordinary data objects 7 choice of call notation is a style decision - (*fptr)(...) visibly marks an indirect call - fptr(...) is shorter and equally valid 8 generalizing a list operation: - deleting negative values, even values, and multiples of 7 needs the same traversal - copying the traversal for each condition duplicates maintenance work 9 pass the deletion criterion as int (*crit)(int) - is_negative(x): x < 0 - is_even(x): x % 2 == 0 - is_div7(x): x % 7 == 0 delete_from_int_list receives the address of the link that points to the current node - criterion true: save node, replace its incoming link with next, free saved node - criterion false: advance to the address of this node's next field - after deletion keep the same link address to examine its new target - &first lets the same code remove the first node as well - changing the supplied function changes the policy without changing traversal 4.9.3 Callback functions 1 callback: one module supplies a function for another module to call - service module finds or produces data - calls the supplied function for each available item - user here means the module using the service 2 a reusable service knows the callback's required profile - receives its address as an argument - need not know the caller's internal organization 3 processing can depend on earlier items - accumulated state must remain accessible to later callback invocations - one global variable ties independent operations to shared storage - passing state explicitly permits separate processing contexts 4 void* userdata carries the address of caller-owned state - caller supplies both callback and userdata - service passes userdata back unchanged for every item - callback knows the actual type and interprets the address accordingly 5 generalize binary-tree traversal: - replace the fixed printing operation with a callback - pass each stored int and the same userdata pointer 6 callback profile: void callback_function(int num, void *userdata) int_bin_tree_traverse: - empty tree: return - traverse left subtree - callback(current value, userdata) - traverse right subtree printing callback: - prints the current number; ignores userdata - pass NULL to show explicitly that no state is needed 7 summing the tree requires state across callback invocations - initialize int sum = 0 - pass &sum as userdata - callback converts userdata to int* and adds the current number to *sum - *(int*)userdata += data expresses the same update directly - traversal returns with the accumulated result in the caller's variable 8 minimum, maximum, and count in one traversal: - state structure: int count, min, max - initialize count to 0; pass the structure's address - first item sets both min and max - later items update the appropriate bounds - every callback increments count - after traversal, count == 0 means the tree was empty - in that case min and max were never assigned and must not be read 4.9.4 Complex declarations and how to read them 1 declarations combine prefixes and suffixes - prefixes: *, const, and the base type - suffixes: array dimensions and function parameter lists - grouping parentheses change how these pieces attach to the name 2 examples of nested declarations: - int (*funret(int x))(int, int) * funret takes int and returns a pointer to a function taking two ints and returning int - int (*funvec[10])(int, int) * array of 10 pointers to functions with that two-int profile - double (*select_segment(int a, int b))[10] * function taking two ints and returning a pointer to a row of 10 doubles - double (*(*selptr)(int, int))[10] * pointer to a function with the select_segment profile - returned row pointers can select a starting row within double matrix[100][10] 3 a function can accept and return the same function-pointer type - replace_f installs a new callback and returns the previous one - raw declaration: int (*replace_f(int (*func)(int, int)))(int, int) - pointer to it: int (*(*replace_f_ptr)(int (*)(int, int)))(int, int) - unnamed parameter types omit func but keep the surrounding pointer structure 4 parameter names may appear in a function-pointer declaration - nested names can obscure which identifier the outer declaration introduces - omitting unnecessary parameter names can help, but does not remove the complexity 5 typedef breaks the declaration into understandable parts - typedef int (*fptr)(int, int); - fptr (*replace_f_ptr)(fptr); - same type as the long declaration - knowing the raw rules still helps when reading existing programs 6 reading procedure: - find the declared identifier; start with "name is ..." - move outward, processing the nearest suffixes before prefixes - finish everything inside grouping parentheses before moving outside - [n]: array of n elements of ... - (parameters): function taking ... and returning ... - *: pointer to ... - const qualifies the relevant type at that level - finish with the base type 7 replace_f_ptr example: - pointer to a function - parameter: pointer to a function taking two ints and returning int - result: pointer to a function taking two ints and returning int - read each nested parameter declaration by the same rules 8 funvec example: - begin with [10]: array of 10 elements - then *: each is a pointer - then (int, int): to a function taking two ints - final int: each function returns int 9 C restricts how array and function types can be combined - a function cannot return an array or another function by value - an array cannot have function elements - array and function parameter declarations adjust to pointer parameters - pointers to arrays/functions supply the required indirection 10 invalid examples illustrate the distinction: - void (*f15)(int)(int): attempts to return a function - void *m[5](int): attempts to make an array of functions - int (*f100)()[15]: attempts to return an array - use pointers at the relevant level instead 4.10 More of the standard library 1 standard library supplies many commonly needed operations - chapter introduces a selection, not a complete reference - author's learning advice: understand the underlying operations before relying on helpers 4.10.1 Additional heap operations 1 calloc(nmemb, size): allocate space for nmemb elements of size bytes each - parameters have type size_t - initializes the allocated bytes to zero - malloc leaves the allocated bytes uninitialized - returns NULL when allocation fails - zero bytes are not a portable guarantee of a null pointer or every type's numeric zero 2 realloc(ptr, size): change an existing allocation's size - may extend/shrink it in place or move it to a different address - preserves the first min(old size, new size) bytes - additional bytes are uninitialized - successful call replaces the old allocation; use the returned pointer - for nonzero size, failure returns NULL and leaves the original allocation valid - keep the result in a temporary pointer until success is known - direct p = realloc(p, size) can lose the original address on failure - allocator preserves bytes without knowing which ones the program still needs 3 special cases: - realloc(NULL, size) acts as allocation - do not use realloc(ptr, 0) as a portable spelling of free(ptr) - zero-size rules vary by C version; explicitly free memory when that is intended - malloc, calloc, realloc, and free communicate different intentions 4.10.2 String operations 1 standard function names make common operations immediately recognizable - a reader need not inspect a private implementation to learn what it does - implementation performance depends on library, compiler, architecture, and input 2 learning the functions does not replace understanding strings - practice walking character arrays and finding their terminating zero - otherwise unfamiliar string operations remain difficult 3 string and memory function declarations are in string.h - author's exercise: implement the operations yourself before relying on the library 4 strlen(str): length before the terminating zero byte - returns size_t, not int - equivalent in purpose to the earlier string_length helper 5 strcpy(destination, source): copy a complete string, including its terminating zero - destination first, source second - destination needs at least strlen(source) + 1 bytes - caller must establish sufficient capacity before copying - the source and destination must not overlap 6 strncpy(destination, source, n): write exactly n bytes when n is nonzero - copy until source ends or n bytes have been written - shorter source: fill the remaining destination bytes with zeros - source length >= n: no terminating zero is appended - destination must have at least n bytes; n has type size_t - if using the result as a truncated string, reserve or explicitly set a terminator - setting destination[n-1] requires n > 0 and may discard a copied character 7 strcpy and strncpy return the destination address - their principal effect is modifying the supplied array - returned address is often ignored 8 strdup(source): allocate and return an independent string copy - allocation failure returns NULL - caller owns the result and eventually calls free - allocation is hidden inside the helper, so ownership must remain clear - historically a Unix/POSIX function; also included in C23 9 strcmp(s1, s2): compare complete strings lexicographically strncmp(s1, s2, n): compare at most n character positions - first unequal bytes, interpreted as unsigned char, determine order - an ended string sorts before a longer string with the same prefix - result < 0: s1 precedes s2 - result == 0: no difference in the compared part - result > 0: s1 follows s2 - test the sign; do not assume the result is exactly -1 or 1 10 make equality tests explicit - 0 == strcmp(str1, str2) clearly tests for equal strings - !strcmp(str1, str2) is valid but less direct to an unfamiliar reader - placing zero on the left is the author's style preference 11 strchr(s, c): first occurrence of a character strrchr(s, c): last occurrence - return a pointer into the existing string - return NULL if no occurrence exists - no copy or new allocation is produced 12 strstr(haystack, needle): first occurrence of a substring - haystack: string to search - needle: string to find - returns a pointer to the match or NULL - strstr("abrakadabra", "kada") points 4 characters into the first string 13 memset(memory, value, size): fill a byte region - ignores string terminators; operates on exactly size bytes - each byte receives value converted to unsigned char - size has type size_t; result is the original destination pointer - filling with byte value 1 does not generally set every int element to integer 1 14 memcpy(dest, src, size) and memmove(dest, src, size): copy raw bytes - both copy size bytes and return dest - memcpy requires non-overlapping regions - memmove handles overlap as if a temporary copy were used - a typical implementation chooses a safe copying direction - use memmove to shift the remainder of a string when inserting/deleting characters - include the terminating zero when shifting the string's end 4.10.3 Pseudorandom numbers 1 randomness is useful for games, simulation, and security - these uses require different guarantees - security needs unpredictability to someone trying to guess the result 2 operating systems gather unpredictable information from available sources - entropy helps initialize a secure random generator - output quality depends on the generator and its initialization 3 the book demonstrates obtaining random bytes from Linux /dev/random - read bytes through file operations rather than inventing a seed - security-sensitive generation should use the operating system's secure random facility 4 ordinary pseudorandom sequences can suffice for nonsecurity tasks - deterministic computation produces varied-looking numbers cheaply 5 stdlib.h declares rand and srand - rand() returns int in 0 ... RAND_MAX, inclusive - RAND_MAX depends on the implementation - without an explicit seed, behavior is as if srand(1) had been called - same seed and implementation reproduce the same sequence 6 srand(seed) initializes generator state - call once before generating a sequence - choose a changing seed if different runs should normally differ - initialization does not itself return a random value 7 ordinary demonstration seed: srand(time(NULL)) - time is declared in time.h; on Unix it supplies time in seconds since the epoch - executions within the same second can obtain the same seed - repeatedly reseeding before rand can repeatedly restart the same sequence 8 time-based seeding is unsuitable for passwords and secrets - knowing the generation day leaves only 86400 possible second-based seeds - rand is not a cryptographic generator even with a less obvious seed 9 mapping results to a smaller interval: - rand() % 12 + 1 produces values from 1 through 12 - low-bit quality and uneven division of the original range can bias the result - book's scaled alternative: 1 + (int)(12.0 * rand() / (RAND_MAX + 1.0)) - scaling uses the full value but does not guarantee an exactly uniform distribution - exact uniformity requires a suitable generator and unbiased range selection 4.10.4 (*) Variadic functions 1 variadic function: accepts a variable number of arguments - printf and scanf families are examples - stdarg.h supplies va_list and macros for accessing unnamed arguments - va_list representation is implementation-dependent 2 traditional declaration: named parameters followed by ... - va_start(list, last_named_parameter): initialize argument traversal - va_arg(list, type): obtain the next argument as the specified type - va_end(list): finish traversal in the function that initialized it - argument types must match the actual promoted types - char/short normally promote to int; float promotes to double 3 implementation depends on the calling convention - i386 CDECL stack layout makes simple address-based traversal imaginable - other conventions also pass arguments in registers - use stdarg macros instead of assuming a particular layout 4 the variable argument list contains no automatic count or type description - caller and callee need an agreed protocol - format string, explicit count, or sentinel can supply it - printf's conversion directives determine which arguments it consumes 5 sum example uses integer 0 as an end marker - named int c initializes the sum - va_start(vl, c) - repeatedly read va_arg(vl, int); stop at 0, otherwise add the value - va_end(vl); return accumulated sum - every call must supply the terminating zero among the unnamed arguments - omitting it causes reads beyond the supplied arguments 6 print_times example uses alternating string pointer / int pairs - first string is the named parameter - read count; print that string count times; then read the next pointer - null pointer terminates the sequence without a following count - use a correctly typed null pointer for a variadic pointer argument - example sequence: "once", 1, "twice", 2, "seven times", 7, (const char*)0 7 vprintf, vfprintf, vsprintf, vsnprintf and the vscanf family accept va_list - perform the corresponding formatting or input operation using that list - useful for wrappers that do extra work before delegating formatting - initialize the list in the variadic wrapper and finish it appropriately - va_copy is available when an independent traversal is needed 4.11 (*) Full-screen terminal programs in C 1 full-screen terminal program: - positions text anywhere in the terminal - controls character appearance - can react to keys without waiting for Enter - similar purpose to Pascal's crt, with a different interface 2 ncurses handles differences between terminals - uses terminal descriptions instead of hard-coded escape sequences - consoles, terminal emulators, serial terminals, and remote connections can differ - the application requests an operation; the library chooses how to perform it 4.11.1 A simple example 1 example: center "Hello, world!", wait 5 seconds, then finish - suitable terminals can restore the previous screen after the program exits 2 available behavior depends on the selected terminal description - TERM identifies the terminal type - pretending a terminal is vt100 limits use to that description's capabilities - alternate-screen restoration and color cannot be assumed for every terminal 3 initscr(): initialize ncurses and take control of the terminal getmaxyx(stdscr, row, col): obtain screen height and width - stdscr is the standard window covering the screen - other windows can have independent coordinates and output - ncurses consistently puts y / row before x / column 4 getmaxyx is a macro, not an ordinary function - it assigns directly to row and col - pass variables themselves, without & 5 move(y, x): set the cursor's position in the window - top-left cell is (0, 0) - centered row: row / 2 - centered column: (col - message_length) / 2 - display dimensions must be large enough for the chosen message 6 use ncurses output functions while ncurses manages the screen - printf/putchar bypass its screen model - drawing normally updates the library's virtual screen first - refresh is needed to make the physical screen match it 7 addstr(message): write a string at the current cursor position addch(character): write one character - curs_set(0) requests an invisible cursor, where supported - refresh() sends pending screen changes to the terminal 8 finish the demonstration: - sleep(5): wait approximately 5 seconds; POSIX function declared in unistd.h - endwin(): finish terminal management and restore terminal modes - include curses.h and link the separate curses library - book's command: gcc -Wall -g curses_hello.c -lcurses -o curses_hello - this program leaves interrupt-key handling enabled, so Ctrl-C can interrupt it 4.11.2 Keyboard and other events 1 canonical terminal input: - program normally receives a line after Enter - terminal driver performs line editing such as Backspace - special control characters can signal, suspend, or finish a line of input - typed characters are normally echoed to the screen 2 full-screen interfaces usually need different behavior - receive input immediately - recognize cursor and function keys - control whether typed characters are displayed 3 ncurses exposes these choices separately - immediate input need not disable signal-generating keys - echo and special-key decoding are independent settings 4 cbreak(): receive characters without waiting for a complete line - retains signal-generating keys such as Ctrl-C - canonical EOF processing is no longer active; Ctrl-D does not keep its usual line-mode role raw(): also disable the driver's usual special handling of control characters - Ctrl-C can then arrive as character code 3 - corresponding reversal functions: nocbreak and noraw noecho(): disable automatic echo; echo() re-enables it keypad(stdscr, 1): translate recognized key escape sequences into key codes 5 getch(): read an input event as int - ordinary input: character code - special keys: KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_F(n), ... - symbolic names avoid dependence on numeric values - int is necessary because special codes extend beyond the char range 6 Enter and Backspace need attention to terminal behavior - Enter may arrive as '\n' or a keypad-related KEY_ENTER - Backspace may arrive as '\b', another configured erase byte, or KEY_BACKSPACE - Insert: KEY_IC - Page Up / Page Down: KEY_PPAGE / KEY_NPAGE 7 input events can also report mouse activity or a terminal resize - KEY_RESIZE: query dimensions again with getmaxyx - recompute bounds and redraw the interface as needed 8 interactive example: move "Hello, world!" with arrow keys - Escape exits - cbreak preserves Ctrl-C interruption 9 split drawing and movement into helpers - show_message(x, y): move cursor, add string, refresh - hide_message(x, y): overwrite its previous cells with spaces - move_message: erase, change coordinates, clamp to bounds, show again - pass coordinate addresses so the helper updates the caller's state 10 handle_resize recomputes the permitted message position - maximum x = columns - message_length - maximum y = rows - 1 - clamp existing coordinates and redraw - if the window is narrower than the message, handle clipping separately 11 main loop dispatches getch results with switch - arrows call move_message with a unit displacement - KEY_RESIZE calls handle_resize - Escape ends the loop; endwin restores terminal state formatted output: - printw accepts printf-style arguments and writes through ncurses - mvprintw(y, x, format, ...) combines movement and formatted output - printing coordinates needs trailing spaces or explicit clearing to erase longer old text 4.11.3 Colors and character attributes 1 character attributes control appearance - color includes both foreground and background - call start_color after initialization before using color operations - start_color returns OK or ERR; color support depends on the terminal 2 attributes can work independently of color: - A_BOLD, A_DIM, A_UNDERLINE, A_BLINK, A_REVERSE - combine flags with bitwise | - attron(flags): enable selected attributes - attroff(flags): disable selected attributes - addch('*' | A_BOLD | A_BLINK): attributes attached to a single character check color support with has_colors() - retain a usable monochrome presentation when it returns false - a user preference may also request monochrome operation - initialize colors only when the application will use them 3 remaining color examples assume color is available and enabled 4 eight basic named colors: - black, red, green, yellow, blue, magenta, cyan, white - names have the COLOR_ prefix - additional colors and palette changes depend on terminal/library capabilities - can_change_color and init_color provide palette control where supported - the book's blanket claim that palette changes never work is too broad 5 color pair = foreground color + background color - init_pair(number, foreground, background) defines a pair - COLOR_PAIR(number) supplies its attribute value for output - attrset replaces the current attributes - example: pair 1 = white on blue; combine COLOR_PAIR(1) with A_UNDERLINE - pair 0 has special default-color meaning - redefining a pair changes the appearance of cells already using that pair 6 check supported ranges after start_color - COLORS: number of color indices - COLOR_PAIRS: number of pair identifiers - ordinary user-defined pairs start at 1 and remain below COLOR_PAIRS - the traditional COLOR_PAIR attribute encoding also has a finite range - do not infer the supported pair count from a single machine 7 eight foregrounds times eight backgrounds gives 64 combinations - assigning them to pairs 1 ... 64 also needs room for reserved pair 0 - verify capacity rather than assuming every terminal supports all combinations 8 pairs can represent interface roles instead of unique color combinations - several roles may initially have the same colors - redefining one pair recolors all elements assigned that role 9 A_BOLD may display as brighter foreground color on some terminals - exact rendering is terminal-dependent 10 color demonstration fills the screen with stars - assign a pair to each foreground/background combination - pair number = 8 * background_index + foreground_index + 1 - +1 keeps pair 0 unused 11 keep the eight color constants in an array - use array indices 0 ... 7 to enumerate colors - translate each index to its named constant when calling the library - this separates enumeration from the constant's numeric encoding 12 setpair associates a pair number with its two colors - compute the number from the indices - initialize the pair with the corresponding color constants - return the pair number for later output 13 make_line draws one foreground across strips of different backgrounds - every second star adds A_BOLD - every second group of two also adds A_BLINK make_screen clears the display and fills it with these rows 14 input loop recolors the existing display - Escape exits - another key calls shift_pairs to redefine the pairs - refresh applies the changed appearance - no need to recreate each star merely to change its pair's colors 15 complete example joins initialization, drawing, recoloring, and cleanup - if color is unavailable, call endwin before printing the error through stdio - configure cbreak, keypad, noecho, and cursor visibility - start_color; get dimensions; draw; process keys; endwin - keep pair-number indices distinct from color constants when adapting the example 4.11.4 Keyboard input with timeouts 1 blocking input prevents an animation from advancing while no key is pressed - ncurses can instead return immediately or wait for a limited interval - getch returns ERR when that interval expires without input 2 timeout(milliseconds) selects the waiting policy - positive: wait up to that many milliseconds - zero: nonblocking input; return immediately - negative: wait indefinitely for input - timeout(100): at most one tenth of a second per getch wait 3 moving-star example: - arrow keys set a direction - star continues moving without further keypresses - Space sets velocity to zero - Escape exits 4 state structure stores current x/y and velocity dx/dy - initialize position near the center and velocity to (0, 0) - timeout(100); read events in the main loop - arrow: change velocity; Space: stop; ERR: advance position - move helper erases old cell, updates coordinates, handles edges, then redraws - correct wrap period is the dimension: max_coordinate + 1 - after resize, valid coordinates remain 0 ... columns-1 and 0 ... rows-1 - the printed example's wrap and resize checks contain off-by-one errors - each input event restarts the wait, so this simple loop is not a fixed-rate clock 4.11.5 Other ncurses facilities 1 the examples cover only a small part of the library - more ways to control attributes - windows with independent coordinate systems - screen/window scrolling - further terminal initialization and input settings 2 related libraries supply higher-level interface components - menu: menus with single or multiple selections - panel: overlapping windows that can be moved, hidden, and shown - CDK: widgets such as entry fields, buttons, and selectors - CDK is a separate toolkit built on curses 4.12 (*) A C program without the standard library 1 experiment: identify which parts of a C executable come from the language and which come from startup code and library services 2 initial greeting program uses printf - if argc < 2: print a missing-name message and return status 1 - otherwise print "Hello, dear ", argv[1], and "!", then return 0 - the example uses the first supplied argument; it does not reject extra arguments a small dynamically linked executable omits most library machine code - loader brings required shared libraries into the process at startup - strace exposes startup operations as well as the application's output and exit - author's measured run: about 7-8.5 KB executable and 27 system calls - sizes and counts describe that particular system/build 3 -static requests static linking - needed library code is included in the executable - author's result: roughly 510-565 KB and 10 system calls - removing shared-library loading does not remove library initialization 4 replace formatted output with the operating system's write operation - arguments: file descriptor, address of bytes, byte count - C wrapper translates the C calling convention into the syscall convention - unistd.h declares the POSIX wrapper - its actual return type is ssize_t and its count parameter is size_t - result reports how many bytes were written, or an error 5 using write alone still leaves normal C startup and library linkage - greet2 outputs prefix, name, and suffix in three separate calls - constant arrays use sizeof(array) - 1 to exclude their terminating zero - the argument's length is found with a small local loop - a robust output routine also handles short writes and failures to remove libc, replace the startup routine as well - executable entry point in this example is _start - main is called by startup code, not directly by the kernel - startup prepares main's arguments and exits after main returns 6 initial 32-bit process stack and C function arguments have different layouts - initial [ESP]: argc - initial ESP + 4: start of the argv pointer array - load argc, compute argv, then push argv followed by argc - call main according to the chosen C calling convention - result returns in EAX; pass it to the exit system call - startup must also honor the compiler/ABI's required stack alignment 7 book's Linux i386 _start: - save argc in ECX and argv address in EAX - push those arguments in reverse order; call main; reclaim 8 argument bytes - move return status to EBX; put exit syscall number 1 in EAX; int 80h FreeBSD i386 variant: - place exit status on the stack with the expected extra stack slot - invoke its syscall convention with int 80h next component: private syscall wrappers - sys_write and sys_read avoid confusing them with libc wrappers - read writes into its buffer, so that parameter is not const - sys_errno holds this example's saved syscall error 8 three-argument syscall wrappers can share one assembly body - sys_read loads syscall number 3 into EAX - sys_write loads number 4 - both jump to generic_syscall_3 Linux i386 body: - save EBP; set up stack frame; save callee-preserved EBX - arguments at EBP+8, EBP+12, EBP+16 go into EBX, ECX, EDX - int 80h enters the kernel - successful result stays in EAX - error path saves the raw result in sys_errno and returns -1 - restore EBX and EBP and return with the original stack arrangement error convention: - Linux raw errors are negative error numbers, normally -4095 ... -1 - the book's mask test also includes -4096 - its sys_errno stores the negative result; libc errno normally stores the positive number FreeBSD i386 body: - syscall arguments already occupy the required stack positions - carry flag reports failure - on error, save the kernel result and return -1 - otherwise return the kernel's result directly 9 greet3 uses only the private sys_write wrapper - declare its prototype and replace each write call - keep string_length and the greeting logic in ordinary C - no standard header is needed for these chosen types and declarations - a private calls.h can declare sys_read, sys_write, and extern sys_errno - protect that header with an include guard build separate object files: - nasm -f elf start.asm - nasm -f elf calls.asm - gcc -Wall -c greet3.c - ld start.o calls.o greet3.o -o greet3 when the host defaults to 64-bit objects: - compile C with -m32 - select ld's elf_i386 emulation with -m elf_i386 - all objects must target the same architecture - toolchain defaults such as position-independent output may need corresponding settings - direct linking deliberately omits the normal C startup files and libc 10 a minimal executable can be much smaller - author's example was 816 bytes; this size is not a portable promise - important result: this chosen program can run without linking libc - "zero runtime" here means no compulsory library runtime for the selected code - language features and compiler decisions determine which support code is required - C does not have exclusive ownership of this approach; other languages/subsets can also use it 11 control over startup and runtime dependencies is useful for kernels and firmware - these environments may lack a normal hosted C library - they need deliberate control over memory, hardware, and initialization - suitability depends on implementation and chosen features, not only language name 12 compiler-generated helpers can still introduce unresolved references - operations unavailable directly on the target may call support routines - GCC commonly supplies such helpers through libgcc - link an appropriate support library or provide the required implementation - direct ld use may need an explicit library search path compiler-generated memory operations are another dependency - a loop or aggregate operation may become a call to memcpy/memset - -ffreestanding selects freestanding compilation assumptions - it does not guarantee that no helper or memory-function calls are generated - inspect the final undefined symbols and supply any required routines 13 distinguish a language's usable subset from a particular compiler's output - this experiment removes libc from a small, selected program - it does not establish that every C program needs no runtime support - a freestanding build must account for the actual compiler, target, and options 5. Operating-system objects and services 5.1 Operating System 5.1.1 Kernel and user programs 1 operating system in the narrow sense: - the program loaded first for ordinary operation - controls hardware - handles interrupts - provides system calls -> this program is the kernel 2 operating system in the broad sense: - kernel plus system utilities - configuration and management programs - sometimes compilers and language interpreters -> use terms such as distribution or operating environment -> kernel has the unambiguous meaning 3 user task: - can transform information only in its assigned memory - interacts with the outside world only through the OS -> request for an OS service = system call 4 background needed before studying OS: - review volume 1, section 3.1.2 and chapter 3.6 - understanding basic OS operation is required for further study 5 CPU execution modes: - privileged mode: all CPU instructions are available - restricted mode: only non-privileged instructions are available - kernel starts in privileged mode - user task runs after the kernel switches to restricted mode 6 return from a user task to privileged mode also transfers control to a predefined handler owned by the OS: - hardware interrupt: an external device needs attention - exception: the CPU cannot execute an instruction correctly (invalid opcode, division by zero, access outside task memory, ...) - system call: the task explicitly requests an OS service -> restricted code cannot change the handler addresses 7 only kernel code executes in privileged mode - all other programs are user tasks in restricted mode - a user task cannot directly affect the whole computing system - it can request such an action from the OS 8 multitasking modes: - batch: task runs until it finishes or waits for an event/I/O useful on supercomputers where total throughput matters - time-sharing: ready tasks receive portions of CPU time useful for interactive and server systems - non-preemptive: task keeps CPU until it gives it up mostly obsolete - real-time: scheduler aims at predictable completion by a deadline 9 full multitasking needs hardware support for: - interrupts - memory protection - privileged and non-privileged instructions/modes - timer generating interrupts at regular intervals 10 OS material had appeared earlier because later programming topics could not be explained without it; earlier treatment was necessarily superficial 11 detailed OS study has 2 aspects: - services visible to programs using system calls - internal structure and operation of the OS - this part and the next two cover the first aspect - the final part of the volume covers the second aspect 12 why the OS is needed: - manage user tasks: * start and stop programs * distribute CPU time and RAM * allow processes to interact - manage the computer hardware -> the OS is the layer coordinating applications and hardware 5.1.2 Managing user tasks 1 starting and stopping tasks: - only the OS can create a task after it has taken control of the machine - only the OS can remove it correctly - it must update task structures, scheduling queues, and free memory 2 CPU scheduling: - several tasks may exist on one or more CPUs - scheduler pauses some tasks and runs others - batch mode lets a task run while it has work - time-sharing gives tasks time slices and switches at their expiry 3 memory management is part of task management: - allocate RAM among tasks - configure virtual memory and memory protection - manage hardware features related to memory - swap data to disk temporarily to free RAM 4 processes need to communicate - processes cannot directly change one another -> the OS provides inter-process communication 5 privileges belong to running programs/processes, not directly to human users - a process may represent a user task or part of one 6 multi-user systems need access control: - unrestricted access would let ordinary mistakes damage shared resources - the risk exists even without malicious users 7 giving one user unrestricted privileges on a personal machine is dangerous: - launching a program gives its author control of the machine through that program - malware can act against the owner's interests - an ordinary programming error can destroy the system and user data 8 the book notes that Unix systems had avoided actively spreading viruses; it attributes this mainly to privilege separation and Unix design choices 9 Unix administrators normally: - work under ordinary user accounts - obtain unrestricted privileges only for a specific administrative task - leave the privileged session immediately afterward -> everyday programs do not receive administrator privileges 10 Unix interfaces usually expose technical details instead of hiding them: - no generic action that opens an arbitrary file type by executing it - an attached executable from mail is not given a convenient launch button -> accidental execution is harder 11 Unix design traditionally favors engineering and security over marketing claims of convenience: - user interface behavior is not forced by the kernel - what looks attractive in advertising need not be convenient in daily work 5.1.3 Managing external devices 1 device management has 2 parts: coordination and abstraction - coordination prevents tasks from conflicting over one device - without it, disk requests can repeatedly move the head in opposite directions and may corrupt each other's results - tasks submit device requests through system calls - the OS chooses the order in which requests are performed 2 abstraction is needed because devices are numerous and different: - controllers use different commands and data formats - supporting every possible device in every application is impractical - a new or unknown device could otherwise make an application incompatible 3 OS device abstraction: - OS handles device-specific details - system calls present simpler, often uniform objects to programs - tasks see an abstraction instead of a physical device and its quirks 4 physical storage devices differ widely: - magnetic diskettes and hard disks use magnetized tracks - CD/DVD uses optical changes along a spiral track - flash drives, memory cards, and SSDs have no rotating disk 5 OS presents these devices as one disk abstraction: - numbered sectors of equal size, commonly 512 bytes - disks differ by sector count, read/write capability, and removability - most tasks use the higher-level file abstraction instead - named files can be opened, read/written, and closed in the same way regardless of whether the storage is optical or flash 5.1.4 Boundaries of kernel responsibility 1 OS responsibilities: - user-task management: * start and stop processes * schedule CPU time * allocate RAM * provide process interaction * separate privileges - external-device management: * hide differences between device models * coordinate several tasks using one device 2 kernel has special costs and risks: - kernel memory normally cannot be swapped out -> a larger kernel leaves less physical memory for user tasks - kernel code runs privileged -> a kernel error is more damaging and harder to fix than a user error 3 minimal-kernel principle: - kernel should contain only work that really needs kernel privileges - moving drivers to user programs can reduce kernel size but adds system calls and frequent context switches - application-level work has no place in the kernel 4 OS should not provide user communication: - no window system or other user interface belongs in the kernel - application programs talk to users and request OS services - ideally, the end user need not see the OS itself 5 Android and Mac OS X illustrate the distinction: - their graphical layers are user-space programs, not the kernel - Linux is the kernel under Android - Darwin (a BSD-family kernel) is the kernel under Mac OS X - programming for these systems mainly uses high-level user-space GUI libraries 5.1.5 Unix: family of systems and a way of thinking 1 Unix names a family of systems built around common principles, not one particular OS; a broader Unix philosophy grew around those principles 2 main Unix design principle: - each program should solve one task and solve it well - programs should work together - text streams should be a universal information representation 3 example setting: - a mixed-faculty computer class ran Windows workstations - students logged into a remote Linux server - the task was to count how many students had logged in successfully 4 program w lists active sessions and their users - successive transformations by separate filter programs were connected in one pipeline - output of one program became input of the next 5 remove the two header lines with tail -n +3 - select only the login-name field with cut -d' ' -f 1 6 finish the pipeline: - remove the author's own login with grep -v ^avst$ - sort and remove duplicate student sessions with sort -u - count the remaining names with wc -l - complete command: w | tail -n +3 | cut -d' ' -f 1 | grep -v ^avst$ | sort -u | wc -l 7 this is an example of six small programs cooperating in one pipeline to solve a real task 8 text representation can use more memory and require parsing than binary, but it is easy for people to: - read and understand - edit - create - combine with many text-processing programs 9 Unix generally prefers text except for: - machine-code executables - digitized analog data: photographs, video, recorded sound - compressed data - encrypted data - drawings, diagrams, synthesized music, and computer animation can still be represented effectively as text 10 many Internet protocols use text streams: - e-mail and Web protocols are examples - DNS is a common binary-protocol example 11 "silence is golden": - a successful program prints only the output requested by the user - NASM and gcc normally finish silently on success 12 Unix user interfaces generally assume that the user knows what they are doing: - commands are not replaced by a supposedly wiser policy - every system function should be reachable from the command line - graphical and full-screen interfaces may offer alternatives but do not replace the command line - alternatives are often implemented by calling command-line utilities 13 graphical interfaces follow "mechanism, not policy": - provide mechanisms for building a GUI - do not dictate its appearance or behavior - users can choose among many window managers 14 "everything is a file": - file names identify ordinary files, peripheral devices, virtual devices, and communication channels - pseudo-filesystems expose kernel settings and process information - there are exceptions, including System V IPC and some Linux devices 15 Unix syscall interfaces also follow the simple-composition philosophy: - many calls have no arguments or only one to three - four-, five-, and six-argument calls are less common - no Unix syscall has more than six arguments - complex operations are built from several simple calls 16 "everything is a byte stream" in the syscall interface: - files, terminals, pipes, and many network exchanges use byte streams - positioned streams allow the current file position to change - non-positioned streams deliver bytes sequentially - datagram networking is an important exception 17 KISS = "Keep it simple, Stupid!" - Unix software favors simple designs 18 Unix software is usually distributed as portable source code: - well-written source can be compiled on other Unix systems and platforms - binary executables depend on the OS interface and hardware architecture - free licenses commonly allow copying, study, modification, and redistribution - Linux distributions consequently provide many freely available programs 19 free software is not the same as freeware or merely open source - the four freedoms are: * run the program for any purpose * study and modify it (source code must be available) * redistribute copies * distribute modified versions (source must remain available) 20 GNU GPL protects these freedoms with a copyleft condition: - exact and modified copies, and derivative works containing GPL code, must be distributed under the GPL - using GPL software means accepting its license conditions 21 GPL does not require a zero price: - a GPL program may be sold - the buyer still receives the GPL freedoms - an additional agreement cannot remove those freedoms 22 open source and free software are different: - BSD-style licenses can allow modified binaries without source - source code may be published under a license that still forbids redistribution, so source availability alone does not guarantee freedom 5.1.6 Notes on the X Window System 1 Unix architecture was not changed fundamentally by graphical desktops because graphical shells are outside the kernel 2 X Window System: - implemented entirely by ordinary user programs - kernel support is limited to generic access to the video card - other graphical systems can use the same support - Mac OS X and Android use different user-space graphical systems 3 an X GUI application remains an ordinary Unix process: - it has command-line arguments - it has stdin, stdout, and stderr - it connects to X and sends requests using the X protocol 4 X server: - draws requested objects on the user's screen - normally draws only in response to client requests - sends events back for keyboard, mouse, and required redraws 5 X connection may be local or over a network - an application can run remotely while its window appears locally 6 X uses a stream socket: - local connections commonly use AF_UNIX - network connections use AF_INET or AF_INET6 - after connection, both look like bidirectional byte streams 7 X server is also an ordinary process - kernel only provides access to the video card, for example by mapping video memory into the server's virtual address space 8 an X server need not use a physical video card: - it only has to implement the X protocol - Xvfb writes the rendered image to a file - Xming and Cygwin/X let Windows users display remote Unix applications 9 to inspect the system directly, start an X server without the usual desktop wrapper; the classic display mode uses the -retro option 10 if another X server is already running: - start the test server on :1 or :1.0 - on a clean machine, the default is :0.0 11 a bare X server shows an empty screen, a large X-shaped cursor, and its default textured background 12 without clients, the only useful action is moving the cursor - return to a text console - put X in the background with Ctrl-Z and bg, or use another console - console switching uses Alt-F1, Alt-F2, ... 13 start a client and explicitly select its display: - DISPLAY=:0.0 xterm - use the actual display identifier if the test server is :1.0 14 with only X and xterm running, the xterm window has no border, title, or minimize/maximize/close buttons 15 window decoration is provided by a separate window manager: - it is not provided by the X server - it is not required from every client -> this preserves both simplicity and user choice 16 some modern Gnome applications take over work traditionally assigned to the window manager, which makes them awkward under other window managers 17 start a lightweight window manager such as twm from xterm - fvwm2 or icewm can be used for the same experiment 18 when the window manager runs: - windows gain decorations - they can be moved, resized, and closed - killing the window manager removes decorations but leaves clients running 19 an X window manager is just another X client - it uses the same X protocol as other applications 20 an X application may run on the same host as the X server or remotely - an X terminal is a specialized machine whose main job is running X - user programs run on an application server, which need not have a display 21 X-terminal sessions need remote authentication and session setup: - xdm runs on the application server - the X server contacts it using XDMCP - after login, a session leader or window manager is started 22 terminology is confusing because several levels are involved: - an X-terminal is a client workstation toward the application server - xdm is an XDMCP server on that application server - the program on the terminal is called an X server - applications on the application server are X clients 23 at the X protocol level, the X-terminal provides the display service and is therefore the server; applications requesting display are clients 24 many X terminals plus a few application servers can reduce administration: - terminals need little hardware and usually no disks - parameters arrive over the network - only the servers need maintenance 25 traditional X terminals carried keyboard/mouse events and graphics - sound can be forwarded by programs such as JACK and PulseAudio - local hardware can play sound generated by a remote application 5.1.7 System calls and their wrappers 1 system-call entry is processor-dependent: - i386 assembly used software interrupts such as int - other processors use different mechanisms - the common idea is to transfer control to the kernel with a request 2 C normally uses library wrappers that look like ordinary C functions - assembly can bypass wrappers, but this is uncommon - syscall numbers and constants differ between Linux, FreeBSD, and other kernels - Linux changed and cache-grouped syscall numbers for 64-bit systems; the practical gain is questionable 3 C library wrappers smooth kernel differences: - they improve portability - a function can be a syscall on one system and a library emulation using other syscalls on another 4 common Unix wrapper error handling: - successful calls return their normal non-negative result - failure usually returns -1 - errno receives an error code such as ENOENT, EINVAL, EPERM, or EACCES - strerror converts the code to text; perror prints a diagnostic - syscall documentation lists the possible error codes 5 with threads, errno is usually a macro selecting a per-thread integer: - each independent thread gets its own error value - it can still be read, assigned, and addressed like an integer lvalue - do not use errno as the name of your own object 5.1.8 Privilege separation 1 user task alone: - can only transform data in its assigned memory kernel: - can use the computer's hardware capabilities - spends some of this power servicing user requests -> without kernel services, a task's results would remain invisible in its memory 2 privilege separation is essential: - some requests have no system-call interface at all (read kernel memory, reprogram memory protection, disable interrupts) - for other requests, the kernel checks whether this particular task is allowed -> a system call is both a request and a permission check 3 requests normally allowed to every task include: - _exit to terminate itself - reading the system clock - obtaining information about itself - closing its own open I/O streams 4 many requests depend on user or group identity: - a task may normally terminate another task only when both have the same owner - opening a file checks the task's owner against the file owner and permissions - open fails when the requested access is not allowed - changing file permissions is normally restricted to the owner 5 root is the Unix superuser: - owner restrictions do not apply to root's tasks - they can read/write any file and stop any task - many operations, such as changing system time, are reserved for root 6 quantitative limits can also be enforced: - maximum virtual memory for a task - maximum open files - maximum number of tasks for a user - kernel rejects a request that would exceed a limit 7 Unix privilege separation uses numeric identifiers: - uid = user identifier - gid = group identifier - both are non-negative integers - older systems may use 16-bit values; modern systems commonly use 32-bit values 8 "user" in the kernel does not necessarily mean a human: - one person can have several accounts - service programs commonly run under separate dummy accounts - from the kernel's viewpoint, a user is essentially a uid number 9 uid 0 identifies root - the kernel recognizes root by numeric uid, not by the name root 10 users can belong to groups: - every user has at least one primary group - a user may have several supplementary groups - a group can exist even when it has no members 11 groups originally supported cooperation on multi-user systems - group membership can allow access to shared files/directories - today groups also provide fine-grained rights for service accounts - example: create a printer group and give device files to that group 12 /etc/passwd and /etc/group are ordinary readable text files: - one line describes each account or group - fields are separated by colons - administrator rights are not needed just to inspect them 13 fields in /etc/passwd describe: - login name - password field - uid - primary gid - real name - home directory - login shell 14 passwords are no longer stored in /etc/passwd: - an x usually marks a moved password field - public password hashes enabled offline guessing - modern systems use /etc/shadow (root-readable) or mechanisms such as /etc/tcb 15 /etc/group has four fields: - group name - group-password field - gid - comma-separated supplementary members 16 primary-group membership comes from the fourth /etc/passwd field and need not be repeated in /etc/group - gid 0 for a group has no special meaning merely because uid 0 is root 17 kernel does not read /etc/passwd or /etc/group itself: - user-space login programs read the files and verify credentials - they set uid, primary gid, and supplementary gids on the task - they drop administrator privileges and start the user's shell or GUI session - the kernel only services the privilege-changing system calls 5.2 Input/Output and File Systems 1 input/output includes: - terminal input and output - reading and writing disk files - standard streams that may be connected to files instead of a keyboard or screen 2 programs under multitasking OSs perform I/O through system calls - Pascal hid most of the mechanism - assembly made the system-call boundary visible - C library functions can do block I/O, but direct system calls are often simpler 3 this chapter fills in file and stream details that were previously left implicit 5.2.1 File System 1 file: - named data stored on an external storage device filesystem: - OS subsystem that stores named files on external devices 2 filesystem can also mean the on-disk data structures: - superblock with general filesystem information - record of free and used sectors - file names and the sectors occupied by each file - metadata such as type, permissions, and modification time 3 "filesystem" therefore has 2 meanings: - data structures on the disk - kernel code that manages those structures 4 early filesystems used short names in one global namespace - names had to be unique - directories were introduced as storage grew 5 use directory or catalogue, not the informal word folder 6 directory: - a special file containing file names, including names of other directories - each filesystem starts with a root directory - subdirectories can be recorded in the root or in other subdirectories 7 each process has a current directory - absolute path: starts at the root / - short name: contains no slash and means a name in the current directory - relative path: starts at the current directory and may include .. 8 Unix uses one directory tree instead of device letters such as A: or C: - one filesystem supplies the root - other filesystems are mounted at directories called mount points - example: /mnt/flash/work/prog.c 9 Unix directory entry stores only: - a file name - the number of its inode (index node) - type, size, disk location, times, owner, and permissions belong to the inode - inode numbers are unique within one filesystem 10 file structure: - normally an inode plus data blocks - an empty file may have no data blocks - some special files never use data blocks - a file name is not part of the file; names occur only in directories 11 Unix file names may be about 255 characters and may contain almost any character except NUL and slash - avoid spaces, shell metacharacters, control characters, non-ASCII characters, and a leading minus - unusual names are possible but make commands difficult to use 12 hard links: - several directory entries may refer to one inode - all such names are equally valid; there is no privileged original name - hard links can cross neither disks nor filesystems - inode stores a link count, incremented and decremented with link creation/removal 13 unlink removes a directory entry, not necessarily the data: - data is removed only after the last hard link is gone - if a process still has the file open, the inode/data remain until it closes it - an unlinked open file has no name but remains a disk object temporarily 14 command ln creates a hard link - unlike cp, it creates another name and does not copy the file data 15 directory is itself a special kind of file: - its data blocks contain names and inode numbers - at the low level it differs from an ordinary file mainly by its type field - Unix has seven file types; ordinary files and directories are the common ones 16 directory restrictions: - rmdir removes a directory only when it is empty - hard links to directories are forbidden - allowing them could create cycles and make recursive traversal and deletion impossible 17 symbolic link: - special file containing the name of another file - opening it follows the stored name - has its own inode and does not change the target's inode - target may be absent or later removed -> dangling link - can cross filesystem boundaries because it stores a name, not an inode number 18 create a symbolic link with: - ln -s /path/to/old/name new_name 19 short symbolic-link targets may be stored inside the inode's block-pointer area - this avoids allocating a separate data block - longer targets use a separate block 20 other special files may also occupy no blocks outside the inode - a symbolic link can therefore use either only its inode or its inode plus a block 5.2.2 File Permissions 1 file permissions determine which processes, acting for which users, may perform operations on a file 2 inode stores: - owner uid - owner group gid - a 12-bit permission word - lower 9 bits are 3 groups of read/write/execute bits for owner, group, others 3 octal notation matches the three-bit groups: - three digits normally represent owner, group, others - read = 4, write = 2, execute = 1 - 644: owner read/write, group and others read - 751: owner read/write/execute, group read/execute, others execute 4 directory execute permission means access/traversal, not running a program: - read without execute: names can be listed, but files cannot be used - execute without read: known names can be used, but names cannot be listed - read+execute is usual - read without execute is practically useless 5 special permission bits: - SetUid 04000: executable runs with file owner's privileges - SetGid 02000: executable runs with file group's privileges - Sticky 01000: meaning depends on whether the object is a file or directory 6 SetUid is often used on administrator-owned programs - passwd is a traditional example - some systems no longer make passwd suid 7 Sticky bit originally kept frequently used executable code in memory - kernel file caching makes that optimization obsolete - today Sticky is meaningful mainly for directories 8 Unix executables can be binary or script files: - script begins with a line such as #!/bin/sh - system runs the named interpreter and passes the script name - any suitable program can be the interpreter, even /bin/cat - execute permission lets the script run like an ordinary command 9 SetUid and SetGid are ignored for executable scripts - this is an intentional security restriction 10 suid-script threat setup: - a normal user can execute a script owned by root - the user wants the script to grant broader privileges 11 starting a script involves a race: - system first opens the script to read the interpreter name - it closes that file and starts the interpreter - interpreter opens the script again 12 attacker can exploit the two opens: - replace a symbolic link from the trusted script to an attacker script - race the interpreter's second open - privileged interpreter may execute attacker-controlled code -> SetUid/SetGid are disabled for scripts 13 Sticky bit on a public writable directory: - users may remove only their own files - 01777 is typical for /tmp 14 SetGid on a directory: - new files inherit the directory's group - subdirectories inherit both the group and SetGid bit - useful for shared mail directories such as /var/spool/mail 15 SetUid on directories is ignored on most systems, including Linux - FreeBSD may use it to make new files inherit the directory owner 16 some systems interpret SetGid without group execute as mandatory locking - this feature is rarely used 17 permission and ownership tools: - ls -l uses stat to inspect permissions - chmod changes permissions - chown changes owner and group through one system call - chgrp changes only the group using chown 18 symlink permissions are normally ignored - operations use the target's permissions - chmod applied to a symlink changes the target, not the link itself 5.2.3 Reading and writing file contents 1 Unix commonly represents transferred data as byte streams - C's high-level streams use FILE* - block functions in the C library offer little advantage over syscall-level byte-oriented I/O for arbitrary streams 2 C wrappers for the basic I/O calls are named open, read, write, lseek, and close - on non-Unix systems they may be library functions rather than syscalls - their behavior can still be the same 3 system calls identify streams by file descriptors: - small non-negative integers: 0, 1, 2, 3, ... - a descriptor can refer to any I/O stream, not only a disk file 4 file descriptor and inode are unrelated: - descriptor means an open-stream number - inode (index node) is the filesystem object storing file metadata 5 standard descriptors are a convention: - 0 = standard input - 1 = standard output - 2 = standard diagnostic/error output - they are normally open at program start - kernel does not give these numbers intrinsic meaning; programs agree on the convention 6 number is only an index into a kernel data structure - the real descriptor is a complex kernel object - descriptor numbers are local to each process - descriptor 5 can refer to different objects in different processes 7 open creates a new I/O stream and has two profiles: - int open(const char *name, int mode); - int open(const char *name, int mode, int perms); 8 open name and mode: - name may be short, absolute, or relative - mode is a bit mask of options combined with | - exactly one basic mode is required: O_RDONLY, O_WRONLY, or O_RDWR 9 common modifying flags: - O_APPEND: write at the end of the file - O_CREAT: create when absent - O_TRUNC: discard old contents and set length to zero - O_EXCL with O_CREAT: fail if the file already exists 10 O_NONBLOCK makes reads and writes return immediately instead of waiting - an operation may then fail if the stream is not ready - other flags exist as well 11 perms is used only when O_CREAT may create a new file - ignored for an existing file - must be supplied when a new file may be created 12 umask: - per-process mask inherited by child processes and launched programs - bits set in umask are removed from requested permissions for new files - applies to files, directories, and other newly created objects - umask(mask) changes the process's mask and returns the previous value - only the lower 9 bits matter 13 common umask choices: - 022 removes group/other write permission - 027 denies access to users outside the group - 077 denies all access to everyone except the owner - shell umask changes only that shell session and its children 14 new ordinary data files usually request perms 0666 - read/write for owner, group, and others, with umask removing unwanted bits - 0600 is suitable for confidential data - execute permission is normally not requested for data files 15 open result: - -1 on error - a file descriptor for the new stream on success 16 opening must always be checked - open has many failures outside the program's control - ignoring whether the result equals -1 makes the program incorrect 17 read and write profiles: - int read(int fd, void *mem, int len); - int write(int fd, const void *data, int len); - fd selects the stream, buffer points to memory, len is the requested byte count 18 read behavior: - blocks if no data is ready - returns as soon as at least one byte is available - may return fewer bytes than requested 19 write may block on streams with limited kernel buffers: - network output can be slower than the producer - a pipe can block when its reader is not consuming data - ordinary disk-file writes rarely block for this reason 20 read/write results: - -1 means error - positive result is the number of bytes transferred, never more than len - read returns 0 at end of stream - EOF meaning depends on the stream: end of file, Ctrl-D, or peer disconnect 21 always inspect read's result - do not discard it with read(fd, buf, sizeof(buf)); - store it, for example count = read(fd, buf, sizeof(buf)); 22 write results should normally be checked too - a write may return less than len when a disk fills - a nonblocking network stream may accept only what fits in its kernel buffer - repeat writes as needed for the remaining bytes 23 without O_NONBLOCK, write usually waits until all supplied data is accepted - O_NONBLOCK can be set when open is called - fcntl can set it later, including for streams not created by open 24 modern write returns zero only when len is zero, which should not be relied on - older Unix systems had rarer zero-return cases 25 lseek changes the current position in an open stream: - long lseek(int fd, long offset, int whence); - whence = SEEK_SET, SEEK_CUR, or SEEK_END - returns the new position measured from the beginning 26 seeking past the end and writing creates a sparse-file hole - hole reads as zero bytes - zero-filled regions need not occupy physical blocks 27 only some streams are seekable - ordinary disk files support lseek - pipes, terminals, and other non-positioned streams do not 28 off_t size matters: - on old 32-bit systems it was a signed 32-bit value - lseek could therefore not address files over 2 GB 29 lseek64 supplies a 64-bit offset and return value - on 64-bit systems long and long long may already have the same size 30 close releases a descriptor: - descriptors are limited system/process resources - int close(int fd) returns 0 on success and -1 on error - descriptor is closed even when close reports an error 31 check close especially after writing - kernel may buffer output and perform physical I/O later - delayed write errors may be reported only by close 32 several descriptor numbers may refer to one kernel stream object - close removes only that number - the kernel object disappears only after its last descriptor is closed 33 asynchronous output is common: - write copies data into kernel memory and returns - physical output is scheduled later when the device is available - processes can continue without waiting for the device 34 asynchronous output can lose data on a crash or power failure - a mail server may read a message from a queue, write the mailbox, then delete the queue copy - interruption between these steps can lose the message 35 fsync waits for one file's pending data and required metadata: - int fsync(int fd); - returns 0 on success and -1 on error - physical write is complete before it returns 36 fdatasync is similar to fsync - guarantees data and metadata needed to read it correctly - need not force irrelevant metadata such as the last-modification time 37 sync requests system-wide writeback: - no parameters and no return value - waits for all pending filesystem data to be physically written - request is accepted by every process, not only root - kernel schedules the work normally rather than abandoning all other work 38 fcntl configures descriptor behavior: - int fcntl(int fd, int cmd, ...); - command determines the number and types of additional arguments 39 open flags have categories: - access mode: O_RDONLY, O_WRONLY, O_RDWR - creation flags: O_CREAT, O_EXCL, O_TRUNC, O_NOCTTY - status flags: O_APPEND, O_NONBLOCK, and others - status flags can be changed after open - F_GETFL reads the current status flags 40 test a status flag with bitwise and: - flags = fcntl(fd, F_GETFL); - if (flags & O_APPEND) { ... } 41 F_SETFL changes status flags - preserve existing flags while adding O_NONBLOCK: flags = fcntl(fd, F_GETFL); fcntl(fd, F_SETFL, flags | O_NONBLOCK); 42 fcntl(fd, F_SETFL, O_NONBLOCK) is enough when no other status flags matter - more fcntl commands will be introduced later 5.2.4 Managing filesystem objects 1 filesystem-object calls cover operations besides reading and writing - failure convention is usually -1 - success is another value, commonly 0 2 link creates a hard link: - int link(const char *oldpath, const char *newpath); - oldpath must name an existing file and newpath the new name - both arguments name files, not directories - ln can additionally accept a destination directory, but link cannot 3 unlink removes a directory entry: - int unlink(const char *name); - it does not remove directories 4 unlink deletes file data only after the last link is removed and the file is closed by the last process using it - an orphaned inode may survive an unclean shutdown until the next boot 5 rename changes a file name or moves it within one filesystem: - int rename(const char *oldpath, const char *newpath); - source and destination may be in different directories - moving across filesystems is not supported 6 rename can atomically replace an existing non-directory target - directory replacement has stricter rules - network filesystems may not provide full atomicity 7 mkdir and rmdir create and remove directories: - int mkdir(const char *name, int perms); - int rmdir(const char *name); - perms is filtered by umask - 0777 is common; 0700 protects a sensitive directory 8 symlink creates a symbolic link: - int symlink(const char *oldpath, const char *newpath); - oldpath must be non-empty but need not exist - newpath becomes a symlink, possibly dangling 9 unlink applied to a symbolic link removes the link itself - it does not follow the link to remove the target 10 chmod changes permission bits: - int chmod(const char *path, int perms); - example: chmod("file.txt", 0600); - ordinary users may change only files they own; root is unrestricted - umask does not affect chmod 11 chown and lchown change ownership: - chown follows a symlink; lchown changes the link itself - -1 preserves the corresponding uid or gid - only root may change an owner - owner may change the group only to one of the owner's groups - 0 means success, -1 means error 12 stat, lstat, and fstat obtain metadata: - stat(path, buf) follows a symbolic link - lstat(path, buf) reports the link itself - fstat(fd, buf) reports an open object without its name - struct stat includes device, inode, mode/type, link count, uid, gid, device id, size, block size/count, and access/modification/status times - st_mode contains type and permissions; mask with 07777 to extract permissions 13 truncate and ftruncate change file length: - truncate uses a path; ftruncate uses an open descriptor - shortening discards data after the new length - extending reads as zeroes and may create holes - truncate requires write permission; ftruncate requires O_WRONLY or O_RDWR 5.2.5 Device files and device classes 1 Unix presents many external devices as special files: - disks - serial and parallel ports - virtual terminals -> ordinary file operations become a general device interface 2 device-file examples: - cat /dev/cdrom > image.iso reads a CD image - cat myfile.ps > /dev/lp0 sends data to a printer port - print subsystems normally provide a higher-level interface 3 device files use ordinary system calls: - open the disk device - lseek to a sector - write the sector -> disk formatting can be implemented this way 4 older Linux audio devices could be read and written as files - copying bytes from a microphone device to a sound device reproduced sound - modern audio subsystems are more complex 5 not every peripheral has a file representation - Linux does not provide device files for network interfaces 6 device files are either: - character/stream/byte-oriented * transfer bytes or sequences of bytes - block-oriented * transfer fixed-size blocks - examples of character devices: terminal, printer port, mouse, sound card 7 pseudo character devices: - /dev/null discards writes and returns EOF on reads - /dev/zero returns unlimited zero bytes and discards writes - /dev/full returns zeros on read and ENOSPC on write - /dev/random returns random data 8 block devices usually represent disks - physical disks may require whole-sector operations - the driver can satisfy an unaligned user request by reading several sectors - kernel caching is often associated with block devices 9 device files are special file types alongside directories and symbolic links - both classes support open, read, and write - block devices support lseek - character devices do not support positioning - ordinary disk files and block devices are the only seekable streams 10 FreeBSD moved away from a separate block-device type because of cache control - all device files there are character-oriented - disk-related ones may still support lseek - Linux and other BSD systems retain block devices 11 ioctl handles device-specific operations: - int ioctl(int fd, int request, ...); - examples: open/close a CD tray, set serial speed, format a floppy, control sound volume - e.g. ioctl(fd, CDROMEJECT) and ioctl(fd, CDROMCLOSETRAY) - additional arguments depend on request; CDROMPLAYTRKIND can select an audio track 5.2.6 Reading directory contents 1 directory is a special disk file containing names and inode numbers 2 kernel alone changes directory contents: - create, remove, or rename files/hard links - direct writes are forbidden to preserve filesystem integrity - directories may be opened read-only, but read on their descriptor does not work - Linux and FreeBSD use getdents internally; direct use is non-portable 3 C library directory interface: - DIR *opendir(const char *name); - struct dirent *readdir(DIR *dirp); - int closedir(DIR *dirp); - DIR* is library-managed state, analogous to FILE* 4 readdir returns a pointer to a library-owned struct dirent - one state object is used for each open directory - the next readdir call may overwrite the previous record 5 when entries are exhausted, readdir returns NULL - call closedir to release the descriptor and library state 6 struct dirent is system-dependent: - d_name is always present, but its array size is not generally fixed - NAME_MAX gives the implementation's maximum name length - d_ino usually contains the inode number - other fields vary by system 7 sample directory listing program: - choose argv[1] or . - opendir the directory and report errors with perror - loop while readdir returns non-NULL - print dent->d_name - closedir at the end 5.2.7 Memory-mapped files 1 mmap maps file contents into a process's virtual address space - file data can then be accessed like ordinary memory variables - void *mmap(void *start, int length, int protection, int flags, int fd, int offset); 2 before mmap, open the file and pass its descriptor in fd - offset and length select the file region - mappings use whole pages - start, length, and offset are constrained by page size - getpagesize() reports the relevant page size - length is rounded up; an unaligned offset is an error 3 mmap page size need not equal the virtual-memory page size - old Linux versions could report unusual values such as 16 4 protection flags: - PROT_READ and PROT_WRITE allow reading/writing - PROT_EXEC allows execution, for example for dynamic libraries - PROT_NONE forbids all access - protection must be compatible with the file's open mode 5 flags select shared or private behavior: - MAP_SHARED writes can be reflected in the file - MAP_PRIVATE changes are private to the mapping - MAP_ANONYMOUS creates memory without a file; fd and offset are ignored 6 MAP_ANONYMOUS|MAP_SHARED creates shared memory across forked processes - parent and child see each other's changes - shared memory is useful for process interaction but has subtle synchronization problems 7 start is an optional preferred address - passing NULL lets the system choose a free virtual area - non-NULL placement is outside the basic discussion 8 mmap returns the mapped address - failure is MAP_FAILED, equal to -1 converted to void* 9 example mapping: - open file.dat read/write - get its size with lseek(fd, 0, SEEK_END) - map it with PROT_READ|PROT_WRITE and MAP_SHARED - p[25] reads the 26th byte; p[25] = 'a' changes that byte 10 file length need not be page-aligned: - unused bytes at the end of the last mapped page read as zero - writes there do not change the file - mapping well beyond the file may fail with MAP_FAILED - touching a page wholly beyond the file may cause SIGBUS, even after mmap succeeded 11 munmap cancels mappings: - int munmap(void *start, int length); 12 munmap removes every page intersecting the requested range - range need not equal one original mapping - it can remove part of a mapping or several adjacent mappings - start must be page-aligned; length may be any positive value 13 msync can force modified mapped pages to be written to the file - details are left for later study 14 mmap is now also a general virtual-memory allocation interface - BSD malloc can use MAP_PRIVATE|MAP_ANONYMOUS - passing fd = -1 and offset = 0 creates memory directly from the OS 5.3 Processes 5.3.1 What a process is 1 process: - an entity created by the OS kernel to execute a user program 2 technical terms can become established before anyone defines them precisely - process is one such term - simple definitions admit counterexamples 3 first approximation: a program that has been started - includes code and execution state: variable values, current instruction, ... - can own resources such as open files - has permissions problem with this approximation: - the running kernel is also a program - the kernel as a whole is not a user process - it enforces process permissions and may contain several execution contexts 4 bare-metal firmware is another counterexample: - runs directly on hardware, without an OS - has execution state but no OS-created process around it 5 working approximation: a program executing under OS control - useful for understanding processes, but still incomplete - Unix can replace the program while keeping the same process 6 kernel's view of a process: - a data structure supporting execution of a user program - records assigned memory, permissions, open streams, ... - stores register contents while the process is not running - switching out: save CPU registers into this structure - switching in: restore those registers 5.3.2 Process properties 1 process identifiers: - pid: unique identifier of a process currently present in the system - ppid: identifier of its parent - traditional Unix: orphaned processes are adopted by process 1 Linux can also reparent them to a designated subreaper - pgid: process group identifier - sid: session identifier 2 permissions belong to the process acting for a user - uid, gid: real user and group identifiers - euid, egid: effective user and group identifiers - real and effective identifiers normally agree - set-user-ID programs can execute with the executable owner's permissions 3 query identifiers using getpid(), getppid(), getuid(), getgid(), geteuid(), getegid(), and related calls - these no-argument getters return the calling process's corresponding IDs - session/group queries have different interfaces: getsid(0), getpgid(0), or getpgrp() - cannot assign a new pid or directly set ppid - session/group membership and credentials have separate rules for changes 4 process memory consists of regions with different properties - called segments or mappings - executable-file sections and runtime mappings are related but not identical 5 main memory regions: - code: machine instructions, normally read-only and shareable - data: global variables and, in the simplified model, the heap - heap: dynamically allocated objects - stack: local variables, return addresses, and call state - other mappings depend on the program and system 6 register state is part of process state: - instruction pointer, flags, stack pointer, general-purpose registers - saved in the kernel when the process is blocked or waiting for CPU time - restored when execution resumes 7 CPU scheduler selects processes to run - readiness: whether the process can continue executing - priority: influences selection among ready processes - some schedulers also use priority to determine time-slice length book's example scheduler: - total priority = static priority + dynamic priority - waiting raises the dynamic component - running lowers it -> eventually a waiting process can take the CPU 8 static scheduling preference in Unix is usually expressed by nice value - adjusted with nice and setpriority - background calculations can receive less CPU preference - response-sensitive work can receive more - the scheduler controls its own dynamic calculations 9 command-line arguments and environment are also process properties - Linux exposes initial argument/environment storage through /proc, subject to access permissions - environment: NULL-terminated array of pointers to strings - each string has the form NAME=value 10 new programs normally inherit the launching program's environment - exec library wrappers arrange this inheritance - execve receives the environment explicitly - C access: extern char **environ; - environ points to the first element of the NULL-terminated pointer array - declaration availability depends on headers and feature settings 11 some implementations allow a third parameter to main for the environment - pointer-array representation like argv - this is an implementation extension, not a portable ISO C main signature 12 environment strings live in process memory -> ordinary library functions suffice - getenv(name): returns the value string or NULL when absent - always check NULL, even for PATH and HOME - setenv(name, value, overwrite): creates the variable if missing - replaces an existing value only when overwrite != 0 - unsetenv(name): removes the variable - setenv and unsetenv return int status values 13 Linux /proc/PID/environ and the library's current environment can differ - setenv/unsetenv can change pointers and heap strings used by environ - /proc exposes the initially recorded environment memory region - directly overwriting that region can change what /proc displays - such overwriting does not itself update the library's environment model 14 some programs change their displayed command line to show current activity - overwriting argv storage can affect ps output on Linux - storage is limited and may border the original environment strings - do not overwrite beyond the available area - this technique is platform-specific 15 current working directory: - starting point for relative paths - affects system calls receiving relative file names - a process can change its own current directory 16 root directory: - starting point for absolute paths - with process root /foo, /bar resolves inside /foo/bar - restricts ordinary pathname lookup to a subtree - inherited by descendants 17 chroot is not a complete security boundary - privileged processes can escape under suitable conditions - interaction with same-user processes outside the tree can undermine isolation 18 change directory with chdir(path) - path can be absolute or relative - .. denotes the parent directory change process root with chroot(path) 19 chroot changes pathname resolution for this process and its descendants - requires the appropriate privilege - does not change the current directory automatically - existing directory references and privileges matter for isolation - current/root directories cannot be changed directly for another process 20 file descriptor table is another process property - descriptors are small integers local to a process - corresponding kernel objects contain the actual stream state - files and sockets require different kernel state - descriptor 0 in two processes need not identify the same stream 21 descriptor table maps numbers to kernel I/O objects - open creates an entry; close removes one - other calls can create streams without open - descriptor-manipulation calls can change these mappings directly 22 umask is a process property - controls which permission bits are removed when creating files - changed with umask() 23 other process properties: - signal dispositions: what to do when each signal arrives - resource counters: CPU time, memory use, ... 5.3.3 Virtual address space 1 executable sections and runtime memory segments were introduced with assembly - now examine the address space seen by a user-mode program 2 virtual addresses are translated to physical addresses by the MMU - all possible virtual addresses form the virtual address space - translation rules can change - paging is the usual translation mechanism - each process has its own virtual address space - one physical page can appear at different virtual addresses within one process or in several processes 3 memory organization depends on hardware and OS - some embedded processors have no MMU - systems without virtual memory do not follow this model 4 book's example: a simplified Linux/i386 address space - exact layout is architecture-, executable-, and system-dependent - unused virtual ranges consume address space, not physical RAM 5 illustrated executable starts at 0x08048000 - chosen through executable/linker settings, not an immutable kernel rule - other architectures and executable types use different addresses - leaving addresses near zero unmapped helps detect NULL-pointer bugs - also catches some small offsets calculated from NULL 6 code/data regions are mappings in the kernel's memory model - mmap is a general mechanism for managing virtual memory - mappings need not represent disk files - Linux /proc/PID/maps lists a process's mappings, subject to access checks 7 initial mappings: - text: executable code mapped from the executable file - data: initialized data mapped from that file - bss: zero-initialized storage, commonly backed by anonymous memory - exact section/page grouping depends on linker layout - stack: anonymous memory - further mappings can be created while the program runs 8 Linux also provides brk for changing the program break - program break marks the end of the traditional heap area - increasing it can provide more heap memory - book describes the raw Linux syscall: brk(0) reports the current break - the C library brk wrapper instead reports success/failure - sbrk(0) is the traditional library interface for querying the break 9 address-space randomization introduces unpredictable gaps and positions - heap start, stack, and mmap placement can vary between runs - makes addresses of runtime objects harder to predict - can make exploitation of memory bugs more difficult 10 stack has a configured size limit, often 8 MB in the book's example - the virtual limit does not mean all those physical pages exist immediately - initial stack contains argument/environment strings and pointer arrays - additional pages are supplied as the stack grows - access to a not-yet-backed page traps into the kernel - kernel can allocate a page and resume the interrupted instruction - exceeding stack or address-space limits instead causes failure -> avoid unnecessarily large stack allocations 11 heap and mmap areas can grow into the remaining virtual space - illustrated layout lets them grow toward one another - growth is bounded by available address space and process resource limits - allocation must fail rather than overlap an existing mapping 12 illustrated i386 split reserves 0xC0000000–0xFFFFFFFF for kernel addresses - user-mode access to this area is forbidden - the kernel also executes through virtual addresses and the MMU - system calls must access user buffers, file names, and other arguments - having kernel and current-process memory available together simplifies this 13 in the illustrated design: - lower 3 GB: current process mappings - upper 1 GB: kernel mappings - kernel can access both while servicing that process - another process's memory needs additional handling 14 traditional implementation includes protected kernel mappings in each process's page tables - user-mode permissions prevent process access - kernel mode can use them while retaining access to that process's memory - this explains the memory context of a process executing in kernel mode - actual kernels may use additional separation mechanisms 15 systems can add special mappings such as Linux vDSO - kernel-provided code/data can serve some requests without a syscall - reading the time is one example - exact mappings and mechanisms are platform- and version-specific 5.3.4 Creating a process 1 traditional Unix process creation: duplicate an existing process with fork() - declaration uses pid_t fork(void) - some systems also expose platform-specific creation interfaces 2 fork results: - -1: creation failed - parent receives the child's pid - child receives 0 child initially resembles parent, with important differences: - new pid - ppid equals parent's pid - resource-use counters start at zero - both continue immediately after fork 3 not every property is inherited - for example, the child does not inherit a pending alarm() timer 4 three successive successful fork calls produce eight processes - 1 -> 2 -> 4 -> 8 - each process reaches the following printf("Hello\n") -> eight lines are printed 5 parent and child usually need different work - test the fork result with if - p == 0: child branch - p > 0: parent branch - child can call exit after its work to avoid falling into parent code 6 also handle p == -1 - possible causes include process-count limits and insufficient resources - an else branch alone does not distinguish parent success from failure 7 parent and child execute concurrently - execution order after fork is not guaranteed - an example prints one message from each process 8 parent may print first - child has not yet been scheduled when parent reaches printf 9 child may print first - parent can lose the CPU immediately after fork - child can run and print before parent resumes 10 race condition: result depends on the ordering of independent events - common when several control flows run concurrently - overlooked races can cause incorrect results and security problems 11 ordinary private memory is logically copied by fork - child starts with the same variable values - later writes in one process do not change the other's variables - read-only code can remain shared - implementations commonly use copy-on-write: share physical pages until a write requires a private copy - descriptor table and signal dispositions are inherited too 12 MAP_SHARED mappings are an exception to private-memory copying - create anonymous shared storage before fork - example requests 4096 bytes with PROT_READ|PROT_WRITE - flags: MAP_SHARED|MAP_ANONYMOUS - round requested size up to a multiple of page size - check mmap result against MAP_FAILED 13 both processes then access the same mapped storage through ptr - 4096 bytes contain 1024 four-byte ints - ptr[77] = 120 changes shared storage visible to both 14 shared memory needs synchronization - access ordering and concurrent modification require explicit care - simply having a shared pointer does not make an algorithm correct 15 fork copies the descriptor table, not the underlying open-file descriptions - descriptors are local integer references to kernel objects - corresponding parent/child descriptors refer to the same open streams 16 shared open-file descriptions include the current file offset - lseek in one process changes where the other next reads or writes - several descriptors can refer to one stream in other situations too 5.3.5 Replacing the running program 1 exec replaces the program inside an existing process - new program begins at its entry point - the process itself continues to exist - process identity and program identity are different things 2 advantage of separating creation and program replacement: - configure the process before running the new program - inherited properties include many credentials and open descriptors - change only what the new program needs changed - some properties have special exec rules, including set-ID credentials 3 an interface combining creation and execution must receive more settings at once - book contrasts this with Windows process-creation interfaces - those take many arguments and configuration structures 4 execve performs program replacement - execve(path, argv, envp) - argv and envp are NULL-terminated arrays of string pointers 5 execve arguments: - path: executable file, absolute or relative to current directory - argv: arguments delivered to the new program - envp: environment delivered to the new program - explicit environment means the kernel need not infer inheritance 6 exec library functions provide convenient wrappers around execve - execv(path, argv) 7 execv uses the caller's current environment - no explicit environment argument -> environment inheritance 8 execvp(file, argv) has the same argument arrangement as execv 9 execvp can search PATH - if file contains no /, search directories listed in PATH - if file contains /, use it directly as a pathname - "ls" can locate /bin/ls through PATH - "./prog" explicitly selects prog in the current directory - shell command lookup follows the same general distinction 10 when argument count is known in source code, an argument list is convenient - execl(path, argv0, ...) - execlp(file, argv0, ...) 11 execl/execlp form argv from their variadic arguments - terminate the list with a null pointer, e.g. (char *)NULL - argv0 is the program's conventional name, not its first user argument - executable path and argv0 are separate arguments - execl uses a pathname - execlp follows the same PATH/slash rules as execvp 12 example: run ls -l -a /var - char *args[] = { "ls", "-l", "-a", "/var", NULL }; execvp("ls", args); - or execlp("ls", "ls", "-l", "-a", "/var", (char *)NULL); 13 successful exec never returns to the old program - old program image has been replaced - any return from exec means failure; return value is -1 - usual child failure path: report error, then terminate with failure status - otherwise child may incorrectly continue the launching program's work 14 exit performs library cleanup before terminating - fork can copy unflushed stdio output buffers - child exit can flush its copy - parent can later flush the same original bytes again -> duplicated output 15 _exit avoids flushing inherited stdio buffers - useful after an exec failure in the child - any newly buffered diagnostic output must still be delivered deliberately - stderr is normally unbuffered; code can change its buffering 16 book's explicit failure sequence: - execlp("ls", "ls", "-l", (char *)NULL); - perror("ls"); - fflush(stderr); - _exit(1); 17 flush pending parent diagnostics before fork when needed - prevents inherited buffered diagnostic text being emitted twice - same copying issue applies to other buffered output streams 18 exit, _exit, and return from main are examined in the next subsection 19 open descriptors normally survive exec - arrange descriptors before replacement - new program inherits the resulting input/output connections -> basis of I/O redirection 20 FD_CLOEXEC is the exception - descriptor marked close-on-exec is closed on successful replacement - applies to that descriptor, not every reference to the stream 21 descriptor flags and stream status flags are different - fcntl F_SETFL changes shared stream flags such as O_APPEND/O_NONBLOCK - FD_CLOEXEC belongs to one descriptor-table entry - several descriptors can refer to one shared open-file description 22 fcntl descriptor-flag commands: - F_GETFD: read descriptor flags - F_SETFD: set descriptor flags - fcntl(fd, F_SETFD, FD_CLOEXEC) sets close-on-exec 23 query using fcntl(fd, F_GETFD) - check for -1 on error - otherwise test result & FD_CLOEXEC 24 open(..., O_CLOEXEC, ...) can set close-on-exec at creation - avoids a separate fcntl step - availability on older target systems must be checked 5.3.6 Process termination 1 two main termination paths: - voluntary: process asks the kernel to terminate it - signal: a terminating signal ends the process 2 ordinary language-level termination eventually requests kernel termination - C return from the initial main call performs normal exit processing - exit(code) does the same from elsewhere - _exit(code) requests termination without that library cleanup - declaration: void _exit(int code) 3 exit status convention: - 0: success - nonzero: failure or another documented outcome - traditional wait interfaces expose only the low eight bits -> use values from 0 to 255 exit versus _exit: - exit flushes stdio output and runs normal library cleanup - _exit does not flush user-space stdio buffers 4 example: printf("Hello, world"); followed by _exit(0) - with ordinary buffered stdout, text remains in its buffer and is lost - exit(0) or return 0 from main flushes it 5 adding a newline changes the example's behavior when stdout is line-buffered - printf("Hello, world\n"); followed by _exit(0) 6 usual terminal output: newline flushes the line -> message appears usual redirected output: fully buffered -> message may remain unflushed - ./h prints the message - ./h | cat and ./h > file can produce no message 7 newline flushing depends on buffering mode - terminal stdout is normally line-buffered - redirected stdout is normally fully buffered second example: print a line, fork, then return from main 8 second example prints once to the terminal but twice when redirected - terminal line was flushed before fork - redirected line remains buffered at fork 9 explanation of the duplicated redirected output: - fork copies the buffer into the child - both processes perform normal exit processing - both flush the same previously buffered line 10 _exit, exit, and return from main are voluntary termination - process supplies an exit status - termination by signal is a separate case 11 signal termination has a signal number, not a normal exit status - process did not reach a terminating call supplying a status - wait status distinguishes these outcomes 12 fatal program errors are commonly reported through signals - invalid memory access or certain arithmetic faults cause CPU exceptions - kernel identifies a process error and delivers the corresponding signal - signal number helps identify the cause 13 termination leaves information that the parent may need - normal termination versus signal - exit status or terminating signal - resource-use counters - pid must remain reserved until this information is collected -> terminated process can remain as a zombie 5.3.7 Waiting for termination; zombie processes 1 parent collects the child's termination information - normal exit/status or terminating signal - resource usage - traditional Unix orphans are adopted by process 1 - Linux can use a designated subreaper as the adopting ancestor - unrelated processes cannot normally reap someone else's child 2 zombie occupies a process-table entry until it is reaped - wait-family calls collect status and remove that entry - simplest interface: pid_t wait(int *status) 3 wait behavior: - no children to wait for: -1, with errno indicating the error - living children but no completed child: block - completed child available: collect its status and reap it - return that child's pid - non-NULL status receives encoded termination information - wait(NULL) reaps without storing the status 4 decode wait status with macros: - WIFEXITED(status): normal termination - WEXITSTATUS(status): exit code, only after WIFEXITED is true - WIFSIGNALED(status): termination by signal - WTERMSIG(status): signal number, only after WIFSIGNALED is true - inspect errors before using status - -1 can also indicate interruption; it does not always mean no children 5 wait4 offers child selection, options, and resource accounting - wait4(pid, status, options, usage) 6 wait4 child selector: - positive pid: that specific child - -1: any child - waiting only for one child can leave other completed children unreaped 7 process-group selectors: - 0: any child in the caller's process group - less than -1: any child whose group ID equals the negated value - -2735 selects group 2735 - group selection still applies only to children the caller may wait for 8 remaining wait4 arguments: - status: encoded outcome, as with wait - options = 0: ordinary blocking wait - WNOHANG: return immediately if no selected child has a reportable outcome - non-NULL usage: receive a struct rusage with resource counters 9 wait4 results: - -1: error - 0: WNOHANG and no qualifying completed child - positive value: pid whose outcome was collected 10 related interfaces: - wait3(status, options, usage) - waitpid(pid, status, options) 11 in the cases discussed here: - wait3 corresponds to wait4 with pid = -1 - waitpid corresponds to wait4 with usage = NULL - the several interfaces reflect historical development 12 cannot kill a zombie: it has already finished executing - parent must collect its status - if parent disappears, the adopting process can reap it - sending signals to the zombie cannot make it run cleanup 13 blocking on one particular child can delay reaping all the others - completed siblings may remain zombies for a long time - persistent zombies indicate missing or delayed collection 14 when waiting for one target among several children: - reap completed children in a loop - compare each returned pid with the target - preserve any other statuses the program needs 5.3.8 Example of launching an external program 1 fork + exec + wait: - start ls -l -a /var - wait for it to finish - print "Ok" creation: - pid = fork(); - pid == -1: perror("fork"), terminate with failure child, pid == 0: - execlp("ls", "ls", "-l", "-a", "/var", (char *)NULL); - successful exec replaces child program and never returns - returned exec: report the error and terminate the child - use the preceding subsection's flushing/_exit precautions as appropriate parent, pid > 0: - wait(NULL) waits for and reaps the child - printf("Ok\n"); then return 0 - this simple example discards child status - "Ok" therefore reports reaching the final step, not verified ls success - production code must also handle wait errors/interruption 5.3.9 Process Execution and Time 1 program execution takes time - kernel maintains the system clock - programs can read the time and arrange work around particular times or intervals 2 time(&t): current time as seconds since the Epoch - Epoch = 1 January 1970, 00:00:00 UTC - return type: time_t 3 book's historical aside: Unix time passed 1,500,000,000 seconds on 14 July 2017 - first billion: 2001; second billion: 18 May 2033 4 time also stores its result through the supplied time_t pointer - time(NULL): use only the return value; no additional variable is written 5 use time_t for a variable whose address is passed to time - its underlying integer type depends on the implementation - integer values can be converted on assignment; incompatible pointer types cannot be substituted just because both pointed-to objects hold integers 6 convert seconds since the Epoch to calendar fields: - gmtime / gmtime_r: UTC - localtime / localtime_r: configured local time zone - input: pointer to time_t; result: struct tm struct tm fields: - tm_year: year minus 1900; 2016 -> 116 - tm_mon: month 0..11; tm_mday: day 1..31 - tm_hour: hour 0..23; tm_min: minute 0..59 - tm_sec: seconds, normally 0..59 - tm_wday: weekday 0..6, Sunday = 0 - tm_yday: day of year 0..365 - tm_isdst: daylight-saving-time indication 7 convert a date/time into a fixed-format string: - asctime / asctime_r: input is struct tm - ctime / ctime_r: input is time_t - example result: "Sat Oct 22 00:57:53 2016\n" 8 functions ending in _r write into storage supplied by the caller - ordinary versions return pointers to library-owned storage - a later call can overwrite an earlier result - copy a result that must survive another call, or use caller-owned storage 9 strftime formats a struct tm using a format string - caller supplies output buffer and its size - useful when the fixed asctime / ctime format is unsuitable 10 one-second resolution is too coarse for many communication timeouts gettimeofday(&tv, NULL): obtain time in struct timeval - tv_sec: whole seconds since the Epoch - tv_usec: microseconds within that second; 1 microsecond = 10^-6 second - obsolete time-zone argument should be NULL 11 sleeping process: temporarily asks for no CPU time - sleep(seconds) blocks the caller for the requested number of seconds - sleep(60): request a one-minute pause - after the interval, the process becomes eligible to run again 12 sleep is a library function that can be implemented through other system calls - a separate kernel operation specifically named sleep is unnecessary 13 sleep return value: - 0: requested interval completed - positive: seconds remaining when a handled signal interrupted the sleep - includes a remaining fraction of a second in the returned whole-second count 14 usleep requests a pause in microseconds - some implementations require an argument below 1,000,000 - sleep(3), then usleep(500000), attempts a 3.5-second pause 15 combining sleep and usleep adds overhead and reduces timing precision - entering/leaving the kernel takes time - becoming runnable does not mean immediately receiving CPU time - other runnable processes may delay actual execution 16 usleep returns 0 on completion or -1 on failure/interruption - does not directly report the remaining interval - book measures elapsed time by reading the clock before and after the call 17 nanosleep(&requested, &remaining): request a pause using struct timespec - tv_sec: whole seconds - tv_nsec: nanoseconds, 0..999,999,999; 1 nanosecond = 10^-9 second - requested specifies the interval - on interruption, remaining can receive the unexpired part - provides one interface for intervals both shorter and longer than a second - can also underlie the library sleep functions 18 nanosecond units do not guarantee nanosecond timing accuracy - actual clock resolution and scheduling delays depend on the system - the book's 1000 timer interrupts/second is an illustrative historical model, not a universal limit on modern timer resolution 19 priority affects how a process receives CPU time - book separates a user-controlled static priority from scheduler calculations - Linux nice values: -20 = highest priority, 19 = lowest - some Unix systems use an upper endpoint of 20 - ordinary starting nice value: 0, unless inherited or explicitly changed 20 nice(increment): add to the current nice value - positive increment -> larger number -> lower scheduling priority - values are limited to the supported range - nice(1000) therefore requests the lowest available priority - returns the new nice value; nice(0) can read the current value 21 negative nice increment requests a higher scheduling priority - requires the appropriate privilege or permission - book describes the traditional rule allowing this only to superuser processes 22 -1 from nice may mean either failure or a legitimate nice value of -1 - set errno = 0 before the call - if the result is -1, inspect errno to distinguish error from success - requesting an unauthorized priority increase is an error 23 nice value survives exec and is inherited through fork - set it before executing an external program to control that program's priority - a login process can establish a priority inherited by the user's session - raising priority still requires permission 24 getpriority(which, who) / setpriority(which, who, priority): - PRIO_PROCESS: who identifies a process by pid - PRIO_USER: who identifies a user's processes by uid - PRIO_PGRP: who identifies a process group by pgid getpriority: - returns the nice value for the selected processes - if values differ, returns the smallest number / highest priority setpriority: - assigns the requested nice value to selected processes - ordinary users can generally change only their own processes - increasing scheduling priority requires permission 25 getpriority has the same -1 ambiguity as nice - clear errno before calling; check it when the result is -1 5.3.10 Redirecting Input and Output 1 file descriptors can refer to files, pipes, sockets, and other kernel objects - open and similar descriptor-allocating operations choose the lowest free number - after close(0), the next successful open normally obtains descriptor 0 - close releases a descriptor regardless of the kind of object behind it 2 standard descriptor numbers are a convention used by programs and libraries: - 0: standard input - 1: standard output - 2: standard error - kernel does not give these numbers a special file type redirecting stdout by closing and reopening: - close(1) - open("file.txt", O_WRONLY|O_CREAT|O_TRUNC, 0666) - if 0 remains open, successful open gets descriptor 1 - printf / putchar then write to that file through the usual stdout stream 3 closing stdout before opening its replacement is fragile: - if open fails, descriptor 1 remains closed - a later unrelated open may accidentally become stdout dup(fd): duplicate an existing descriptor using the lowest free number - both descriptors refer to the same open file description - does not create an independent I/O stream or file position - lseek through either descriptor changes their shared offset - same sharing occurs when fork copies the descriptor table 4 dup2(fd, new_fd): duplicate fd at a specified descriptor number - if new_fd is open, it is replaced by the duplicate - closing the old destination and replacing it are one operation - if the two descriptor numbers are identical and valid, nothing changes 5 temporarily redirect a library that always writes to stdout: - open file.dat for writing, creating/truncating it; handle failure first - fflush(stdout): send any previously buffered output to its original destination - save1 = dup(1): keep a descriptor for the original stdout - dup2(fd, 1): make the file the new stdout - close(fd): remove the redundant descriptor; descriptor 1 still holds the file - run the library operations that produce the required output - fflush(stdout) before restoring, so buffered file output reaches the file - dup2(save1, 1): restore original stdout; redirected descriptor is replaced - close(save1): release the saved duplicate - check dup / dup2 failures as well as open failures in complete code 6 shell redirections (<, >, >>) usually happen when launching a program - child performs dup2 before exec, then closes the redundant descriptor - exec preserves ordinary open descriptors unless marked close-on-exec - executed program inherits the redirected standard stream 7 example: reproduce ls -l -a -R / > flist - fork; handle failure child: - open flist with O_CREAT|O_WRONLY|O_TRUNC, mode 0666 - on failure: report error and terminate - dup2(fd, 1), then close the redundant fd - execlp("ls", "ls", "-l", "-a", "-R", "/", NULL) - if exec returns: report its error and terminate unsuccessfully parent: - wait for child and collect status - !WIFEXITED(status) or WEXITSTATUS(status) != 0 -> unsuccessful execution - all directory-listing output goes to flist; stderr remains separate 8 alternative: open flist in the parent before fork - parent can report an open error without creating a child - child inherits fd, redirects stdout, closes its redundant copy, and executes ls - parent must close its own copy of fd before waiting - closing one process's copy does not invalidate the other's copy - examples assume fd differs from 1; do not close descriptor 1 after a no-op dup2 9 fcntl(fd, F_DUPFD, minimum): duplicate fd at the first free number >= minimum - dup(fd) is equivalent to fcntl(fd, F_DUPFD, 0) - fcntl(fd, F_DUPFD, 20): use 20 if free, otherwise the next free number above it - unlike dup2, does not replace an already open target descriptor 5.3.11 Process Credentials 1 process credentials include: - real uid / gid: normally identify the user who started the process - effective uid / gid: used for most permission checks - saved user ID / saved group ID - supplementary group IDs Linux also has: - fsuid / fsgid for filesystem permission checks, usually matching effective IDs - capabilities: individual privileges separate from the simple root/non-root model 2 book's ordinary user-process model starts with PID 1, traditionally /sbin/init - starts with root credentials; other user processes descend from it - fork copies the parent's real, effective, saved, and supplementary group IDs - credentials therefore remain unchanged until a process explicitly changes them 3 privileged login programs establish the user's session credentials - set supplementary groups while still privileged - set real, effective, and saved group IDs to the user's primary group - set real, effective, and saved user IDs to the user's uid - then run the shell or window manager - dropping all root user IDs removes the saved route back to root - merely changing the effective ID need not make a privilege drop permanent 4 executing a SetUid / SetGid program can separate real and effective IDs: - real IDs remain those of the calling process - SetUid: effective uid becomes the executable owner's uid - SetGid: effective gid becomes the executable's group ID - resulting effective IDs are copied to the saved IDs - supplementary groups are preserved 5 real and saved IDs allow controlled switching of effective credentials - a SetUid program can use the invoking user's rights for some operations and the program owner's rights for others - unprivileged changes are restricted to already held identity values - a sufficiently privileged process can choose other IDs 6 example: Vasya uid 1003 owns SetUid program vasyaprog; Petya uid 1012 runs it - real uid = 1012 - effective uid = 1003; saved uid = 1003 - initially performs permission-checked work with Vasya's rights - setting effective uid to 1012 temporarily uses Petya's rights - saved uid remains 1003, allowing effective uid to switch back to Vasya 7 read process IDs: - getuid(): real uid - geteuid(): effective uid - getgid(): real gid - getegid(): effective gid - these calls return the requested ID and do not fail 8 actual return types are uid_t and gid_t, not necessarily int - preserve these types when storing IDs - converting an unsigned ID above INT_MAX to int can lose the intended value 9 getresuid / getresgid retrieve real, effective, and saved IDs together - available on Linux and some other systems - book distinguishes these extensions from the more portable basic getters 10 getgroups(size, array): retrieve supplementary group IDs - array elements must have type gid_t - size gives array capacity; insufficient space produces an error - getgroups(0, NULL): ask how many entries are needed - allocate n * sizeof(gid_t), then call getgroups(n, array) - complete code must handle call/allocation failures and later free the array - effective primary gid may or may not appear in the returned list -> use getgroups together with getegid for the full group information 11 seteuid / setegid change only the effective user/group ID - an unprivileged process can select its corresponding real, effective, or saved ID; requesting its current ID is an allowed no-op - selecting an unrelated ID fails - privileged callers can choose IDs outside that restricted set - use uid_t / gid_t arguments in actual declarations 12 setuid / setgid also primarily affect the effective ID - unprivileged caller: can switch within the IDs permitted by the system - privileged caller: changes real, effective, and saved IDs together - seteuid / setegid still change only the effective ID when called with privilege -> setuid away from root can permanently discard the saved root identity 13 setgroups(size, list): replace the supplementary group list - privileged operation - list points to size elements of type gid_t - old supplementary group membership is replaced, not extended - real, effective, and saved primary group IDs do not change 14 other interfaces can change or retrieve several IDs together: - setreuid / setregid - setresuid / setresgid - getresuid / getresgid - exact availability and semantics depend on the system 5.3.12 Resource Limits 1 resource limits restrict how much of a permitted resource a process may use - examples: virtual memory, open descriptors, processes for a user - different from permission checks that simply allow or forbid an operation 2 ulimit -a displays the calling shell's current resource limits - examples: file size, core size, open files, stack, CPU time, user processes - units depend on the displayed resource and shell interface 3 limits belong to individual processes - inherited by fork; preserved by exec - setting a limit affects the caller and descendants that inherit it - does not change limits of unrelated processes or the system as a whole user-process-count limit: - caller's limit is checked against the user's total process count - at the limit, fork fails with -1 and errno = EAGAIN - another process of the same user can have a different limit - such a process is governed by its own limit when it calls fork 4 each resource limit has two levels: - soft limit: value the kernel enforces - hard limit: ceiling for changes to the soft limit ordinary process: - can lower or raise its soft limit up to its hard limit - can lower its hard limit, but cannot raise it again without privilege privileged process: can raise hard limits within system constraints 5 setrlimit(resource, &limit): set a resource's soft and hard limits struct rlimit: - rlim_cur: current / soft limit - rlim_max: maximum / hard limit - RLIM_INFINITY: no limit for that value - use the symbolic constant; its representation depends on the implementation 6 resource selects the limit to change: - RLIMIT_AS: virtual address-space size in bytes - RLIMIT_CORE: maximum core-dump size in bytes; 0 disables core dumps core dump records process memory/state for examining a crash in a debugger - RLIMIT_CPU: CPU time in seconds soft limit -> SIGXCPU; further CPU use can cause repeated SIGXCPU delivery hard limit -> SIGKILL, which cannot be caught or ignored - RLIMIT_FSIZE: maximum file size in bytes at the setrlimit interface exceeding it -> SIGXFSZ; if execution continues, write can fail with EFBIG do not confuse this with block units used by some shell ulimit displays - RLIMIT_NOFILE: upper bound on descriptor numbers, not just current open count a newly obtained descriptor must have a number below the limit applies even when many lower-numbered descriptors are unused - RLIMIT_NPROC: process-count limit checked against processes of the real user checked using the limit of the process attempting fork - RLIMIT_STACK: maximum stack address-space size - other limits are described by the system's setrlimit documentation 7 getrlimit(resource, &limit): read the current soft and hard limits - fills the same struct rlimit used by setrlimit 8 disk quotas are a separate mechanism - limit disk space for users and/or groups on individual filesystems - Linux and FreeBSD expose quota operations through quotactl 5.3.13 Overview of Interprocess Communication 1 processes can affect one another through shared objects - one process can modify a file that another reads - mmap can map a memory region accessible to several processes - shared memory: one process's changes can be observed by others - communication does not always require a separate, specialized IPC operation 2 signals are a simple specialized communication mechanism - in the book's classical-signal model, the signal number identifies the event - no general data stream is carried by such a signal 3 pipes provide one-way data transfer - named pipes: FIFO - unnamed pipes: pipe - one end is used for writing, the other for reading - data written by one process can be read by another 4 tracing lets one process control and inspect another's execution - typical controller: debugger - controlled process: program being debugged 5 a pseudo-terminal lets a user process emulate a terminal device - examples: xterm and remote-login servers such as sshd - emulator communicates with programs attached to the emulated terminal - those programs can use it as their controlling terminal 6 System V IPC includes: - shared memory - semaphore sets - message queues - author strongly discourages these interfaces; this is the book's assessment 7 sockets provide a common interface for communication protocols - support communication between processes on different computers - not limited to TCP/IP or any one network standard - adding a protocol need not require an entirely new system-call interface - Unix-domain sockets also support communication within one system - local sockets do not require an external network connection 5.3.14 Signals 1 this subsection covers ordinary signals - real-time signals can carry additional information and be queued - the author's advice against using them is a design preference 2 signal: a notification chosen from a predefined set - originally used to terminate processes - later acquired other uses 3 termination signals: - SIGTERM: request termination; can be caught or ignored - SIGKILL: force termination; cannot be caught or ignored - commonly SIGTERM = 15 and SIGKILL = 9; use symbolic names in programs 4 graceful termination followed by forced termination: - send SIGTERM first -> allow cleanup - send SIGKILL after a timeout if the process remains alive - e.g. an editor may save recovery information before shutting down 5 fault signals: - SIGILL: illegal instruction - SIGSEGV: invalid memory access / protection violation - SIGFPE: arithmetic exception, e.g. integer division by zero - SIGBUS: certain invalid memory accesses, including alignment errors default action: terminate and, when enabled, produce a core dump - catching a fault does not repair the damaged program state - trying to save corrupted data can cause another fault 6 SIGSTOP: suspend execution; cannot be caught or ignored SIGCONT: resume execution - can have a handler, but still resumes a stopped process 7 terminal keyboard signals go to its foreground process group: - Ctrl-C -> SIGINT - Ctrl-\ -> SIGQUIT - default: terminate; SIGQUIT also requests a core dump 8 SIGCHLD: notify a parent about a child's termination - default disposition does not terminate the parent 9 SIGALRM: timer notification requested by alarm - useful for timeouts - default action is termination -> install the intended disposition first 10 SIGUSR1 and SIGUSR2: application-defined notifications - default action is termination 11 signal names are integer macro constants in system headers - e.g. SIGKILL denotes a signal number - include the headers; do not define these constants yourself 12 senders: another process or the kernel; recipient: a process kill(target_pid, sig_no) sends a signal: - target_pid > 0: that process - target_pid = 0: the caller's process group - target_pid < -1: process group -target_pid - target_pid = -1: eligible processes, with system-specific exclusions - group signalling can include the caller itself permissions restrict which processes can be signalled - normally processes of the same user; privileged processes have broader access - return: 0 on success, -1 on error 13 signal disposition: what to do when a signal arrives - default action - ignore it - call a handler SIGKILL and SIGSTOP cannot have their dispositions changed 14 simple handler signature: void handler(int s) - receives the signal number - returns no value 15 signal installs a disposition: - typedef void (*sighandler_t)(int); - sighandler_t signal(int signo, sighandler_t hdl); - hdl: handler address, SIG_IGN, or SIG_DFL - return: previous disposition, or SIG_ERR on failure 16 installing a handler does not call it - it changes the response to a future signal - if no such signal arrives, the handler is never called 17 handlers run asynchronously relative to the main program - execution can be interrupted at an unexpected point - one handler can serve several signals by inspecting its argument 18 historical signal semantics differed between systems System V behaviour: - reset disposition to default before entering the handler - handler must reinstall itself to catch another occurrence - another signal can arrive before reinstallation and take the default action -> a second SIGUSR1 can terminate the process 19 early implementations made this race difficult to observe in practice - relying on their scheduling details does not provide a portable guarantee - interface users should not need undocumented timing assumptions 20 kernel implementation of signal delivery is discussed later 21 another System V problem: the same signal can interrupt its own handler - occurs after the handler has reinstalled itself - nested calls can interfere through shared global state 22 traditional names for the two behaviours: - System V semantics - BSD semantics these names refer to differences between historical Unix families 23 BSD signal handling: - disposition remains installed until explicitly changed - the signal being handled is blocked during its handler -> no re-entry caused by that same signal - same signal interface name, but different behaviour from System V 24 Linux historically exposed a System V-style signal syscall - C libraries commonly implement signal through sigaction with BSD behaviour - library function behaviour need not match a same-named kernel syscall 25 prefer sigaction when explicit, predictable handling semantics matter - availability of a raw signal syscall depends on the architecture - the library can still provide signal using another kernel interface 26 sigaction gives finer control over handling and signal masks - queued signals and attached data use additional interfaces such as sigqueue - detailed configuration is outside this subsection 27 for the book's signal-based examples: - reinstall at the start of the handler for historical System V compatibility - explicitly select SIG_DFL if only one occurrence should be caught - sigaction avoids depending on these historical signal differences 28 a handler is entered through signal delivery, not an ordinary main-program call - main cannot pass arbitrary arguments or collect a return value - examples communicate through carefully chosen global variables 29 most library functions cannot safely run in a signal handler - a signal may interrupt an update to the library's internal state - calling into that state again can observe an incomplete update - use only operations guaranteed to be async-signal-safe 30 malloc and free are unsuitable in handlers - the interrupted program may already be modifying heap metadata - re-entry can corrupt the heap or cause other failures - timing-dependent failures are particularly hard to reproduce 31 buffered standard I/O is also unsuitable in handlers - printf and related functions maintain mutable stream buffers and state 32 low-level I/O such as write can be used, but preserve errno - a handler's syscall may overwrite an error belonging to interrupted code - save errno on entry and restore it before returning 33 ordinary global variables can also be unsafe - an access wider than a machine operation may be interrupted halfway - example: a 64-bit value accessed in two halves on a 32-bit processor -> main can combine half of the old value with half of the new value 34 volatile tells the compiler that a value can change unexpectedly - prevents reuse of a cached value where a fresh access is required - does not itself make compound operations atomic 35 volatile sig_atomic_t is the portable type for a simple handler flag - its individual reads and writes are indivisible relative to signal delivery - this does not make all arithmetic or read-modify-write operations atomic - it is not a general synchronization mechanism for threads or shared memory 36 native-width accesses often use one instruction on the processors discussed - this explains why small integer flags are convenient - instruction-level observations are not a substitute for C's guarantees 37 the book uses volatile int, reflecting its target implementations - sig_atomic_t is often an alias for int - retaining sig_atomic_t expresses the required portable guarantee 38 a caught signal can interrupt a blocking operation - many affected calls return -1 with errno = EINTR - EINTR indicates interruption, not necessarily an underlying I/O failure 39 handlers execute in user space - a process blocked in the kernel must be allowed to run its handler - after handling, the interrupted operation may finish, restart, or report EINTR 40 waiting indefinitely in the kernel must not prevent signal handling - a short operation can finish before the handler runs - an unfinished blocking operation can report EINTR - caller may need to retry or reconsider whether to keep waiting 41 SA_RESTART, configured through sigaction, restarts certain interrupted calls - eligibility depends on the call and circumstances - some read, write, and wait operations can restart - nanosleep does not restart automatically this way 42 some signal library implementations enable SA_RESTART implicitly -> signal alone can conceal the restart policy 43 for each blocking call in a program with handlers: - handle EINTR appropriately - do not assume a signal will necessarily make that call return - use sigaction to control the policy explicitly 44 example task: print a message on Ctrl-C and finish after 25 notifications naive implementation: - global counter n - handler increments n and calls printf - main installs SIGINT handler and spins while n < 25 45 improvements to that example: - use a volatile signal-safe counter / flag - account for the historical disposition-reset behaviour - use a fixed message and write instead of printf - save and restore errno in the handler - replace the empty busy loop with a blocking wait - the book first uses sleep(1) 46 increasing the sleep interval avoids more periodic wakeups - a handled signal interrupts sleep - main can then check the loop condition immediately 47 pause waits for a signal whose handler is executed - no parameters - after the handler returns: -1, errno = EINTR - avoids periodic wakeups caused by sleep 48 replacing sleep with pause still leaves a race - checking the counter and beginning to wait are separate operations 49 ordinary signals with the same number can merge while pending - several sends need not produce the same number of handler calls - do not use their occurrence count as a reliable message count 50 alarm(seconds) requests one SIGALRM after the specified interval - timer is removed when it expires - return: remaining seconds from a previous timer, or 0 if none existed 51 only one alarm timer is active for a process - another alarm replaces the previous request - alarm(0) cancels it without starting another 52 install the desired SIGALRM disposition before starting the timer - otherwise its default action terminates the process 53 sleep has historically been allowed to use alarm and SIGALRM internally - mixing these mechanisms can therefore be implementation-dependent - implementations can instead use nanosleep or another waiting mechanism 54 interrupted sleep calls have different return conventions - sleep returns the number of seconds still to sleep - usleep and nanosleep can return -1 with errno = EINTR - nanosleep does not use a SIGALRM timer for its operation 55 the author prefers the more explicit sleep interfaces - nanosleep is useful when precise interruption handling is needed 56 signal-heavy designs are difficult to make correct - races between main code and handlers - coalescing of ordinary signals - effects on every relevant blocking call 57 example: parent must wait until a new child has finished initialization - child sends SIGUSR1 when ready - parent may handle other signals too -> returning from pause alone does not prove the child is ready 58 first attempt: - set child_ready = 0 and install SIGUSR1 handler - handler sets child_ready = 1 - fork; child initializes, then kill(getppid(), SIGUSR1) - parent repeats pause while child_ready is zero 59 lost-wakeup race in that attempt: - parent checks child_ready and sees zero - child sends SIGUSR1 before parent enters pause - handler sets child_ready to one - parent enters pause anyway and may wait indefinitely for another signal 60 solution: combine sigprocmask and sigsuspend - block SIGUSR1 before the critical check - sigsuspend atomically enables it while beginning to wait - an early signal remains pending until that wait 61 the author recommends keeping signal use simple - termination and fault handling - occasional requests to a long-running process, e.g. reload configuration - use a more suitable IPC mechanism for reliable exchanges of data 62 the remaining discussion explains waiting with sigsuspend 63 blocking a signal defers its delivery - pending signal can be delivered after it is unblocked - blocking is different from ignoring - SIGKILL and SIGSTOP cannot be blocked 64 sigprocmask(how, set, oldset) changes the blocked-signal set - sets have type sigset_t - SIG_BLOCK: add signals from set - SIG_UNBLOCK: remove signals from set - SIG_SETMASK: replace the entire blocked set - non-NULL oldset receives the previous mask 65 query the current mask without changing it: - pass NULL as set and an address as oldset - how is ignored 66 functions operating on sigset_t: - sigemptyset: remove all members - sigfillset: include all signals - sigaddset: add one signal - sigdelset: remove one signal - sigismember: 1 if present, 0 if absent, -1 on error - modifying functions return 0 on success, -1 on error - an invalid signal number can produce EINVAL 67 sigsuspend(const sigset_t *mask): temporarily replace the signal mask and wait - mask specifies signals blocked during the wait - old mask is restored before sigsuspend returns 68 sigsuspend waits for an unblocked signal with an effective action - ignored signals do not end the wait - a terminating signal ends the process - a caught signal runs its handler, then sigsuspend returns -1 / EINTR - this return convention is the expected successful wait outcome 69 a signal mask lists blocked signals, which can make this interface confusing - the important operation here is permitting the awaited signal to arrive 70 usual waiting pattern: - block the relevant signal outside the wait - temporarily unblock it inside sigsuspend - restore blocking when the handler and wait finish 71 correct child-readiness example: - construct mask_usr1 containing SIGUSR1 and mask_empty containing none - initialize child_ready, block SIGUSR1, install the handler, then fork - child initializes and sends SIGUSR1 to the parent - parent: while(!child_ready) sigsuspend(&mask_empty); - early notification stays pending until sigsuspend unblocks it - later notifications remain pending for a later wait - in a larger program, preserve unrelated entries in the original mask 72 the same reasoning explains the remaining bugs in the 25-message example 73 25th-signal race: - main checks n < 25 - handler increments n to 25 before main calls pause - main still enters pause and needs an extra signal to wake it 74 signal-flood experiment: int_grill runs pressagain as a child - fork / exec the target, wait briefly, then repeatedly send SIGINT - use waitpid with WNOHANG to check whether it has finished - ./int_grill ./pressagain | wc -l can count far more than 25 messages - output through a pipe removes much of the terminal's display delay 75 why the count can become so large: - another SIGINT is often already pending when the handler returns - return passes through signal-restoration code using sigreturn - restoring the mask enables the pending signal - its handler can run immediately, before main rechecks the counter -> main can be starved by consecutive handler invocations 76 the example eventually gets a gap between incoming signals - main finally checks the counter and exits - this does not make the earlier excess output correct 77 make the check-and-wait sequence correct: - block SIGINT before installing its handler - use sigsuspend to enable it only during each wait - on return the mask blocks SIGINT while main checks the counter 78 some programmers avoid pause entirely in favour of atomic wait interfaces - sigsuspend and pselect can combine mask changes with waiting - the author considers the appropriate choice dependent on the task 79 the author contrasts deliberate signal flooding with ordinary keyboard input - human typing and terminal processing are much slower - this makes the demonstrated failure hard to provoke interactively - low probability does not remove the underlying check-and-wait race 80 choose complexity with the real task in mind - understand the guarantees and limitations of the selected mechanism 5.3.15 Pipes and FIFOs 1 pipe: kernel object for one-way data transfer - write end receives bytes - read end supplies those bytes - descriptors in different processes can refer to the same ends 2 two kinds of pipe: - named pipe / FIFO: filesystem name can be opened by processes - unnamed pipe: created with both ends already open, without a pathname - ordinary open cannot connect to an unnamed pipe by name 3 pipe(fd) creates an unnamed pipe - int fd[2]; - fd[0]: read end; fd[1]: write end - return: 0 on success, -1 on error, e.g. descriptor/resource exhaustion - the book shares descriptors by creating the pipe before fork -> children inherit references to the same pipe 4 connect two children through one pipe: - parent creates pipe, then forks both children - first child closes fd[0] and writes through fd[1] - second child closes fd[1] and reads through fd[0] - parent closes both of its descriptors -> only the writer and reader keep the ends they actually use 5 reading while both ends still have open descriptors: - empty pipe -> read blocks until data arrives or all writers close - available bytes -> read returns data without waiting to fill the request - returned byte count may be smaller than the requested count 6 a pipe contains a finite kernel buffer - writes can initially succeed even if a reader is not actively reading - once space runs out, a blocking write waits for a reader to free space - capacity depends on implementation and configuration 7 when the last write descriptor closes: - reads can consume bytes already buffered - after the buffer empties, read returns 0: EOF - an unnamed pipe has no pathname through which to reopen that end 8 when the last read descriptor closes: - writing generates SIGPIPE - default action: terminate the writer - if SIGPIPE is caught or ignored, write can report -1 / EPIPE 9 pipelines connect concurrently running programs - first program's stdout -> second program's stdin - second program's stdout -> third program's stdin, and so on 10 an N-stage pipeline normally needs N - 1 pipes - connect descriptors 0 and 1 to the appropriate ends - close every unused pipe descriptor in every process - an accidental extra write descriptor prevents the reader from seeing EOF 11 an accidental extra read descriptor also matters - intended consumer exits, but the pipe still appears to have a reader - producer can fill the buffer and block instead of receiving SIGPIPE - tasks waiting for the producer can then remain blocked too 12 example: ls -lR | grep '^d' - create one pipe - first child: * close read end * dup2(fd[1], 1), then close the original fd[1] * execlp("ls", "ls", "-lR", NULL) - second child: * close write end * dup2(fd[0], 0), then close the original fd[0] * execlp("grep", "grep", "^d", NULL) - children report an exec failure and terminate - parent closes both pipe descriptors and waits for both children 13 FIFO: first in, first out - a named pipe lets unrelated processes find the same channel by pathname - bytes are read in the order in which they entered the stream - the unnamed-pipe examples rely on inherited descriptors 14 FIFO is a special filesystem object - processes can independently open it - closing every descriptor for one end does not remove its pathname - a process can later open that end again 15 mkfifo(name, permissions) creates the FIFO filesystem object - permissions are filtered by umask - return: 0 on success, -1 on error 16 opening a FIFO connects to the kernel channel - O_RDONLY: read end - O_WRONLY: write end - O_RDWR behaviour is not portable; Linux permits it - creating the pathname does not itself open a channel descriptor 17 kernel pipe state and filesystem FIFO have different lifetimes - last descriptor closes -> kernel channel state is released - FIFO pathname remains until explicitly removed - a later open can establish a new channel through the same name 18 ordinary FIFO open waits for the other end to be opened O_NONBLOCK changes this: - read-only open succeeds even without a writer - write-only open with no reader fails: -1, errno = ENXIO 19 FIFO end closure follows pipe rules: - no writers and no buffered data -> read returns 0 - no readers -> write generates SIGPIPE but new descriptors can later appear through the pathname - a new writer can make data available after a reader has observed EOF - without a writer, reads continue returning 0 - a later reader can make writing possible again if the writer survived SIGPIPE 5.3.16 Tracing 1 tracing allows one process, usually a debugger, to control another - stop or resume it - inspect / modify memory - execute individual instructions - use breakpoints or stop at system calls 2 ptrace provides tracing operations - arguments identify the request, target process, address, and data - interpretation of address and data depends on the request - exact declaration and available requests are system-specific 3 trace a newly started program: - debugger forks - child requests PTRACE_TRACEME, then execs the target program - tracing stop after exec notifies the debugger with SIGCHLD - debugger uses wait-family calls to observe the stop - PTRACE_SINGLESTEP: execute one instruction - PTRACE_CONT: continue execution - PTRACE_GETREGS: obtain register contents on supporting systems 4 attach to an existing process with PTRACE_ATTACH - debugger assumes tracing-related responsibilities of a parent - receives tracing notifications and observes stops through wait - target's getppid still identifies its actual parent 5 tracing is a powerful security capability - where permitted, it allows inspection and alteration of another process - same-user identity alone does not bypass every system's ptrace restrictions - chroot changes filesystem lookup; it does not by itself isolate processes - tracing a process outside a chroot can defeat the intended confinement - actual access depends on credentials, capabilities, and system policy 5.4 Terminals and sessions 5.4.1 Terminal driver and line discipline 1 terminal originally combined keyboard, screen, and a communication line: - keyboard input was sent along the line - received text was displayed on the screen - one computer could serve many terminals and users -> terminal remains central to Unix process management 2 terminal streams usually imply a human user: - C library buffering differs for terminals and other streams - ls may use columns and colors on a terminal - redirected output normally lists one name per line - ls | cat demonstrates this: ls writes to a pipe, even though cat eventually displays that text on the terminal 3 isatty(fd): - returns 1 if fd refers to a terminal, otherwise 0 - library function implemented through a terminal-specific ioctl - tests the kind of stream, not its descriptor number 4 terminal behavior can be emulated in software: - hardware terminal and physical line are no longer necessary - Linux / FreeBSD virtual consoles use the local keyboard and display - switch consoles with Alt-F1, Alt-F2, ... in the setup described - servers can be administered remotely and use consoles for local work 5 graphical terminal emulators: xterm, rxvt, konsole, ... - ordinary user processes implement terminal behavior - kernel implements virtual consoles instead - virtual consoles still exist while X Window runs - console-switching keys depend on the system's configuration 6 physical serial consoles are useful on machines without a local display: - server provides an RS-232 / COM console port - laptop plus terminal program can act as the terminal - USB-to-serial adapter replaces a missing built-in COM port - minicom and similar programs communicate over this connection - often used for initial setup before network access is available 7 serial communication: - minimal connection: transmit, receive, common ground - bits are sent sequentially, grouped with start / stop bits - optional parity helps detect transmission errors - modems convert digital data for transmission over telephone lines - dial-up was widespread before faster access became affordable 8 terminal traffic needs much less bandwidth than images or video: - traditional COM-port speeds are sufficient for typed commands - output includes generated text and escape sequences - even relatively slow serial connections can support text interaction 9 remote-access services such as sshd also provide a terminal interface - a pseudoterminal connects remote input/output to local processes 10 line discipline sits between terminal input/output and user programs - terminal transmits characters; it does not know Unix signals - Ctrl-A -> code 1, Ctrl-B -> 2, Ctrl-C -> 3, ... Ctrl-Z -> 26 - Ctrl-[ -> 27, Ctrl-\ -> 28, Ctrl-] -> 29 - driver recognizes configured control characters -> code 3 normally generates SIGINT instead of reaching the program 11 terminal-generated signals target the foreground process group - this belongs to the session associated with the terminal 12 canonical line editing is also handled by the line discipline: - Backspace: erase the previous character - Ctrl-W: erase the previous word - Ctrl-R: redisplay the current input line - Ctrl-U: erase the entire current line - active application does not have to implement these operations 13 programs can change or disable special-character handling: - Ctrl-C can become ordinary input instead of generating SIGINT - applications can implement their own editing - bash / gdb provide history, arrow keys, and completion - GNU Readline supplies these features beyond basic line discipline 14 xterm receives keyboard events from X Window: - pressing Ctrl-C in its window does not signal xterm itself - xterm sends byte 3 to the pseudoterminal - kernel line discipline generates SIGINT for the foreground job 15 Ctrl-D does not close the terminal connection: - xterm sends byte 4 - canonical input uses it to deliver pending input without a newline - on an empty line, read returns 0 -> application sees EOF - cat can finish while the shell and terminal session remain usable 5.4.2 Sessions and process groups 1 session = set of processes sharing one sid (session identifier) - normally associated with work through one terminal - session has at most one controlling terminal, possibly none - terminal controls at most one session - login and starting a terminal emulator usually create new sessions 2 a session contains one or more process groups: - a group cannot span different sessions - terminal records one foreground group; others are background groups - switching the foreground group makes the previous one background - without a controlling terminal, foreground has no practical meaning 3 process group collects processes working on one job: - interactive shell normally creates a group for each command - all stages of a pipeline belong to the same group - pgid = process group identifier 4 fork preserves sid and pgid process can: - create a new session and its initial group * becomes leader of both, with sid = pgid = pid - create a group within its session - join another group within the same session 5 leadership restricts creating sessions and groups: - setsid fails for a process group leader - a session leader is also leader of its initial group - a new group/session would need the caller's pid as its identifier - fork gives a child a fresh pid so it can create a session 6 groups determine which processes terminal actions affect: - Ctrl-C -> SIGINT to foreground group - background read -> SIGTTIN, normally stopping that group - background output can optionally be restricted too - terminal disconnection can cause SIGHUP - shell may propagate the hangup to its jobs - exact behavior on ordinary shell exit depends on shell settings 7 getsid(pid) and getpgid(pid) return session / group identifiers - pid = 0 queries the calling process - leader's pid provides the identifier of the session / group 8 setsid() creates a session - fails if caller is already a process group leader - usual preparation: fork, let parent exit, call setsid in child - fork failure must be handled before continuing 9 a successful setsid creates both a new session and its initial group - caller is initially the only member of both - sid and pgid both equal caller's pid 10 setsid detaches the process from its controlling terminal - existing terminal descriptors can remain open - a session leader may acquire a free terminal by opening it - O_NOCTTY prevents open from acquiring a controlling terminal - useful when a session leader opens arbitrary files 11 setpgid(pid, pgid) changes group membership: - caller can move itself or an immediate child that has not executed exec - destination group must be in the same session - pgid = pid creates a group led by that process 12 tcsetpgrp(fd, pgrp) assigns a terminal's foreground group - fd must refer to the controlling terminal - implemented through ioctl on that terminal - terminal driver needs the group to direct signals and control access 13 standard descriptors are not reliable handles for the controlling terminal: - any of 0, 1, 2 may have been redirected - isatty proves only that a descriptor is a terminal - it does not prove that this is the caller's controlling terminal 14 /dev/tty refers to the caller's controlling terminal - open it to obtain a suitable descriptor for tcsetpgrp - opening fails if the process has no controlling terminal 15 background caller of tcsetpgrp may trigger SIGTTOU for its group - caller can block or ignore SIGTTOU while changing foreground groups - only the calling process needs to do this 5.4.3 Controlling the terminal driver 1 usual terminal behavior: - input is delivered after a complete line is entered - typed characters are echoed - certain control characters trigger special actions 2 crt and ncurses change terminal-driver settings for full-screen programs - the same settings can be controlled directly 3 termios provides C library functions for terminal control - underlying device operations use ioctl - includes tcsetpgrp and functions for line settings - serial-line settings reflect its origins with physical RS-232 terminals - these options still matter when communicating with serial devices 4 direct terminal control is useful for small tasks: - example: read a password without echo - a full-screen library is unnecessary for changing one setting 5 canonical vs noncanonical input: - canonical: line discipline collects and edits complete lines - noncanonical: read behavior is controlled by byte counts and timers - echo and signal handling are separate options - special characters can be reassigned 6 struct termios stores terminal settings: - tcgetattr(fd, &settings) reads them - tcsetattr(fd, options, &settings) installs them - fd must refer to the terminal to configure - check isatty before assuming standard input is a terminal 7 tcsetattr timing options: - TCSANOW: apply immediately - TCSADRAIN: wait for queued output to be transmitted - TCSAFLUSH: drain output and discard unread input before applying 8 main struct termios fields: - c_iflag: input processing flags - c_oflag: output processing flags - c_cflag: communication / hardware control flags - c_lflag: local line-discipline flags - c_cc[NCCS]: control-character settings - use declared types tcflag_t and cc_t, not assumed int / char types 9 IXON in c_iflag enables software flow control: - Ctrl-S normally suspends terminal output - Ctrl-Q resumes it - useful when output scrolls faster than the user can read 10 other input-processing examples: - IGNCR discards incoming carriage returns (CR, code 13) - ISTRIP removes the high bit of incoming bytes - such transformations can corrupt multibyte or eight-bit text - many input flags relate to physical serial-line behavior 11 c_oflag controls outgoing character processing - flags can affect newline / carriage-return handling - OLCUC, where supported, maps lowercase Latin letters to uppercase 12 c_cflag mostly concerns the physical communication channel - baud rate, character format, and modem-related behavior - these are less relevant to an entirely virtual terminal connection 13 c_lflag includes the main line-discipline controls: - ICANON enables complete-line input and line editing - basic editing includes erase-character and erase-line - IEXTEN enables additional processing such as word erase and redisplay 14 ISIG enables terminal-generated signals: - Ctrl-C -> SIGINT - Ctrl-\ -> SIGQUIT - Ctrl-Z -> SIGTSTP 15 TOSTOP controls output from background process groups: - clear: background output is normally allowed - set: background output can generate SIGTTOU and stop the group - background reads are already restricted by SIGTTIN - SIGCONT resumes stopped processes 16 ECHO controls whether typed characters appear on the screen password-input example: - verify that input is a terminal - get settings and save an unchanged copy - clear ECHO, then apply the changed settings - read the secret without displaying it - restore saved settings on completion and on error paths 17 usual terminal-setting pattern: read -> modify a copy -> apply -> restore - constructing all termios fields from scratch is error-prone - set flags with bitwise OR: ts.c_lflag |= ICANON | IEXTEN | ISIG | ECHO; 18 clear selected flags with an inverted mask: - ts.c_lflag &= ~(ICANON | IEXTEN | ISIG | ECHO); - selected bits become zero; other bits retain their values 19 editing the struct changes only the process's copy - call tcsetattr to change the actual terminal settings 20 c_cc stores special-character codes at named indices - c_cc[VEOF] normally contains 4 -> Ctrl-D - assigning another code changes the EOF control character - VEOF processing belongs to canonical mode 21 other c_cc indices and usual bindings: - VINTR: 3 / Ctrl-C -> SIGINT - VQUIT: 28 / Ctrl-\ -> SIGQUIT - VSUSP: 26 / Ctrl-Z -> SIGTSTP * these require ISIG - VSTOP / VSTART: 19 / Ctrl-S and 17 / Ctrl-Q * flow control requires IXON - VERASE: 127 / Backspace; VKILL: 21 / Ctrl-U - VWERASE: 23 / Ctrl-W; VREPRINT: 18 / Ctrl-R * word erase and redisplay use extended canonical processing 22 newline itself is always code 10 - VEOL and VEOL2 can add alternative line-ending characters 23 disable an individual control character using the platform's disable value - _POSIX_VDISABLE is used for this purpose - disabling VINTR removes the keyboard binding that generates SIGINT 24 noncanonical reads use VMIN and VTIME: - VMIN: minimum byte count - VTIME: timer measured in tenths of a second - VMIN = 1, VTIME = 0 waits for at least one byte - disabling ICANON does not itself clear the separate ISIG flag 25 VMIN = 0, VTIME = 0: - read returns immediately with available bytes - no data -> read returns 0 - unlike EOF, this can just mean that nothing is ready yet - O_NONBLOCK commonly reports unavailable input with -1 / EAGAIN 26 with a nonzero VTIME: - VMIN = 0: timer starts when read begins - VMIN > 0: timer starts after the first byte and restarts for each byte - return when the required data arrives or the applicable timer expires - useful for serial devices as well as interactive terminals 27 further reading from the book: - The TTY demystified - man 3 termios 5.4.4 The other side of a pseudoterminal 1 terminal emulation has two main forms: - virtual consoles implemented by the kernel - ordinary user programs such as xterm - pseudoterminal = kernel object providing the latter's virtual link 2 pseudoterminal has two bidirectional endpoints: - master: used by the terminal emulator - slave: used by programs running under the terminal 3 create a pseudoterminal master: - getpt() is a glibc-specific interface - portable interface: posix_openpt(O_RDWR | O_NOCTTY) - Linux implements this through /dev/ptmx - returns the master descriptor and creates an associated slave device - slave's device file lets the session's programs connect to the pair 4 prepare the slave before opening it: - grantpt(master_fd) establishes suitable ownership / access - unlockpt(master_fd) allows the slave to be opened - ownership setup must correspond to the user receiving the session - remote-login services also establish the authenticated user's credentials 5 unlockpt completes the preparation: - ptsname(master_fd) supplies the slave device's pathname - child can create a session with setsid - open the slave and connect it to descriptors 0, 1, and 2 - exec starts the shell or other session program - master remains with the program implementing terminal behavior 6 openpty can create and open both endpoints together: - returns master and slave descriptors through pointer arguments - optional name buffer receives the slave pathname - optional termios and winsize arguments initialize terminal behavior - optional arguments may be NULL 7 openpty originated in BSD - available on several systems, but not the POSIX portable interface 5.4.5 Daemons 1 daemon = process intended to work without direct terminal interaction - examples: web / mail servers, cron, print service - often runs for a long time - commonly changes current directory to / so it does not keep another filesystem busy or prevent its unmounting 2 keep standard descriptors open even if unused: - otherwise a later open may reuse 0, 1, or 2 for an unrelated file - accidental standard-output writes could then corrupt that file - traditional daemons redirect all three to /dev/null 3 traditional daemonization separates the process from the terminal: - redirect standard streams to /dev/null - chdir("/") - fork and let the original parent exit - setsid creates a separate session - fork again and let the session leader exit 4 the two forks have different purposes: - first ensures child is not a group leader, allowing setsid - second makes surviving daemon a non-leader -> it cannot accidentally acquire a controlling terminal 5 without terminal output, diagnostics go to system logging: - openlog establishes logging settings - syslog sends a formatted message - closelog releases logging resources - implementation may send messages to a logging daemon through a socket 6 openlog(ident, options, facility): - ident names the program in log messages - options controls logging details; 0 is often enough - facility classifies the service - LOG_USER is suitable when no special facility applies 7 syslog(priority, format, ...) resembles printf: - LOG_ERR: error - LOG_WARNING: warning - LOG_INFO: informational message - administrator can filter messages by severity - example: syslog(LOG_INFO, "Daemon started, pid == %d", getpid()); 8 closelog ends the program's connection to system logging - releases any associated open resources 9 signals can serve as daemon-control requests: - SIGHUP commonly requests a configuration reload - more elaborate services may use other control interfaces 6. Networks and protocols 6.1 Computer networks 1 computer network: connected computers able to exchange data - at least two participants - historical store-and-forward exchanges even used removable media - this chapter considers networks with actual communication links 6.1.1 Networks and network connections 1 communication networks can use fixed connections - endpoints remain connected according to a fixed wiring scheme - changes require manual reconnection - examples: public-address systems and field telephones with dedicated wires 2 circuit switching: - endpoints attach to switches forming a switching network - control commands establish and release connections - traditional telephone networks illustrate this model 3 packet switching: - digital information is divided into packets - each packet contains destination information - network forwards each packet toward its recipient - one physical link carries packets for many different conversations 4 chapter's scope: packet-switched computer networks - other specialized arrangements exist - data travels in small addressed units - network forwarding does not itself guarantee successful delivery 5 physical media vary widely - electrical cables, radio, optical fiber, infrared, directed light - differences include modulation, synchronization, cable type/length, wire count - wired versus wireless alone is an incomplete classification 6 applications can often ignore the physical transmission technology - Internet access can work through mobile radio, Wi-Fi, Ethernet, DSL, ... - higher layers provide a common interface 7 physical access still affects security assumptions - radio can extend beyond the intended room or building - a shared password is known to multiple people and can spread - control access to services such as printers rather than trusting proximity 8 physical topology and logical communication topology are different - bus, star, ring, mesh describe different arrangements - a physically star-shaped network can behave like a shared bus - topology labels alone do not explain application-visible behavior 9 historical Ethernet used coaxial cable - central conductor plus surrounding insulated shield/conductor - shield reduces interference and radiation - other equipment also uses coaxial cables 10 coaxial Ethernet bus: - interfaces connected in parallel with T-connectors - example speed: 10 Mbit/s - simultaneous transmissions collide - heavier traffic causes more collisions and lost useful capacity 11 bus cable required correct termination at both ends - 50-ohm terminators suppress reflected signals - breaks or disconnected connectors can disrupt the whole segment - cable passing every workstation makes accidental damage hard to avoid 12 historical twisted-pair Ethernet replaced the coaxial bus - twisting helps reject interference - discussed 10/100-Mbit arrangement uses separate transmit/receive pairs - crossover wiring can connect two interfaces directly - a hub connects multiple machines, one cable per port - hub repeats incoming signals onto the other ports 13 switches replaced hubs - forward known unicast traffic toward its destination port - independent pairs of hosts can communicate without sharing one collision domain - broadcast and unknown-destination traffic still require wider forwarding 14 switch maintains address-to-port information - inspect each frame's destination - one port may lead to several hosts through another switch - managed switches also expose configuration/monitoring interfaces - VLANs divide ports into separate logical networks 15 manufacturing made simple switches inexpensive - enclosure, connectors, power supply, and board are needed for hubs too - reduced electronics cost removed the main economic reason to use hubs 16 historically, hubs and especially switches were expensive - coaxial networks needed neither - lower equipment cost prolonged their use despite maintenance problems 17 coaxial bus -> twisted-pair hub: - physical topology changes from bus to star - logical behavior remains shared broadcast delivery - every connected participant still receives the transmitted signal 18 network cards sometimes supported both coax and twisted pair - replacing cabling/hub and selecting the other connector could preserve software setup - applications did not need to know that the physical medium changed 19 for programming, classify networks by properties visible to programs - physical wiring alone often does not determine the interface they use 20 TCP/IP hides many differences between local and remote communication - peer may be across the world, next door, or on the same computer - latency and other performance properties can still differ 21 network boundaries can be administrative as well as technical - connected networks can form parts of larger networks - one administration/security policy can define a network boundary - outside peers cannot be trusted merely because they are reachable - internal peers also require appropriate checks 22 one logical link can serve several computers - Ethernet is a multipoint example - participants communicate directly at the link layer - intervening hubs/switches are normally transparent to endpoint software 23 point-to-point link connects exactly two endpoints - abbreviated PtP - can use Ethernet or technology inherently limited to two participants - useful for links between networks or to an access provider 24 multipoint links need a way to select the next recipient on the link - point-to-point link has only one possible peer - link-layer identifiers differ from IP addresses used above them - address resolution connects the two kinds of address 25 networking does not require a dedicated network card - serial ports and modems historically carried Internet traffic - null-modem cable connects nearby serial ports - USB, parallel ports, and even SCSI can also transport network data - technologies differ in speed and hardware requirements 26 network hardware need not be a separate expansion card - Ethernet/Wi-Fi may be built into the motherboard - USB adapters are another packaging option 27 network interface: the connection point used to exchange data with other computers - term avoids assuming any particular physical card or connector 28 interface can also be a software abstraction - virtual interfaces represent tunnels and VPNs - VLAN trunking can present several logical interfaces through one physical port - each logical interface can participate in its own link/network 6.1.2 Gateways and routing 1 one large link has scaling limits - link/switch failures can divide connectivity - inter-switch links can become bottlenecks - broadcasts impose work on all members - forwarding loops must be prevented or controlled; redundant physical links need suitable protocols 2 large shared networks also complicate administration and isolation - many participants can reach one another directly - separating organizations makes security policy easier to enforce 3 one computer can have several network interfaces - can participate in several links simultaneously - Ethernet and Wi-Fi on one laptop are a familiar example - choosing one preferred interface is a policy, not an inherent hardware limit 4 router/gateway forwards packets between networks - requires connectivity to those networks and forwarding configuration - GW commonly abbreviates gateway 5 home Internet router is also a computer - often combines routing, Ethernet switching, and Wi-Fi access - runs firmware/OS, sometimes Linux 6 gateway is a transfer point between links - routes tell hosts where to send nonlocal packets - gateway can filter, limit, log, or translate traffic - packets may cross several successive gateways - route describes how forwarding carries them toward the destination 7 example: two separate home LANs - first: Anna, Boris, Vera - second: Gennady, Dmitry, Elena, Zhanna 8 residents want communication between the LANs - games, file access, and voice/video communication - a link between only Boris and Dmitry is useful to others if they forward traffic 9 joining switches could make one larger LAN - duplicate addresses would need resolving - physical separation and cable constraints may make this inconvenient - residents may also want separate access policies 10 Boris and Dmitry establish a radio link and act as gateways - Boris forwards traffic for the second LAN to Dmitry - Dmitry forwards traffic for the first LAN to Boris 11 configure other hosts' routes toward the relevant gateway - Anna/Vera use Boris to reach the other LAN - Gennady/Zhanna use Dmitry - Dmitry can filter incoming traffic addressed to Elena - local communication within Elena's LAN remains possible 12 add an Internet router to the first LAN - local destinations: send directly - second LAN: send through Boris - all other destinations: send through the provider router - last rule is the default route/default gateway 13 extend Internet access to the second LAN - Dmitry's default gateway: Boris - second-LAN hosts' default gateway: Dmitry - redundant more-specific routes using the same next hop can be removed - Elena's filter must allow desired replies while blocking unwanted sources 14 possible extensions: - second Internet connection and failover routing - dedicated gateways instead of personal computers that must stay switched on - later sections explain concrete IP routes and address translation 6.2 Network protocols 6.2.1 Protocols and the OSI model 1 protocol: agreements participants follow to understand one another - several protocols operate together at different levels - example stack: physical signaling, TCP transport, HTTP application exchange 2 protocol specification tells implementers how to interoperate - describes formats, meanings, rules, and required behavior - software/hardware implements these agreements - protocol is distinct from one particular implementation 3 OSI = Open Systems Interconnection; seven-layer reference model - physical: signals, transmission medium, electrical/optical/radio characteristics - data link: frames and communication over one link - network: addressing and forwarding between networks - transport: communication between endpoints; may provide ordering/reliability - session: organization of a conversation - presentation: representation/encoding of exchanged data - application: rules for the actual service 4 mnemonic from top to bottom: All People Seem To Need Data Processing - Application, Presentation, Session, Transport, Network, Data link, Physical - OSI is useful as a conceptual model - practical Internet protocols need not form seven separate implementation layers 5 author contrasts committee-designed layering with TCP/IP's practical development - treat this as the author's commentary - central technical point: working protocol stacks need not mirror the reference model 6.2.2 Physical and data-link protocols 1 physical protocol depends on the actual connection - 100BASE-TX is a twisted-pair Ethernet example - specifies signaling and medium requirements - Ethernet specifications also define framing and link-layer addresses - a technology's specifications can span more than one conceptual layer 2 Wi-Fi uses the IEEE 802.11 family - shared radio medium requires coordination between transmitters - channels, bands, and permitted operation vary by standard and region - includes physical signaling and medium-access/framing rules 3 cellular access adds its own radio and network protocols - book uses GSM/GPRS as examples - cellular specifications cover several layers, not just physical transmission 4 RS-232 is a simpler physical-interface example - can connect serial ports with a null-modem cable - low data rate limits its usefulness for ordinary networking 5 Ethernet/Wi-Fi interfaces use link-layer MAC addresses - common MAC address length: six bytes - usually displayed as hexadecimal byte pairs, e.g. 00:1F:C6:65:42:48 - manufacturer-assigned addresses commonly combine an assigned prefix and device-specific part 6 manufacturer address allocations do not all use the same prefix length - allocation structure is separate from how applications use IP addresses 7 effective MAC address can differ from the factory address - OS/driver can configure a locally chosen address - randomization can reduce tracking of mobile Wi-Fi devices - MAC address should not be treated as an unchangeable identity 8 ARP resolves an IPv4 next-hop address to a link-layer address - sender needs the recipient's MAC address on a multipoint link - broadcasts a request asking which interface owns the IP address - owner replies with its MAC address - sender caches the association for later packets - remote destinations are reached using the gateway's local MAC address 9 point-to-point links do not need ARP to choose among several peers - PPP is a common link protocol for such connections - defines framing and integrity checks - can negotiate link settings, check liveness, and authenticate peers 6.2.3 IP 1 IP provides network-layer packets, addresses, and forwarding - higher protocols put their data inside IP packets - ICMP also belongs to network-layer operation although carried inside IP - ICMP reports delivery problems and other control information - conceptual layers do not require one protocol per layer 2 IP supports interconnection of heterogeneous networks - different underlying links can carry the same IP packets - several paths can provide resilience when links fail - book traces development through ARPANET and the 1983 TCP/IP transition 3 Internet consists of networks under many separate administrations - no single operator owns all links, hosts, or local networks - common protocols let independently built networks cooperate 4 individual links and operators can disappear or change - overall resilience must not depend on every component being reliable 5 alternative routes can preserve communication after failures - routing must detect changes and find a usable path - recovery is not an unconditional or instantaneous guarantee 6 network host: a computer/end system participating in a network - addresses identify reachable endpoints/interfaces - book distinguishes globally reachable hosts from machines hidden behind NAT - NAT/firewall restrictions affect reachability, not whether a machine is technically a host 7 IPv4 address: 32 bits, commonly written as four decimal octets - example: 192.168.215.17 - each octet is from 0 to 255 - network byte order is big-endian: most significant byte first 8 routing needs to describe sets of destinations compactly - one route often serves many addresses in the same network - listing every host separately would be impractical 9 prefix/subnet groups addresses sharing their first N bits - remaining 32 - N bits vary - address count = 2^(32 - N) - network address sets all variable bits to zero - /29: 8 addresses; /24: 256; /22: 1024 10 CIDR notation: network-address/prefix-length - 203.0.113.32/28 contains 16 addresses - range: 203.0.113.32 through 203.0.113.47 - last four bits vary 11 ordinary IPv4 broadcast subnets reserve boundary addresses - all-zero host part: subnet identifier - all-one host part: directed broadcast - special cases such as /31 point-to-point links have different rules - an address prefix used only for route aggregation is not itself a physical broadcast subnet 12 /32 prefix selects exactly one IPv4 address - 203.0.113.41/32 is a host route 13 one address belongs to nested prefixes of every length - 198.51.100.115 belongs to 198.51.100.112/28 - also to 198.51.100.0/24 and 198.51.0.0/16 - longer prefix -> smaller, more specific set 14 0.0.0.0/0 includes the entire IPv4 address space - no fixed prefix bits - useful for a default route 15 assign contiguous prefixes to simplify routing - router normally has an address in each directly connected network - addresses are associated with interfaces, not one immutable address per computer - an interface can also have more than one address 16 some IPv4 ranges have special meanings - 127.0.0.0/8: loopback; 127.0.0.1 is the common local-host address - 0.0.0.0 has special unspecified/default uses depending on context - other reserved ranges are not ordinary public unicast space - exact assignments and permitted uses must not be inferred solely from this historical list 17 224.0.0.0/4 is IPv4 multicast address space - address identifies a group of receivers - one source can distribute the same information to many recipients 18 multicast forwarding builds distribution paths - receivers announce group membership to local routers using IGMP - multicast routing protocols connect interested networks - routers replicate packets only where paths branch -> potentially fewer copies over shared links 19 multicast also supports local control/routing protocols - end-to-end Internet multicast requires support along the path - local group membership alone does not ensure global multicast delivery 20 private IPv4 ranges: - 10.0.0.0/8 - 172.16.0.0/12 - 192.168.0.0/16 - can be reused in independent private networks - not globally routed as public addresses - NAT can provide outgoing Internet access 21 example LAN addressing: - Boris's LAN: 192.168.12.0/24 - Boris .1; Anna .2; Vera .3 - Dmitry's LAN: 192.168.13.0/24 - Dmitry .1; Gennady .2; Elena .3; Zhanna .4 - reserve .0 for subnet and .255 for broadcast in each /24 22 separate radio link gets a separate subnet - 192.168.14.0/30 - Boris: 192.168.14.1; Dmitry: 192.168.14.2 - .0 network; .3 broadcast in this illustrative arrangement 23 Internet router's inside address: 192.168.12.100 - default gateway for hosts on Boris's LAN - hosts on Dmitry's LAN instead use local gateway 192.168.13.1 24 two routing forms: - destination prefix -> directly connected interface - destination prefix -> next-hop gateway IP - multipoint-link direct routes normally identify on-link destinations - point-to-point link already has an unambiguous peer - gateway itself must be reachable 25 example interface names: eth0 for LAN, wlan0 for radio link - actual interface names depend on system configuration - Gennady/Elena/Zhanna: 192.168.13.0/24 -> eth0 0.0.0.0/0 -> 192.168.13.1 26 Anna/Vera need two different gateways - 192.168.12.0/24 -> eth0 - 192.168.13.0/24 -> 192.168.12.1 - 0.0.0.0/0 -> 192.168.12.100 27 Boris connects two links - 192.168.12.0/24 -> eth0 - 192.168.14.0/30 -> wlan0 - 192.168.13.0/24 -> 192.168.14.2 - 0.0.0.0/0 -> 192.168.12.100 28 Dmitry's routes: - 192.168.13.0/24 -> eth0 - 192.168.14.0/30 -> wlan0 - 0.0.0.0/0 -> 192.168.14.1 29 Internet router has an inside Ethernet interface and illustrative point-to-point wan0 - 192.168.12.0/24 -> eth0 - 192.168.13.0/24 -> 192.168.12.1 - 0.0.0.0/0 -> wan0 - external example address: 198.51.100.115 - that address block is reserved for documentation, not a real assignment 30 routing alone does not make private source addresses globally usable - remote networks cannot route replies to independently reused private addresses 31 NAT translates private traffic using the router's external address - example internal aggregate: 192.168.12.0/22 - outgoing packet's source is translated to the external address - reply is translated back and forwarded to the internal destination 32 remote peer normally sees the NAT's external address - ordinary outgoing mappings allow replies - unsolicited incoming connections need suitable mappings/forwarding and policy 33 many-to-one NAT must distinguish simultaneous exchanges - track addresses, transport ports, protocol, and mapping state - transport headers may also need translation - protocols carrying addresses/ports in application data can need extra handling - FTP's separate data connection illustrates such complications 34 radio-link subnet can also be advertised to ordinary hosts - Anna/Vera can add 192.168.14.0/30 -> 192.168.12.1 35 routers can then be reached through their radio-interface addresses too - alternative: a true point-to-point link can use unnumbered routing - this relies on actual link semantics; Wi-Fi alone is not automatically a point-to-point interface 36 illustrative unnumbered point-to-point route arrangement: - Boris: second LAN -> connecting interface; default -> Internet router - Dmitry: own LAN -> eth0; default -> connecting interface - removes the separate transit-prefix routes 37 longest-prefix match chooses the most specific matching route - /24 beats /22; /22 beats /0 - Anna/Vera can aggregate neighboring ranges: 192.168.12.0/24 -> eth0 192.168.12.0/22 -> 192.168.12.1 0.0.0.0/0 -> 192.168.12.100 38 more-specific local route overrides the broader aggregate - .12.0/24 goes directly through eth0 - other destinations covered by .12.0/22 go through Boris 39 address conservation matters when the available allocation is small - particularly for public IPv4 blocks - private allocations can also be constrained by a larger organization's plan 40 compact example requirements: - each LAN needs at least /29 if network/broadcast addresses are reserved - transit link needs /30 - 8 + 8 + 4 = 20 addresses -> covering block must be at least /27 (32) - use spare space to enlarge Dmitry's LAN to /28 (16 addresses) 41 choose aggregate 192.168.45.64/27: .64 through .95 - Boris's LAN: .64/29 - Boris .65; Anna .66; Vera .67; Internet router .70 - .71 broadcast; .68/.69 spare 42 Dmitry's LAN: 192.168.45.80/28 - Dmitry .81; Gennady .82; Elena .83; Zhanna .84 - .95 broadcast; .85–.94 spare - prefix boundaries require a correctly aligned block 43 transit link: 192.168.45.76/30 - Boris .77; Dmitry .78 - .72–.75 remain outside the assigned component subnets - routing follows the same principles as before 44 subnet mask is another representation of prefix length - N one-bits followed by 32 - N zero-bits - /27 -> 255.255.255.224 - /24 -> 255.255.255.0; /16 -> 255.255.0.0 - network address = IP address bitwise-AND subnet mask 45 IPv4 TTL limits packet lifetime in router hops - each forwarding router decreases TTL - expired packet is discarded, normally with an ICMP report - prevents routing loops from circulating packets indefinitely 46 MTU limits packet size on a link - Ethernet commonly carries 1500-byte IP packets - IPv4 can fragment oversized packets when fragmentation is permitted - destination reassembles fragments - DF prevents router fragmentation; oversized delivery then fails with suitable feedback - IPv4 header checksum protects the header, not the entire payload 47 IPv4 has 2^32 possible bit patterns - reserved ranges and historical allocation reduce usable public supply - early classful allocations sometimes gave organizations much larger blocks than needed 48 address scarcity motivated conservation and a replacement protocol - IPv6 development began in the 1990s - smaller allocations and NAT prolonged IPv4 use 49 IPv6 addresses have 128 bits - 2^128 possible addresses - written as hexadecimal groups separated by colons - example: 2001:0db8:21b1:a742:0000:ff00:0042:8326 - /64 provides 64 interface-address bits within a subnet - allocation sizes vary; the book's provider/customer sizes are examples 50 transition requires compatibility across independently operated networks - an IPv6-only service is unreachable to an IPv4-only client without translation - dual-stack deployments can serve both - book's claims about negligible IPv6 use describe its historical viewpoint 51 book discusses IPv4 exhaustion, allocation restrictions, and possible address reuse - exhaustion did not create one simultaneous global cutover - precise allocation limits and market predictions are time-dependent - fragmented allocations can increase routing-table complexity 52 author speculates about IPv6's future and possible alternatives - this is a prediction from the book, not a technical requirement or current usage fact 6.2.4 Datagrams and streams 1 IP delivers packets on a best-effort basis - packets may be lost, duplicated, or reordered - datagram exchange sends one addressed block of data at a time - an application needing reliability must add acknowledgments, timeouts, and retries - acknowledgments can cover groups of packets 2 splitting one object across datagrams requires reconstruction - include sequence numbers or positions - receiver restores order and detects missing fragments - missing information may need retransmission 3 minimal transport still needs two things - integrity checking for the payload, beyond IPv4's header checksum - identification of different communicating endpoints on one host 4 UDP = User Datagram Protocol - 16-bit source and destination port numbers identify endpoints - eight-byte header: source port, destination port, length, checksum - length includes UDP header and payload - UDP datagram is carried in an IP packet with source/destination IP addresses 5 stream transport presents a bidirectional byte stream - read/write-style operations at each endpoint - received bytes retain their transmitted order - no application-visible packet boundaries - failures can terminate the connection and appear through EOF/errors - successful write alone does not prove the peer application consumed the data 6 TCP = Transmission Control Protocol - provides ordered reliable byte-stream delivery or reports failure - handles acknowledgments, retransmission, and reassembly - uses port numbers like UDP - establish a connection before exchanging stream data - flow-control window limits outstanding data; it is not the packet size - TCP header is normally 20–60 bytes, including any options - OS implementation handles transport mechanics for applications 6.2.5 Application-layer protocols 1 session, presentation, and application responsibilities often overlap in real protocols 2 Internet applications organize sessions without a distinct universal session layer - session behavior may be part of an application protocol or built above it 3 web login session can span many requests and connections - application associates requests using a session identifier - cookies are a common mechanism - transport connection lifetime and login-session lifetime are different 4 data representation also relies on agreements - character encodings: ASCII, UTF-8, ... - document/image formats: HTML, JPEG, PNG, ... - MIME describes media types, multipart content, and transfer encodings - e-mail attachments use MIME conventions - these are presentation-like responsibilities 5 application protocols provide actual user services - e-mail, the Web, messaging, ... 6 client-server model: - server waits for requests and provides a service - client initiates requests - one program can be server to one peer and client to another - these are roles in an interaction, not fixed hardware categories 7 many application protocols exchange text over a bidirectional stream - SMTP and HTTP/1.x are examples - a plain TCP terminal tool can expose their unencrypted exchanges - encrypted transports require the corresponding TLS support 8 book's SMTP example sends one test message through a mail server - connect to the server's TCP port 25 - greeting -> EHLO -> MAIL FROM -> RCPT TO -> DATA -> message -> QUIT 9 transcript distinguishes three sources of text - '=': local shell/telnet output, not SMTP data - '>': commands/text sent by the client - other lines: server replies 10 SMTP server starts by sending a greeting - example: 220 pluto.unicontrollers.com ESMTP Postfix 11 greeting fields identify the service - 220: numeric response code - hostname: server identity - ESMTP: extended SMTP - Postfix: implementation name in this example 12 EHLO introduces the client and requests extended SMTP capabilities - parameter identifies the client host - older HELO form gives a simpler greeting exchange - server text after the numeric response is mainly explanatory 13 multiline EHLO response lists supported extensions - client uses only capabilities advertised by the server - this example needs only the basic mail-transfer commands 14 MAIL FROM supplies the envelope sender and begins a mail transaction - example: MAIL FROM: 15 example successful reply: 250 2.1.0 Ok 16 SMTP clients interpret response codes, not decorative English wording - 250 means the requested action succeeded - 2.1.0 is an enhanced status code supplied by an extension - 'Ok' may be replaced with different explanatory text 17 RCPT TO supplies an envelope recipient - repeat for multiple recipients - server checks recipient validity and relay authorization - accepting mail for local users differs from relaying to unrelated destinations 18 open relay accepts mail from arbitrary senders for arbitrary destinations - abuse by spammers led operators to restrict relaying - relay policy matters when configuring a mail service - the book's dates describe its historical account 19 unauthorized relaying can be rejected - example: 554 5.7.1 ... Relay access denied 20 unknown recipient can also be rejected - example: 550 5.1.1 ... User unknown 21 DATA requests permission to send the message content - after accepted envelope sender and recipients - 354 tells the client to continue with the content 22 SMTP content format: - protocol line ending: CR LF, bytes 13 and 10 - header fields, then a blank line, then message body - a line containing only '.' ends DATA - lines beginning with '.' require SMTP dot-stuffing - envelope MAIL FROM/RCPT TO and message From:/To: headers are distinct - final 250 reply accepts the message into the server's delivery process - server may add trace, delivery, date, and message-identifier headers 23 DNS MX records identify mail exchangers for a domain - book illustrates lookup with host -t MX domain - server accepting a message does not by itself prove final mailbox delivery 24 HTTP/1.1 example requests a site's root resource on TCP port 80 - client sends GET / HTTP/1.1 - Host field selects the intended site 25 shell/telnet messages precede the actual HTTP request - request data begins with the GET line and Host header 26 blank line terminates the HTTP request headers - example response begins HTTP/1.1 200 OK - response headers precede a blank line and the response body - HTTP client sends first, unlike SMTP's server greeting 27 both protocols use three-digit response codes, with different category meanings - SMTP: 2xx success; 3xx continuation; 4xx temporary failure; 5xx permanent failure - SMTP 354 invites message data; extensions can define other continuation replies - HTTP: 1xx informational; 2xx success; 3xx redirection - HTTP: 4xx client error; 5xx server error - HTTP's first digit does not classify errors as simply temporary/permanent 6.2.6 Domain names 1 domain names are more convenient for people than numeric IP addresses - example: www.stolyarov.info 2 DNS = Domain Name System - distributed hierarchical database keyed by domain names - supports name-to-address lookup and many other record types - information for a name is not limited to one IP address 3 'domain' means an area or collection in several technical contexts - DNS uses it for a portion of the hierarchical namespace 4 names consist of dot-separated labels - ordinary hostname labels use letters, digits, and internal hyphens - www.stolyarov.info has labels www, stolyarov, info - hierarchy is read from the right: top-level domain, child, further child - internationalized hostnames use an encoded DNS representation - DNS labels in general are broader than the simplified hostname syntax 5 resource records have class, type, content, and TTL - TTL: how long a cached record may be retained - IN: Internet class used for ordinary Internet DNS - A: IPv4 address; AAAA: IPv6 address - MX: mail exchanger; SRV: service location; TXT: text data - one name can have several records 6 DNS domain is a subtree identified by a common name suffix - class.stolyarov.info lies within stolyarov.info and info - a subdomain is contained within its parent domain - root, written '.', contains the entire DNS namespace 7 hierarchy distributes authority across independently operated servers - authoritative servers hold a zone's official data - multiple servers improve availability - primary/secondary arrangements replicate zone data - change notifications can trigger early refresh; periodic checks still matter 8 parent can delegate a child domain to another set of servers - those servers answer authoritatively for the delegated portion - zone = authority's part of the domain, excluding delegated child zones 9 zone data can be stored in a text zone file - lookup finds authoritative servers and requests the desired record type - @ denotes the zone origin in the example file - relative names receive the origin suffix - trailing '.' marks an absolute domain name 10 $TTL sets the default record TTL in a zone file - example 86400 seconds = one day - individual records may override the default 11 important zone-file records: - SOA: zone authority information, serial, and timers - NS: authoritative name servers - parent delegation and child-zone NS records should be consistent - MX: mail server, with a preference value - A: IPv4 address - CNAME: alias to another domain name 12 wildcard record can provide answers for otherwise missing names - *.camp IN A 198.51.100.72 - can synthesize answers for names below camp.stolyarov.info - actual wildcard rules depend on existing names and delegation boundaries 13 delegate example.stolyarov.info by adding NS records in its parent zone - example IN NS ns1.example.com. - example IN NS ns2.example.com. 14 glue avoids circular dependence when server names lie inside the delegated zone - resolver must know a server address before asking that server anything - parent includes needed A/AAAA address records alongside the delegation 15 root zone delegates top-level domains such as com, net, and info - recursive resolvers bootstrap from known root-server addresses - stable, redundant root service allows cached/bootstrap information to remain useful 16 root service uses 13 named server identities, a.root-servers.net through m.root-servers.net - logical identities are distinct from physical server instances - geographically distributed anycast instances provide service - book's instance counts and deployment locations are historical examples 17 recursive resolver caches records until their TTL expires - repeated lookups can reuse answers and delegation information - root servers are not contacted for every user query - caching and delegation distribute the load across the hierarchy 6.3 Unix sockets 1 socket system calls expose networking to user programs - move from network concepts to implementing communicating processes 6.3.1 Address families and communication types 1 socket is a kernel communication endpoint - local process operates on it through system calls - peer addresses it as an endpoint of communication - sockets also support local communication without a physical network 2 Unix socket is accessed through a file descriptor - close releases a descriptor - Internet endpoint address combines IP address and transport port 3 address representation depends on protocol family - IPv4 address: four bytes; IPv6: sixteen - historical IPX/SPX used network, host, and socket-number components - Unix-domain pathname sockets use filesystem paths 4 common socket API accommodates different families - choose an address family when creating the socket - new protocol support need not replace the basic syscall interface - applications use the appropriate family-specific address structures 5 socket type selects communication semantics - SOCK_DGRAM: datagrams - SOCK_STREAM: byte stream - other types exist but are outside this discussion 6 IP datagrams have finite size and no delivery/order guarantee - send one message; receive one message - loss, duplication, and reordering are possible - maximum UDP datagram size differs from path MTU - keeping packets within path MTU avoids IP fragmentation - IPv4 with 1500-byte MTU, 20-byte IP header, and 8-byte UDP header leaves 1472 payload bytes - the book's conservative 508-byte figure allows for a 60-byte IPv4 header within 576 bytes 7 stream socket exposes an ordered bidirectional byte stream - application need not handle packet reassembly or retransmission - errors can still interrupt delivery - no message boundaries; read sizes need not match write sizes 8 create with socket(family, type, protocol) 9 socket arguments: - AF_INET: IPv4 Internet addresses - AF_UNIX: communication within one machine - SOCK_STREAM or SOCK_DGRAM selects semantics - protocol = 0 selects the default for the family/type combination - AF_INET examples: IPPROTO_TCP for stream, IPPROTO_UDP for datagrams 10 socket returns a new file descriptor on success - -1 on error 6.3.2 Socket addresses 1 bind assigns a local address to a socket - bind(sockfd, address, address_length) - sockfd: socket descriptor - address: pointer to the family-specific address structure - address_length: size in bytes, represented by socklen_t 2 bind returns 0 on success, -1 on error - address/port may already be in use - requested address may not be local - permissions may prevent binding a privileged port or pathname - check the result before continuing 3 IPv4 uses struct sockaddr_in - sin_family: AF_INET - sin_port: port number in network byte order - sin_addr: struct in_addr containing s_addr - s_addr: 32-bit IPv4 address in network byte order 4 address-family field identifies the concrete address representation - appears in each supported socket-address structure - field names differ between structures 5 IP address identifies an interface/address on a host - port distinguishes communication endpoints using that address - many processes can use different ports on the same host address 6 network byte order is big-endian - host byte order depends on CPU architecture - conversion functions make source portable: htons: host -> network, 16 bits htonl: host -> network, 32 bits ntohs: network -> host, 16 bits ntohl: network -> host, 32 bits 7 function names encode direction and width - h = host; n = network; s = 16-bit; l = 32-bit - 'long' here does not mean whatever size C long has on the platform - example: addr.sin_port = htons(7654); 8 low-numbered ports traditionally require privilege - TCP/UDP ports below 1024 are the conventional privileged range - root or appropriate capability/configuration can authorize binding - permission failure is reported by bind, commonly as EACCES 9 inet_aton converts textual IPv4 address to struct in_addr - inet_aton(text, &address.sin_addr) 10 inet_aton result: - nonzero: accepted address text - 0: invalid text - fill sin_family, convert sin_port with htons, then parse sin_addr - check parsing before using the address 11 inet_addr also converts IPv4 text - returns an address value for sin_addr.s_addr 12 inet_addr result is already in network byte order - do not apply htonl again - error value collides with the valid bit pattern for 255.255.255.255 - inet_aton or inet_pton gives clearer validation 13 server can bind to all local IPv4 addresses - addr.sin_family = AF_INET; - addr.sin_port = htons(port); - addr.sin_addr.s_addr = htonl(INADDR_ANY); - kernel chooses a suitable source address for outgoing traffic 14 INADDR_ANY represents 0.0.0.0 for wildcard binding - useful for a local bind address, not as a remote destination - textual-address conversion is often used for the peer address instead - use the documented byte order for INADDR constants 15 struct sockaddr_in is declared through - address conversion declarations are normally in 16 generic API takes struct sockaddr pointers - bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) - cast family-specific structure pointer at the call boundary - initialize the structure and handle bind failure 17 Unix-domain addresses use struct sockaddr_un from - sun_family = AF_UNIX - sun_path stores pathname bytes directly - Linux commonly provides 108 bytes, but capacity is platform-dependent - check path length rather than assuming an arbitrary name fits 18 pathname socket has a socket-type filesystem entry - bind creates it; directory permissions must allow creation - existing pathname may make bind fail - closing the socket does not automatically unlink the entry - remove the pathname with unlink when appropriate 19 pathname socket permission checks vary by OS - Linux uses write permission for relevant connection/send operations - do not assume identical checks on every Unix system - directory access restrictions also matter 20 other families provide their own address structures - same structures are used by bind and other address-taking socket calls 6.3.3 Sending and receiving datagrams 1 create a datagram socket with SOCK_DGRAM - bind when peers need a known local destination address/port - INADDR_ANY can cover all local IPv4 addresses - unbound UDP socket normally receives an automatic local address/port on first use - automatic binding suits a requester whose peer replies to the observed source 2 sendto sends a datagram; recvfrom receives one - sendto(fd, buf, len, flags, destination, destination_length) - recvfrom(fd, buf, len, flags, source, &source_length) - byte counts use ssize_t results and size_t buffer lengths 3 common arguments: - fd: socket descriptor - buf: bytes to send or storage for received bytes - len: send length or receive-buffer capacity - flags = 0 for basic use - check returned byte count/-1 rather than assuming success 4 sendto destination has the selected family's address structure - sockaddr_in for AF_INET; sockaddr_un for AF_UNIX - pass actual structure size as destination length - use socklen_t for variables whose addresses are passed as length pointers 5 source comments on the history of socklen_t - practical rule: use the API's declared type instead of guessing int or size_t 6 recvfrom can return the sender's address - initialize socklen_t source_length to available structure capacity - pass its address - call updates it with the address length - receive buffer must be large enough; oversized datagrams may be truncated 7 choose datagram size with path constraints in mind - UDP's protocol limit and the path's unfragmented payload limit are different - large messages may require fragmentation or application-level subdivision - path-MTU handling is a separate technical topic 8 naive request/reply sequence can block forever - sendto(request), then blocking recvfrom(reply) - request may be lost -> peer never knows to answer - reply may be lost -> requester keeps waiting 9 bound waiting time and decide what to do when it expires - book suggests SIGALRM as one possible timeout mechanism - alarm-handler/restart behavior must allow the wait to be interrupted - retries require a policy, not an infinite blind resend loop 10 other receive-timeout mechanisms: - select can wait for socket readiness or a deadline - SO_RCVTIMEO sets a socket receive timeout through setsockopt - struct timeval contains seconds and microseconds 11 example SO_RCVTIMEO = 3.5 seconds - tv_sec = 3; tv_usec = 500000 - setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) - check option-setting and receive results 6.3.4 Stream sockets and client-server roles 1 stream communication begins by establishing a connection - client initiates - server waits for and accepts connection requests - TCP provides this behavior for the Internet stream sockets discussed here 2 server has a listening socket and separate connected sockets - listening endpoint receives connection requests - accepted connection gets a new socket for actual data exchange - listener remains available for further clients 3 server setup: socket -> bind -> listen - listen(sockfd, backlog) 4 listen backlog concerns pending connections awaiting acceptance - limits the relevant kernel queue, subject to OS rules - does not limit total established client sessions - queue overflow behavior depends on the implementation/protocol 5 choose backlog with workload and system limits in mind - old examples' value 5 is historical - kernel may cap requested backlog - book's value 128 is not a universal modern maximum - sustained overload needs capacity/design changes; queue size mainly absorbs bursts 6 accept obtains the next pending connection - accept(listenfd, peer_address, &peer_address_length) 7 accept address arguments report the peer - initialize socklen_t length to the supplied address-storage capacity - call writes address and updates length - same input/output-length pattern as recvfrom 8 accept returns a new connected descriptor, or -1 on error - blocking listener waits if no connection is ready - server now has listener plus connected client descriptor - deciding when to accept versus read a client leads to the next chapter's scheduling problem 9 client setup: socket -> connect - explicit bind is optional for ordinary outgoing TCP connections - kernel can select local address and port - connect(sockfd, server_address, server_address_length) 10 connect takes the remote server endpoint - use the appropriate family-specific structure and size - normal blocking success: 0 - failure: -1 with errno 11 connected stream supports read and write - server uses accept's returned descriptor - client uses the descriptor passed to connect - recv/send add a flags argument - handle partial reads/writes and errors 12 UDP connect sets a default peer without a TCP-style handshake - configures the local socket; does not establish a reliable stream - received datagrams are filtered to the selected peer - read/write or recv/send can then omit destination arguments - datagram boundaries and UDP reliability limitations remain 13 close releases one descriptor reference - dup/dup2 or fork can create several references to the same socket - closing one of several references does not normally close the connection 14 last descriptor close initiates socket cleanup - queued transmission may continue in the kernel after close returns - orderly peer shutdown produces read/recv result 0 after buffered data is consumed - connection errors can instead be reported as errors 15 shutdown changes permitted communication directions - shutdown(sockfd, how) 16 shutdown directions: - SHUT_RD: stop receiving - SHUT_WR: stop sending - SHUT_RDWR: both - use symbolic names rather than historical numeric values 0, 1, 2 17 shutdown affects the socket itself, across all descriptor references - does not release descriptors - does not replace the need for close - descriptor resources remain allocated until closed 18 SHUT_WR performs a half-close - queued output precedes the end-of-stream indication - peer reads remaining bytes, then sees EOF - caller can continue receiving - example: client sends request, half-closes output, then reads server's response 19 SHUT_RD declares that the application will receive no more data - further reads/data handling follow the socket implementation's semantics - do not depend on identical treatment of already queued data across systems 20 ordinary close can return while kernel still has unsent output - later transmission errors cannot be reported through that closed descriptor - closing is not an application-level acknowledgment of successful processing 21 SO_LINGER changes close behavior - disabled: ordinary background completion behavior - enabled with zero interval: typically abortive close - enabled with positive interval: can wait for transmission progress up to a limit - precise timeout/error behavior is platform-dependent 22 SO_LINGER is configured with setsockopt - consult target-system socket documentation for exact behavior 23 transport acknowledgment does not prove the remote application processed data - SO_LINGER alone cannot establish that stronger guarantee - application protocols need their own confirmation when it matters 6.3.5 Reusing a TCP server address 1 restarting a TCP server can encounter address-in-use errors - old connection state may remain after processes finish - TIME_WAIT helps keep delayed packets from being confused with later connections - it normally arises during orderly active close too, not only after a crash 2 bind may fail while relevant old state remains - waiting period is implementation-dependent - always check bind, otherwise subsequent failures obscure the original cause 3 SO_REUSEADDR can permit normal server-address reuse - set it on the intended listener before bind - use setsockopt(sockfd, level, option, value_pointer, value_length) - reuse remains subject to platform rules and existing active bindings 4 example option setup: - int opt = 1; - setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); - SOL_SOCKET: generic socket option level - optval points to the value; optlen gives its size - check the result before proceeding to bind/listen 6.3.6 Sockets between related processes 1 socketpair creates an already-connected pair for local communication - convenient alternative to two one-way pipes - socketpair(family, type, protocol, descriptors) 2 typical call: socketpair(AF_UNIX, SOCK_STREAM, 0, sv) - sv is an int array of two elements - returns 0 on success, -1 on failure - sv[0] and sv[1] are both readable and writable - create pair before fork so related processes inherit endpoints - each process closes the endpoint copies it does not need - then exchange data through the remaining connected endpoints 6.4 Choosing which operation to perform next 6.4.1 The ordering problem 1 a server has several possible sources of work - listening socket: new connection requests - accepted sockets: data from existing clients - blocking in accept prevents it from handling existing connections - a new connection might not arrive for an arbitrarily long time 2 blocking in read / recv has the same problem - one client may send nothing for a long time - meanwhile other clients and new connection requests go unserved 3 writes can block too - network throughput and kernel buffers are finite - sending a large file to one slow client can delay every other client 4 restaurant analogy: one waiter, separate booths, and an entrance - waiting at the entrance = accept - waiting for one table's order = read from one connection - waiter cannot see all tables and the entrance simultaneously - any table or a new arrival may require attention at any moment 5 one possible approach: make every socket nonblocking and poll them repeatedly - flags = fcntl(sd, F_GETFL); - fcntl(sd, F_SETFL, flags | O_NONBLOCK); - preserve existing status flags when adding O_NONBLOCK - read / accept with nothing available return immediately * normally -1 with EAGAIN or EWOULDBLOCK - write may transfer only part of the requested data * positive return = number of bytes accepted * unavailable output space -> -1 / EAGAIN or EWOULDBLOCK -> repeatedly trying sockets without work is busy waiting 6 busy waiting wastes CPU time - competes with other processes - can exhaust a process's CPU-time limit - prevents useful idle time and increases energy consumption 7 an idle server should consume little CPU - some services receive no requests for long periods - heavy traffic also does not justify useless polling 8 first useful solution: a separate worker process for each client - parent accepts connections - child waits for and serves its own client - analogy: receptionist plus one waiter per table 9 second solution: wait for notification that something needs attention - analogy: doorbell and call button at every table - timer handles actions due after a specified interval - one process can sleep until a relevant event occurs -> I/O multiplexing 10 the following subsections develop worker processes and event-driven operation 6.4.2 A worker process for each connection 1 parent accepts connections; each child serves one connection setup: - socket(AF_INET, SOCK_STREAM, 0) - enable SO_REUSEADDR - fill sockaddr_in with family, htons(port), and htonl(INADDR_ANY) - bind, then listen with the example's queue length of 16 main loop: - accept -> obtain client descriptor and peer address - fork a worker - child closes listening socket, serves client, then exits - parent closes its copy of the client descriptor and accepts again - example repeatedly calls wait4(-1, NULL, WNOHANG, NULL) until no more terminated children are ready to reap - real code must also handle accept and fork failures 2 reaping only after another accept can leave zombies indefinitely - parent may remain blocked waiting for a new connection - handle SIGCHLD and reap completed children promptly - reap in a loop because several children can finish before notification - accept may then return -1 / EINTR; this is an interruption to handle 6.4.3 Event-driven programming 1 one process per client is not always convenient - process creation costs matter at high connection rates - clients may interact through shared application state - example: players affect the same multiplayer game - separate workers then need communication and coordination - each worker may still need to choose between client input and peer updates 2 alternative: one process handles many event sources without busy waiting - sleep while none requires work - learn which source is ready - perform a useful operation, then consider other events 3 event-driven program: - main loop waits for events and reacts to them - examples: network servers and graphical applications - GUI events include keyboard input, mouse movement, and clicks 4 each iteration has two phases: - obtain ready events - dispatch them to event handlers 5 event handlers must return promptly - one long handler delays every other event - acceptable duration depends on response-time requirements - GUI pauses are visible; network clients may time out 6 do not issue an operation that can block indefinitely inside a handler - its waiting time is outside the event loop's control - one blocked handler stops the entire process from serving other events 7 sequential application logic must become resumable - remember each client's current stage - when its event arrives, perform the next available step - save the resulting state and return to the main loop - continue later when another relevant event arrives 6.4.4 Obtaining events in Unix: select 1 efficient event waiting needs kernel support - kernel blocks the process when there is no work - process does not consume CPU repeatedly checking sources 2 wait for any event from a set: - incoming client data - new connection request - output buffer space becoming available - elapsed timeout - caught signal I/O multiplexing: readiness selects which I/O operation to attempt next 3 Unix readiness interfaces include select and poll - similar purpose, different representations and capabilities - platform-specific alternatives include BSD kqueue and Linux epoll - an interface may be a library wrapper around another kernel interface - this subsection develops select 4 select(n, readfds, writefds, exfds, timeout) - readfds: descriptors to check for readable input / pending connections - writefds: descriptors to check for writable output - exfds: descriptors to check for exceptional conditions - n = highest descriptor number being checked + 1 * not the number of descriptors placed in the sets - timeout: maximum wait, even if no descriptor becomes ready - a caught signal can also interrupt the wait 5 fd_set represents a descriptor set - FD_ZERO(&set): empty it - FD_SET(fd, &set): add fd - FD_CLR(fd, &set): remove fd - FD_ISSET(fd, &set): test membership - use these macros instead of assuming the internal representation 6 fd_set has a descriptor-number limit - valid members satisfy 0 <= fd < FD_SETSIZE - largest representable descriptor is FD_SETSIZE - 1 7 FD_SETSIZE and the process's descriptor limit are different limits - the book commonly encountered FD_SETSIZE = 1024 - do not assume every descriptor the process can open fits in fd_set - use an appropriate alternative when descriptor numbers exceed this range 8 timeout uses struct timeval - tv_sec: whole seconds - tv_usec: additional microseconds, 0 through 999999 - 5.3 seconds -> tv_sec = 5, tv_usec = 300000 9 select may modify the timeout structure - behavior differs between implementations - rebuild it before every call - do not rely on it retaining either its original value or remaining time 10 unused set pointers may be NULL - timeout = NULL: no time limit - no descriptor sets + finite timeout: timed wait - no descriptor sets + no timeout: wait until interrupted by a signal 11 select return values: - -1: error; inspect errno * EINTR: interrupted by a caught signal * other errors include an invalid open-descriptor reference - 0: timeout expired - positive: number of ready entries across the descriptor sets * one descriptor can contribute in more than one set input sets are overwritten with the corresponding ready subsets - rebuild them on the next iteration - use FD_ISSET to locate ready descriptors - readiness includes EOF and some error conditions; check the actual I/O result 12 exfds is often unused in simple socket applications - TCP out-of-band / urgent-data notification is one use - exceptional conditions are not a general replacement for checking I/O errors 13 readability means a read can produce a result without waiting - available input can be less than the requested amount - EOF is readable too: read returns 0 immediately - readiness does not promise a complete application-level message 14 readfds also supports sockets used through other operations - listening socket: a pending connection can be accepted - datagram socket: a datagram can be received - use the corresponding accept / receive operation after notification - nonblocking descriptors also protect against readiness changing before use 15 writability does not promise space for an arbitrarily large write - some output can proceed immediately - a blocking write requesting more can still wait -> readiness alone is insufficient to guarantee a responsive event loop 16 robust output uses a nonblocking socket and a per-client output buffer - wait for writability before attempting pending output - inspect the returned byte count - remove only bytes actually accepted by write / send - keep the remainder for a later writable event - handle EAGAIN / EWOULDBLOCK and interruptions appropriately - small writes simplify the book's examples, but can still block in principle 17 watch for writability only when there is output to send - sockets with available buffer space are usually writable immediately - watching an idle writable socket makes select return repeatedly -> accidental busy waiting even though select is being used 18 server-loop outline: - clear readfds and writefds; begin max_d with the listening descriptor - add listening socket to readfds - add client sockets to readfds - add a client to writefds only when its output buffer contains data - update max_d and construct the timeout - call select(max_d + 1, ...) - -1: handle EINTR or other error; do not inspect readiness sets - 0: handle timeout; do not inspect readiness sets - listening socket readable: accept and record the new client * configure required nonblocking behavior on accepted descriptors - client readable: read input, handle EOF/errors, and process received data - client writable: attempt queued output and retain unsent bytes - return to the beginning and rebuild all sets 19 two phases remain distinct in that outline - preparation and select obtain events - the rest of the iteration handles the events reported 6.4.5 A session as a finite-state machine 1 an event-driven interaction cannot rely on a blocking sequence of statements - the application must preserve progress while servicing other clients 2 read / recv may return only part of one client request - do not issue another blocking read just to finish that request - save the fragment and return to the event loop - append later fragments from the same client - after each read, check whether the request is complete 3 each client needs its own accumulation buffer - TCP supplies a byte stream, without application-message boundaries - a buffer can contain a partial request, a complete request plus a fragment, or several complete requests - framing logic must distinguish and preserve these cases 4 application protocols also contain sequences of separate exchanges - receiving complete requests is only one part of maintaining the dialogue - remember which exchange each client has reached 5 example questionnaire asks, in order: - name - age - town - favorite band ordinary Pascal version alternates write(question) with readln(answer) 6 the same sequential dialogue can use socket write and repeated reads - suitable when the process serves only that client - e.g. the worker-process approach 7 one blocking dialogue is unsuitable for a shared event loop - a distracted client can make every other client wait - a deliberately silent client can make the same failure persistent 8 on each client's readable event: - append bytes to its buffer - if no complete line exists, keep state unchanged and return - otherwise extract a line, record the answer, and advance the dialogue - queue the next question and return promptly - other clients can progress between this client's steps 9 session state records the current stage of communication - changes when relevant requests, responses, or other events arrive 10 finite-state machine (FSM): - predefined set of states - events cause transitions between states - client-session logic naturally fits this representation 11 questionnaire state diagram: - creation: ask name; enter name / start - name received: save it, ask age, enter age - valid age received: save it, ask town, enter town - town received: save it, ask band, enter band - band received: save it, thank the user, enter finish - invalid age: remain in age and ask again transitions can have both a condition and associated actions 12 use a distinct error state for a session that cannot continue - example: input buffer fills before a newline arrives - a 2048-byte limit is ample for this example's expected answers - report an overlong line and terminate that session - error must remain distinguishable from successful completion 13 more complex protocols can branch according to previous answers - several transitions may leave one state - large diagrams can be split into groups with separate diagrams - another diagram describes transitions between those groups 14 implement states as stored values - an enum can contain start, name, age, town, band, finish, error - fsm_name = fsm_start gives the initial state two names - each session stores its own current state 15 state information can include several variables - counters, parameters, and saved answers can accompany the state enum - application state is explicit data retained between handler calls 16 FSM reacts to events supplied by the surrounding program - event acquisition remains outside the FSM step - FSM receives a completed line and decides what it means - it must not block waiting to obtain its next event 17 example struct session contains: - fd: client socket descriptor - buf[2048]: accumulation buffer - buf_used: number of occupied bytes - state: current FSM state - name, town, band: pointers to saved answers - age: parsed integer 18 make_new_session(fd) initializes a newly accepted connection - allocate the session structure and record fd - set buf_used = 0 and state = fsm_start - initialize answer pointers to NULL and age to -1 - send / queue the first question, "What is your name?" - return the initialized session 19 session_send_string isolates outgoing text handling - example simply calls write(fd, s, strlen(s)) - every question and diagnostic uses the same helper 20 that helper is deliberately simplified for this small demonstration - a fully nonblocking implementation queues outgoing data - tracks writable events and partial writes - tiny messages do not provide an unconditional guarantee against blocking 21 session_fsm_step(sess, line) receives ownership of a complete allocated line - name state: retain line as name; ask age; enter age - age state: parse / validate through a helper, then free the input line - town state: retain line as town; ask band; enter band - band state: retain line as band; send thanks; enter finish - unexpected finish/error invocation: free the supplied line ownership avoids copying saved text unnecessarily 22 switch(state) selects the action for the current FSM state age helper: - use strtol with base 10 - reject empty input, trailing invalid characters, or an age outside 0–150 - invalid answer: ask again without changing state - valid answer: save age, ask town, enter town - robust parsing also checks strtol overflow before narrowing to int 23 main loop should use a session interface instead of manipulating the FSM session_do_read: - read into buf + buf_used, leaving existing data intact - update buf_used after a successful read - call session_check_lf to extract and process complete input - if a line has exhausted the buffer, report it and mark error - return 1 to retain the session, 0 when it should be closed - EOF, fatal read errors, and finish end this example's session - distinguish retryable EINTR / EAGAIN when extending it to nonblocking I/O 24 session_check_lf connects byte-stream handling with the FSM - search the occupied buffer for '\n' - no newline: leave the fragment buffered and return - copy bytes before newline to a separately allocated, NUL-terminated string - remove that line and newline from the buffer - use memmove to shift remaining bytes and reduce buf_used - strip a trailing '\r' to accept CRLF input * check that the line is nonempty before examining its last character - transfer line ownership to session_fsm_step for pipelined input, process additional complete buffered lines promptly - the shown one-line helper can otherwise leave a line waiting for new data - stop when the session finishes or errors; keep each event's work bounded 25 tcp_questn.c in the book's examples contains the complete questionnaire server - accepts TCP clients - runs this session FSM - saves completed questionnaire results in a text file 26 explicit states replace information previously carried by control flow - sequential version: current instruction position records dialogue progress - event-driven version: stored state records that progress -> programming in terms of explicit states 6.4.6 Establishing a connection without blocking 1 a program can act as both server and client - while serving its own clients, it may request data from another server 2 ordinary connect can block until establishment succeeds or fails - this can take long enough to stall the whole event loop - outgoing connections therefore need nonblocking handling too 3 make the socket nonblocking before connect possible outcomes: - 0: connection completed immediately - -1 / EINPROGRESS: attempt has started but is still pending - another error: handle the failed attempt - immediate success must be handled even if it is uncommon 4 a pending connect uses writable readiness - put its socket in writefds - writability reports that the connection attempt has finished - completion can mean success or failure - this is a separate use of writefds from queued application output 5 check the outcome with getsockopt - level = SOL_SOCKET - option = SO_ERROR - provide an int to receive the socket error - provide socklen_t initialized to sizeof(that int) - getsockopt(sd, SOL_SOCKET, SO_ERROR, &opt, &optlen) - optlen is an input/output size parameter - check getsockopt's own return value before using opt 6 after successful getsockopt: - opt = 0: connection established - opt != 0: connection failed; opt contains its error code - move the connection into its next application state or clean it up 6.4.7 Signals as events: pselect 1 signal notifications can become events in a select-based program - the difficulty is coordinating their delivery with the event loop's wait - the same signal-mask principles apply as in sigsuspend 2 a caught signal interrupts select with -1 / EINTR - this lets the main loop react to a signal - but the loop also spends time outside select 3 minimal signal handler records that work is pending - example: SIGUSR1 updates usr1_caught - use volatile sig_atomic_t for a simple pending flag - ordinary signals can coalesce; the flag is not a reliable count of sends 4 perform substantive work in an ordinary main-loop function - example name: actions_on_usr1 - can use facilities unsuitable inside the asynchronous signal handler - must still return promptly like every event handler example sequence: preparation A -> select -> code B -> process signal flag -> C - signal during select or B is handled by that iteration's flag check 5 signal during A or C creates a lost-wakeup problem - handler records the signal before the next select begins - select does not know there is already pending application work - it may wait indefinitely for a different event 6 visible effect: a control request appears to have been ignored - e.g. administrator sends SIGUSR1 to request configuration reload - the flag is set, but reload waits until an unrelated event wakes select 7 first attempted fix: process the flag immediately before select - reduces the vulnerable interval - does not make checking the flag and entering the wait atomic 8 a signal can still arrive between the final check and select - small probability does not remove the race 9 this is the same problem as checking a flag before pause - sigsuspend solves it by atomically replacing the mask while waiting - keep the relevant signal blocked outside the wait - allow its delivery only during the wait 10 pselect adds atomic signal-mask replacement to select-style waiting - pselect(n, readfds, writefds, exfds, timeout, sigmask) - sigmask: pointer to the mask active during the wait - previous mask restored before return - timeout uses const struct timespec, not timeval * tv_sec: whole seconds * tv_nsec: nanoseconds, 0 through 999999999 - specified interface leaves the supplied timeout unchanged 11 for this pattern, sigmask temporarily permits the awaited signal - mask still lists blocked signals - omit the awaited signal from the temporary mask - the normal mask outside pselect keeps it blocked 12 SIGUSR1 event-loop pattern: - create a set containing SIGUSR1 - sigprocmask(SIG_BLOCK, &mask, &orig_mask) - install the handler; preserve the original mask - call pselect with a temporary mask that permits SIGUSR1 * using orig_mask assumes it did not already block SIGUSR1 - signal can now run its handler during the wait and interrupt it - after return, normal blocking is restored - inspect the flag, perform the work, and clear the flag while SIGUSR1 is blocked - continue dispatching other events; repeat with rebuilt descriptor sets 13 ordinary select can be sufficient when bounded notification delay is acceptable - a short periodic timeout ensures the flag is checked regularly - e.g. a 0.1-second timeout bounds most waiting delay to roughly that interval plus time spent in other handlers - pselect removes the signal-check / wait race without periodic polling 7. Parallel programs and shared data 1 parallel programming: divide work into subtasks that can execute concurrently - threads run functions alongside the main program - threads share the process's memory, including globals and dynamically built structures 2 multithreading = programming with multiple threads of execution - Russian terminology often translates this as "multistream" programming - thread / control flow refers to execution, not transferred data 3 thread, flow, and stream have overlapping Russian translations - an I/O stream carries data; a thread executes instructions - keep the two programming concepts distinct 4 book uses "thread" for one execution thread - uses the conventional Russian term for multithreaded programming 5 multicore processors made parallel programming widely available - speed may instead be limited by network, storage, memory, or bus throughput - dependent steps must still execute in sequence - identifying enough independent work is essential to useful parallelism - author's broad criticism of parallel programming is a viewpoint, not a universal rule 6 Amdahl's law: the serial part limits total speedup - alpha = fraction that remains sequential; p = processor count - ideal speedup S = 1 / (alpha + (1 - alpha) / p) - assumes perfect parallelization of the remaining fraction - alpha = 1/4: 10 processors -> about 3.08x; 21 -> 3.5x; 100 -> about 3.88x - even infinitely many processors approach only 4x - alpha = 0.05: limit 20x; 21 processors -> 10.5x, 57 -> 15x, 361 -> 19x - communication, data transfer, and cache coherence add costs beyond this ideal model 7 book highlights numerical simulation and video processing as parallel workloads - independent calculations can make the serial fraction small - benefit depends on the actual workload; these are examples, not an exhaustive list 8 interactive compression / decompression example: - lengthy computation must not freeze interface events or cancellation - one worker can compute while another handles the interface - author prefers separate processes with isolated memory for this design 9 creating threads does not itself create useful parallel work - threads that immediately wait for one another may add overhead without speedup 10 several independent event sources complicate sequential control flow - waiting for one client's next answer can delay every other client - each client may have its own logical request / response sequence 11 event-driven design: wait for an available event, identify its source, then handle it - handlers must not block waiting for a particular unrelated event - long computations must be split into manageable portions or moved elsewhere - explicitly retain each session's state / next expected action - some events only update state; further work waits for later events 12 one thread per event source can hide session state in thread execution state - blocked threads do not by themselves improve computational throughput - each thread consumes user-space and kernel resources - shared memory introduces synchronization responsibilities - author's preference here is explicit event handling 13 shared data: data accessible to several independently executing participants - participants may be processes or threads - shared objects may live in memory or in disk files 14 shared-data access requires deliberate coordination - critical section: logically connected work on shared data - mutual exclusion prevents conflicting critical sections from overlapping - simultaneous read-only access can be permitted 15 understanding the need for synchronization is part of writing threaded programs - using a thread API alone does not establish correctness 16 author's experience: programmers may use mutexes without being able to justify them - forthcoming examples explain concrete failures that a mutex must prevent 17 concurrency bugs may require rare execution interleavings - incorrect programs can appear to work for a long time - reproducing the same ordering of several threads is difficult - successful runs and ordinary debugging alone do not prove synchronization correct 18 Edward Lee's cited argument: threads introduce many possible execution orderings - programmer must restrict this nondeterminism to obtain predictable behavior 19 shared-data problems matter even when choosing not to use threads - needed to evaluate other concurrent programs - some domains, including multiprocessor kernels, inherently share state 20 independent programs can share data without belonging to one parallel application - mailbox example: delivery appends mail while clients read or delete it - database example: many users access and update the same records - when sharing is part of the problem itself, it cannot simply be designed away 7.1 Working with Shared Data 7.1.1 Stale Data and Data Integrity 1 two processes increment a shared integer initially equal to 5 - intended final value: 7 - each increment consists of load from memory, increment register, store to memory 2 some processors offer atomic memory arithmetic, e.g. suitable x86 LOCK operations - this does not make arbitrary multi-step updates atomic - incrementing a number stored as text still involves several operations - load/store architectures also illustrate the general problem 3 first process loads 5, then is interrupted - second process loads 5, increments to 6, and stores 6 4 first process resumes with its old register value 5 - increments and stores 6, overwriting the other's update - final value 6 instead of 7 -> lost update - result depends on interleaving -> race condition 5 bank example: account balances 301 = $1000, 515 = $1500, 768 = $2000 - transfer A: $100 from 301 to 768 - transfer B: $200 from 768 to 515 - correct balances after both: $900, $1700, $1900 6 transfer B reads balances, then pauses while A completes - A writes account 768 = $2100 - B computes from the old $2000 and writes $1800 - $100 disappears from the recorded total - reverse the unlucky ordering and account 768 can instead retain $200 too much 7 read-only summation can also race with transfers - sum has already visited destination account but has not visited source account - transfer occurs between the two reads - transferred money is counted in neither account - a reader can obtain an inconsistent result without modifying anything 8 common cause: computation uses input that became stale during the operation - increment overwrites a newer value - transfer computes from an obsolete balance - total combines balances observed at incompatible moments 9 data becoming old is not automatically an error - displayed results can legitimately describe a recent past state - problem: overwrite current data using a stale version of that same data - problem: combine values that were never simultaneously valid - latter case violates the integrity / consistency of the observed data 7.1.2 Mutual Exclusion and Critical Sections 1 serializing entire process lifetimes is usually too restrictive - a long-running server may access shared data only occasionally - protect the relevant operation, not every unrelated action of the process 2 keep related input consistent for the duration of a shared-data operation - updating shared storage: protection lasts through the final result write - producing an external report: result may legitimately become old afterward - read-only report needs a coherent set of inputs - once all required inputs have been safely copied, later private computation need not keep the shared data locked 3 critical section: logically connected manipulations of particular shared data - starts before the first relevant shared read - ends after required reads and all shared result writes - increment: load through store - transfer: first balance read through last updated balance write - summation: the complete protected scan 4 "critical section" can mean either: - a region of program code - the time interval during which that region executes 5 critical sections are defined relative to particular data - unrelated data need not share one exclusion mechanism - distinguish read-only sections from modifying sections 6 two critical sections conflict when: - both touch some of the same data - at least one modifies those common data - two read-only sections do not conflict 7 mutual exclusion: conflicting critical sections cannot execute simultaneously - its implementation must also avoid creating progress problems 8 participants follow synchronization rules voluntarily - access to shared memory is not physically blocked by an ordinary mutex - every cooperating program must obtain permission before using protected data - one participant ignoring the protocol can invalidate the whole scheme 9 requirements for the book's exclusion mechanisms: - never allow overlapping conflicting critical sections - do not assume relative process speeds or a particular processor count - a process outside its critical section must not prevent others from entering - avoid starvation: a participant must not wait forever while others proceed - avoid busy waiting where practical; blocked waiters should not waste CPU time 7.1.3 Mutual Exclusion Using Variables 1 this subsection studies shared-variable algorithms with busy waiting - they illustrate synchronization logic without a blocking kernel primitive - real C implementations also require appropriate atomic operations / memory ordering 2 naive lock variable s: 1 = free, 0 = occupied - wait while s == 0 - set s = 0; run critical section; set s = 1 - separate test and assignment make this attempt incorrect 3 race: first process sees s == 1, then pauses before storing 0 - second process also sees 1, sets 0, and enters - first resumes and enters too - both passed the test before either claimed the resource 4 testing availability and claiming the resource must form one atomic action - another participant must not intervene between these steps 5 disabling hardware interrupts is not a general user-space solution - long interrupt suppression disrupts device handling - accessing paged-out memory or performing I/O may require kernel activity - disabling interrupts on one CPU does not stop another CPU 6 busy waiting with interrupts disabled can freeze a uniprocessor system - resource owner cannot run to release the resource being awaited 7 ordinary user processes cannot disable interrupts - a bug or infinite loop could otherwise stop the system - kernel may briefly disable local interrupts as part of its own synchronization 8 strict alternation: shared turn chooses process 0 or process 1 - process waits for its turn, executes its section, and hands over the turn - then performs unrelated work 9 alternation prevents simultaneous entry but can prevent useful progress - process cannot re-enter until the other returns and hands over its turn - other process may be busy with noncritical work - violates the rule that a participant outside its section must not block others 10 Peterson's algorithm: two participants, numbered 0 and 1 - interested[2]: each participant's intent to enter / presence in its section - who_waits: participant that yields if both want to enter - generalized shared-variable algorithms include Lamport's bakery algorithm 11 participant i enters by: - interested[i] = true - who_waits = i - wait while who_waits == i AND interested[other] - proceed if the other yields or is no longer interested - on leaving: interested[i] = false 12 Peterson supplies enter_section and leave_section procedures - avoids the logical failures of naive locking and strict alternation - still busy-waits - correctness assumes atomic, properly ordered shared accesses; plain unsynchronized C variables are not a portable implementation 7.1.4 Mutexes 1 busy waiting repeatedly polls shared state while doing no useful work - preferable alternative: block until access may become available - later wake the waiter so it can acquire the resource - mutexes and semaphores provide the required synchronization abstractions 2 mutex: initially unlocked object with lock and unlock operations - blocking lock: acquire immediately if free, otherwise wait until acquisition succeeds - nonblocking try-lock: acquire if free, otherwise immediately report failure - once acquired, exactly one participant owns the mutex 3 mutex ownership rule: only the participant that locked it may unlock it - successful unlock releases ownership and makes further acquisition possible 4 absence of an ownership check does not permit another thread to unlock a mutex - implementation may leave misuse undetected - mutex ownership distinguishes a mutex from a binary semaphore 5 acquisition must be atomic with respect to other participants - no gap between observing "free" and claiming ownership - blocking may suspend the caller, but must not break the protocol 6 replace the naive lock variable with a real mutex - repeatedly trying a nonblocking lock preserves exclusion but still busy-waits - blocking version: lock(m); critical_section(); unlock(m) - the mutex's atomic acquisition prevents two successful owners at once 7.1.5 Implementing Mutexes 1 kernel manages blocking and wakeup of scheduled processes / threads - sleep for an arbitrary interval cannot predict when a resource will become free - kernel synchronization can coordinate waiting and resource-state changes - local interrupt suppression alone is insufficient on multiple CPUs 2 entering the kernel for every acquisition and release can be expensive - synchronization cost can outweigh the work on a small protected object 3 atomic CPU operations allow an uncontended user-space fast path - x86 xchg with a memory operand atomically exchanges memory and a register - use the old value to determine whether acquisition succeeded 4 example representation: integer mutex, 1 = free, 0 = locked - put 0 in a register and exchange it with the mutex - old value 1 -> this operation acquired the lock - old value 0 -> already locked; caller must wait - release stores 1 with the ordering required by the implementation 5 simple assembly spinlock repeats exchange until the old value is 1 - release restores 1 - correct atomic claim, but repeated failure wastes CPU time - yielding to another thread between attempts can reduce spinning - yielding alone still does not provide a proper blocking wait 6 practical blocking implementations track contended locks and waiters - failed acquisition may ask the kernel to block the caller - releasing a lock with waiters may ask the kernel to wake one - lock operations can avoid kernel calls when nobody needs to block or wake 7 Linux futex supports waiting and waking around a shared user-space word - protocol must avoid races between changing the word and blocking - low-level futex programming is normally encapsulated by synchronization libraries 8 uncontended mutex operations often stay entirely in user space - contention introduces blocking, wakeups, scheduling, and extra kernel calls - keep critical sections short relative to useful independent work - frequent waiting can erase the benefit of parallel execution 7.1.6 Dijkstra Semaphores 1 semaphore operations resemble mutex operations at first glance - one operation can block until another participant performs the opposite operation - both require atomic synchronization 2 mutex protects ownership of a shared resource - semaphore commonly counts available resources or signals events - one participant may legitimately wait on a semaphore that another posts 3 counting semaphore holds a nonnegative integer - up: add 1 and make an additional permit available - down: if positive, subtract 1 and continue - down at 0: block until a permit can be obtained - checking, consuming permits, and coordinating wakeups must be atomic 4 binary semaphore uses values 0 and 1 - can enforce exclusion if initialized to 1 and used with balanced down / up - unlike a mutex, has no owner-only release rule - one process may perform down and another up 5 counting semaphore can represent several available resources - mathematical model allows any nonnegative count - implementations impose a finite maximum 6 historical attribution: semaphore abstraction is associated with Edsger Dijkstra - book also mentions an account crediting Carel Scholten with its counting extension 7 do not use mutex ownership violations as a substitute for semaphore signaling - missing runtime checks do not make misuse valid - roles should remain clear to readers - mutex normally starts unlocked; an event semaphore may start at zero 8 semaphore as resource counter: - wait before entering a section when the resource needed there is unavailable - example: no empty buffer slot or no produced item - binary event semaphore: wait until another participant signals permission 9 some implementations provide additional operations: - up(sem, n): add n permits - down(sem, n): wait for at least n, then consume n atomically - nonblocking down: immediately report unavailable permits - query/set count operations, often useful during initialization 10 System V semaphore arrays support compound atomic operations - example: add 2 to one semaphore and subtract 3 from another as one operation - can also wait for a semaphore to become zero 11 pipe illustration: one queued byte represents one available permit - up writes one byte; down reads one byte - reading an empty pipe blocks until another participant writes - finite pipe capacity bounds the count; writing a full pipe can block - every operation is a system call, so this is not an efficient mutex fast path - handle interrupted calls and endpoint lifetime in a real implementation 7.2 Classical Mutual Exclusion Problems 1 examples use abstract C-like pseudocode - lock(m) / unlock(m): mutex operations - down(s) / up(s): semaphore operations - focus on synchronization logic, independent of process/thread API details 7.2.1 Producers and Consumers 1 producers generate data for later processing - possible sources: sensors, network input, user interaction, computation 2 consumers process the data prepared by producers 3 bounded shared buffer holds N fixed-size items - buffer operations require mutual exclusion - example protects the entire buffer as one shared object 4 two resource shortages must block useful work: - consumer wants an item, but buffer is empty - producer has an item, but buffer is full - each waits for an operation by the opposite kind of participant 5 repeatedly locking, checking, unlocking, and retrying is busy waiting - long retry intervals delay available work - short intervals waste CPU and cause lock contention - no arbitrary polling interval solves the underlying coordination problem 6 counting semaphores prevent entry until a needed resource is available - empty: free slots; initially N for an empty buffer - full: available items; initially 0 - mutex m separately protects changes to buffer contents and bookkeeping 7 put_data / get_data perform only buffer manipulation - assume caller already owns m - assume a suitable slot / item has already been reserved - find slot, copy data, update buffer bookkeeping 8 producer: - prepare item; down(empty); lock(m); put_data(); unlock(m); up(full) - consumer: down(full); lock(m); get_data(); unlock(m); up(empty); process item - semaphore waits happen before taking the mutex - semaphores count resources; mutex provides exclusion - item preparation / processing happens outside the buffer's critical section 7.2.2 Dining Philosophers and Deadlocks 1 deadlock: participants wait for resources held by one another - none can reach the operation that would release what another needs 2 English technical term: deadlock - "dead end" does not name this concurrency condition 3 five philosophers share five forks around a table - each alternates thinking and eating - eating requires both adjacent forks - naive protocol: acquire left fork, then wait for right without releasing left 4 if all five acquire their left fork, nobody can acquire the right fork - each needed fork is held by a neighbor who is also waiting - nobody can start eating and then release resources 5 two processes and two mutexes suffice for deadlock - first locks m1, then m2 - second locks m2, then m1 - if each acquires its first mutex, both wait forever for the second 6 deadlock also occurs without explicit mutexes - example: child executes ls with stdout redirected to a pipe - parent closes its write end, waits for child, then intends to read the pipe - may work for small output and hang for large output 7 child must finish writing ls output before it exits - parent waits for exit before starting to read - therefore nobody drains the pipe while the child is running 8 pipe buffer has finite capacity - once full, child's write blocks until a reader frees space - parent cannot read because it is blocked in wait 9 dependency cycle: parent waits for exit; child waits for parent's read - fix this example by reading / draining the pipe before waiting for child exit - correctness must not depend on a particular pipe-buffer size 10 naive philosopher implementation uses five fork mutexes - left(n) = (n - 1 + 5) % 5; right(n) = (n + 1) % 5 - philosopher n locks forks[n], then forks[right(n)] - eat, release both, repeat - simultaneous first acquisitions reproduce the circular wait 11 limit the number attempting acquisition with a counting semaphore - down(sem) before taking forks; up(sem) after releasing both - initial count below 5 prevents all five holding one fork - count 1 serializes all eating - count 2 can admit neighbors that still interfere, leaving other possible work idle 12 at most four philosophers may compete under this semaphore solution - count 4 avoids the circular deadlock but can still leave only one eating - removing deadlock does not automatically maximize concurrency 13 resource ordering: always acquire lower-numbered fork before higher-numbered fork - philosopher between forks 4 and 0 takes 0 first, reversing the usual order - a consistent ordering prevents a circular acquisition dependency 14 ordering can be partial rather than a complete numbering - objects acquired together must be comparable under the ordering - can suit a dynamically changing resource set 15 resource ordering has practical tradeoffs - philosophers holding one fork may still leave usable resources idle - real programs may discover the next needed object only after locking others - if that object comes earlier in the order, held locks must be released and retried - repeated release / reacquisition can cost substantial work 16 steward mutex serializes acquisition of fork pairs - lock(steward); acquire both forks; unlock(steward); eat; release forks - eating and releasing forks do not need the steward - prevents circular acquisition deadlock - if current acquirer waits for a neighbor's fork, everyone else waits for steward, even philosophers who could otherwise eat 17 starvation: participant repeatedly fails to obtain the resources it needs - identical timeouts can make everyone release, wait, and retry in step - this active but unproductive cycle is livelock - random retry delays can break synchronized collisions - timeouts alone do not guarantee progress or fairness 18 state-based solution: thinking, hungry, or eating for each philosopher - one private binary semaphore can_eat[i], initially 0 - hungry philosopher may eat when neither neighbor is eating / reserved to eat - otherwise waits until a neighbor releases forks and grants permission 19 one state_mutex protects the state array; separate fork mutexes are unnecessary - take_forks(i): lock; state[i] = hungry; test(i); unlock; down(can_eat[i]) - put_forks(i): lock; state[i] = thinking; test(left); test(right); unlock - test(i): if i is hungry and neither neighbor is eating, set state[i] = eating and up(can_eat[i]) - reserving the eating state before notification prevents conflicting grants - semaphore wait occurs outside state_mutex 20 state-based solution prevents deadlock but does not guarantee no starvation - neighbors 1 and 3 can alternate so that at least one is always eating - philosopher 2 then never sees both neighbors available 21 Chandy-Misra solution uses ownership transfer and messages - each fork is always held by one adjacent philosopher - fork is clean or dirty; eating makes it dirty - sent fork is cleaned before transfer - initially forks are dirty - complete algorithm also requires a suitable acyclic initial ownership ordering; the book's informal description omits this condition 22 hungry philosopher requests each missing fork from its holder - waits until both have arrived - if already holding both, can begin eating 23 on receiving a fork request: - dirty fork may be cleaned and sent when holder is not eating - hungry sender also requests it back - clean fork is retained; request is remembered - after eating, satisfy remembered requests by cleaning and sending dirty forks - never hand away a fork while actively using it to eat 24 clean/dirty distinction prevents neighbors endlessly reclaiming a newly received fork - clean fork can be retained until its holder gets a turn to eat - with the full protocol and progress assumptions, waiting does not become starvation 25 book explains why five philosophers make a useful teaching example - smaller cases admit special simplifications 26 one philosopher: no competition - two philosophers: only one can eat anyway - protect the pair of forks as one resource instead of independently locking both 27 three philosophers: again only one can eat at a time - one mutex around the meal captures all useful exclusion 28 four philosophers can eat as two fixed pairs of opposite seats - members of one pair do not share forks - synchronize between the two pairs rather than treat every fork independently 29 five participants remove these particular one-resource / fixed-pair simplifications - larger rings retain the same main acquisition and fairness problems 7.2.3 Resource Allocation Graphs 1 graph described in the book has process nodes and resource nodes - resource -> process: resource is held exclusively by that process - process -> resource: process waits to acquire that resource - for single-instance exclusive resources, a directed cycle indicates deadlock - often called a resource-allocation graph; book calls it a waiting graph 2 examples distinguish a graph without a wait cycle from: - two processes each waiting for the other's resource - five philosophers each waiting for the next fork in the ring 3 reduce the graph by repeatedly removing edges: - leaving a node with no incoming edges - entering a node with no outgoing edges - a remaining irreducible directed cycle identifies the deadlocked dependency 4 transactions allow recovery when avoiding every deadlock is impractical - retain information needed to undo modifications until completion - rollback restores the transaction's changes and releases its claims - graph can track transactions instead of whole processes - on a cycle, choose a victim using rollback cost; abort it and recheck - transaction may span many short critical sections - database lock bookkeeping avoids requiring one permanent mutex per record 7.2.4 Readers and Writers 1 allow several readers at once, but make writers exclusive - reader + reader: compatible - writer + reader or writer + writer: conflict - even a read-only computation needs protection against concurrent modification 2 shared rc counts active readers - first reader acquires database access; last reader releases it - these may be different threads -> use binary semaphore db_access, initially 1 - rc starts at 0; mutex rc_mutex starts unlocked and protects changes to rc 3 writer: down(db_access); modify data; up(db_access) 4 reader entry: - lock(rc_mutex); increment rc - if rc becomes 1, down(db_access) while still holding rc_mutex - unlock(rc_mutex), then read shared data - later readers join the group without acquiring db_access separately - exit: lock(rc_mutex); decrement rc - if rc becomes 0, up(db_access); unlock(rc_mutex) 5 continuous overlapping readers can keep rc above zero indefinitely - no individual reader need be slow - writer still waits forever for the whole reader group to disappear 6 add barrier mutex to stop admitting new readers once a writer owns it - reader briefly locks and unlocks barrier before the normal entry procedure - writer locks barrier before waiting on db_access - after barrier is acquired, only already-admitted readers can remain ahead 7 writer waits for admitted readers to finish, writes, then releases db_access and barrier - new readers can then enter again - prevents an endless influx of new readers from extending the current read phase - absolute starvation freedom still depends on fair enough lock acquisition / scheduling 7.2.5 The Sleeping Barber 1 one barber, one work chair, and N waiting-room chairs - clients and barber represent concurrent participants 2 barber finishes one client, then takes another waiting client - sleeps when no clients are waiting 3 arriving client wakes an idle barber - if barber is occupied, waits in a free waiting-room chair - leaves without service if no waiting seat is available 4 checking a condition and acting on it are separate operations - two arrivals can both observe the final free seat - without exclusion, both attempt to claim it 5 lost coordination example: - arriving client sees busy barber and starts toward waiting room - barber finishes, sees room still empty, and sleeps - client sits and waits for barber - both can wait indefinitely unless another arrival intervenes 6 common solution needs seat count, protected by a mutex, plus customer/barber semaphores - fuller version also coordinates entering the work chair and finishing the haircut - barber must not work before the client is ready - client must not leave before the work is finished 7 shared state: - seats = N; seats_mutex initially unlocked - customers: count of waiting clients - barber: permission for one client to approach the work chair - client: client signals that preparation is complete - seat_belt: barber signals completion - all four semaphores initially 0 8 barber loop: - down(customers) - lock(seats_mutex); up(barber); increment seats; unlock(seats_mutex) - down(client); perform haircut; up(seat_belt) - sleep for lack of clients happens through customers, not polling 9 inviting a client and updating free-seat count are coordinated under seats_mutex - other arrivals should observe a consistent allocation of waiting places - separating these changes exposes intermediate states to their seat checks 10 client: - lock(seats_mutex) - if no seat: unlock and leave - otherwise up(customers), decrement seats, unlock - down(barber); prepare in the work chair; up(client) - down(seat_belt) before leaving - one posted barber permit admits one waiting client 11 this client also announces itself through customers inside seats_mutex - extra client / seat_belt handshakes change which race arguments apply - justification must match the actual version of the algorithm 12 fuller model assumes a passive client during the haircut - useful when barber alone acts on a resource associated with the client - if both sides must actively work, blocking client for the whole operation is unsuitable - shorter textbook form calls BARBER_WORK and CUSTOMER_WORK concurrently - then those procedures must contain their own preparation/completion synchronization 13 assume BARBER_WORK / CUSTOMER_WORK handle their own rendezvous correctly - announcing a client before safely reserving a seat is still wrong - client may announce, discover no seat, then decide to leave - barber may consume the announcement before it can be withdrawn - result: invite / try to serve a nonexistent client 14 reserving a seat first and posting customers afterward needs separate analysis - earlier argument against announcing before reservation does not apply directly 15 literal story details are not all represented by the semaphore model - concurrent up(customers) calls are valid; each records one customer - barber may briefly sleep after a seat is reserved but before its customer is posted - eventual post still wakes it; holding seats_mutex alone does not forbid this pause - exact "who woke whom" and chair movement need extra state if those details matter 16 author's revision history illustrates why synchronization explanations need precision - adding a handshake can remove the very race used to justify another ordering - compare complete protocols, including assumptions hidden inside work procedures 7.3 Multithreaded Programming in Unix 1 practical thread examples let us test shared-data synchronization concepts - book uses threads to demonstrate mutexes and semaphores - author's criticism of threads and System V IPC is a design preference 2 understand thread programming even when choosing another design - choosing an alternative should follow knowledge of its tradeoffs 3 threads belong to one process and share its virtual address space - main thread and worker threads can access the same ordinary objects - each thread has its own execution state and stack - kernel schedules threads independently - getpid / getppid return the same process identifiers across the process's threads 4 each thread's stack is still memory in the common address space - another thread can access a valid object there if given its address - separate stacks do not provide memory isolation 7.3.1 The POSIX Threads Library 1 POSIX standardized thread interfaces under the name POSIX Threads / pthreads - common portable interface for Unix thread programming 2 thread entry function has form void *entry(void *arg) - one arbitrary pointer supplies startup information - returned pointer supplies a result - referenced objects must remain valid for as long as they are used 3 pthread_create(&thread, attributes, entry, argument): start a thread - pthread_t stores its identifier - attributes = NULL selects defaults - entry receives argument as its one void* parameter - returns 0 on success, otherwise an error number directly - EAGAIN can mean exhausted resources / thread limit; other errors are possible 4 thread finishes by returning from its entry function or calling pthread_exit(result) - both provide a void* result to a joining thread - pthread_exit ends the calling thread - exit, or returning from the process's main function, ends the whole process 5 pthread_join(thread, &result): wait for a joinable thread to finish - result argument is an address of a void* variable - receives the thread's returned value - join also reclaims the terminated thread's retained resources 6 joinable thread retains termination information until joined - pthread_detach(thread) arranges automatic cleanup on termination - detached thread cannot later be joined for its result - join / detach return 0 or an error number 7 pthread_self(): obtain caller's pthread_t - pthread_detach(pthread_self()): detach the calling thread 8 pthread_cancel(thread): request cancellation - cancellation is not necessarily immediate - with deferred cancellation, request is acted on at a cancellation point - joined result is PTHREAD_CANCELED if cancellation terminates the thread - cancellation state, cleanup, and held resources require careful handling 7.3.2 Semaphores and Mutexes 1 POSIX mutex and semaphore interfaces use different naming conventions - mutex functions use pthread_ prefix - semaphore functions use sem_ and also support suitable interprocess use 2 pthread_mutex_t represents a mutex - initialize ordinary static/default mutex with PTHREAD_MUTEX_INITIALIZER - example: pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER - macro is an initializer, not an arbitrary assignment expression - other initialization forms allow attributes 3 mutex functions take pthread_mutex_t*: - pthread_mutex_lock: wait until acquired - pthread_mutex_trylock: attempt without waiting - pthread_mutex_unlock: owner releases it - return 0 or an error number directly - busy trylock reports EBUSY, not the book's stated EAGAIN - pthread_mutex_destroy ends the mutex's lifetime - destroy only when unlocked and no thread can still use or wait on it - do not rely on the implementation detecting every invalid destruction 4 sem_t represents a POSIX semaphore - interfaces are intended for threads and, when supported/configured, separate processes 5 process-shared semaphore support depends on implementation - semaphore object must live in shared memory - initialization must request process sharing 6 sem_init(&sem, pshared, value): initialize an unnamed semaphore - pshared = 0: shared by threads of one process - nonzero: shared by processes, requiring actual shared-memory placement - value: initial permit count - returns 0 or -1 with errno, unlike pthread error-number returns - implementations can use user-space fast paths and kernel waiting/wakeup 7 sem_post(&sem): add one permit, waking a waiter if needed - sem_wait(&sem): consume one permit, blocking while unavailable - sem_trywait(&sem): immediate attempt; at zero returns -1 with errno = EAGAIN - successful operations return 0 - real code must also handle failures, including interrupted sem_wait 8 sem_getvalue(&sem, &value): obtain an observed semaphore value - another participant may change it immediately - reading the count does not reserve a permit 9 sem_destroy(&sem): end semaphore lifetime - no thread or process may still be waiting on it or using it - destroying a semaphore with waiters has undefined behavior - do not expect sem_destroy to detect this lifecycle error 7.3.3 Demonstration Program 1 demonstration tests shared-data correctness rather than solving a useful application task - author's skepticism about threads motivates the choice of a deliberately simple example 2 main creates an integer array, initially all zeros - each worker repeatedly chooses two positions - increments one element and decrements another - expected invariant: sum of all elements remains zero - main prints the sum and array once per second 3 compile the same example with synchronization enabled or disabled - protected version should preserve the invariant and print consistent snapshots - unprotected updates can lose increments / decrements and corrupt the total - exact unprotected output is not predictable; unsynchronized C accesses are data races - correctness also assumes valid integer ranges and successful API calls 4 thread startup introduces a second shared-data problem - example therefore uses a semaphore as well as the array mutex 5 workers need independent pseudo-random generator state - a shared rand generator mixes requests according to unpredictable thread scheduling - safety of concurrent rand calls depends on the library implementation - even a synchronized global generator does not give each thread a reproducible sequence - private state avoids this shared generator dependency 6 book uses rand_r(&seed) with an unsigned int seed private to each worker - function updates caller-supplied state instead of one shared generator state - calling time separately in quickly started threads can give them identical seeds 7 main obtains time(NULL) once, then increments the seed for each new worker - different startup values produce different per-thread generator sequences - this is a simple demonstration setup, not a guarantee of independent random streams 8 startup information includes seed, shared array, and its mutex - pass these explicitly instead of relying on global variables 9 one void* can point to a structure containing all startup data - initial fields: unsigned int randseed, int *array, pthread_mutex_t *arr_mutex - fill the structure and pass its address as pthread_create's argument 10 startup race: worker reads the structure while main prepares the next worker - reusing the same structure can overwrite fields before the first worker copies them - passing a pointer does not copy the pointed-to object 11 one structure per worker is a possible alternative - each structure must remain alive until its user finishes reading it - resizing a contiguous array can invalidate addresses already handed to threads - stable allocation or a controlled lifetime is required 12 example instead uses a copy-and-acknowledge handshake - worker copies every startup field into its own local variables - then tells main it no longer uses the structure - main waits for that acknowledgment before modifying the structure again 13 startup semaphore initially 0 - main starts worker, then sem_wait - worker finishes copying, then sem_post - posting before main begins waiting is safe: permit remains available - one ordinary POSIX semaphore suffices for this binary signaling pattern 14 example constants: - ARRAY_SIZE = 10 - WORKERS_COUNT = 3 - PAUSE_LENGTH = 1 second - PROTECTION defaults to 1; compiler definition can set it to 0 15 thread_start_data also receives sem_t *data_sem - array and seed fields are always present - mutex and semaphore pointers exist only under #if PROTECTION == 1 16 worker entry: - convert void* argument to thread_start_data* - copy seed, array pointer, and synchronization pointers locally - sem_post(data_sem) only after all copying is complete - repeatedly choose idx1 and idx2 using rand_r % ARRAY_SIZE - if indices match, skip the iteration - otherwise lock array mutex, increment one element, decrement the other, unlock - random-number generation stays outside the array's critical section - loop has no normal termination path; trailing return NULL is unreachable 17 main's local variables hold the shared array and startup structure - also holds pthread_t, array mutex, and startup semaphore - initialize every array element to zero - main remains alive, so these local objects outlive the workers' use of them 18 initialize startup structure once: - randseed = time(NULL) - array = the_array - arr_mutex and data_sem point to main's synchronization objects - sem_init(&tsd_sem, 0, 0): thread-shared, initially zero 19 worker creation loop: - increment tsdata.randseed - pthread_create(..., worker_thread, &tsdata) - when protection is enabled, sem_wait(&tsd_sem) before the next iteration - check creation success before waiting; otherwise a failed creation leaves no poster - real code must also handle interrupted waits and other synchronization errors 20 printing loop must observe one consistent state - lock arr_mutex - compute sum across all elements - print sum and those same element values - unlock mutex, then sleep(PAUSE_LENGTH) - locking only the summation would allow printed elements to belong to another state - an alternative design copies a snapshot under the lock and prints afterward 21 main also ends with an unreachable return 0 after its infinite loop - demonstration has no normal join / shutdown path - a finite application needs explicit worker termination and object cleanup 22 book supplies the complete example as balance.c - protected build: gcc -Wall -g balance.c -lpthread -o balance - unprotected build adds -DPROTECTION=0 and names output bal_noprot - conditional compilation removes both mutex protection and startup signaling 23 sample output shows zero totals with protection and drifting totals without it - total is printed first, followed by the array in parentheses - printed values and rates of corruption depend on execution order - observed failures illustrate the race; an apparently correct run cannot disprove it 24 older producer-consumer demonstration was corrected after errors were found - corrected example remains available as prod_cons.c in the book's examples 25 conclusion: hidden shared state can appear inside called library functions - global or static variables may be accessed by several calling threads - synchronization requirements must cover those objects too - concurrency bugs may remain invisible through ordinary testing 26 author favors threads only when independent computation gives a measured multicore benefit - also prefers process isolation where practical - treat this as the author's design position; evaluate the actual task's concurrency needs 7.4 Shared data on disk 1 shared disk data can be unavoidable even when shared memory is avoided - independent programs may need the same persistent information - author recommends avoiding concurrent file access where practical - otherwise choose a locking protocol understood by every participant 7.4.1 Available file-locking mechanisms 1 file lock: a way to tell other processes that a file is in use - intended to prevent conflicting access during a critical section - acquiring a lock and blocking while waiting for one are different concepts 2 the book distinguishes the English word lock from blocking - informal Russian transliterations are common in conversation - an explicit term is needed for the written discussion 3 the author uses the Russian term meaning acquisition / capture for a lock - in these English notes, the term remains file lock 4 ordinary Unix file locks are advisory: - do not themselves prohibit ordinary reads and writes - a process with sufficient file permissions can ignore the locking protocol 5 all participants must cooperate: - acquire the appropriate lock before accessing protected data - a program unaware of the protocol can invalidate its guarantees - a user may unknowingly run such a program against the shared file 6 mandatory locking would enforce restrictions on ordinary I/O too - book describes historical Linux mount options and special mode bits - that mechanism was uncommon and problematic - the following discussion uses advisory locking 7 three approaches considered: - lock file: existence of an additional file indicates ownership - BSD locks: flock - traditional POSIX record locks: fcntl, also exposed through lockf - kernel-mediated requests reject or wait for conflicting locks 8 network filesystems add another layer of semantics: - locking depends on the filesystem, protocol, client, and server - do not assume local-filesystem behavior carries over unchanged - document the environments the program's protocol supports - the book's blanket warning about network locks is not a universal rule 9 author suggests configurable support for several locking mechanisms - participants must agree on which mechanisms and conventions to use - combining mechanisms also requires a consistent acquisition order 7.4.2 Creating a separate lock file 1 lock-file protocol for foobar.dat: - attempt open("foobar.dat.lock", O_WRONLY|O_CREAT|O_EXCL, 0666) - success: close the descriptor; existence of the file retains the lock - -1 with EEXIST: another participant owns the lock; wait and retry - another error: handle it as an actual failure, not as lock contention - work on foobar.dat only after acquisition - unlink("foobar.dat.lock") when finished 2 analogy with a mutex: - atomically creating the lock file = acquire - removing it = release - checking for absence and then creating in separate operations is unsafe - older network implementations did not always provide atomic O_EXCL - correctness depends on the actual filesystem's guarantees 3 alternative when exclusive creation cannot be relied on: - create a uniquely named temporary file on the same filesystem - use link to create the agreed lock pathname pointing to that file - ownership is indicated by the hard link, not the temporary name alone - source suggests including process identity / time in the unique name 4 network errors can make the outcome of link ambiguous: - server may create the link but its success reply may be lost - after an error, stat the unique temporary file - st_nlink == 2 indicates that the second name was created 5 release by removing the agreed hard-link pathname - temporary file can be retained for reuse - remove the temporary file when it is no longer needed 6 advantages of this approach: - simple filesystem operations, without a special file-locking API - can work across some network filesystems with an appropriate protocol - still has coordination and failure-recovery costs 7 all participating programs must agree on the lock pathname: - same program / development team can establish a convention easily - independently written programs may use incompatible names - some use the data directory, others a directory such as /var/lock 8 crash can leave a stale lock file: - other participants then wait for an owner that no longer exists - timeout alone cannot prove that an owner has died; it may just be slow - storing owner identity can support liveness checks, with suitable care - sometimes recovery must be handled explicitly by the user / administrator 7.4.3 BSD locks with flock 1 flock(fd, operation) works on an already open file: - LOCK_SH: shared lock; compatible with other shared locks - LOCK_EX: exclusive lock; conflicts with shared and exclusive locks - LOCK_UN: release the lock 2 conflicting acquisition normally blocks until it can succeed - add LOCK_NB to request an immediate result instead - LOCK_SH|LOCK_NB or LOCK_EX|LOCK_NB - unlock does not need a nonblocking flag 3 shared / exclusive locks implement readers-and-writers exclusion: - readers may hold shared locks concurrently - a writer needs an exclusive lock - while a writer holds it, other cooperating readers and writers wait 4 exclusion alone does not guarantee fairness: - repeated overlapping readers can starve a writer - do not assume the API gives priority to a waiting writer - demonstration repeatedly locks, sleeps, unlocks, and sleeps again 5 build two versions of the demonstration: - -D SHARED selects LOCK_SH -> flock_sh - otherwise use LOCK_EX -> flock_ex - both versions operate on the pathname passed as an argument 6 demonstration timing: - hold lock for 1.9 seconds, release for 0.1 seconds, repeat - shared-lock processes can overlap - one reader and one writer can alternate - staggered readers may leave no interval in which all shared locks are free -> writer waits indefinitely under the illustrated scheduling behavior 7 use an extra admission lock to prevent new readers bypassing a waiting writer: - use another file as the gate - reader takes gate exclusively, acquires the data-file shared lock, then releases the gate - writer takes gate, waits for the data-file exclusive lock, and retains the gate through its operation - every participant must follow the same lock ordering 8 flock can convert between shared and exclusive modes - conversion is not guaranteed atomic - old lock may be released before new lock is acquired - another participant can intervene or the conversion can block -> finish the logical critical section before changing lock type 9 BSD-style flock locks belong to the open file description: - fork / dup / dup2 / F_DUPFD create references to the same kernel object - those references therefore share the same lock - opening the pathname again creates an independent open description 10 consequences of open-description ownership: - child unlocking an inherited descriptor also removes the parent's lock - opening the file again and acquiring a conflicting lock can deadlock against a lock already held through the first open description - library code can accidentally create this second-open situation 11 locks can survive exec through inherited descriptors - new program may not know it inherited a locked open description - unrelated participants can remain blocked unexpectedly - descriptor lifetime and close-on-exec settings therefore matter 12 last close releases an open-description lock - crash closes the process's descriptors automatically - inherited / duplicated references elsewhere may still keep the lock alive - unlike a lock file, no separate stale pathname needs removal - network-filesystem behavior must be checked for the actual environment 7.4.4 POSIX record locks 1 traditional POSIX locks can cover part of a file - flock covers the whole file - record locks describe a byte range 2 traditional POSIX lock ownership is process + file: - different descriptors for the same file access that process's locks - this includes descriptors obtained by separate open calls - fork does not give the child ownership of the parent's record locks - distinct from the open-description ownership used by flock 3 interfaces: - fcntl with F_SETLK, F_SETLKW, F_GETLK - lockf(fd, cmd, len), commonly implemented through fcntl - fcntl supports read and write locks - lockf provides exclusive locking only 4 lockf parameters: - fd: file opened with write access - F_LOCK: acquire, waiting if necessary - F_TLOCK: try to acquire without waiting - F_UNLOCK: release - F_TEST: query whether a conflicting lock prevents acquisition - len: range length from the current file position - negative length selects the range preceding that position 5 lockf result: - 0: success - -1: failure - with F_TEST, success means no conflicting lock was found at that moment - a successful test does not reserve the range 6 fcntl record-lock commands receive a struct flock pointer: - fcntl(fd, F_SETLKW, &lock) - struct flock is a data type, separate from the flock function 7 struct flock fields: - l_type: F_RDLCK, F_WRLCK, or F_UNLCK - l_whence: SEEK_SET, SEEK_CUR, or SEEK_END - l_start: starting offset relative to l_whence - l_len: range length; negative selects preceding bytes - l_len = 0: extend from the start through EOF, including later growth - l_pid: owner information returned by F_GETLK 8 F_GETLK queries a proposed lock: - first describe the desired range and lock type - no conflict -> l_type becomes F_UNLCK - conflict -> structure describes a conflicting lock and its owner's pid - query does not acquire the lock 9 F_SETLK and F_SETLKW acquire, change, or release a lock: - fill l_type, l_whence, l_start, and l_len - F_SETLK returns immediately if another lock prevents acquisition - F_SETLKW waits for the conflict to clear; W means wait - handle errors and interruption in either case 10 partial unlock can split an existing range: - lock 1000 bytes starting at 500 -> [500, 1500) - unlock 100 bytes starting at 700 -> [700, 800) - remaining locks: [500, 700) and [800, 1500) - overlapping changes can also merge ranges or alter their lock types 11 POSIX record locking can be supported by network filesystems - depends on protocol and kernel support - do not infer universal guarantees from the name of a locking API alone 7.4.5 File-locking pitfalls 1 closing any descriptor for a file releases that process's traditional POSIX record locks on the file - even a descriptor obtained by an independent open - library may open and close the file, unexpectedly dropping application locks - another subsystem can also change the process's lock type on an overlap - all threads in the process share this ownership problem 2 read permission can allow interference with cooperating writers: - a shared lock can hold up an exclusive writer indefinitely - with local BSD-style flock, even an exclusive lock can be requested through a read-only descriptor - ability to acquire a lock is different from permission to modify data 3 interaction between locking APIs varies: - lockf commonly uses the same locks as fcntl - native flock and traditional fcntl locks can be independent - another system may connect them or implement flock through fcntl - filesystem and protocol behavior can change these relationships -> cooperating programs must agree on a compatible mechanism 4 author's conclusion: avoid unnecessary shared file access - where sharing is required, account for ownership, descriptor lifetime, fairness, failure recovery, and portability - one successful experiment does not establish those guarantees 8. Inside the kernel 1 what happens inside the kernel 2 it is too difficult to actually write something useful for the kernel 3 it is useful to at least have a high-level understanding of kernel 8.1 Basic principles of OS operation 1 kernel starts earlier than other processes and works in privileged mode; it launches other programs in limited mode kernel mode configures special handlers for: interrupts exceptions syscalls in which cases program continues in kernel mode limited mode can only modify memory allocated to it; everything else requires access to kernel 2 no user code could ever be executed in privileged mode; only kernel code could be executed in privileged mode within a process as a scheduling unit while preserving MMU configuration this happens upon: exceptions syscalls return to process 3 kernel has 2 main purposes: manage processes: launching, stopping scheduling memory management process interactions process permissions manage devices abstractions coordination 4 kernel does not have to be monolithic some parts could be processes only in user mode in kernel mode 8.1.1 The kernel as a request handler 1 after launching, kernel does not do anything "from it's own will"; it only responds to user requests if there are no user tasks it can become idle if there are no tasks in the system it can even turn off 2 userspace tasks often need something from kernel; in this case kernel responds to requests same for interrupts that might not happen immediately but kernel still responds to actions here not initiates them 3 in all of these cases interrupts exceptions syscalls control passes over to kernel code in privileged mode via predefined addresses of procedures-handlers 4 during exceptions and syscalls the process continues in privileged mode as process from scheduler's perspective 5 interrupt happen asynchronously, so there might not even be another process 6 interrupt handlers have limited capability of blocking other interrupts until the information about the original interrupt is saved properly and the interrupts are unblocked 7 sometimes there is no need for unblocking because the interrupt handler finishes extremely fast i.e. timer interrupts without scheduler and the unblocking happens automatically when the process continues 8 it gets more complicated in case interrupt handler does not finish that fast 9 because of multicore processors and no ability of being blocked (interrupt handlers are not scheduling units) we need to use active waiting to handle critical sections 10 kernel implements more than 10 techniques for mutual exclusions. programmer should not use mutexes designed for interrupts in processes and vice verse. 11 sometimes as result of interrupt, we need to switch process kernel saves context of the current process, then restores context of another process 12 sometimes interrupt handlers are complex enough that need to be executed as scheduling unit, but could not be related to the context of any of the processes 13 top half: interrupt handler executed during interrupt block bottom half: longer processes 14 bottom half: tasklets and workqueues tasklets: no interrupt blocking, not scheduling unit, on the same processor, executed immediately or on the next time interval workqueue: scheduling unit with pid, can be delayed more than tasklet 15 init process with id 1 is being executed during the whole lifecycle of operating system. it becomes parent for orphan child processes 16 init is the last stage of operating system launching 17 when init process is stopped the whole system stops 8.1.2 Booting and the Unix lifecycle 1 ROM (read-only memory) is similar to RAM but its data can only be read and the data is not erased upon power off. It is used to boot system. 2 ROM was built as PROM (programmable ... ) -> EPROM (erasable ... ) -> EEPROM (electrically ... ) 3 system boots from a program stored in ROM (address 0xFFFFFFF0 on i386 in real 16-bit mode no memory protection and [non-]privilege modes,; it is switched into protected mode later by kernel (in the case of BIOS) by advanced loader (UEFI)) 4 BIOS (basic input-output system) UEFI (unified extensible firmware interface) ROW saves configuration of how to load BIOS or UEFI program in ROM determines the boot device BIOS: passes control to boot sector UEFI: finds special sector with particular executable and loads it, it can also boot in the same way as BIOS 5 BIOS: boot sector is only 512 bytes, thus its purpose is to load more complicated program (bootloader of operating system) UEFI: directly loads bootloader 6 bootloader boots the kernel, which: loads its subsystems including drivers mounts root file system in read-only mode launches process 0, which forks process 1 and terminates process 1 launches init with execve 7 init: checking disks remounts root file system with read/write and mount other file systems launching other OS subsystems including: network interfaces launches system daemons launches getty, which: creates a session performs login launches command line interpreter 8 because init is quite complicated, most functionality is performed via scripts: /etc 9 restart or poweroff is also performed through init via scripts: SIGTERM SIGKILL unmount all file systems apart from the root one sync buffers remount root as read-only 8.1.3 Emulating a physical computer 1 we can emulate a computer by running guest code in a restricted mode, intercepting privileged instructions and protected memory, and simulating their effects. 2 hypervisor (Xen, KVM (Kernel Virtual Machine) for Linux) can load operating systems as its processes, or; it can be part of a host operating system that loads its guest operating systems 3 trap and emulate technique did not work originally on i386: POPF behaved differently in privileged and limited modes and did not raise exceptions i386 could understand that it is in limited mode from segment registers 4 MMU configuration is done by modifying memory in privileged mode, but when emulated system tries to do that it just modified its process memory. That can be fixed my slightly modifying machine code of the guest kernel 5 In 2006 both amd and intel added support for virtualization at hardware level. 6 systems can also be emulated via interpretation (DOSBox, Atari, Commodore-64) of machine code, this way no need from the operating system, but it is much slower 7 WINE is something in between virtualization and interpretation, calls to WinAPI is replaced by function that refer to UNIX syscalls Executing .exe in WINE is achieved via modification of binary code 8 QEMU uses both virtualization and interpretation so that it can emulate different platforms and get speed benefits when possible 9 Paravirtualization is achieved by modifying the kernel of guest operating systems or installing special drivers to efficiently interact with hypervisor on the host operating system 10 Containers (OpenVZ, LXC) work inside host operating system without its own kernel. Host operating system can see process inside containers and its file tree, but the containers cannot see host processes and file tree. 11 VPS can be created with virtualization or containers. Containers improve efficiency of resource usage, because they don't need separate kernel. 8.1.4 Kernel structure and main subsystems 1 Kernel is designed as separate layers distinguished by proximity to hardware. The further away from the hardware, the higher the abstraction. 2 The lowest layer includes: drivers interrupt handler others hardware-specific components Some part of it is usually written in assembly. 3 Memory subsystem consists of: hardware layer interacting with MMU of particular CPU tracking, allocation and freeing of physical memory frames abstraction of physical memory allocation for kernel and processes disk storage mapping (mmap) Both virtual memory management and virtual file systems need other lower-level systems: virtual memory needs swapping virtual file systems needs disks, sometimes networking 4 Storage: disk controllers and interrupt handlers abstraction of block device, planning of disk operations virtual file system and swapping subsystem Virtual file system also needs implementation of actual file systems 5 Networking: network card drivers and interrupt handlers abstraction of network interface implementations of network protocols family of protocols sockets Scheduler: programming of interrupt handlers and interrupt handlers themselves including timer scheduler of kernel threads blocking of critical sections including mutexes userspace threads management of processes: fork, execve, wait, _exit 6 Main kernel subsystems: hardware level including drivers and interrupt handlers process management and scheduler memory storage networking 8.2 Process management 8.2.1 A process as a kernel object 1 From a programmer perspective a process is: program code global data including heap and stack 2 From a kernel perspective a process is: allocated memory permissions table with file descriptors registers (execution context) when process is not being executed 3 To start a process (or replace with execve), an operating system has to allocate enough memory for: code, data, stack initialize code and data create execution context with initial values in registers _start address in instruction pointer initial value of stack pointer command line arguments and pointer to them other important registers 4 For each new process kernel has to: allocate and initialize memory configure MMU Then the process is ready to be executed and is included in the schedule Finally the scheduler decides when the process starts 5 Process can have 3 states: execution blocked ready The transition between states could look like: execution <-(scheduler)-> ready execution -(syscall)-> blocked execution -(swapping)-> blocked blocked -(interrupt handler)-> ready 6 Process is executed in kernel mode: on syscall on exceptions before returning back to user mode 7 Process can change state from execution to read without syscall, but vice verse is not true 8 If a process is blocked waiting for a syscall, required memory pages will not be swapped back in before the process becomes unblocked by the original syscall 9 Threads work in parallel within a process with the same shared memory From the scheduler perspective though, threads are almost like individual processes each with its own execution context 8.2.2 CPU-time scheduling 1 3 levels of scheduling: long-term: decides when to execute a process mid-term: decides what memory to swap out this can block a process short-term: decides which processes shall be paused and resumed The following systems mainly use: Batch OS: mainly long-term scheduling Time-sharing OS: mainly short-term use mid-term scheduling indicates that system is working at its capacity 2 Tasks could be bound by: CPU I/O Good short-term scheduler should prioritize I/O bound tasks This will increase responsiveness of a system. Good long-term scheduler should have a balanced mix of CPU- and I/O-bound tasks. 3 Primitive short-term schedules without priorities include: round-robin: cycles through ready each task and start the ready ones with equal time slices FIFO: ready tasks are in line, the first one gets executed first and then is placed last blocked tasks could be places first or last 4 Task priority is determined from static: defined by user dynamic: increases while task is waiting from 0 to max when task is finally executed dynamic priority is 0 and priority of all other tasks increases by 1 Scheduler selects a task with the highest static+dynamic priority but it has to be extremely efficient because it is executed ~1000 times per second within a critical section without block with blocked interrupts 5 we can set scheduling policy for a process using sched_setscheduler: SCHED_OTHER: default SCHED_RR and SCHED_FIFO: real-time higher priority than SCHED_OTHER you can set static priority no dynamic priority SCHED_BATCH: batch mode, lower priority than SCHED_OTHER SCHED_IDLE: lowest priority, executed only when there are no other processes 6 Modern systems use efficient algorithms such as CFS (Completely Fair Scheduler): performs calculation only when starting, resuming or stopping a task remember how long each process has been executing selects a process with the lowest time 7 Let's assume all processes start at the same time For each process we will have a variable (vruntime) that stores how long (nanoseconds) it has been executing. Since, we assumed all processes started at the same time, initially it is zero. Scheduler selects a process with the lowest vruntime and assigns a time slice based on processes priority (nice value) After the time slice has passed, the processes is replaced with another one with the lowest vruntime, while the current one's vruntime is increased by the time slice 8 Since time-slices are based on priorities there could be processes with vastly different vruntime, so it is important to efficiently find those with the lowest vruntime, for which scheduler uses red-and-black trees. 9 Processes with the lowest vruntime are on the left, after they are selected and replaced they usually move on the right and with this progression every process will be executed at some point. 10 To eliminate our assumption that all programs were started simultaneously we just have to replace 0 in vruntime upon program start with minimum current vruntime. Thus it is not really a time a program has been executing, but some constant + time a program has been executing. 11 For blocking processes if the current time is lower than min vruntime, then min vruntime is assigned, otherwise the current vruntime is being unchanged. 8.2.3 Signal handling 1 Processes do not know when a signal handler could be called, on the contrary to kernel. 2 If a process got a signal, the signal handler gets called when the process switches from kernel to user modes, which happens when process returns from ready state to execution syscall interrupt 3 When switching from kernel to user mode and there is a signal: the kernel modified the stack frame of the process with the signal handler at the top with return address of machine code that just calls sigreturn, which: restores original state of the stack restores signal masks other cleanups 4 It just modifies instruction pointer to point to the address of signal handler, which when done eventually returns to sigreturn. Kernel then again checks for new signals when returns from sigreturn. 5 Signal arrival is noticed by raising the relevant flag, which is reset to zero upon calling signal handler. However, if the flag is already raised, all the arrived signals will be ignored until the flag is reset (returning from kernel to userspace). 6 This also explains why blocking syscalls are interrupted by signals: to handle a signal we have to return from kernel to userspace, thus interrupting the blocking syscall 7 c int setjmp(jmp_buf env); void longjmp(jmp_buf env, int val); setjmp: macro that saves EIP and ESP; returns 0 jmp_buf: array; that is why there is no need for the address-of operator env: is valid until returning from the function where it has been called, thus we can use it in longjmp from any subfunction longjmp: uses env saved in setjmp and some non-zero number in val to return to the location of setjmp while returning val. It restores EIP and ESP, but modifications to global variables and other side effects are not undone. 8 the functions are implements by: setjmp: 0 -> EAX ESP and EIP -> env longjmp: val -> EAX ESP and EIP <- env returns from setjmp with val in EAX instead of 0 9 for long jumps from inside the signal handler, there are similar functions: int sigsetjmp(sigjmp_buf env, int savesigs); int siglongjmp(sigjmp_buf env, int val); savesigs: non-zero value saves current signal mask then siglongjmp with restore signal mask before jumping siglongjmp: no call to sigreturn in this case 10 readline library specifies that we can use siglongjmp to process Ctrl-C (jumping out of the library functions) 8.3 Memory management 1 UNIX kernel has memory management subsystem to manage memory of multiple processes in a system. Hardware running multitasking OS should have memory protection. Usually CPU has MMU (memory management unit) so that programs can work with virtual addresses instead of the physical ones. Memory protection and configuration of MMU is kernel's job. 8.3.1 Problems handled by the memory manager 1 memory protection: process-process, kernel-process not enough memory: swapping, can slow down processes data duplication: starting copies of the same program code portability: hard-coded absolute physical memory addresses can create problems when that specific physical memory is taken, that is why we need MMU fragmentation: there could be enough memory for a new process but it is spread out through different areas within RAM, also running task might need more memory, but the adjacent memory is already taken by another process 2 Most of these problems appear only in multitasking operating systems: there is only 1 process: memory protection, data duplication we can use the same physical memory: code portability, fragmentation not enough memory: we can use overlays, load into memory only parts of program we need at the moment 8.3.2 Virtual memory and swapping 1 MMU is not required, but it: solves code portability when flexible enough simplifies: data duplication fragmentation protection Kernel configures MMU for each process You can even transfer part of a process into a different physical memory while modifying MMU Without MMU we can only swap out an entire process 2 Some virtual pages may not correspond to physical ones Access to such pages causes an exception initiated by MMU Kernel handles it depending on the situation: process never had such memory -> error: SIGSEGV, segmentation fault write access next to stack in stack-growing direction -> increase stack swapped-out memory: block process swap it back in resume process 8.3.3 A simple virtual-memory model 1 CPU uses 2 registers: base limit for every memory access: physical address = virtual address + base if virtual address > limit: exception 2 base: start of process memory in physical RAM -> virtual memory addresses limit: size of memory available to the process -> process can only access its own memory area memory protection 3 process can be moved to another part of physical memory copy its data to the new location change base virtual addresses stay the same portability switching to another task: interrupt / exception / syscall kernel gets control changes base / limit restores EIP and other process state new task continues in user mode 4 limitations: not enough physical memory whole process may have to be swapped the problem of single task exceeds memory size is not solved fragmentation expensive copying of large segments duplication 8.3.4 Segmented memory 1 several segments placed independently in physical memory -> (base, limit) pairs 2 address must specify: segment offset inside that segment x86 uses segment registers: CS, DS, ES, SS, FS, GS 3 segment descriptor contains information about a segment: base limit attributes address translation: segment selector -> find segment descriptor -> get segment base physical address = segment base + offset if offset > segment limit: exception 4 duplication common segments for different tasks not significant implication: +/- swapping: individual segments can be swapped separately +/- fragmentation: segments do not have to be next to each other -> easier to use fragmented free memory 5 in flat model if a large data structure grows -> the whole data structure next to it has to be moved this is solved in segment model 6 caching of segment descriptors to avoid excessive memory access saved in "hidden part of" CS, DS, ES, SS, FS, GS 8.3.5 Paged memory 1 each process has: virtual address space tables for translation into physical addresses 2 frame: block in physical memory page : block in virtual memory page size = frame size lowest 12 bits in address are offset within page/frame highest are page/frame numbers 3 virtual pages can be placed in any free physical frames: -> do not have to be next to each other each process has its own translation table virtual page number -> page table -> physical frame and attributes, one of which says if the virtual page has corresponding physical frame in memory at the moment 4 page size selection: large pages: more unused space inside partially used pages small pages: more pages -> larger page tables 4 KB (2^12) is the most popular 2^20 > 10^6 number of pages with each row 4 bytes -> 4MB of page table for EVERY process this problem is solved via multilevel (2-3) pages: 2 10-bit groups specify location in tables of respective layers 5 fragmentation: any free physical frame can hold a page of any process limited physical memory capacity: individual pages can be swapped a process can use more virtual memory than available physical RAM limit: size of virtual address space available disk / swap space 6 drawbacks: unused space can remain in the last page / frame every memory access requires: access page directory access page table access actual memory = 2 additional memory accesses for address translation solved by TLB (Translation Lookaside Buffer) TLB: caches recently used translations: virtual page number -> physical frame number + attributes uses associative / parallel lookup 7 if translation is not found in TLB: get it from page tables cache it in TLB if TLB has no free entry: -> replace / erase one existing entry TLB usually contains from tens to thousands of entries -> enough to greatly reduce page-table accesses 8 when switching tasks: address space changes TLB entries from previous task may no longer be valid TLB is flushed / replaced 9 software-managed TLB: OS takes care of page-table data structures (vs CPU) flexibility TLB miss causes an exception OS handles the miss and updates the TLB TLB miss is more expensive 8.3.6 Segmented and paged memory 1 segmentation: multidimensional address space segment-paging model: double address conversion: segment part of address via segment descriptor -> flat virtual flat virtual address via page table -> physical frame / address each process has its own paged virtual address space segments can be organized inside it 2 disadvantages: tied to i386 / x86 architecture complicated not portable to other CPUs on i386, segmentation is usually flat: segment base = 0 segment limit = full address space segment registers do not need to be changed 8.4 Hardware management and input/output 8.4.1 Two views of input/output 1 hardware perspective: CPU + RAM are treated as one unit I/O = exchange of information between: CPU + RAM <-> external devices CPU <-> RAM communication is not considered I/O 2 the same program may or may not cause hardware I/O: ./hello > file1 output is written to disk hardware I/O occurs ./hello | ./prog2 output of hello is passed to prog2 interaction may stay entirely in CPU + RAM no hardware I/O 3 programmer's perspective: I/O = exchange of information through I/O streams typically using: read / write actual access to an external device is not required 4 not every exchange of information with a process is considered I/O: signals, shared memory are traditionally not considered I/O 8.4.2 OS interaction with hardware 1 CPU communicates with external devices through controllers: CPU <-> bus <-> controller <-> device controllers provide a uniform bus interface: hide device-specific details from CPU from CPU's perspective, devices differ only by port addresses devices created after the CPU can still be connected provided their controllers are compatible with the bus 2 controller has two sides: CPU side: connects to the common bus exchanges numerical values with CPU device side: connects directly to the device it was designed for generates the electrical signals needed to control it driver: software executed by CPU specifies how to interact with a particular controller CPU does not need built-in knowledge of each device 3 many controllers can be connected to the bus at once CPU needs to identify which controller to communicate with I/O ports: each port has an address representable on the bus each controller has one or more ports ports can be read-only, write-only or both 4 I/O ports resemble memory locations: CPU accesses them through read / write operations on some architectures, they share RAM's physical address space then the same instructions can access both ports and RAM but their meaning differs from ordinary memory access: write: can send a command specifying what the device should do read: can return information about the device's current state reading a port need not return the value previously written 5 some controllers also have I/O buffers: RAM built into the controller used to exchange blocks of data between CPU and controller writing to disk: copy data into the controller's buffer send a write command through an I/O port controller writes the buffered data to disk reading from disk: controller places data from disk into its buffer copy data from the buffer into main RAM video memory (VRAM): another example of an I/O buffer stores the image shown on the display 6 separate address spaces: I/O ports have their own address space, separate from RAM port addresses usually use fewer bits than memory addresses separate CPU instructions, for example: IN / OUT for I/O ports MOV for memory 7 shared address space: I/O ports share the same physical address space as RAM ordinary memory-access instructions for both, e.g. MOV example: PDP-11 advantages: I/O regions can be mapped into a process's virtual address space direct device access without a syscall for every operation makes it easier to implement drivers in userspace drivers can use high-level languages supporting pointers no assembly inserts needed for port access disadvantages: I/O ports occupy part of the limited memory address space address regions for ports / buffers must be explicitly excluded from caching using one common bus for RAM and controllers can be difficult their optimal data-bus widths can differ using two separate buses with one shared address space requires a decision about which bus handles each address 8 combined approach: i386 example: I/O ports are in a separate address space I/O buffers share the physical address space with RAM 8.4.3 Drivers 1 driver: software component for controlling a hardware device provides abstraction provides operations that allow device control without knowing hardware-specific details 2 driver is usually a collection of functions, not a standalone program mainly called by other parts of the kernel resembles a library in structure kernel is the program that works with hardware devices via drivers drivers usually become part of the kernel when loaded 3 device-specific details are hidden inside the driver other kernel subsystems call its operations / entry points: externally accessible driver functions same interface for drivers of the same category example: HDD and USB flash drive request from the rest of the kernel can look the same actual hardware operations can be completely different -> abstraction 4 drivers usually run in kernel mode privileged operations may be needed to access device controllers user-space alternative: driver runs as a regular process requests hardware access through syscalls kernel performs required operations and returns results extra context switches reduce efficiency 5 3 ways drivers can be included / loaded: built-in driver: compiled directly into kernel adding / removing it requires kernel rebuild + reboot requires kernel source code or object modules + corresponding interface files traditional Unix approach module loaded at boot: driver is stored as a separate kernel module system configuration determines which modules are loaded kernel loads them during boot no kernel rebuild required traditionally used by Windows / MS-DOS loadable kernel module (LKM): can be loaded into an already running kernel no reboot required module file must follow required kernel conventions loaded through kernel module-loading mechanism becomes part of kernel unused modules can usually be unloaded flexibility Drawback: security risk privileged user can load arbitrary kernel code 6 driver interface: set of operations / entry points provided by driver drivers for different devices can implement the same interface -> abstraction kernel calls these operations through function pointers driver usually registers an operations structure: sometimes an array of function pointers usually structure containing function pointers 7 one interface cannot cover all device types OS supports several device classes: each class defines a fixed set of operations corresponding drivers must implement those operations 8 virtual devices: implement the required device interface no corresponding physical hardware functionality is implemented in software example: RAM disk driver allocates RAM emulates disk sectors in this RAM write: copies data into RAM read: copies data from RAM can be read, written, formatted and mounted like a real disk 9 logical devices: abstraction layer built on top of physical devices and their drivers represent underlying devices in a different logical form example: disk partitions one physical disk can be divided into several partitions each partition appears as a separate logical block device physical disk itself remains the same 10 RAID (Redundant Array of Independent Disks): one logical block device can be built on top of multiple physical disks loop device: ordinary file presented as a logical block device useful for accessing files inside a disk image no need to write image to CD / DVD / USB drive 11 all devices accessible to user programs through syscalls are logical devices even when logical representation matches physical device almost exactly 12 "driver" can refer to: driver controlling a physical device kernel component implementing a logical device both provide operations called by other kernel subsystems set of operations = driver interface classic Unix device types: character devices block devices each type has a different driver interface: fixed set of operations required for that type drivers of the same type implement the same interface Linux also supports network interfaces: not represented as ordinary device files use a different driver interface 13 FreeBSD: no separate block-device category block-device writes may be buffered in kernel memory data may remain there before reaching physical disk program does not directly control when buffered data reaches disk some character-device drivers support lseek positioning is possible without a separate block-device interface Linux: O_DIRECT can bypass the page cache 14 Virtual File System (VFS): allows mounting filesystems without an underlying device physical virtual logical filesystem implementation: fixed set of operations similar to driver entry points ordinary filesystems implement them using data structures on disk the same interface can be implemented in other ways 15 physical and virtual devices occupy the same architectural level virtual devices imitate physical devices logical devices / abstractions can be built on top of either 16 pseudo-devices: /dev/null, /dev/zero, /dev/full, /dev/random character devices no corresponding physical hardware could be called logical (more appropriate) / virtual devices 8.4.4 Input/output at different bus levels 1 Computing system: computer + all programs running on it. Each layer translates requests into terms of the next lower layer: text user | prog > f1.txt program | printf("Hello, world"); system library syscall interface | write(1, "Hello, world", 12); virtual file system (OS) | sde1, sector 127563 logical-device level (OS) | SCSI/5:1:0, cylinder 125, head 8, sector 20 physical-device driver (OS) | control codes hardware / controller Moving toward the user: more abstraction, simpler descriptions. VFS handles write using the open-file object referenced by the descriptor. 2 disk geometry visible to OS can differ from physical geometry physical geometry: inner tracks contain fewer sectors than outer tracks keeps recording density approximately constant OS-visible / virtual geometry: fixed numbers of heads, cylinders and sectors per track controller translates between virtual and physical geometry hardware itself can contain several abstraction layers 3 controller connected to the computer bus may communicate with the disk through another hardware interface / bus: another controller (SATA) can be located directly on the disk connection: computer bus <-> host-side controller <-> disk interface / bus 8.4.5 The role of hardware interrupts 1 after driver starts an I/O operation by writing to controller ports: operation takes some time 2 ways to wait: active waiting: driver repeatedly reads controller port / status CPU does no useful work until operation finishes interrupt-driven I/O: driver sets up / uses an interrupt handler and returns requesting process can be blocked CPU runs another process or becomes idle when device finishes -> controller sends interrupt request interrupt handler gives control back to driver driver completes operation / gets results waiting process may change: blocked -> ready active waiting can be better when response is extremely fast polling can cost less CPU time than setting up and processing an interrupt e.g. checking whether a network cable is connected 2 I/O organization levels: text user software | device-independent OS components (OS) | physical-device drivers (OS) | interrupt handlers (OS) | hardware Physical-device driver: directly starts operations through I/O ports and reads results from the controller. Interrupt handlers: Not really a completely independent layer. Tell the driver when operation results are ready. Can also report that a device became available, allowing the next operation to start. 8.4.6 Input/output buffering 1 several processes may request I/O on the same device process A starts a disk write and becomes blocked CPU runs process B B requests a write to the same disk controller is still processing A's request -> B's operation cannot start immediately simple approach: block B until controller becomes available then start B's operation 2 processing requests in arrival order can cause unnecessary head movement A: write to last cylinders B: write to first cylinders C: write to last cylinders head movement: last cylinders -> first cylinders -> last cylinders repeated back-and-forth movement reduces performance 3 processing C before B could reduce head movement waking C before B would require CPU scheduler to know how to optimize requests for this device device-specific knowledge should remain inside drivers -> CPU scheduler should not depend on these details 4 reading directly into process memory can create a circular dependency: process A is blocked waiting for a disk read requested data becomes available in controller buffer destination pages in A's memory may be swapped out swap area may be on the same disk problem: to empty controller buffer into A's memory, its pages must be loaded to load those pages, the same controller must first become available -> circular dependency solution: copy data into a kernel I/O buffer temporary storage in main RAM separate from the controller's own buffer 5 buffered output: upper kernel layer copies data into a buffer driver retrieves it later and writes it to disk driver determines the order of physical writes buffers for adjacent disk regions can be processed together regardless of request arrival order 6 buffering can reduce the number of physical I/O operations example: process A requests a write -> data stored in buffer process B reads the same data -> supplied from buffer no physical disk read needed B modifies the data and requests a write -> same buffer updated if A's data has not yet been written to disk: driver writes only the latest version -> one physical write instead of two fewer physical operations improved performance, especially for frequent updates to filesystem metadata / global filesystem parameters 7 I/O buffering for character devices: input: accumulates incoming data before passing it to process delivers accumulated data in one syscall fewer syscalls than reading many small portions separately retains data when process is not ready to read or its memory is swapped out output: process can continue without waiting for physical output 8 kernel I/O buffers: stored in kernel memory that cannot be swapped out consume physical RAM -> total buffer capacity is limited disk buffers: can be discarded to free up memory cannot be discarded while holding data not yet written to disk when output buffers are full: write may block until buffered data is written and buffer space becomes available input buffer overflow: incoming data accumulates faster than process reads it data may be lost connection may be interrupted 9 I/O buffer management: traditionally handled by logical-device drivers character-device buffers are usually still managed this way Linux page cache: originally used to track physical pages and their use by processes tracks file-backed pages mapped through mmap changes to these pages must eventually be written to disk combines physical-memory management, disk I/O buffering and swapping uses free physical pages to cache disk data releases cached pages when memory is needed elsewhere -> disk-buffer capacity changes dynamically FreeBSD: file I/O buffering is handled by VFS 10 output modes: synchronous: process waits until the physical write finishes write errors can be reported before returning to the process more reliable asynchronous: process continues after data is copied into a kernel buffer physical write happens later more efficient: process does not wait for physical output process may finish before a write error becomes known Unix filesystems: synchronous / asynchronous operation can be selected through mount options shutdown: buffered data must be written before power is switched off unexpected power loss can cause data loss / filesystem corruption logical damage, even if physical hardware remains intact forced synchronization: requests that buffered data be written to disk fsync / fdatasync / sync msync for memory mappings created with mmap hardware limitation: disk controller may have its own cache outside software control synchronization cannot provide an unconditional guarantee that data has physically reached the disk 8.4.7 Disk-I/O scheduling 1 system needs disk I/O when: a user process requests a read / write a process accesses a page that must be brought back from swap if controller is available: operation can start immediately if controller is busy: request is placed in a queue several requests may accumulate before controller becomes available 2 simplest strategy: FIFO / FCFS (First Come, First Served) process requests in arrival order USB flash drives, SSDs, network disks 3 HDD requests can be reordered to reduce head movement consecutive requests in a FIFO queue may target distant disk regions serving a nearby request first can avoid unnecessary backtracking -> improved performance 4 scheduling strategy: rule for selecting the next queued request shortest seek time first (SSTF): select request requiring the least head movement time greedy strategy: choose the best immediate option efficient, but can cause starvation nearby requests keep being selected requests for distant tracks may wait indefinitely elevator algorithm (LOOK): move head in one direction, serving requests along the way reverse direction after the last requested track in that direction repeat in the opposite direction avoids starvation waiting times can vary considerably request just behind the head must wait for its return sequential requests toward higher track numbers can wait longer while head is moving toward lower track numbers circular elevator algorithm: serve requests only from lower to higher track numbers after the highest requested track, return to the beginning start another sweep toward higher track numbers more evenly distributed waiting times the return to the beginning is usually very fast 5 modified scheduling strategies: use greedy strategy (SSTF) for at most N requests then select the next request using the elevator algorithm efficiency close to SSTF, without starvation anticipatory scheduling: pause briefly before a large head movement another request may arrive for the same or next track -> large head movement may be avoided 6 Completely Fair Queuing (CFQ): historical Linux I/O scheduler separates synchronous and asynchronous requests prioritizes synchronous requests, e.g. reads requesting process cannot continue until operation finishes each process receives a time slice for servicing its disk requests other processes' requests wait during that interval 7 disk scheduler works with the virtual geometry presented by controller does not know the actual physical geometry cannot determine exact physical head-movement distances limits how accurately scheduling can optimize physical head movement 8.4.8 Virtual filesystem 1 VFS: kernel subsystem supporting files as abstract objects file operations: open, read, write, close mmap / lseek where supported file properties: owner, group, access permissions timestamps number of hard links inode: stores file metadata, except the filename some file types require no disk storage beyond the inode filenames: stored in directories one file can have several names / hard links Unix file types: regular files directories symbolic links named pipes / FIFOs sockets character-device files block-device files 2 "filesystem" can mean: data structures organizing information on disk software functions that work with those structures Unix systems support different filesystem implementations different on-disk formats common file concepts and operations 3 root filesystem: its root directory corresponds to the system-wide / other filesystems: mounted at existing directories called mount points become part of the common directory tree mount points are usually empty directories existing contents are hidden while another filesystem is mounted there reappear after unmounting common directory tree can contain different filesystem types filesystems from other operating systems: do not use the same inode-based organization as Unix filesystems permissions may be absent or organized differently 4 filesystems without an underlying disk: different from a filesystem placed on a virtual / RAM disk implement file operations without disk data structures tmpfs: stores temporary files in memory no fixed disk size needs to be defined beforehand limited by available virtual memory: physical RAM + swap deleting files releases memory pseudo / synthetic filesystems: expose kernel information through files and directories interface for inspecting / controlling kernel subsystems read: obtain information write: change settings procfs: usually mounted at /proc /proc// contains information about a process: exe: symlink to executable cwd: symlink to current working directory fd: symlinks for open file descriptors cmdline: command-line arguments maps: virtual-memory mappings Linux ps obtains process information from /proc can also expose kernel settings: echo "1" > /proc/sys/net/ipv4/ip_forward -> enables IPv4 packet forwarding sysfs: usually mounted at /sys information about connected devices and loaded kernel modules devfs: mounted at /dev provides device files for devices supported by kernel alternative: tmpfs at /dev, populated by udev device files are created by a user-space daemon devpts: mounted at /dev/pts provides pseudo-terminal device files network filesystems: NFS / smbfs present remote files as part of the local directory tree actual data is stored on another computer 5 Unix filesystem formats share common concepts: inodes superblocks directories other filesystem formats: e.g. vfat, NTFS, smbfs emulate the file abstractions expected by Unix pseudo filesystems: implement these abstractions without corresponding disk structures filesystem module: handles the specifics of its filesystem provides a fixed set of operations / entry points similar to a device driver 6 VFS coordinates filesystem implementations: mounts / unmounts filesystems maintains the common directory tree selects the appropriate filesystem module translates syscalls into calls to filesystem entry points handles file I/O syscalls creates and maintains I/O streams as kernel objects 8.4.9 Filesystem on disk 1 on-disk data structures can differ considerably even between Unix-style filesystems some common principles still apply 2 physical sectors are grouped into filesystem blocks sector size: usually 512 bytes block size: e.g. 4 KB, but can differ depends on filesystem; may be selected during formatting each block has its own number superblock: stores global information about the filesystem copies are stored in different disk locations 3 some blocks are reserved for inode tables filesystem may contain tens to thousands of inode areas each block in these areas contains several inodes inodes are numbered across the whole filesystem block groups, e.g. ext2-ext4: group of filesystem blocks superblock copy inode table free-block bitmap: each bit represents one block in the group 0: free 1: occupied 4 inode (index descriptor): typically 256 bytes; size depends on filesystem stores file metadata, not filename or contents filenames are stored in directories file contents are stored in data blocks inode records the numbers of blocks containing file data block-pointer layout: first entries point directly to data blocks final 3 entries point to indirect blocks: single indirect: contains data-block numbers double indirect: contains single-indirect block numbers triple indirect: contains double-indirect block numbers indirect blocks: store block numbers rather than file contents provide additional levels for locating a file's data blocks 5 example: ext2 with 4 KB (4096-byte) blocks inode contains 15 block pointers: 12 direct pointers 1 single-indirect pointer 1 double-indirect pointer 1 triple-indirect pointer each block number occupies 4 bytes one indirect block holds 4096 / 4 = 1024 block numbers direct blocks only: 12 * 4 KB = 48 KB files up to 48 KB need no indirect blocks with single indirect: 12 + 1024 = 1036 data blocks 1036 * 4 KB = 4144 KB with double indirect: 12 + 1024 + 1024^2 = 1049612 data blocks 1049612 * 4 KB > 4 GB with triple indirect: 12 + 1024 + 1024^2 + 1024^3 data blocks (12 + 1024 + 1024^2 + 1024^3) * 4 KB > 4 TB additional ext2 limit: inode contains a 32-bit number of 512-byte sectors 2^32 * 512 = 2^41 bytes -> file-size limit is about 2 TB 8.4.10 Bus, cache, and DMA 1 signal travel time depends on physical distance CPU chip is small; motherboard bus traces are much longer longer path -> longer signal propagation time bus frequency therefore cannot grow as easily as CPU frequency 2 example: bus length: about 25 cm request + response travel about 0.5 m even at speed of light -> theoretical limit about 600 MHz real bus must also allow time for components to respond -> actual frequency is lower if CPU had to access RAM constantly: much of its time would be spent waiting 3 cache: fast memory placed close to CPU reduces need to access slower RAM through shared bus 80286 could insert wait states while waiting for memory with larger CPU / RAM speed gap, many cycles could be wasted 4 how cache works: physical RAM is divided into equal-size blocks cache stores copies of some RAM blocks each cached block has a tag identifying its RAM block if required block is already cached -> use it if not: load whole block into cache possibly replace an existing block block transfers allow several bytes to be moved efficiently at once 5 cache writes: write-back: modify cache only mark block as dirty write it to RAM when block is removed write-through: update cache and RAM immediately 6 direct-mapped cache: RAM block n maps to cache block: n mod M where M = number of cache blocks if M = 2^k: index = lowest k bits of block number simple and fast disadvantage: different RAM blocks can map to same cache block they may repeatedly replace each other 7 multi-level cache: L1: smallest, fastest, closest to CPU core usually private to each core often separate instruction + data caches L2: larger and slower than L1 usually private to each core usually unified for instructions + data L3: much larger and slower usually shared between cores example: L1: 32 KB instructions + 32 KB data per core L2: 256 KB per core L3: 8 MB shared 8 cache means CPU uses shared bus less often free bus time can be used for transfers between RAM and device controllers without DMA: driver starts I/O device works while CPU can run another task after interrupt, CPU still has to copy data between controller buffer and RAM 9 DMA (Direct Memory Access): lets hardware transfer data between RAM and device without CPU copying every byte was also useful in early computers because CPU could be slower than bus / memory IBM PC: used Intel 8237 DMA controller connected to shared bus had I/O ports for configuring transfers 10 without DMA: RAM -> CPU -> device port MOV: read byte from RAM OUT: write byte to device port increment address decrement counter repeat with DMA: driver gives DMA controller: start RAM address amount of data transfer direction starts operation CPU does not copy every byte itself 11 ISA DMA channels: each channel has 2 control lines: DRQ: DMA request DACK: DMA acknowledgement fly-by mode: device sends DRQ when ready DMA controller responds with DACK DMA controller supplies RAM address + read / write signals actual data moves directly: device port <-> RAM DMA controller: increments RAM address counts remaining data stops when transfer is complete one data portion can be transferred in one bus cycle data does not pass through DMA controller itself 12 PCI changed the DMA model: central DMA controller was replaced by bus arbitration bus arbiter: does not transfer data decides which component may control the bus component currently controlling bus = bus master device controllers can perform DMA themselves example: disk read driver tells disk controller where in RAM to place data disk controller requests bus arbiter grants bus disk controller becomes bus master disk controller writes data directly into RAM 13 DMA and virtual memory: device controllers work with physical addresses virtual contiguous memory can correspond to scattered physical pages simple DMA transfer needs a physically contiguous RAM region example: 1 MB = 256 pages of 4 KB OS may have 256 free pages, but not 256 consecutive physical pages -> cannot use them as one contiguous DMA area physical-memory fragmentation therefore limits DMA OS tries to avoid excessive physical-memory fragmentation ============================================================================== Volume III - Paradigms (progintro_2_92_v3.txt) English study notes for chapters 9-12 ------------------------------------------------------------------------------ 9. Programming paradigms and the programmer's way of thinking 9.1 The word paradigm 1 first two volumes approached programming from the machine upward - Pascal fundamentals, assembly, C, and operating-system services - this volume turns to other ways of understanding programs 2 "high level" historically meant above assembly - book treats C as comparatively low level: representation and machine behavior remain important to the programmer - assembly can supply target-specific operations missing from C - system calls define the OS-service boundary for ordinary processes - C's usefulness here does not make it the only possible systems language 3 Pascal also exposes the stored-program machine model - variables occupy memory; pointers identify memory locations - assignment changes stored state - being above assembly does not remove those assumptions 4 low-level programming uses knowledge of the machine deliberately - improve efficiency or expose capabilities - systems software serves other software and computer operation - application software directly addresses the user's external problem 5 systems software often needs machine-level knowledge - its performance can affect many applications at once - kernel efficiency is an especially broad example 6 application development has additional tradeoffs - development effort and delivery time may outweigh small runtime costs - acceptable performance still depends on the particular application 7 abstraction can shift attention from machine mechanics to the problem - seek a simpler, shorter, or clearer expression of the desired behavior - alternative mental models become possible 8 volume examines paradigms beyond familiar imperative programming - object-oriented approaches - models where variables are not mutable memory cells - programs without assignments or explicit loops 9 several paradigms have already appeared in systems work - recursion: a local way of structuring an algorithm - event-driven execution and explicit states: whole-program organization - parallel programming: multiple interacting control flows - paradigms are not restricted to application programming 10 language features can influence how a programmer frames a problem - even Pascal and C encourage noticeably different habits - systems constraints restrict choices; other tasks may allow more freedom 11 learning several models develops flexibility - a paradigm can improve understanding even if never used directly at work 9.1.1 Terminological difficulties 1 previously introduced styles include imperative, functional, declarative, and object-oriented programming 2 Unix design supplies further examples - "everything is a byte stream" shapes interfaces - "one program, one task" concerns system composition more broadly 3 preferring text is a representation paradigm - inspect, edit, and combine data with general text tools - exceptions include machine code, compressed/encrypted data, and media whose textual encoding would not make it directly understandable 4 an event-driven program has a repeating event loop - obtain an event - perform the corresponding response - organize actions around available events rather than one dialogue 5 parallel execution and shared-data programming are distinct ideas - parallel processes can communicate by messages instead of shared memory - independent applications can share persistent files - either technique introduces its own reasoning requirements 6 recursion is another paradigm, at a different scale - examples suggest different ways of thinking about the same problem - the term needs more explanation than a list of programming techniques 7 authors disagree on what belongs in the category - Floyd includes structured programming; some other accounts do not - definitions vary and can presuppose the understanding they should explain 8 ask why the term is needed and what recognizing it helps us do - historical purpose can clarify an otherwise vague definition 9.1.2 Paradigms outside programming 1 Greek origin suggests example/model - Kuhn used the term for established frameworks of scientific inquiry - paradigm shifts replace a way of explaining the same phenomena - old and new frameworks may coexist during a transition 2 social and political discussion also uses "paradigm shift" - the phrase alone does not explain which assumptions are changing 3 common theme: different ways of interpreting one phenomenon - distinguish the phenomenon from a person's model of it 4 working meaning used by this book: - paradigm = an approach to understanding/modeling a subject - following examples clarify this before returning to programs 5 geometry can be understood visually or through formal statements - drawn spots/lines are illustrations, not ideal mathematical objects - axioms and reasoning do not require a particular drawing - both approaches concern the same underlying geometry 6 individual mental pictures differ even within the visual approach - author's image of brown lines came from a school textbook - learning pointers can likewise involve distinct personal models 7 learning a difficult subject involves forming a usable mental model - good teaching helps build that model rather than merely presenting facts 8 skiing is offered as an example outside mathematics and programming - physical activity also depends on how the participant interprets it 9 author contrasts the movement and attention of novices and practiced skiers - focus is on the model behind an observable difference 10 example's practical problem: retain control of speed while descending - uncontrolled acceleration makes stable movement difficult 11 turns can be viewed as the whole trajectory or as means toward a destination - novice model: follow the immediate zigzag - experienced model: aim along an overall route, with turns serving it - same physical descent, different organization of attention 12 explaining the purpose of an action helps change the model behind it - author distinguishes understanding an instruction from imitating it 13 Floyd applied the paradigm idea to programming - different programming paradigms can coexist and combine - individual development involves expanding one's repertoire 14 there is no universal recipe for choosing the best paradigm for every task - available models, constraints, and programmer experience affect the choice - flexible thinking increases the set of solutions one can consider 9.1.3 Main programming styles 1 imperative program acts within an execution environment - variables, streams, other processes, users, and controlled devices - environment includes anything affecting or affected by the program 2 imperative reasoning centers on state that changes over time - this is one model of computation, not a requirement of every algorithm - a mathematical transformation can be described without mutable cells 3 program instructions tell an executor which actions to perform - executor may be a CPU or interpreter - imperative means command-oriented 4 assignment is a characteristic imperative action - replace the value in a variable - previous value is lost unless saved elsewhere - other actions include I/O, signaling, and connection management 5 assignment requires a mental model of changing variable values - author describes it as a difficult early teaching barrier - his generalizations about innate aptitude reflect his experience, not a demonstrated rule about who can learn programming 6 tracing loops also requires imagining execution over time - author links difficulties with loops to that same mental-model issue 7 book calls this mutable-memory model von Neumann programming - connects variable updates to the stored-program machine - cites Backus's use of the terminology 8 historical von Neumann programming differed in implementation details - early machines sometimes modified instruction operands to index data - ordinary modern code is commonly protected from writes - the continuing conceptual feature is mutable state and assignment 9 procedural and imperative are not identical - imperative instructions do not inherently require isolated subprograms 10 historical line-numbered BASIC combined editing and execution - entering a numbered line inserted/replaced that program line - interactive commands executed directly - cassette-based machines made separate editor/compiler workflows costly 11 BASIC line numbers also served as jump destinations - GOTO supplied control transfers - numbering by tens left room for later insertions - renumbering tools also updated references to those numbers 12 GOSUB / RETURN supplied limited call-like control flow - described BASIC lacked local variables and formal parameter isolation - global variables carried information between fragments 13 procedural programming decomposes a problem into isolated subprograms - caller relies on the interface, not the implementation - implementing a helper should not require knowledge of each caller - one call can stand for a complex subtask 14 parameters and local state support that separation - separate call frames allow independent active invocations - support recursive use - stack frames alone do not make shared global state safely reentrant 15 assembly programmers can impose procedural organization manually - calls, stack frames, conventions, and local naming require deliberate work - language support and programmer discipline are different sources of structure 16 procedural programming is an important form of imperative organization - the two terms should not be used as interchangeable definitions 17 command scripting is another imperative style - examples organize commands and data through textual representations - named values need not expose addressable machine memory to the programmer - source emphasizes interpreted execution; implementations may add compilation 18 pure functional programming avoids destructive state updates - compute results instead of changing an existing environment in place - "destructive" and "modifying" describe the same state-change concern here 19 functional variables can denote immutable bindings - parameters bind to supplied arguments - local names denote computed values - establishing a binding is distinct from overwriting an earlier value 20 functions are the main composition units - first-class functions can be stored, passed, and returned - functional languages commonly create function values at runtime 21 function syntax alone does not make a program functional - C also has functions and function pointers - ordinary C functions often perform effects instead of pure mappings - pure result depends only on inputs, without other observable effects - replacing a pure computation with its value preserves its meaning 22 a functional subset can be imposed on an imperative language - avoid assignments, increments, and effectful helper calls in the core - theoretical computability assumes an idealized resource model - practical expressiveness and convenience still differ from a functional language 23 without updates, mutable global variables and ordinary state-changing loops disappear - recursion can express repeated computation instead - string search: empty -> NULL; matching head -> current address - otherwise recurse on s+1 - function decomposition replaces the loop's changing pointer 24 recursive repetition has a resource cost unless tail calls can reuse frames - return g(y) leaves no work for the current invocation after g completes - frame can sometimes be replaced rather than retained - C permits some such optimizations but does not guarantee them 25 computability models abstract away finite memory limits - unbounded tape and unbounded recursion are idealizations - do not confuse this theoretical equivalence with practical stack capacity 26 I/O changes the program's observable environment - reading consumes external input; writing affects output and other participants - a pure computational core still needs some account of interaction 27 languages combine pure computations with effects in different ways - Lisp/Scheme also expose mutation and ordinary I/O - lazy sequences can represent incrementally supplied input/output - source's Hope example emits elements of an output list as needed - lazy evaluation is one useful technique, not a universal prerequisite for pure effect models 28 Haskell's IO organizes effectful actions as values composed by pure code - the runtime executes the resulting action - this is more structured than treating every expression as an arbitrary I/O action 29 monad terminology can be a teaching obstacle - a mathematical definition alone may not explain its programming purpose 30 seminar anecdote: several accounts of monads emphasized different intuitions - illustrates the difficulty of teaching a new mental model 31 book does not develop Haskell or monad programming further 32 restricted C example takes its inputs through command-line arguments - exit status alone is too small a channel for arbitrary result data - eliminating normal output therefore creates an interface problem 33 one option allows I/O while keeping other computations free of effects - a pragmatic mixture rather than a completely pure program 34 illustration separates a functional core from effectful wrappers - main_func receives argc/argv and returns a list of output strings - mkitem allocates and initializes a fresh list node - main traverses the result and performs fputs calls - allocation, failure handling, output, and cleanup remain boundary concerns - this simple batch model does not provide general interactive timing 35 input/output histories can be encoded as data transformations - environment reactions and timing add concerns beyond a fixed batch input 36 interactive input may not exist until after the program produces output - external participant can delay, react, or make independent choices - program and environment can each wait for the other -> deadlock - protocol ordering is therefore part of the practical problem 37 logic programming describes facts and inference rules - execution seeks a proof/solution of a query 38 Prolog is the main logic-programming example - can also be understood operationally as searching alternatives - declarative and procedural readings expose different aspects 39 logic programming requires an inference/search mechanism - a general-purpose language can implement or host such a mechanism - simply avoiding mutation does not supply a logic solver 40 family example uses parent, male, and female facts - queries such as parent(X, ann) ask for satisfying bindings - father/mother rules combine parenthood with another predicate - brother rule combines shared parent and male status - example finds John as Ann's brother - a complete sibling relation must also exclude a person being their own sibling 41 more facts and rules express richer relational queries - combine age, education, language, occupation, and family information 42 declarative view specifies properties of a desired result - solver chooses how to search for a satisfying object - distinguish describing what is wanted from prescribing each search step 43 declarative programming is broader than logic programming - SQL is another declarative interface, based on relational queries 44 relations connect logic predicates with database tables - a fact resembles a tuple/row - Prolog's dynamic database can be modified through effectful operations 45 logic languages can serve as database-query tools - Prolog and Datalog supply examples - author's criticism of SQL dominance is a design viewpoint 46 Prolog also includes mechanisms that complicate a purely logical reading - I/O and dynamic database updates have effects - arithmetic evaluation, cut, and negation have operational conditions - variables denote unknowns/bindings, not ordinary assignment targets - recursion remains a major structuring tool 47 some Prolog programs require reasoning about the solver's search order - pure subsets and languages such as Datalog support a more restricted, declarative interpretation 48 object-oriented programming is often explained using three terms - encapsulation, inheritance, polymorphism - their mechanisms and purpose matter more than repeating the terminology 49 modularity helps control the complexity perceived by a programmer - hiding private names reduces how much context must be held at once 50 encapsulation hides implementation behind an interface - local variables and module-private names already provide examples 51 object model groups behavior behind individual object interfaces - client sends a request and receives a response - implementation may change internal state or communicate with other objects - clients rely on the contract rather than internal representation 52 object-level encapsulation can reduce visible complexity within a module - builds on, rather than invents, information hiding 53 class describes a family of objects - instances follow that description - inheritance derives a related class from an existing one 54 several classes may support a common interface - clients can use that shared set of operations 55 polymorphism means that similar syntax can have type-dependent behavior - + for different numeric types or strings - array and pointer expressions can also select different mechanisms - these examples are not uniquely object-oriented 56 operator overloading and subtype polymorphism are distinct facilities - derived objects can be used through a suitable base interface - virtual dispatch can select derived behavior - source contrasts class-based OOP with object-based facilities lacking inheritance 57 abstract data type: representation hidden behind permitted operations - FILE* is an interface example: clients use functions, not private layout - representation-independent operations help distinguish abstraction from raw storage 58 ADTs and object-oriented interfaces both hide implementation - shared encapsulation does not make the two models identical - author emphasizes message-oriented object reasoning as a further shift 59 book contrasts value copying with independent object identity - an ADT may define value assignment/copying - copying a value is not the same as sending an object a request - exact assignment semantics depend on the language/model 60 object-oriented and imperative features often coexist in one language - author argues that this popularity should not define OOP itself - his "pure OOP" classification is one conceptual interpretation 61 many object-oriented languages still use assignment and changing state - state is shared ground with imperative programming - organization of access to it differs 62 major style labels do not determine every aspect of a program - each leaves room for local models, strategies, and individual reasoning 63 smaller paradigms can coexist inside a broader one - callbacks, states, loops, recursion, and bindings shape thought locally - aim of this volume: learn to switch models deliberately 9.2 Recursion as a paradigm 1 languages differ in how naturally they support recursive solutions - some functional/logic styles rely on them extensively - Pascal/C allow a choice among several formulations - low-level assembly requires explicit calling/frame conventions - historical dialects lacking local call state make recursion difficult 2 study recursion as a model of thought, not only a self-calling technique 9.2.1 Tree traversal example 1 recursive inorder traversal: - empty tree -> return - traverse left subtree, print current value, traverse right subtree - node stores val plus left/right links 2 iterative traversal explicitly remembers the path back to ancestor nodes - linked stack entries hold node pointers and processing state - push a child when descending; pop when its subtree is finished - handle an empty input tree and allocation failure in complete code 3 three states for a saved node: - start: left subtree, value, and right subtree still need processing - left_visited: print value and process right subtree - completed: remove this stack entry and resume its parent - begin with a start entry for the root - before descending left, mark the parent left_visited 4 left subtree completed -> print current value - mark current node completed before descending right - absent right child needs no descent 5 completed node -> pop its traversal frame - popping the root's frame empties the stack and ends the loop 6 switch fallthrough skips redundant loop iterations for absent children - omitting the optimization can make the state transitions easier to follow - behavior remains the same; performance difference is implementation-specific 7 explicit path list is a stack - most recently entered node is processed first - each entry remembers node address and continuation stage 8 recursive calls preserve equivalent information implicitly - parameter identifies the node - instruction position identifies current work - return address records where parent processing resumes 9 both versions save a node and unfinished work for each active subtree - stack entry lifetime corresponds to entering/leaving that subtree - machine-level operations are closely related 10 representation of the explicit stack affects cost - allocating a linked node per traversal step adds overhead - an expandable array can reduce it - assembly can even use the hardware stack explicitly 11 main contrast is the programmer's description of the work - short recursive decomposition versus explicit continuation bookkeeping - paradigm shapes how a person understands the algorithm 9.2.2 Kinds of recursion 1 factorial is a common teaching example, but not always a useful practical one - 21! exceeds the range of an ordinary 64-bit integer - small fixed-domain values can be tabulated - arbitrary-precision arithmetic is an alternative when large values matter 2 binomial coefficients need not be computed through large factorials - C(n+1,k) = C(n,k-1) + C(n,k) - Pascal's triangle avoids unnecessarily huge factorial intermediates - example: C(30,12) = 86493225 3 author prefers examples whose recursive structure arises in ordinary tasks - blanket claims that factorials are never useful are his teaching viewpoint 4 array sum: - empty/nonpositive-length case -> 0 - otherwise first element + sum of the remaining array - arr+1 and len-1 describe that smaller problem - indexing versus dereferencing can express the same computation - ?: versus if does not by itself determine whether a function is pure 5 simple recursion: one recursive continuation per invocation - mutual recursion: f calls g, possibly through more functions, back to f - branching recursion: several recursive subproblems - independent subproblems can potentially run in parallel - tree sum combines left result + node value + right result - actual parallel execution requires an implementation that schedules it 6 nested recursion: a recursive result becomes input to another recursive call - shape: f(... f(...) ...) - Ackermann example: * A(0,n) = n+1 * A(m,0) = A(m-1,1), for m > 0 * A(m,n) = A(m-1,A(m,n-1)), for m,n > 0 - total computable function that is not primitive recursive - grows extremely quickly; a direct recursive evaluator is not a practical way to obtain large values 9.2.3 Reducing or folding a sequence 1 fold combines sequence elements with an initial accumulator/seed - empty sequence returns the seed - sum: addition with seed 0 - product: multiplication with seed 1 - maximum: take the first element as seed, requiring a nonempty sequence 2 left fold groups from the left: - f(f(f(seed,a1),a2),a3) - accumulator is the first argument in the convention used below - right fold: f(a1,f(a2,f(a3,seed))) - order and operand roles matter when f is not associative/commutative - accumulator type need not equal element type - filtering is possible when the accumulator itself is a list 3 recursion expresses the dependency structure of folds - left fold can also be a simple accumulator loop - right fold on a singly linked list must first handle the remaining tail - an iterative version can retain/reverse elements explicitly 4 C illustration uses integer nodes and intfunptr = int (*)(int,int) - left: reduce_l(f, f(seed, head), tail) - right: f(head, reduce_r(f, seed, tail)) - empty list returns seed in both cases - left fold computes the new seed before its recursive call 5 right fold must wait for the tail result before calling f - expanded code names rest_res to make that dependency explicit 6 left-fold recursive call is in tail position - right-fold recursive call is followed by another computation - this affects whether a frame can be reused 7 supply arithmetic helpers as fold arguments - addition/0 -> sum; multiplication/1 -> product - maximum starts with head value and folds the remaining tail - respect overflow limits of the chosen integer type 8 zero-counting helper must match operand order - left helper takes count, element - right helper takes element, count - zero element increments the count; other elements preserve it - seed is 0 9 examples illustrate the abstraction rather than prescribing a C optimization - performance depends on compiler, calling overhead, and representation - later languages make generic folds easier to express 9.2.4 Tail recursion 1 recursive list search: - empty list -> NULL - matching head -> head address - otherwise return find_value(next, value) directly - nothing remains to do after that recursive call - reusing the caller's frame can avoid a chain of redundant returns 2 self-tail-call can be modeled as updating parameters and restarting the body - preserve the original return destination - source illustrates this with a backward goto - the goto version explains an optimization, not a preferred source style 3 an ordinary loop expresses the same repeated search - indirect/mutual tail calls require a more general transformation 4 wildcard matcher uses match and starmatch - empty pattern matches only empty input - main recursion progressively removes pattern characters - star handling explores possible lengths of the matched substring 5 ordinary character / ? case: - reject exhausted input - reject a differing character unless the pattern has ? - otherwise tail-call match on both remaining suffixes 6 leading * delegates to starmatch - preserve the current input suffix - remove the star from the pattern passed onward 7 first try matching the star against an empty substring - call match with unchanged input and the remaining pattern - this is mutual recursion between match and starmatch 8 failed alternative does not yet mean complete failure - if input remains, try consuming one more character for the star - tail-call starmatch with shorter input - exhausted input ends the alternatives 9 only unresolved alternatives need retained continuation state - starmatch must remember where to retry after a failed match - other calls returning a callee's result directly need no later work 10 last alternative needs no retry state - when input is empty, return match("", remaining_pattern) directly - moving that base case first makes the final attempt a tail call 11 if all eligible tail calls were optimized, retained frames would represent unresolved stars rather than every consumed character - C does not guarantee this optimization - particular compilers can optimize self and some mutual/sibling calls - book's claim that C compilers cannot do mutual tail calls is too broad 12 recognizing tail position does not promise a particular machine-code result - compiler, ABI, optimization settings, and object lifetimes matter 13 reusing a frame must preserve arguments still needed to compute new ones - parameter placement and live values can complicate transformation - temporary moves/copies may be needed - this is a potential constraint, not proof that tail calls are always slower 14 optimizers balance execution cost and resource use - a language that relies on proper tail calls gives different guarantees from C's optional optimizations 15 list_length(next) + 1 is not itself a tail call - addition remains after the recursive result arrives - being textually inside return is not sufficient 16 accumulator parameter moves pending work before the recursive call - list_length_do(list, count): empty -> count - otherwise recurse on next with count+1 - wrapper starts count at 0 - array sum similarly passes the accumulated sum to the next call - reversing a list can move each head onto an accumulated result list - save next before changing the link; begin result at NULL - this link-reversal algorithm is linear rather than repeatedly appending through the whole growing result 17 an accumulator cannot erase every outstanding branch - tree sum still must resume after processing one subtree - one recursive call may be tail-positioned while the other is not - eliminating all frames requires storing unfinished nodes elsewhere - explicit stack and tail-recursive encodings preserve equivalent work 9.2.5 Recursive thinking 1 using recursive calls does not automatically mean thinking recursively - an operational account may still describe a sequence of actions 2 two descriptions of list length: - operational: compute tail length, then add one - structural: empty length is zero; other length is tail length plus one - second directly characterizes the result on recursively defined data - it need not first be rewritten as an instruction-by-instruction story 3 nested fold expressions expose the recursive structure - left grouping and right grouping show how results are composed - a sequence of r1, r2, ... updates emphasizes an operational interpretation 4 accumulator-based recursion often invites operational reasoning - explain what has been accumulated and what remains - structural definitions are not always the clearest description 5 recursive string-copy example uses descent and return phases - descend while tracking position/depth to find the required length - at the terminator, allocate depth+1 bytes - while returning, each frame writes its character at its saved index - every level returns the same newly allocated result address - allocation failure must be handled before any writes in real code 6 ordering is essential in that example - storage must exist before characters are copied into it - other algorithms use returning calls to reverse the order of actions 7 both structural and operational explanations have uses - choose the one that exposes the essential dependencies of the task 8 recursion as technique: direct or indirect self-invocation - recursion as paradigm: a particular way of understanding the problem - technical usefulness does not depend on always adopting that paradigm 9.3 Paradigms and programming languages 9.3.1 The role of language 1 language supplies concepts as well as notation for expressing a solution - book cites Barron and Dijkstra on tools shaping thought - Budd's example searches a long DNA-like sequence for repeated windows - direct solution compares every pair of starting positions - comparing fixed-length prefixes gives roughly quadratic pairwise work 2 alternative uses a sortable collection of windows - create one row per length-k window plus its original starting index - sort by the k data elements, not the saved position - equal windows become adjacent - scan groups to recover their original positions - for fixed k, sorting costs O(N log N) 3 algorithmic improvement can dominate implementation overhead - sorting-based approach can also be implemented in other languages - availability of a natural sorting operation may suggest it sooner - enumerating every matching pair can add output-size-dependent work 4 language communities develop habits and conventions - author argues these influence the solutions programmers notice - the anecdote does not prove a language uniquely determines an algorithm 5 one paradigm label rarely describes an entire language - languages can support several models - same paradigm can be expressed using different languages 6 book proposes seven relationships between a language and a paradigm: - require: cannot avoid it - strongly pressure: alternatives exist but are awkward - encourage: using it offers a practical advantage - support: supplies dedicated facilities - permit: can implement it without special facilities - impede: possible only with substantial inconvenience - prohibit: cannot express it within the intended model 7 illustrative classifications from the author - Smalltalk centers object-oriented interaction - imperative numerical languages center assignment - Lisp encourages recursive formulations - these are conceptual comparisons, not complete language specifications 8 C++ offers several independently useful models - ADTs, objects/inheritance, templates, exceptions - programmer can adopt some without adopting all - Lisp's higher-order functions and lambdas similarly reward a new style 9 having a feature is distinct from making it the preferred style - Lisp loops, C++ macros, C recursion illustrate that distinction 10 a skilled programmer can impose conventions beyond direct syntax support - C can represent objects as structures and methods as functions - function-pointer tables supply dynamic dispatch - embedding a common structure can model shared interface/layout - Linux VFS illustrates such object-oriented organization in C 11 C macro-based generic code can be cumbersome - setjmp/longjmp alone also do not provide a complete exception system - required bookkeeping can discourage a paradigm despite its expressibility 12 historical languages without localized subprogram state restrict recursion - sufficiently elaborate manual encodings can change what is possible - author's examples of "prohibition" concern ordinary practical language use 9.3.2 C and Pascal: a conceptual difference 1 C and Pascal share many imperative constructs - variables, types, assignment, blocks, branches, loops, subprograms - notation changes such as braces versus begin/end are superficial - language meaning matters more than the printed symbols 2 more substantial differences include: - main function versus a distinct main-program block - C block-local declarations - C character codes as integer values - value-only parameter passing with explicit pointer output parameters - pointer arithmetic makes array suffixes easy to pass 3 book values C's separation between core syntax and library facilities - many services are ordinary function calls rather than special statements 4 many such facilities could be added to another dialect or implementation - they do not alone explain the difference in programming habits 5 author identifies treatment of side effects as the central conceptual difference 6 book adopts a narrow, expression-centered definition of side effect - distinguishes an action's main purpose from an effect of evaluating a value - wider programming literature also calls procedure/statement effects side effects - follow the author's terminology when interpreting this comparison 7 within that definition, expression evaluation has a side effect if it changes something observable beyond producing its value 8 C assignment is an expression - x = 7 yields a value and changes x - x = 7; discards the value and retains the effect 9 Pascal assignment is a statement, not a subexpression - author therefore calls its update an action rather than a side effect - this distinction is terminological, not a difference in whether state changes 10 Pascal expressions can still call effectful functions - sample f prints its argument and returns its square - a := f(15) + 2 includes output during right-side evaluation - m[f(5)-3] := 7 includes output while selecting a destination 11 Pascal distinguishes procedure calls from value-returning function calls - original dialect restricted discarding a function's result - later dialects relaxed that restriction - author associates the separation with clearer action/value roles 12 C uses functions, including void functions, for both roles - machine-level similarity does not eliminate a source-level conceptual difference 13 void call has no result value but can perform effects - C's expression-statement model accommodates those effects directly - ordinary state-changing actions therefore appear as effectful expressions - author argues that this makes side effects seem unremarkable 14 compact copy idiom combines assignment and two pointer increments - while((*dest++ = *src++)) {} - expanded version separates copy, pointer advances, and final zero - same intended transformation, different burden on the reader 15 some loops naturally follow retrieve -> test -> process - while(fscanf(stream, "%d", &n) == 1) retrieves inside the condition - moving retrieval outside may duplicate the call before/inside the loop - result must be checked before processing n 16 another form uses an indefinite loop and an explicit break - retrieve once in the body - if retrieval failed, break - otherwise process and repeat - author weighs duplicated code, condition effects, and less visible termination 17 choice among these forms is partly a readability decision - condition-side retrieval has a real purpose in this specific loop shape 18 author does not generalize that exception to every effectful condition - recommends separating unrelated effects from tests - wait(NULL) loops illustrate a case needing closer analysis 19 waiting without per-child processing is action -> test - can be written as do { pid = wait(NULL); } while(pid != -1) - adding processing after each successful wait changes the loop shape - real code must distinguish EINTR from "no children" rather than stop indiscriminately on every wait error 20 array[i++] = value combines storing and advancing - author prefers separate statements to expose both steps - compact spelling alone does not establish a speed advantage 21 action-oriented functions often return status or another result in C - output parameters are an alternative - existing C interfaces mix these conventions - cannot impose a single stylistic rule by ignoring documented return values 22 book's Pascal rule allows effectful retrieval where it clarifies an input loop - otherwise favors explicit procedure actions and effect-free calculations 23 translating that rule to C requires exceptions - assignment as a separate statement still has an effect - status-returning library functions must have their results handled 24 experience with another language can make a style rule's motivation clearer - unexplained prohibitions teach compliance rather than understanding 25 author argues that C makes mixing actions into expressions particularly easy - the proposed lesson is to recognize and control that habit 26 this reasoning influenced changes between the book's editions - especially its treatment of effectful Pascal functions 27 author strongly prefers alternatives to C for first-language teaching - this is his pedagogical conclusion, not a universal verdict on learners 28 fork example exposes the danger of copying syntax without understanding effects - fork(); followed by if(fork() == 0) makes additional processes - if both forks succeed, four processes reach the following code - one initial fork plus two second calls occur across the processes - clearer teaching form: pid = fork(); then inspect pid - a conditional expression can perform an action as well as compare values 29 an expert may no longer notice the mental model a beginner is missing - explain the action and its result, not merely an idiomatic spelling 30 author's closing concern is teaching habits that obscure effects - understanding the model should precede imitating concise C idioms 9.3.3 Two ways of comparing languages 1 many languages exist, but no single best language serves every purpose - author's broad dissatisfaction frames the following comparison 2 two perspectives emphasize different criteria - language as a practical delivery tool - language as a notation for expressing knowledge/solutions 3 tool-centered view includes the implementation and deployment environment - writing, debugging, packaging, installing, running, and maintaining - goal: make the user's system perform the required task 4 notation-centered view emphasizes expressing the solution itself - may temporarily abstract from installation/runtime details - those details still have to be handled when delivering a real application 5 author warns against confusing abstraction with lack of understanding - not thinking about machine details in one task differs from never learning them 6 concise source is only one comparison criterion - execution strategy, dependencies, and target environment can matter too - neither brevity nor language name alone establishes suitability 7 author prefers tools that impose few requirements on the end user - treats deployment/runtime dependencies as part of language choice - this is an engineering preference to weigh against actual constraints 8 later chapter examines compilation and interpretation as mental models - abstract notation-only comparison can be useful in some contexts - it is not enough for every practical decision 9.4 Examples of local paradigms 1 condition can itself be a computed value - return a == b; replaces an if returning 1 or 0 - a boolean flag can be tested directly - complex conditions can be named by a function - understanding this is more important than memorizing a shorter spelling 2 explicit comparison remains useful when zero is a nonboolean result - strcmp(...) == 0 clearly denotes equality - its sign has meaning beyond simply true/false 3 "condition as value" is a small but consequential mental model - broader paradigms contain many such local models 9.4.1 Callbacks 1 callback supplies behavior for another subsystem to invoke - service may complete later, through a deep call chain, or for many items - avoids requiring one immediate result at the original call site 2 client gives the service a function to call when appropriate - pass received data or each found item through callback parameters - void* user data can identify the client's per-operation state - define lifetime and invocation rules as part of the interface 3 callbacks change how control flow is perceived - client cannot assume every action happens in its own linear sequence - timing, ordering, and count follow the service's documented behavior 4 practice with higher-order functions or event systems can make this model familiar - callbacks are not inherently mysterious just because control is indirect 5 client/server roles also exist inside one program - one component requests a service; another provides it - networked machines are not required for that relationship 9.4.2 Programming with explicit states 1 GUI libraries can hide the main event loop - application appears as separate event handlers - loop is the service; handlers are callbacks - merely recognizing the hidden loop is not enough for responsiveness 2 long handlers make other work wait - GUI appears frozen; server clients may time out - more CPU power does not remove every source of delay 3 handler must return within the application's response-time budget - potentially long blocking operations stall a single-threaded event loop - use nonblocking work, resumable steps, or a separate worker as appropriate 4 explicit-state programming represents progress between events - finite-state machines are one instance of a broader state-machine model 5 explicit states also arise outside interactive event loops - iterative tree traversal stored the work that recursion kept implicitly 6 state representation replaces saved execution position - tree example stores active nodes and whether their subtrees were processed - state records what remains to be done when execution resumes 7 book's strict step model performs one transition at a time - remove switch fallthrough from the traversal to follow that convention - this changes organization, not the traversal's result 8 state-machine style is an imperative model with explicit transition rules - define what constitutes state and how an event changes it - state may be richer than a finite enum 9 represent state as one coherent set of data - one enum, a structure, or a connected collection of objects - cohesion should be visible to the programmer 10 divide operation into clearly separated steps - external caller/event requests each step - inputs can be characters, timer events, or explicit advance requests - steps need not involve waiting for real-world events 11 step can update state and produce output actions - in this model it does not recursively request its own next step - event acquisition remains outside the state machine - a parser is fed characters rather than blocking to read them internally 12 next action depends on the current state and the supplied event 13 caller need not run the machine continuously in a loop - resumable tree traversal can return one value per request - retained state permits a later request to continue where it stopped 9.4.3 Metaprogramming 1 metaprogramming writes code that produces or manipulates program code - analogous to metadata describing data or a metalanguage describing languages 2 a generator can produce another program or one module of it - generated code then performs the original task 3 macros are an earlier example of this idea - macro definition produces source fragments during expansion - C preprocessing is limited compared with more capable macro languages - NASM macro repetition supports richer compile-time generation 4 C++ templates and later interpreted-language facilities extend the examples - reason about both the generator and the program it produces - that additional level of reasoning makes metaprogramming a paradigm 10. C++, OOP, and abstract data types 1 C++: introduced by Bjarne Stroustrup as an extension of C - supports objects and messages - also supports abstract data types, generic programming, exceptions and other ways of organizing a program 2 OOP and abstract data types: two related but distinct paradigms - the preceding chapter introduced both 3 C++ uses the same mechanisms for several purposes: - access control hides both object state and ADT representation - classes and inheritance also participate in exceptions - the underlying imperative model remains visible using these mechanisms does not by itself establish an OOP design 4 ADTs are useful independently of OOP OOP also requires thinking in terms of objects and their messages - practise that way of describing large cooperating systems 5 language features provide technical support for paradigms - the programmer chooses how to interpret and organize a program - the chapter returns to this distinction after the mechanisms 10.1 From C to C++ 1 C++ extends C, but is not a strict superset - extra keywords can invalidate former identifiers: e.g. try - a struct declaration introduces a usable type name - mystruct s1 is sufficient; struct mystruct s1 also works correction to the example: - typedef struct mystruct { ... } mystruct is valid C++ - repeating the same type name this way is redundant, not an error 2 C++ requires declarations before function calls - the comparison with implicit function declarations concerns old C - incompatible pointer conversions require attention - void* does not implicitly convert to an arbitrary object pointer C's permission to convert void* does not extend to all pointer types 3 the book uses 0 as a null pointer constant - conversion produces the null value of the required pointer type - its machine representation need not be an all-zero address - NULL is also available; this is the book's older C++ convention 4 several C++ additions are useful before introducing classes or ADTs 5 bool: false and true - conversion to an integer gives 0 and 1 respectively - integer expressions can still be used as conditions 6 ordinary character literals: type char in C++, type int in C - this difference matters when a function is selected by argument type 7 declarations can occur among statements and in a for initializer - e.g. declare the loop counter in the loop header // introduces a comment extending to the end of the line - /* ... */ comments remain available these comparisons describe older C; later C also has these facilities 10.2 Choosing a subset of C++ 1 author's concern: teaching library use before language mechanisms - can hide how containers and other abstractions work - can blur the distinction between language and library - a large feature catalogue can crowd out conceptual understanding 2 the author associates this teaching approach with Stroustrup's third edition, which uses container templates before explaining templates - his experience led him to prefer learning the machinery first - using existing templates and designing templates are different skills 3 the chapter grew from a separately published C++ booklet - its treatment deliberately follows an older language subset - its attacks on C++ standards are the author's opinions - they are not technical proof that later C++ is unusable 4 the author considers alternatives inadequate for his low-level needs - this is his assessment of language design and industrial practice 5 two properties especially important to the author: - a clear distinction between language and library - ability to build without a supplied runtime where the target needs it these motivate his interest in kernels and microcontroller firmware 6 the author argues for understanding what abstractions cost and require - cites restricted C++ usage in GUI libraries as examples - their choices illustrate selective use of language features - the book's claims about particular projects reflect its time 7 the book deliberately omits STL and newer language additions - its examples teach a selected subset, not the whole current language 10.3 Methods, objects, and access control 1 start from familiar C structures and functions - add member functions, hidden state and controlled lifetime - arrive at classes with methods, constructors and destructors 10.3.1 Member functions: methods 1 member functions and classes support object-oriented programming - first examine a method inside a structure 2 complex number: re and im store its Cartesian components C version: magnitude receives a pointer to the structure C++ version: magnitude belongs to the structure - accesses re and im directly - z.magnitude() uses z.re and z.im - result = sqrt(re*re + im*im) method: a function called for a particular object 3 calling a method corresponds to sending an object a message - z receives magnitude: calculate your magnitude - its double result is the reply, then assigned to mod 10.3.2 The implicit object pointer 1 a non-static member call supplies the object implicitly - conceptually like passing its address to an ordinary C function - moving the function into the structure need not add runtime cost 2 this: pointer to the object receiving the call - this->re makes the otherwise implicit member access explicit - useful when another function needs the current object's address - the pointer itself cannot be reassigned 10.3.3 Access control and constructors 1 hiding implementation requires restricting direct access to members - clients should use the operations the type exposes 2 public: accessible to clients private: accessible to the class's own member functions - simply hiding re and im leaves no way to initialize them - adding set allows values to be supplied later problem: a client can forget set or call magnitude first - the object then has no established valid state - initialization should be part of creation itself 3 constructor: instructions for initializing each new object - may require arguments - specifies how those arguments establish its initial state 4 constructor name matches the class or structure name - has no declared return type, not even void - the result of construction is the initialized object 5 str_complex(double a_re, double a_im): requires both components - constructor stores them before ordinary use of the object 6 constructors may be supplied implicitly in cases the language permits - a programmer need not write every special member explicitly - aggregate initialization is a separate case in C++ 7 str_complex z(2.7, 3.8): construction with the two arguments - z.magnitude() then reads initialized components a temporary can also receive the message immediately: - str_complex(2.7, 3.8).magnitude() 8 declaring a parameterized constructor suppresses an implicit no-argument constructor - str_complex z is then invalid unless a suitable constructor exists 9 parenthesized initialization also works for built-in types - int v(7) initializes v to 7 initialization and assignment are different operations - array initialization does not imply array assignment is possible - some initialization is encoded in the loaded program image - global C++ objects can also require runtime initialization 10 constructors initialize new objects - assignment changes an object that already exists - C++ provides separate control over assignment 11 access control belongs to the type, not to each individual instance - a method can access private members of another object of its class 10.3.4 Why restrict access? 1 access control is useful because it limits dependencies on representation 2 complex numbers: repeated magnitude calculation can become expensive - storing magnitude and argument may suit a workload better 3 public re and im tie every client to Cartesian storage - changing the representation then requires changing client modules - widespread edits cost time and introduce opportunities for mistakes 4 private fields plus GetRe, GetIm, Magnitude and Argument: - preserve the external operations while changing internal storage Cartesian storage: - components are returned directly - magnitude and argument are calculated polar storage: - magnitude and argument are returned directly - re = mod*cos(arg); im = mod*sin(arg) - constructor converts supplied Cartesian values to polar form implementations can be switched and measured without rewriting clients 5 another representation: store both coordinate pairs - trades extra storage for simpler repeated queries invariant: both pairs must describe the same complex number - changing only one pair would break consistency - private fields confine responsibility to the class implementation - checking one module is easier than checking every user of the type 6 access control prevents accidental misuse by cooperating programmers - it is not a security boundary against hostile machine-level access - deliberately circumventing it defeats its engineering purpose 10.3.5 Classes 1 class: a structure whose members are private by default - suits types whose representation is normally hidden 2 Complex stores re and im privately - public constructor and query methods form its usable interface - public: changes access for following declarations 3 class and struct have the same underlying capabilities - default member and base-class access differ usual convention in this book: - struct for open records - class for objects and abstract data types 10.3.6 Destructors 1 destructor: controls cleanup when an object's lifetime ends 2 an object may own resources that clients cannot see - dynamically allocated storage, an open file, or another resource - the object knows how to release them - cleanup must accompany the relevant end of its lifetime 3 ~A(): destructor for class A - no parameters and no declared return type - invoked automatically during normal object destruction 4 File example: - fd starts at -1: no open file - OpenRO stores open's result and reports whether it succeeded - destructor closes fd when it is valid local objects are destroyed on normal scope exit, including return - one completed lifetime has one construction and one destruction - abrupt process termination does not guarantee destructor calls a production owner must also handle repeated OpenRO calls and copying - the short example does not yet solve these ownership cases 10.4 Abstract data types in C++ 1 access control and lifetime operations support both OOP and ADTs - methods are central to the object/message interpretation - ADT operations can also be expressed as non-member functions 2 this section adds user-defined operations and lifetime control - creation, copying, assignment and destruction - references connect expression properties with the type system - these facilities are not restricted to OOP 3 goal: use a complicated abstraction as naturally as a built-in value - implementation details stay inside its definition 4 author's assessment: effective ADTs can greatly reduce work relative to C - the gain depends on how the program and its types are organized 10.4.1 Function overloading and name mangling 1 overloading: a language mechanism used by several later features - not in itself an OOP or ADT design 2 functions can share a name when their parameter lists distinguish them - print(int), print(const char*) and print() are separate functions - argument number and types determine the selected overload function signature includes its name and relevant parameter types - return type alone cannot distinguish two overloads - overloads may return different types if parameters distinguish them - int* and const int* differ; top-level const on a value parameter does not create a distinct overload 3 adding an overload can make an existing call ambiguous - f(float) and f(const char*) both accept conversion from literal 0 - f(1) selects the numeric possibility; f("string") the pointer one - f(0) gives neither candidate a sufficient advantage 4 overloading is static polymorphism - the compiler chooses the operation before the program runs 5 the author prefers distinct names for ordinary functions - e.g. print_int and print_str make intent explicit constructors need overloading because their names match their class - different parameter lists provide different ways to create a value 6 operator functions also share prescribed names - argument types distinguish implementations for different types 7 author's recommendation: avoid ordinary-function overloading - this is his style preference, not a language restriction - constructors and operator functions use it throughout the chapter 8 mixed-language projects expose an additional issue - C, C++ and assembler modules must agree on linker symbols 9 a linker resolves labels and addresses, not high-level function overloads - one plain function name cannot distinguish all C++ overloads 10 name mangling: encoding C++ naming information into linker symbols 11 a mangled name can encode the function and its parameter types - the example foo(double, int) becomes _Z3foodi with its toolchain - user-defined types and templates require more elaborate encodings 12 binary compatibility depends on the compiler's ABI - matching mangling is necessary but not the whole ABI contract - source distribution allows rebuilding for a chosen toolchain 13 C and C++ declarations can look alike but produce different symbols - a C definition named foo will not satisfy a request for _Z3foodi - compilation may succeed while linking fails 14 extern "C": gives declarations C language linkage - allows a C++ caller and a C implementation to agree - the usual overload-based C++ symbol encoding is not applied 15 two ways to expose a C header to C++: - place its #include inside extern "C" { ... } - put the linkage wrapper inside the header itself shared header: - protect the wrapper with #ifdef __cplusplus - retain ordinary include guards - the C compiler sees declarations without C++ linkage syntax nested scopes also require distinguishable linker names - class members are not identified solely by their short names 16 author's language-design criticism: - constructors could hypothetically have distinct names - operators could hypothetically use a different special mechanism these are proposed alternatives, not facilities offered by C++ 17 the author treats these costs as lessons for future language design - his judgment of C++ alternatives remains an opinion 10.4.2 Overloading operator symbols 1 a useful Complex type needs arithmetic as well as component queries 2 operator+: a member function implementing addition for the type - b.operator+(c) can be written b + c - the left operand supplies this; the right is the explicit argument - class access permits reading the other Complex object's private data complex arithmetic: - addition/subtraction operate on corresponding components - multiplication: (ac-bd, ad+bc) - division: ((ac+bd)/(c*c+d*d), (bc-ad)/(c*c+d*d)) for numerator (a,b) and denominator (c,d) - each operation constructs and returns its result (c1+c2).Magnitude(): call a method on the sum many operator symbols can be overloaded, but not every language operation - conditional ?: and member selection . cannot be overloaded - neither can scope resolution :: or sizeof - overloading does not change operator precedence or arity 3 operator selection by operand type is static polymorphism - operator functions may also be non-members - familiar notation makes user-defined values easier to use as ADTs 4 terminology matters: a statement is a structural unit of program text - if, loops and expression statements are examples - an expression followed by ; becomes an expression statement 5 an operator belongs inside an expression - arithmetic, comparison, assignment, logical and pointer operations 6 the English term operator follows mathematical usage - a transformation or operation applied to its operands 7 Russian terminology uses a misleadingly similar word for statement - keep statement and operator distinct when reading English C++ 10.4.3 Default constructors and arrays of objects 1 Complex's two-argument constructor cannot initialize Complex sum - it needs both components - arrays also need a way to initialize their elements - the simple uninitialized-array syntax requires default construction 2 add Complex() alongside Complex(double, double) - overloading distinguishes the two constructors - the no-argument version sets both components to zero default constructor: callable without arguments - Complex z3 uses it once - Complex v[50] uses it for each of the 50 elements 10.4.4 Converting constructors 1 implicit conversions allow a value where another type is expected - e.g. an integer argument passed to a float parameter - C++ can also define conversions involving user-defined types 2 converting A to B means constructing a B from the supplied A - a B constructor taking A provides the required instructions 3 Complex(double a): store a as the real part and zero as the imaginary part - Complex c(9.7) requests that construction directly - f(2.7), with a Complex parameter, can perform it implicitly - the resulting Complex value is passed to f explicit can disallow this implicit use of a constructor - direct construction remains available 10.4.5 References 1 references are central to the following ADT mechanisms - understand their semantics before treating them as pointer shorthand 2 a reference aliases an object - operations through it act on that object - assignment changes the referred-to value, not the reference's binding - taking its address obtains the address of the referred-to object - address passing is a usual implementation, not its full meaning 3 int &r = i: r and i designate the same integer - r++ changes i just as i++ does - unlike *p, no explicit dereference is written at each use - initialize i before any operation that reads its value 4 a reference definition needs an initializer - there is no later assignment that can establish its binding - initialization and assignment therefore have visibly different roles 5 reference parameters let a function work on the caller's objects C max_min example: - results min and max must be returned through pointer parameters - caller supplies &min and &max - function dereferences the pointers when reading or writing them 6 C++ max_min uses float& for the two result parameters - call max_min(a, 500, min, max) - initialize both results from a[0] - scan the remaining elements and update the smaller/larger bound - assignments to parameter names update the caller's variables preconditions: nonempty valid array and suitable distinct result variables 7 a function can return a reference to a located object - int &find_var(...) makes the call usable as a variable - can read, assign, multiply-assign or increment the selected integer - the referenced object must still exist after the function returns 10.4.6 References to const 1 const char *p: p can change, but cannot modify characters through p char * const p: p cannot change, but its pointed-to characters may change const int &r = i: - prevents modification through r - i may still be changed through another permitted access - an ordinary int& cannot bind to a const int a reference is never reseated; const qualifies the referred-to access 2 const-reference parameters avoid copying while preventing direct changes through that parameter - particularly useful for larger objects - Complex operator+(const Complex &op2) reads the existing operand - the operation still returns a new Complex result 10.4.7 References as a semantic idea 1 the author considers references an especially important C++ innovation 2 lvalue: an expression that identifies an object or other identity - examples: a variable name, *p, v[i], q->f - reading obtains a value from the designated object - assignment selects the destination object - += and ++ both read and modify it 3 author's explanatory model: treat such expressions as references - *p behaves like access through int& when p points to int - member and indexing expressions similarly designate their objects 4 in this model, value use reads the referenced object - modifying use keeps its identity as the destination 5 const references illustrate access that identifies an object but cannot modify it - the author prefers this account to a catalogue of value categories - this is a teaching model; standard C++ distinguishes expression types, reference types and value categories 6 (x < y ? x : y) = z selects an integer object and assigns to it - works when the conditional expression has the required lvalue form - the corresponding C technique selects addresses, then dereferences: *(x < y ? &x : &y) = z 10.4.8 Const member functions 1 const A* permits access to A without modification through that pointer - calling an arbitrary method would undermine that guarantee 2 the same issue arises for const references and const objects - hidden fields make a usable read-only method interface essential 3 put const after a member function's parameter list - the method cannot change ordinary members through this - cannot pass those members as modifiable references or pointers - can be called on a const object - this is not a guarantee against all externally observable side effects 4 mark query operations const when their meaning permits it - Complex's component queries, magnitude and arithmetic are examples - a const method cannot call a non-const method on the same object - this has type const C* within a const member of C 10.4.9 Dynamic allocation operations 1 C allocation functions supply and release storage - C++ object creation/destruction may additionally require constructors and destructors, with constructor arguments 2 malloc and free do not by themselves perform those object operations - object lifetime needs language-aware handling 3 new T: obtain storage and create a T - new Complex(2.4, 7.12) passes arguments to its constructor delete p: destroy that object and release its allocated storage array forms: new T[n] and delete[] p - construction and destruction apply to each class-type element - the book's new T[n] form uses default construction - new int alone does not initialize the integer's value 4 match allocation and release forms exactly - new with delete - new[] with delete[] - malloc-family storage with free mismatching them has undefined behavior, regardless of apparent success 5 an implementation seeming to tolerate a mismatch proves nothing - a different build or allocator can expose the error 10.4.10 The copy constructor 1 Cls1 owns an array through an int* member - constructor allocates 20 integers; destructor uses delete[] passing a Cls1 by value creates another object - implicit memberwise copying copies the pointer value - both objects then refer to the same allocation 2 unplanned sharing breaks ownership - changes through the copy affect the original's array - destruction of the copy frees storage still used by the original - later access dangles; later destruction attempts a second release 3 copy constructor: define how a new object is made from an existing one - usual form: Cls1(const Cls1 &a) - allocate a separate array and copy its initialized elements - each object then owns and destroys its own allocation - a class member of class type is itself copied by its copy operation 4 a copy constructor cannot take its own type by value - preparing that argument would already require another copy - a reference avoids the impossible recursive requirement 10.4.11 Temporary and unnamed objects 1 an explicitly written unnamed object is convenient for a single use - t = z * Complex(0, 1) multiplies z by the imaginary unit implicit conversions can also create temporary objects - passing a double where Complex is needed constructs the operand 2 a + b + c groups as (a + b) + c - the first addition produces a Complex result - that result becomes the next addition's left operand - returning class values can therefore supply temporary intermediates 3 the book calls explicitly written temporaries anonymous objects - ordinarily temporaries are destroyed at the end of the full expression - their destructors run then binding a suitable local const reference can extend a temporary's lifetime - lifetime extension has specific rules; it is not inherited by every later reference or by a reference returned from a function 4 an ordinary non-const lvalue reference cannot bind to a temporary - by-value and const-reference parameters can accept it - treating a disposable temporary as an output parameter is unhelpful 5 use const references when modification through a parameter is unnecessary - reserve modifiable references for operations that need to change the caller's object 10.4.12 Default argument values 1 a function declaration can supply defaults for omitted trailing arguments - f(5) can mean f(5, "string", 5) for the example declaration - defaults must be available for all omitted positions at the end - supplied arguments always match positions from the left - cannot skip a middle string argument by supplying a later pointer 2 default expressions have their own lookup and evaluation rules - the author recommends simple constants to avoid surprises 3 the author questions calling default arguments static polymorphism - the mechanism itself does not select behavior by differing types 4 special constructor categories depend on how they can be called - a default constructor is callable without arguments - a converting constructor can accept the source value - a copy constructor can take the appropriate reference to its class Complex(double re = 0, double im = 0) serves three purposes - no arguments: zero value - one double: real-to-complex conversion - two doubles: specified real and imaginary components 10.4.13 Defining methods outside the class and qualifying names 1 method bodies can be as large as ordinary function bodies - the author still recommends small, understandable subroutines 2 long bodies inside a class obscure its interface - readers need to see the available methods together 3 classes shared by modules normally have definitions in headers - method bodies there are seen by every including translation unit - inline definitions have special rules; duplicated final machine code is not an inevitable consequence 4 keep declarations in the class and place longer definitions separately - retain return type, name, parameters and any trailing const - end the declaration with ; - usually put definitions in the module's implementation file 5 ClassName::MethodName identifies an out-of-class member definition - constructors use ClassName::ClassName - const must agree between declaration and definition - a short member name is otherwise local to its class scope 6 class scope separates its member names from unrelated names - f inside C1 and C1::f outside designate the same member - qualification identifies the scope; access control still applies 7 ::func selects func in global scope - useful when a member with the same name hides it - qualification also applies to static members 8 :: qualifies names rather than computing a scope from an expression - the author discusses whether to call it an operator - operationally, names on its sides must satisfy qualification syntax 10.4.14 Inline functions 1 very short accessors might appear expensive if each required a full call - call setup can outweigh simply loading one field 2 inlining substitutes the function's operations at a call site - subsequent optimization can remove unnecessary intermediate work - encapsulation need not imply an extra machine-level call 3 methods defined inside the class are implicitly inline in the book's model - this suits the suggested convention of keeping only short bodies there 4 inline may also be written on an ordinary or out-of-class function 5 inline does not force machine-code substitution - optimization decisions belong to the compiler - functions without inline can also be inlined 6 an inline function used across translation units needs its definition available where required, conventionally in a header - separate compilation otherwise sees only the declaration - inline also permits corresponding identical definitions in multiple translation units under the language's definition rules 7 a function may have both inlined call sites and callable emitted code - taking its address can require a callable implementation - these implementation choices must preserve program semantics 8 short methods can therefore expose a clean interface without necessarily adding call overhead 10.4.15 Member initialization in constructors 1 members already need to be constructed before the constructor body runs - B contains A a; A requires two constructor arguments - assignment inside B's body cannot supply a's initial construction 2 member initializer list follows the constructor header after a colon - B::B() : a(2, 3) constructs a with those arguments - Complex can initialize re and im in the same way - also necessary for reference members and applicable const members members initialize in declaration order, not initializer-list order - write the list in that same order to make dependencies clear 10.4.16 Non-member operator functions 1 a member Complex::operator+ can accept t + 0.5 through conversion - 0.5 becomes its explicit Complex argument - 0.5 + t cannot first convert 0.5 into the receiving object 2 a non-member operator+(const Complex&, const Complex&) treats both operands as parameters - conversions can apply on either side - use public component queries to construct the sum binary member form: a.operator+(b) non-member form: operator+(a, b) - equivalent-quality competing candidates can make a + b ambiguous - neither form automatically takes priority 3 non-member operations can extend a type's usable notation - useful when its class definition cannot be edited - the needed behavior must still be expressible through available access 10.4.17 Friend functions and classes 1 friend grants selected external code access to private implementation - a friend function can access the granting class's members - friend class B grants that access to B's member functions 2 friendship expands the code responsible for preserving invariants - friend definitions may be elsewhere in the program - use it deliberately, with the participating code understood 3 a non-member operator may need representation access - exposing every internal detail through public getters is not ideal - friendship can provide narrow access instead 4 declare the operator's prototype with friend inside Complex - its external definition can then read a.re, a.im, b.re and b.im - it remains a non-member with two explicit operands 5 ordinary functions and whole classes can also be friends - friend void f(...); or friend class B; - use whole-class access for closely related implementations - narrower friendship still exposes less than making all fields public 6 a non-member operator function need not be a friend - ordinary public methods may provide all the access it needs - overloading and friendship solve different problems 10.4.18 Assignment operators 1 some overloadable operators have additional declaration rules 2 assignment is an expression operation in C and C++ - its result can participate in another expression - simple operator= must be a member - correction: compound assignments such as operator+= may also be non-members; the source incorrectly extends the restriction to them 3 an assignment operation normally returns the assigned-to object - commonly T&; the book's examples return const T& or void - return *this permits chaining without making an extra copy - operator= copies Complex's components - operator+= adds to the existing components compound operations are independent overloads - defining + and = does not automatically define += - preserve their expected mathematical relationship deliberately 4 assignment may accept a different source type - assigning double to Complex can set re to it and im to zero - copy assignment from the same class has special implicit-generation rules considered next 10.4.19 Implicit special members 1 ordinary record-like classes remain usable without handwritten constructors - the compiler can supply special members where their rules permit 2 implicit copying initializes members from corresponding source members - class-type members use their copying behavior - pointer members copy pointer values, not owned allocations - an implicit declaration need not be usable: a member can prevent it this section describes the book's older subset of special-member rules 3 a default constructor is implicitly declared if no constructor was declared - adding a constructor takes responsibility away from that default rule 4 default construction initializes class-type members through their defaults - ordinary scalar members are not thereby guaranteed useful values - explicitly initialize state that subsequent operations read 5 an implicit destructor destroys members as required by their types - a raw pointer's destruction does not delete its pointee 6 implicit copy assignment assigns corresponding members - class-type members use their own assignment operations - const or reference members can make implicit assignment unavailable - its ordinary return type is A&, correcting the source's const A& 7 omitting a copy constructor does not prohibit copying old-subset technique: declare copying and assignment private - outside code then cannot call them - references and pointers can still be passed - a noncopyable member can prevent implicit copying of its owner - friends and members still have private access - private empty definitions in the example should not be treated as valid implementations of ownership-preserving copying 10.4.20 Indexing operators 1 built-in a[b] corresponds to *(a+b) - a class can provide operator[] with its own storage interpretation - the book uses a member with one explicit index parameter 2 IntArray example: storage grows as an index requires - begin with capacity 16 - repeatedly double capacity until the requested index fits 3 private p and size hold storage and current capacity - destructor releases p with delete[] - copying and assignment are disabled to prevent shared ownership - Resize is an internal operation, not part of the client's interface 4 operator[] returns int& so an element can be read or modified - resize when idx >= size - then return p[idx] Resize: - calculate enough capacity, allocate replacement storage - copy existing initialized values, release old storage - install the new pointer and capacity - returned element references are invalidated by later reallocation correctness requirements omitted by the short example: - initialize elements before reading or copying their values - guard capacity doubling against overflow and impossible sizes indexing need not use integers or physically contiguous storage 5 the modifying index operation cannot serve a const IntArray - resizing changes the object - returning a modifiable reference would expose mutable contents 6 members may be overloaded by trailing const - non-const objects select the suitable non-const overload - const objects require the const overload 7 the read-only overload should not resize - return the stored value when present - return zero for an out-of-capacity index in this example 8 int operator[](unsigned int idx) const supplies that behavior - returns by value, so callers cannot assign through it - in-range values still need initialization before being read 9 const overloading is available for other member functions too 10 the author rejects general array-like container classes for his style - cites maintenance costs and tension with his view of hidden objects - this is a design opinion, not a defect inherent in all containers 10.4.21 Increment and decrement operators 1 prefix and postfix ++/-- need separate overloads - their conventional results differ even when the update is identical 2 prefix member form has no explicit parameters - operator++() or operator--() - a non-member version takes the operand as its one parameter 3 postfix form adds a dummy int parameter - member operator++(int) or operator--(int) - non-member form has the operand plus dummy int - the dummy parameter distinguishes the overload, not an increment size the example's calls select first, third, second, fourth in that order 4 usual prefix behavior: update and return the updated object by reference usual postfix behavior: - save a copy of the old value - update the original - return the saved value by value never return a reference to the local saved copy - it is destroyed as the function exits - preserving postfix semantics can cost more for large objects 10.4.22 The arrow operator 1 operator-> supports objects that behave like pointers - allows extra behavior around ordinary member access 2 in p->a, p is an expression but a is a fixed member name - the member name is not computed as another runtime operand - this motivates the author's description of member-specific access 3 operator-> is a member with no explicit parameters - returns a pointer, or another object supporting operator-> - the compiler repeats the operation until ordinary pointer access works - most wrappers simply return their stored pointer 4 Pointer_s1 owns an optional s1 pointer - constructor accepts a pointer or starts empty - destructor deletes the owned object - assignment from a raw pointer releases the old object and adopts new - copying the owning wrapper is disabled to avoid double deletion - operator* returns s1&; operator-> returns s1* local owner: acquired objects are cleaned up on normal function exit requirements for a correct owner: - do not dereference an empty wrapper - do not adopt storage already owned elsewhere - assigning its existing pointer must not delete and retain that pointer 10.4.23 Function-call operators 1 operator() lets an object use function-call notation - void operator()() means a call with no explicit arguments - the book defines this operation as a class member 2 Fun overloads calls with zero, one and two integer arguments - f(), f(100), f(25, 36) select the corresponding implementations - each prints its own parameters a callable object is often called a function object or functor 10.4.24 Conversion operators 1 constructors define conversion into their class - they cannot add a constructor to a built-in destination type - sometimes the source class can be edited but the destination cannot conversion members provide conversion out of the source class 2 operator int() const defines conversion from the class to int - its name already identifies the destination type - no separate return type is written - int x; x = a can then use the conversion 3 multiple implicit conversion paths can produce ambiguity - the author usually prefers explicitly named conversion methods - the following proxy example gives a specific reason for a conversion 10.4.25 Example: a sparse array 1 sparse array: most positions contain a common value, usually zero - storing only exceptions avoids allocating every possible position 2 SparseArrayInt exposes integer indexing - stores nonzero entries as a linked list of index/value pairs - linear search is acceptable only when that list is small enough - private representation permits replacing the search structure later 3 const indexing is straightforward - search for the index - return its stored value, or zero if absent 4 modifiable indexing has two different uses: read and write - both select the non-const operator[] on a non-const array - a missing zero element has no stored int to return by reference - returning an int value alone would prevent assignment through [] 5 creating a zero entry on every access would make assignment possible - but reading many absent positions would defeat sparse storage 6 remembering the last accessed node could permit later cleanup - repeated creation and removal would still cost time 7 operator[] cannot directly ask whether its result will be read or assigned - const overloading answers whether the array is const, not whether this particular expression is a read 8 return a small intermediate proxy object instead - stores the array's address and the selected index - postpones the actual access until its result is used 9 proxy conversion to int implements reading proxy assignment implements writing - absent index reads as zero - assigning nonzero creates or updates an entry - assigning zero removes its entry other modifying syntax needs corresponding proxy overloads - +=, both ++ forms, and analogous operations do not appear for free 10 Interm helpers: - Provide finds or creates the selected entry and returns int& - Remove deletes that entry if present 11 SparseArrayInt disables copying and assignment in this example - owns the linked list and deletes all nodes in its destructor - nested Interm and the array grant access needed for cooperation proxy implementation: - assignment removes zero, otherwise writes through Provide - += updates the value, saves the result, removes a resulting zero - prefix ++ returns the new value; postfix ++ returns the old one - conversion searches without creating a missing entry Provide: search first, otherwise prepend a new node - correction: initialize its value to 0 before returning the reference - the listing omits this, making += and ++ read an uninitialized int Remove: use a pointer to the link that leads to the selected node - redirect that link around the node and delete it - this handles the first node without a separate head case additional proxy case requiring an explicit operation: - arr[i] = arr[j] must assign the value read from the right proxy - implicit proxy copy assignment would merely copy proxy bookkeeping - a retained proxy also requires its owning array to remain alive 10.4.26 Static data members and methods 1 static members belong to the class independently of individual objects - can be used even when no instance exists 2 a static data member has static storage duration and class scope - normal public/private access rules still apply 3 one shared data member exists for the class - it is not repeated inside each object's storage 4 static int the_static_field inside the class is a declaration - the book's non-inline form also needs a definition 5 this resembles an extern declaration of a global variable - putting the class declaration in many modules must not allocate independent copies of the supposed shared field 6 define it once outside the class: int A::the_static_field = 0 - normally in one implementation file, not the shared header 7 public static members can be named through an object or as A::member - mutable shared state has the same coupling risks as globals - a static list head fixes one list for the whole class - later needing two independent lists can require redesign 8 the author recommends static data mainly for immutable shared information - transition tables, diagnostic strings or command tables - this is his design rule, not a restriction imposed by C++ 9 static method: a class-scoped function without an implicit receiver - mark its declaration static - do not repeat static on the out-of-class definition 10 call through Cls::TheStaticMethod(...) or through an object - there is no this parameter - non-static fields and methods still require an actual object - that object may be passed in, obtained elsewhere, or constructed 11 static methods retain the class's private access rights - access control is class-wide - private constructors plus a public static creation method can control how instances are made 10.5 Exception handling 1 the author distinguishes the useful exception idea from its implementation - criticizes runtime support, code size and throwing costs in C++ - actual costs depend on implementation and workload 2 some projects deliberately disable exceptions - the book retains the topic despite its preference for a small subset 3 exceptions can reduce the work needed for complete error propagation - compare against code that actually checks all failures - assess resource and performance costs for the application 4 exception handling is not unique to C++ - criticisms of this implementation do not disprove the general idea 5 the author proposes identifying exceptions by stable object addresses - offered as an alternative design, not C++ syntax - its claimed simplicity and performance are the author's argument 6 understanding exceptions remains useful for other languages and designs 7 the author recommends reserving throws for exceptional failures - repeatedly throwing for routine loop exits can be costly - ordinary return and explicit control flow suit ordinary completion 8 understand the mechanism's consequences before adopting it 10.5.1 Error situations and their handling 1 operations can fail because external preconditions do not hold - unavailable file, unreachable server, invalid mathematical input - failure need not imply a bug in the implementing function 2 detecting failure is easier than deciding the appropriate response - printing ERROR and exiting can destroy valuable user work - a failed editor save should not terminate the editor automatically 3 error reporting depends on the surrounding application - a terminal message, GUI interaction and a log have different uses - low-level or embedded code may have no direct reporting channel 4 the same failure can be fatal, recoverable or expected - ask for another filename - try another server - search the next directory after a failed file-open attempt 5 policy belongs at the level that understands the whole operation - reusable low-level functions report failure to their callers - designated application code decides about messages and termination 6 return-code propagation requires work at every intermediate call - f10 fails, f9 checks and returns failure, then f8, and so on - each function needs a way to represent and propagate that failure 7 the effort tempts programmers to omit checks - an ignored failure can appear later under difficult-to-reproduce use 8 exception mechanisms provide language support for this propagation task 10.5.2 The general exception mechanism 1 a return type may have no spare value for reporting failure - atoi cannot distinguish invalid input from valid "0" by its result exceptions add a different completion route - either produce the ordinary result or report exceptional failure 2 exceptions are independent of the OOP paradigm - several different language families provide related mechanisms - the book later connects them with more general continuations 3 a throw searches active calling contexts for a matching handler - intermediate functions need not repeat ordinary failure checks - their normal remaining statements are skipped while unwinding - f10's failure can reach a handler associated with f1 4 main can provide a useful outer handling boundary - it surrounds much ordinary application work - initialization before main and destruction afterward are outside it 10.5.3 Throwing exceptions 1 throw expression creates an exception - its type selects possible handlers - its value carries information about the failure - built-in values and suitable class objects can be thrown 2 line_count_in_file example: - open the named file - throw a const char* message if opening fails - otherwise read characters, count '\n', close and return the count this counts newline characters, not an unterminated final text line - a complete reader would also distinguish an I/O error from EOF throw 27 would instead create an int exception - dedicated exception classes usually express failures more precisely 10.5.4 Handling exceptions 1 handle a failure where the required recovery policy is known - code allowed to communicate with the user can request new input 2 a handler surrounds an interval of execution - applies to exceptions from its block and functions called indirectly - textual nesting of the throwing function is unnecessary 3 try { ... } is followed by one or more catch clauses - catch's parameter type identifies accepted exceptions - its name provides access to the exception value 4 file-counting main: - reject a missing filename before calling the worker - place the call and success output inside try - catch(const char*) prints the error and returns failure status on a throw, neither the worker's remainder nor try's remainder executes 5 an exception can originate arbitrarily far down the call chain - the active try block can still handle it 6 the thrown C++ string literal produces a const char* exception - catch(char*) cannot remove that const qualification 7 multiple handlers are considered in written order - the first suitable one handles the exception - only one of the sibling catch clauses runs - redundant handlers for an already covered case are ineffective 8 handler matching has different conversion rules from function calls 9 a catch clause handles throws from its associated try execution - an exception thrown by one catch is not handled by its siblings 10 without a matching handler, propagation continues outward - other active try blocks may provide the matching catch - an ultimately unhandled exception leads to termination 11 throw; rethrows the currently handled exception - useful after local work when the present layer cannot fully recover 10.5.5 Catch-all handlers 1 catch(...) accepts an exception regardless of its type - no named parameter exposes the value - place it after specific handlers - can provide an outer fallback for unknown library exceptions cleanup-and-rethrow example: - allocate an array before entering try - normal path deletes it after try - exceptional path catches anything, deletes it and uses throw; - throwing skips the ordinary delete after the handler without this cleanup, a raw pointer's scope exit would leak its allocation 10.5.6 Exception classes 1 failures often need several pieces of context - filename, operation description and saved errno - one integer or string is an awkward combined representation 2 unrelated subsystems may throw the same built-in type - type-only matching then cannot distinguish their different meanings 3 dedicated exception classes solve both problems - fields carry structured diagnostic information - distinct types identify different failure categories or subsystems 4 the exception object must survive the throwing function's scope - it is not a reference to a destroyed local object - copying, when required, must preserve its owned information - an implicit copy constructor is sufficient when members copy safely 5 FileException stores errno, a copied filename and a copied comment - capture errno before other operations can change it - private static strdup allocates with new[] and copies the string - copy constructor creates independent string allocations - destructor uses delete[] on both strings catch(const FileException &ex) avoids a second handler-parameter copy - query methods supply filename, comment and error code - strerror translates the saved code for reporting ownership details still need completion in production code - if the second allocation throws, release the first allocation - define or disable copy assignment to avoid shallow pointer assignment 10.5.7 Automatic cleanup 1 stack unwinding destroys fully constructed automatic objects it leaves - their destructors release the resources they own - removes many manual catch-cleanup-rethrow blocks 2 if f has a local A and calls g, a throw from g can unwind f - A's destructor runs during that unwinding - the same cleanup occurs on an ordinary return - cleanup is tied to object lifetime, not to a particular return statement 10.5.8 Exception type matching 1 handler matching does not perform arbitrary numeric conversions - catch(int) does not catch char or long exceptions 2 an exception object can be caught by reference - catch(A &ref) refers to the thrown A object - adding permitted const qualification is possible - catch(const char*) can accept char*, not the reverse - class inheritance provides another important matching relationship 10.6 Inheritance and polymorphism 1 methods and hidden state alone do not exhaust the book's view of OOP - the author calls that restricted approach object-based programming 2 inheritance adds related types and substitutable interfaces - the following runtime polymorphism differs from earlier overloading 10.6.1 Hierarchical domains 1 domain entities often fall into successively narrower categories - road users include pedestrians and vehicles - vehicles can have more specialized subcategories 2 properties of a category apply to its subcategories - all road users have relevant position and motion information - a particular vehicle model may have fuel and refuelling operations - freight vehicles additionally have load/unload operations choose categories and assumptions that actually fit the modeled domain 3 related structures need both shared and specialized fields and operations - hand-matching initial fields in C leads to fragile pointer conversions - inheritance supplies a language-defined relationship instead 4 first examine inherited data, then add inherited methods and behavior 10.6.2 Inherited structures and pointer polymorphism 1 inheritance specializes a more general concept 2 student derives from person - person supplies name, sex and year_of_birth in this example - student adds subject code, study year and average mark - the derived object contains its base subobject plus added state person: base/parent; student: derived/child 3 a student can be accessed through its person part - student* converts to a suitable accessible unambiguous person* - corresponding reference conversion also works - a function accepting person& can therefore receive a student the reverse is not automatic: an arbitrary person need not be a student - the language handles any required pointer adjustment - do not generalize the diagram into a universal zero-offset layout rule 4 the author calls this pointer or reference polymorphism - one operation can accept several related concrete types - other sources use narrower definitions of the word polymorphism 10.6.3 Methods and access in inheritance 1 inheritance works with both class and struct declarations - either can derive from the other - class here also means the OOP concept, independent of that keyword 2 public inheritance exposes the base interface as part of the derived type private inheritance makes that relationship an implementation detail - class B : public A and class C : private A express the distinction - access and implicit base conversions depend on that choice 3 default inheritance: public for struct, private for class - the book normally writes public explicitly for derived classes 4 a derived class does not automatically gain the base's private access - private base details remain the base implementation's responsibility 5 protected members form an interface for derived classes - accessible in the class, permitted derived contexts and friends - unavailable to arbitrary clients 6 protected is a published contract for subclasses - unknown future subclasses may depend on it - document it and change it as carefully as a public interface - private implementation has a more limited, identifiable set of users 7 inherited ordinary methods retain their base implementation - a truck can reuse its vehicle's refuelling operation - that operation need not know the truck's extra state 8 the inherited method receives a base view of this - conversion from the derived object supplies the appropriate base part 9 public derivation means the specialized object accepts its base's messages - clients can use the shared interface without knowing the subtype 10 two compatible views: - design: the derived object is a specialized base object - implementation: it contains a base-class subobject 10.6.4 Constructing and destroying derived objects 1 base construction precedes use by the derived constructor body - the derived body needs its base part to exist destruction reverses the order - the derived destructor body runs while the base still exists 2 the compiler arranges the base destructor after derived cleanup constructor arguments for the base go in the initializer list - B::B() : A(2, 3), i(4) initializes base A, then member i - the body executes after that initialization 10.6.5 Virtual functions 1 a derived object may need a different reaction to a shared message - virtual functions let the base interface allow that variation 2 graphics example: Pixel has coordinates, color, Show, Hide and Move Move algorithm: - Hide at the old position - change x and y - Show at the new position Circle initially derives from Pixel and adds radius - supplies circle-specific Show and Hide - constructor initializes inherited coordinates/color and its radius - protected fields make these values available to its drawing methods - the text later repairs the conceptual error of treating a circle as a specialized pixel 3 inherited Move would be ideal because its algorithm does not change - ordinary non-virtual calls inside Pixel::Move bind to Pixel's methods - merely adding Circle methods does not change those calls 4 that ordinary binding would erase and draw a point for a circle - the reused algorithm would perform the wrong concrete operations 5 declare Show and Hide virtual in the base - calls can select the override for the actual receiving object - descendants share the message but may change its implementation - constructors and static member functions cannot be virtual 6 common implementation: a virtual-function table - object contains hidden information identifying its class's table - a virtual call obtains the chosen function address through that table - this is an implementation model, not a prescribed memory layout 7 derived classes have corresponding tables with appropriate overrides - object construction establishes the appropriate dispatch information 8 Move now works through the shared algorithm - its virtual calls reach Circle's Hide and Show for a Circle 9 provide a virtual destructor for this polymorphic owning interface - derived destruction then works through a base pointer - overriding methods remain virtual even without repeating the keyword 10 virtual dispatch also works for calls outside the class - references and pointers may designate different derived types - when the actual type is known, the compiler may resolve directly without a table lookup while preserving behavior 11 p->Show() through Pixel* or Circle* selects the appropriate final override - caller need not list all concrete classes that might appear later 10.6.6 Pure virtual methods and abstract classes 1 a circle is not a kind of pixel - both can instead be kinds of graphical figure - each has color and an anchor position 2 the shared Move algorithm uses the anchor independently of shape 3 introduce a general figure base and derive both Pixel and Circle from it - this follows the domain relationship instead of borrowing an unrelated concrete class only for its fields 4 a shape without a particular form has no useful generic drawing body 5 the base can still implement Move using a required Show/Hide interface - concrete descendants must provide the missing behavior 6 virtual void f() = 0 declares a pure virtual member - marks an interface obligation for concrete descendants - it does not prescribe a literal zero table entry - pure virtual functions can have separate definitions in C++ 7 = 0 is the fixed declaration syntax - the author's dissatisfaction with it is a syntax preference 8 a class with an unimplemented pure virtual obligation is abstract - cannot create an object whose most-derived type is that class - a subclass remains abstract until it supplies the required overrides - abstract base subobjects can exist inside concrete derived objects 9 GraphObject stores anchor/color and declares pure virtual Show and Hide - supplies constructor, virtual destructor and the common Move - Move's virtual calls dispatch to concrete implementations 10 Pixel and Circle derive independently from GraphObject - both define Show and Hide - Circle additionally stores radius - declaring those non-pure methods without required definitions causes missing-definition problems at link time 10.6.7 Virtual calls during construction and destruction 1 construction proceeds through base and derived stages - the object cannot yet behave as a fully constructed later descendant 2 virtual calls on the object under construction/destruction use the current class's stage, not a more-derived override - base construction invokes base-stage behavior - base destruction occurs after derived-stage cleanup 3 do not rely on a descendant to finish work called virtually by a base constructor or destructor - virtual calls reaching a pure virtual function are invalid - avoid such calls when their lifetime behavior is unclear 10.6.8 Deriving a class for its constructor 1 a derived class can add only a convenient construction procedure - reuse the base's state and ordinary operations - example: construct a square using a polygonal chain 2 PolygonalChain stores relative vertex offsets in a private linked list - starts with no vertices - AddVertex prepends one vertex - reverse traversal still draws the same unoriented chain - Show and Hide interpret offsets relative to the inherited anchor - destructor walks the list and deletes every node as an owning class, copying needs either a real deep copy or prohibition 3 axis-aligned square of side a is a closed five-vertex chain - include the first corner again at the end - offsets describe the four corners around the chosen anchor 4 Square's constructor initializes PolygonalChain, then adds those vertices - drawing, hiding, movement and cleanup are inherited - this saves repeating the construction sequence at each use - inherited AddVertex can still alter the shape, so the example alone does not enforce a permanent square invariant 10.6.9 Virtual destructors 1 polymorphic deletion needs the destruction behavior of the actual object 2 GraphObject* can hold the result of new Square(...) - delete through that pointer must destroy the whole Square - virtual base destructor leads through Square, PolygonalChain and base - PolygonalChain then releases its allocated vertices without a virtual base destructor, this base-pointer deletion has undefined behavior; it is not merely a guaranteed call to the wrong destructor 3 the author recommends virtual destructors on polymorphic base classes - keeps future deletion through that interface correct - runtime representation costs depend on the implementation 10.6.10 More polymorphism 1 a scene may contain an unknown mixture of concrete graphical objects - types and count can come from a file or runtime generation 2 store an array of GraphObject* after determining scene_length - each initialized slot owns a Pixel, Circle, Square or other subtype - valid index range is 0 <= i < scene_length - Show, Hide and Move work through the shared interface cleanup: - delete each stored object through its virtual-destructor base - then delete[] the pointer array itself - construction-failure paths must also release objects already created behavior selected from the actual runtime type is dynamic polymorphism 10.6.11 Private and protected destructors 1 private destruction restricts access to members and friends protected destruction also permits the relevant derived-class contexts 2 ordinary outside automatic objects need an accessible destructor - making it private prevents that ordinary lifetime arrangement - a controlled heap-only interface can expose a Disappear method delete this requires a compatible dynamic allocation and careful ownership - no further object access afterward - no later second deletion through another owner private destruction also prevents ordinary derived construction/destruction unless friendship grants the needed access - protected destruction can permit derivation while restricting clients 3 applying the access policy throughout a hierarchy can enforce controlled destruction for ordinary clients - privileged members and friends retain their special access 4 this is a specialized lifetime-design tool - the author notes its usefulness without developing a full example 10.6.12 Overloading and name hiding 1 a declaration named f in a derived scope can hide base declarations named f - even a data member can hide a base method - the inherited member still exists - b.A::f(2, 3) explicitly selects the base declaration if accessible 2 a derived f(const char*) also hides a base f(int, int) - ordinary lookup does not combine these scopes into an overload set - b.f(2, 3) therefore fails in the example - explicit qualification works; using A::f can also expose base overloads 10.6.13 Bypassing virtual dispatch 1 explicit class qualification suppresses virtual dispatch for that call - A::f() calls A's implementation even on a B object - an unqualified f() still dispatches to the override example: b.g() and b.f() print second - b.h() and b.A::f() print first - pa->f() dispatches; pa->A::f() explicitly selects A useful when an override extends the base operation - explicitly call the base version, then add derived behavior 10.6.14 Explicit casts 1 C-style casts can conceal several different kinds of conversion - pointer reinterpretation especially needs careful reasoning - a cast does not establish object validity or permission to modify it 2 C++ named casts make the intended conversion category visible - syntax: cast_name(expression) const_cast changes appropriate const/volatile qualification - cannot convert an unrelated character pointer into an integer pointer - casting away const does not make a genuinely const object writable - first check whether a missing const-qualified interface is the problem 3 static_cast can perform a permitted base-to-derived pointer/reference cast - programmer must ensure the object has the required derived type - unrelated class pointers do not become related through this cast correction: static_cast also supports many ordinary conversions - it is not restricted to inheritance casts 4 reinterpret_cast expresses specified low-level reinterpretations - does not remove const - is not permission to convert absolutely anything into anything - valid storage access still depends on type, lifetime and alignment rules 5 dynamic_cast can check a polymorphic downcast at runtime - failed pointer cast yields a null pointer - avoids asserting an unverified derived type with static_cast 6 the runtime check uses type information associated with polymorphic objects - checked downcasts need a polymorphic source, e.g. a virtual method - ordinary unambiguous upcasts do not need this runtime mechanism 7 the author discourages routine repeated dynamic_cast use - prefers behavior expressed through the shared virtual interface - actual cost depends on implementation and hierarchy 8 failed dynamic_cast to a reference throws std::bad_cast - a reference has no null result to return - the book prefers pointer casting followed by an explicit null check 10.6.15 Exception hierarchies 1 inheritance supplies another relationship used by exception handlers 2 catch(const A&) accepts A and a suitably publicly derived B - the handler sees the base interface of the exception object 3 Error can be the root of a failure classification - UserError: input, filename, password, incompatible requests - ExternalError: storage, memory, I/O or network failures - Bug: broken program assumptions needing correction more specific subclasses allow more specific handling - IncorrectPassword handler handles that category - UserError handler handles its broader family - Error handler handles the whole hierarchy order catches from specific to general when both are present - prefer const-reference catching to retain the dynamic exception object - correction: catching a base by value can also match a derived exception, but copies only the base portion and slices it 10.7 Templates 1 duplicating nearly identical code creates repeated maintenance work - every fix must reach every copy - eventually one copy is easily missed 2 ordinary functions remove duplication when only values differ - parameters express the varying values - pointers/references can identify different variables to operate on 3 varying types are harder to express with an ordinary function - integer and floating-point elements need different operations/layout - C macros can generate variants but introduce their own difficulties 4 template: a parameterized definition used to produce functions or classes - common parameters are types; supported constant values are also possible - supply arguments to obtain a particular specialization - the author compares this generative role with sophisticated macros 5 templates support parametric polymorphism - their type-dependent work is resolved during compilation - they are useful independently of OOP 6 templates also support metaprogramming - describe how concrete program structures are to be generated - specialization can produce more than simple textual substitution 10.7.1 Function templates 1 bubble-sort example: - scan adjacent pairs from the end toward the settled prefix - swap when the later element is smaller - a pass without swaps proves the array is sorted integer and double versions otherwise have the same algorithm - differ in element pointer type and temporary swap variable type 2 template makes those types parameters of sort - T *array and T tmp replace the fixed int uses - class here means a type parameter, including built-in types - size, comparison and copying depend on the eventual argument type 3 sort and sort request concrete function specializations - any usable T must support copying, assignment and the comparison - the comparison must describe a suitable consistent ordering 4 instantiation produces the required function from the template - repeated calls to the same specialization do not require separate source copies of the algorithm 5 template argument deduction can infer T from the array argument - sort(a, 30) can select sort for an int array - the book's claim that class arguments always require explicit spelling belongs to its older C++ subset 10.7.2 Class templates 1 generalize SparseArrayInt instead of copying it for every element type - SparseArray shares the same storage/proxy design 2 a generic element type need not have a usable numeric zero - constructor accepts a default value and stores it as defval - entries equal to defval need not be stored 3 the possible operations on an unknown T are not limited to integer operators - begin with assignment rather than pretending to implement all behavior 4 accept generic values through const references where appropriate - their copying cost is not known in advance 5 SparseArray stores Item nodes with T values, plus first and defval - nested Interm holds SparseArray* and the selected index - conversion supplies a T value; assignment updates/removes the entry - destructor releases nodes - out-of-class definitions begin template and qualify the relevant specialization, e.g. SparseArray::Interm correction to the listing: - the assignment definition must use const T& to match its declaration - C++ also permits the injected class name in appropriate class scope; the book's rule to spell everywhere has exceptions 6 the full remaining example implementation is in the accompanying archive - its operations follow the preceding sparse integer design 7 an unknown element type makes a complete proxy interface difficult - its operations need not match the finite integer operator set 8 class-template member bodies are generally instantiated when required - an unused dependent <<= implementation need not invalidate an otherwise usable SparseArray - actually requesting that operation requires T to support it - <<= updates through Provide and removes a result equal to defval 9 arbitrary fields and methods cannot all be forwarded by this proxy - array[idx].re and array[idx].GetRe() operate on Interm itself - . cannot be overloaded to redirect the operation - returning a real T& recreates the missing-element storage problem 10 const indexing returning T by value has another trap - calling a modifying method changes only the temporary result - it does not update the array element - a compile-successful expression can therefore conceal lost work 11 changing a parameter from mutable reference to const reference can expose that difference without producing a diagnostic 12 for a reference-like read interface, return const T& from const indexing - prevents direct modification through the returned access - a stored entry can supply its value reference - an absent entry can refer to the owner's stored defval - those references still depend on owner/node lifetime 13 for pointer-like element types, forwarding operator-> can be useful - it does not solve arbitrary forwarding through the dot operator 14 this template still imposes concrete requirements on T - construction used by node allocation - copying, assignment and equality comparison with defval - the exact required operations depend on the implementation used 15 document a template's requirements - generic does not mean valid for every imaginable type 10.7.3 Template specialization 1 specialization supplies a different implementation for selected arguments - use it instead of the general definition in those cases 2 string-pointer sorting needs lexical comparison, not pointer comparison - factor comparison into a sort_less helper template - ordinary T uses a < b - the sorting algorithm stays unchanged 3 explicit specialization begins template<> - sort_less uses strcmp(a, b) < 0 - applies to const char* specifically - char* is a different template argument and needs appropriate handling 4 class specialization can replace representation as well as operations - SparseArray can store indexes of exceptional bits only - with default false, presence means true - with a configurable default, presence means the opposite of that default partial class specialization leaves some parameters variable - Cls fixes only the second parameter - Foo recognizes pointer arguments and binds the pointed-to type 5 function templates do not permit partial specialization - class templates do - declare the primary before its specializations and make a needed specialization available before instantiating that case 10.7.4 Example: folding sequences 1 templates allow the earlier fold idea to apply to several representations 2 sequence elements have a consistent element type for each instantiation 3 a position abstraction must support three actions - obtain the current element - obtain the next position - determine whether the sequence has ended linked list: a node pointer supplies position; null means empty 4 array position also needs a boundary - the example stores an element pointer and remaining count 5 other possible sequences include file input and generated values Pos interface: Get, Next and Empty - Next returns a new position value - position copying must have suitable semantics - do not use Get or Next after Empty reports true 6 ListPosition stores a node pointer - Get returns data; Next follows next; Empty checks null ArrayPosition stores pointer and remaining count - Get dereferences, Next advances/decrements, Empty checks count generic folds take Pos, Elem and Res template parameters - element type and accumulated result type may differ - both examples call func(element, accumulated_result) right fold: - recurse over the tail first, then combine the current element left fold: - combine the current element with the accumulator first, then recur - empty sequence returns the supplied initial result - recursive implementation can consume stack; C++ does not promise tail-call elimination 7 sum and product use corresponding combining functions - initial sum = 0; initial product = 1 - array 1..10 gives 55 and 3628800 - left/right folds agree here within the arithmetic's valid range 8 make_il takes an integer and a tail pointer, allocates a new head - right fold builds a linked list from the array - initial result must have pointer type for deduction, e.g. (int_item*)0 9 each result node points to the already constructed tail - right fold preserves original element order - ownership of the resulting nodes belongs to the resulting list's user 10 the same prod function folds the resulting list - only the position adapter changes - the combining function does not know whether storage is array or list 11 printing is a side effect, but the example can still use a fold - left fold invokes the printing function in forward element order - right fold invokes it in reverse order - its nominal pointer result only satisfies the fold's accumulator type other possible folds construct copies, reverse lists, filter or transform 12 these particular tasks may be simpler as direct loops - the example demonstrates the paradigm and template abstraction - it does not claim that folding is always the best implementation 10.7.5 Constant template arguments 1 templates can accept permitted compile-time values as well as types - an array length can become a template argument - sort and sort then become distinct specializations - choose this only when compile-time distinction is useful 2 MultiMatrix: an automatically growing N-dimensional array - T is the stored element type - init_val is the common initial element value - dim is the compile-time dimension count general indexing returns a reference to a matrix of dim-1 dimensions - specialize dim == 1 to return an element reference - the design requires a positive dimension count 3 store pointers to lower-dimensional matrices - create a child only when a mutable access needs it - null means that whole child region still has default values 4 Array supplies the common growing one-dimensional storage - initially empty, carrying its element initial value - mutable indexing grows capacity from 8 by doubling as needed - copies old elements and initializes every newly allocated element - const indexing returns a const reference to an existing element or init - copying/assignment of the owner are disabled MultiMatrix's general form uses Array initialized with null - mutable indexing creates the child on demand, then returns *child - const indexing returns an existing child or an empty dummy - dimension recursion happens through distinct template specializations 5 MultiMatrix owns the pointed-to children - its destructor deletes each existing child - Array's destructor releases only the pointer array - both levels of ownership therefore need their cleanup 6 const access must not dereference a null child pointer - a static empty dummy represents the missing submatrix - return it as const so the caller cannot populate shared dummy state 7 one-dimensional specialization wraps Array initialized with init_val - mutable [] returns T& - const [] returns const T& - constness selects the corresponding underlying Array operation 8 for dim == 1, inheritance from Array can remove forwarding methods - the constructor merely supplies init_val - higher-dimensional indexing differs because storage contains pointers while the interface returns references to their pointed-to matrices 9 storing child matrices directly would complicate resizing - the current Array implementation assigns its elements - child owners deliberately disallow copying/assignment - deep-copying their entire trees at each resize would be expensive 10 MultiMatrix demonstration: - assign 193 and 251 at two five-index positions - those positions read back their assigned values - untouched positions read -1 - output: 193 251 -1 -1 - mutable reads can allocate missing paths even when the value is default 11 non-type template arguments must obey the selected language version's rules - the book emphasizes integer constants and permitted object/function addresses - a local runtime address cannot supply a compile-time specialization - the example's T and init_val must form a permitted argument pair - the book's narrow catalogue and rarity claims reflect its older subset 12 the author again objects to generic containers as a design practice - the multidimensional array is an instructional example of templates - that objection is his opinion, not a general C++ correctness rule 10.8 Returning to programming paradigms 1 organize the language mechanisms just studied by the ways of thinking they support 10.8.1 C++ and the range of paradigms 1 apply the earlier seven-level scale of language/paradigm compatibility 2 the author argues that C++ strictly imposes few programming styles - considers compilation its assumed execution model - this is the book's model, not a requirement to use a particular ahead-of-time implementation for every C++ environment 3 C++ strongly encourages imperative programming in practice - avoiding assignments entirely is possible but often inconvenient 4 the author classifies several paradigms as actively rewarded - OOP and abstract data types - exceptions - generic programming through templates 5 ordinary preprocessing is supported, though not preferred in this account 6 many additional paradigms can be expressed with suitable effort or libraries - no complete list of paradigms establishes an exhaustive answer 7 the author gives no definite example of an entirely prohibited paradigm - that is not proof that all paradigms fit equally well 10.8.2 OOP and ADTs 1 distinguish support for objects/messages from support for abstract values 2 shared mechanisms: - access control, constructors and destructors ADT-oriented mechanisms in the author's classification: - control over default construction, conversion, copying and assignment - operator notation for user-defined values these help an abstract type behave naturally beside built-in types 3 methods make the object/message interpretation explicit - ADT operations could instead be appropriately privileged free functions - the author considers methods important when teaching OOP thinking 4 the author's fuller OOP model adds inheritance and virtual dispatch - related objects respond through a shared message interface - this classification explains intended uses; features can participate in designs that mix several paradigms 10.8.3 Polymorphism without mystification 1 two common descriptions of polymorphism: - one operation accepts several types - one notation selects different operations according to type 2 + illustrates the second description naturally - integer addition, floating-point addition, matrix addition and string concatenation may have unrelated implementations 3 the narrower operation-selection definition omits ordinary base conversion - a derived object can satisfy a base interface without changing the implementation of a non-virtual operation 4 the author accepts both uses of polymorphism - interpret the term using the surrounding technical context 5 crucial distinction: when selection occurs - static polymorphism: selected during compilation - dynamic polymorphism: selection depends on runtime information 6 virtual methods provide the chapter's runtime dispatch mechanism - the actual object's type determines the applicable override 7 ordinary function/operator overloading is ad hoc static polymorphism - explicitly supplied implementations cover particular argument cases - adding a new case requires an appropriate declaration or conversion 8 templates provide parametric static polymorphism - one definition accepts an open set of suitable argument types - the type-dependent operations determine which types are suitable 9 base pointer/reference conversion also belongs to the author's static category when using his broader definition of polymorphism 10.8.4 Inheritance as set inclusion 1 method call and message sending describe the same interaction at different levels of explanation 2 view a class as a set of objects satisfying its conditions - a substitutable derived class describes a subset - every instance in that subset also satisfies the base interface - the converse need not hold 3 inheritance specializes a general case - superclass names the containing conceptual set - subclass names the more restricted conceptual set 4 implementation containment points in the opposite direction - the derived object contains its base subobject - the conceptual derived class is contained in the base class's set 5 keep these two models separate - subclass/superclass: classification of objects - base subobject/derived storage: physical implementation relationship - both are useful, but mixing them creates apparent contradictions 10.9 Formatting C++ code 10.9.1 Naming conventions 1 the book distinguishes C-style entities from class-related names - C tradition uses lowercase words and underscores - its classes and methods use mixed-case names with word boundaries marked by capitals - these are conventions, not language syntax requirements 2 ordinary functions and variables retain lowercase_with_underscores - macros use uppercase to stand out - the author prefers language facilities over macros where practical - include guards and conditional compilation remain preprocessing uses - the source's use of 0 for null belongs to its older C++ convention 3 one cited convention uses UpperCamelCase for classes - lowerCamelCase with at least two words for ordinary methods - lowercase_with_underscores for data members 4 the author instead uses UpperCamelCase for both classes and methods - accommodates single-word methods - constructor/destructor names already follow their class names - consistency within the chosen convention is the practical objective 10.9.2 Formatting class definitions 1 access labels add a formatting choice - the author aligns public:, private: and protected: with class braces - all member declarations receive the same single indentation level avoid making equally nested members appear at different depths - changing access does not introduce another containing scope 10.9.3 Formatting constructor declarations and definitions 1 initializer lists distinguish constructor formatting from ordinary functions - decide where the list begins and how long lists wrap 2 usual out-of-class style: initializer list starts on its own indented line - colon can begin that line - several alternatives are stylistically possible keep continuation indentation regular - do not create arbitrary depths merely to align a name after punctuation one compact option: align a leading colon and subsequent leading commas - each initializer occupies a clearly marked line long horizontal lists can wrap at sensible boundaries - grouping base and member initializers can improve readability - preserve the actual declaration/construction order - formatting must not suggest that writing order changes member order 10.9.4 Method bodies inside class definitions 1 member bodies may be inside or outside the class definition - in-class definitions are inline under the book's model - machine-code substitution is still an optimizer decision 2 keep the class's visible interface compact - readers should quickly see its available operations - longer implementation bodies belong outside the class definition - the author suggests usually one line, occasionally two or three inside header bodies can increase compilation work across modules - inline rules do not imply every translation unit contributes a permanently separate final executable copy 3 short accessor bodies can share a line with their declaration - a short body can instead occupy one indented following line - a small multiline body may put { on the declaration line - compactness can justify limited departures from ordinary function style if compression obscures the code, move the definition outside the class - explicit inline remains available where its definition rules fit 10.10 Example: TCP chat server 1 objects are a natural option when a task is organized around events - events identify responsibilities that different objects can implement 2 example: select-based TCP chat server - ask each connected client for a name - broadcast later lines with that name to connected participants - simulations and network event loops both motivate event-oriented designs 3 example omits command features such as rename, list users, and leave - focuses on object organization - a command prefix such as / could distinguish commands from chat text 4 one object owns the event-selection loop - other objects receive and handle events - separates waiting/dispatch from application-specific reactions 5 lower layer supports descriptor readability and writability - chat example uses readable events only - a handler object records the associated descriptor 6 timeout and signal events would need additional abstractions - their interfaces differ from descriptor-ready notifications - author cites his Sue library as a larger example of the overall design 7 first layer: - FdHandler: descriptor and event-handling interface - EventSelector: registration, readiness selection, main loop 8 application layer: - ChatServer represents the listening socket and connected sessions - ChatSession represents an accepted client connection - both specialize FdHandler - server coordinates broadcasts between session objects 9 FdHandler describes how to react to descriptor events - concrete behavior belongs to a derived class - design this interface without embedding chat-specific responsibilities 10 selector and derived handlers need access to the descriptor - supply it through the constructor - GetFd exposes its value - no setter: changing it behind the selector would invalidate registration 11 ownership is explicit - own_fd indicates whether destroying the handler must close the descriptor - supports either owned or borrowed descriptors 12 interest in readiness can change during operation - WantRead defaults to true - WantWrite defaults to false - normally request writable events only while output is queued - virtual queries let derived handlers choose their policy 13 Handle(read_ready, write_ready) is pure virtual - FdHandler is abstract - virtual destructor closes fd only when own_fd is true - GetFd is a const observer - trivial methods can be defined directly in the class EventSelector registration storage: - array indexed by descriptor number contains FdHandler pointers - allocate lazily on the first registration - retain capacity and maximum registered descriptor - selector manages registrations, not the handlers' application lifetimes 14 BreakLoop requests orderly loop termination - sets quit_flag instead of terminating the process directly - Run clears the flag when starting - caller can regain control for cleanup after Run returns 15 EventSelector interface: Add, Remove, BreakLoop, Run - destructor releases the pointer array, not the registered objects Add: - initial capacity is at least 16 and must include the descriptor index - initialize unused entries to null - grow and copy entries when necessary; clear new unused positions - update max_fd and register the handler Remove: - verify that the indexed entry is the requested handler - clear it; if it was max_fd, scan backward to the last occupied slot Run: - rebuild read/write sets from each handler's current interests - select(max_fd+1, ...) waits for readiness - EINTR retries; other select errors end this simplified loop - dispatch Handle for registered descriptors reported ready - stop when quit_flag is set Implementation conditions: - descriptor indices must fit FD_SETSIZE when using fd_set - initialize/guard empty-selector state before running or removing - registration changes during callbacks require careful lifetime handling Upper-layer ownership: - ChatServer accepts connections and creates ChatSession objects - retains a list of live sessions for broadcast and deletion - a disconnected session asks the server to remove it 16 ChatServer is the application-level manager of each ChatSession - make session operations private and declare ChatServer a friend - EventSelector sees only the FdHandler interface - private overrides can still implement public virtual dispatch 17 server needs a prepared listening descriptor before construction - private constructor prevents creating an unprepared server - static Start performs socket/bind/listen setup - failure returns a null pointer; success returns a server object 18 session's name field also identifies its protocol stage - initially null -> next line is the chosen name - later lines are chat messages - welcome new user; notify others about arrivals and departures 19 SendAll(message, except) broadcasts to the session list - null except means include everyone - session Send sends text to one client 20 named limits in the example: - max_line_length = 1023 - listen queue request = 16 Session helpers: - ReadAndIgnore discards the rest of an overlong input line - ReadAndCheck appends new bytes to the current input buffer - CheckLines extracts all complete lines, retaining an unfinished suffix - ProcessLine applies the name/chat protocol Server startup: - socket(AF_INET, SOCK_STREAM, 0) - set SO_REUSEADDR; bind the chosen port on INADDR_ANY - listen, then construct/register ChatServer - close the socket if setup fails - complete code must check setsockopt/listen and allocation failures too Server lifetime: - constructor initializes the session list and registers itself - destructor unregisters/deletes each session and list node - unregister itself; base destructor closes its owned listening socket Accept handling: - readable listening socket -> accept a client - construct a session and list entry, then register the session - peer address could be retained for logging/administration 21 RemoveSession: - unregister the handler before destroying it - locate its list entry through a pointer to the incoming link - unlink and delete both session and entry SendAll: - traverse live sessions, skipping except Session Send: - sample calls write once for the whole message - this can block or write partially; a robust event loop queues output and uses nonblocking writable events as described earlier Session lifetime: - constructor clears buffer state, starts with no name, and sends prompt - destructor releases the name; base destructor closes the owned socket Handle: - if buffer filled without a complete line, reset it and enter ignoring mode - choose ReadAndIgnore or ReadAndCheck ReadAndIgnore: - read a chunk and search for the next newline - discard everything through it; retain any following bytes - leave ignoring mode and process any now-complete lines ReadAndCheck: - append into unused buffer capacity - on successful read, update buf_used and call CheckLines - EOF/fatal error: announce departure if named, then request removal - distinguish retryable read errors from disconnect in complete code - after removal, return without accessing the destroyed object CheckLines: - locate newline, replace it with zero - remove a preceding CR when present - process the line, shift remaining bytes with memmove - repeat for every complete line; preserve final fragment ProcessLine: - first line becomes an owned copy of the name - send personal welcome and broadcast arrival to the other sessions - later line becomes " text\n" and is broadcast to everyone - temporary message arrays are deleted after use Program entry: - create selector; Start server on the example's fixed port 7777 - report startup failure; otherwise call Run - complete application also arranges shutdown/cleanup and output errors - source archive places the implementation in cpp_chat modules 10.11 Graphical user interfaces 1 many users expect a graphical interface - the author's broad criticism of GUIs is a personal assessment - graphical interaction still has conventions that users must learn 2 programmers need to provide a GUI when the application requires one - event-driven architecture, C++ and objects now supply the background 3 OOP and graphical interfaces have a close historical connection - Smalltalk helped develop object-oriented interactive environments - windows, buttons and other widgets fit an object/message model - the text's sweeping historical priority claims are simplified 4 building directly on a window system requires much detailed work - establish a connection and create windows - draw controls, labels and visual feedback - interpret mouse and keyboard events - maintain appearances when a control is pressed or released 5 widget libraries implement this common machinery - create controls, arrange them and specify application responses - library handles much drawing and routine input behavior - application callbacks implement the events with domain meaning 10.11.1 Introducing FLTK 1 FLTK: Fast Light Toolkit, a C++ widget library - selected because it fits the book's restricted C++ approach - concepts learned with one toolkit also help when learning another 2 the examples target the FLTK 1.3 series, especially 1.3.5 - version and development-history statements describe the book's period 3 the source describes installing development headers and libraries - its Debian package example is libfltk1.3-dev - custom installation paths require appropriate -I and -L options - compiling examples assumes the toolchain can find FLTK 4 window: a rectangular graphical-system surface - top-level windows are independent application surfaces - the window manager normally supplies their decorations - child windows live inside other windows - an application may have several top-level windows, including dialogs 5 widget: a distinct interface element - button, checkbox, text field, label or containing group - widgets may contain other widgets FLTK treats a window as one kind of widget - most ordinary controls are drawn within a window - they do not each need a separate native child window 6 hello example: a window titled hello, containing Hello, World! - Fl_Window represents the window - Fl_Box displays the text - Fl supplies common static library operations and event handling 7 include the headers for each class used - create a 300 by 100 window - create its Fl_Box while the window is the current group Fl_Window derives from Fl_Group - widgets created while a group is current become its children - end() finishes that implicit addition interval 8 Fl_Box constructor takes x, y, width, height and optional label - ordinary coordinates are relative to the containing window - the example's box fills its window 9 labelsize(36) enlarges the displayed text 10 end() completes construction of the group's contents show() displays the window, establishing graphical-system access as needed Fl::run() enters the event loop - return its result as the process status in this example 11 the source builds with g++ and links -lfltk - run the resulting executable to see the window - Escape uses FLTK's default window-closing behavior in this example - decorations can differ with the window manager 12 the initial window moves but has no configured resizing behavior - resizing policy is introduced later 13 the short example embeds dimensions and font size as literal constants - later examples give layout quantities names 10.11.2 Buttons and callbacks 1 Fl_Box is normally an output widget - displays information rather than soliciting an action - its displayed information may still change during execution 2 input widgets respond to user actions - begin with an ordinary button activated by clicking it - an input widget can also be disabled temporarily 3 users may understand graphical controls differently from their developers - design the interface with the user's interpretation in mind 4 Fl_Button constructor follows the common widget pattern - x, y, width, height, label 5 FLTK supplies the button's pressed/released visual feedback - the application must supply the meaningful action 6 callback signature: void function(Fl_Widget *w, void *user) - w identifies the initiating widget - Fl_Widget is the common widget base type - user carries application-specific context 7 register a function and context with the widget's callback method - on activation FLTK supplies the widget and saved context 8 the example prints to stdout to keep event handling visible and short - a normal GUI application cannot assume the user sees its terminal 9 three buttons: Say hello, Say goodbye and Quit - two share a callback that prints the string carried by user - Quit can hide the enclosing top-level window Fl::run finishes when no displayed application windows remain - hiding the one main window allows ordinary return from main - more orderly than calling exit from the button callback finding the intended window: - parent()->hide() works only if the immediate parent is the window - walking parent links to the outermost widget tolerates nested groups layout uses named width, height, spacing and font-size constants - window width = one button width + two margins - height = three button heights + four gaps/margins - loop builds equal buttons and advances y by height + spacing retain button pointers to configure callbacks - message context differs for the first two buttons - Quit needs no message context 10 finish the group, show the window and run the event loop - the full example is speak.cpp in the source examples 10.11.3 Other button types 1 several controls derive from Fl_Button - share its interface while offering different interaction behavior 2 Fl_Check_Button: a checkbox with a label - clicking toggles its checked state 3 radio buttons represent mutually exclusive choices - selecting one clears the others in its group 4 Fl_Radio_Round_Button supplies the familiar circular indicator - Fl_Radio_Button provides similar selection behavior with button styling 5 FLTK radio grouping follows the common parent widget - separate Fl_Group parents establish independent sets of choices 6 the demonstration combines radio buttons, a checkbox and ordinary buttons - chosen radio determines a box's background color - checkbox determines whether the box displays A - Set applies the choices; Quit closes the window 7 pass all relevant widget pointers in a controls structure - callback receives that structure through user - avoids global mutable widget pointers parallel constant arrays associate radio positions with colors and labels Set callback: - use value() to find the selected radio button - set the box color from its corresponding entry - label is A when checked, otherwise an empty string - callback context must outlive its use by the widgets 8 derive layout from six named dimensions/style values - radio controls and checkbox occupy the left column - color box fills the remaining upper region - Set and Quit occupy the bottom row box setup: - large white label - FL_FLAT_BOX supplies a filled rectangular background - without a drawing box type, a label-only box remains transparent register Set with the controls pointer, then end/show/run the window - changing state and requesting redraw are distinct operations; redraw explicitly when the changed property requires it 9 the same callback could be registered on the options for immediate updates - the author prefers an explicit Set action - that is a UI-design preference; choose the behavior for the task 10.11.4 Text input widgets 1 three relevant input classes: - Fl_Input: one line - Fl_Multiline_Input: a simple multiline field - Fl_Text_Editor: a fuller text editor 2 Fl_Input takes coordinates, dimensions and an optional label - the default label appears to the left, outside the input rectangle - leave space for it or position a separate label widget 3 value() returns the current text as const char* - value(text) replaces it with the supplied text 4 demo: input field with print, clear and quit buttons - pass the input widget pointer to callbacks as user context 5 keyboard focus identifies the widget receiving typed input - buttons also use keyboard events, e.g. Space to activate - Tab and Shift-Tab move between focusable controls - a visual focus indicator shows the active recipient 6 clicking a button can move focus away from the input field - the print callback reads value(), then calls take_focus() - the clear callback sets value(""), then restores focus layout reserves space for the input's Type: label - input and button dimensions derive from named constants - both callbacks receive the same input object typing followed by Enter should perform the natural primary action - requiring a mouse click after typing interrupts that interaction 7 Fl_Input can invoke the same print callback directly - when(FL_WHEN_ENTER_KEY | FL_WHEN_NOT_CHANGED) - Enter triggers the callback even if the text did not change - the default focus-change trigger would serve a different purpose 8 position(): get or set the insertion cursor - two-argument form also sets the opposite selection boundary mark(): get or set that other boundary - equal cursor and mark positions mean no selection 9 size() without arguments reports text length - do not confuse it with widget size(width, height) 10 replace(begin, end, text) edits a half-open range - equal positions insert without deleting - empty replacement deletes the selected range - cut and insert provide convenient editing forms - undo reverses an edit according to the widget's supported undo behavior 11 additional operations are documented by the toolkit 12 Fl_Int_Input and Fl_Float_Input constrain numeric input syntax - still validate that the resulting text is a complete acceptable value Fl_Secret_Input masks displayed characters for password entry - these retain the general Fl_Input interface 13 Fl_Multiline_Input displays embedded newlines as separate lines - still exposes text as a C-style string - limited visible area can hide content without scrollbar controls 14 wrap controls display of long lines - enabled: wrap at whitespace - disabled: show the visible portion of the original line - a very long unbroken word still needs consideration 15 for multiline input, place a label appropriately above the editing region - keep Enter available for inserting newlines - do not blindly reuse the single-line submit-on-Enter behavior 16 Fl_Text_Editor suits more substantial editing and supplies scrolling - text is held in a separate Fl_Text_Buffer - buffer->text() returns an allocated copy - caller releases that copy with free, as this API requires - do not infer the buffer's internal representation from this interface 17 create a buffer and attach it to the editor with buffer(buf) print callback: - obtain the allocated text copy - write/flush the output, free the copy, restore focus clear callback: - replace buffer contents with an empty string, restore focus one buffer may be shared by several editor/display widgets - an editor can also be switched among several buffers - manage the buffer's lifetime separately from each displayed view 18 the chapter leaves the editor's larger feature set to toolkit documentation 10.11.5 Boxes and labels 1 Fl_Widget supplies common presentation properties - colors, box style and labels - particular widget types interpret or ignore properties as appropriate - Fl_Box is specifically useful for a drawn box/frame and optional label 2 box() chooses the frame/background style - box styles fill the interior with the widget background color - frame-only styles draw a border without filling the interior - FL_NO_BOX draws neither, so background color has no filling effect 3 color() selects a background color value - named colors include the ordinary primaries and dark variants - semantic values include foreground, background, inactive and selection - fl_rgb_color(r, g, b) constructs a color from component values 4 labelcolor() separately selects the label text color 5 label(text) retains the supplied text pointer - its storage must remain valid and suitable while used copy_label(text) copies the text into library-managed storage - appropriate for generated results or short-lived application buffers - a permanent string literal normally needs no extra copy 6 constructor-supplied labels also retain their text pointer - the same lifetime requirement applies 7 @ introduces a built-in graphical symbol within a label - write @@ when a literal at-sign is required by this label syntax 8 built-in symbols can be resized, reflected and rotated - further symbols can be added through the toolkit's drawing support 9 symbol modifiers follow @ before the symbol name - signed size adjustment, e.g. -9 through +9 - $ reflects horizontally; % reflects vertically - keypad direction digit or zero-prefixed angle selects rotation keypad examples: 6 faces right, 8 up, 4 left, 2 down - the longer numeric form supplies an angle in degrees 10 @8>> and @00090>> point the double-arrow symbol upward - @2>> and @00270>> point it downward - @+93>> enlarges it and points it down-right - @$--> reflects an arrow; @%fileprint flips the printer symbol 11 the labelpics example demonstrates combinations of these modifiers 12 symbol parsing expects symbols at label boundaries - a leading symbol ends at the separating space - a trailing symbol uses the remaining symbol text - text can sit between leading and trailing symbols - account for the parser's spacing conventions in the book's version 13 align() combines FL_ALIGN_ flags to position the label - boxes/buttons normally center labels - input fields normally place labels to the left 14 FL_ALIGN_INSIDE moves alignment to the widget's interior - combine with directions using bitwise OR - INSIDE | BOTTOM puts the label just inside the lower edge - BOTTOM alone places it below the widget - distinguish corner/side variants when selecting combined flags 15 FL_ALIGN_WRAP wraps labels within the allocated width - explicit newlines also create multiline labels 16 labelcolor and labelsize set label color and font size 17 labelfont selects a font family/style - Helvetica, Courier, Times and Screen are the examples - supported bold/italic variants have predefined identifiers - the book also combines family/style numeric constants 18 Helvetica is sans serif; Times has serifs; Courier is monospaced - monospaced text is useful for source code and alignment-sensitive text - the author's screen/print preferences are typography recommendations 19 the author found Screen selection unpredictable in his environments - uses Courier when an explicitly monospaced display is wanted 20 the fonts example displays available variants - exact appearance depends on the graphical platform's fonts 21 labeltype selects label rendering effects and more complex label forms - shadow, engraved and image-related presentations are examples 22 some controls rely on their drawing style for correct repainting - arbitrary decorative box changes can disrupt input-field rendering - preserve the functional appearance of interactive controls 10.11.6 Output widgets 1 labels can show results but their text is not normally selectable - generated label text needs appropriate lifetime/copy handling - users often need to select and copy an actual output value 2 Fl_Output provides a non-editable single-line text field - Fl_Multiline_Output provides its multiline counterpart - these retain selection/navigation behavior while disabling editing - the simple multiline output lacks full scrollbar facilities 3 selectable output belongs in value(text), not the widget's label - value copies the supplied text - the application can then reuse or release its source buffer 4 output text follows input-like left alignment - wrapping is available - these controls do not offer the label's full positioning freedom 5 make read-only results look read-only - FL_FLAT_BOX avoids the usual editable-field appearance - matching the surrounding background makes the border unobtrusive retain a filled box style - text controls erase old content by repainting their box - FL_NO_BOX or frame-only drawing can leave old text artifacts 6 Fl_Text_Display suits larger scrollable text views - uses Fl_Text_Buffer, possibly shared with other views - append adds successive messages to the buffer - connected views reflect buffer changes 10.11.7 Resizable windows 1 resizable windows require an explicit policy for their contained widgets - decide what stretches, moves and stays fixed 2 the source presents FLTK's geometry-based scheme - its ease of use depends on the layout being expressed 3 Fl_Group manages child resizing - Fl_Window inherits that capability 4 resizable(widget) identifies a reference rectangle for the group's changes - can name one child or the group itself 5 resizable(0) disables automatic resizing of the group's children - on the simple window setup this corresponds to a fixed-size window - choosing the group itself makes its children scale with its geometry 6 choosing a contained resizable widget distributes changes by overlap - horizontal overlap determines horizontal stretching - vertical overlap determines vertical stretching - controls outside those ranges keep their sizes but may move 7 diagram's central R changes in both dimensions - A, B and H change width only - D, E and F change height only - C and G keep their sizes 8 nested groups and invisible widgets can express more complex policies - deriving the right group structure may require thought 9 useful patterns: - isolate a fixed-size control in a non-resizing group - use a zero-height invisible reference box for horizontal-only growth - use the symmetric zero-width arrangement for vertical-only growth 10 such patterns require deliberate construction of the group hierarchy 11 a window is also a group - parent() identifies a widget's containing group - ordinary controls need a path into a displayed window 12 current group determines the parent of newly created widgets - constructing a group makes it current - begin() selects that group again - end() selects its parent, or no group if there is no parent - Fl_Group::current provides explicit access to this setting 13 add can attach an existing widget directly - more commonly construct children immediately after their group - call end(), then continue constructing the parent's remaining children 14 window shrinking can stop at an automatically selected minimum - the resize demonstration stops while its central region remains visible 15 Fl_Window::size_range configures limits explicitly - minw/minh: minimum dimensions - maxw/maxh: optional upper limits - dw/dh: increments, useful for integral character-cell sizes - aspect: preserve the specified aspect-ratio policy 16 without size_range, the example version derives minimums from resizable - the source describes a 100-unit minimum cap for that region - a smaller starting region keeps its smaller minimum - a zero extent can prevent resizing along that axis 10.11.8 Command-line arguments 1 graphical programs can still accept command-line options - -display selects an X server instead of the default DISPLAY setting - -geometry specifies size and possibly position - -bg changes the background color - FLTK supplies parsing for its recognized options 2 win->show(argc, argv) offers the simple library-only route - suitable when the application has no additional argument syntax 3 applications with their own options can combine the two parsers - let Fl::args drive parsing and call an application handler - or drive parsing themselves and delegate individual options to Fl::arg 4 Fl::args takes argc, argv, an index reference and optional handler - handler signature: int function(int, char**, int&) - the returned index identifies where option processing stopped 5 the application handler gets first chance at the current option - return zero if it is not recognized - when handled, advance the index by the number of consumed arguments - return that same consumed count - taking a library option name therefore overrides its usual processing 6 parsing stops at end of arguments or a positional argument - an unrecognized option or missing required option value is an error - zero return reports parsing failure 7 options after the first positional argument are not processed by this pass - place the expected options before the trailing positional arguments 8 this argument-handler interface has no user-data pointer - the example therefore stores the selected count in a file-local variable 9 in the book's Fl::args path, still call show(argc, argv) - parsed display/window settings must be applied when showing the window 10 demo: a variable number of buttons with trailing arguments as labels - default button count is three - -count N changes it - ordinary FLTK display and geometry options remain available 11 name layout constants and begin with buttons_count = 3 count parser: - strtol reads a decimal value - reject absent digits and trailing junk - also check overflow, destination range and an acceptable positive count before computing geometry; the short listing omits these checks application option handler: - recognize -count and require its following value - consume both arguments; otherwise return zero main: - reject failure from Fl::args - derive window height from the accepted count - use remaining arguments as labels, with Not set for missing labels - each button prints its own label through the shared callback - end the group, show(argc, argv), then run 12 Fl::arg processes one current option under the application's own loop - accepts the current index by reference - returns zero when unhandled - otherwise advances the index and returns the consumed count coordinate this manual route with show's parsing behavior - the source tracks whether FLTK's argument parser was invoked - avoids asking show to reject application options a second time 13 cmdline2.cpp demonstrates that manually driven variant 10.11.9 Further FLTK facilities 1 the following is an orientation to facilities omitted from full examples 2 event handling can intercept keyboard, mouse and other activity - Fl_Event names event categories - handle is a virtual widget method - system/application handlers and event dispatch supply broader hooks 3 menu and selection widgets: - Fl_Menu_Bar: horizontal menu bar - Fl_Menu_Button: a button opening a menu - Fl_Choice: current selection plus a menu of alternatives - Fl_Tree: expandable/collapsible hierarchical items 4 Fl_Scroll provides a scrollable area containing widgets - Fl_Scrollbar supplies scrollbar controls - Fl_Pack arranges child widgets in a horizontal or vertical sequence 5 Fl_Progress displays progress through a longer operation 6 Fl_Valuator's subclasses offer numeric-value controls - sliders, dials and other specialized presentations 7 Fl_Table supports tabular arrangements - subclassing its virtual drawing/interaction hooks customizes cells 8 Fl_Tile arranges touching child regions with draggable boundaries - changing a boundary redistributes their sizes 9 Fl_Tabs provides user-selectable pages Fl_Wizard provides pages selected by the application - useful for controlled multistage dialogs 10 Fl_Tooltip controls tooltip behavior - widget tooltip/copy_tooltip methods supply the displayed text 11 predefined modal dialogs provide simple messages and choices - fl_message/fl_alert: information or warning - fl_ask/fl_choice in the book's API: select among supplied answers - format strings and arguments construct their messages - modal interaction temporarily prevents ordinary use of other windows 12 other dialogs request text, passwords, files, directories or colors - corresponding functions supply those specialized interactions - predefined button-label variables allow changing common dialog labels 13 Fl_Image and its subclasses represent image data - examples include bitmap and PNG support - image/deimage associate normal and inactive imagery with widgets 14 the toolkit contains much more than this introduction - use its documentation when a specific facility becomes necessary 10.11.10 FLTK and OOP 1 inspect the toolkit as an example of architectural paradigms 2 the author considers parts of FLTK only partly object-oriented - base classes sometimes implement many optional behaviors - some derived widgets mainly select modes already implemented by a base - this is an assessment against his preferred OOP model 3 he also contrasts callback functions with object/message interaction 4 ordinary callback registration combines function address and void* context - callback casts that context back to the expected type - caller and callback must agree about its type and lifetime 5 an object-oriented alternative passes an object with a virtual method - object fields hold its context - service sends a message by calling that method - a derived override supplies application-specific behavior 6 for widgets, derive a class and override an event-reaction method - keep the reaction's data in that object's fields 7 an adapter layer can provide that interface over FLTK callbacks - the example uses an OOFL prefix for reusable adapter classes - application-specific subclasses then supply their own behavior 8 rewrite the earlier speaking-buttons demo with unchanged visible behavior - change its decomposition and event interface 9 OOFLButton derives from Fl_Button - constructor registers one bridge callback - callback invokes virtual OnPress() - default OnPress does nothing; subclasses override it 10 a no-op default is meaningful here - the author therefore chooses a concrete virtual method - pure virtual would instead require every concrete subclass to override 11 a normal non-static member cannot match the plain callback pointer type - it has an implicit object parameter private static CallbackFunction matches FLTK's callback signature - use its Fl_Widget* argument to recover the OOFLButton - the adapter constructor establishes the precondition for that cast - dispatch OnPress virtually on that object 12 the adapter explicitly declares a virtual destructor - preserves polymorphic lifetime behavior - FLTK's base already supplies virtual destruction in this example 13 the reusable adapter contains no application-specific action - short methods can stay in its class definition - a real project can place the adapter in its own module 14 application subclasses divide the two button roles - SayButton prints a message - ExitButton requests termination 15 ButtonCommon centralizes shared position, dimensions and label font - an example of deriving primarily for a constructor SayButton stores its message pointer and implements OnPress with output - the example uses permanent string literals, so pointer retention is safe ExitButton's override performs its exit action - the source calls exit(0); hiding the window can instead permit normal event-loop return as discussed earlier main now constructs the window and three already-configured buttons - no separate per-button callback/context setup remains there - object fields and virtual methods replace repeated void* conversions - the adapter's internal bridge cast remains localized 10.11.11 (*) Using an application-owned event loop 1 GUI toolkits commonly offer their own main event loop - the author prefers the application to control this architectural choice 2 other event sources may need equal attention - e.g. network clients serving many outstanding connections - blocking network work inside GUI callbacks would stop responsiveness 3 one route is to register other events with FLTK - add_fd/remove_fd for descriptor readiness - add_timeout/remove_timeout/repeat_timeout for scheduled callbacks 4 the source then explores an external loop instead - its particular integration is specific to the FLTK/X11 environment examined in the book 5 idea: open the X connection under application control - share that Display with FLTK - monitor its connection descriptor alongside other event sources - give FLTK opportunities to dispatch its events 6 the book's recipe: - XOpenDisplay(0) obtains a Display*; test for failure - ConnectionNumber(display) obtains the connection descriptor - fl_open_display(display) supplies that connection to FLTK - when it is readable, call Fl::wait(0.0) without blocking - the previous chapter's descriptor-handler design can host that action a complete integration must also account for already queued events, timers, pending redraws and library work that does not create fresh socket readiness 7 the author warns that this low-level recipe may change across versions - Fl::flush requests pending drawing work to be sent/displayed - event-loop pumping and flushing need to match the library's contract - treat the example as an architectural illustration, not a portable promise that one socket callback handles every FLTK event source C++: further study 1 the chapter deliberately covers a limited historical subset - omits the standard library, multiple inheritance, namespaces, member pointers and other features 2 professional work may require the standard library and newer C++ - the author's opposition to them is his preference - the chapter's employment claims reflect its publication period 3 if preparing for a specific role, learn its required missing facilities - practise them in code; reading alone does not establish proficiency - the source's advice about which standards to ignore is dated opinion 4 the author's alternative learning sequence is to build one or two useful programs with the studied mechanisms before moving to other facilities - intended to develop understanding of how abstractions work - his blanket rejection of later C++ is not a language correctness rule 5 the author suggests Jeff Alger's C++ for Real Programmers as further reading - presented as a way to deepen understanding of the classical mechanisms - this is the source's recommendation, not an updated reading survey 11. Non-destructive paradigms 1 earlier languages: program changes a state over time - functional examples were possible, but the languages mainly supported imperative programming 2 non-destructive languages: avoid changes to the execution environment - Lisp / Scheme allow assignment, but favour building new values - Prolog / Hope have no ordinary assignment - Prolog still has I/O and database changes as side effects - lazy Hope evaluates a value only when needed -> expression side effects would have unpredictable timing 3 learning these models requires a different way of thinking - author values this flexibility even for later imperative work 11.1 Lisp and its S-expressions 11.1.1 A little history 1 Lisp dates from the 1950s - among the languages discussed, only Fortran is older - both changed considerably during their subsequent development 2 McCarthy: symbolic expressions for artificial intelligence, from 1956 - IPL suggested representing formulas with lists - attempted symbolic differentiation using FLPL in 1958 - missing conditional expressions / recursion prevented completion 3 McCarthy / Minsky group formed in 1958 - initially Lisp was separate IBM 704 assembly subroutines 4 universal Turing machine: interpreter expressed as a Turing machine - input encodes machine M and its input word W - result is the result of running M on W - compact implementations may hide complexity in the encoding 5 universal function: same idea for computable functions - McCarthy represented both functions and data as lists - parentheses supplied a formal notation for writing EVAL - initially intended as a theoretical description 6 Stephen Russell translated EVAL into assembly - obtained a working Lisp interpreter - theoretical list notation became an actual programming syntax 7 Lisp notation: parenthesized lists; whitespace separates elements - function call: function first, then argument expressions - (+ (* 5 10) (- 55 5)) -> 50 + 50 -> 100 - (princ "Hello, world!") prints text; (terpri) adds a newline 8 author: unfamiliar syntax becomes readable with practice - parenthesized prefix notation survived major changes to Lisp 9 historical accounts mentioned in the book: - Herbert Stoyan: early development of Lisp - Paul Graham: Revenge of the Nerds 10 McCarthy presented Lisp in a 1960 paper on symbolic expressions - many dialects followed, including systems for Lisp machines - Lisp now describes a family of languages 11 Common Lisp: work began in 1981; ANSI standard published in 1994 - author criticizes its size and the effort of implementation - implementation extensions still limit source portability - author argues that treating Common Lisp as the only Lisp harmed smaller implementations and the language family's reputation 12 domain-specific dialects developed somewhat independently - Emacs Lisp: extension language of Emacs - AutoLISP: embedded language in AutoCAD 13 book describes dynamic binding in these dialects - its difficulties motivate the later discussion of funargs 14 Scheme: first implementation in 1975 - Sussman / Steele investigated actors and continuations - resulting model also provided a compact Lisp dialect - SICP helped popularize it - comparisons of implementation numbers describe the book's period 15 Steele also participated in other language standardization work - author's disapproval is a judgment about those committees 16 book will introduce Common Lisp before Scheme - Common Lisp retains features of older Lisp traditions - author nevertheless prefers Scheme for practical consideration 17 Scheme reports: R5RS, R6RS, R7RS - number identifies the revision of the language report - book dates R5RS to 1997 and favours its small specification 18 R6RS used a formal committee / voting process - separate language, libraries, appendices and rationale documents - author contrasts their combined size with R5RS's 50 pages 19 R6RS final version appeared in 2007 - author considers the additional complexity damaging - some implementers chose to keep targeting R5RS 20 2009: proposal to separate small and large Scheme specifications - R7RS-small appeared in 2013 - intended to complement R6RS - author disputes the educational / industrial justification 21 Chicken Scheme, as used in the book, targets R5RS - includes useful facilities beyond it as extensions - book's claims about relative support describe that period 11.1.2 SBCL, GCL and ECL 1 Common Lisp implementations used in the book: - SBCL: Steel Bank Common Lisp - GCL: GNU Common Lisp - ECL: Embeddable Common Lisp - corresponding packages commonly use these lowercase names 2 Unix script: interpreter path and script-mode flag on the first line - SBCL: #!/usr/bin/sbcl --script - GCL: #!/usr/bin/gcl -f - ECL: #!/usr/bin/ecl -shell - body: (princ "Hello world!") followed by (terpri) - chmod +x myfile.lsp -> run ./myfile.lsp 3 shebang restrictions vary between Unix systems - book warns about short first-line limits and one optional argument - some systems require the interpreter to be a binary executable - Linux can also permit an interpreter script 4 REPL = read, evaluate, print, repeat - starting sbcl / gcl / ecl without a script enters this mode 5 load definitions before entering the REPL: - sbcl --noinform --load myfile.lsp - gcl -load myfile.lsp; ECL also uses -load - SBCL's --noinform suppresses its startup information 6 interactive editing differs between the implementations described - GCL uses GNU Readline for history / editing / completion - rlwrap supplies editing for SBCL / ECL - example: rlwrap sbcl --noinform --load myfile.lsp - wrapper does not automatically know the interpreter's symbols 7 rlwrap controls: - up / down: history; Ctrl-R: reverse search; Tab: completion - -c enables filename completion - -f can supply a file of words for completion 8 command-line arguments are implementation-specific - SBCL: *posix-argv*; GCL: si::*command-args* - both give a list beginning with the script name - echo: mapcar prints each element of (cdr argument-list) - ECL: (ext:command-args) includes interpreter and -shell first -> script must use cdddr to skip three elements - book mainly uses a shared, classical Lisp subset 9 remaining discussion concerns distributing standalone executables - ordinary interpretation is sufficient for the following examples 10 compilation and producing a distributable executable are distinct - book compares the implementation-specific delivery procedures 11 SBCL can save a running Lisp image as an executable - load application definitions into the running system - saved image also contains runtime code and supporting data 12 sb-ext:save-lisp-and-die: - required argument: destination filename - :executable t makes an executable image - :toplevel selects the entry function; otherwise startup uses REPL 13 SBCL example: define main to print the greeting - save with :executable t :toplevel 'main - process this file with sbcl --load - author's resulting executable exceeded 60 MB 14 :compression t reduces the image size - author's example: about 12 MB, with visible decompression delay - these sizes / timings are measurements of that setup 15 GCL -compile produces an object file - this alone does not produce the standalone program being sought 16 GCL can load the compiled object into its Lisp system - saving that system normally produces an executable entering REPL 17 GCL example: define si:top-level as the application entry point - (compile-file "hello.lsp") -> hello.o - (load "hello.o") -> load definitions into the running system - (si:save-system "hello") -> save executable and exit - author's image was about 12 MB without an observed startup delay 18 ECL can translate Lisp into C and build a program - (compile-file "hello.lsp" :system-p t) -> object file - c:build-program links the object specified by :lisp-files - :epilogue-code () avoids entering the usual interactive ending - small executable still depends on shared ECL runtime libraries 19 ECL argument list differs between script and compiled execution - compiled program lacks the interpreter / -shell prefix - cdddr now discards two real arguments -> compiled echo must use cdr instead 20 author criticizes these application-distribution interfaces - later I/O examples examine further portability difficulties 11.1.3 S-expressions: a heterogeneous data model 1 S-expressions represent both Lisp data and program forms - heterogeneous lists can contain different types and nested lists 2 S-expression = atom or dotted pair - literal atoms: numbers, characters, strings - characters: #\a, #\5, #\Space, #\Newline, #\Tab 3 numeric types can preserve more information than machine arithmetic - 2/3 is one rational-number token, stored as numerator / denominator - #C(1 -2) represents a complex number - arbitrary-size integers avoid a fixed machine-word limit 4 symbols: named objects resembling identifiers in other languages - names may include punctuation: GO-JOHNNY-GO, *STDIN*, ==^== - ordinary Common Lisp input converts letters to uppercase -> as21 / As21 / AS21 normally name the same symbol 5 symbols can be names and ordinary data values - useful as distinct tags, somewhat like enumeration constants - a file-summing function may return a number on success - exceptional results can be OPEN_ERROR, WRONG_DATA or EMPTY 6 nil = false = empty list - () is another notation for the same object - nil evaluates to itself 7 atom means any object that is not a dotted pair - does not necessarily mean a small or indivisible implementation 8 dotted pair: (left . right), with arbitrary S-expressions in both parts - whitespace must separate the dot from surrounding tokens - each part can be understood as a pointer to another object - objects can be shared by several pairs - changing a shared (1 . 2) affects every structure containing it 9 proper list: chain of pairs ending in nil - each left part holds an element; right part points to the rest - (1 . (2 . (3 . ()))) = (1 2 3) - elements may themselves be lists / dotted pairs / other atoms - non-nil ending -> improper list: (1 2 3 . 4) 10 modern Lisp also provides arrays, structures and hash tables - heterogeneous values can be used as hash-table keys / values - Common Lisp Object System adds object-oriented facilities 11 these additional objects can occur inside S-expressions - arrays / structures / objects are atoms in the pair-versus-atom classification, even when they contain further objects 12 book omits most non-list structures - they add facilities already encountered in earlier paradigms 11.1.4 Evaluating S-expressions 1 evaluation gives S-expressions computational meaning - result may depend on the environment in which evaluation occurs 2 numbers, characters and strings evaluate to themselves - 25 -> 25; #\A -> #\A; "Simple string" -> that string 3 nil and t are constant symbols evaluating to themselves - nil means false; every non-nil value counts as true - other constant symbols may have fixed values, such as pi 4 ordinary symbol -> look up its value in the current environment - an unbound symbol normally causes an error - some older dialects instead supplied a default value 5 an evaluable list is called a form - normally a proper list; an improper list is not a valid call form 6 first element usually names the operation - a lambda expression can also appear in function position 7 ordinary function call: evaluate arguments, then apply the function - (* (+ 3 7) 5 (- 6 4)) - argument values: 10, 5, 2 -> multiplication returns 100 8 function call is only one possible interpretation - a leading symbol can instead designate a macro / special form 9 Lisp macro: constructs another form from unevaluated argument forms - expansion code runs as Lisp code - its result is code to evaluate, rather than the final answer - expansion can occur before the resulting program runs 10 book omits macro programming details - author's point: macro systems need not share C macros' weaknesses 11 special forms have individual evaluation rules - can leave arguments unevaluated, select branches or bind names - language defines the primitive special operators - macros build additional constructs from those primitives 12 following examples use a small selection of built-in facilities - the complete Common Lisp library is much larger 13 quote: return the supplied expression without evaluating it - (quote (1 2 3)) = '(1 2 3) - (f '(1 2 3)) passes a list; (f (1 2 3)) attempts an invalid call - 'x gives the symbol X rather than its variable value 14 arithmetic uses prefix function calls - + / * combine arguments; unary - changes sign - (/ 2 3) can return exact rational 2/3 - <, >, =, <=, >=, /= compare numbers 15 not returns t only for nil - and evaluates left to right, stopping at the first nil -> otherwise returns the last argument's value - or stops at the first non-nil value and returns it -> returns nil if no argument succeeds 16 and / or cannot be ordinary eager functions - later arguments may remain unevaluated - this also determines whether their side effects happen 17 Common Lisp implements and / or as macros - conditional evaluation can be expressed using if 18 cons constructs a new pair from two argument values - (cons 1 (cons 2 (cons 3 nil))) -> (1 2 3) - a pair is also commonly called a cons 19 car returns the left part; cdr returns the right part - (car '(1 2 3)) -> 1 - (cdr '(1 2 3)) -> (2 3) 20 historical background: IBM 704 had 36-bit words - magnetic-core memory; addresses fitted into 15 bits 21 its instruction formats included address and decrement fields - some instructions held a 15-bit immediate / decrement value 22 assembly macros extracted those instruction fields - CAR: contents of the address part of the register - CDR: contents of the decrement part of the register - register here used the older, broader meaning of a storage cell 23 Lisp pairs reused the two address-sized fields - extraction routines inherited the CAR / CDR macro names - book distinguishes these macros from machine instruction names 24 alternative names exist: first / rest, head / tail - car / cdr remain established Lisp terminology 25 list constructs a proper list of its evaluated arguments - (list 'a 'b 'c) -> (A B C) 26 predicates for the pair / atom model: - listp: true for nil or any cons, including improper lists - atom: true exactly when the value is not a cons - null: tests for nil; same truth result as not 27 if: evaluate condition, then exactly one selected branch - (if (> x 0) (f x) (g (- x))) - positive x -> f(x); otherwise -> g(-x) - missing false branch returns nil when the condition is false 28 cond supports several alternatives and several forms per alternative - author observes a preference for cond in the Lisp code discussed 29 cond clauses: (condition body-form ...) - test conditions in order; choose the first non-nil result - evaluate that clause's body; return its last value - condition-only clause returns its successful condition value - no successful clause -> nil 30 final clause headed by t acts as a default - reached only when all earlier conditions were false 31 the two-branch if can also be written using cond - ((> x 0) (f x)) followed by (t (g (- x))) 32 eq compares identity: physically the same object - useful for symbols; identical-looking separate lists need not match 33 eql adds same-type numeric equality and character equality - do not rely on an implementation making equal numbers eq - distinct equal strings are not eql in Common Lisp 34 eql differs from numeric = - (= 2 2.0) -> t; (eql 2 2.0) -> nil - integer and floating-point objects have different types 35 equal also compares list structure recursively - compares corresponding car / cdr values - includes string / bit-vector content comparison in Common Lisp - do not infer deep comparison of every possible object type 36 additional operations will be introduced when examples require them 11.1.5 User-defined functions 1 Lisp program: sequence of top-level forms - evaluated in order; many normally define functions 2 defun: name, parameter list, then body forms - arguments bind the parameter names during a call - last body form supplies the function's result - sqe-discrim(a,b,c): (- (* b b) (* 4 a c)) -> b*b - 4*a*c 3 defun has a side effect - associates the function name with a function object - association persists after the defining form finishes 4 recursive list length: - empty list -> 0; otherwise -> 1 + length(cdr list) - null base case fails on an improper list's final atom - atom base case counts cons cells and stops at any atomic tail - either if or cond can express the two alternatives 5 length2 distinguishes invalid atomic input - nil -> 0; other standalone atom -> nil - cons with an atomic cdr -> 1 - otherwise -> 1 + length2(cdr list) - cond separates normal, base and exceptional cases 6 recursion is central to Lisp programming - tail-call optimization is especially useful for recursive loops - availability depends on the implementation / compilation settings 7 accumulator makes list-length recursion a tail call - wrapper handles nil / atomic input - helper starts with len = 1, advances cdr and increments len - no addition remains after the recursive call - reversing a list uses the same accumulator technique -> move each car to the front of the accumulated result -> (1 2 3), () -> (2 3), (1) -> (3), (2 1) -> (), (3 2 1): return the accumulated list 11.1.6 Destructive functions 1 destructive operation = operation with an observable modifying effect - examples include assignment and input / output 2 binding a new function parameter is different from assignment - establishes the initial value of a newly created binding - that binding disappears after its lifetime ends 3 defun changes the function associated with a name - normally definitions run before the main computation - Lisp also permits reassignment and changes to existing structures 4 setq assigns a value to a variable - variable name is not evaluated; value expression is evaluated - (setq x 25), then (setq x (+ x 1)) -> x is 26 5 quoting a name alone does not reproduce setq's behaviour - lexical binding matters; later sections explain the distinction 6 setq can contain several name / value pairs, processed in order - psetq first evaluates all values, then performs assignments - (psetq x y y x) swaps the old values 7 declare global variables explicitly with defvar - (defvar *myglobvar* 100) - surrounding asterisks are a naming convention - book's SBCL warns about undeclared globals 8 defvar also makes the name special / dynamically bound - more than a declaration of storage or an initial value 9 rplaca / rplacd replace a pair's car / cdr - starting with mutable list (1 2 3): -> replace first car with 10 -> replace second cdr with 30 -> resulting structure: (10 2 . 30) - variable still points to the same first cons - use newly constructed lists for mutation; Common Lisp quoted literal data must not be destructively modified 10 changing a final cdr can form a cycle - last cons of (1 2 3) points back to the first cons - traversal no longer reaches nil - an unaware printer / traversal can run indefinitely 11 shared tails make mutations visible through several variables - a = (1 2 3 4); b = cons(10, cdr(a)) -> (10 2 3 4) - both share the cons cells holding 2, 3 and 4 - setting the second cons's cdr to nil changes a to (1 2) -> b simultaneously becomes (10 2) 12 copying the list spine avoids sharing those cons cells - recurse over cdr and cons each existing car onto the copied tail - Common Lisp provides copy-list - nested objects in the cars are still shared 13 setf assigns through generalized places - (setf (car x) v) changes a car - (setf x y) assigns a variable - (setf (aref arr 3) value) changes an array element - (setf (char str 4) #\u) changes a string character - also supports fields, hash-table entries and function bindings - setting (symbol-function 'car1) to #'car gives another name for that function object 14 setf implementation is separate from its uniform surface notation - author compares InteLib's location references with Common Lisp - Common Lisp supports setter functions named (setf accessor) - author's criticisms concern this implementation design 15 Common Lisp also specifies built-in setf places / expansions - book discusses implementation differences and code-size concerns - these are the author's arguments, not universal runtime costs 16 Lisp permits functional programming but does not enforce purity - author identifies heterogeneous S-expressions as its central idea - destructive operations remain available throughout the language 11.1.7 The eval function 1 eval evaluates an S-expression supplied as data - ordinary call evaluation first computes eval's argument - eval then interprets that resulting value as a form - (eval (list 'cdr '(list 1 2 3))) -> constructs (cdr (list 1 2 3)) -> evaluates it -> (2 3) 2 the expression can be constructed while the program runs - it may contain defun or changes to function bindings -> running program can construct and install new behaviour 3 intern finds / creates a symbol from its textual name - returns the existing interned symbol when one already exists - together with eval, permits construction of arbitrary Lisp forms 4 unrestricted runtime code construction complicates static analysis - in general, cannot predict every symbol / operation it will use - simple restricted cases can still be analysed 5 read parses textual S-expressions and interns their symbols - ordinary readable structures can arrive from files / input - unrestricted evaluation of such input needs runtime language facilities; static source alone does not determine all behaviour 6 book relates this flexibility to the size of Lisp runtime images - SBCL / GCL examples include runtime facilities in the executable - ECL examples depend on shared runtime libraries 7 SBCL compiles Lisp functions to native machine code - includes functions entered through the REPL - book disputes calling this compilation because runtime support remains; that is the author's terminology, not a denial that native-code compilation takes place 8 generated native code needs executable memory - original executable text and ordinary data have access protections - operating-system facilities such as mmap can allocate suitable memory, subject to the system's protection rules 9 author argues that execution speed is not the only relevant distinction - also considers runtime size / dependence on the language system 10 book postpones its wider interpretation-versus-compilation discussion 11.1.8 Functions as objects 1 first-class function: can be passed, returned and created at runtime - function accepting functions -> higher-order function 2 (symbol-function 'cons) obtains the function bound to CONS - printed representation differs between implementations 3 many Lisp data structures can be printed and read back - textual S-expressions provide a portable representation of data 4 printed function objects generally cannot be read back into functions - #<...> marks an unreadable object representation 5 function obtains the function denoted by its unevaluated argument - (function cons) obtains cons - respects lexical function bindings unlike symbol-function - can also construct a function from a lambda expression 6 #' is shorthand for function - #'cons = (function cons); #'+ obtains addition 7 funcall receives arguments individually; apply receives a final list - (funcall #'+ 1 20 300 4000 50000) -> 54321 - (apply #'+ '(1 20 300 4000 50000)) -> 54321 - apply permits a number of arguments determined at runtime 8 Common Lisp also accepts a symbol as a function designator - higher-order functions can resolve its function binding - author chooses explicit function objects in the examples 9 mapcar applies a function to corresponding list elements - maps addition over (1 2 3 4), (10 20 30 40), (100 200 300 400) -> (111 222 333 444) - mapping list instead -> ((1 10 100) (2 20 200) ...) - results form a new list 10 named plus3 can add 3 to each element through mapcar - many tiny named helpers become awkward - fixed definition also does not solve a runtime-selected increment 11 lambda creates an anonymous function - avoids requiring a separate name - free variables can refer to the enclosing environment 12 lambda expression: lambda, parameter list, body forms - ((lambda (a b c) (+ a (* b c))) 10 3 5) -> 25 - #'(lambda (x) (+ 3 x)) can be passed to mapcar - add-to-list(num,lst) maps #'(lambda (x) (+ x num)) over lst - num comes from the enclosing call's parameter binding 13 returning functions: make-adder(n) returns #'(lambda (x) (+ n x)) - make-adder(13) creates a function that adds 13 - store it as plus13's variable value; (funcall plus13 77) -> 90 - no quote needed: evaluating plus13 already gives the function 14 function and variable bindings are separate in Common Lisp - placing that object in (symbol-function 'plus13) permits ordinary call syntax: (plus13 77) 15 ordinary functions cannot decide whether to evaluate their arguments - mapcar / apply already supply computed data values - a function cannot treat the same interface sometimes as source forms and sometimes as already computed arguments 16 ordinary call evaluation therefore computes argument values first - same application operation is usable by higher-order functions - macros / special operators control evaluation and cannot be used interchangeably with ordinary function objects 11.1.9 The funarg problem and lexical binding 1 early Lisp stored a symbol's current value in the symbol itself - symbol-value still accesses a symbol's dynamic value - lexical variable lookup need not return that value 2 simple local-variable implementation: - save old symbol value; install parameter / local value - execute body; restore old value on return 3 this is dynamic binding - value depends on the active call chain - book discusses its historical use and resulting surprises 4 make-adder(thevar) returns a function adding thevar - global thevar = 100; create plus5 with make-adder(5) - dynamic binding: (funcall plus5 10) returns 110, not 15 - declaring thevar with defvar reproduces the special binding case 5 why 110: the temporary binding to 5 ended with make-adder - later free reference to thevar finds restored value 100 - lambda's own x parameter still correctly receives 10 6 without an outer value, the returned function encounters an unbound name - restoration includes restoring the absence of a value 7 upward funarg problem: returned function loses its intended environment - downward variant: pass the function while its creator is active - sample(thevar) passes lambda(x) = x + thevar and 1000 to f2 - f2 itself names its second parameter thevar 8 dynamic binding in f2 shadows sample's intended value 7 with 1000 - lambda sees 1000; adds it to its argument 1000 -> 2000 - intended lexical result: 1000 + 7 -> 1007 9 book proposes trying both modes in separate interpreter sessions - ordinary lexical variable -> 1007 - defvar makes thevar special -> 2000 10 downward problem exposes accidental dependence on a caller's names - renaming f2's local parameter can change another function's result - banning free variables would also remove useful higher-order code 11 lexical binding resolves these examples - Common Lisp normally binds ordinary local variables lexically - special declarations retain dynamic binding where requested 12 conceptual lexical environment: name / binding entries plus parent link - search current environment, then enclosing environments - inner binding shadows an outer binding with the same name 13 environment tables describe semantics, not required implementation - compilers / interpreters can resolve access more efficiently 14 creating a local binding need not overwrite a symbol's dynamic value - add a distinct binding to the local environment 15 setq respects the active lexical binding - updates that binding rather than the symbol's dynamic value slot 16 var-values(var) returns (cons var (symbol-value 'var)) - lexical argument "local", dynamic value "global" -> ("local" . "global") - declaring var special would change what this example demonstrates 17 closure = function code together with its lexical environment - preserves bindings available where the function was created - top-level functions can have no captured local bindings 18 calling a closure uses its captured environment - parameter bindings belong to a new environment for that call - caller's unrelated lexical locals do not become visible - special operators can introduce / control binding environments 19 macro expansion code has its own environment - the generated form is subsequently processed at the use site 20 make-adder(33) captures a binding of thevar to 33 - applying the closure to 27 creates x = 27 - x found locally, thevar in captured environment -> 60 21 ordinary functions cannot evaluate arguments in a caller's lexical scope - that scope is not implicitly passed to the callee 22 Common Lisp eval does not receive the caller's lexical environment - demo-eval-symb(x) = (eval 'x) ignores the lexical parameter - uses the dynamic / global x, or reports it unbound 23 set receives an evaluated symbol and changes its dynamic value - cannot discover / modify a caller's lexical binding by name 24 let introduces local bindings and evaluates body forms in their scope - binding specifications: name or (name initial-expression) - omitted initializer gives nil in Common Lisp - result is the last body form's value 25 let example computes sum and product in one traversal - initialize s = 0, p = 1 - mapped lambda updates both bindings for each list element - return (cons s p) - let initializers run in the outer environment -> newly introduced variables are unavailable to one another 26 let* introduces bindings sequentially - later initializer can use a binding introduced earlier 27 flet / macrolet introduce local functions / macros - book does not develop these facilities further 28 closures capture bindings, not separate copies of their current values - several closures can share the same mutable binding 29 shared counter example: - let creates counter = 0 - seq-next increments and returns counter - seq-reset assigns 0 to the same counter - successive calls -> 1, 2, 3; reset -> 0; next -> 1 - binding survives because the defined functions retain it 30 shared private state plus functions resembles an object with methods - quoted teaching story contrasts closures and objects - point: the two mechanisms can express closely related structures 31 book traces the story to Anton van Straaten's mailing-list posting - Russian retellings changed the wording while retaining the idea 11.1.10 The funarg problem in other languages 1 funarg problems are not specific to Lisp - arise with callable values and nested functions referring to an enclosing environment whose lifetime may end 2 functional-language implementations account for captured bindings - variable representation need not be merely a stack location 3 traditional Pascal / C variables map closely to memory locations - globals in persistent storage; ordinary locals in stack frames - captured locals require additional lifetime / access machinery 4 nested Pascal procedures need access to enclosing activations - implementation may use static links / displays between frames - book relates this to i386 ENTER's nesting operand 5 book's Pascal history: procedural parameters precede general variables - passing a nested routine downward keeps its creator active - forbidding returned routines excludes the upward lifetime problem 6 implementations later added procedural / functional variable types - resemble function pointers for routines without captured context 7 downward use can retain a live enclosing stack frame - implementation must still pass / recover the correct environment 8 upward use outlives that frame - returned code address alone cannot preserve its former locals - requires a different representation and lifetime arrangement - author's rejection of this in compiled languages is a design preference, not a general impossibility of compiled closures 9 Pascal implementations discussed restrict ordinary procedural values - top-level routines have no disappearing local environment - nested-routine support depends on the implementation / routine type 10 standard C has function pointers but no nested functions - GCC nested functions are an extension - author advises against relying on them 11 GNU C sumprod example has nested plus, times and reduce - they share the enclosing automatic variable accum - sum starts at 0; product starts at 1 - direct nested calls can pass an enclosing-frame pointer in a hidden register / argument; book illustrates i386 ECX 12 taking a nested function's address also needs its environment - illustrated GCC implementation creates a stack trampoline - trampoline loads the context pointer, then jumps to function code - function pointer refers to that trampoline 13 trampoline / captured stack data live only while the creator is active - returning the address does not extend either lifetime - apparently working calls may merely encounter unreused stack bytes 14 make_adder returning a nested adder is therefore invalid after return - one call may appear to yield 13 - creating adders for 3 and 7 may reuse the same stack locations -> observed 17 / 17 is possible, not a guaranteed result 15 an intervening call can overwrite the stale trampoline - eraser's local array demonstrates this reuse - author's run terminated with an illegal-instruction error 16 descending callbacks still raise implementation concerns - traditional trampolines require executable stack memory - alternative function descriptors have ABI / compatibility costs - neither technique alone makes expired captured locals valid 17 author recommends avoiding nested routines in these low-level languages - explicit environment objects offer a clearer lifetime model 18 C++ member functions also require a context: the target object - a bare ordinary function pointer does not encode that object 19 pointer-to-member-function is a separate type - invocation explicitly supplies an object using .* or ->* - static member functions do not require an object - pointer-to-member alone is not a closure retaining object lifetime 11.1.11 Reducing lists 1 folds become especially expressive with first-class functions - Lisp examples build on the earlier C / C++ reduction examples 2 lreduce(fun,lst,init): combine accumulator with car, recurse on cdr - empty list returns init - recursive call is in tail position - rreduce instead computes fun(car, reduction-of-cdr) -> combination remains after recursion returns 3 right-fold cons with nil copies the list spine - (1 2 3) -> new cons cells containing the same elements - left-fold cons with nil -> (((nil . 1) . 2) . 3) - addition / multiplication folds use 0 / 1 as initial values - for these variadic operations, apply is often simpler 4 left-fold lambda(acc,x) = cons(x,acc) reverses a list - (1 2 3) -> (3 2 1) - using that function in a right fold instead creates nested pairs 5 further fold examples: - maximum: initial car, fold larger-of-two over cdr -> requires a nonempty list - ins2list inserts into an already sorted list -> stop at nil or first larger element; otherwise copy prefix - fold insertion from nil -> insertion sort -> swap combiner arguments when changing fold direction - redmap: right-fold cons(funcall(fun,x), accumulated-results) -> mapping unary - over (1 2 3) gives (-1 -2 -3) 6 filtering with a right fold: - predicate true -> cons element onto accumulated result - false -> retain accumulated result unchanged - select numbers from (1 2 "abc" t 15) -> (1 2 15) - preserves the order of retained elements 11.1.12 The burden of older paradigms 1 early Lisp used symbols for words and lists of symbols for phrases - separate string objects were absent - author links this to a period when users were often programmers 2 later Lisp added strings but retained escaped symbol names - ordinary John becomes JOHN - |John| preserves mixed case and denotes a different symbol - vertical bars also permit spaces / punctuation within the name 3 symbol-name returns a symbol's name as a string - intern finds / creates a symbol from a string 4 author argues for separating program identifiers from user-facing text - renaming internal variables should not change visible behaviour - criticizes using symbols as a substitute for ordinary strings 5 symbol property lists are another older facility retained in Lisp - author's broader point concerns inherited programming habits - age alone does not change the semantics of the available features 11.1.13 Features the author would rather omit 1 author criticizes Common Lisp's large specification - rejects the assumption that adding features has no cost 2 large libraries could in principle be modular - include only needed functions / symbols in an application - author favours implementations that can be reduced this way 3 general lambda lists add several parameter conventions - &optional: optional arguments - &rest: remaining arguments collected into a list - &key: keyword arguments; &aux: local auxiliary bindings - declarations can provide additional information to a compiler 4 these conventions complicate parsing and function application - unrestricted runtime eval can encounter them in generated code - author's concern: supporting unused possibilities still costs space 5 coerce takes a value and a type specifier - type can be a symbol such as string / float or a compound list - author criticizes coupling runtime facilities to many type symbols 6 loop provides an extensive iteration sublanguage - example combines bounds, stopping condition, collection and output - for / from / to / while / collect / do / when / finally guide it - author prefers smaller constructs for these jobs 7 author's main criticism: the specification does not promise a minimal runtime containing only facilities a particular application needs 8 author also objects to needing additional concepts for basic I/O - next section illustrates keyword arguments and condition handling 11.1.14 Input and output 1 I/O is necessary for complete applications - book uses this section to explain facilities and criticize their interfaces from the author's perspective 2 stream model: input / output operations can succeed, end or fail - EOF is an ordinary input state - applications need control over recoverable errors and diagnostics 3 Lisp's early I/O predates the later file / user-interface conventions - author traces some present interfaces to that history 4 input calls offer explicit EOF handling - specify stream, false eof-error-p, then value to return at EOF - otherwise EOF signals a condition 5 open appears with filesystem operations in the reference manual - accepts filename and keywords controlling stream creation 6 keyword arguments are needed to select output and other modes - condition handlers allow the application to handle failures 7 read parses Lisp syntax, which may be unsuitable for ordinary input - users asked for numbers should not need to understand Lisp forms - author distinguishes a programmer interface from a user interface 8 book first develops normal stream / EOF handling - then adds explicit condition handling 9 standard stream variables: - *standard-input*, *standard-output*, *error-output* - additional streams include *trace-output*, *query-io*, *debug-io* and *terminal-io* 10 actual terminal routing varies by implementation / startup mode - author's tests found several named streams sharing destinations - reported GCL diagnostic routing describes the tested version 11 many I/O calls accept stream designators - nil / omitted stream: standard input or output as appropriate - t: terminal I/O for the ordinary reader / printer functions - pass an explicit stream when its destination matters 12 prin1, print, pprint and princ take an object and optional stream - (prin1 x *error-output*) directs output to the diagnostic stream 13 prin1 prints a readable Lisp representation when possible - string includes quotation marks - character may appear as #\A or #\Newline 14 print adds a preceding newline and a trailing space - pprint performs pretty printing with layout decisions - author considers the historical collection of interfaces awkward 15 princ prints strings without surrounding quotes - prints characters as characters, including actual newline characters - useful for user-facing text 16 terpri writes a newline to the selected output stream - stream argument may be omitted for standard output 17 format uses a control string with ~ directives - format with nil destination returns a constructed string - t destination means standard output for format 18 read is a Lisp parser, not a general numeric-input routine - an unmatched opening parenthesis makes it wait for more input - malformed input can signal reader conditions - user interface must define and handle its own expected format 19 customizing the Lisp reader can support specialized file formats - author recommends separating controlled program data from input supplied by users, whose validity cannot be assumed 20 read-char obtains one character - (read-char stream nil nil) returns nil at EOF - alternative sentinel such as 'eof distinguishes EOF from characters 21 line-length example uses a recursive character-processing loop - EOF -> finish - newline -> print accumulated length; continue with 0 - other character -> continue with length + 1 - unfinished final line is not printed by this particular example 22 Ctrl-C behaviour is implementation-dependent - book's tested script runtimes could emit diagnostics / enter debugger - later handler explicitly addresses SBCL's interrupt condition 23 read-line returns text without its newline - extra return value reports whether EOF ended the line - multiple-value facilities are needed to inspect that information 24 open returns a file stream; default direction is input - standard Common Lisp does not provide a portable Unix socket API - implementations may offer extensions for additional stream sources 25 filename designator can be a string, pathname or stream - pathname objects have their own supporting operations 26 keyword call syntax: keyword followed by its value - (f :weirdnum 13) supplies 13 for :weirdnum - omitted keyword parameters use their defaults 27 keyword symbols also occur as values - they evaluate to themselves - ordinary symbols used as data usually require quotation 28 open directions include :input, :output, :io and :probe - (open "file.txt" :direction :output) requests output - :probe returns a closed stream when the probe succeeds 29 checking existence before opening creates a race - another process can remove / replace the file between operations - handle the actual open result instead of trusting an earlier probe 30 successful open supplies a stream usable by printers - failures may signal conditions requiring handlers 31 open policies distinguish existing and missing files - :if-exists :overwrite writes from the beginning -> it does not promise truncation of an existing trailing suffix - :append writes at the end; nil declines to open an existing file - :if-does-not-exist accepts :error, :create or nil - input example: (open "file.txt" :if-does-not-exist nil) - permission / other failures still need condition handling 32 close closes a stream - optional :abort requests abort-related closing behaviour 33 binary streams use an element type suitable for integer elements - byte-oriented example: :element-type '(unsigned-byte 8) - write-byte receives integer and stream - read-byte receives stream and optional EOF controls 34 condition handling gives application code control over I/O failures 35 Common Lisp conditions support more than simple exception unwinding - book limits discussion to handler-case 36 handler-case evaluates a protected form - clauses specify condition type, bound condition variable and body - (file-error (er) ...) handles a matching file-error - progn can group several protected operations 37 condition objects belong to a type hierarchy - handler for a general type can cover more specific condition types - author criticizes the coupling to the object system 38 file-error-pathname retrieves the associated pathname - portable interface does not expose every OS-specific failure detail - book probes SBCL internals to extract a diagnostic string - private slots / localized strings are unsuitable as stable error codes; the example is specific to the author's tested version 39 book reports different limitations in tested ECL / GCL versions - these observations should not be read as current compatibility guarantees for every implementation version 40 princ can print a condition's human-readable report - its wording comes from the implementation - report text alone is not a portable structured recovery interface 41 worked application: print lengths of lines from a selected file - fall back to standard input when no filename is supplied 42 SBCL script builds on the earlier recursive character loop - do_it(file,len) accepts its input stream explicitly - process_stdin calls it with *standard-input* and zero length 43 opening a file and later signalling a condition can skip plain close - resource cleanup must also work on abnormal exit 44 with-open-file binds the newly opened stream and evaluates its body - closes the stream on normal completion or nonlocal exit - accepts the relevant open options 45 complete example combines opening, processing and handlers - process_file uses :if-does-not-exist nil -> nil stream: print application diagnostic -> valid stream: call do_it - *posix-argv* selects filename or standard input - file-error handler prints a concise report to *error-output* - sb-sys:interactive-interrupt handler ends quietly on Ctrl-C - interrupt condition name and argument access are SBCL-specific 11.1.15 A discouraging conclusion 1 author judges the Common Lisp implementations discussed unsuitable for his preferred practical and teaching use - this is the author's broad assessment based on the preceding tests 2 author still values Lisp's core ideas - hopes for smaller implementations with less inherited complexity 3 principle proposed: application behaviour should be under the programmer's control through the program's source - motivates criticism of imposed diagnostics and runtime behaviour 11.2 Scheme: Lisp, with differences 1 author values Scheme's relatively compact specification - repeats his preference for the smaller Scheme reports 2 many Lisp concepts carry over directly - discussion concentrates on the differences 11.2.1 Chicken Scheme 1 book uses Chicken as its example Scheme implementation 2 tools: csi = interpreter; csc = compiler driver - book's Debian-family package name: chicken-bin 3 Chicken compiles Scheme through generated C - csc runs the Scheme compiler and then the C compiler - intermediate C is intended for compilation, not hand maintenance 4 Chicken's normal symbol handling is case-sensitive - book describes -i for case-insensitive input - this discussion concerns the versions used in the book 5 csi without arguments enters a REPL - rlwrap adds command-line editing - file arguments load definitions before entering the REPL - (load "myfile.scm") or REPL command ,l also loads a file 6 script mode: #!/usr/bin/csi -s - (display "Hello, world!\n") prints a greeting and newline - csc can compile the same script source - command-line-arguments returns arguments without program name - program-name retrieves that name separately 7 Chicken 5 requires imports for facilities that Chicken 4 exposed directly - (import (chicken process-context)) supplies argument access - echo maps a printing function over command-line-arguments 8 book also mentions argv - its script / compiled differences make it less convenient here 9 -ss script mode calls main with the argument list - define main(args) and place application work there - loading definitions into REPL need not run the application 10 compiling the -ss arrangement needs an explicit main call - book supplies it through csc's -postlude option - postlude evaluates (main (command-line-arguments)) 11 small default executables depend on Chicken runtime libraries - book's static-build example uses -static and -strip - -x / -uses library select runtime components in that version - omits eval support when runtime evaluation is unnecessary - author's approximately 2 MB echo is a setup-specific measurement 11.2.2 Visible differences from traditional Lisp 1 Scheme separates the empty list from false - () is the empty list; #t / #f are boolean objects - only #f is false; even () counts as true - nil has no special built-in meaning 2 naming conventions expose the kind of operation - predicates end in ?: null?, number?, pair? - mutation ends in !: set!, set-car!, set-cdr! - conversions: string->list, number->string, char->integer - type-specific comparisons: char=?, string>?, etc. 3 map corresponds to Common Lisp's mapcar - for-each runs the procedure for effects without building a result list; its calls occur in list order 4 several operations have unspecified results - examples: set!, define, display, for-each - an if without an else cannot supply a meaningful value when false - unspecified result is distinct from a guaranteed useful value 5 Scheme requires proper tail calls - tail position can pass control onward without retaining a frame merely to return the same value 6 if evaluates the condition and transfers to the selected branch - selected branch can retain tail position - missing false branch supplies no specified useful result 7 Chicken's void produces an unspecified value - can explicitly finish an effect-oriented function 8 values returns multiple values; call-with-values receives them - (values) produces zero values - zero values and one unspecified value are different cases 9 Common Lisp also supports multiple / zero values - ordinary single-value contexts use its primary-value conventions 10 remaining differences concern the underlying evaluation model 11 Scheme has one ordinary namespace for variable / function values - a function name is a variable whose value is a procedure 12 ordinary application evaluates the operator expression too - resulting procedure is applied to the computed operands - macros / special syntax still follow their own rules 13 lambda is an expression yielding a closure - no Common Lisp function form or #' notation is required 14 funcall is unnecessary - where Lisp uses (funcall f a b), Scheme uses (f a b) - apply remains useful for arguments supplied as a list 15 define establishes both ordinary values and procedures - (define myvar 275) - (define (plus3 x) (+ 3 x)) - shorthand for (define plus3 (lambda (x) (+ 3 x))) 16 definitions belong at top level or in allowed body-definition positions - internal definitions introduce local bindings - local name shadows a same-named outer binding 17 dotted formal-parameter lists express variable arity - (define (myvarfunc x y . rest) ...) - at least two arguments; extras collected into rest 18 Common Lisp expresses the same pattern with &rest - author prefers Scheme's reuse of existing dotted-list notation 19 author values the smaller set of core constructs - contrasts it with Common Lisp coerce, setf and loop 20 Scheme still converts between symbols and strings - symbol->string / string->symbol - escaped names can contain unusual characters 21 ordinary Scheme bindings are lexical - set! changes an existing binding - define / let introduce bindings; implementation extensions may accept more than the portable language requires 22 parameter objects provide controlled dynamic binding - make-parameter / parameterize interact with dynamic extent - continuation re-entry makes that extent more than one time interval - fluid-let is an extension, not a universal R7RS core form 23 other characteristic facilities: hygienic macros and continuations - book leaves macros aside and develops continuations next 11.2.3 Input and output in Scheme 1 display prints an object; newline writes a line break - default destination is current output 2 write prints Scheme-readable notation - strings retain quotation marks; characters use #\... notation - display writes string contents / actual characters - read parses Scheme data; author advises against using it as an ordinary user-input parser without suitable error handling 3 read-char returns a character or an EOF object - eof-object? recognizes EOF - no extra argument is needed to treat EOF as ordinary input 4 write-char outputs a character directly - book distinguishes primitive operations from library procedures 5 peek-char observes the next character without consuming it - char-ready? tests whether input can proceed immediately - book notes limits of Chicken's terminal behaviour in its version 6 R5RS leaves aspects of file-error handling / existing output files insufficiently specified for the author's desired application interface 7 Chicken provides condition-handling facilities - usable to intercept failures instead of exposing default handling 8 Scheme calls I/O streams ports - input and output ports represent the corresponding directions 9 current-input-port / current-output-port are zero-argument procedures - Chicken also supplies current-error-port for diagnostics - example: (display "Error\n" (current-error-port)) 10 author comments on the word current and changing these ports - parameterized current-port facilities depend on Scheme version / implementation; this passage reports his investigation 11 an explicit port is an optional I/O argument - only argument for newline / read-char - second argument for display / write / write-char 12 open-input-file / open-output-file take a filename string - return an opened port on success - failure signals a condition rather than returning a normal port 13 close-input-port / close-output-port close the corresponding port 14 with-exception-handler receives two procedures - handler: one argument, the condition object - thunk: zero arguments, performs protected computation - handler is active while that computation runs 15 for the non-continuable errors discussed, handler must escape - simply returning can cause another exception - example reports the condition and calls (exit 1) - continuation-based escape is another option - condition->list exposes implementation-specific condition data 16 worked script again prints input-line lengths - #!/usr/bin/csi -s also permits compilation by csc 17 Chicken 5 imports condition and process-context modules - do_it reads characters and tests eof-object? / newline - no filename -> use current-input-port - filename -> open, process, close input port - handler writes diagnostic information to current-error-port and exits with status 1 - example does not print a final unterminated line - author suggests C modules for OS-facing work when Scheme's portable / implementation-specific interfaces are insufficient 11.2.4 Continuations 1 continuation = the remaining computation at a particular point - begin by considering what happens after a function returns 2 caller uses the result, completes its work and returns to its caller - continuation represents that entire pending chain 3 remaining computation depends on the value supplied to it 4 ordinary call stacks illustrate a possible representation - return addresses and saved activation information describe pending work, although implementation needs more than code alone 5 Scheme need not represent this using an ordinary hardware stack - semantic requirement is preserving the pending computation 6 captured continuations are first-class objects - can be stored, passed and invoked like procedures 7 invocation supplies the value expected at the captured point - substitutes that value for the result being awaited there 8 captured continuation can survive beyond the original call - invoking it abandons the current continuation and resumes the saved control context with the supplied value - does not undo assignments, I/O or other completed side effects 9 book introduces concrete capture / invocation examples next 10 call-with-current-continuation, commonly call/cc - accepts a procedure of one argument - passes that procedure the current continuation 11 (call/cc (lambda (cc) ...)) binds the captured continuation to cc - captures the continuation of this call/cc expression 12 (cc x) makes the saved call/cc expression deliver x - resumes the work that was waiting for its result 13 the supplied procedure can also return normally - (call/cc (lambda (cc) 25)) -> 25 - (call/cc (lambda (cc) (cc 25))) -> 25 by continuation invocation - second form abandons the lambda's current continuation 14 these minimal examples illustrate control flow rather than useful work 15 continuations can express early returns, exception-like escapes, coroutines and other control arrangements 16 early exit: bind the continuation to a name such as return - enclose the computation inside call/cc and lambda - (return value) immediately supplies the enclosing result - return is an ordinary parameter name here 17 search / exception examples: - search scans with for-each; first matching element invokes return - exhausted list -> #f in the first search implementation - traverse can accept that continuation directly as its callback -> first successful callback escapes all intervening calls -> search2 needs an explicit fallback if a #f miss is required - quad-eq(a,b,c,throw) checks exceptional cases -> a = 0: throw 'NotAQuadraticEq -> negative discriminant: throw 'NoRealRoots -> otherwise compute and return the two real roots 18 call/cc receives either normal roots or the thrown tag - outer let binds the outcome; cond selects a handler - pass throw explicitly through intermediate functions - normal results stay local; exceptional escape skips all those calls 19 this exception-like control transfer needs no object-oriented mechanism 20 right-now returns its own current continuation - (call/cc (lambda (cc) (cc cc))) - continuation is both invoked object and supplied value 21 go-when invokes a saved continuation with itself as argument - re-enters the saved point while retaining the same continuation - greeting followed by go-when -> repeated greeting - outer mutable counter starts at 5 and decreases on each pass -> stop invoking when counter reaches 0 -> five greetings - counter changes persist across re-entry 22 further applications include coroutines, backtracking and generators - book points to Matt Might's worked continuation examples 11.2.5 (*) Continuation-passing style 1 CPS makes the next computation an explicit procedure argument - after computing a result, call continuation k with it - continuation determines where control goes next 2 Pythagorean example: sqrt(x*x + y*y) - *&(x,y,k) invokes k(x*y); +& and sqrt& do likewise - compute x*x; continuation receives x2 - compute y*y; next continuation receives y2 - add x2+y2; next continuation takes its square root - final result goes to original k - nested lambdas express intermediate continuations explicitly 3 CPS is useful as a compiler representation - book describes Chicken's Scheme-to-C implementation technique - generated calls grow a stack-based allocation area - collection copies reachable objects onward and resets that area - this is a particular implementation strategy, not Scheme semantics 4 John Reynolds's historical account surveys discoveries of continuations - links explicit continuation passing with language implementation 11.3 Formatting Lisp-like code 1 indentation makes nested lists readable - author contrasts his fixed-indent style with argument alignment - traditional alignment can make each indentation step depend on the operator name's length 2 function definitions conventionally keep a recognizable header - name / parameters together; body starts on the following line 3 traditional Lisp style groups closing parentheses at the end - author prefers making each enclosing level visible - a close-all marker, such as historical muLISP's ], hides mismatches 4 book's alternative: fixed indentation and separately aligned closings - break a long form after its operator - indent each nested level by the same amount - place its closing parenthesis under the construct's start 5 prefix notation such as quote / #' belongs to the construct - align the closing parenthesis under that prefix, in this style - lambda keeps its parameter list with its header, like defun 6 let needs special care because bindings and body have different roles - short binding list can stay on the header line - long binding list gets its own indented block - optional ;; after its closing parenthesis marks the body boundary - author compares two layouts; these are style preferences 11.4 Logic and declarative programming 1 logic programming describes predicates / rules and asks for solutions - declarative programming states properties of the desired result - leaves the method of finding that result to the implementation 2 logic is one way to write declarative specifications - Prolog / Datalog combine the approaches - book contrasts SQL's declarative model with this logic vocabulary 3 earlier overview supplied introductory examples - following sections develop the operational details 11.4.1 Prolog and its history 1 Prolog emerged in Colmerauer's French research group - Colmerauer and Roussel produced an early implementation in 1972 2 Planner combined Lisp with logical inference ideas - book identifies it as an influence on Prolog 3 full Prolog has effects and control constructs beyond pure logic - solution order matters when search spaces are infinite - depth-first search can remain on one infinite branch 4 pure definite-clause Prolog is described through SLD resolution - author emphasizes operational search and binding environments - his criticism concerns explaining the whole language solely as formal logical inference 5 procedural semantics describe what the solver actually does - clause / goal order; alternative order; creation / undo of bindings - declarative reading alone may not predict termination or effects 6 early implementation papers describe its working data structures - author found the reproduced diagrams difficult to follow 7 Warren Abstract Machine: introduced in 1983 - stack, heap and trail support execution / backtracking - many Prolog implementations compile to related abstract operations 8 Ait-Kaci's 1991 tutorial reconstructs the WAM - author still regards its explanation as demanding 11.4.2 SWI-Prolog 1 book uses SWI-Prolog; executable normally swipl - interactive prompt: ?- - X is 2 * 2. evaluates arithmetic and reports X = 4 - author's claims about alternative implementations describe his assessment at the time of writing 2 member relates a value to a list containing it - member(100,[1,2,3]) fails - successful query may leave alternatives to explore - ; requests another answer; . accepts the current answer 3 member(X,[1,2,3]) enumerates X = 1, then 2, then 3 - each further answer resumes search at an alternative 4 whether the prompt waits depends on remaining choice points - last-element optimization can establish that no alternative remains 5 halt. or end-of-input leaves the interactive interpreter 6 load source using consult('myprog.pl'). or ['myprog.pl']. - swipl -s myprog.pl loads it before entering the interactive loop 7 SWI-Prolog convention: .pl source suffix - also used by Perl, which the author finds inconvenient 8 author reports suffix-related failures in his tested setup - describes tracing attempted filenames to diagnose them 9 book therefore consistently uses .pl for Prolog examples 10 script starts with #!/usr/bin/swipl - merely loading a file may leave the interpreter interactive 11 book's simple greeting executes write, nl and halt in a directive - -q suppresses startup / informational output - shebang example: #!/usr/bin/swipl -q 12 /usr/bin/env can locate swipl through PATH - author notes the argument-limit tradeoff of traditional shebangs 13 initialization(main) selects startup work - book's main/1 arrangement receives command-line arguments - list excludes the executable name in the script example 14 printing the raw argument list is only a teaching shortcut - user-facing output should follow the application's intended format 15 current_prolog_flag(argv,Argv) also retrieves arguments - custom main/0 must arrange normal termination itself 16 author reports unsolicited input prompts and debugger entry on Ctrl-C - relevant behaviour depends on runtime mode / version 17 book's script sets prompt(_, '') and on_signal(int, _, default) - uses main/0 to avoid a reported SWI-Prolog 6.6.6 interaction 18 standalone-building discussion follows the author's tested setup - options and quirks are historical examples, not universal promises 19 that setup required the expected .pl source suffix 20 book uses custom main/0 and an explicit --goal=main build option 21 compiled argument handling in the author's example differed from scripts - he removed the shebang and used current_prolog_flag 22 build options in the example: - -nodebug, -O: execution / optimization settings - -g true: initialization goal - --goal=main: application's entry goal - --stand_alone=true, -o myprog, -c myprog.pl: saved program output 23 author concludes that these interfaces were unnecessarily awkward 11.4.3 Prolog's data model 1 term = a Prolog data expression - heterogeneous dynamic structures resemble Lisp S-expressions 2 numeric atomic terms include integers and floating-point values - book's SWI build normally supports arbitrary-size integers - floating-point representation follows the platform implementation 3 atoms resemble Lisp symbols - lowercase-leading letter / digit / underscore names need no quotes - 'Hello' requires quotes; unquoted Hello denotes a variable - quoted atoms can contain spaces and escaped characters - certain punctuation sequences also form unquoted atoms 4 atoms can be tags, compound-term functors or predicate names - older Prolog code also uses them as text strings 5 atom is narrower than atomic term - numbers are atomic but are not atoms - book's newer SWI model treats [] as a special empty-list value 6 SWI also has string objects and blobs - blobs carry special data, including foreign-interface objects 7 compound term = functor with arguments - date(2019,may,31), person('John Doe',m,1978) - analogous to tagged records with positional fields - arity = number of arguments 8 arguments can themselves be compound terms - circle(point(2,2),1) has principal functor circle - nested point has its own functor and two arguments 9 functor name plus arity identifies a compound shape - point/2, date/3, place/4 - same name with different arity describes a different shape 10 an atom can be regarded as a zero-argument functor - written without parentheses - numbers do not serve as ordinary functor names 11 no whitespace between functor and opening argument parenthesis - f(x) is compound syntax; f (x) does not mean the same thing 12 operator notation is an alternative way to write terms - op(1000,xfx,loves) permits john loves mary - same structure as loves(john,mary) 13 operator declaration gives precedence and associativity - lower precedence number binds more tightly - xfx: non-associative; yfx: left; xfy: right - fx / fy: prefix; xf / yf: postfix 14 arithmetic-looking expressions are also term structures - X is 2 * 2 = is(X,*(2,2)) as notation - executing a query gives the structure its operational meaning 15 clauses are terms too - :-, conjunction comma and disjunction semicolon have operator notation; they are not an unrelated syntax for program text 16 punctuation can additionally act as syntax - comma separates arguments / list elements - terminating dot ends a clause or query 17 lists consist of head / tail pairs - [1|[2|[3|[]]]] = [1,2,3] - [1,2,3|4] has a non-list tail and is improper 18 traditional list-pair functor was '.'/2 - SWI-Prolog 7 changed its internal notation to '[|]'/2 - '[|]'(1,'[|]'(2,[])) represents [1,2] 19 this naming change does not change the head / tail structure 20 lists can contain different term types and arbitrary nesting - suitable unification can also construct cyclic structures 21 traditional double-quoted text often meant a list of character codes - "Hello" could mean [72,101,108,108,111] - distinct from a dedicated string object 22 SWI introduced string objects before making quoted strings the default - book describes the transition through versions 3, 6 and 7 - set_prolog_flag(double_quotes,string) selects string interpretation 23 quote interpretation is configurable - double_quotes modes include string, codes, chars and atom - back_quotes has related implementation-specific settings 24 SWI 7 defaults described by the book: - double quotes -> string; backquotes -> code list - --traditional restores older parsing conventions 25 dedicated text values avoid conflating text with program identifiers - atom interning has lookup / uniqueness overhead - some implementations also restrict atom-name length 26 code lists have their own costs - indistinguishable from ordinary integer lists without context - multiple list cells consume more memory than compact text - traversal / allocation / garbage collection add overhead 27 author welcomes the distinction but questions why it arrived so late 28 variables start with uppercase letters or underscore - examples: X, Person, _list, F15 29 variable scope is one clause or query instance - may be free or bound to a term, including one with variables - backtracking can undo bindings made while exploring an alternative 30 binding is not imperative reassignment - a free variable acquires a binding - later incompatible requirements fail instead of replacing its value 11.4.4 Unifying terms 1 unification makes two terms equal by binding their free variables - may succeed with new bindings or fail when incompatible 2 operator = performs unification - [1,X] = [Y,2] -> X = 2, Y = 1 - atomic terms must match - bound variables are followed to their values - free variables can bind to matching terms - compound functor / arity must agree; corresponding arguments unify - every argument must match consistently with earlier bindings 3 one unification does not enumerate alternative substitutions - success produces the most general compatible bindings - multiple Prolog answers arise from alternative clauses / searches 4 X = Y can link two initially free variables - later binding either one constrains the other to the same value 5 implementation can make one variable refer to the other - orientation does not change their logical relationship 6 explicitly equating two names is often avoidable in source - replace both with one name when they play the same role - compound-term matching still creates such links implicitly 7 X = f(Y) binds X while Y can remain free - filling Y later refines the structure seen through X 8 unification without an occurs check can create rational / cyclic terms - X = f(X) produces a cycle, not a finite tree - X = [1,2|X] repeats 1,2 indefinitely under traversal - unifying that list with [1,2,1|Y] gives a tail repeating 2,1 11.4.5 Relations, predicates and facts 1 relation is the central logical model used here 2 binary relation over A and B specifies which pairs (a,b) belong to it - can be written a R b 3 geometrical example: ellipses inscribed in / around triangles - a relation can connect many objects on both sides - need not determine one unique output for each input 4 when A = B, familiar examples include equality, order and divisibility - 3 < 7 states that the pair belongs to the less-than relation 5 a relation is a subset of the Cartesian product - R is contained in A x B - completely specified by which pairs belong and which do not 6 n-ary relations contain tuples of n elements - same idea extends to unary and zero-argument cases 7 mathematical relations need not have a computable membership test - their definition alone does not provide an algorithm 8 book treats a predicate as the logical description of a relation - avoid picturing it only as a routine returning a boolean - interest lies in all tuples satisfying it 9 predicate / relation terminology comes from different mathematical areas - book emphasizes the common underlying set of satisfying tuples 10 relational-database tables also model sets of tuples - stored table is finite - Prolog procedure may generate indefinitely many solutions 11 unary relation selects individual elements - zero-argument relation concerns the single empty tuple - either contains that tuple, or does not 12 true succeeds; fail / false fail - repeat succeeds and can succeed again on every backtracking visit - repeated proof paths are an operational property, beyond a set's simple membership interpretation 13 user equivalents: success. and failure :- 1 = 2. - always-failing defined procedure differs from an undefined name - undefined procedure normally causes an error 14 repeated success can use a fact followed by a recursive clause - forever. then forever :- forever. - other zero-argument procedures can have effects, including cut 15 predicate identity: atom name plus arity - same compound notation can denote a goal or ordinary data 16 variables do not declare a fixed data type - relation arguments range over the relevant Prolog term universe 17 procedure emphasizes executable behaviour - book uses procedure or predicate according to context 18 facts explicitly list satisfying cases - simplest way to define a finite relation 19 family example: - parent("Mary","Ann"); parent("Mary","John") - parent("George","John") - male("George"), male("John"); female("Mary"), female("Ann") - each fact is a separate term ending with a dot 20 fact-based relations often act as the program's database - rules supply the processing logic 21 SWI can also modify dynamic rules at runtime - author recommends retaining a clear distinction between program logic and changing data 11.4.6 Rules and procedures 1 rules describe cases without explicitly listing every satisfying tuple - loves(X,Y) :- parent(X,Z), parent(Y,Z) would infer affection from a shared child; author rejects it as a real-world assumption - loves("Don Juan",X) :- female(X) expresses the example's rule - loves("Vorona",_) accepts any second argument - each bare _ is a fresh anonymous variable - one-occurrence named variables can produce singleton warnings - book calls variable-containing unconditional clauses rules; ordinary Prolog terminology also permits non-ground facts 2 program consists of clauses, each ending with a dot - rule: Head :- Body. - body absent: unconditional clause - head absent: directive executed when the source is processed 3 head identifies the procedure by its functor / arity - clauses normally grouped together for readability - their source order determines the order of attempted alternatives 4 body combines goals - comma: conjunction, both must succeed - semicolon: disjunction, an alternative may succeed - parentheses override grouping; comma binds more tightly 5 goal is a term used as a procedure invocation - conjuncts normally execute left to right 6 goal may fail, succeed once or succeed with remaining alternatives - choice point stores where another attempt can resume - disjunction also introduces alternatives 7 backtracking returns to the latest available choice point - undoes bindings made along the abandoned search path 8 built-in procedures can implement special operations / effects - user-defined procedures follow the ordinary clause-search rules 9 procedure invocation tries clause heads in order - unify goal with a fresh instance of a head - successful unification -> solve that clause's body - retain a choice point if further clause alternatives remain 10 last matching clause needs no choice point for later clauses - goals inside its body may still create their own alternatives 11 failed head unification proceeds to the next candidate clause - exhausting candidates makes the goal fail 12 recursion expresses repeated relational structure - every activation has fresh local variables - matching can link variables across these separate instances 11.4.7 Procedure calls, argument modes and inversion 1 goal arguments can be constants, variables or partially built structures - bound variables behave as their values - solving a goal may bind initially free variables 2 logical reading: find values satisfying the relation - procedural reading: free arguments can receive outputs 3 ancestor example adds recursion to parent facts - ancestor(X,Y) :- parent(X,Y). - ancestor(X,Y) :- parent(X,Z), ancestor(Z,Y). - direct parent, or parent of an ancestor of Y 4 book adjusts older SWI double-quote interpretation for string names - other dialects may require atoms or different text conventions 5 ground queries check a relationship - Lucas is Laura's ancestor; Jason is Joseph's - Jason is not Fred's ancestor in the supplied tree 6 several ancestry paths can produce repeated successful proofs - even a ground query can therefore leave alternatives 7 leaving arguments free asks for related people - ancestor(X,"John") finds Jessica, Lucas, Jason in search order - ancestor("Jason",X) finds his descendants - ancestor(X,Y) enumerates all 22 pairs in the supplied example 8 argument modes describe which arguments are supplied / free - (+,+), (+,-), (-,+), (-,-) - one relation working in different directions -> inversion 9 this flexibility supports declarative thinking - describe the required relationship instead of a fixed input-output direction for every procedure 10 del_any removes zero or more occurrences of a selected element - n matching occurrences give 2^n keep/delete choices - distinct choices can sometimes produce the same resulting list 11 del_any(Element,Source,Result) is a ternary relation - Result is obtainable by optional deletion of Element from Source 12 three recursive cases: - del_any(_,[],[]). - matching head: delete it and recurse on the tail - any head: retain it and recurse, attaching it to the result tail - del_any(1,[1,2,1,3,1],L) explores eight keep/delete choices 13 clause order determines answer order - delete clause first -> answers deleting an earlier match first - swapping delete / keep clauses reverses that preference 14 the same relation can check a proposed result or infer the deleted value - del_any(X,[1,2,1,3,1],[1,2,3]) finds X = 1 - del_any(X,[1,2,3],[1,2]) finds X = 3 - with only Source fixed, enumerate possible deletions and results - unchanged Source can leave Element unbound 15 reconstructing Source introduces infinitely many possibilities - delete-first search can recurse indefinitely before an answer - keep-first order finds [2,3], [2,3,1], [2,3,1,1], ... - remains on that infinite branch and never reaches [1,2,3] 16 logical invertibility does not guarantee useful search in every mode - termination and control-sensitive built-ins also matter 17 join(A,B,C) means C is A followed by B - counterpart of the built-in append relation 18 list representation suggests recursion over the first list - second list can be shared as the final tail 19 definition: - join([],L,L). - join([H|T],L,[H|M]) :- join(T,L,M). - matching the result structure in the head avoids a separate result variable and explicit final unification 20 join(X,Y,[a,b,c]) enumerates all splits - [], [a,b,c] - [a], [b,c] - [a,b], [c] - [a,b,c], [] 21 listrev/2 uses listrev/3 with an initially empty accumulator - base: listrev([],A,A) - step: listrev([H|T],R,A) calls listrev(T,R,[H|A]) - forward mode reverses the supplied list - reverse mode finds the intended answer, then may search forever if asked for additional answers 22 finding a correct first solution is not enough for reliable enumeration - subsequent search can still diverge 23 inside another procedure, later failure may demand another answer - there is no interactive user to stop the unnecessary search 24 next section changes control flow to avoid this divergence - illustrates the difference between relation and search procedure 11.4.8 Negation and cut 1 cut, written !, commits within the current procedure invocation - discards its alternative clauses and choices created to the left since that invocation began - later failure does not restore those alternatives 2 cut affects procedural search, not just logical relationships - can improve termination / efficiency or remove valid answers - therefore can restrict supported argument modes 3 negation as failure: not(T), commonly written \+ T - succeeds if attempting T fails - fails if T finds a solution - exports no bindings made while testing T 4 this is not a generator of values satisfying logical negation 5 order-sensitive example: - X = abra, Y = kadabra, not(X = Y) succeeds - X = abra, not(X = Y), Y = kadabra fails - second version tests while Y is free, so X = Y can succeed 6 A \= B tests that A and B cannot unify now - equivalent to negation-as-failure of A = B - does not install a persistent inequality constraint 7 book uses not; SWI documentation normally uses \+ 8 del_all must delete every matching occurrence - keeping both unrestricted delete / keep clauses would still define the nondeterministic del_any relation 9 guard the keep clause with X \= Element - works when source and deletion element are supplied - del_all(X,[1,2],[2]) finds X = 1 - del_all(X,[1,2],[1]) fails although supplied X = 2 succeeds - free Element makes the early non-unification test fail 10 var / nonvar could dispatch to separately implemented modes - inversion would then require extra procedural code 11 cut version commits when empty-list or matching-head case applies - base clause ends with ! - delete clause starts its body with !, then recurses - remaining keep clause no longer needs the negative guard - removes useless alternatives in the intended supplied-input mode 12 return to accumulator-based listrev - smallest problematic reverse query: listrev(X,[]) 13 trace must distinguish same-named variables in different activations - book uses depth indices for that explanation 14 variables / structures can survive an individual predicate activation - runtime must preserve bindings still reachable by the computation 15 printed fresh variables can have generated names - pred(X,Y) :- X = f(Y) queried with pred(X,_) can print X = f(_G894), with an implementation-generated suffix 16 listrev/2 forwards the query to listrev(X,[],[]) - initial accumulator and required result are both empty 17 base clause succeeds with X = [] - recursive clause remains an alternative 18 after that answer, backtracking undoes X's binding - recursive alternative sets X to [H|T] - calls helper with required result [] but accumulator [H] 19 base case can no longer match the nonempty accumulator to [] - recursive clause keeps adding arbitrary heads indefinitely 20 cut after successful helper base case stops that later search - listrev([],A,A) :- !. - intended forward / reverse finite-list modes now finish 21 cut can therefore improve usable inversion in a particular mode - does not imply every use of cut preserves all modes 22 in del_all_cut, pruning changes which solutions the clauses admit - removes keep choices for matching elements 23 in the finite-list listrev modes discussed, pruning removes a barren search branch without changing the required answer - this operational distinction motivates the usual green / red cut distinction; correctness depends on the intended modes 11.4.9 Arithmetic 1 arithmetic includes integers, floating-point and rational values - example rational expression: 2 rdiv 3 2 arithmetic notation initially constructs ordinary terms - -1 * (3 * X - 25) does not evaluate merely by being written - can be stored, matched or embedded in another term 3 is evaluates its right argument and unifies the result with its left - X is 4*5 -> X = 20 - then A is -1*(3*X-25) -> A = -35 - every variable used arithmetically must already have a value - an unbound arithmetic operand causes an error, not ordinary failure 4 list-length example first obtains the tail length, then adds 1 - listlen([],0) - recursive clause: listlen(T,TL), L is TL+1 - <, >, =<, >=, =:=, =\= evaluate both operands before comparison - numeric equality =:= differs from term unification = 5 ordinary is / comparison operations are evaluators, not equation solvers - this limitation does not describe separate constraint libraries - arbitrary expressions do not admit a universal symbolic solver 6 prefix(Prefix,List,N) can compute using known N - base: prefix([],_,0) - recursive case decrements N, then processes matching list heads - supplying two lists but leaving N free fails at N2 is N-1 7 later section uses binding-state tests to support different modes 8 ten/1 example seeks the integers 1 through 10 without listing them - direct facts or member with a fixed list would work but do not illustrate the search problem being investigated 9 naive recursion: ten(1); then ten(Y), X is Y+1, X =< 10 - finds all ten answers for free X - afterward keeps recursively searching without termination - unsuitable supplied values can also cause endless search 10 moving the bound test is insufficient - before recursion: free argument is not yet evaluable - after recursion: search can still remain unbounded 11 unconditional cut at the wrong point also fails - before recursion does not remove recursive search choices - after first recursive answer can discard later valid answers 12 trace explains lost answers - recursive Y = 1 yields X = 2 - cutting its remaining alternatives prevents generation of 3,4,... - behaviour also changes between supplied and free X 13 commit only when the generation boundary has been reached - smaller Y must retain alternatives 14 working version: - ten(1). - ten(X) :- ten(Y), ((Y >= 10, !, fail); X is Y+1). - at boundary: cut and fail - below boundary: compute next value without pruning later answers 15 alternative bounded generator mbetween(A,B,X): - A > B -> cut and fail - otherwise offer X = A - subsequent alternative increments A and recurses - ten(N) becomes mbetween(1,10,N) - supplied bounds make progress / termination explicit 11.4.10 Input and output 1 author recalls his criticisms of older Lisp / Scheme I/O conventions 2 book distinguishes Edinburgh-style and ISO-style Prolog I/O - mainly differ in how files / current streams are managed 3 write prints values; nl adds a newline - read parses Prolog syntax, which needs care as a user-input format - author recommends explicit character processing for these examples 4 old get skips whitespace; get0 reads it too - binds output argument to the character code - -1 indicates EOF in the examples 5 put outputs a character given its code - put(65) prints A under the illustrated character encoding 6 text input decodes characters according to stream encoding - non-ASCII character code can differ from its original input bytes 7 byte input requires suitable stream configuration - get_byte is intended for byte-oriented streams - book uses encoding(octet) to obtain unconverted byte values 8 get_code obtains a code; get_char obtains a one-character atom - get_char reports EOF using end_of_file 9 corresponding outputs: put_code, put_char and put_byte - character and byte interfaces must match the chosen stream model 10 Edinburgh style keeps a current input stream - see(File) opens / selects it - seen closes current file and restores standard input - see(user) switches to user input without closing another file 11 copy-file example uses repeat and backtracking as a loop - read a character - EOF -> succeed, cut off repeat, close file - otherwise print character and fail deliberately -> backtrack to repeat and read the next character 12 tell / told similarly select / close current output - append opens for appending - seeing / telling retrieve current stream designators - save current output, append a greeting to a file, restore output 13 using filenames as stream identities makes independent uses interfere - a module may unknowingly select a file already in use elsewhere 14 SWI exceptions can handle failures in the older I/O interface too 15 newer interface exposes distinct stream objects - optional atom aliases identify streams separately from filenames - printed stream representation is not ordinary readable source data 16 user_input / user_output / user_error initially denote standard streams - current_input / current_output designate implicit I/O destinations - changing an association does not assign a value to the atom itself 17 explicit-stream versions add the stream as first argument - write(user_output,Text); write(user_error,Diagnostic) - distinguishes selected standard destinations from current output 18 open takes filename, mode, result stream and optional option list - SWI also offers extensions such as opening a pipe to a command 19 modes: read, write, append, update - write starts fresh / truncates - update writes over existing contents without initially clearing it 20 result argument obtains a stream object - book also discusses establishing an atom alias for the opened stream 21 even user_* aliases can be reassociated - set_stream(Stream,alias(user_output)) changes that association 22 fourth argument is a list of stream options - book explicitly chooses [encoding(octet)] for byte interpretation - text applications instead need their intended encoding 23 close closes a stream - book describes special treatment of initial standard streams - closing reassociated aliases can restore their original streams 24 author considers explicit-stream I/O closer to the desired OS model - error handling still requires separate treatment 25 I/O errors are exceptions rather than ordinary goal failure - ordinary failure would undo bindings used to return error details 26 throw(Term) raises an exception - catch(Goal,Pattern,Handler) executes Goal - matching exception unifies with Pattern and runs Handler - unmatched exception propagates outward - handler can use variables bound while matching the exception 27 built-in errors commonly use error(Formal,Context) - examples: existence_error, permission_error, io_error - formal term classifies the error; context carries further details 28 book's observed diagnostic wording / locale behaviour is version-specific - structured error categories are preferable to parsing message text 29 worked line-length program: - reading(Stream,N) reads a code and calls handle(Stream,Code,N) - EOF -> stop; newline -> print N and continue with 0 - other code -> increment N and continue - error handler decomposes error terms and writes to user_error - process_file opens with octet encoding and protects work with catch - main configures prompt / SIGINT, chooses filename or standard input - halt ends execution; this example omits explicit file closing - only newline-terminated lines cause a length to be printed 11.4.11 Analysing atoms and terms 1 built-ins expose information about terms and bindings 2 var(X) succeeds when X is currently a free variable - linking two free variables still leaves var true for both - var(f(X)) fails even when X is free: f(X) is already a compound 3 nonvar succeeds for every non-variable term - does not require a compound term's internal variables to be bound 4 binding-state tests are procedural facilities - can dispatch between implementations for different argument modes 5 prefix example selects arithmetic order according to N - nonvar(N): decrement N before recursing - var(N): recurse first, then calculate N from the tail length - prefix(P,[1,2,3],N) enumerates lengths 0,1,2,3 and their prefixes - =.. relates a term to [Functor|Arguments] -> X =.. [a,b,c] constructs a(b,c) -> p(1,2,3) =.. Y gives [p,1,2,3] - construction / decomposition require enough structure on one side 6 name/2 relates atom or number to character-code list - name(12321,X) -> [49,50,51,50,49] - name(X,[55,55,55]) -> 777 - string_codes relates a string object to codes - atom_string relates an atom to a string object 11.4.12 Lists of solutions 1 findall(Template,Goal,List) collects every answer from Goal - requires search to finish before producing its complete list - no answers -> [] 2 template determines what is copied into the list for each success - can contain one variable, several variables or a constructed term 3 color facts red / green / blue illustrate template choices - X -> [red,green,blue] - [X] -> [[red],[green],[blue]] - f(X) -> [f(red),f(green),f(blue)] - X+X builds terms such as red+red; no arithmetic is implied - constant template yields repeated copies of that constant - ancestor example uses [A,D] or A/D to retain both related people while excluding direct-parent pairs 4 interactive answer printing can abbreviate long lists - explicit write(L), nl displays the collected structure - book then uses abort to stop further query-result presentation 5 bagof groups by free goal variables omitted from the template - bagof(D,(ancestor(A,D),not(parent(A,D))),L) - separate descendant list for each A - multiple groups appear as separate backtracking answers - unlike findall, bagof fails when there are no solutions 6 setof also sorts each answer list and removes duplicates - otherwise uses bagof-style grouping 11.4.13 Working with the database 1 dynamic predicates can change during execution - :- dynamic parent/2, male/1, female/1. - asserta inserts a clause before existing clauses - assertz inserts after them - position affects search order; SWI's assert follows assertz 2 retractall removes every clause matching the supplied head pattern - retractall(parent("Jessica",_)) removes her parent entries - succeeds even when nothing matched 3 retract removes matching clauses one at a time - binds variables to the removed clause's values - on backtracking, can remove further matching clauses - fails when matching possibilities are exhausted - assertion / retractall can establish a previously absent dynamic predicate in SWI; explicit declaration still communicates intent 4 dynamic rules can change executable behaviour as well as data - author warns against constructing executable clauses from unchecked external input 5 author recommends keeping data parsing separate from loading code - consult executes source; read alone parses terms, so how parsed terms are subsequently used also matters 6 database can imitate global mutable variables - global_vars(Name,Value) stores one binding per chosen name - assign_var retracts old entries, then asserts the new one - updates are effects and are not undone by ordinary backtracking - author discourages this as a substitute for relational programming 11.4.14 Formatting Prolog code 1 clause-based languages group similar heads into procedures / functions - formatting should make both clause boundaries and body structure easy to see 2 short clause may fit on one line - otherwise put body below the head with a fixed indentation - choose consistently between compact body lines and one goal per line - avoid aligning later goals under a first goal after a long head -> would make indentation depend on head length 3 disjunction requires visible separation of alternatives - short alternatives can occupy separate lines - long alternatives can use condition / cut as a branch header - separate semicolons make alternative boundaries clear - align grouping parentheses and use a constant indentation step for nested goals 11.5 Lazy evaluation 11.5.1 Two possible strategies for evaluating expressions 1 eager evaluation computes an expression when its value is needed for a binding, such as an ordinary function argument - arguments are evaluated before the function body uses them - also commonly called strict evaluation 2 a higher-level value need not have only one machine representation - it can be represented by an expression that will produce the value - static typing does not prevent such a representation 3 lazy evaluation delays work until the value is actually demanded - retain the expression in an unevaluated form - evaluate it when necessary and share the resulting value 4 unused function arguments need never be evaluated - f uses y only when x is zero - f(1, g(a,b)): return from the x branch without evaluating g - eager argument evaluation would compute g before entering f 5 this can also change termination - if the unused g diverges, eager evaluation never reaches f's result - lazy evaluation can still produce it 6 laziness is not a universal speed optimization - delayed computations need storage and bookkeeping - eager code can also avoid known unnecessary work - the main interest is its programming model 7 lazy structures can be potentially infinite - keep the unrequested remainder as a suspended computation - compute another finite part whenever it is demanded - no finite request requires materializing the entire structure 8 uncontrolled side effects conflict with demand-driven evaluation - an expression may run later than expected or never run - output / mutation cannot rely on textual evaluation order alone - pure lazy languages need explicit mechanisms for ordered effects 11.5.2 Hope and other lazy languages 1 pure functions readily transform available inputs into results - interaction is harder: later input can depend on earlier output - lazy languages need a model for ordering that interaction - Haskell is the prominent example discussed by the book 2 the author finds Haskell too involved for this short introduction - wants the evaluation model visible without extensive extra machinery - this is a teaching choice and assessment, not a language limitation 3 Hope is chosen as a small illustrative language - historically used in Field and Harrison's functional-programming book - demonstrates lazy evaluation and static typing with type inference - the implementation discussed here is Hopeless 4 Miranda and Clean are mentioned as other lazy languages - the historical licensing / availability remarks reflect the book's date - Hope keeps the examples small enough for this chapter 11.5.3 The Hopeless interpreter 1 the implementation began with Ross Paterson - the book recounts later maintenance and disappearing project sites 2 the author distributes a modified version - includes reading standard input through an empty filename - build the downloaded source as an ordinary user - installation places binary, manual and library files under /usr/local 3 the archive version named in the book is historical - its exact filename is not a language requirement 4 -f tells Hopeless to read program text from a file - usable in a script shebang - write argv prints the command-line arguments without -f, use the interactive interpreter - rlwrap supplies command editing / history 5 interactive prompt: >: - ordinary Hope sentences end with a semicolon - a newline alone may leave the interpreter waiting for more input 6 edit is an exception to the semicolon requirement - supplying one remains acceptable 7 enter an expression to evaluate it - output includes both value and type - 2 + 3 -> 5 : num dec declares a named value's type; --- supplies its definition - cube : num -> num - cube x is defined as x*x*x 8 use module loads a module - the described interpreter appends .hop and searches locally - file-loading flexibility is limited in this implementation 9 edit module invokes the editor from EDITOR, or vi by default - after editing a loaded module, its definitions are refreshed 10 editing errors cause the interpreter to reopen the editor - diagnostic lines begin with @ - correct the error or comment out unfinished code with ! 11 use can also enter this editing cycle when a loaded file contains errors 12 display shows definitions entered during the current session - loaded modules appear as use directives rather than expanded contents save writes this session state to a .hop file 13 Hopeless is an experimental teaching implementation - its I/O limitations become apparent later 11.5.4 Hope's lexical rules and syntax 1 program consists of semicolon-terminated sentences / directives - a sentence may span several lines - line width is a readability convention, not an interpreter limit 2 lexical elements: - ! begins a comment through the end of the line - commas, semicolons, parentheses and brackets are delimiters - number, character and string literals use familiar notation - quoted characters / strings allow escapes such as \n and \t identifier forms: - letters / underscores followed by letters, digits or underscores * trailing apostrophes are allowed - symbolic names made from suitable punctuation characters - word-like and symbolic tokens can be adjacent, as in a+b-25 3 reserved syntax includes declaration, type and expression keywords - dec, data, type, lambda, let, letrec, if, then, else - also directive names and punctuation such as --- and <= - some reserved words exist for compatibility with other dialects - backslash, use and infixrl alias lambda, uses and infixr 4 infix / infixr can declare operator-like use of nonreserved names - allow custom infix expression notation 5 arithmetic and comparison operators are library function names - +, -, *, /, div, mod, =, /=, <, =<, >, >= - their names are not reserved syntax - no unary minus: write 0 - z when needed 6 built-in type names and many predefined names are not keywords either 11.5.5 Data model and type system 1 Hope is statically typed - functions accept / return values of appropriate types - list elements must share one type - compound types are built from simpler ones 2 three basic types in this implementation: - num: numeric values represented using C double - truval: true / false - char: single-byte characters 3 the historical dialect in the referenced textbook differs - num represents integers there, with a separate real type 4 tuple: fixed number of ordered components, possibly of different types - (25, 'a', true): num # char # truval - # combines component types; commas combine component values functions accept and return values that may themselves be tuples - a multiargument function can be viewed as taking one tuple 5 list: variable-length sequence of elements of one type - length is not part of its type 6 constructors distinguish structured alternatives - resemble Prolog functors, but belong to declared types - a nullary constructor is a distinct named value - ++ separates alternatives, such as red ++ green ++ blue 7 data introduces a new type and its constructors - data Rainbow == red ++ orange ++ ... - data PlanePoint == Point(num # num) - type names and constructor names are separate declarations ++ and new constructors occur at the declaration's outer level - unlike #, which can form a tuple type wherever a type is expected 8 MaybeNum example: Good(num) ++ Bad - SafeDiv(_,0) returns Bad - otherwise return Good(x/y) - failure is represented explicitly in the result type constructor identity also includes arity in this implementation - Point with two and three components can belong to different types - same constructor name / arity cannot be reused in another type 9 type defines an alias; data introduces a constructor-based type - type Vec3num == num # num # num - a plain tuple needs no new data constructor 10 recursive data declarations can describe lists - NumList: NumNil or NumCons(number, another NumList) - separate fixed-element types would otherwise need new constructors parameterized type avoids that repetition: - List(any): Nil or Cons(any, List(any)) - List(num), List(char), List(List(char)) belong to one family - constructors are shared across that family 11 a one-element tuple is just the element - parentheses can be omitted around a simple argument - commas create tuple structure; parentheses mainly group expressions 12 type application also permits omission of unnecessary parentheses - List any and List(any) express the same parameterized type 13 Nil has a polymorphic element type - its value contains no element that would constrain that type - the interpreter reports an unknown type variable, such as alpha 14 built-in lists already provide this construction - type constructor: list - empty list: nil or [] - head :: tail constructs a nonempty list - :: associates to the right - 1 :: 2 :: 3 :: nil equals [1,2,3] 15 string is a list of characters - "Hope" equals ['H','o','p','e'] 11.5.6 Functions in Hope 1 declare a function using dec - define it with one or more --- equations 2 these directives can also introduce constants - dec gives a name and its type after : - --- gives the defining value after <= 3 function type: argumentType -> resultType - Cube: num -> num; result x*x*x - SumProd: num # num -> num # num - SumProd(5,6) returns (11,30) 4 several defining equations use pattern matching DropElems example, for an intended nonnegative count: - empty input list -> empty list - zero count -> original list - otherwise remove the head and recurse with count minus one _ marks an unused pattern component - avoids inventing names for ignored values the implementation selects a most-specific matching pattern - clause order is not the Prolog-style selection rule 5 most-specific selection can still leave ambiguity - DropElems(0,[]) matches both base cases - this example is harmless because both return [] 6 deep constructor patterns can make matching more complicated - overlapping cases can imply different results - the implementation promises deterministic but otherwise unspecified selection in such cases - avoid depending on an unspecified tie-breaking choice 11.5.7 The if and let expressions 1 function bodies can combine arithmetic, constructors and function calls - if adds conditional values - let / where add local names - the chapter develops if and let 2 if A then B else C is an expression - A must be boolean - B and C must have the same type - evaluate only the selected branch to obtain the result - both branches are required; there are no effect-only statements here 3 let V == E in B introduces local bindings through a pattern - match pattern V against E; use its bound names in B - shared binding avoids writing the same computation repeatedly - let x == f(a,b,c) in (p(x),q(x),r(x)) patterns can unpack structured results: - tuple (x,y,z): extract three components of a returned vector - list [x,y,z]: extract three list elements - head :: tail: separate a nonempty list - compute sqrt(x*x+y*y+z*z) from the extracted coordinates 4 patterns can use previously declared constructors - a variable may occur only once in the pattern - new local variables are not in scope within E - let matching is therefore not Prolog unification 5 a same-named variable inside E refers to an enclosing binding - otherwise it is an unbound-name error - recursive bindings require letrec in this implementation 6 BreakString: split a character list into a list of word strings recursive helper works on the tail before the current character - returned list's first word is considered unfinished - nonspace: prepend the current character to that first word - space before a nonempty word: prepend a new empty unfinished word - space before an empty unfinished word: ignore the extra space 7 base case: empty input returns [[]] - one empty unfinished word preserves the helper's invariant 8 wrapper removes a remaining leading empty word - needed for empty input, all-space input and leading spaces - the worker is named BreakStringDo 9 let unpacks the worker result; if tests whether the first word is empty - nonspace branch rebuilds (c :: Word) :: List - space branch either preserves the empty word or starts a new one alternative without if / let: - DropFirstEmpty uses patterns to remove an initial empty word - CharToFirstWord prepends a character to the first word - helper calls and pattern equations express the same algorithm 11.5.8 Polymorphic functions 1 DropElems never examines the type of a list element - its algorithm works for characters, numbers or other values - only its original numeric declaration was too restrictive 2 this resembles the motivation for C++ function templates - static typing need not force duplicate algorithms 3 polymorphic declarations use type variables - alpha, beta and gamma are predefined - typevar introduces more names when needed general DropElems type: - num # list(alpha) -> list(alpha) - keep the existing equations unchanged local variable types are inferred rather than written in the body 4 data declaration parameters need no separate typevar declaration - their role is clear from that context - dec must distinguish type variables from concrete type names 5 Hopeless does not expose C++'s template / generated-instance distinction - no separate compilation and linking boundary is involved here - callers use the polymorphic function directly 6 internal specialization is an implementation question - changing such internal choices need not change program semantics 11.5.9 Anonymous functions and higher-order functions 1 higher-order functions receive functions as arguments - anonymous functions supply convenient local behavior - closures retain free-variable bindings - immutable bindings simplify the closure model 2 map example: transform every list element and return the result list 3 the example accepts one list and a one-argument function - unlike variadic map facilities in some Lisp dialects 4 input elements have type alpha; transformation results have type beta - the supplied function therefore has type alpha -> beta - the algorithm need not know either concrete type 5 map type: (alpha -> beta) # list(alpha) -> list(beta) - empty list -> empty list - nonempty list -> f(head) :: map(f,tail) Times10 example maps [1,2,3,4] to [10,20,30,40] - lambda x => 10*x avoids a separate named function - backslash can abbreviate lambda functions can also return closures: - MakeAdder x returns lambda y => x+y - MakeAdder 21 produces a function adding 21 - applying it to 19 gives 40 - a let binding can name it, or it can be applied immediately 6 -> associates to the right - num -> num -> num means num -> (num -> num) operator sections fix one operand: - (+t): x -> x+t; (t+): x -> t+x - (-2) subtracts 2; (20-) subtracts its argument from 20 - mapping (::[100]) creates [value,100] for each input element 7 an infix operator in parentheses denotes its two-argument function - (+) corresponds to lambda (x,y) => x+y 8 anonymous functions can contain several pattern clauses - separate alternatives with | - example: remove an initial empty list when present - Hopeless infers the lambda expression's type 9 ordinary let can be expressed by function application - let P == E in B equals (lambda P => B) E 11.5.10 The letrec expression 1 letrec V == E in B resembles let - its new names are available in both E and B - permits a definition to refer to itself 2 local recursive / mutually recursive functions are an immediate use - bind a local drop_elems lambda - its recursive branch can refer to drop_elems - no global declaration is required 3 laziness also permits recursive data - letrec lst == 1 :: 2 :: lst - lst begins with 1 and 2, then continues with itself - taking five elements gives [1,2,1,2,1] - :: is right-associative: 1 :: (2 :: lst) 4 an eager Lisp / Scheme list can instead be made cyclic by mutation - replace its final tail with a reference to the list itself - Hope constructs the cycle through a recursive lazy binding - the example requires no destructive update 11.5.11 Folding lists 1 fold combines a sequence using a supplied operation - laziness gives this familiar technique additional possibilities 2 the section uses a right fold - unlike a usual accumulator-style left fold, its recursive call is inside the combining operation - demand determines whether that recursive result must be computed 3 right-fold structure: - f accepts an element of alpha and a result of beta - f returns beta - a seed of beta represents the empty-list case - finite-list expansion: f(first, f(second, ... seed)) 4 Reduce takes the combining function, list and seed - type: (alpha # beta -> beta) # list(alpha) # beta -> beta - empty list -> seed - nonempty -> f(head, Reduce(f,tail,seed)) examples: - (+) with seed 0 sums [1,2,3,4] to 10 - (*) with seed 1 multiplies it to 24 5 first Member implementation uses the fold to test membership - combiner: if ok then true else x = element - ok is the recursive fold of the remaining list - testing ok first forces traversal of the tail - even Member(1,[1,2,3]) reaches the end before succeeding if is strict in its condition: choosing a branch needs that value 6 revised combiner: if x = element then true else ok - compare the current element before demanding the recursive result - matching the head returns true immediately - the unevaluated fold of the tail is discarded - a right fold can consequently stop after a finite prefix 7 understanding demand is essential to writing lazy programs - tracing evaluation exposes why equivalent finite results can have very different termination / resource behavior - experience makes these demand relationships easier to recognize 11.5.12 Infinite data structures: examples 1 lazy data can represent structures whose full evaluation never finishes - even some otherwise eager languages support lazy structures 2 :: is non-strict in both components From x = x :: From(x+1): an unbounded ascending list - From 1 represents the natural-number sequence - asking for the entire printed result never completes 3 finite consumers make such lists useful - Nth uses one-based indexing in the first example - FirstN returns a prefix of the requested length - Nth(From(20),30) -> 49 - FirstN(From(10),3) -> [10,11,12] - these examples assume suitable counts and sufficiently long lists 4 only demanded structure is materialized - the rest remains an unevaluated recursive expression - finding a later element forces enough list structure to reach it 5 prime-number example starts from the idea of sieving - choose the first remaining number as prime - eliminate its multiples from the remaining candidates - a finite initial array requires a chosen upper bound 6 lazy filtering avoids choosing that bound beforehand - Filter(n,list) skips elements divisible by n - Sieve(n::rest) returns n :: Sieve(Filter(n,rest)) - apply Sieve to From 2, then take the requested prefix - the 1,000th prime is 7,919; the 10,000th is 104,729 - this repeated-filter implementation becomes expensive as work grows - it illustrates laziness rather than an optimized sieve algorithm 7 Pascal's triangle can be an unbounded list of finite rows NextLineRest: - sum adjacent entries and recurse - final singleton supplies the trailing boundary value NextLine prepends 1 to complete the next row PascalsTriangleBuild: - return current row followed by construction from NextLine(current) - start from [1] Cnk uses zero-based indexing in this second example - select row n, then entry k - only the portion needed for that coefficient is demanded 11.5.13 Input and output in Hope 1 Hopeless is experimental and lacks robust application error handling - examples concentrate on the evaluation model 2 ordinary modifying I/O operations do not fit pure expression evaluation - streams need another representation 3 lazy lists provide that representation - an input stream becomes a not-yet-completed list of characters 4 read filename returns a lazy character list - actual reading occurs as characters are demanded - evaluation may block waiting for input - empty filename, "" or [], selects standard input in this version 5 several input streams can coexist as separate lazy lists - combine their references in tuples or other structures - demand characters from whichever stream is needed 6 output must also be incremental for interaction to work - cannot wait for the complete output list before emitting its prefix 7 write evaluates a character-list expression and emits available characters - a potentially infinite result can therefore produce ongoing output 8 write is an interpreter directive, not a callable Hope function - allowed at the program's top level - cannot appear as an operation inside a function body 9 the book organizes a program around one final write directive - define the functions first - call a main function returning a character list - main constructs the output in the required order 10 this interface severely limits coordinated output to several destinations - shell redirection can choose the destination of standard output 11 input denotes standard input in the expression given to write - elsewhere use read "" in this implementation 12 additional library operations: - num2str / str2num: convert numbers and their textual forms - <>: concatenate lists - argv: list of command-line argument strings 13 Pascal-triangle program has three modes - two arguments n,k: output the chosen binomial coefficient - one argument n: output row n - no arguments: display successive rows on Enter, stopping at EOF 14 start with a Hopeless script header - reuse NextLineRest, NextLine, PascalsTriangleBuild and Cnk 15 NumList2Str builds text from a numeric list - empty list -> empty text - prepend num2str(head), a space and the conversion of the tail interactive helper receives input characters and remaining triangle rows 16 LineByLine algorithm: - EOF -> empty output - newline -> current row's text followed by processing the next row - other character -> skip it without advancing the triangle - express cases through if or separate pattern equations prepend a synthetic newline to the input for interactive startup - causes row zero to appear before the first user keypress 17 main dispatches by the shape of argv - []: interactive helper - [n]: convert n and format the selected row - [n,k]: convert both and format Cnk(n,k) - more arguments: return an explanatory message final write evaluates main(argv,input) followed by a newline - output strings, not imperative print calls, connect the computation 11.5.14 Currying 1 the book marks this and the next section as optional background 2 consider a mathematical function accepting several values - equivalently, it may accept one tuple of those values 3 fixing one argument of f(x,y) creates a one-argument function - if f(x,y)=10*x+y and x=3, the remaining function is 30+y - applying that function to 5 gives 35 4 currying transforms f into a function that performs that first step - curried f takes x and returns the function awaiting y - applying the returned function to y gives f(x,y) - fixing one particular x is partial application of that curried form - distinguish the transformed function from one particular closure 5 the name refers to logician Haskell Brooks Curry - the book mentions other language names honoring him 6 Curry is itself a higher-order function - input type: alpha # beta -> gamma - result type: alpha -> beta -> gamma - Curry f returns lambda x => lambda y => f(x,y) - right-associative arrows make extra parentheses optional 7 example with Func(x,y)=10*x+y - Curry Func: function awaiting x, then y - Curry Func 2: function y -> Func(2,y) - Curry Func 2 3 -> 23 8 define a function in curried form directly - Func x y <= 10*x+y - Func 4 7 -> 47 - likewise Func3 x y z <= 100*x+10*y+z - Func3 7 3 6 -> 736 - implementation can optimize intermediate function applications 9 curried definitions are conventional in Haskell - tuple-taking definitions remain possible 10 currying prepares the fixed-point example in the next section - its function-producing-function structure is what the example needs 11.5.15 The fixed-point combinator 1 letrec allows recursion for a locally named anonymous function - the function still acquires a name through the local binding 2 lambda calculus studies computation through function abstraction / application - fixed-point constructions express recursion without naming each recursive function directly 3 lambda notation in these programming languages comes from that formalism - the chapter gives only a practical illustration 4 fixed-point combinators provide the alternative recursion mechanism 5 separate a recursive algorithm from its recursive reference - give its body a parameter representing the recursive function to use - a fixed-point operation connects that parameter back to the result fixed point of f: a value x satisfying f(x)=x 6 in lambda-calculus terminology, a combinator is a closed expression - it has no free variables 7 fixed-point equation: Fix f = f(Fix f) - type: (alpha -> alpha) -> alpha - the Hope example implements this equation recursively - with laziness, it can produce useful results without expanding forever 8 summing example uses a function transformer phi - phi receives fn and returns a list-processing function - empty list -> 0 - head :: tail -> head + fn(tail) apply Fix to phi, then apply the resulting function to [1,2,3] - Fix phi expands to phi(Fix phi) - returned closure keeps fn bound to unevaluated Fix phi - first element produces 1 + (Fix phi)[2,3] - repeat for 2 and 3 - empty-list branch returns 0 without demanding fn - final result: 1+2+3+0 = 6 9 unconditional expansion would create an infinite nesting - f(f(f(...))) - the supplied transformer need not call itself by a name - the recursive connection is supplied by Fix 10 a strict function can make that expansion diverge - if f requires its argument before returning any result, evaluation immediately demands another Fix f 11 the sum transformer avoids that demand initially - returns a function before needing the recursive argument - examines the input list through that function - demands the recursive reference only for a nonempty tail computation - the base case discards the still-suspended remainder 12 Fix is not a numerical root-finding algorithm - x -> 20-x has ordinary numeric fixed point 10 - the recursive Fix definition does not solve that equation numerically - a constant function can return its constant without demanding input 13 domain-theoretic fixed points include partial / undefined computations - bottom represents absence of a defined result - least fixed point refers to the information ordering of that model - strict numeric examples can have bottom as the computed fixed point 14 Sumlist is a concrete functional fixed point of phi - phi(Sumlist) returns a function with the same behavior as Sumlist - empty list -> 0; nonempty -> head + Sumlist(tail) - therefore phi(Sumlist)=Sumlist extensionally - Fix phi constructs that same list-summing behavior 15 letrec can be expressed using a fixed point - letrec V == E in B - equivalent to (lambda V => B)(Fix(lambda V => E)) - the direct letrec implementation can evaluate it more efficiently 12. Compilation, interpretation, and scripting 1 languages studied so far use different execution arrangements: - Pascal, C, C++ and assembly: ordinary compiled programs - SBCL: can compile Lisp functions to machine code * saved executables can also contain a large Lisp runtime - Scheme implementations may translate through C * generated programs can still depend on a substantial runtime machine-code generation and independence from a runtime: - separate questions, developed later in this chapter 2 execution strategy influences how programmers view their programs - the author treats compilation / interpretation as paradigms - scripting languages provide the next example 12.1 Characteristic features of scripting languages 1 command languages originally describe jobs for the operating system: - which programs to run and how to run them Bourne Shell: - already used to launch editors, compilers and our own programs - a programming language, even during ordinary terminal work 2 script: commands saved as a program to automate a recurring task shell programming includes: - variables, assignment, branches and loops - while, until, for and case - functions; recursion is possible, though often unsuitable here 3 command scripts coordinate work performed by other programs - interpreter overhead can be small compared with that work traditional scripting model: everything is represented as text - numbers, commands and other values can all be strings - string processing therefore receives substantial support - ordinary words can represent themselves without quotation quoting changes how characters are interpreted: - double quotes: group words while allowing some substitutions - single quotes: preserve literal shell text - command substitution: insert a command's output in another command command text remains data until evaluated in a command context 4 variable name and variable value must be distinguished explicitly - MY_VARIABLE=256: assign using the name, without spaces around = - $MY_VARIABLE or ${MY_VARIABLE}: retrieve the value - echo MY_VARIABLE: print the name itself - echo $MY_VARIABLE: print 256 reading a variable is an operation: - the $ marks that operation in many command languages - comparable to distinguishing a NASM label from memory at [label] 5 program text is also string data -> evaluation can execute built text - analogous to evaluating constructed S-expressions in Lisp - strings need less structure than Lisp's list representation - metaprogramming fits naturally into this execution model 6 command languages make external programs easy to combine: - launch programs and redirect their input / output - inspect and transform their output text-based interfaces connect scripts with ordinary Unix programs - also useful in scripting languages without an interactive shell 12.2 The Tcl language 1 Tcl: Tool Command Language - spelling: capital T, lower-case c and l - pronounced "tickle" or as the three letters 2 John Ousterhout developed Tcl at Berkeley; first release: 1988 original purpose: an embedded command language for applications - useful when plain configuration files are insufficient Tk added facilities for graphical interfaces - other languages can access Tk through Tcl as well 3 the book mentions alternative implementations, including Jim / TinyTcl - its discussion reflects the implementations available then - the author criticizes additions in Tcl 8.5 and 8.6 4 backward compatibility allows the book to use the classic Tcl / Tk facilities available in version 8.4 12.2.1 The interpreter and the simplest programs 1 tclsh: the Tcl interpreter - which tclsh: find its installed path - a shebang can name that interpreter directly - puts "Hello, world": print a line - chmod +x: make a saved script directly executable # starts a comment where the interpreter expects a command 2 alternative script header: begin with /bin/sh - second line: a comment ending in a backslash - third line: exec tclsh "$0" "$@" the same header has two interpretations: - sh ends the comment at the newline and executes the third line - exec replaces sh with tclsh, preserving the script's arguments - Tcl joins the continued comment and ignores the third line 3 advantages of the shell wrapper described in the book: - finds tclsh through PATH instead of a fixed installation path - avoids historical shebang length / argument restrictions - works around systems with restrictions on script interpreters 4 later examples use this wrapper - a direct tclsh shebang is sufficient in ordinary installations 5 commands are separated by newlines or semicolons - backslash-newline continues a command onto the next line - the continuation rule also applies to Tcl comments an inline comment needs a preceding command separator: - puts "Hello" ; # comment - puts #: print #, since it is an argument here 6 run tclsh without arguments for interactive use - rlwrap can add convenient command-line editing 7 interactive cycle: - print a prompt, usually % - read and execute a complete command - display the command's returned result every command has a result, represented as a string - resembles a Lisp read-evaluate-print loop 8 expr evaluates an arithmetic expression supplied as text - expr 2*3 -> 6 - multiple arguments can form one expression returning a value differs from printing it: - expr returns its answer - the interactive interpreter displays that answer 9 exec runs an external program - its usual captured I/O is unsuitable for a full-screen editor - a child process cannot change the interpreter's directory - use Tcl's own cd command to change that directory 10 [command]: substitute the result of executing command - puts [expr 10+20]: evaluate expr, then run puts 30 - puts prints as a side effect and returns an empty string 11 command substitution also works within double-quoted strings - returned values can be inserted into longer messages 12 exec captures the external program's standard output as its result - exec ls in a script does not itself print the captured listing - puts [exec ls]: print it explicitly - frequently the script analyzes the captured text instead 13 interactive tclsh can try unknown top-level commands as programs - this shell-like fallback differs from explicit exec capture - the author doubts the usefulness of replacing a usual shell 12.2.2 Variables and their values 1 Tcl's visible data model uses strings for many purposes: - numbers, booleans, variable names and command names - entire programs and individual program constructions implementation can cache other representations internally - avoids repeatedly converting the same value 2 identifiers are strings naming commands or variables - unusual names are possible but need careful quoting - conventional letter / underscore / digit names are clearer 3 set name value: assign a value to a variable - set x 25: store 25 in x - $x: substitute x's value - substitution also works within double quotes arithmetic updates require evaluating an expression with the value - set n [expr {$n + 1}] 4 set name: return the variable's current value - [set x] can therefore be used where $x would appear 5 strings can represent lists - lindex list index: retrieve an element, numbering from zero - grouping allows one list element to contain spaces - embedded quotes can preserve a nested multiword element list structure depends on Tcl's grouping / escaping rules 6 string command: operations selected by its first argument - index: character at a zero-based position - range: substring between inclusive endpoints - end / end-1: final / penultimate position - length: number of characters - toupper / tolower: change case - trim / trimleft / trimright: remove surrounding whitespace - replace: replace a range of characters - equal / compare: compare strings, with different result formats - is: test a category, such as integer or alphabetic text example: abrakadabra - index 4 -> k; range 4 6 -> kad; length -> 11 7 command-line arguments are available through built-in variables: - argc: argument count, excluding the script name - argv: list of arguments, excluding the script name - argv0: script name these resemble C names but use a different counting convention 8 simple argument examples: - puts $argv: display the argument list - lindex $argv 0: retrieve the first argument - expr can evaluate that argument as an expression the initial calculator lacks argument checks; next section fixes this 12.2.3 Branches, loops... and strings 1 the first calculator fails when called without arguments - expr receives an empty expression - interpreter diagnostics expose implementation details to the user 2 application behavior should be controlled by the application - detect user mistakes and respond deliberately 3 error messages should explain the problem in terms the user understands - the author contrasts this with the Lisp / Prolog systems tested - Tcl provides mechanisms for handling such errors in the script 4 first repair: check that argc is 1 - true: evaluate the supplied expression and print the result - false: print usage instructions to stderr and exit with status 1 5 argument counting alone does not reject an invalid expression - catch runs expr and captures failure - success: print the computed result - failure: print an application-level message and exit unsuccessfully 6 if resembles a C branch superficially - comparison uses == - braces around the condition need a different explanation 7 understanding that explanation matters more than copying familiar shapes - the author describes initially using Tcl without understanding it 8 braces delimit a string argument - they are not Tcl's version of a C compound statement - variable / command substitution is deferred in a braced word - literal newlines can remain inside that string 9 braces inside a braced word must balance - nested braces remain part of its text - an escaped brace is excluded from nesting counts - its backslash remains in the resulting braced text backslash-newline is a special substitution even in braced words 10 double quotes allow escapes such as \n, \r and \t - braced text preserves these sequences at this evaluation stage - later evaluation of that text may interpret them 11 if is an ordinary built-in command general command processing: - identify/group words, then substitute within each word - ordinary substitution does not split a word into new arguments - use the first word as the command name - pass the remaining words as arguments - let that command decide how to interpret its arguments 12 this model permits new control constructions - implemented in Tcl procedures or C commands - no change to the core parser is required 13 command names are not reserved language keywords - a procedure can replace an existing command name - rename can retain the old command under another name - replacing familiar controls is possible but can obscure a program 14 if receives the condition as string data - evaluates it using Tcl expression rules - uses the resulting boolean to choose a branch 15 boolean representations: - zero: false; nonzero numeric values: true - true / on / yes and false / off / no - accepted boolean words are case-insensitive - valid unambiguous abbreviations are also accepted arbitrary strings are not automatically true command and variable names remain case-sensitive 16 branch bodies are also string arguments, interpreted as scripts - only the selected script is executed - else is recognized by the if command's implementation - it is not a keyword understood by the core parser 17 then and else can be optional in supported if forms - if $b "puts YES" "puts NO": both bodies are ordinary strings - off selects NO; on selects YES 18 braces are convenient because they defer substitutions - nested scripts otherwise require repeated escaping - quotes become especially awkward with variables / nested controls 19 if returns the result of the last command in the selected branch - a branch can print a message and then return an expr result - assignment can capture that result - comparable to a value-producing conditional in Lisp 20 while takes two strings: condition and body - evaluate the condition before each iteration - execute the body while it remains true braces keep references such as $n available for repeated evaluation - quoted condition: variables may be substituted before while starts - a condition reduced to 0 < 3 stays true forever argument-printing example: increment n while n < argc 21 for takes initialization, condition, increment script and body - run initialization once - test condition before each pass - run body, then increment script incr n: increase the named variable by one foreach iterates through lists: - foreach a $argv: bind each argument to a in turn - foreach {x y z} $greek: consume three elements per pass - the alphabet example prints eight rows of three names - multiple variable-list / value-list pairs advance in parallel - digit and digit-name lists can be traversed together - groups of different sizes can also be combined 22 break: leave the nearest enclosing loop continue: finish the current pass and proceed with the loop 23 while, for and foreach return an empty string - use them for their side effects 24 switch provides selection among cases - details are left to the reader 25 the author connects Tcl's runtime script strings with interpretation - a body can be supplied or constructed at runtime - its meaning must be preserved when it is executed this does not prohibit internal bytecode compilation or caching 12.2.4 Procedures and variable visibility 1 proc defines a new Tcl command implemented in Tcl - arguments: command name, parameter list, body - each argument is a string - an empty parameter list means no arguments are required 2 hello example: a procedure whose body prints Hello, world - braces conveniently quote the empty list and body - double-quoted strings with suitable escaping express the same data 3 parameter list gives both argument count and local parameter names - greet receives one name, which can contain spaces return value: - return value: stop the procedure and return that value - otherwise: return the last executed command's result - quad can return x*x implicitly or through explicit return args as the final formal parameter: - collect all remaining arguments into a list - supports a variable number of arguments 4 sumargs example: - initialize sum to zero and add every element of args - no arguments -> zero maximum example: - require one ordinary argument, followed by args - initialize maximum from the required argument - compare remaining values; an empty-input maximum is avoided variables inside procedures are local by default: - reading a same-named global does not find it automatically - assigning a local does not alter that global global x y: - create local aliases for global variables x and y - a procedure can then read / change those globals - the example adds x and y; the author discourages global coupling 5 global can receive a name computed at runtime - first print_and_clear receives the name of a global variable - builds a command to read it, prints it, then assigns an empty string - nested quoting / eval makes this example unnecessarily awkward - it also cannot operate on an ordinary caller-local variable 6 upvar links a local name to a variable in the caller's context - arguments occur in external-name / local-alias pairs - supports an effect similar to a reference parameter revised print_and_clear: - receive the variable's name - upvar $name var: create the alias var - print $var and set var to an empty string - works for both global callers and procedure-local callers 7 swap example: - receive two variable names and create aliases p and q - save p temporarily, assign q to p, assign the saved value to q - return an empty string; the useful result is the changed variables 8 optional upvar level selects another stack frame - 1: caller, used by default - 2: caller's caller; higher numbers continue outward - #0: global frame; #1: first absolute procedure frame - deep frame dependencies make code fragile 9 uplevel evaluates a script in another frame - level notation follows upvar - remaining arguments are combined as script text - useful for implementing controls that run a caller-supplied body - for example, a loop with a postcondition 10 assignment creates a variable; unset removes it - info exists name: 1 if the variable exists, otherwise 0 - other info subcommands inspect interpreter state 12.2.5 Handling exceptional situations 1 commands return values, but some also alter surrounding control flow - return: leave a procedure or an appropriate script context - break: leave a loop - continue: finish one loop iteration 2 error message: raise an error with a supplied message - unwind execution until a handler is found - otherwise the interpreter reports the error and its context 3 every Tcl command also has a completion code - 0 / ok: normal completion - 1 / error: error - 2 / return: return from the relevant context - 3 / break: leave a loop - 4 / continue: continue a loop additional numeric codes can support custom control mechanisms 4 ordinary script evaluation continues only after completion code 0 - any other code stops the current sequence of commands 5 surrounding contexts decide what to do with the completion code - loops handle break / continue from their bodies - procedure and script contexts handle return - an unhandled error propagates outward - break / continue in inappropriate contexts become errors 6 return -code can specify how the procedure completes - numeric code or its recognized symbolic name - a procedure returning -code break can act as a custom break - similarly for continue 7 return -code return can return from the calling procedure - retABC returns with code 2 and value ABC - a caller invoking retABC consequently returns ABC 8 catch script resultVariable: - execute the supplied script and catch its completion - store its returned value / error message in the named variable - return the numeric completion code as catch's own result 9 suspicious 42 example: - capture code with set code [catch {...} result] - code 0: result contains the procedure's successful return value - code 1: result contains the error message 10 other completion codes remain possible - explicit return -code can generate them - intermediate procedure contexts may handle / transform them 11 inspect the code and report success or failure deliberately - separating catch from if can make the logic clearer - the discussion uses the classic two-argument catch interface 12.2.6 Files, streams and external commands 1 Tcl I/O combines familiar file operations with command pipelines - open can open a file or start an external command - text is the natural interface; binary data need explicit care 2 open filename mode: open a channel - r: read; r+: read / write an existing file - w: write, creating or truncating; w+: read / write with truncation - a: append - binary mode avoids text transformations 3 mode can also be a list of low-level-style flags - RDONLY, WRONLY, RDWR, APPEND, CREAT, EXCL and others - {WRONLY CREAT TRUNC}: create / truncate for writing 4 optional permissions argument applies when creating a file - normally an octal mode such as 0666 or 0600 - default creation mode is 0666, subject to the process umask 5 omitting mode opens the file for reading - open "file.txt": read - open "file.txt" "w": create / truncate for writing - text processing is the main use discussed here 6 open returns a channel identifier - save it for subsequent I/O and close - treat its textual spelling as opaque standard channels: stdin, stdout and stderr 7 open can fail before an enclosing set executes - catch the operation and report its diagnostic appropriately filename beginning with | requests a command pipeline: - read mode: read the command's captured output - write mode: send data to the command's input - examples: read an ls listing or feed a grep filter 8 a pipeline can be opened for both reading and writing - buffering can prevent an apparent line-by-line dialogue - flush affects our output, not the external program's buffers - pipe behavior differs from interactive terminal behavior 9 possible approaches include sending all input and closing the write side - nonblocking I/O is another, more involved approach 10 puts writes a string and normally appends a newline - -nonewline suppresses that newline - optional channel argument selects the destination - otherwise output goes to stdout 11 read and gets require an explicit channel - use stdin for standard input 12 gets reads one line, excluding its newline - one argument: return the line itself - second argument: store the line in that variable * return its character count, or -1 when no line is available - the variable form distinguishes an empty line from end-of-file 13 read channel ?count?: read characters - omitted count: read through end-of-file - reading stdin this way may wait for the user to signal EOF - an interactive interpreter shares that same standard input 14 blocking read with a count waits for that many characters or EOF - differs from a low-level read that may return currently ready data - nonblocking mode changes the waiting behavior 15 read returns the data as its result - it has no gets-style destination-variable argument 16 eof reports whether a previous read encountered end-of-file - test after attempting input - it does not predict the result of a future read 17 fblocked reports a previous nonblocking read's inability to get data - useful when distinguishing temporary unavailability from EOF 18 close releases a channel - closing a blocking command pipeline waits for its child commands - that wait must be considered when designing the interaction - the book criticizes limited process control at this interface 19 closing a nonblocking output channel may defer flushing - completion relies on the Tcl event loop running - returning from close does not necessarily mean all output was sent 20 an additional close direction can close only the read or write side - supported channel kinds include bidirectional command pipelines - socket half-close is related to shutdown 21 bidirectional command communication uses two underlying pipes - closing one direction closes the corresponding underlying path 22 remaining I/O facilities are introduced briefly - full option details belong to their reference documentation 23 fconfigure changes channel settings - blocking mode, text encoding, newline conversion and buffering 24 binary handles binary representations - format: construct binary data - scan: extract fields from binary data - encode / decode: textual forms such as base64, uuencode and hex 25 socket creates TCP clients or servers - server callback runs when a connection is accepted - it receives the new connection's channel fileevent associates handlers with readable / writable channels vwait runs the event loop until a named variable changes - together these support an event-driven server - the script still needs a clear understanding of event ordering 26 file operates on filesystem objects and paths - copy, rename, delete and inspect files - query / change attributes and permissions - create directories and links 12.2.7 Associative arrays 1 lists can serve as ordinary integer-indexed sequences - lindex provides element access - cached internal list representations can make indexing efficient 2 these internal structures preserve the visible string / list semantics - their presence can be inferred from performance measurements 3 associative arrays map arbitrary string keys to values - suitable for sparse / named keys - dense numeric indexing is usually better represented by a list 4 array element syntax: arrayName(key) - set foo(bar,bur) value: assign one element - $foo(bar,bur): retrieve it - bar,bur is one string key, not two dimensions 5 key expressions can contain substitutions - $foo($a,$b): compute the key from a and b - a command result can also contribute to a key constructed ordinary variable names are less convenient - creating m15 from m$i is easy - retrieving it needs another level of indirection - arrays have direct interpreter support for these operations 6 upvar can alias an entire array by name - arr receives array name a and key i - upvar $a an: local array alias - return $an($i): retrieve the selected element 7 array command provides whole-array operations - names: list keys - get: produce a key / value list - set: assign entries from such a list - further operations support searching and inspection 8 an array is not a first-class Tcl value - cannot be assigned or returned as one ordinary value - pass its name and use upvar to operate on it - alternatively serialize entries with array get 9 later Tcl versions provide dictionaries through dict - a dictionary is a value that can be passed / returned as a whole - retains a string representation with efficient internal storage 12.2.8 Comparing Tcl with Lisp 1 shared ideas beneath different notation: - programs and data use the same representation - evaluation can execute constructed data - command / function calls identify an operation and its arguments 2 different defaults for evaluating data: - Lisp forms are normally evaluated; quotation suppresses evaluation - Tcl words remain text unless substitution is requested - $ requests a variable value; [...] requests a command result 3 Tcl control commands can receive unevaluated script strings - if and while use the ordinary command mechanism - users can build similar controls without special parser forms - the author regards this uniformity as conceptually simpler 4 Lisp functions can be first-class closures - preserve code together with its surrounding variable bindings classic Tcl procedures are named associations of parameters and bodies - code strings themselves can be passed and returned as data - inserting values into a script can capture those values - this differs from retaining mutable lexical bindings in a closure 12.3 The Tcl interpreter and C 1 Tcl was designed as an embeddable C library - tclsh is itself a user of that library - another C application can create and use an interpreter 2 the author recommends embedding only for a concrete requirement - knowing a technique does not make it necessary for every program 3 Tcl can also be extended with commands written in C - a short script can coordinate existing efficient components - the author favors this for modest tasks with acceptable overhead 4 example: a server needs configuration files created by its users - a small Tcl/Tk interface can help generate those files - the server itself need not acquire a graphical interface 5 reuse an existing C / C++ library for the file operations - a small adapter exposes its functions as Tcl commands - especially useful when the files have a binary format 6 the chapter explains the arrangement and a working example - detailed API reference material is needed when applying it 7 examples require Tcl library binaries and development headers - the book names tcl-dev for Debian-family distributions 12.3.1 Embedded Tcl 1 minimal host program: - include the Tcl header - Tcl_CreateInterp: create an interpreter object - Tcl_Interp*: handle for commands, globals and evaluation state 2 Tcl_Eval executes command text and returns a completion code - TCL_OK, TCL_ERROR, TCL_RETURN, TCL_BREAK, TCL_CONTINUE - Tcl_GetStringResult retrieves the result or diagnostic text 3 a command may span several input lines - accumulate text until quotes / braces and other syntax are complete - Tcl_CommandComplete checks this without a separate parser 4 read_command receives a buffer and its capacity - success: store one complete command and return true - EOF: return false - oversized input: report it, discard the remaining line, return false 5 reading algorithm uses fgets and appends successive lines - keep a running length - set a sentinel near the buffer's end before reading - a changed sentinel detects an overlong line - repeat until Tcl_CommandComplete succeeds the example reserves a fixed 32 KiB command buffer REPL repeatedly reads, evaluates and reports a command 6 before evaluation: Tcl_ResetResult clears the previous result - TCL_OK: print the result only if it is nonempty - TCL_ERROR: print a diagnostic - other codes: report unexpected control flow main creates the interpreter and calls the REPL with a prompt - link the program with libtcl using -ltcl 7 custom commands make embedding useful - expose operations belonging to the host application triple example: receive one string and return three copies joined 8 C command callback receives: - ClientData: optional application-specific pointer - interpreter pointer: access results and nested evaluation - argc / argv: arguments, including command name at argv[0] callback returns a Tcl completion code Tcl_SetResult stores the textual result in the interpreter: - TCL_STATIC: the supplied storage remains valid - TCL_VOLATILE: Tcl must copy the supplied text - TCL_DYNAMIC: transfer storage allocated with Tcl_Alloc - custom release callback: use a specified disposal operation triple implementation: - require argc == 2; otherwise set diagnostic and return TCL_ERROR - allocate space for three copies plus the terminating zero - copy the input three times and transfer ownership of the result - return TCL_OK Tcl_CreateCommand registers name, callback, client data and cleanup - main registers triple before starting the REPL - triple abrakadabra returns three concatenated copies top-level break / continue / return experiments reveal another detail - Tcl_Eval normally converts inappropriate top-level codes to errors 9 Tcl_Eval tracks nested evaluation on the same interpreter ENTER command creates a nested REPL: - entered from an existing Tcl_Eval callback - its evaluations are no longer at the outermost level - therefore the demonstration can observe additional completion codes 10 ENTER accepts an optional prompt and invokes the REPL - Ctrl-D ends that nested input loop - clearerr(stdin) clears EOF so the outer loop can continue - set an empty result and return TCL_OK register ENTER just like triple - nested break / return now reach the REPL's corresponding cases further extension left as an exercise: - accept script files as command-line arguments - Tcl_EvalFile executes a file in the supplied interpreter - choose whether to enter interactive mode afterward 12.3.2 Extending tclsh's command set 1 loadable C / C++ extensions add commands without rebuilding tclsh - compile the implementation into a shared library - load that library into a running interpreter - this kind of extension is commonly called a plugin 2 command callbacks use the same interface as embedded Tcl commands - include the supporting functions they depend on 3 the plugin needs an initialization entry point - example: tclembed.so -> Tclembed_Init - receives the interpreter pointer - registers commands with Tcl_CreateCommand - returns TCL_OK or TCL_ERROR 4 reuse triple and ENTER from the embedded-interpreter example - conditional compilation selects main or plugin initialization - define PLUGIN to build the plugin version shared-library build options in the example: - -shared: produce a shared object - -fpic: generate position-independent code - -DPLUGIN: select the initialization function 5 load ./tclembed.so adds the commands to tclsh - triple foobar returns foobar three times - ENTER opens the nested REPL and returns on EOF - the example archive contains the combined implementation 12.4 Graphical interfaces with Tcl/Tk 12.4.1 Tk and the wish interpreter 1 Tk builds graphical interfaces from widgets - can be loaded into Tcl or used from a C / C++ application - wish already includes Tk and handles window-related options 2 interactive wish creates an empty main window and a terminal prompt - commands can be tested immediately - rlwrap provides convenient input editing 3 -name sets the application's name and initial title - use a simple identifier for the application name - wm title sets the visible title independently - the application name also matters to resource configuration 4 . identifies the application's main window - wm title . "Another Title": change that window's title 5 geometry hierarchy: a widget can contain managed subordinate widgets - the containing widget determines their available display area 6 parent / child hierarchy is a separate relationship - often coincides with geometry containment, but need not - destroying a parent destroys its descendants 7 all widgets except the main window have a parent - even additional top-level windows belong to this hierarchy widget paths reflect parentage: - .grp.btn1: btn1 under .grp under . - ancestors must exist; levels cannot be skipped - use lower-case initial letters for component names 8 widget-creation command is named after the widget type - button .bt -text "Press Me" - returns the widget's path, .bt 9 creating a widget does not itself display / position it - a geometry manager must arrange it - place .bt -x 10 -y 10: position its corner at those offsets - fixed positions are mainly useful for this first demonstration 10 each widget path is also a command for operating on that widget - cget: read an option - configure: change options that remain configurable button example: - read -text and assign it to a Tcl variable - change the label to a longer two-line string - requested widget size grows to fit the new text - -padx / -pady adjust space around its contents 11 button-specific operations include: - flash: briefly change its visual state - invoke: perform its configured action 12 label is a passive text widget - pack .lab -side bottom -fill x: occupy the bottom across its width - configure -text changes the label just as for a button - text and newlines influence its requested height 13 the main window also supports a widget command - . configure -bg #ff0000: set its background button -command stores a script to run when activated - initialize counter i to zero - callback increments i and changes .lab's text to its new value - braces defer the callback's substitutions until execution 14 wish can visualize another program's work - have the program emit Tcl/Tk commands into a pipe to wish - the book's Prolog example animates knight-tour search / backtracking 15 complete GUI script uses wish as its interpreter - shell wrapper passes the script, -name and command-line arguments x11echo example: - set a window title - display argv0 and argv in a label - create an Ok button whose command is exit - pack label above button 16 the shell-wrapper technique permits multiple interpreter arguments - useful for supplying both -name and its value 17 argv0 / argv work as in tclsh scripts - wish extends Tcl with graphical facilities 18 finishing a wish script does not normally end the GUI application - initialization finishes, then the event loop handles interaction - windows remain until the application is closed interactive mode runs the interface while commands are being entered 12.4.2 Interacting with the window manager 1 window manager controls decorations, movement and resizing - Tk's wm command communicates window-management requests 2 wm title changes a top-level window's title wm attributes window -fullscreen 1: request full-screen presentation - use 0 to return to ordinary presentation 3 wm state queries / changes window state - withdrawn: removed from the screen - iconic: minimized; normal: ordinarily displayed - icon can be reported for a window serving as another's icon wm withdraw / iconify / deiconify provide related operations 4 icon-related subcommands configure bitmap, mask, name, image and position - details are outside the chapter's scope 5 wm geometry takes a top-level path and geometry string - 200x300: width 200, height 300 - +50+70: offsets from left / top screen edges - -100-200: offsets from right / bottom edges - omit dimensions to change only position this geometry notation is conventional in X applications 6 wm minsize / maxsize constrain width and height wm resizable sets permission separately for each dimension - yes no: allow width changes, disallow height changes 7 gridded windows resize in units of an internal cell grid - useful for terminal-style character cells - wm grid / -setgrid describe that arrangement - geometry and size constraints then use grid units 8 other wm operations depend partly on the window manager - consult the reference when a more specialized operation is needed 12.4.3 Basic widgets 1 Tk offers many widget types beyond windows, buttons and labels - checkbutton / radiobutton: boolean / alternative choices - entry / text: single-line / multiline text editing - frame / labelframe: grouping containers - listbox, menu, menubutton, message, scale - panedwindow, scrollbar and canvas 2 the book explains principles rather than every widget option - installed man pages describe individual widgets - example: man 3tk button 3 main interfaces: creation options and widget-command subcommands - cget / configure are shared operations - standard options are documented together in options - standard means shared semantics, not support by every widget 4 -text supplies text for widgets such as labels and buttons -textvariable links displayed text to a global variable - changing the variable changes the display - entry also updates that variable when the user edits the field - multiple widgets can consequently share synchronized text 5 Tcl variable tracing supports these update notifications - trace can observe variable reads / writes and other changes - related tracing facilities also help debugging 6 -relief controls the border's appearance - raised, sunken, solid, groove, ridge or flat - -borderwidth / -bd sets its thickness - groove / ridge need enough pixels to show their structure -padx / -pady add space around supported widget contents - exact applicability depends on the widget and content type 7 passive widgets display information; active widgets accept interaction - buttons, entries and selection controls have configurable behavior - explicit event bindings can also make passive widgets respond 8 -state can disable or otherwise alter interaction - button: normal, active, disabled - entry: normal, disabled, readonly - readonly permits selection / copying but prevents editing - supported states differ by widget 9 button combines -text with a -command callback - flash changes appearance briefly - invoke activates the callback, unless the button is disabled 10 checkbutton represents a boolean choice - supports select, deselect and toggle - also supports configure, cget, flash and invoke 11 -variable links a checkbutton to its state variable - default off / on values are 0 / 1 - -offvalue / -onvalue can replace those representations - reading the variable reveals the selected state - assigning the variable also updates the widget 12 checkbutton -command is optional - user activation first changes the linked variable - then runs the callback, which can inspect the new state 13 -indicatoron 0 gives a checkbutton the appearance of a latching button - changes presentation, preserving the underlying choice behavior 14 radiobutton chooses one alternative from a group - supports much of the checkbutton interface - toggle does not fit its one-of-many meaning 15 radiobutton grouping uses -variable together with -value - same group: same variable, different values - selecting a button assigns its value to the variable - every button updates according to whether that value matches - the widgets need no direct knowledge of each other 16 entry has a richer text-editing interface - use its text operations or linked variable for actual content 17 entry get returns the current text - delete first last removes an index range, excluding last - insert index text inserts before that position - indices start at zero; end is just after the final character - delete 0 end, then insert 0 text: replace the whole contents - insert as an index denotes the insertion cursor 18 entry also supports icursor and selection operations - a linked variable is often simpler for ordinary content access 19 entry's linking option is -textvariable - changing the field changes the variable - changing the variable changes the field 20 validation can constrain / inspect entry edits - -validatecommand / -vcmd supplies a checking script - -validate selects when checks run - possible triggers include edits and focus changes 21 other widgets follow related option / subcommand conventions - learn their specialized behavior from the reference as needed 12.4.4 Position and size 1 GUI layout must address both initial arrangement and window resizing - these often consume much of interface implementation work 2 geometry manager arranges widgets inside a containing widget - controls positions and sizes when available space changes - geometry propagation can also resize the container to fit contents 3 place uses explicit coordinates or fractions of container dimensions - straightforward, but manual positioning scales poorly 4 grid arranges widgets in rows / columns - a widget may span a rectangular group of cells - requested widget sizes influence row heights and column widths 5 pack places widgets along edges of remaining space - convenient for quickly assembling many interfaces - frames can group controls and use a different layout internally 6 distance units: - bare numbers: pixels - c: centimeters; i: inches; m: millimeters - p: points, each 1/72 inch 7 place options for position: - -x / -y: explicit offsets - -relx / -rely: fractions of container width / height 8 place options for size: - omitted dimensions use the widget's requested size - -width / -height: explicit dimensions - -relwidth / -relheight: fractions of the container 9 -anchor selects which point is placed at the requested coordinates - nw by default: upper-left corner - n, s, e, w: side midpoints - ne, sw, se: other corners; center: center 10 top-centered label example: - -y 0 -relx 0.5 -anchor n absolute and relative offsets can be combined - -x 20 -relx 0.5: 20 pixels right of the horizontal center 11 place forget stops managing a widget - info reports its layout configuration - slaves lists widgets managed inside a container 12 grid requires more concepts but suits substantial structured interfaces 13 the grid grows as rows / columns are used - it need not be allocated as a fixed-size matrix beforehand 14 grid positioning: - -row / -column: zero-based cell coordinates - -rowspan / -columnspan: number of occupied rows / columns row-by-row shorthand can place several widgets at once - x: leave a cell empty - -: extend the previous widget across another column - ^: extend the widget above into this row 15 demonstration helper m creates a square frame with a centered label - frame dimensions are convenient in pixels - label dimensions instead relate to text units - place centers each label inside its frame 16 mosaic example combines empty cells and horizontal / vertical spans - Close button occupies a two-by-two region near the bottom - by default, small widgets are centered in their allocated regions -sticky controls alignment / stretching within that region - adjacent compass letters: align toward a corner - opposite letters: stretch along that dimension - nswe: fill the entire region 17 row / column sizes need resizing policies as well - rowconfigure / columnconfigure set weights - equal nonzero weights distribute extra space evenly - uniform groups keep grouped dimensions proportional - the example gives all rows and all columns equal weights 18 grid provides forget, info and slaves - remove hides a widget while retaining its layout settings - it can then be restored without repeating those settings 19 pack repeatedly allocates a strip of the remaining empty area - top / bottom strips take the remaining width - left / right strips take the remaining height - the requested widget size determines the other initial dimension 20 pack's main options: - -side: choose top, bottom, left or right - -fill: stretch the widget along x, y, both or neither - -expand: let its allocated region receive surplus space fill changes the widget; expand changes the region available to it 21 spiral example: - five passes through top, left, bottom, right - create labels numbered 1 through 20 - each expands and fills its assigned region - place a Close button in the remaining center experiment with fill / expand and resize the window to see the difference 22 pack also supports forget, info and slaves 23 pack / grid normally propagate requested geometry to their containers - this can override a container's requested width / height - propagate container 0 disables that automatic sizing - the example then requests a 400 by 400 main window - managed labels expand inside that chosen initial size 12.4.5 Fonts 1 font control selects size, typeface and emphasis - needed when defaults are too small or text needs differentiation 2 simple text widgets use a -font option for their displayed text - a single label does not assign different fonts to separate words - richer widgets such as text provide more detailed styling 3 one font specification is a list of family, size and optional styles - styles include bold, italic, underline and overstrike - Times, Helvetica and Courier are conventional portable family names - {Courier 20 italic}: 20-point italic monospaced text 4 named fonts provide shared, changeable configuration - font create: choose family, size, weight, slant and other properties - assign its name to widgets with -font - font configure: change that named font later - every widget using it reflects the change 12.4.6 Event handling 1 -command is sufficient for many simple interfaces - wait for a button, then inspect the other controls and act - unexpected actions while the user edits text can be confusing 2 bind associates a script with an event - keyboard / mouse actions, focus or window changes - widget appearance, disappearance or destruction - application-defined virtual events bindings can make even passive widgets respond 3 keyboard binding examples: - or : Escape key - : F3 while Control and Shift are held - an ordinary printable character can be specified directly avoid global letter shortcuts that interfere with text-entry fields 4 : triple press of mouse button 3 - example changes a label after that action - Double and Quadruple also describe repeated events 5 virtual events use doubled angle brackets - bind . <> script: install a handler - event generate . <>: produce that event bind's three arguments: target tag, event description, script 6 target can represent a widget, top-level window or group - top-level bindings normally apply through descendant bindtags - class tags group widgets of a particular type - all is a predefined broad tag - bindtags can attach custom tags to chosen widgets 7 these targets all operate through the widget's bindtag list - widget and top-level names are normally present as tags - tags can be removed, inserted or reordered 8 event description forms: - printable character - - <> physical event types include KeyPress / KeyRelease and ButtonPress - also ButtonRelease, Motion, MouseWheel, FocusIn / FocusOut - Configure: geometry changes; Destroy: widget destruction 9 detail after the event type identifies a particular key or button - keysyms name letters, punctuation, arrows and function keys - KeyPress can be omitted when the key name is sufficient 10 mouse button details are numeric - common X convention: 1 left, 2 middle, 3 right 11 modifiers precede the event type - Control, Shift, Alt: required modifier keys - Double, Triple, Quadruple: repetition count 12 a binding can describe a sequence of events - handler runs after the complete sequence matches 13 handler scripts can use event substitutions - %b: mouse button number - %k: key code - %x / %y: pointer coordinates relative to the event window - available substitutions depend on the event 14 one event can trigger handlers attached to several tags - widget classes use bindings for their normal behavior too - a custom binding need not replace those class handlers break in a handler stops remaining handlers for that event - can deliberately suppress the usual widget response 15 continue ends the current binding script - remaining applicable handlers can still run 12.4.7 Resources and localization 1 translated interface strings can be kept outside program code - Tcl's msgcat serves a message-catalog role similar to gettext - this section uses X resources as another way to supply labels 2 X resources associate hierarchical option names with string values - names / classes identify application, widgets and option - capitalized components designate classes - dots specify hierarchy; asterisks can match intervening levels 3 resource-file syntax: resourceName: value - a precise path configures one option of one nested widget - Fig*canvas.background: gray97 matches relevant canvas backgrounds - Fig*foreground: black supplies a broad foreground default - more specific matches can override general ones 4 the section leaves detailed resource matching to the reference material - focuses on translating Tcl/Tk interfaces 5 wish -name myprog supplies application name myprog and class Myprog - Myprog.lab.text: text for .lab - nested widget paths produce corresponding resource paths - wildcard patterns can share labels for similarly named controls 6 resources can set other options as well - example: label relief and border width - option add supplies resource defaults from the script itself 7 localization procedure: - remove explicit widget -text values - put the corresponding English resources in a .rc file - copy it and translate the values for another language - choose a file from command-line / environment settings - option readfile loads it before creating the widgets 8 the resource-reading interface discussed here expects UTF-8 text - ASCII-only files conceal encoding differences - translated non-ASCII text must use the expected encoding 9 if the source file uses another encoding, convert it before loading - iconv is one tool for that conversion 12.5 Execution strategies as paradigms 12.5.1 What is a script? 1 earlier command-language features do not define all scripting - strings as universal data and external-command control are common - browser JavaScript and embedded Lisp dialects differ from that model - command languages can also be used for nonscripting applications 2 the kind of program must therefore be distinguished from its language - examine the roles called scripting in different environments 3 shell scripts commonly automate recurring manual tasks - launch and coordinate other programs 4 office macros automate document / spreadsheet operations - browser scripts also give documents behavior - the author distinguishes author automation from imposed site behavior - his criticism of browser scripting is a viewpoint, not a definition 5 MUD / IRC clients provided event-driven scripts - examples: react to low health or a familiar person entering a channel 6 embedded languages can configure complex applications - used when plain configuration data are insufficient - if the embedded program becomes the main substantial application, calling it a small auxiliary script becomes less useful 7 embedded systems may use a custom language or an existing dialect - domain-specific language / DSL: tailored to a particular problem area - general-purpose language: intended for many problem areas 8 adding domain-specific commands raises a terminology question - is extended Tcl a new language or Tcl with an application API? - both descriptions can capture part of the arrangement 9 scripting is one family of application domains - domain-specific languages cover many other purposes too 10 the author's working definition: scripts control other programs - from outside through commands, or inside through an embedded API - occupy an auxiliary role relative to the controlled application - make little sense independently of that application 11 dependence alone does not determine that auxiliary role - an OS supports applications, despite their dependence on it - an interpreter can similarly serve a substantial main application - ask which component supplies the primary purpose / value 12.5.2 Ousterhout's dichotomy and its opponents 1 the author questions using originally auxiliary languages as the main implementation language of substantial applications - this is his design position, not a restriction of those languages 2 the historical discussion centers on Richard Stallman and John Ousterhout 3 Stallman's 1994 message argued against Tcl as a common extension language - wanted an extension language capable of substantial programming - criticized Tcl's data structures, numeric model and syntax - recommended Scheme with Tk access 4 the book also recounts contemporary GNU plans for different syntaxes - its comments on those projects describe the historical discussion 5 Ousterhout's reply advocated two complementary language roles - C / C++: complex internal data structures and efficient computation - Tcl: short scripts connecting and extending those components - easy learning and composition matter especially in the latter role - dropping into C handles work unsuited to Tcl he had not intended Tcl for programs of tens of thousands of lines - expressed surprise that some large applications remained manageable - accepted that Tcl could improve while defending the two-language idea 6 his later scripting article formalized this distinction - system programming languages versus scripting languages - compared language level and degree of typing on two axes - the resulting separation became Ousterhout's dichotomy 7 the author notes counterexamples to a simple two-region picture - Haskell combines high abstraction with a strong type system - the diagram alone cannot establish a universal classification 8 critics argue that languages associated with scripting can also serve general-purpose programming successfully - large Tcl applications already appeared in Ousterhout's reply 9 language use can expand beyond its original domain - Perl: text processing to broader programs - JavaScript: browsers to servers and other applications - Lua, Ruby, PHP and Python also enter this discussion 10 the author's proposed explanation emphasizes ease of initial learning - small useful programs attract people with limited prior training - he associates this with later reuse outside the original task 11 he combines two possible biases: - familiar-tool bias: try the tool one already knows on new problems - first-language attachment: treat the first model learned as natural - a solution being possible does not by itself make its design suitable 12.5.3 What is interpretation? 1 the chapter asks how execution strategy affects programming habits - terminology must first be made explicit 2 compilation and interpretation can coexist - translate source into an intermediate representation - execute it using a virtual machine, possibly with further compilation - storing the representation separately is only one design difference 3 the Lisp implementations examined retain substantial runtime support - saved applications can therefore be much larger than their own code - the book criticizes this deployment cost 4 SBCL's machine-code compilation illustrates the terminology problem - code generation and the amount of runtime machinery are distinct - calling CPU execution interpretation does not resolve that distinction - raw speed comparisons also answer a different question 5 CPU execution speed may matter less than time spent waiting for I/O - therefore performance is not the chapter's sole concern 6 the author's concern is development machinery required during execution - runtime evaluation / reading of source can retain translator functions - those facilities were often designed with programmers in mind 7 initial working criterion used by the author: - source passed to a program that executes it: interpreted execution - translated executable requiring no translator: compiled execution - these are deployment-oriented definitions for this discussion 8 development and user environments may be different machines - ask which development tools the delivered program requires - processor microcode is outside this chosen distinction 9 the criterion remains imprecise - a runtime rarely needs every tool used during development - the programmer's text editor is an obvious counterexample 10 historical systems sometimes tied execution closely to their editor - earlier BASIC examples illustrated that arrangement 11 debuggers also raise a separation issue - an end user normally needs an application-level error response - the book's Common Lisp experiments exposed debugger-oriented behavior 12 bytecode execution needs runtime machinery even without its source compiler - the author groups this as partial interpretation for his argument - this differs from saying that no compilation occurred 13 libraries complicate the proposed boundary further - compiled C / C++ programs can require shared libraries - static linking instead includes needed library code in the executable - library use alone does not make ordinary C execution interpretation 14 platform-provided runtimes blur the distinction again - what users regard as part of the OS depends on the platform - the book discusses managed runtimes and mandatory platform APIs 15 final proposal: treat runtime dependence as a spectrum - more required development-system machinery -> more interpreted, in the author's specific sense - earlier assembly programs needed only the CPU and OS kernel - the C example without a standard library approached that arrangement - compiler-generated helper routines can still introduce dependencies 12.5.4 Interpretation as a paradigm 1 available runtime source / translator facilities invite new uses - eval is one example: execute code constructed during execution 2 a program controls its interpreter only through exposed facilities - some capabilities may be absent or intentionally inaccessible 3 Hopeless example: - top-level directives define / inspect functions and types - write can output elements of an unbounded lazy list incrementally - those directives are not expressions callable from Hope functions 4 other systems expose much more of their execution machinery - inspect names and definitions - replace program components during execution - alter parts of the evaluator's behavior 5 reflection: access to a program's own structure or execution - structural reflection: inspect / modify internal program objects - behavioral reflection: influence the evaluation process / context - the book introduces this through Brian Smith's account 6 reification makes otherwise implicit machinery available as program data - provide objects representing it and operations on those objects 7 a closure can normally be used without exposing its internals - behavior reveals captured bindings - does not necessarily permit reading / changing its stored body - the book treats the examined closures as black boxes 8 hypothetical closure-inspection operations would reify those internals - retrieve / replace body - list captured variables and inspect / alter their bindings - implementation becomes more constrained by the exposed representation 9 textual program representation is easy to expose as ordinary strings - access / replacement operations can manipulate whole procedures - internal code representations instead require specialized interfaces 10 Lisp symbol names are an example of reified information - symbol -> string name; name -> existing or newly created symbol - the author questions whether such exposure is always beneficial 11 structural reflection is not confined to source interpreters - managed compiled languages expose metadata too - C dynamic loading can also involve looking up functions by name 12 continuations provide an example related to behavioral reflection - represent aspects of the current computation as usable objects deeper reflective systems can expose interpreter data structures - program and interpreter updates may interfere - reflective towers separate levels to address that interference - the author questions the practical motivation of these constructions 13 the discussion then moves from theoretical machinery to practical risks 14 runtime patching replaces program behavior while it is running - the source definition a reader knows may no longer be the active one 15 this can obstruct debugging - reasoning from an unchanged-looking source definition becomes wrong - an unexpected replacement may be far from the observed failure 16 monkey patching can replace library behavior at runtime - documentation may no longer describe the modified behavior - one subsystem's patch can violate another subsystem's assumptions 17 the author strongly discourages everyday reliance on such patching - his concern is hidden behavioral change and difficult coordination 18 bytecode distribution can separate source translation from execution - reflection can remain available - generating new source is less direct if no source compiler is present - exact capabilities depend on the runtime, not this category alone 19 the broader recommendation is to separate developer concerns from user ones - programming mistakes and anticipated operating failures deserve appropriate, deliberately designed handling 12.5.5 Dependencies and self-contained programs 1 interpretation costs can include startup translation as well as execution - caching and incremental translation can reduce those costs - performance is only one aspect of the author's objection 2 dependency: something required for another component to function - the book compares battery-powered and mechanical watches 3 self-contained describes independence from additional required components - its meaning differs from autonomous behavior 4 software always depends on some underlying platform - the chapter treats CPU / OS requirements as the baseline - self-contained here means avoiding extra dependencies above it 5 build-time dependencies are needed to produce the delivered program - compiler, build tools, headers and libraries runtime dependencies are needed to execute the delivered program - shared libraries, data files, images and external commands 6 transitive dependencies form a directed graph - package managers track and install required packages automatically - manual tracking quickly becomes difficult 7 ship analogy used by the author: - pumps can compensate for leaks, but encourage neglect if treated as a reason to stop sealing the hull - larger compensating mechanisms can hide a worsening basic design 8 he asks the reader to explain why that engineering approach is unsound - merely calling it obviously wrong does not identify the principle 9 principle: having a solution to a problem is not a reason to create it - every workaround has costs - treating manageable problems as nonexistent can allow them to grow 10 historical example from the author's machine: installing Atril proposed many packages and substantial downloads - some dependencies were real; others followed packaging choices - this is an anecdote about that installation, not a current size claim 11 updating one shared dependency can require coordinated upgrades - further dependencies may extend the update through the system - new versions can also introduce regressions or remove useful behavior 12 incompatible version requirements create dependency conflicts - the author calls the resulting difficulty dependency hell - his claim of inevitability is part of the argument 13 maintainers also inherit developers' dependency choices - obtaining and building prerequisites can dominate packaging work - each additional component requires maintenance effort 14 the author's preferred delivery models: - user: copy one executable, run it, remove it when finished - maintainer: unpack a source tree and build with supplied prerequisites 15 bundled source and static linking can approach these ideals - include required library sources and needed code in the executable - an externally supplied interpreter remains an additional dependency 16 a compact bundled interpreter could also simplify delivery - the author argues that larger surrounding ecosystems often obstruct it 17 interpreter ecosystems may require extra installers and language libraries - convenience for developers can transfer setup work to users - the relevant cost is the complete deployed environment 18 a package-manager command may automate installation - the author argues that automation does not remove all resulting costs 19 less common target platforms may lack ready-made runtime packages - users may need to build prerequisites themselves - expertise does not make that work free 20 author's Openwall example: - an unsuccessful Erlang build influenced his Jabber-server choice - illustrates a deployment constraint on that particular environment 21 availability of installation tools differs across systems - the book's platform examples reflect its historical experience - a solution available on one system cannot simply be assumed elsewhere 22 several applications sharing an ecosystem may require conflicting versions - dependency compatibility needs deliberate management 23 containers can isolate applications and their dependencies - separate environments reduce conflicts between applications - Docker is the example discussed 24 container delivery has its own storage / distribution costs - includes required userspace components while sharing a host kernel - actual image size depends on what is included 25 the author sees adoption of isolation as evidence that dependency problems were real, despite earlier assurances that they were trivial 12.5.6 The portability myth 1 higher-level abstractions can hide platform differences - this does not by itself guarantee effortless portability 2 platforms expose different underlying facilities and conventions - process creation, readiness notification and graphical interfaces - equivalent-looking APIs may have different limits or costs 3 a common abstraction can fit some platforms poorly - the author criticizes environments that impose an awkward model - a portable interface still needs suitable platform implementations 4 an abstraction may omit a needed platform capability - extensions / foreign interfaces can fill the gap - platform-specific use then requires additional portability work - absence from Common Lisp's standard is not absence from every library 5 runtimes themselves are software that must be ported and tested - complex applications can reveal differences missed by small examples 6 the author favors planning portability around actual application needs - implement the required common interface over each platform - gives C / C++ and a portable widget library as his preferred approach 7 his Tcl/Tk versus C++ comparison reflects his own deployment experience - include installation burden in portability planning - do not treat that experience as a universal language ranking 12.5.7 When interpretation is appropriate 1 the criticism raises a question: why study these interpreted languages? 2 alternative paradigms are useful intellectual tools - ideas can be valuable even without adopting a particular runtime - restricting dynamic facilities can make compact compilation easier - a language's possible implementations need not match one example 3 personal / short-lived programs avoid some deployment concerns - programmer and user are the same person - an existing interpreter may be entirely acceptable - examples: one-off runs and private task automation 4 internal organizational software can be considered similarly - development and operations costs fall within the same organization - the organization can choose a tradeoff that suits its needs 5 an appliance can hide its implementation environment from users - supplier installs and supports the complete software / hardware system - users need not manage the runtime themselves 6 domain-specific languages are another suitable use - scripting can control an existing application from inside or outside - more substantial domain programs may use an embedded interpreter too - scripting is one subset of this broader case 7 two layers have different modification expectations - main application: supplied by its developers - extension layer: intended for users to write / adapt - user code may be supplied initially or added later 8 this extends the two-language idea behind Ousterhout's dichotomy - users and application developers can have different skills / tasks - their languages can therefore have different design priorities 9 an embedded language can be simpler than the main implementation language - users avoid learning C++ and installing its full toolchain - a compact interpreter can expose the needed application operations 10 embedding the interpreter inside the main executable can simplify delivery - the user-facing extension environment becomes part of the application 11 keep any extension ecosystem focused on users' tasks - preserve the distinction between user tools and developer tools 12 the author proposes a two-layer paradigm - compiled application core - interpreted user-modifiable extensions - distinguishes roles, not merely performance-sensitive code 13 his architectural rule: core functionality must not depend on a particular user-modifiable script remaining unchanged - extensions call core operations - essential implementation belongs in the maintained core 14 reason: users expect the extension layer to be safe to modify - hidden core assumptions about exact script contents violate that model - comments alone do not repair an unclear boundary 15 the author recognizes that his list of suitable cases may be incomplete - nevertheless argues strongly against transferring runtime-management burdens to an unknown public audience - this is his deployment philosophy, not a general prohibition 16 if future public distribution is plausible, he recommends considering compiled, statically linked delivery from the beginning 12.5.8 (*) Reflections on pure compilation 1 the author contrasts reflection research with his interest in reducing runtime development machinery - reports difficulty finding related work during his group's search 2 proposed ideal: implementation choices should not unnecessarily affect what an end user must see or manage 3 first requirement: no translator needed to run the delivered program - stronger form: no program translation during execution at all - installation should leave it ready to execute 4 bundling an interpreter with program text does not meet the stronger form - one executable file can still perform runtime translation internally 5 further requirements proposed by the author: - no mandatory external development-system components - include only explicitly requested libraries - allow the required library set to be empty - move substantial supporting mechanisms into optional libraries 6 implementation names should not change user-visible behavior - consistently rename identifiers without changing bindings - the author calls this stability under alpha conversion 7 ordinary C compilation may generate helper-library calls - operations unsupported directly by a target CPU need implementation - gcc can also assume certain memory-support routines exist - source with no explicit library calls can still require helpers 8 C macro stringification can expose an identifier's spelling - #x converts the argument token sequence into a string - renaming myvar then changes a printed string produced from its name - this violates the author's stated naming-independence requirement 9 another proposed requirement concerns compile-time computation - permit work whose inputs are known at build time to happen then - avoid forcing it into every execution - discusses format processing and compile-time function evaluation - cites D as an example supporting such evaluation 10 two further proposed controls over the delivered artifact: - avoid unnecessary traces of the particular implementation tool - permit producing any valid executable for the chosen target - the author uses assemblers as the point of comparison 11 he names the combined ideal pure compilation - a particular research / design proposal, not the usual definition - argues for a high-level language designed around those requirements 12 C++ demonstrates that low-level access can coexist with high abstractions - the author objects to mandatory support machinery for some features - discusses virtual dispatch, exceptions, allocation and RTTI - his criterion is optionality / control over implementation support 13 proposal: move such mechanisms into explicitly selected libraries - retain expressive abstractions with a minimal language core - choose different supporting libraries for different problem domains 14 the author presents pure compilation as a possible direction for a new general-purpose language, motivated by his criticisms of C and C++