Advanced C and C++
Compiling
Contents at a Glance
Contents
About the Author
About the Technical Reviewers
Acknowledgment
Introduction
Chapter 1: Multitasking OS Basics
Useful Abstractions
Memory Hierarchy and Caching Strategy
Virtual Memory
Virtual Addressing
Process Memory Division Scheme
The Roles of Binaries, Compiler, Linker, and Loader
Summary
Chapter 2: Simple Program Lifetime Stages
Initial Assumptions
Code Writing
Concept illustration: Demo Project
Compiling
Introductory Definitions
Related Definitions
The Stages of Compiling
Preprocessing
Demo Project Preprocessing Example
Linguistic Analysis
Assembling
Demo Project Assembling Example
AT&T Assembly Format Example
Intel Assembly Format Example
Optimization
Code Emission
Demo Project Compiling Example
Object File Properties
Compilation Process Limitations
What Makes Section Combining so Complicated?
Linking
Linking Stages
Relocation
Resolving References
Demo Project Linking Example
Linker’s Viewpoint
Executable File Properties
Variety of Section Types
A Variety of Symbol Types
Chapter 3: Program Execution Stages
Importance of the Shell
Kernel Role
Loader Role
Loader-Specific View of a Binary File (Sections vs. Segments)
Program Loading Stage
Executing Program Entry Point
The Loader Finds the Entry Point
The Role of _start() Function
The Role of __libc_start_main() Function
Stack and Calling Conventions
Functions Calling Conventions
Chapter 4: The Impact of Reusing Concept
Static Libraries
Dynamic Libraries
Dynamic vs. Shared Libraries
Dynamic Linking in More Detail
Part 1: Building the Dynamic Library
Part 2: Playing by Trust While Building the Client Executable (Looking for the Symbols Only)
Part 3: Runtime Loading and Symbol Resolution
Peculiarities of Dynamic Linking on Windows
Special Binary File Types Related to Dynamic Linking in Windows
Dynamically Linked Library (.dll)
Import Library File (.lib)
Export File (.exp)
Unique Nature of Dynamic Library
Property 1: Dynamic Library Creation Requires the Complete Build Procedure
Property 2: The Dynamic Library Can Link In Other Libraries
Application Binary Interface (ABI)
Static vs. Dynamic Libraries Comparison Points
Differences in Import Selectiveness Criteria
Import Selectiveness Criteria for Static Libraries
Import Selectiveness Criteria for Dynamic Libraries
Whole Archive Import Scenario
Deployment Dilemma Scenarios
Choice 1: Linking with a Static Library
Choice 2: Linking with a Dynamic Library
Final Verdict
Useful Comparison Analogies
The Conclusion: The Impact of Binary Reuse Concept
Chapter 5: Working with Static Libraries
Creating Static Library
Creating Linux Static Library
Creating a Windows Static Library
Using the Static Library
Recommended Use Case Scenarios
Static Libraries Tips and Tricks
Potential for Losing the Symbol Visibility and Uniqueness
Counterindicated Use Case Scenarios
Specific Rules of Linking Static Libraries
Converting Static to Dynamic Library
Static Libraries Issues on 64-bit Linux
Resolving the Problem In Real Life Scenarios
Chapter 6: Designing Dynamic Libraries: Basics
Creating the Dynamic Library
Creating the Dynamic Library in Linux
About the -fPIC Compiler Flag
Question 1: What does - fPIC stand for?
Question 2: Is the use of the -fPIC compiler flag strictly required to build the dynamic library?
Question 3: Is the use of the -fPIC compiler flag strictly confined to the domain of dynamic libraries? Can it be used when...
Creating the Dynamic Library in Windows
Designing Dynamic Libraries
Designing the Binary Interface
C++ Issues
Issue #1: C++ Imposes More Complex Symbol Name Requirements
Issue #2: Static Initialization Order Fiasco
Problem Description
Avoiding the Problem
Issue #3: Templates
Designing the Application Binary Interface
Guideline #1: Implement the Dynamic Library ABI as a Set of C-style Functions
Guideline #2: Provide the Header File Carrying the Complete ABI Declaration
Guideline #3: Use Widely-Supported Standard C Keyword s
Guideline #4: Use a Class Factory Mechanism (C++) or Module (C)
Guideline #5: Export Only the Really Important Symbols
Guideline #6: Use Namespaces to Avoid Symbol Naming Collision
Controlling Dynamic Library Symbols’ Visibility
Exporting the Linux Dynamic Library Symbols
The Symbol Export Control at Build Time
The Other Methods
The Symbol Export Control Demo Example
The Default Symbols Visibility Case
The Controlled Symbols Visibility Case
Using the strip Utility
Exporting the Windows Dynamic Library Symbols
Using the __declspec(dllexport) Keyword
Using the Module-definition File (.def)
Linking Completion Requirements
--no-undefined Linker Flag
Dynamic Linking Modes
Statically Aware (Load-Time) Dynamic Linking
Runtime Dynamic Linking
Dynamic Linking Modes Comparison
Chapter 7: Locating the Libraries
Typical Library Use Case Scenarios
Development Use Case Scenario
End User Runtime Use Case Scenario
Build Time Library Location Rules
Linux Build Time Library Location Rules
Linux Static Library Naming Conventions
Linux Dynamic Library Naming Conventions
Dynamic Library Filename vs. Library Name
Dynamic Library Version Information
Dynamic Library Soname
Linker’s vs. Human’s Perception of Library Name
Linux Build Time Library Location Rules Details
Beginners’ Mistakes: What Can Possibly Go Wrong and How to Avoid It
Windows Build Time Library Location Rules
Project Linker Settings
#pragma Comment
Implicit Referencing of the Library Project
Runtime Dynamic Library Location Rules
Linux Runtime Dynamic Library Location Rules
Preloaded Libraries
rpath
LD_LIBRARY_PATH Environment Variable
runpath
ldconfig Cache
The Default Library Paths (/lib and /usr/lib)
Priority Scheme Summary
Windows Runtime Dynamic Library Location Rules
Linux Demo of Build Time and Runtime Conventions
Chapter 8: Designing Dynamic Libraries: Advanced Topics
Why Resolved Memory Addresses Are a Must
General Problem of Resolving References
Which Symbols Are Likely to Suffer from Address Translation?
Problems Caused by Address Translation
Scenario 1: Client Binary Needs to Know the Address of Dynamic Library Symbols
Scenario 2: Loaded Library No Longer Knows the Addresses of Its Own Symbols
Linker-Loader Coordination
Overall Strategy
Linker Recognizes Its Own Limitations
Linker Precisely Estimates the Damage, and Prepares Directives for Fixing It
The Loader Precisely Follows the Linker Directives
Tactics
Linker Directives Overview
Linker-Loader Coordination Implementation Techniques
Load Time Relocation (LTR)
Position Independent Code (PIC)
Lazy Binding
Rules and Limitations of the Recursive Chain of Dynamic Linking
Strong Implementation Preferences
Chapter 9: Handling Duplicate Symbols When Linking In Dynamic Libraries
Duplicate Symbols Definition
Typical Duplicate Symbols Scenarios
Duplicate C Symbols
Duplicate C++ Symbols
Duplicate Symbols Default Handling
Duplicate Local Symbols Are Allowed
Duplicate Symbols Handling When Linking in Dynamic Libraries
General Strategies of Eliminating Duplicate Symbols Problems
Duplicate Symbols and Dynamic Linking Modes
Linker’s Criteria in the Approximate Algorithm of Resolving Dynamic Libraries’ Duplicate Symbols
Location, Location, Location: Code Priority Zoning Rules
First Level Priority Symbols: Client Binary Symbols
Second Level Priority Symbols: Dynamic Library Visible Symbols
Third Level Priority (Unprioritized, Noncompeting) Symbols
Analyses of Specific Duplicate Names Cases
Case 1: Client Binary Symbol Collides with Dynamic Library ABI Function
Windows-Specific Twist
Case 2: ABI Symbols of Different Dynamic Libraries Collide
No Impact of Different Function Calls Order
Impact of Different Linking Order
Case 3: Dynamic Library ABI Symbol Collides with Another Dynamic Library Local Symbol
Case 4: Dynamic Library Non-exported Symbol Collides with Another Dynamic Library Non-exported Symbol
Interesting Scenario: Singleton in Static Library
Solving the Problem
Final Remark: Linking Does Not Provide Any Kind of Namespace Inheritance
Chapter 10: Dynamic Libraries Versioning
Gradation of Versions and their Impact on Backwards Compatibility
Major Version Code Changes
Minor Version Code Changes
Patch Version
Linux Dynamic Library Versioning Schemes
Linux Soname-based Versioning Scheme
Linux Library Filename Carries the Version Information
The Usual Dynamic Library Upgrade Practices
Preamble: The Flexibility of Softlinks
Preamble: Library Soname vs. Library Filename
Combining Softlink and Soname in the Library Upgrade Scheme
Extra Softlink Needed as Convenience for Development Scenarios
Analysis of Soname-based Versioning Scheme
The Softlink’s Role
Version Safeguarding Role of Soname
Technicalities of the Soname Implementation
Soname Embedded into the Dynamic Library File
Soname Propagated into the Client Binary File
The Support from the Other Utility Programs (ldconfig)
Linux Symbol Versioning Scheme
The Advantage of Symbol Versioning Mechanism
Symbol Versioning Mechanisms Analysis Model
Phase 1: Initial Version
Phase 2: Minor Version Changes
Phase 3: Major Version Changes
The Basic Implementation Ingredients
Linker Version Script
.symver Assembler Directive
How Does This Scheme Work?
Sample Project Analysis: Phase 1 (Initial Version)
ELF Format Support
Propagation of Version Symbol Information to the Client Binaries
Sample Project Analysis: Phase 2 (Minor Version Changes)
Sample Project Analysis: Phase 3 (Major Version Changes)
The Case of Changed ABI Function Behavior
The Case of Changed ABI Function Prototype
Version Script Syntax Overview
Version Node
Version Node Naming Rules
Symbols Export Control
Wildcard Support
Linkage Specifier Support
Namespace Support
Unnamed Node
Version Script Side Feature: Symbol Visibility Control
Windows Dynamic Libraries Versioning
DLL Version Information
Specifying DLL Version Information
Querying and Retrieving DLL Version Information
VERSIONINFO Structure
Linking Requirements
Elegant Way: Calling the DLL’s DllGetVersion Function
Brutal Alternative: Examining File Version Directly
Chapter 11: Dynamic Libraries: Miscellaneous Topics
Plug-in Concept
Rules of Exporting
Popular Plug-in Architectures
Tips and Tricks
Practical Implications of Working with Dynamic Libraries
Compartmentalized, Faster Development
Runtime Quick Substitution Ability
Miscellaneous Tips
Converting Dynamic Library to Executable
Conflicting Runtime Memory Handling of Windows Libraries
Linker Weak Symbols Explained
Chapter 12: Linux Toolbox
Quick Insight Tools
file Utility Program
size Utility Program
Detailed Analysis Tools
ldd
Safer ldd Alternatives
nm
objdump
Parsing ELF Header
Listing and Examining Sections
Listing All Symbols
Listing Dynamic Symbols Only
Examining Dynamic Section
Examining Relocation Section
Examining Data Section
Listing and Examining Segments
Disassembling the Code
objdump nm equivalents
readelf
Parsing ELF Header
Listing and Examining Sections
Listing All Symbols
Listing Dynamic Symbols Only
Examining the Dynamic Section
Examining the Relocation Section
Examining the Data Section
Listing and Examining Segments
Detecting the Debug Build
Deployment Phase Tools
chrpath
patchelf
strip
ldconfig
Runtime Analysis Tools
strace
addr2line
gdb (GNU Debugger)
Static Library Tools
ar
Creating the Static Library
Listing the Static Library Object Files
Deleting an Object File from the Static Library
Adding the New Object File to the Static Library
Restoring the Order of Object Files
Chapter 13: Linux How To’s
Debugging the Linking
Determining the Binary File Type
Determining the Binary File Entry Point
Determining the Executable Entry Point
Determining the Dynamic Library Entry Point
List Symbols
List and Examine Sections
Listing the Available Sections
Examining Specific Sections
Examining the Dynamic Section
Determining Whether Dynamic Library is PIC or LTR
Examining the Relocation Section
Examining the Data Section
List and Examine Segments
Disassembling the Code
Disassembling the Binary File
Disassembling the Running Process
Identifying the Debug Build
Listing Load-time Dependencies
Listing the Libraries Known to the Loader
Listing Dynamically Linked Libraries
strace Utility
LD_DEBUG Environment Variable
/proc//maps File
lsof Utility
Programmatic Way
Creating and Maintaining the Static Library
Chapter 14: Windows Toolbox
Library Manager (lib.exe)
lib.exe as a Static Library Tool
lib.exe as a Default Archiver Tool
lib.exe as a Command Line Utility
Creating a Static Library
Listing the Static Library Contents
Removing Individual Object Files from the Static Library
Inserting the Object File into the Static Library
Extracting the Individual Object File from the Static Library
lib.exe in the Realm of Dynamic Libraries (Import Library Tool)
dumpbin Utility
Identifying the Binary File Type
Listing the DLL Exported Symbols
Listing and Examining the Sections
Disassembling the Code
Identifying the Debug Build
Object Files
DLLs and Executables
Listing the Load Time Dependencies
Dependency Walker
Index