A comprehensive guide to building reliable, secure and efficient systems software with Rust
Introduction
- Book Organization
- Toolchain and Edition
- How to Read This Book
Chapter 1: Why Rust for Systems Programming
- What Systems Programming Demands
- The Rust Value Proposition
- Historical Context: From C to Rust
- When Rust Is the Right Choice
- When Rust Is Not
- The Book’s Approach and Projects
Chapter 2: The Rust Toolchain and Build System
- Installing and Configuring the Toolchain
- Understanding rustc and the Compilation Pipeline
- Cargo Projects and Directory Layout
- Dependency Management and Version Resolution
- Features, Profiles and Build Scripts
- Cross-Compilation and Target Management
- Summary
Chapter 3: Modules, Crates and Visibility
- Crates vs Modules vs Packages
- The Module System and File Structure
- Visibility Rules and pub Paths
- Use Statements and Paths
- Procedural Macros and Derive
- Conditional Compilation with cfg
- Summary
Chapter 4: Types, Expressions and Control Flow
- Primitive Types and Their Sizes
- Type Inference and Annotations
- Compound Types: Tuples and Arrays
- Functions, Parameters and Return Values
- Control Flow: Match, If, Loops
- Closures and Capture Semantics
- Summary
Chapter 5: Ownership, Borrowing and Lifetimes
- The Ownership Rules
- Move Semantics and Transfer of Ownership
- Borrowing and References
- Reborrowing and Mutable Borrowing
- Lifetimes and Lifetime Elision
- Non-Lexical Lifetimes (NLL)
- Summary
Chapter 6: The String and Slice Types
- str vs String vs String Literal
- UTF-8 Encoding and Character Boundaries
- Slices and Borrowed Views
- Performance of String Operations
- Working with Bytes and Encodings
- Custom String-Like Types
- Summary
Chapter 7: Collections and Data Structures
- Vec: The Dynamic Array
- VecDeque and LinkedList
- HashMap and HashSet
- BinaryHeap and BTreeMap
- Custom Collection Implementations
- Choosing the Right Collection
- Summary
Chapter 8: Generics, Traits and Trait Objects
- Generic Functions and Types
- Trait Definition and Implementation
- Trait Bounds and Where Clauses
- Associated Types and Type Aliases
- Trait Objects and Dynamic Dispatch
- Const Generics and Advanced Patterns
- Summary
Chapter 9: Smart Pointers and Interior Mutability
- Box and Heap Allocation
- Rc and Arc for Shared Ownership
- Interior Mutability: Cell and RefCell
- Mutex Guards and RwLock
- Pin and Self-Referential Types
- Designing Custom Smart Pointers
- Summary
Chapter 10: Stack, Heap and Data Layout
- Stack Allocation and Call Frames
- Heap Allocation and the Global Allocator
- Data Layout, Alignment and Padding
- Repr Attributes and ABI Control
- Sized vs Dynamically Sized Types
- Measuring and Optimizing Layout
- Summary
Chapter 11: Raw Pointers and Unsafe Rust
- When Unsafe Is Necessary
- Raw Pointer Operations
- Unsafe Functions and Blocks
- Soundness and Undefined Behavior
- Pointer Provenance and Validity
- Establishing and Maintaining Invariants
- Summary
Chapter 12: Initialization, MaybeUninit and Volatile
- Uninitialized Memory and ZSTs
- MaybeUninit: Safe Uninitialized Buffers
- Partial Initialization and Cleanup
- Volatile Operations
- Atomic Operations and Memory Ordering
- FFI-Safe Initialization
- Summary
Chapter 13: The Drop Trait and RAII
- The Drop Trait and Destruction Order
- RAII Pattern in Rust
- Drop Guards and Scoped Resources
- Interaction with Move and Clone
- Leak and Forget Semantics
- Designing Resource-Safe APIs
- Summary
Chapter 14: System Calls and OS Interfaces
- The Role of libc and syscalls
- Platform Abstraction Strategies
- Processes and Subprocess Management
- Environment Variables and Command-Line Arguments
- Signals and Interrupt Handling
- Cross-Platform System Programming
- Summary
Chapter 15: Filesystem and File I/O
- Path Types and Cross-Platform Paths
- File Handles and Descriptors
- Buffered and Raw I/O
- Directory Operations and Traversal
- Memory-Mapped Files
- Permissions, Ownership and Metadata
- Summary
Chapter 16: Networking and Sockets
- Socket Types and Address Families
- TCP Client and Server Programming
- UDP and Connectionless Communication
- Nonblocking I/O and Polling
- Protocol Implementation Strategies
- Network Error Handling
- Summary
Chapter 17: Threads and Shared-State Concurrency
- Thread Creation and Lifetime Management
- Scoped Threads
- Send and Sync Traits
- Mutex and Shared Mutable State
- RwLock for Read-Mostly Data
- Condition Variables and Synchronization
- Summary
Chapter 18: Message Passing and Channels
- Channel Semantics and Variants
- mpsc: Multiple Producer, Single Consumer
- Watch and Oneshot Channels
- Actor Pattern Implementation
- Work Distribution with Channels
- When to Choose Messages Over State
- Summary
Chapter 19: Atomics and Lock-Free Programming
- Atomic Types and Operations
- Memory Ordering Explained
- Building Lock-Free Data Structures
- Double-Checked Locking
- ABA Problem and Solutions
- When Lock-Free Is Worth It
- Summary
Chapter 20: Asynchronous Programming with Futures
- Why Async: The C10K Problem
- Futures and Poll Semantics
- Async and Await Syntax
- Executors and Task Scheduling
- Async I/O and Epoll/Kqueue/IOCP
- Task Cancellation, Join and Select
- Summary
Chapter 21: Concurrent Architecture Patterns
- Thread Pools and Work Scheduling
- Event Loops and Reactor Pattern
- Hybrid Sync/Async Architectures
- Backpressure and Flow Control
- Deadlock, Livelock and Starvation
- Choosing Between Concurrency Models
- Summary
Chapter 22: Foreign Function Interface
- FFI Basics and extern Blocks
- Calling Conventions and ABI Compatibility
- Representing C Types in Rust
- Ownership Across Language Boundaries
- Callbacks and Function Pointers
- Panics Across the Boundary
- Building Safe FFI Wrappers
- Summary
Chapter 23: Binary Formats and Serialization
- Endianness and Byte Order
- Manual Binary Parsing
- Serde and Serialization Frameworks
- Compact Binary Formats
- Parsing Untrusted Binary Input
- Memory-Efficient Deserialization
- Summary
Chapter 24: No Std and Embedded Rust
- The Difference Between std and core
- Setting Up no_std Projects
- Custom Allocators
- Panic Strategies in no_std
- Hardware Registers and Memory-Mapped I/O
- Cross-Compilation for Embedded Targets
- Summary
Chapter 25: Dynamic and Static Linking
- Library Types: lib, dylib, cdylib, staticlib
- Linking Models and Trade-Offs
- Executable Formats: ELF, Mach-O, PE
- Symbol Visibility and Link-Time Optimization
- Building Shared Libraries
- Deployment and Distribution
- Summary
Chapter 26: Security Engineering in Rust
- Rust’s Safety Guarantees (and Their Limits)
- Integer Overflow and Wrapping Arithmetic
- Buffer Safety and Bounds Checking
- Path Traversal and Filesystem Security
- Dependency Supply Chain and Auditing
- Cryptographic API Usage and Best Practices
- Summary
Chapter 27: Performance Engineering
- Understanding Rust’s Optimization Pipeline
- Cache Locality and Data-Oriented Design
- Memory Allocation Overhead
- Branch Prediction and Control Flow
- Vectorization and SIMD
- Release Builds, LTO and PGO
- Summary
Chapter 28: Profiling and Benchmarking
- Benchmarking with Criterion
- CPU Profiling and Flame Graphs
- Memory Profiling
- Hardware Performance Counters
- Assembly-Level Analysis
- Microbenchmarking Pitfalls
- Summary
Chapter 29: Testing, Debugging and Reliability
- Unit, Integration and Doc Tests
- Property-Based Testing with Proptest
- Fuzzing with AFL and Honggfuzz
- Miri for Undefined Behavior Detection
- Sanitizers: ASan, TSan, MSan
- Debugging and Core Dumps
- Summary
Chapter 30: Logging, Tracing and Observability
- Logging with the log Crate
- Structured Logging
- Tracing with the tracing Crate
- Span-Based Instrumentation
- Metrics and Telemetry
- Observability in Production
- Summary
Chapter 31: Building a High-Performance Network Service
- Requirements and Architecture Design
- Async Server Implementation
- Connection Handling and Protocol
- Concurrency and Backpressure
- Performance Optimization
- Testing and Deployment
- Summary
Chapter 32: Real-World Rust Systems and Case Studies
- Rust in the Linux Kernel
- Firecracker: Lightweight VM Management
- Cloudflare’s Rust Migration
- Discord’s Performance Improvements
- The Rust Ecosystem for Systems Programming
- Common Mistakes and Anti-Patterns
- Supply Chain and Security
- Career and Community
- Summary
Conclusion
Glossary
- A
- B
- C
- D
- E
- G
- H
- I
- J
- K
- L
- M
- N
- O
- P
- Q
- R
- S
- T
- U
- V
- W
- X
- Y
- Z
Rust Systems Programming Reference
- Essential Types and Sizes
- Key Traits
- Memory Ordering
- Common Unsafe Patterns
- Essential Macros
- Essential Standard Library Modules
Tools and Workflows Reference
- Essential Tools
- Essential Workflows
- Development Environment
- CI Pipeline Example
References
Further Reading
- Core Rust Resources
- Systems and Concurrency
- Performance and Optimization
- Embedded and Bare Metal
- Security
- Operating Systems and Kernel Development
- Community and Development
Roadmap for Production Systems
- Phase 1: Foundation (Weeks 1-4)
- Phase 2: Systems Basics (Weeks 5-8)
- Phase 3: Concurrency (Weeks 9-12)
- Phase 4: Advanced Topics (Weeks 13-16)
- Phase 5: Production Readiness (Weeks 17-20)
- Phase 6: Specialization (Weeks 21+)
- Ongoing Practices
- Production Checklist