Executable Files for Linux / Исполняемые файлы для Linux
Год издания: 2026
Автор: Mishra Mohit / Мишра Мохит
Издательство: Apress
ISBN: 979-8-8688-2154-7
Язык: Английский
Формат: PDF/EPUB
Качество: Издательский макет или текст (eBook)
Интерактивное оглавление: Да
Количество страниц: 338
Описание: Focusing on the Executable and Linkable Format (ELF) used in Linux and Unix systems, this book explores how code is compiled, linked, and loaded into memory, and how the operating system executes it. You’ll learn to analyse ELF files, debug and optimize programs at the binary level, write custom linker scripts, and understand dynamic linking and symbol resolution.
ELF files are important because low-level programming and binary analysis are critical skills for system programmers, embedded developers, and security researchers. With the rise of performance optimization, cybersecurity, and resource-constrained environments (e.g., IoT), understanding executables is more relevant than ever.
Executable Files for Linux provides a hands-on, modern approach to a topic often overlooked in learning resources today.
What You Will Learn:
· Analyse and modify ELF files to optimize software performance
· Debug and optimize programs at the binary level
· Write custom linker scripts for complex projects
· Understand dynamic linking, lazy loading, and symbol resolution
· Explore kernel-level processes for loading and executing binaries
Who This Book Is For:
Developers and programmers working on operating systems, embedded systems, or low-level software as well as performance engineers and security professionals.
Сосредоточив внимание на формате исполняемых файлов и связываемых файлов (ELF), используемом в системах Linux и Unix, эта книга исследует, как код компилируется, связывается и загружается в память, а также как операционная система выполняет его. Вы научитесь анализировать файлы ELF, отлаживать и оптимизировать программы на двоичном уровне, писать пользовательские скрипты компоновщика и разбираться в динамической компоновке и разрешении символов.
Файлы ELF важны, поскольку низкоуровневое программирование и бинарный анализ являются важнейшими навыками для системных программистов, разработчиков встраиваемых систем и исследователей в области безопасности. С развитием технологий оптимизации производительности, кибербезопасности и сред с ограниченными ресурсами (например, Интернета вещей) понимание исполняемых файлов становится более актуальным, чем когда-либо.
Исполняемые файлы для Linux - это практический современный подход к теме, которая сегодня часто упускается из виду в учебных ресурсах.
Что Вы узнаете:
· Анализируйте и модифицируйте файлы ELF для оптимизации производительности программного обеспечения
· Отлаживайте и оптимизируйте программы на двоичном уровне
· Писать пользовательские сценарии компоновщика для сложных проектов
· Разбираться в динамической компоновке, отложенной загрузке и разрешении символов
· Изучать процессы загрузки и выполнения двоичных файлов на уровне ядра
Для кого предназначена эта книга:
Разработчики и программисты, работающие над операционными системами, встраиваемыми системами или низкоуровневым программным обеспечением, а также инженеры по производительности и специалисты по безопасности.
Примеры страниц (скриншоты)
Оглавление
About the Author xvii
About the Technical Reviewer xix
Acknowledgments xxi
Introduction xxiii
Chapter 1: Why Is My “Hello World” So Big? 1
Our Starting Point: The Simplest C Program 2
The Executable: More Than Meets the Eye 2
Introduction to the ELF Format 3
The Anatomy of an Executable: A Deeper Look 4
Code and Data Segments: Where Your Program Lives 4
Essential Infrastructure: Making Your Program Runnable 5
Runtime Support: Making Your Program Robust 6
Examining the Sections: A Guided Tour 6
Essential Code and Data Sections 7
Dynamic Linking Infrastructure 8
Runtime Support Sections 9
The Size Breakdown: Where Do All Those Bytes Go? 10
Can We Make It Smaller? 12
Basic Size Optimization 13
Static Linking (for Comparison) 13
Advanced Optimization 13
Why Keep All This “Overhead”? 13
Dynamic Linking Benefits 14
Runtime Infrastructure Benefits 14
Platform Compatibility Benefits 14
The Executable Lifecycle 15
Summary 16
Chapter 2: ELF: Demystifying the Executable Format 19
The Role of ELF in the Linux Ecosystem 19
A Brief History of ELF 20The Anatomy of an ELF File ...................................................................20
ELF File Structure Overview 22The ELF Header: The File’s Identity Card 23
Magic Number .......................................................................................................................24
File Type ...............................................................................................................................24
Machine Architecture 25Entry Point ..........................................................................................25
Header Locations 26Header Counts and Sizes ............................................................................26
Program Headers: Loading Instructions 27PHDR Segment 28INTERP Segment 28
LOAD Segments .....................................................................................................................28
DYNAMIC Segment 29Sections: Where Program Components Live 30Code Sections 32
Data Sections 33Symbol and Relocation Sections 34
Special Sections ....................................................................................................................35
The Linking Process: How ELF Files Come Together 36Creating a Relocatable Object File 36
Creating a Shared Library 36Creating a Static Executable 37
Security Implications of ELF Structure 38Memory Permissions and W^X 39
Position-Independent Executables (PIE) 39
Stack Canaries ......................................................................................................................40
RELRO (RELocation Read-Only) 40Working with ELF Files: Practical Examples 41
Adding Custom Data to an ELF File 41Stripping Debug Information 42
Analyzing Dependencies 42Viewing the Dynamic Symbol Table 43
Disassembling Functions 43
Tracing System Calls .............................................................................................................44
ELF in Different Contexts: A Comparison 44
Relocatable Files (.. 45
Executable Files ....................................................................................................................45
Shared Objects (.. ..............................................................................................................45
Core Dumps ...........................................................................................................................46
The Evolution of ELF: Past, Present, and Future 46Historical Evolution 46Modern Features ...............47
Future Directions ...................................................................................................................47
Case Study: Analyzing a Real-World Program 48Summary 49
Chapter 3: Where Your C Code Lives: Understanding ELF Sections 53
Sections vs.. Segments: A Quick Reminder 53The Four Primary Sections 54
The ..text Section: Where Your Code Lives 54
The ..rodata Section: Constants and String Literals 57
The ..data Section: Initialized Global Variables 58
The ..bss Section: Uninitialized Variables 60
Memory Layout 61
Section Permissions and Memory Protection 63
Security Through Section Permissions 64
Let's Get Hands-On: A Complete Example 64
Beyond the Basics: Other Important Sections 67
Dynamic Linking Sections .....................................................................................................67
Symbol and Relocation Sections 67Initialization and Finalization 67
Debugging Sections 68Practical Tips for Working with Sections 68
Examining Section Sizes to Optimize Binaries 68
Stripping Unnecessary Sections 69
Inspecting Section Permissions 70
Common Pitfalls and How to Avoid Them 70
String Literals Modification Attempts 70
Large .. 70
Accidentally Making Data Executable 71
Controlling Section Placement with GCC Attributes 71
Security Implications of Section Layout 73
How Sections Affect Program Loading and Performance 74
Tracing Real-World Examples .....................................................................................................74
New Innovations in ELF Sections 75Summary 75Chapter 4:
Before main(): The Secret Life of Global Variables in C 77
Introduction 77
The Mystery of Global Variable Initialization 78
Using GDB to Examine Pre-main Initialization 78
The Hidden Startup Sequence ....................................................................................................79
The ELF Initialization Sections ....................................................................................................80
Types of Global Variable Initialization 80Constant Initialization .......................................................80
Zero Initialization 81Dynamic Initialization 81Global Variable Storage in ELF Sections 82
Constructor and Destructor Functions 82
Common Pitfalls and How to Avoid Them 83
Initialization Order Dependencies 83
Dynamic Allocation Without Cleanup 84
Circular Dependencies ..........................................................................................................86
Best Practices for Global Variable Management 87
Prefer Static Initialization ......................................................................................................87
Use Singleton Functions for Complex Initialization 87
Implement Guards for Dynamic Initialization 88
Debugging Global Initialization Issues 88
Performance Considerations .......................................................................................................89
Minimize Constructor Work 89Use Lazy Initialization 89
Security Implications ..................................................................................................................89
Avoid Sensitive Operations in Constructors 90
Initialize Security-Critical Data Carefully 90
Summary 90
Chapter 5: The Linker: Bringing Your C Code Together 93
Introduction 93
A Multi-file Project Example .......................................................................................................93
The Compilation Process ............................................................................................................95
Understanding Object Files and Symbols 96
The Linking Process 96
Symbol Resolution in Detail ........................................................................................................97
Relocation: Patching Addresses ..................................................................................................97
Common Linking Issues and Solutions 98Undefined References ......................................................98
Multiple Definitions 98Link Order Dependencies ............................................................................99
Working with Static Libraries 99
Understanding the Linker’s Verbose Output 100Link-Time Optimization 100
Controlling Symbol Visibility 100
Advanced Linking Techniques 101
Version Scripts 101
Weak Symbols 102
Common Symbols ................................................................................................................102
Debugging Link Issues 102
Best Practices for Linking 103
Use Header Guards 103
Minimize Global Variables ...................................................................................................103
Use Static for Internal Functions 103
Organize Libraries Logically 103
Performance Considerations .....................................................................................................103
Link Order Optimization .......................................................................................................103
Dead Code Elimination 104Profile-Guided Optimization 104Summary 104
Chapter 6: Relocations: How the Linker Patches Your Code 107
Introduction 107Understanding Relocations with a Practical Example 108Examining Relocations in Object Files 109Common Relocation Types 110Absolute Relocations (R_X86_64_32S) 110PC-Relative Relocations (R_X86_64_PC32) 110PLT Relocations (R_X86_64_PLT32) 110Detailed Relocation Analysis 110How the Linker Applies Relocations 112Relocation Calculation Methods 113Absolute Relocations 113
Table of Contttt
xi
PC-Relative Relocations ......................................................................................................113PLT Relocations ...................................................................................................................114Debugging Relocation Issues 114Undefined References .........................................................................................................114Position-Independent Code Issues 114Text Relocations ..................................................................................................................114Advanced Relocation Types .......................................................................................................115Copy Relocations .................................................................................................................115GOT Relocations ..................................................................................................................115IFUNC Relocations .....................................................................................................................115Performance Implications of Relocations 116Absolute Relocations 116PC-Relative Relocations ......................................................................................................116PLT Relocations ...................................................................................................................116Security Considerations ............................................................................................................117RELRO (RELocation Read-Only) 117Address Space Layout Randomization (ASLR) 117Best Practices for Relocations 117Use Position-Independent Code When Appropriate 117Minimize Global Variables ...................................................................................................117Group-Related Symbols 117Tools for Analyzing Relocations 118Essential Commands 118Advanced Analysis 118Optimization Techniques ...........................................................................................................119Link-Time Optimization 119Profile-Guided Optimization 119Troubleshooting Common Issues 119Relocation Truncation ..........................................................................................................119Mixed PIC and Non-PIC Code 119Summary 120
Table of Contttt
xii
Chapter 7:
Symbols: The Linker’s Address Book 123The Symbol Mystery: What’s Really in Your Object Files? 123Understanding Symbol Types and Bindings 126The Three Levels of Symbol Visibility 126Common Symbols: A Legacy Feature 128Symbol Resolution: How the Linker Makes Decisions 129Advanced Symbol Properties 131Symbol Versioning for Library Evolution 131Symbol Visibility Control 133Practical Symbol Debugging 134Finding Symbol Problems 134Symbol Interposition for Debugging 136Symbol Tables in Shared Libraries 138Performance Impact of Symbol Resolution 139Summary 142Chapter 8:
Customizing the Layout: Introduction to Linker Scripts 143The Mystery of Memory Layout 143Understanding Linker Scripts: Your Memory Map Blueprint 145Creating Your First Custom Linker Script 145Practical Linker Script Concepts 148Understanding Memory Regions 148Understanding Sections ......................................................................................................148Load Address vs.. Runtime Address 149Advanced Linker Script Features 149Separating Critical Code ......................................................................................................149Exporting Linker Symbols 153Debugging Linker Scripts 154Common Issues and Solutions 155Practical Performance Impact ..................................................................................................155Summary 156Practical Exercises 157
Table of Contttt
xiii
Chapter 9:
Dynamic Linking in C: Shrinking Executables and Sharing Code 159The Cost of Static Linking: A Sobering Example 159Creating Your First Shared Library 162Building the Shared Library 164Using the Library: Method 1—Compile-Time Linking 165Solving the Library Path Problem 166Understanding the Dynamic Linking Process 168The GOT and PLT: Dynamic Linking’s Secret Machinery 168Watching Dynamic Linking in Real Time 169Method 2: Runtime Dynamic Loading with dlopen 171Advanced Topics: Symbol Versioning 174Performance Analysis: Static vs.. 176Security Considerations ............................................................................................................1791.. Library Injection Attacks 1792.. Protecting Against Injection 180Best Practices for Library Design 1811.. Proper Symbol Visibility 1812.. Library Initialization and Cleanup 181Debugging Dynamic Linking Issues 1821.. Common Problems and Solutions 1822.. Useful Debugging Tools 183Summary 183Chapter 10:
Lazy Loading: Dynamic Linking on Demand 185The Problem: Loading Everything Upfront 185Understanding the PLT and GOT 188The PLT (Procedure Linkage Table) 188The GOT (Global Offset Table) 189Observing Lazy Loading in Action 189Tracing the Resolution Process 192Controlling Lazy Loading Behavior 192
Table of Contttt
xiv
Forcing Immediate Binding 192Using dlopen with Different Flags 194Real-World Application: Plug-In Systems 195Performance Impact of Lazy Loading 200Security Implications of Lazy Loading 203The LD_BIND_NOW Security Pattern 203Advanced Topics: Profiling Symbol Resolution 204Summary 205Chapter 11:
Taking Control: Environment Variables for Dynamic Linking 207The Power Hidden in Environment Variables 207LD_LIBRARY_PATH: Controlling Library Search Order 208LD_LIBRARY_PATH 210Security Warning: The Dangers of LD_LIBRARY_PATH ........................................................212LD_DEBUG: Your Window into Dynamic Linking 213LD_PRELOAD: The Power and Peril of Function Interposition 214Example 2: Security Monitoring 216Example 3: Testing with Mock Functions 217LD_BIND_NOW: Trading Startup Time for Predictability 218Advanced Environment Variables 220LD_SHOW_AUXV: Understanding Process Initialization 220LD_TRACE_LOADED_OBJECTS: Alternative to ldd 222LD_DYNAMIC_WEAK: Controlling Weak Symbol Behavior ...................................................222Creating a Comprehensive Dynamic Linking Debugger 223Security Best Practices 224Protecting Against Library Injection 224Performance Optimization Patterns 226Dynamic Library Path Caching 226Summary 228
Table of Contttt
xv
Chapter 12:
Understanding Linux Executable Loading: A Deep Dive into Kernel Internals 231The Journey from Command to Execution 231The execve System Call: Where It All Begins 233Inside the Kernel: How execve Works 235The Kernel’s Loading Process: Step by Step 238Understanding Memory Mapping 243Binary Format Detection: Beyond ELF 245The VDSO: Kernel Services in Userspace 248Debugging Kernel Loading Issues 250Performance Impact of Different Loading Strategies 254Summary 256Chapter 13:
Weak Symbols: A Linker’s Flexibility 259The Problem: One Size Doesn’t Fit All 259Understanding Weak Symbols 261Examining Weak Symbols .........................................................................................................263Practical Applications of Weak Symbols 2661.. Hardware Abstraction Layers 2662.. Memory Allocator with Debug Hooks 2693.. Architecture-Specific Optimizations 275Symbol Resolution Rules ..........................................................................................................279Common Patterns and Best Practices 2811.. Library Initialization .........................................................................................................2812.. Error Handling Hooks .......................................................................................................283Debugging Weak Symbol Issues 285Performance Implications .........................................................................................................288Summary 291
Table of Contttt
xvi
Chapter 14:
Level Up Your C: Key Takeaways About Linking and Loading 293The Complete Picture: From Source to Running Process 293Key Concepts Integration Map 298Source Code to Object Files 298Linking Phase 300Executable Structure ...........................................................................................................302Kernel Loading Process 303Dynamic Linking at Runtime 303Program Execution 305Practical Toolbox: Essential Commands 307Compilation and Linking 307Analysis Tools 307Runtime Debugging .............................................................................................................307Performance Analysis ..........................................................................................................308Best Practices Checklist ...........................................................................................................308Library Design .....................................................................................................................308Security ...............................................................................................................................308Performance ........................................................................................................................308Debugging ...........................................................................................................................309Portability ............................................................................................................................309Real-World Application: Building a Plug-In System 309Performance Optimization Strategies 314Future Directions and Advanced Topics 316Conclusion: The Power of Understanding 317
Index 319