Linux User Space Debugging & Profiling

Anil Kumar Pugalia
Anil Kumar PugaliaLinux Geek and Open Source Hardware & Software Freak, Corporate Trainer, Entrepreneur in Automation
© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Debugging & Profiling
2© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
What to Expect?
Debugging
Various Techniques
Using Debugger: gdb
Profiling using
Program Checkers
Code Coverage Tools
Performance Analyzers
3© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Debugging
4© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Ways of Debugging
Basic: Printing
Querying
Kernel Windows: /proc, /sys
Using Commands like ipcs
Tracing: strace
Debugger: gdb
5© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Debugger: gdb
Text mode debugger
Repetition of previous command
Very powerful
All kind of options: Breakpoint, Watch, ...
Extensive Help
GUI interfaces: ddd, ...
6© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
gdb: Debugging Strategies
Oh no!!! Another tool to learn
Worth learning a new tool
Segmentation faults & Core dumps
Execution intercepted by gdb
Allows examining the state, backtrace, etc
Debugging is Narrowing Down
Reaching close & then stepping
7© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
'gdb' Usage
Compile with -g option
gcc -g file.c -o file
Run gdb (with desired options)
gdb [options] ./file [core file]
Pass command line arguments by setting args
set args <cmd_line_args>
Run the program by
Typing c, or
run <cmd_line_args>
For debugging: break, watch, backtrace, …
For help: help <command>
8© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
gdb: Examining Source Files
list <line>
Print 10 lines around <line>
list [<filename>:]<function>
Print 10 lines around beginning of <function>
list <start>,<end>
Print lines from <start> to <end>
list
Print 10 more lines
9© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
gdb: Other ways of Running
step [ count ] – step into sub-routines
next – run over sub-routines in a go
finish – run till current function returns
return – make selected stack frame return to its
caller
jump <address> – continue program at specified
line or address
10© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
gdb: Breakpoints
info break – Show list & status of breakpoints
Setting breakpoints (returns its number)
[t]break <function> [ if <expr> ]
[t]break [<file>:]<line>
Breakpoint Operations
disable <break_no>
enable <break_no>
delete <break_no>
commands <break_no>
Execute gdb commands on reaching <break_no>
11© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
gdb: Examining the Stack
Stack grows down
Each call state is referred as a frame
backtrace – Show stack frames
frame <frame_no> – Select <frame_no>
down – Select callee's frame
up – Select caller's frame
info args – Show args of current frame
info locals – Show locals of current frame
12© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
gdb: Examining Data
print[/xduotcf] <expr>
Evaluate the valid C <expr> within current frame
set variable <var> = <expr>
Assign <expr> to <var> in the current scope
Variables starting with $ are local to gdb
display <expr>
Print <expr> whenever program stops
undisplay
Cancels all previous display requests
13© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
gdb: Other Examinations
Watchpoints / Catchpoints
info watchpoints (Same as info break)
watch <expr> - Break on Write watchpoint
rwatch <expr> - Break on Read watchpoint
awatch <expr> - Break on Both watchpoint
Default is hardware watchpoint
Registers: info registers
Set-able options: info set
14© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
gdb: Shortcuts
Just enough of command
To make it unique
Added with tab completion
First letter only for
break, delete, run, continue, step, next, print
Repeat last by <Enter>
Executing the same set of initial commands
Put them in .gdbinit
-x <gdb command file>
15© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
gdb: Miscellaneous
Set editmode for gdb command line
editmode [ emacs | vi | dumb ]
Execute a shell command
shell <cmd>
Print command history
history
Set logging
set logging <on | off>
set logging file <log_file> (Default: gdb.txt)
16© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
gdb: Thread Debugging
Automatic notification of new threads
Switching among threads
thread <thread_no>
Auto switching on stop by breakpoint or signal
Inquiry on existing threads
info threads
Applying command to a list of threads
thread apply <thread_no> | all <cmd>
Thread specific breakpoints
Example: break <line> thread <thread_no>
17© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
gdb: Multi-Process Debugging
gdb version >= 7.1
Multiple processes from same session
Before that
Run different programs with different gdb
If parent-child program
Run the parent using gdb
Attach another gdb with running child pid
18© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Let's Debug
Debug
debugging_cprog.c
find_the_bug.c
Thread Debugging
multi_threads.c
19© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
User Process Memory Debugging
ElectricFence → DUMA
MEMWATCH
All these tools replaces the usual memory
allocation functions like malloc, free, … by the ones
to keep track of the same
20© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Profiling
21© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
W's of Profiling
Analyzing & Understanding Programs
Many varieties
Coding Style Checker
Logic Analysis
Memory Analysis
Execution Time Profiling
Run Time Error Capture
Execution Flow Analysis
22© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Profiling Categories
Program Check
Static (splint)
Dynamic (memwatch, ElectricFence → DUMA)
Code Coverage (Dynamic)
Execution Flow using test vectors (gcov)
Performance Analysis (Dynamic)
Execution Time using test vectors (gprof)
All in One: valgrind
23© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Static Program Checkers
Compiler itself
Really fast
But too naive
Other Extreme: Formal Verification Tools
Extensive
But needs huge resources
Preference: In between solutions
Example: splint
24© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
'splint' detects
Memory related Problems
Dereferencing a possibly null pointer, Using possibly undefined storage
Returning storage that is not properly defined
Dangling references, Memory leaks, Buffer overflow, ...
Dangerous Coding
Likely infinite loops, fall-through cases or incomplete switches
Suspicious statements, Dangerous aliasing
Dangerous macro implementations or invocations
Type mismatches with greater precision and flexibility, ...
Specific Violations of
Customized naming conventions
Information hiding
Modifications & Usage of global variable as per specified interfaces
...
25© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
'splint' Usage
Run splint (with desired options)
splint [options] file[.c]
Prints out all the messages about the file
On standard output
Errors on standard error (using -usestderr)
Some interesting options
-weak for lesser messages
-I <incl_dirs>
Try 'splint splint_cprog'
26© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Dynamic Program Checkers
Memory Debugging
mtrace (export MALLOC_TRACE=outfile.txt)
memwatch
ElectricFence → DUMA
...
Replaces the memory allocation functions
Like malloc, free, ...
By the ones to keep track of the same
27© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Code Coverage
Dynamic Execution Flow Analysis
Done by actually running the Program
Usually done with sets of test vectors
Providing the Test Code Coverage
Coverage of: Line of Code, Branches, Blocks, ...
Typically provides
Entity executed or not executed
% or times of execution of various entities
Tool: gcov
Could provide performance info when used with gprof
28© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
'gcov' Usage
Compile with -fprofile-arcs -ftest-coverage options
gcc -fprofile-arcs -ftest-coverage file.c -o file
Execute the program with the test vectors
./file [ <cmd_line_args> ]
Generates .gcda (Data) & .gcno (Graph) files
Run gcov (with desired options)
gcov [options] file.c
Interesting options: --all-blocks --branch-probabilities
Generates coverage output in .gcov file
Try with gcov_cprog.c
29© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Performance Analysis
Dynamic Execution Time Analysis
Done by actually running the Program
Usually done with sets of test vectors
Providing the Test Performance Analysis
Typically provides info on Functions
Time Spent, Times Called
Call Graph Profile Data
Performance Bottlenecks
Tool: gprof
30© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
'gprof' Usage
Compile with -pg option
gcc -pg file.c -o file
Run the program
./file [ <cmd_line_args> ]
Generates gmon.out file
Run gprof (with desired options)
gprof [options] ./file [gmon.out]
Dumps profiling info on stdout
Try with gprof_cprog.c
31© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Interesting 'gprof' Options
-b # Brief output
-p # Flat Profile
-q # Call Graph Analysis
-A # Print with Annotated source code
-x # Annotate all lines
-l # Line-by-line profiling
-s # Sum
-z # Display unused functions
-r, -R <mapfile> # Reordering suggestions
32© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Tool Suite: valgrind
Provides a number of debugging & profiling tools
Most popular being Memcheck
Best behaviour without optimization
Other possibly useful tools
Cachegrind: Profiler for cache (miss) and branch (misprediction) events
Callgrind: Profiler to show cost relationships across function calls,
optionally with cache simulation
Massif: Space profiler to explore in detail which parts of your program
allocate memory
Helgrind: Debugging tool for threaded programs
Looks for various kinds of synchronisation errors in code
That uses the POSIX pthreads API
GUI frontend: valkyrie
33© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
valgrind: Memcheck detects
Touching “shouldn’t” memories
Overrunning heap block boundaries
Reading/Writing freed/unallocated memory
Memory leaks
Not freeing heap blocks
Incorrect freeing of memory
Double-freeing heap blocks
Using values before initialization
34© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
'valgrind' Usage
Compile with -g option
gcc -g file.c -o file
Run using valgrind & desired options
valgrind [options] ./file [ <cmd_line_args> ]
By default, runs Memcheck
Profiles out the memory usage of the program
For using other tools of valgrind, add
--tool=<toolname>
Try with valgrind_cprog.c
35© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
What all have we learnt?
Debugging
Various Techniques
Using Debugger: gdb
Profiling using
Program Checkers
splint, mtrace, memwatch, ...
Code Coverage Tools
gcov
Performance Analyzers
gprof, valgrind, ...
36© 2010-15 SysPlay Workshops <workshop@sysplay.in>
All Rights Reserved.
Any Queries?
1 of 36

