SlideShare a Scribd company logo
1 of 24
Download to read offline
Whirlwind tour of the Runtime Dynamic
Linker
Goncalo Gomes
~ Software Development Engineer ~
~ Workday ~ Big Data Infrastructure ~
Agenda
1. Anatomy of a Linux C/C++ Library
2. Dynamic Link API
3. Linux Process Startup
4. Assorted DEMOS
The examples and this presentation will be available from
https://github.com/gagomes/presentations
.init
Who am I?
● Software Engineer at Workday, previously worked at Amazon
and Citrix R&D
● Interested in various CS subjects, e.g
○ Operating Systems, Virtualization, Debugging, Security, Algorithms,
Compilers and Distributed Systems
● Wrote an ELF parsing library in 2002 and a small debugger to
replace GDB
○ Eventually surrendered to using GDB
*Not currently using C on a regular basis :sad_panda:
● Libraries are reusable collections of data + code
● In Linux several other UNIX-like OSes, ELF is the default binary format for
executables and libraries
● There are two main types of libraries in Linux
○ Static libraries
○ Dynamically libraries (aka DSO, or Dynamic Shared Objects)
Libraries
Static Libraries
● Statically linked libraries are a collection of object files bundled in an archive
file
● Pros
○ Simple format. Think tarball of relocatable object files
○ Reduced link complexity (i.e each object file is bound to the executable file at link time)
○ Reduces runtime overhead
● Cons
○ Increases the final executable size
○ And consequently increases the memory footprint
○ Deployment of fixes for critical bugs and/or security vulnerabilities is harder
Dynamic Libraries
● Dynamic linked libraries are a type of ELF file (ET_DYN)
● Pros
○ Low storage and memory footprint
○ Can be loaded dynamically during runtime
○ Deployment of fixes for critical bugs and/or security vulnerabilities is easy
● Cons
○ Bindings occur during runtime
○ Symbol relocation is harder
○ Often requires PIC (Position Independent Code) in order to work
Sample “hello world” library
To build
Anatomy of a Linux C/C++ Library
#include <stdio.h>
void hello(void) {
printf("Hello, library world.n");
}
gcc -fPIC -c -o helloworld.o helloworld.c
gcc -shared -o libhelloworld.so helloworld.o
● Two distinct phases of compilation
● Step 1
○ Generate a relocatable object helloworld.o
● Step 2
○ Link objects in final assembly as a Shared Object (SO) aka libhelloworld.so
Library Build process
Invoking the helloworld() function from the libhelloworld.so library
Building our sample application and linking it against libhelloworld.so
Linking against libhelloworld.so
#include "helloworld.h"
int main(int argc, char **argv)
{
helloworld();
return 0;
}
gcc -o app app.c -l helloworld -L .
Dynamic Link API
● In libc since version 2.0 released in 1997
● Main header is dlfcn.h
● Consists of 4 main functions
○ dlopen(3)
○ dlclose(3)
○ dlsym(3)
○ dlerror(3)
● GNU extensions can be made visible by defining _GNU_SOURCE prior to
inclusion of the header
● Requires explicit linking against libdl
dlopen
#include <dlfcn.h>
void *dlopen(const char *filename, int flags);
● Opens the library pointed to by the filename parameter
● Typically called with one of RTLD_LAZY or RTLD_NOW
○ For additional flags, check the dlopen(3) man page
● On success returns a handle to the library
● On error NULL is returned and dlerror will be set
dlclose
#include <dlfcn.h>
int dlclose(void *handle);
● Attempts to close a previously dlopen()’d handle
● On success returns 0, and on error returns a nonzero number
dlsym
#include <dlfcn.h>
void *dlsym(void *handle, const char *symbol);
● Returns a pointer to the symbol from the specified handle
● The GNU extensions define a special handle, which points to the next loaded
object containing the symbol name being requested
○ RTLD_NEXT
dlerror
#include <dlfcn.h>
char *dlerror(void);
● Returns a pointer to a string describing the most recent Dynamic Linking API
usage related error
Demo
Caveats
● RTLD_NEXT will find the next occurrence of a function in the search order
after the current library. If the next library in the search order contains their
own implementation of the symbol you’re trying to use, it will default to that
symbol.
● dl*sym functions do not report errors via dlerror (fixed in glibc 2.24)
● GCC inlines some builtin functions
○ E.g: abs, cos, exp, fabs, fprintf, fputs, labs, log, memcmp, memcpy, memset, printf, putchar,
puts, scanf, sin, snprintf, sprintf, sqrt, sscanf, strcat, strchr, strcmp, strcpy, strcspn, strlen,
strncat, strncmp, strncpy, strpbrk, strrchr, strspn, strstr, vprintf and vsprintf
○ Compile with -fno-builtin and -O0
Linux Process Startup - the 10,000 foot view
● This process entails:
○ System calls fork and execve are executed to spawn a new child process with our executable
○ The kernel then performs the following for us:
■ Identifies the type of executable file amongst a set of known / supported file formats
■ Sets up the environment variables and auxiliary vectors
■ Maps binary into memory
■ Locates the segment containing the interpreter (i.e ld-linux.so)
■ Maps the interpreter into memory, freshens up the registers and jumps into the
interpreter’s entry _dl_start
● HERE BE DRAGONS
■ Interpreter performs runtime dynamic linking operations (relocations and fixups)
■ it jumps into the executable’s entry point, which typically means the _start
● There are several linker related environment variables
○ LD_LIBRARY_PATH
○ LD_DEBUG and LD_DEBUG_OUTPUT
○ LD_PRELOAD
○ Etc.
Special environment variables
LD_PRELOAD
● Loads and interposes a library in the chain of dependencies (link map)
● It’s quite useful to subvert functionality from dynamic compiled executables
without modifying them
● It’s often used to superpose the functionality of existing code
○ e.g replace the calls to strcmp
● Some tricks it’s widely used for:
○ When working a library where you may not want to recompile the executable every time
○ Replace the system malloc implementation with an alternative one
○ Make spotify play “Never gonna give you up” *all* the time
● For security reasons, it is ignored by setuid binaries, but can still be made
available via /etc/ld.so.preload
Demo
● Listing symbols - nm
● Listing dependencies - ldd
● Listing the ELF related information
○ eu-readelf from elf-utils (recommended) or alternatively readelf from binutils
● Managing library search paths and links - ldconfig
Tools for managing and inspecting binaries
References and sources
● Glibc Manual
https://www.gnu.org/software/libc/manual/
● Linkers and Loaders
https://www.iecc.com/linker/
● x86-64 ABI documentation (r252)
https://github.com/hjl-tools/x86-psABI/wiki/x86-64-psABI-r252.pdf
● Ulrich Drepper’s DSO howto
https://www.akkadia.org/drepper/dsohowto.pdf
● Mayhem’s RTLD internals document
http://s.eresi-project.org/inc/articles/elf-rtld.txt
● Man pages: ld.so, dlopen, dlerror, dlsym, ar, gcc, ld, ldd, eu-readelf
Questions?
Thank you!

