SlideShare uma empresa Scribd logo
1 de 23
Девятая независимая
научно-практическая конференция
«Разработка ПО 2013»
23 - 25 октября, Москва

Легковесное профилирование
разделяемых библиотек в Linux
для встраиваемых систем
Кирилл Кринкин, Марк Заславский, Эдуард Рябиков
Motivation
Popular Linux Profilers (gprof, gcov, GPT, Valgrind)
have following problems:
Need to recompile with special options
(gprof, gcov)
Need to relink program with 3rd-party libraries
(GPT)
Need to use special environment for profiling
(Valgrind)
Need to use superuser rights

12 November 2013

2
Project goals
We need a tool for system-wide ELF executables performance
analysis.

This tool should allow user next things do easily:
Profile function calls without recompilation and relinking with
3rd-party libraries
Profile only given set of C/C++ functions from shared libraries
in Linux
Profile both dynamically linked and dynamically loaded
functions
Profile without creating of special environment

Get information about number and total duration of function calls
Perform profiling on x86/x64 platforms
12 November 2013

3
“Non-invasive” profiling
Main ideas:
Profiler can not be implemented in the program code
Profiling should be performed at well-defined points of
function calls
Profiling process should not corrupt the algorithm of
profiled application
Profiling process should use minimum amount of
system resources
Results of profiling should be as accurate as possible

12 November 2013

4
Ways to implement
Infiltration into the symbol relocation
process
Modification of Linux dynamic linker
(ld-linux.so)
Modification of dynamic loading library
(libdl.so)

12 November 2013

5
Dynamic Linking
anylib.so
anyfunc1()
ld-linux.so 2

3

anyfunc2()
LD_LIBRARY_PATH

_dl_fixup

…
anyfuncn()

exe

_dl_profile_fixup
_dl_call_pltexit
1

12 November 2013

int main()
{
…
anyfunc1();
…
return 0;
}

6
ELF Parsing by Dynamic Linker
Executable object file
ELF header

Process image

Program header table
(required for executables)

init and shared lib
segments

.text section
.data section

.bss section
.symtab
.rel.text

.text segment
(r/o)

.data segment
(initialized r/w)

Virtual Address
0x080483e0

0x08048494

0x0804a010

.dynamic
.debug
Section header table
(required for relocatables)

.bss segment
(uninitialized r/w)

12 November 2013

0x0804a3b0

7
1. Resolving the Dependencies
When linking a dynamic executable, one or more shared
objects are explicitly referenced. These objects are recorded
as dependencies within the dynamic executable.
The runtime linker uses this dependency information to locate,
and load, the associated objects.
Once all the dynamic executable’s dependencies are loaded,
each dependency is inspected, in the order the dependency is
loaded, to locate any additional dependencies.

12 November 2013

8
1. Resolving the Dependencies
The Linux runtime linker looks in two default locations for dependencies /lib
and /usr/lib.

The dependencies of a dynamic executable or shared object can be displayed
using ldd. For example, the file /usr/bin/cat has the following dependencies:
$ ldd /usr/bin/cat
libc.so.1 => /lib/libc.so.1
libm.so.2 => /lib/libm.so.2
The dependencies recorded in an object can be inspected using dump. Use
this command to display the file’s .dynamic section, and look for entries that
have a NEEDED tag.
$ dump -Lvp prog
prog:
[INDEX] Tag Value
[1] NEEDED libfoo.so.1
[2] NEEDED libc.so.1
[3] RUNPATH /home/me/lib:/home/you/lib
.........
12 November 2013

9
Symbol Table Structure

12 November 2013

10
Parsing other sections of ELF
For dynamic linking, the Dynamic linker primarily uses two
processor-specific tables:
Global Offset Table (GOT)
Procedure Linkage Table (PLT)

Dynamic linkers support PIC Code through the GOT in each
shared library
The GOT contains absolute addresses to all of the static data
referenced in the program.

12 November 2013

11
Dynamic Loading
anylib.so

libdl.so

anyfunc1()

dlsym
dlsym

anyfunc2()

dlclose
LD_LIBRARY_PATH

dlopen
dlopen

…
anyfuncn()

1

dlerror

exe

2

ld-linux.so

?

3