Recommended

[오픈소스컨설팅] Red Hat ReaR (relax and-recover) Quick Guide by
[오픈소스컨설팅] Red Hat ReaR (relax and-recover) Quick Guide[오픈소스컨설팅] Red Hat ReaR (relax and-recover) Quick Guide
[오픈소스컨설팅] Red Hat ReaR (relax and-recover) Quick GuideJi-Woong Choi
6.7K views21 slides
How to Choose a Software Update Mechanism for Embedded Linux Devices by
How to Choose a Software Update Mechanism for Embedded Linux DevicesHow to Choose a Software Update Mechanism for Embedded Linux Devices
How to Choose a Software Update Mechanism for Embedded Linux DevicesLeon Anavi
611 views42 slides
A practical guide to buildroot by
A practical guide to buildrootA practical guide to buildroot
A practical guide to buildrootEmertxe Information Technologies Pvt Ltd
2.7K views20 slides
Using and Customizing the Android Framework / part 4 of Embedded Android Work... by
Using and Customizing the Android Framework / part 4 of Embedded Android Work...Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Using and Customizing the Android Framework / part 4 of Embedded Android Work...Opersys inc.
10K views61 slides
The Linux Block Layer - Built for Fast Storage by
The Linux Block Layer - Built for Fast StorageThe Linux Block Layer - Built for Fast Storage
The Linux Block Layer - Built for Fast StorageKernel TLV
4.3K views42 slides
Embedded Android : System Development - Part III (Audio / Video HAL) by
Embedded Android : System Development - Part III (Audio / Video HAL)Embedded Android : System Development - Part III (Audio / Video HAL)
Embedded Android : System Development - Part III (Audio / Video HAL)Emertxe Information Technologies Pvt Ltd
11.9K views69 slides