More Related Content

What's hot

10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about goDvir Volk
 
JDK8 Functional API
JDK8 Functional APIJDK8 Functional API
JDK8 Functional APIJustin Lin
 
OpenZFS code repository
OpenZFS code repositoryOpenZFS code repository
OpenZFS code repositoryMatthew Ahrens
 
Self-Hosted Scripting in Guile
Self-Hosted Scripting in GuileSelf-Hosted Scripting in Guile
Self-Hosted Scripting in GuileIgalia
 
CNIT 127: Ch 8: Windows overflows (Part 2)
CNIT 127: Ch 8: Windows overflows (Part 2)CNIT 127: Ch 8: Windows overflows (Part 2)
CNIT 127: Ch 8: Windows overflows (Part 2)Sam Bowne
 
Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming languageSlawomir Dorzak
 
Briefly Rust - Daniele Esposti - Codemotion Rome 2017
Briefly Rust - Daniele Esposti - Codemotion Rome 2017Briefly Rust - Daniele Esposti - Codemotion Rome 2017
Briefly Rust - Daniele Esposti - Codemotion Rome 2017Codemotion
 
Redis: Lua scripts - a primer and use cases
Redis: Lua scripts - a primer and use casesRedis: Lua scripts - a primer and use cases
Redis: Lua scripts - a primer and use casesRedis Labs
 