int main()
{
void* p =
dlopen(“anylib.so”, RTLD_LAZY);
…
void(*f)() =
dlsym(p, “anyfunc1”);
…
f();
…
dlclose(p);
…
}

12 November 2013

12
Profiler components
Shared library libelfperf.so
Call redirection and function wrapping mechanisms
Collecting of calls statistics
Memory management

Modified dynamic linker (ld-linux.so)
Uses libelfperf.so for profiling of dynamically linked
functions
Displays the results of profiling

Modified dynamic loading library (libdl.so)
Uses libelfperf.so for profiling of dynamically loaded
functions

12 November 2013

13
Call redirection mechanism
Calls redirection mechanism (Redirector) is a set of
machine codes for the next assembly instructions:
push $fcnPtr
jmp $wrapper_addr

All they do is:
Save address of profiled function in program stack
Jump to wrapper-function

12 November 2013

14
Redirector workflow
Code

1

…
void(*f)() = dlsym(p, “any_function”);
…
f();
…

2

Redirector
push $fcnPtr
jmp $wrapper_addr

3
wrapper_addr

any_function
push %ebp
mov %esp,%ebp

fcnPtr

...
call preProfile
...

4

…
leave
ret

Wrapper

5

wrapper_rp:
...
call postProfile
...
ret

12 November 2013

15
Redirector details
Each redirector is created individually for
each profiled function
Redirectors are placed into data segment of
process virtual memory
The operating system allows to mark these
memory areas as executable

12 November 2013

16
Wrapping mechanism
Function Wrapping mechanism (or Wrapper) is a
function that does next things:
Takes control from redirector
Performs pre-profile operations
Performs replacement of return address
Performs jump into profiled function
Again takes control after the work of profiled
function

Performs post-profile operations
Returns to caller
12 November 2013

17
Working scheme of Wrapper
Params

Wrapper
Context
Return address

jmp

Function address

Function

Start time
ret

End time

Return value
12 November 2013

18
Implementation details (x86)
Wrapper
void wrapper()
{
//
push
%ebp
//
movl
%esp, %ebp
asm volatile (
"popl %ebpn"
"pushaln"
"pushl 32(%esp)n"
"pushl 40(%esp)n"
"call
preProfilen"
"addl
$8, %espn"
"movl
$wrapper_rp, 36(%esp)n"
"popaln"
"retln"
);
asm volatile (
"wrapper_rp:n"
"pushl $0n"
"pushaln"
"call
postProfilen"
"movl
%eax, 32(%esp)n"
"popaln"
"retln"
);

Function
push %ebp
mov %esp,%ebp

Context
ret address

start time

fcn address

end time

...
leave
retl

Stack Base
…

Registers

Higher
Memory
Addresses

%EAX

%EBX

fcn param #0
wrapper_rp
ret address
$0
fcn %EBX,
old %EBP
%EAX, address %E
CX, %EDX, %ESI,
old %EBP
%EAX, %EBX,
%EDI
%ECX, %EDX,
%ESI, %EDI

}

12 November 2013

%ESP

%EBP
%EBP

new
oldr
old

%ECX

new
oldr
old

%EDX

new
rval
old
old
new
oldr

%ESI

…

raddr
new
rval
old

%EDI

fcn param #n

new
oldr
old

19
Wrapper details
Wrapper doesn’t corrupt stack content

Wrapper exists in a single copy for all
functions in each profiler implementation (x86
or x64)
Saving/Restoring of registers’ state allows
to escape of uncontrollable changes in the
program state
Allows to profile wide set of C/C++ functions

12 November 2013

20
Interaction of ElfPerf’s components
elfperf-ld-linux.so

LD_PRELOAD

dlopen

_dl_fixup

dlsym

_dl_profile_fixup
LD_LIBRARY_PATH

elfperf-libdl.so

dlclose

_dl_call_pltexit
Shared memory
libelfperf.so

dlerror
ElfPerf Storage

Wrapper

Function Infos

Redirectors
Function Statistics

Statistics

Memory
management

12 November 2013

21
Conclusion
Now we have:

«Light» profiler based on «patched» ld-linux.so
and libdl.so
Support of profiling for C/C++ functions from
shared libraries
(including libs compiled with –fomit-frame-pointer
flag)
Collecting of information about number and total
duration of function calls
Support of both x86 and x64 platforms
12 November 2013