More Related Content

What's hot

Kernel Debugging & Profiling by
Kernel Debugging & ProfilingKernel Debugging & Profiling
Kernel Debugging & ProfilingAnil Kumar Pugalia
18.8K views14 slides
SFO15-200: Linux kernel generic TEE driver by
SFO15-200: Linux kernel generic TEE driverSFO15-200: Linux kernel generic TEE driver
SFO15-200: Linux kernel generic TEE driverLinaro
4.7K views17 slides
Introduction to Linux Drivers by
Introduction to Linux DriversIntroduction to Linux Drivers
Introduction to Linux DriversAnil Kumar Pugalia
64.7K views29 slides
Android Boot Time Optimization by
Android Boot Time OptimizationAndroid Boot Time Optimization
Android Boot Time OptimizationKan-Ru Chen
13.1K views59 slides
Jagan Teki - U-boot from scratch by
Jagan Teki - U-boot from scratchJagan Teki - U-boot from scratch
Jagan Teki - U-boot from scratchlinuxlab_conf
708 views90 slides
syzkaller: the next gen kernel fuzzer by
syzkaller: the next gen kernel fuzzersyzkaller: the next gen kernel fuzzer
syzkaller: the next gen kernel fuzzerDmitry Vyukov
82.6K views54 slides

What's hot(20)