CNIT 127: Ch 4: Introduction to format string bugs
CNIT 127: Ch 4: Introduction to format string bugsCNIT 127: Ch 4: Introduction to format string bugs
CNIT 127: Ch 4: Introduction to format string bugsSam Bowne
 
Introduction to Go for Java Developers
Introduction to Go for Java DevelopersIntroduction to Go for Java Developers
Introduction to Go for Java DevelopersLaszlo Csontos
 
Compilation and Execution
Compilation and ExecutionCompilation and Execution
Compilation and ExecutionChong-Kuan Chen
 
Working with Shared Libraries in Perl
Working with Shared Libraries in PerlWorking with Shared Libraries in Perl
Working with Shared Libraries in PerlIdo Kanner
 
Lex tool manual
Lex tool manualLex tool manual
Lex tool manualSami Said
 
JavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closuresJavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closuresHDR1001
 
GNU Compiler Collection - August 2005
GNU Compiler Collection - August 2005GNU Compiler Collection - August 2005
GNU Compiler Collection - August 2005Saleem Ansari
 

What's hot (20)

10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about go
 
JDK8 Functional API
JDK8 Functional APIJDK8 Functional API
JDK8 Functional API
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Compilation
CompilationCompilation
Compilation
 
MinGw Compiler
MinGw CompilerMinGw Compiler
MinGw Compiler
 
OpenZFS code repository
OpenZFS code repositoryOpenZFS code repository
OpenZFS code repository
 
Self-Hosted Scripting in Guile
Self-Hosted Scripting in GuileSelf-Hosted Scripting in Guile
Self-Hosted Scripting in Guile
 
CNIT 127: Ch 8: Windows overflows (Part 2)
CNIT 127: Ch 8: Windows overflows (Part 2)CNIT 127: Ch 8: Windows overflows (Part 2)
CNIT 127: Ch 8: Windows overflows (Part 2)
 
Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming language
 
Briefly Rust - Daniele Esposti - Codemotion Rome 2017
Briefly Rust - Daniele Esposti - Codemotion Rome 2017Briefly Rust - Daniele Esposti - Codemotion Rome 2017
Briefly Rust - Daniele Esposti - Codemotion Rome 2017
 
Redis: Lua scripts - a primer and use cases
Redis: Lua scripts - a primer and use casesRedis: Lua scripts - a primer and use cases
Redis: Lua scripts - a primer and use cases
 
CNIT 127: Ch 4: Introduction to format string bugs
CNIT 127: Ch 4: Introduction to format string bugsCNIT 127: Ch 4: Introduction to format string bugs
CNIT 127: Ch 4: Introduction to format string bugs
 
Introduction to Go for Java Developers
Introduction to Go for Java DevelopersIntroduction to Go for Java Developers
Introduction to Go for Java Developers
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Compilation and Execution
Compilation and ExecutionCompilation and Execution
Compilation and Execution
 
Working with Shared Libraries in Perl
Working with Shared Libraries in PerlWorking with Shared Libraries in Perl
Working with Shared Libraries in Perl
 
Lex tool manual
Lex tool manualLex tool manual
Lex tool manual
 
Eval4j @ JVMLS 2014
Eval4j @ JVMLS 2014Eval4j @ JVMLS 2014
Eval4j @ JVMLS 2014
 
JavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closuresJavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closures
 
GNU Compiler Collection - August 2005
GNU Compiler Collection - August 2005GNU Compiler Collection - August 2005
GNU Compiler Collection - August 2005
 

Viewers also liked

Universidad del atlántico
Universidad del atlánticoUniversidad del atlántico
Universidad del atlánticomariela1183
 
Understanding overtime laws in california
Understanding overtime laws in californiaUnderstanding overtime laws in california
Understanding overtime laws in californiaRoger Carter
 
Cartilha: Vírus ZIKA — Informações ao Público.
Cartilha: Vírus ZIKA — Informações ao Público.Cartilha: Vírus ZIKA — Informações ao Público.
Cartilha: Vírus ZIKA — Informações ao Público.Elaine Cristine
 
dInformatica tipos-de-redes
dInformatica tipos-de-redesdInformatica tipos-de-redes
dInformatica tipos-de-redesjohn_zurita
 
Scarborough man accused of attempted murder
Scarborough man accused of attempted murderScarborough man accused of attempted murder
Scarborough man accused of attempted murderbrina97
 
Terry Taylor resume
Terry Taylor resumeTerry Taylor resume
Terry Taylor resumeTerry Taylor
 
Google My Business for Get Social Kent 2015
Google My Business for Get Social Kent 2015Google My Business for Get Social Kent 2015
Google My Business for Get Social Kent 2015Mark Jennings
 
Apache Apex connector with Kafka 0.9 consumer API
Apache Apex connector with Kafka 0.9 consumer APIApache Apex connector with Kafka 0.9 consumer API
Apache Apex connector with Kafka 0.9 consumer APIApache Apex
 
In the lands of corrupted elves - Breaking ELF software with Melkor fuzzer
In the lands of corrupted elves - Breaking ELF software with Melkor fuzzerIn the lands of corrupted elves - Breaking ELF software with Melkor fuzzer
In the lands of corrupted elves - Breaking ELF software with Melkor fuzzerAlejandro Hernández
 
LLVM Register Allocation (2nd Version)
LLVM Register Allocation (2nd Version)LLVM Register Allocation (2nd Version)
LLVM Register Allocation (2nd Version)Wang Hsiangkai
 
GNU gettext簡介 - 以C語言為範例
GNU gettext簡介 - 以C語言為範例GNU gettext簡介 - 以C語言為範例
GNU gettext簡介 - 以C語言為範例Wen Liao
 
[2007 CodeEngn Conference 01] seaofglass - Linux Virus Analysis
[2007 CodeEngn Conference 01] seaofglass - Linux Virus Analysis[2007 CodeEngn Conference 01] seaofglass - Linux Virus Analysis
[2007 CodeEngn Conference 01] seaofglass - Linux Virus AnalysisGangSeok Lee
 
bh-europe-01-clowes
bh-europe-01-clowesbh-europe-01-clowes
bh-europe-01-clowesguest3e5046
 
A hands-on introduction to the ELF Object file format
A hands-on introduction to the ELF Object file formatA hands-on introduction to the ELF Object file format
A hands-on introduction to the ELF Object file formatrety61
 

Viewers also liked (20)

Universidad del atlántico
Universidad del atlánticoUniversidad del atlántico
Universidad del atlántico
 
Understanding overtime laws in california
Understanding overtime laws in californiaUnderstanding overtime laws in california
Understanding overtime laws in california
 
Fourth paradigm
Fourth paradigmFourth paradigm
Fourth paradigm
 
Cartilha: Vírus ZIKA — Informações ao Público.
Cartilha: Vírus ZIKA — Informações ao Público.Cartilha: Vírus ZIKA — Informações ao Público.
Cartilha: Vírus ZIKA — Informações ao Público.
 
dInformatica tipos-de-redes
dInformatica tipos-de-redesdInformatica tipos-de-redes
dInformatica tipos-de-redes
 