22
Links
Project resources:
https://github.com/OSLL/elfperf
http://dev.osll.ru/projects/epat/wiki/

Contacts:
http://osll.ru/
kirill.krinkin@gmail.com

edward.ryabikov@gmail.com
mark.zaslavskiy@gmail.com
12 November 2013

23

Mais conteúdo relacionado

Mais procurados

Program Structure in GNU/Linux (ELF Format)
Program Structure in GNU/Linux (ELF Format)Program Structure in GNU/Linux (ELF Format)
Program Structure in GNU/Linux (ELF Format)
Varun Mahajan
 
FORECAST: Fast Generation of Accurate Context-Aware Signatures of Control-Hij...
FORECAST: Fast Generation of Accurate Context-Aware Signatures of Control-Hij...FORECAST: Fast Generation of Accurate Context-Aware Signatures of Control-Hij...
FORECAST: Fast Generation of Accurate Context-Aware Signatures of Control-Hij...
Alexey Smirnov
 
Processes in unix
Processes in unixProcesses in unix
Processes in unix
miau_max
 

Mais procurados (20)

Compilation and Execution
Compilation and ExecutionCompilation and Execution
Compilation and Execution
 
Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11
 
Embedded Systems: Lecture 11: Introduction to Git & GitHub (Part 2)
Embedded Systems: Lecture 11: Introduction to Git & GitHub (Part 2)Embedded Systems: Lecture 11: Introduction to Git & GitHub (Part 2)
Embedded Systems: Lecture 11: Introduction to Git & GitHub (Part 2)
 
嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain
 
Assembler
AssemblerAssembler
Assembler
 
intro unix/linux 10
intro unix/linux 10intro unix/linux 10
intro unix/linux 10
 
Program Structure in GNU/Linux (ELF Format)
Program Structure in GNU/Linux (ELF Format)Program Structure in GNU/Linux (ELF Format)
Program Structure in GNU/Linux (ELF Format)
 
FORECAST: Fast Generation of Accurate Context-Aware Signatures of Control-Hij...
FORECAST: Fast Generation of Accurate Context-Aware Signatures of Control-Hij...FORECAST: Fast Generation of Accurate Context-Aware Signatures of Control-Hij...
FORECAST: Fast Generation of Accurate Context-Aware Signatures of Control-Hij...
 
FISL XIV - The ELF File Format and the Linux Loader
FISL XIV - The ELF File Format and the Linux LoaderFISL XIV - The ELF File Format and the Linux Loader
FISL XIV - The ELF File Format and the Linux Loader
 
Systems Programming Assignment Help - Processes
Systems Programming Assignment Help - ProcessesSystems Programming Assignment Help - Processes
Systems Programming Assignment Help - Processes
 
Configuration management I - Ansible + Packer
Configuration management I - Ansible + PackerConfiguration management I - Ansible + Packer
Configuration management I - Ansible + Packer
 
E bpf and dynamic tracing for mariadb db as (mariadb day during fosdem 2020)
E bpf and dynamic tracing for mariadb db as (mariadb day during fosdem 2020)E bpf and dynamic tracing for mariadb db as (mariadb day during fosdem 2020)
E bpf and dynamic tracing for mariadb db as (mariadb day during fosdem 2020)
 
Processes in unix
Processes in unixProcesses in unix
Processes in unix
 
File Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CFile Handling and Command Line Arguments in C
File Handling and Command Line Arguments in C
 
Ganesh naik linux_kernel_internals
Ganesh naik linux_kernel_internalsGanesh naik linux_kernel_internals
Ganesh naik linux_kernel_internals
 
Mc7404 np final
Mc7404 np finalMc7404 np final
Mc7404 np final
 
intro unix/linux 08
intro unix/linux 08intro unix/linux 08
intro unix/linux 08
 
Best Of Jdk 7
Best Of Jdk 7Best Of Jdk 7
Best Of Jdk 7
 
Ch3 gnu make
Ch3 gnu makeCh3 gnu make
Ch3 gnu make
 