SFO15-200: Linux kernel generic TEE driver by Linaro
SFO15-200: Linux kernel generic TEE driverSFO15-200: Linux kernel generic TEE driver
SFO15-200: Linux kernel generic TEE driver
Linaro4.7K views
Android Boot Time Optimization by Kan-Ru Chen
Android Boot Time OptimizationAndroid Boot Time Optimization
Android Boot Time Optimization
Kan-Ru Chen13.1K views
Jagan Teki - U-boot from scratch by linuxlab_conf
Jagan Teki - U-boot from scratchJagan Teki - U-boot from scratch
Jagan Teki - U-boot from scratch
linuxlab_conf708 views
syzkaller: the next gen kernel fuzzer by Dmitry Vyukov
syzkaller: the next gen kernel fuzzersyzkaller: the next gen kernel fuzzer
syzkaller: the next gen kernel fuzzer
Dmitry Vyukov82.6K views
Introduction to GitHub Actions by Knoldus Inc.
Introduction to GitHub ActionsIntroduction to GitHub Actions
Introduction to GitHub Actions
Knoldus Inc.3.2K views
Course 102: Lecture 20: Networking In Linux (Basic Concepts) by Ahmed El-Arabawy
Course 102: Lecture 20: Networking In Linux (Basic Concepts) Course 102: Lecture 20: Networking In Linux (Basic Concepts)
Course 102: Lecture 20: Networking In Linux (Basic Concepts)
Ahmed El-Arabawy1.9K views
Learning AOSP - Android Booting Process by Nanik Tolaram
Learning AOSP - Android Booting ProcessLearning AOSP - Android Booting Process
Learning AOSP - Android Booting Process
Nanik Tolaram12.5K views
Introduction to ansible by Omid Vahdaty
Introduction to ansibleIntroduction to ansible
Introduction to ansible
Omid Vahdaty1.1K views
Booting Android: bootloaders, fastboot and boot images by Chris Simmonds
Booting Android: bootloaders, fastboot and boot imagesBooting Android: bootloaders, fastboot and boot images
Booting Android: bootloaders, fastboot and boot images
Chris Simmonds120.9K views
Meet cute-between-ebpf-and-tracing by Viller Hsiao
Meet cute-between-ebpf-and-tracingMeet cute-between-ebpf-and-tracing
Meet cute-between-ebpf-and-tracing
Viller Hsiao8.8K views
BKK16-110 A Gentle Introduction to Trusted Execution and OP-TEE by Linaro
BKK16-110 A Gentle Introduction to Trusted Execution and OP-TEEBKK16-110 A Gentle Introduction to Trusted Execution and OP-TEE
BKK16-110 A Gentle Introduction to Trusted Execution and OP-TEE
Linaro10.6K views
Understand and optimize Linux I/O by Andrea Righi
Understand and optimize Linux I/OUnderstand and optimize Linux I/O
Understand and optimize Linux I/O
Andrea Righi6.5K views

Viewers also liked

Shell Scripting by
Shell ScriptingShell Scripting
Shell ScriptingAnil Kumar Pugalia
6.2K views27 slides
Mobile Hacking using Linux Drivers by
Mobile Hacking using Linux DriversMobile Hacking using Linux Drivers
Mobile Hacking using Linux DriversAnil Kumar Pugalia
6K views33 slides
Embedded Software Design by
Embedded Software DesignEmbedded Software Design
Embedded Software DesignAnil Kumar Pugalia
7K views29 slides
Bootloaders by
BootloadersBootloaders
BootloadersAnil Kumar Pugalia
10K views19 slides
Functional Programming with LISP by
Functional Programming with LISPFunctional Programming with LISP
Functional Programming with LISPAnil Kumar Pugalia
6.1K views23 slides
Board Bringup by
Board BringupBoard Bringup
Board BringupAnil Kumar Pugalia
28.7K views16 slides

Viewers also liked(18)

Similar to Linux User Space Debugging & Profiling

Linux Internals Part - 3 by
Linux Internals Part - 3Linux Internals Part - 3
Linux Internals Part - 3SysPlay eLearning Academy for You
121 views52 slides
Kernel Debugging & Profiling by
Kernel Debugging & ProfilingKernel Debugging & Profiling
Kernel Debugging & ProfilingAnil Kumar Pugalia
6K views14 slides
jcmd #javacasual by
jcmd #javacasualjcmd #javacasual
jcmd #javacasualYuji Kubota
16.9K views42 slides
Groovy In the Cloud by
Groovy In the CloudGroovy In the Cloud
Groovy In the CloudJim Driscoll
1.9K views42 slides
Android developmenttools 20100424 by
Android developmenttools 20100424Android developmenttools 20100424
Android developmenttools 20100424Marakana Inc.
718 views20 slides
C# Production Debugging Made Easy by
 C# Production Debugging Made Easy C# Production Debugging Made Easy
C# Production Debugging Made EasyAlon Fliess
4K views35 slides

Similar to Linux User Space Debugging & Profiling(20)