Scarborough man accused of attempted murder
Scarborough man accused of attempted murderScarborough man accused of attempted murder
Scarborough man accused of attempted murder
 
Terry Taylor resume
Terry Taylor resumeTerry Taylor resume
Terry Taylor resume
 
Google My Business for Get Social Kent 2015
Google My Business for Get Social Kent 2015Google My Business for Get Social Kent 2015
Google My Business for Get Social Kent 2015
 
Polskie Startupy 2016
Polskie Startupy 2016 Polskie Startupy 2016
Polskie Startupy 2016
 
Folleto y mapa tarea 6
Folleto y mapa tarea 6Folleto y mapa tarea 6
Folleto y mapa tarea 6
 
Apache Apex connector with Kafka 0.9 consumer API
Apache Apex connector with Kafka 0.9 consumer APIApache Apex connector with Kafka 0.9 consumer API
Apache Apex connector with Kafka 0.9 consumer API
 
In the lands of corrupted elves - Breaking ELF software with Melkor fuzzer
In the lands of corrupted elves - Breaking ELF software with Melkor fuzzerIn the lands of corrupted elves - Breaking ELF software with Melkor fuzzer
In the lands of corrupted elves - Breaking ELF software with Melkor fuzzer
 
LLVM Register Allocation (2nd Version)
LLVM Register Allocation (2nd Version)LLVM Register Allocation (2nd Version)
LLVM Register Allocation (2nd Version)
 
Linkers in compiler
Linkers in compilerLinkers in compiler
Linkers in compiler
 
GNU gettext簡介 - 以C語言為範例
GNU gettext簡介 - 以C語言為範例GNU gettext簡介 - 以C語言為範例
GNU gettext簡介 - 以C語言為範例
 
[2007 CodeEngn Conference 01] seaofglass - Linux Virus Analysis
[2007 CodeEngn Conference 01] seaofglass - Linux Virus Analysis[2007 CodeEngn Conference 01] seaofglass - Linux Virus Analysis
[2007 CodeEngn Conference 01] seaofglass - Linux Virus Analysis
 
bh-europe-01-clowes
bh-europe-01-clowesbh-europe-01-clowes
bh-europe-01-clowes
 
Intro reverse engineering
Intro reverse engineeringIntro reverse engineering
Intro reverse engineering
 
A hands-on introduction to the ELF Object file format
A hands-on introduction to the ELF Object file formatA hands-on introduction to the ELF Object file format
A hands-on introduction to the ELF Object file format
 
Smqa unit iii
Smqa unit iiiSmqa unit iii
Smqa unit iii
 

Similar to Whirlwind tour of the Runtime Dynamic Linker

Exciting JavaScript - Part II
Exciting JavaScript - Part IIExciting JavaScript - Part II
Exciting JavaScript - Part IIEugene Lazutkin
 
嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain艾鍗科技
 
From gcc to the autotools
From gcc to the autotoolsFrom gcc to the autotools
From gcc to the autotoolsThierry Gayet
 
Advanced c programming in Linux
Advanced c programming in Linux Advanced c programming in Linux
Advanced c programming in Linux Mohammad Golyani
 
Understanding how C program works
Understanding how C program worksUnderstanding how C program works
Understanding how C program worksMindBridgeTech
 
DLL Design with Building Blocks
DLL Design with Building BlocksDLL Design with Building Blocks
DLL Design with Building BlocksMax Kleiner
 
Rlite software-architecture (1)
Rlite software-architecture (1)Rlite software-architecture (1)
Rlite software-architecture (1)ARCFIRE ICT
 
New c sharp4_features_part_iv
New c sharp4_features_part_ivNew c sharp4_features_part_iv
New c sharp4_features_part_ivNico Ludwig
 
Настройка окружения для кросскомпиляции проектов на основе docker'a
Настройка окружения для кросскомпиляции проектов на основе docker'aНастройка окружения для кросскомпиляции проектов на основе docker'a
Настройка окружения для кросскомпиляции проектов на основе docker'acorehard_by
 