Embedded Systems: Lecture 12: Introduction to Git & GitHub (Part 3)
Embedded Systems: Lecture 12: Introduction to Git & GitHub (Part 3)Embedded Systems: Lecture 12: Introduction to Git & GitHub (Part 3)
Embedded Systems: Lecture 12: Introduction to Git & GitHub (Part 3)
 

Destaque

141 deview 2013 발표자료(박준형) v1.1(track4-session1)
141 deview 2013 발표자료(박준형) v1.1(track4-session1)141 deview 2013 발표자료(박준형) v1.1(track4-session1)
141 deview 2013 발표자료(박준형) v1.1(track4-session1)
NAVER D2
 
Evdokimov python arsenal for re
Evdokimov   python arsenal for reEvdokimov   python arsenal for re
Evdokimov python arsenal for re
DefconRussia
 
Access to CAS Riak with Erlang
Access to CAS Riak with ErlangAccess to CAS Riak with Erlang
Access to CAS Riak with Erlang
OSLL
 
Geo2tag performance evaluation, Zaslavsky, Krinkin
Geo2tag performance evaluation, Zaslavsky, Krinkin Geo2tag performance evaluation, Zaslavsky, Krinkin
Geo2tag performance evaluation, Zaslavsky, Krinkin
OSLL
 
Porting smart m3 to the MeeGo
Porting smart m3 to the MeeGoPorting smart m3 to the MeeGo
Porting smart m3 to the MeeGo
OSLL
 
Smart-m3 Security Model
Smart-m3 Security Model Smart-m3 Security Model
Smart-m3 Security Model
OSLL
 
Lbs for transport monitoring based on geo2tag
Lbs for transport monitoring based on geo2tagLbs for transport monitoring based on geo2tag
Lbs for transport monitoring based on geo2tag
OSLL
 

Destaque (20)

Sharing C++ objects in Linux
Sharing C++ objects in LinuxSharing C++ objects in Linux
Sharing C++ objects in Linux
 
141 deview 2013 발표자료(박준형) v1.1(track4-session1)
141 deview 2013 발표자료(박준형) v1.1(track4-session1)141 deview 2013 발표자료(박준형) v1.1(track4-session1)
141 deview 2013 발표자료(박준형) v1.1(track4-session1)
 
SFO15-406: ARM FDPIC toolset, kernel & libraries for Cortex-M & Cortex-R mmul...
SFO15-406: ARM FDPIC toolset, kernel & libraries for Cortex-M & Cortex-R mmul...SFO15-406: ARM FDPIC toolset, kernel & libraries for Cortex-M & Cortex-R mmul...
SFO15-406: ARM FDPIC toolset, kernel & libraries for Cortex-M & Cortex-R mmul...
 
Evdokimov python arsenal for re
Evdokimov   python arsenal for reEvdokimov   python arsenal for re
Evdokimov python arsenal for re
 
Symbolic Debugging with DWARF
Symbolic Debugging with DWARFSymbolic Debugging with DWARF
Symbolic Debugging with DWARF
 
DWARF Data Representation
DWARF Data RepresentationDWARF Data Representation
DWARF Data Representation
 
Access to CAS Riak with Erlang
Access to CAS Riak with ErlangAccess to CAS Riak with Erlang
Access to CAS Riak with Erlang
 
Governo rodrigues alves
Governo rodrigues alvesGoverno rodrigues alves
Governo rodrigues alves
 
Fruct13 geo2tag-training
Fruct13 geo2tag-trainingFruct13 geo2tag-training
Fruct13 geo2tag-training
 
Slidesharepresentation introphoto
Slidesharepresentation introphotoSlidesharepresentation introphoto
Slidesharepresentation introphoto
 
Advices
AdvicesAdvices
Advices
 
Geo2tag performance evaluation, Zaslavsky, Krinkin
Geo2tag performance evaluation, Zaslavsky, Krinkin Geo2tag performance evaluation, Zaslavsky, Krinkin
Geo2tag performance evaluation, Zaslavsky, Krinkin
 
Porting smart m3 to the MeeGo
Porting smart m3 to the MeeGoPorting smart m3 to the MeeGo
Porting smart m3 to the MeeGo
 
Na bridge pdf
Na bridge pdfNa bridge pdf
Na bridge pdf
 