jcmd #javacasual by Yuji Kubota
jcmd #javacasualjcmd #javacasual
jcmd #javacasual
Yuji Kubota16.9K views
Groovy In the Cloud by Jim Driscoll
Groovy In the CloudGroovy In the Cloud
Groovy In the Cloud
Jim Driscoll1.9K views
Android developmenttools 20100424 by Marakana Inc.
Android developmenttools 20100424Android developmenttools 20100424
Android developmenttools 20100424
Marakana Inc.718 views
C# Production Debugging Made Easy by Alon Fliess
 C# Production Debugging Made Easy C# Production Debugging Made Easy
C# Production Debugging Made Easy
Alon Fliess4K views
IBM Monitoring and Diagnostic Tools - GCMV 2.8 by Chris Bailey
IBM Monitoring and Diagnostic Tools - GCMV 2.8IBM Monitoring and Diagnostic Tools - GCMV 2.8
IBM Monitoring and Diagnostic Tools - GCMV 2.8
Chris Bailey5K views
Embedded Android by 晓东 杜
Embedded AndroidEmbedded Android
Embedded Android
晓东 杜243 views
Bp307 Practical Solutions for Connections Administrators, tips and scrips for... by Sharon James
Bp307 Practical Solutions for Connections Administrators, tips and scrips for...Bp307 Practical Solutions for Connections Administrators, tips and scrips for...
Bp307 Practical Solutions for Connections Administrators, tips and scrips for...
Sharon James1.1K views
Advanced Python, Part 2 by Zaar Hai
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2
Zaar Hai957 views
Accelerated Mac OS X Core Dump Analysis training public slides by Dmitry Vostokov
Accelerated Mac OS X Core Dump Analysis training public slidesAccelerated Mac OS X Core Dump Analysis training public slides
Accelerated Mac OS X Core Dump Analysis training public slides
Dmitry Vostokov211 views
Linux Cluster Job Management Systems (SGE) by anandvaidya
Linux Cluster Job Management Systems (SGE)Linux Cluster Job Management Systems (SGE)
Linux Cluster Job Management Systems (SGE)
anandvaidya6.8K views
Monitoring using Prometheus and Grafana by Arvind Kumar G.S
Monitoring using Prometheus and GrafanaMonitoring using Prometheus and Grafana
Monitoring using Prometheus and Grafana
Arvind Kumar G.S3.5K views
Troubleshooting real production problems by Tier1 app
Troubleshooting real production problemsTroubleshooting real production problems
Troubleshooting real production problems
Tier1 app1.5K views
Jörg Schad - Hybrid Cloud (Kubernetes, Spark, HDFS, …)-as-a-Service - Codemot... by Codemotion
Jörg Schad - Hybrid Cloud (Kubernetes, Spark, HDFS, …)-as-a-Service - Codemot...Jörg Schad - Hybrid Cloud (Kubernetes, Spark, HDFS, …)-as-a-Service - Codemot...
Jörg Schad - Hybrid Cloud (Kubernetes, Spark, HDFS, …)-as-a-Service - Codemot...
Codemotion153 views
Jörg Schad - Hybrid Cloud (Kubernetes, Spark, HDFS, …)-as-a-Service - Codemot... by Codemotion
Jörg Schad - Hybrid Cloud (Kubernetes, Spark, HDFS, …)-as-a-Service - Codemot...Jörg Schad - Hybrid Cloud (Kubernetes, Spark, HDFS, …)-as-a-Service - Codemot...
Jörg Schad - Hybrid Cloud (Kubernetes, Spark, HDFS, …)-as-a-Service - Codemot...
Codemotion193 views

More from Anil Kumar Pugalia

File System Modules by
File System ModulesFile System Modules
File System ModulesAnil Kumar Pugalia
21K views37 slides
System Calls by
System CallsSystem Calls
System CallsAnil Kumar Pugalia
4.2K views17 slides
Introduction to Linux by
Introduction to LinuxIntroduction to Linux
Introduction to LinuxAnil Kumar Pugalia
4K views33 slides
Playing with R L C Circuits by
Playing with R L C CircuitsPlaying with R L C Circuits
Playing with R L C CircuitsAnil Kumar Pugalia
2.8K views17 slides
Audio Drivers by
Audio DriversAudio Drivers
Audio DriversAnil Kumar Pugalia
20.8K views11 slides
Video Drivers by
Video DriversVideo Drivers
Video DriversAnil Kumar Pugalia
23.4K views38 slides

Recently uploaded