Android Variants, Hacks, Tricks and Resources
Android Variants, Hacks, Tricks and ResourcesAndroid Variants, Hacks, Tricks and Resources
Android Variants, Hacks, Tricks and ResourcesOpersys inc.
 
Development and deployment with composer and kite
Development and deployment with composer and kiteDevelopment and deployment with composer and kite
Development and deployment with composer and kiteChristian Opitz
 
[Defcon24] Introduction to the Witchcraft Compiler Collection
[Defcon24] Introduction to the Witchcraft Compiler Collection[Defcon24] Introduction to the Witchcraft Compiler Collection
[Defcon24] Introduction to the Witchcraft Compiler CollectionMoabi.com
 
Purdue CS354 Operating Systems 2008
Purdue CS354 Operating Systems 2008Purdue CS354 Operating Systems 2008
Purdue CS354 Operating Systems 2008guestd9065
 
New c sharp4_features_part_vi
New c sharp4_features_part_viNew c sharp4_features_part_vi
New c sharp4_features_part_viNico Ludwig
 
.NET Core, ASP.NET Core Course, Session 3
.NET Core, ASP.NET Core Course, Session 3.NET Core, ASP.NET Core Course, Session 3
.NET Core, ASP.NET Core Course, Session 3aminmesbahi
 
Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?Jérôme Petazzoni
 

Similar to Whirlwind tour of the Runtime Dynamic Linker (20)

Libraries
LibrariesLibraries
Libraries
 
Ruxmon.2013-08.-.CodeBro!
Ruxmon.2013-08.-.CodeBro!Ruxmon.2013-08.-.CodeBro!
Ruxmon.2013-08.-.CodeBro!
 
Exciting JavaScript - Part II
Exciting JavaScript - Part IIExciting JavaScript - Part II
Exciting JavaScript - Part II
 
嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain
 
From gcc to the autotools
From gcc to the autotoolsFrom gcc to the autotools
From gcc to the autotools
 
Advanced c programming in Linux
Advanced c programming in Linux Advanced c programming in Linux
Advanced c programming in Linux
 
Understanding how C program works
Understanding how C program worksUnderstanding how C program works
Understanding how C program works
 
DLL Design with Building Blocks
DLL Design with Building BlocksDLL Design with Building Blocks
DLL Design with Building Blocks
 
Linkers
LinkersLinkers
Linkers
 
Rlite software-architecture (1)
Rlite software-architecture (1)Rlite software-architecture (1)
Rlite software-architecture (1)
 
New c sharp4_features_part_iv
New c sharp4_features_part_ivNew c sharp4_features_part_iv
New c sharp4_features_part_iv
 
Настройка окружения для кросскомпиляции проектов на основе docker'a
Настройка окружения для кросскомпиляции проектов на основе docker'aНастройка окружения для кросскомпиляции проектов на основе docker'a
Настройка окружения для кросскомпиляции проектов на основе docker'a
 
Android Variants, Hacks, Tricks and Resources
Android Variants, Hacks, Tricks and ResourcesAndroid Variants, Hacks, Tricks and Resources
Android Variants, Hacks, Tricks and Resources
 
Development and deployment with composer and kite
Development and deployment with composer and kiteDevelopment and deployment with composer and kite
Development and deployment with composer and kite
 
[Defcon24] Introduction to the Witchcraft Compiler Collection
[Defcon24] Introduction to the Witchcraft Compiler Collection[Defcon24] Introduction to the Witchcraft Compiler Collection
[Defcon24] Introduction to the Witchcraft Compiler Collection
 
Purdue CS354 Operating Systems 2008
Purdue CS354 Operating Systems 2008Purdue CS354 Operating Systems 2008
Purdue CS354 Operating Systems 2008
 