Exer._Mask_Variations
Exer._Mask_VariationsExer._Mask_Variations
Exer._Mask_Variations
 
Smart-m3 Security Model
Smart-m3 Security Model Smart-m3 Security Model
Smart-m3 Security Model
 
Na pp
Na ppNa pp
Na pp
 
Lbs for transport monitoring based on geo2tag
Lbs for transport monitoring based on geo2tagLbs for transport monitoring based on geo2tag
Lbs for transport monitoring based on geo2tag
 
Na opening photos acrobat
Na opening photos acrobatNa opening photos acrobat
Na opening photos acrobat
 
NA_EXER_LAYER_MASK_COMP
NA_EXER_LAYER_MASK_COMPNA_EXER_LAYER_MASK_COMP
NA_EXER_LAYER_MASK_COMP
 

Semelhante a SECR'13 Lightweight linux shared libraries profiling

LD_PRELOAD Exploitation - DC9723
LD_PRELOAD Exploitation - DC9723LD_PRELOAD Exploitation - DC9723
LD_PRELOAD Exploitation - DC9723
Iftach Ian Amit
 

Semelhante a SECR'13 Lightweight linux shared libraries profiling (20)

Linux automated tasks
Linux automated tasksLinux automated tasks
Linux automated tasks
 
Asian Spirit 3 Day Dba On Ubl
Asian Spirit 3 Day Dba On UblAsian Spirit 3 Day Dba On Ubl
Asian Spirit 3 Day Dba On Ubl
 
Do you know what your Drupal is doing Observe it! (DrupalCon Prague 2022)
Do you know what your Drupal is doing Observe it! (DrupalCon Prague 2022)Do you know what your Drupal is doing Observe it! (DrupalCon Prague 2022)
Do you know what your Drupal is doing Observe it! (DrupalCon Prague 2022)
 
Whirlwind tour of the Runtime Dynamic Linker
Whirlwind tour of the Runtime Dynamic LinkerWhirlwind tour of the Runtime Dynamic Linker
Whirlwind tour of the Runtime Dynamic Linker
 
ROS+GAZEBO
ROS+GAZEBOROS+GAZEBO
ROS+GAZEBO
 
Writing Character driver (loadable module) in linux
Writing Character driver (loadable module) in linuxWriting Character driver (loadable module) in linux
Writing Character driver (loadable module) in linux
 
Advanced spark training advanced spark internals and tuning reynold xin
Advanced spark training advanced spark internals and tuning reynold xinAdvanced spark training advanced spark internals and tuning reynold xin
Advanced spark training advanced spark internals and tuning reynold xin
 
PHP Development Tools
PHP  Development ToolsPHP  Development Tools
PHP Development Tools
 
Managing PostgreSQL with Ansible - FOSDEM PGDay 2016
Managing PostgreSQL with Ansible - FOSDEM PGDay 2016Managing PostgreSQL with Ansible - FOSDEM PGDay 2016
Managing PostgreSQL with Ansible - FOSDEM PGDay 2016
 
Catalyst MVC
Catalyst MVCCatalyst MVC
Catalyst MVC
 
Kernel Recipes 2016 - Landlock LSM: Unprivileged sandboxing
Kernel Recipes 2016 - Landlock LSM: Unprivileged sandboxingKernel Recipes 2016 - Landlock LSM: Unprivileged sandboxing
Kernel Recipes 2016 - Landlock LSM: Unprivileged sandboxing
 
sysprog4
sysprog4sysprog4
sysprog4
 
Automotive Grade Linux and systemd
Automotive Grade Linux and systemdAutomotive Grade Linux and systemd
Automotive Grade Linux and systemd
 
LD_PRELOAD Exploitation - DC9723
LD_PRELOAD Exploitation - DC9723LD_PRELOAD Exploitation - DC9723
LD_PRELOAD Exploitation - DC9723
 
Firebird Security (in English): The Past and The Future
Firebird Security (in English): The Past and The FutureFirebird Security (in English): The Past and The Future
Firebird Security (in English): The Past and The Future
 