Microsoft Power Platform.pptx by
Microsoft Power Platform.pptxMicrosoft Power Platform.pptx
Microsoft Power Platform.pptxUni Systems S.M.S.A.
52 views38 slides
Lilypad @ Labweek, Istanbul, 2023.pdf by
Lilypad @ Labweek, Istanbul, 2023.pdfLilypad @ Labweek, Istanbul, 2023.pdf
Lilypad @ Labweek, Istanbul, 2023.pdfAlly339821
9 views45 slides
The Research Portal of Catalonia: Growing more (information) & more (services) by
The Research Portal of Catalonia: Growing more (information) & more (services)The Research Portal of Catalonia: Growing more (information) & more (services)
The Research Portal of Catalonia: Growing more (information) & more (services)CSUC - Consorci de Serveis Universitaris de Catalunya
79 views25 slides
Tunable Laser (1).pptx by
Tunable Laser (1).pptxTunable Laser (1).pptx
Tunable Laser (1).pptxHajira Mahmood
24 views37 slides
Case Study Copenhagen Energy and Business Central.pdf by
Case Study Copenhagen Energy and Business Central.pdfCase Study Copenhagen Energy and Business Central.pdf
Case Study Copenhagen Energy and Business Central.pdfAitana
16 views3 slides
STPI OctaNE CoE Brochure.pdf by
STPI OctaNE CoE Brochure.pdfSTPI OctaNE CoE Brochure.pdf
STPI OctaNE CoE Brochure.pdfmadhurjyapb
13 views1 slide

Recently uploaded(20)

Lilypad @ Labweek, Istanbul, 2023.pdf by Ally339821
Lilypad @ Labweek, Istanbul, 2023.pdfLilypad @ Labweek, Istanbul, 2023.pdf
Lilypad @ Labweek, Istanbul, 2023.pdf
Ally3398219 views
Case Study Copenhagen Energy and Business Central.pdf by Aitana
Case Study Copenhagen Energy and Business Central.pdfCase Study Copenhagen Energy and Business Central.pdf
Case Study Copenhagen Energy and Business Central.pdf
Aitana16 views
STPI OctaNE CoE Brochure.pdf by madhurjyapb
STPI OctaNE CoE Brochure.pdfSTPI OctaNE CoE Brochure.pdf
STPI OctaNE CoE Brochure.pdf
madhurjyapb13 views
Special_edition_innovator_2023.pdf by WillDavies22
Special_edition_innovator_2023.pdfSpecial_edition_innovator_2023.pdf
Special_edition_innovator_2023.pdf
WillDavies2217 views
The details of description: Techniques, tips, and tangents on alternative tex... by BookNet Canada
The details of description: Techniques, tips, and tangents on alternative tex...The details of description: Techniques, tips, and tangents on alternative tex...
The details of description: Techniques, tips, and tangents on alternative tex...
BookNet Canada126 views
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院 by IttrainingIttraining
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
Voice Logger - Telephony Integration Solution at Aegis by Nirmal Sharma
Voice Logger - Telephony Integration Solution at AegisVoice Logger - Telephony Integration Solution at Aegis
Voice Logger - Telephony Integration Solution at Aegis
Nirmal Sharma31 views
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas... by Bernd Ruecker
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
Bernd Ruecker33 views
Five Things You SHOULD Know About Postman by Postman
Five Things You SHOULD Know About PostmanFive Things You SHOULD Know About Postman
Five Things You SHOULD Know About Postman
Postman30 views
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive by Network Automation Forum
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveAutomating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive
AMAZON PRODUCT RESEARCH.pdf by JerikkLaureta
AMAZON PRODUCT RESEARCH.pdfAMAZON PRODUCT RESEARCH.pdf
AMAZON PRODUCT RESEARCH.pdf
JerikkLaureta19 views
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors by sugiuralab
TouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective SensorsTouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective Sensors
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors
sugiuralab19 views
1st parposal presentation.pptx by i238212
1st parposal presentation.pptx1st parposal presentation.pptx
1st parposal presentation.pptx
i2382129 views
Business Analyst Series 2023 - Week 3 Session 5 by DianaGray10
Business Analyst Series 2023 -  Week 3 Session 5Business Analyst Series 2023 -  Week 3 Session 5
Business Analyst Series 2023 - Week 3 Session 5
DianaGray10237 views