New c sharp4_features_part_vi
New c sharp4_features_part_viNew c sharp4_features_part_vi
New c sharp4_features_part_vi
 
.NET Core, ASP.NET Core Course, Session 3
.NET Core, ASP.NET Core Course, Session 3.NET Core, ASP.NET Core Course, Session 3
.NET Core, ASP.NET Core Course, Session 3
 
Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?
 
C++Basics2022.pptx
C++Basics2022.pptxC++Basics2022.pptx
C++Basics2022.pptx
 

Recently uploaded

Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxalwaysnagaraju26
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456KiaraTiradoMicha
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 

Recently uploaded (20)

Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 

Whirlwind tour of the Runtime Dynamic Linker

  • 1. Whirlwind tour of the Runtime Dynamic Linker Goncalo Gomes ~ Software Development Engineer ~ ~ Workday ~ Big Data Infrastructure ~
  • 2. Agenda 1. Anatomy of a Linux C/C++ Library 2. Dynamic Link API 3. Linux Process Startup 4. Assorted DEMOS The examples and this presentation will be available from https://github.com/gagomes/presentations .init
  • 3. Who am I? ● Software Engineer at Workday, previously worked at Amazon and Citrix R&D ● Interested in various CS subjects, e.g ○ Operating Systems, Virtualization, Debugging, Security, Algorithms, Compilers and Distributed Systems ● Wrote an ELF parsing library in 2002 and a small debugger to replace GDB ○ Eventually surrendered to using GDB *Not currently using C on a regular basis :sad_panda:
  • 4. ● Libraries are reusable collections of data + code ● In Linux several other UNIX-like OSes, ELF is the default binary format for executables and libraries ● There are two main types of libraries in Linux ○ Static libraries ○ Dynamically libraries (aka DSO, or Dynamic Shared Objects) Libraries
  • 5. Static Libraries ● Statically linked libraries are a collection of object files bundled in an archive file ● Pros ○ Simple format. Think tarball of relocatable object files ○ Reduced link complexity (i.e each object file is bound to the executable file at link time) ○ Reduces runtime overhead ● Cons ○ Increases the final executable size ○ And consequently increases the memory footprint ○ Deployment of fixes for critical bugs and/or security vulnerabilities is harder
  • 6. Dynamic Libraries ● Dynamic linked libraries are a type of ELF file (ET_DYN) ● Pros ○ Low storage and memory footprint ○ Can be loaded dynamically during runtime ○ Deployment of fixes for critical bugs and/or security vulnerabilities is easy ● Cons ○ Bindings occur during runtime ○ Symbol relocation is harder ○ Often requires PIC (Position Independent Code) in order to work
  • 7. Sample “hello world” library To build Anatomy of a Linux C/C++ Library #include <stdio.h> void hello(void) { printf("Hello, library world.n"); } gcc -fPIC -c -o helloworld.o helloworld.c gcc -shared -o libhelloworld.so helloworld.o
  • 8. ● Two distinct phases of compilation ● Step 1 ○ Generate a relocatable object helloworld.o ● Step 2 ○ Link objects in final assembly as a Shared Object (SO) aka libhelloworld.so Library Build process
  • 9. Invoking the helloworld() function from the libhelloworld.so library Building our sample application and linking it against libhelloworld.so Linking against libhelloworld.so #include "helloworld.h" int main(int argc, char **argv) { helloworld(); return 0; } gcc -o app app.c -l helloworld -L .
  • 10. Dynamic Link API ● In libc since version 2.0 released in 1997 ● Main header is dlfcn.h ● Consists of 4 main functions ○ dlopen(3) ○ dlclose(3) ○ dlsym(3) ○ dlerror(3) ● GNU extensions can be made visible by defining _GNU_SOURCE prior to inclusion of the header ● Requires explicit linking against libdl
  • 11. dlopen #include <dlfcn.h> void *dlopen(const char *filename, int flags); ● Opens the library pointed to by the filename parameter ● Typically called with one of RTLD_LAZY or RTLD_NOW ○ For additional flags, check the dlopen(3) man page ● On success returns a handle to the library ● On error NULL is returned and dlerror will be set
  • 12. dlclose #include <dlfcn.h> int dlclose(void *handle); ● Attempts to close a previously dlopen()’d handle ● On success returns 0, and on error returns a nonzero number
  • 13. dlsym #include <dlfcn.h> void *dlsym(void *handle, const char *symbol); ● Returns a pointer to the symbol from the specified handle ● The GNU extensions define a special handle, which points to the next loaded object containing the symbol name being requested ○ RTLD_NEXT
  • 14. dlerror #include <dlfcn.h> char *dlerror(void); ● Returns a pointer to a string describing the most recent Dynamic Linking API usage related error
  • 15. Demo
  • 16. Caveats ● RTLD_NEXT will find the next occurrence of a function in the search order after the current library. If the next library in the search order contains their own implementation of the symbol you’re trying to use, it will default to that symbol. ● dl*sym functions do not report errors via dlerror (fixed in glibc 2.24) ● GCC inlines some builtin functions ○ E.g: abs, cos, exp, fabs, fprintf, fputs, labs, log, memcmp, memcpy, memset, printf, putchar, puts, scanf, sin, snprintf, sprintf, sqrt, sscanf, strcat, strchr, strcmp, strcpy, strcspn, strlen, strncat, strncmp, strncpy, strpbrk, strrchr, strspn, strstr, vprintf and vsprintf ○ Compile with -fno-builtin and -O0
  • 17. Linux Process Startup - the 10,000 foot view ● This process entails: ○ System calls fork and execve are executed to spawn a new child process with our executable ○ The kernel then performs the following for us: ■ Identifies the type of executable file amongst a set of known / supported file formats ■ Sets up the environment variables and auxiliary vectors ■ Maps binary into memory ■ Locates the segment containing the interpreter (i.e ld-linux.so) ■ Maps the interpreter into memory, freshens up the registers and jumps into the interpreter’s entry _dl_start ● HERE BE DRAGONS ■ Interpreter performs runtime dynamic linking operations (relocations and fixups) ■ it jumps into the executable’s entry point, which typically means the _start
  • 18. ● There are several linker related environment variables ○ LD_LIBRARY_PATH ○ LD_DEBUG and LD_DEBUG_OUTPUT ○ LD_PRELOAD ○ Etc. Special environment variables
  • 19. LD_PRELOAD ● Loads and interposes a library in the chain of dependencies (link map) ● It’s quite useful to subvert functionality from dynamic compiled executables without modifying them ● It’s often used to superpose the functionality of existing code ○ e.g replace the calls to strcmp ● Some tricks it’s widely used for: ○ When working a library where you may not want to recompile the executable every time ○ Replace the system malloc implementation with an alternative one ○ Make spotify play “Never gonna give you up” *all* the time ● For security reasons, it is ignored by setuid binaries, but can still be made available via /etc/ld.so.preload
  • 20. Demo
  • 21. ● Listing symbols - nm ● Listing dependencies - ldd ● Listing the ELF related information ○ eu-readelf from elf-utils (recommended) or alternatively readelf from binutils ● Managing library search paths and links - ldconfig Tools for managing and inspecting binaries
  • 22. References and sources ● Glibc Manual https://www.gnu.org/software/libc/manual/ ● Linkers and Loaders https://www.iecc.com/linker/ ● x86-64 ABI documentation (r252) https://github.com/hjl-tools/x86-psABI/wiki/x86-64-psABI-r252.pdf ● Ulrich Drepper’s DSO howto https://www.akkadia.org/drepper/dsohowto.pdf ● Mayhem’s RTLD internals document http://s.eresi-project.org/inc/articles/elf-rtld.txt ● Man pages: ld.so, dlopen, dlerror, dlsym, ar, gcc, ld, ldd, eu-readelf