More on bpftrace for MariaDB DBAs and Developers - FOSDEM 2022 MariaDB Devroom
More on bpftrace for MariaDB DBAs and Developers - FOSDEM 2022 MariaDB DevroomMore on bpftrace for MariaDB DBAs and Developers - FOSDEM 2022 MariaDB Devroom
More on bpftrace for MariaDB DBAs and Developers - FOSDEM 2022 MariaDB Devroom
 
An Overview of LLVM Link Time Optimization
An Overview of LLVM Link Time Optimization An Overview of LLVM Link Time Optimization
An Overview of LLVM Link Time Optimization
 
MyShell - English
MyShell - EnglishMyShell - English
MyShell - English
 
Log4Shell - Armageddon or Opportunity.pptx
Log4Shell - Armageddon or Opportunity.pptxLog4Shell - Armageddon or Opportunity.pptx
Log4Shell - Armageddon or Opportunity.pptx
 
Volatile memory analysis
Volatile memory analysisVolatile memory analysis
Volatile memory analysis
 

Mais de OSLL

Mais de OSLL (20)

SLAM Constructor Framework for ROS
SLAM Constructor Framework for ROSSLAM Constructor Framework for ROS
SLAM Constructor Framework for ROS
 
Студентам и не только. Как выступить с докладом по своей научной работе
Студентам и не только. Как выступить с докладом по своей научной работеСтудентам и не только. Как выступить с докладом по своей научной работе
Студентам и не только. Как выступить с докладом по своей научной работе
 
Full Automated Continuous Integration and Testing Infrastructure for Maxscale...
Full Automated Continuous Integration and Testing Infrastructure for Maxscale...Full Automated Continuous Integration and Testing Infrastructure for Maxscale...
Full Automated Continuous Integration and Testing Infrastructure for Maxscale...
 
MOOCs Virtual Lab in Modern Education
MOOCs Virtual Lab in Modern EducationMOOCs Virtual Lab in Modern Education
MOOCs Virtual Lab in Modern Education
 
Работа с геоданными в MongoDb
Работа с геоданными в MongoDbРабота с геоданными в MongoDb
Работа с геоданными в MongoDb
 
Testing with Selenium
Testing with SeleniumTesting with Selenium
Testing with Selenium
 
Implementation of the new REST API for Open Source LBS-platform Geo2Tag
Implementation of the new REST API for Open Source LBS-platform Geo2TagImplementation of the new REST API for Open Source LBS-platform Geo2Tag
Implementation of the new REST API for Open Source LBS-platform Geo2Tag
 
Microservice architecture for Geo2Tag
Microservice architecture for Geo2TagMicroservice architecture for Geo2Tag
Microservice architecture for Geo2Tag
 
[MDBCI] Mariadb continuous integration tool
[MDBCI] Mariadb continuous integration tool[MDBCI] Mariadb continuous integration tool
[MDBCI] Mariadb continuous integration tool
 
Block-level compression in Linux. Pro et contra
Block-level compression in Linux. Pro et contraBlock-level compression in Linux. Pro et contra
Block-level compression in Linux. Pro et contra
 
Fast Artificial Landmark Detection for indoor mobile robots AIMAVIG'2015
Fast Artificial Landmark Detection for indoor mobile robots AIMAVIG'2015Fast Artificial Landmark Detection for indoor mobile robots AIMAVIG'2015
Fast Artificial Landmark Detection for indoor mobile robots AIMAVIG'2015
 
Обзор файловой системы GlusterFS
Обзор файловой системы GlusterFSОбзор файловой системы GlusterFS
Обзор файловой системы GlusterFS
 
Обзор Btrfs
Обзор BtrfsОбзор Btrfs
Обзор Btrfs
 
Обзор архитектуры [файловой] системы Ceph
Обзор архитектуры [файловой] системы CephОбзор архитектуры [файловой] системы Ceph
Обзор архитектуры [файловой] системы Ceph
 
Linuxvirt seminar-csc-2015
Linuxvirt seminar-csc-2015Linuxvirt seminar-csc-2015
Linuxvirt seminar-csc-2015
 
Обзор Linux Control Groups
Обзор Linux Control GroupsОбзор Linux Control Groups
Обзор Linux Control Groups
 
Raspberry Pi robot with ROS
Raspberry Pi robot with ROSRaspberry Pi robot with ROS
Raspberry Pi robot with ROS
 