Linux User Space Debugging & Profiling

  • 1. © 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Debugging & Profiling
  • 2. 2© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. What to Expect? Debugging Various Techniques Using Debugger: gdb Profiling using Program Checkers Code Coverage Tools Performance Analyzers
  • 3. 3© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Debugging
  • 4. 4© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Ways of Debugging Basic: Printing Querying Kernel Windows: /proc, /sys Using Commands like ipcs Tracing: strace Debugger: gdb
  • 5. 5© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Debugger: gdb Text mode debugger Repetition of previous command Very powerful All kind of options: Breakpoint, Watch, ... Extensive Help GUI interfaces: ddd, ...
  • 6. 6© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. gdb: Debugging Strategies Oh no!!! Another tool to learn Worth learning a new tool Segmentation faults & Core dumps Execution intercepted by gdb Allows examining the state, backtrace, etc Debugging is Narrowing Down Reaching close & then stepping
  • 7. 7© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. 'gdb' Usage Compile with -g option gcc -g file.c -o file Run gdb (with desired options) gdb [options] ./file [core file] Pass command line arguments by setting args set args <cmd_line_args> Run the program by Typing c, or run <cmd_line_args> For debugging: break, watch, backtrace, … For help: help <command>
  • 8. 8© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. gdb: Examining Source Files list <line> Print 10 lines around <line> list [<filename>:]<function> Print 10 lines around beginning of <function> list <start>,<end> Print lines from <start> to <end> list Print 10 more lines
  • 9. 9© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. gdb: Other ways of Running step [ count ] – step into sub-routines next – run over sub-routines in a go finish – run till current function returns return – make selected stack frame return to its caller jump <address> – continue program at specified line or address
  • 10. 10© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. gdb: Breakpoints info break – Show list & status of breakpoints Setting breakpoints (returns its number) [t]break <function> [ if <expr> ] [t]break [<file>:]<line> Breakpoint Operations disable <break_no> enable <break_no> delete <break_no> commands <break_no> Execute gdb commands on reaching <break_no>
  • 11. 11© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. gdb: Examining the Stack Stack grows down Each call state is referred as a frame backtrace – Show stack frames frame <frame_no> – Select <frame_no> down – Select callee's frame up – Select caller's frame info args – Show args of current frame info locals – Show locals of current frame
  • 12. 12© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. gdb: Examining Data print[/xduotcf] <expr> Evaluate the valid C <expr> within current frame set variable <var> = <expr> Assign <expr> to <var> in the current scope Variables starting with $ are local to gdb display <expr> Print <expr> whenever program stops undisplay Cancels all previous display requests
  • 13. 13© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. gdb: Other Examinations Watchpoints / Catchpoints info watchpoints (Same as info break) watch <expr> - Break on Write watchpoint rwatch <expr> - Break on Read watchpoint awatch <expr> - Break on Both watchpoint Default is hardware watchpoint Registers: info registers Set-able options: info set
  • 14. 14© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. gdb: Shortcuts Just enough of command To make it unique Added with tab completion First letter only for break, delete, run, continue, step, next, print Repeat last by <Enter> Executing the same set of initial commands Put them in .gdbinit -x <gdb command file>
  • 15. 15© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. gdb: Miscellaneous Set editmode for gdb command line editmode [ emacs | vi | dumb ] Execute a shell command shell <cmd> Print command history history Set logging set logging <on | off> set logging file <log_file> (Default: gdb.txt)
  • 16. 16© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. gdb: Thread Debugging Automatic notification of new threads Switching among threads thread <thread_no> Auto switching on stop by breakpoint or signal Inquiry on existing threads info threads Applying command to a list of threads thread apply <thread_no> | all <cmd> Thread specific breakpoints Example: break <line> thread <thread_no>
  • 17. 17© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. gdb: Multi-Process Debugging gdb version >= 7.1 Multiple processes from same session Before that Run different programs with different gdb If parent-child program Run the parent using gdb Attach another gdb with running child pid
  • 18. 18© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Let's Debug Debug debugging_cprog.c find_the_bug.c Thread Debugging multi_threads.c
  • 19. 19© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. User Process Memory Debugging ElectricFence → DUMA MEMWATCH All these tools replaces the usual memory allocation functions like malloc, free, … by the ones to keep track of the same
  • 20. 20© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Profiling
  • 21. 21© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. W's of Profiling Analyzing & Understanding Programs Many varieties Coding Style Checker Logic Analysis Memory Analysis Execution Time Profiling Run Time Error Capture Execution Flow Analysis
  • 22. 22© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Profiling Categories Program Check Static (splint) Dynamic (memwatch, ElectricFence → DUMA) Code Coverage (Dynamic) Execution Flow using test vectors (gcov) Performance Analysis (Dynamic) Execution Time using test vectors (gprof) All in One: valgrind
  • 23. 23© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Static Program Checkers Compiler itself Really fast But too naive Other Extreme: Formal Verification Tools Extensive But needs huge resources Preference: In between solutions Example: splint
  • 24. 24© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. 'splint' detects Memory related Problems Dereferencing a possibly null pointer, Using possibly undefined storage Returning storage that is not properly defined Dangling references, Memory leaks, Buffer overflow, ... Dangerous Coding Likely infinite loops, fall-through cases or incomplete switches Suspicious statements, Dangerous aliasing Dangerous macro implementations or invocations Type mismatches with greater precision and flexibility, ... Specific Violations of Customized naming conventions Information hiding Modifications & Usage of global variable as per specified interfaces ...
  • 25. 25© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. 'splint' Usage Run splint (with desired options) splint [options] file[.c] Prints out all the messages about the file On standard output Errors on standard error (using -usestderr) Some interesting options -weak for lesser messages -I <incl_dirs> Try 'splint splint_cprog'
  • 26. 26© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Dynamic Program Checkers Memory Debugging mtrace (export MALLOC_TRACE=outfile.txt) memwatch ElectricFence → DUMA ... Replaces the memory allocation functions Like malloc, free, ... By the ones to keep track of the same
  • 27. 27© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Code Coverage Dynamic Execution Flow Analysis Done by actually running the Program Usually done with sets of test vectors Providing the Test Code Coverage Coverage of: Line of Code, Branches, Blocks, ... Typically provides Entity executed or not executed % or times of execution of various entities Tool: gcov Could provide performance info when used with gprof
  • 28. 28© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. 'gcov' Usage Compile with -fprofile-arcs -ftest-coverage options gcc -fprofile-arcs -ftest-coverage file.c -o file Execute the program with the test vectors ./file [ <cmd_line_args> ] Generates .gcda (Data) & .gcno (Graph) files Run gcov (with desired options) gcov [options] file.c Interesting options: --all-blocks --branch-probabilities Generates coverage output in .gcov file Try with gcov_cprog.c
  • 29. 29© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Performance Analysis Dynamic Execution Time Analysis Done by actually running the Program Usually done with sets of test vectors Providing the Test Performance Analysis Typically provides info on Functions Time Spent, Times Called Call Graph Profile Data Performance Bottlenecks Tool: gprof
  • 30. 30© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. 'gprof' Usage Compile with -pg option gcc -pg file.c -o file Run the program ./file [ <cmd_line_args> ] Generates gmon.out file Run gprof (with desired options) gprof [options] ./file [gmon.out] Dumps profiling info on stdout Try with gprof_cprog.c
  • 31. 31© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Interesting 'gprof' Options -b # Brief output -p # Flat Profile -q # Call Graph Analysis -A # Print with Annotated source code -x # Annotate all lines -l # Line-by-line profiling -s # Sum -z # Display unused functions -r, -R <mapfile> # Reordering suggestions
  • 32. 32© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Tool Suite: valgrind Provides a number of debugging & profiling tools Most popular being Memcheck Best behaviour without optimization Other possibly useful tools Cachegrind: Profiler for cache (miss) and branch (misprediction) events Callgrind: Profiler to show cost relationships across function calls, optionally with cache simulation Massif: Space profiler to explore in detail which parts of your program allocate memory Helgrind: Debugging tool for threaded programs Looks for various kinds of synchronisation errors in code That uses the POSIX pthreads API GUI frontend: valkyrie
  • 33. 33© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. valgrind: Memcheck detects Touching “shouldn’t” memories Overrunning heap block boundaries Reading/Writing freed/unallocated memory Memory leaks Not freeing heap blocks Incorrect freeing of memory Double-freeing heap blocks Using values before initialization
  • 34. 34© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. 'valgrind' Usage Compile with -g option gcc -g file.c -o file Run using valgrind & desired options valgrind [options] ./file [ <cmd_line_args> ] By default, runs Memcheck Profiles out the memory usage of the program For using other tools of valgrind, add --tool=<toolname> Try with valgrind_cprog.c
  • 35. 35© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. What all have we learnt? Debugging Various Techniques Using Debugger: gdb Profiling using Program Checkers splint, mtrace, memwatch, ... Code Coverage Tools gcov Performance Analyzers gprof, valgrind, ...
  • 36. 36© 2010-15 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Any Queries?