Пространства имен Linux (linux namespaces)
Пространства имен Linux (linux namespaces)Пространства имен Linux (linux namespaces)
Пространства имен Linux (linux namespaces)
 
Кратчайшее введение в docker по-русски
Кратчайшее введение в docker по-русскиКратчайшее введение в docker по-русски
Кратчайшее введение в docker по-русски
 
Virtual-HSM: Virtualization of Hardware Security Modules in Linux Containers
Virtual-HSM: Virtualization of Hardware Security Modules in Linux ContainersVirtual-HSM: Virtualization of Hardware Security Modules in Linux Containers
Virtual-HSM: Virtualization of Hardware Security Modules in Linux Containers
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 

SECR'13 Lightweight linux shared libraries profiling

  • 1. Девятая независимая научно-практическая конференция «Разработка ПО 2013» 23 - 25 октября, Москва Легковесное профилирование разделяемых библиотек в Linux для встраиваемых систем Кирилл Кринкин, Марк Заславский, Эдуард Рябиков
  • 2. Motivation Popular Linux Profilers (gprof, gcov, GPT, Valgrind) have following problems: Need to recompile with special options (gprof, gcov) Need to relink program with 3rd-party libraries (GPT) Need to use special environment for profiling (Valgrind) Need to use superuser rights 12 November 2013 2
  • 3. Project goals We need a tool for system-wide ELF executables performance analysis. This tool should allow user next things do easily: Profile function calls without recompilation and relinking with 3rd-party libraries Profile only given set of C/C++ functions from shared libraries in Linux Profile both dynamically linked and dynamically loaded functions Profile without creating of special environment Get information about number and total duration of function calls Perform profiling on x86/x64 platforms 12 November 2013 3
  • 4. “Non-invasive” profiling Main ideas: Profiler can not be implemented in the program code Profiling should be performed at well-defined points of function calls Profiling process should not corrupt the algorithm of profiled application Profiling process should use minimum amount of system resources Results of profiling should be as accurate as possible 12 November 2013 4
  • 5. Ways to implement Infiltration into the symbol relocation process Modification of Linux dynamic linker (ld-linux.so) Modification of dynamic loading library (libdl.so) 12 November 2013 5
  • 7. ELF Parsing by Dynamic Linker Executable object file ELF header Process image Program header table (required for executables) init and shared lib segments .text section .data section .bss section .symtab .rel.text .text segment (r/o) .data segment (initialized r/w) Virtual Address 0x080483e0 0x08048494 0x0804a010 .dynamic .debug Section header table (required for relocatables) .bss segment (uninitialized r/w) 12 November 2013 0x0804a3b0 7
  • 8. 1. Resolving the Dependencies When linking a dynamic executable, one or more shared objects are explicitly referenced. These objects are recorded as dependencies within the dynamic executable. The runtime linker uses this dependency information to locate, and load, the associated objects. Once all the dynamic executable’s dependencies are loaded, each dependency is inspected, in the order the dependency is loaded, to locate any additional dependencies. 12 November 2013 8
  • 9. 1. Resolving the Dependencies The Linux runtime linker looks in two default locations for dependencies /lib and /usr/lib. The dependencies of a dynamic executable or shared object can be displayed using ldd. For example, the file /usr/bin/cat has the following dependencies: $ ldd /usr/bin/cat libc.so.1 => /lib/libc.so.1 libm.so.2 => /lib/libm.so.2 The dependencies recorded in an object can be inspected using dump. Use this command to display the file’s .dynamic section, and look for entries that have a NEEDED tag. $ dump -Lvp prog prog: [INDEX] Tag Value [1] NEEDED libfoo.so.1 [2] NEEDED libc.so.1 [3] RUNPATH /home/me/lib:/home/you/lib ......... 12 November 2013 9
  • 10. Symbol Table Structure 12 November 2013 10
  • 11. Parsing other sections of ELF For dynamic linking, the Dynamic linker primarily uses two processor-specific tables: Global Offset Table (GOT) Procedure Linkage Table (PLT) Dynamic linkers support PIC Code through the GOT in each shared library The GOT contains absolute addresses to all of the static data referenced in the program. 12 November 2013 11
  • 12. Dynamic Loading anylib.so libdl.so anyfunc1() dlsym dlsym anyfunc2() dlclose LD_LIBRARY_PATH dlopen dlopen … anyfuncn() 1 dlerror exe 2 ld-linux.so ? 3 int main() { void* p = dlopen(“anylib.so”, RTLD_LAZY); … void(*f)() = dlsym(p, “anyfunc1”); … f(); … dlclose(p); … } 12 November 2013 12
  • 13. Profiler components Shared library libelfperf.so Call redirection and function wrapping mechanisms Collecting of calls statistics Memory management Modified dynamic linker (ld-linux.so) Uses libelfperf.so for profiling of dynamically linked functions Displays the results of profiling Modified dynamic loading library (libdl.so) Uses libelfperf.so for profiling of dynamically loaded functions 12 November 2013 13
  • 14. Call redirection mechanism Calls redirection mechanism (Redirector) is a set of machine codes for the next assembly instructions: push $fcnPtr jmp $wrapper_addr All they do is: Save address of profiled function in program stack Jump to wrapper-function 12 November 2013 14
  • 15. Redirector workflow Code 1 … void(*f)() = dlsym(p, “any_function”); … f(); … 2 Redirector push $fcnPtr jmp $wrapper_addr 3 wrapper_addr any_function push %ebp mov %esp,%ebp fcnPtr ... call preProfile ... 4 … leave ret Wrapper 5 wrapper_rp: ... call postProfile ... ret 12 November 2013 15
  • 16. Redirector details Each redirector is created individually for each profiled function Redirectors are placed into data segment of process virtual memory The operating system allows to mark these memory areas as executable 12 November 2013 16
  • 17. Wrapping mechanism Function Wrapping mechanism (or Wrapper) is a function that does next things: Takes control from redirector Performs pre-profile operations Performs replacement of return address Performs jump into profiled function Again takes control after the work of profiled function Performs post-profile operations Returns to caller 12 November 2013 17
  • 18. Working scheme of Wrapper Params Wrapper Context Return address jmp Function address Function Start time ret End time Return value 12 November 2013 18
  • 19. Implementation details (x86) Wrapper void wrapper() { // push %ebp // movl %esp, %ebp asm volatile ( "popl %ebpn" "pushaln" "pushl 32(%esp)n" "pushl 40(%esp)n" "call preProfilen" "addl $8, %espn" "movl $wrapper_rp, 36(%esp)n" "popaln" "retln" ); asm volatile ( "wrapper_rp:n" "pushl $0n" "pushaln" "call postProfilen" "movl %eax, 32(%esp)n" "popaln" "retln" ); Function push %ebp mov %esp,%ebp Context ret address start time fcn address end time ... leave retl Stack Base … Registers Higher Memory Addresses %EAX %EBX fcn param #0 wrapper_rp ret address $0 fcn %EBX, old %EBP %EAX, address %E CX, %EDX, %ESI, old %EBP %EAX, %EBX, %EDI %ECX, %EDX, %ESI, %EDI } 12 November 2013 %ESP %EBP %EBP new oldr old %ECX new oldr old %EDX new rval old old new oldr %ESI … raddr new rval old %EDI fcn param #n new oldr old 19
  • 20. Wrapper details Wrapper doesn’t corrupt stack content Wrapper exists in a single copy for all functions in each profiler implementation (x86 or x64) Saving/Restoring of registers’ state allows to escape of uncontrollable changes in the program state Allows to profile wide set of C/C++ functions 12 November 2013 20
  • 21. Interaction of ElfPerf’s components elfperf-ld-linux.so LD_PRELOAD dlopen _dl_fixup dlsym _dl_profile_fixup LD_LIBRARY_PATH elfperf-libdl.so dlclose _dl_call_pltexit Shared memory libelfperf.so dlerror ElfPerf Storage Wrapper Function Infos Redirectors Function Statistics Statistics Memory management 12 November 2013 21
  • 22. Conclusion Now we have: «Light» profiler based on «patched» ld-linux.so and libdl.so Support of profiling for C/C++ functions from shared libraries (including libs compiled with –fomit-frame-pointer flag) Collecting of information about number and total duration of function calls Support of both x86 and x64 platforms 12 November 2013 22