SlideShare une entreprise Scribd logo
1  sur  30
Télécharger pour lire hors ligne
Preventive Debugging

Poul-Henning Kamp
phk@FreeBSD.org
phk@Varnish.org
@bsdphk
1981
Debugging n.
Removing a BUG, either by tinkering with the
program or by amending the program specification so that the side effect of the bug is
published as a desirable feature. See also:
KLUDGE; ONE-LINE PATCH; STEPWISE REFINEMENT.
- Stan Kelley-Bootle
The Devil's D.P. Dictionary
Varnish:

A debugging nightmare

* 40.000 threads
* 1 TB common datastructures
* 1.000.000 requests per second
* 30 Gbit/s traffic
1949
As soon as we started programming, we found to
our surprise that it wasn't as easy to get
programs right as we had thought. Debugging
had to be discovered. I can remember the exact
instant when I realized that a large part of my
life from then on was going to be spent in
finding mistakes in my own programs.
- Maurice Wilkes
1974
Debugging is twice as hard as writing the code
in the first place. Therefore, if you write the
code as cleverly as possible, you are, by
definition, not smart enough to debug it.
- Brian W. Kernighan and P. J. Plauger
The Elements of Programming Style
The crucial debugging insight:
Q: Why are you debugging to begin with ?
A: Because you are not a perfect programmer
Todays task:

Optimize this:

void
debug(input)
{
do {
idea = think(input);
if (idea != NO_IDEA)
patch(idea);
input += test();
} while (unhappy(input));
}
”Option” doesn't mean its optional
If you don't use -Wall -Werror by default,
your code sucks by default.
Also consider:
-Wstrict-prototypes
-Wpointer-arith
-Wcast-qual
-Wswitch
-Wcast-align
-Wchar-subscripts
-Wnested-externs
-Wformat
-Wno-missing-field-initializers

-Wmissing-prototypes
-Wreturn-type
-Wwrite-strings
-Wshadow
-Wunused-parameter
-Winline
-Wredundant-decls
-Wextra
-Wno-sign-compare
Get a second, third & fourth opinion
* Use multiple compilers (LLVM vs. GCC)
* lint(1)
* FlexeLint ($1k)
* Coverity
* LLVM's static analysis tools
* Different CPU/endianess/word-size
Random FlexeLint example:
if (!(dfu_root->flags |= DFU_IFF_DFU))
main.c 483 Info 820: Boolean test of a parenthesized assignment
main.c 483 Info 774: Boolean within 'if' always evaluates to False
[Reference: file main.c: line 483]
main.c 483 Info 831: Reference cited in prior message
1979
The most effective debugging tool is still careful
thought, coupled with judiciously placed print
statements.
- Brian W. Kernighan
Unix for Beginners
2013
It's even easier to let the program just tell you
where the bugs are.
- Poul-Henning Kamp
Proactively eliminate doubt
#include <assert.h>
if (*q != '0' && r == e) {
if (b != vep->tag) {
l = e - b;
assert(l < sizeof vep->tag);
memmove(vep->tag, b, l);
vep->tag_i = l;
}
return (NULL);
}
Performance price List
●
●
●
●
●
●
●
●

char *p += 5;
strlen(p);
memcpy(p, q, l);
Locking
System Call
Context Switch
Disk Access
Filesystem

10-9s

CPU

Memory

Protection

10-1s

Mechanical
What does assert() actually do ?
#define assert(e) ((e) ? (void)0 : __assert( 
__func__, __FILE__, __LINE__, #e))
void
__assert(const char *func, const char *file, int line,
const char *failedexpr)
{

}

(void)fprintf(stderr, "Assertion failed: ”
”(%s), function %s, file %s, line %d.n",
failedexpr, func, file, line);
abort();
/* NOTREACHED */
Make your own asserts
#define AZ(foo)
do {assert((foo) ==
#define AN(foo)
do {assert((foo) !=
#define XXXAZ(foo) do {xxxassert((foo)
#define XXXAN(foo) do {xxxassert((foo)
#define WRONG(expl) [...]
#define INCOMPLETE(expl) [...]
#define Lck_AssertHeld() [...]
void WS_Assert(...);
void MPL_Assert_Sane(...);
void VTCP_Assert(...);
...

0);} while (0)
0);} while (0)
== 0);} while (0)
!= 0);} while (0)
If it can't happen, assert that
AZ(pipe(vwe->pipes));
AZ(shutdown(sock, SHUT_WR));
AZ(close(fd));
AZ(fstatvfs(fd, &fsst));
AZ(pthread_mutex_lock(&vsm_mtx));
...
XXXAZ(unlink(vp->fname));
XXXAZ(setgid(mgt_param.gid));
...
sto = calloc(sizeof *sto, 1);
XXXAN(sto);

...
Assert the locking situation
static void
ban_reload(const uint8_t *ban, unsigned len)
{
struct ban *b, *b2;
int duplicate = 0;
double t0, t1, t2 = 9e99;
ASSERT_CLI();
Lck_AssertHeld(&ban_mtx);
Be constructively paranoid
static enum req_fsm_nxt
cnt_deliver(struct worker *wrk, struct req *req)
{
char time_str[30];

CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CHECK_OBJ_NOTNULL(req, REQ_MAGIC);
CHECK_OBJ_NOTNULL(req->obj, OBJECT_MAGIC);
CHECK_OBJ_NOTNULL(req->obj->objcore, OBJCORE_MAGIC);
CHECK_OBJ_NOTNULL(req->obj->objcore->objhead, OBJHEAD_MAG
CHECK_OBJ_NOTNULL(req->vcl, VCL_CONF_MAGIC);
assert(WRW_IsReleased(wrk));
assert(req->obj->objcore->refcnt > 0);
(Un)trusted types
struct http {
unsigned
#define HTTP_MAGIC

magic;
0x6428b5c9

struct http_conn {
unsigned
#define HTTP_CONN_MAGIC

magic;
0x3e19edd1

struct wrk_accept {
unsigned
#define WRK_ACCEPT_MAGIC

magic;
0x8c4b4d59

struct objcore {
unsigned
#define OBJCORE_MAGIC

magic;
0x4d301302
Miniobj.h
#define ALLOC_OBJ(to, type_magic)
do {
(to) = calloc(sizeof *(to), 1);
if ((to) != NULL)
(to)->magic = (type_magic);
} while (0)
#define FREE_OBJ(to)
do {
(to)->magic = (0);
free(to);
} while (0)
#define CHECK_OBJ_NOTNULL(ptr, type_magic)
do {
assert((ptr) != NULL);
assert((ptr)->magic == type_magic);
} while (0)
A more helpful assert() handler

Panic from VCL:
PANIC: Had Panic header: fetch
thread = (cache-worker)
ident = FreeBSD,10.0-ALPHA4,amd64,-smalloc,-smalloc,-hcritbi
Backtrace:
0x44afeb: PAN_Init+3fb
0x806e05ef0: _end+80673e5b8
0x806c0201d: _end+80653a6e5
0x45f458: VCL_recv_method+7e8
0x4608f5: VCL_backend_response_method+1b5
0x42d3c2: VBF_Fetch+1e32
0x42c01b: VBF_Fetch+a8b
0x44ddd0: Pool_Work_Thread+500
0x474798: WRK_thread+1d8
0x4745ef: WRK_thread+2f
... even more helpful assert() handler
busyobj = 0x803d3a020 {
ws = 0x803d3a098 {
id = "bo",
{s,f,r,e} = {0x803d3bf98,+128,0x0,+57480},
},
do_stream
bodystatus = 4 (length),
},
http[bereq] = {
ws = 0x803d3a098[bo]
"GET",
"/foo",
"HTTP/1.1",
"X-Forwarded-For: 127.0.0.1",
"Accept-Encoding: gzip",
"X-Varnish: 1004",
"Host: 127.0.0.1",
},
http[beresp] = {
ws = 0x803d3a098[bo]
"HTTP/1.1",
"200",
"Ok",
"Panic: fetch",
"Content-Length: 7",
},
ws = 0x803d3a218 {
id = "(null)",
{s,f,r,e} = {0x0,0x0,0x0,0x0},
},
}
How ?
Use pthread_setspecific(3) to tie state to thread
In your __assert() function:
Use pthread_getspecific(3) to get that state
See also backtrace(3) API (OS/Compiler dependent.)
Test that your code works
Automate running of your test-cases
I mean, you do have test-cases ?

right ?

Right ?!
Varnish testing
Varnishtest(1) tool (5000 LOC)
Interprets ”VTC” test-language:
varnishtest "Does anything get through at all ?"
server s1 {
rxreq
txresp -body "012345n"
} -start
varnish v1 -vcl+backend {} -start
client c1 {
txreq -url "/"
rxresp
expect resp.status == 200
} -run
varnish v1 -expect n_object == 1
varnish v1 -expect sess_conn == 1
Varnish testing
336 VTC testcases in 11 categories
Important category:

Regression tests for bugs

”make check” runs test-cases (~ 10 minutes)
Jenkins tinderbox builds/tests ~10 platforms
gcov(1) used to monitor test-coverage. (89%!)
Preventive Debugging Summary
* Code defensively
* Use tools to improve your code & coding
* Assert() that you know what's going on
* Fail ASAP.
* Dump useful info while you can
* Know that your code works & can be executed
Does that work ?
Yes!
Varnish delivers a LOT of web-pages
We get approx 1 crash report every 2-3 weeks
We almost never need gdb(1)
1946
Intet tab bør ramme os, som kan undgås
ved rettidig omhu.
- Skibsreder A.P. Møller

Contenu connexe

Tendances

Vm ware fuzzing - defcon russia 20
Vm ware fuzzing  - defcon russia 20Vm ware fuzzing  - defcon russia 20
Vm ware fuzzing - defcon russia 20DefconRussia
 
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RIThe Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RIEleanor McHugh
 
Практический опыт профайлинга и оптимизации производительности Ruby-приложений
Практический опыт профайлинга и оптимизации производительности Ruby-приложенийПрактический опыт профайлинга и оптимизации производительности Ruby-приложений
Практический опыт профайлинга и оптимизации производительности Ruby-приложенийOlga Lavrentieva
 
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary dataKernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary dataAnne Nicolas
 
Bridge TensorFlow to run on Intel nGraph backends (v0.5)
Bridge TensorFlow to run on Intel nGraph backends (v0.5)Bridge TensorFlow to run on Intel nGraph backends (v0.5)
Bridge TensorFlow to run on Intel nGraph backends (v0.5)Mr. Vengineer
 
Introduction to Debuggers
Introduction to DebuggersIntroduction to Debuggers
Introduction to DebuggersSaumil Shah
 
Ownership System in Rust
Ownership System in RustOwnership System in Rust
Ownership System in RustChih-Hsuan Kuo
 
Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Chih-Hsuan Kuo
 
Specializing the Data Path - Hooking into the Linux Network Stack
Specializing the Data Path - Hooking into the Linux Network StackSpecializing the Data Path - Hooking into the Linux Network Stack
Specializing the Data Path - Hooking into the Linux Network StackKernel TLV
 
Performance tweaks and tools for Linux (Joe Damato)
Performance tweaks and tools for Linux (Joe Damato)Performance tweaks and tools for Linux (Joe Damato)
Performance tweaks and tools for Linux (Joe Damato)Ontico
 
Go concurrency
Go concurrencyGo concurrency
Go concurrencysiuyin
 
Load-time Hacking using LD_PRELOAD
Load-time Hacking using LD_PRELOADLoad-time Hacking using LD_PRELOAD
Load-time Hacking using LD_PRELOADDharmalingam Ganesan
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programmingRodolfo Finochietti
 

Tendances (20)

Vm ware fuzzing - defcon russia 20
Vm ware fuzzing  - defcon russia 20Vm ware fuzzing  - defcon russia 20
Vm ware fuzzing - defcon russia 20
 
Rust
RustRust
Rust
 
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RIThe Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
 
Практический опыт профайлинга и оптимизации производительности Ruby-приложений
Практический опыт профайлинга и оптимизации производительности Ruby-приложенийПрактический опыт профайлинга и оптимизации производительности Ruby-приложений
Практический опыт профайлинга и оптимизации производительности Ruby-приложений
 
CompilersAndLibraries
CompilersAndLibrariesCompilersAndLibraries
CompilersAndLibraries
 
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary dataKernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
 
Bridge TensorFlow to run on Intel nGraph backends (v0.5)
Bridge TensorFlow to run on Intel nGraph backends (v0.5)Bridge TensorFlow to run on Intel nGraph backends (v0.5)
Bridge TensorFlow to run on Intel nGraph backends (v0.5)
 
Introduction to Debuggers
Introduction to DebuggersIntroduction to Debuggers
Introduction to Debuggers
 
Concurrency with Go
Concurrency with GoConcurrency with Go
Concurrency with Go
 
Ownership System in Rust
Ownership System in RustOwnership System in Rust
Ownership System in Rust
 
Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36
 
Specializing the Data Path - Hooking into the Linux Network Stack
Specializing the Data Path - Hooking into the Linux Network StackSpecializing the Data Path - Hooking into the Linux Network Stack
Specializing the Data Path - Hooking into the Linux Network Stack
 
tit
tittit
tit
 
asyncio internals
asyncio internalsasyncio internals
asyncio internals
 
skipfish
skipfishskipfish
skipfish
 
Performance tweaks and tools for Linux (Joe Damato)
Performance tweaks and tools for Linux (Joe Damato)Performance tweaks and tools for Linux (Joe Damato)
Performance tweaks and tools for Linux (Joe Damato)
 
Go concurrency
Go concurrencyGo concurrency
Go concurrency
 
Load-time Hacking using LD_PRELOAD
Load-time Hacking using LD_PRELOADLoad-time Hacking using LD_PRELOAD
Load-time Hacking using LD_PRELOAD
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programming
 
Python Async IO Horizon
Python Async IO HorizonPython Async IO Horizon
Python Async IO Horizon
 

Similaire à Debugging 2013- Poul henning-kamp

NYU hacknight, april 6, 2016
NYU hacknight, april 6, 2016NYU hacknight, april 6, 2016
NYU hacknight, april 6, 2016Mikhail Sosonkin
 
eBPF Tooling and Debugging Infrastructure
eBPF Tooling and Debugging InfrastructureeBPF Tooling and Debugging Infrastructure
eBPF Tooling and Debugging InfrastructureNetronome
 
Davide Berardi - Linux hardening and security measures against Memory corruption
Davide Berardi - Linux hardening and security measures against Memory corruptionDavide Berardi - Linux hardening and security measures against Memory corruption
Davide Berardi - Linux hardening and security measures against Memory corruptionlinuxlab_conf
 
PVS-Studio delved into the FreeBSD kernel
PVS-Studio delved into the FreeBSD kernelPVS-Studio delved into the FreeBSD kernel
PVS-Studio delved into the FreeBSD kernelPVS-Studio
 
Hardwear.io 2018 BLE Security Essentials workshop
Hardwear.io 2018 BLE Security Essentials workshopHardwear.io 2018 BLE Security Essentials workshop
Hardwear.io 2018 BLE Security Essentials workshopSlawomir Jasek
 
Power of linked list
Power of linked listPower of linked list
Power of linked listPeter Hlavaty
 
PVS-Studio, a solution for resource intensive applications development
PVS-Studio, a solution for resource intensive applications developmentPVS-Studio, a solution for resource intensive applications development
PVS-Studio, a solution for resource intensive applications developmentOOO "Program Verification Systems"
 
An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...
An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...
An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...David Beazley (Dabeaz LLC)
 
Writing simple buffer_overflow_exploits
Writing simple buffer_overflow_exploitsWriting simple buffer_overflow_exploits
Writing simple buffer_overflow_exploitsD4rk357 a
 
Linux Kernel, tested by the Linux-version of PVS-Studio
Linux Kernel, tested by the Linux-version of PVS-StudioLinux Kernel, tested by the Linux-version of PVS-Studio
Linux Kernel, tested by the Linux-version of PVS-StudioPVS-Studio
 
NativeBoost
NativeBoostNativeBoost
NativeBoostESUG
 
smash the stack , Menna Essa
smash the stack , Menna Essasmash the stack , Menna Essa
smash the stack , Menna EssaCATReloaded
 
Analyzing the Blender project with PVS-Studio
Analyzing the Blender project with PVS-StudioAnalyzing the Blender project with PVS-Studio
Analyzing the Blender project with PVS-StudioPVS-Studio
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionAndrey Karpov
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionPVS-Studio
 
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)Gavin Guo
 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects 100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects Andrey Karpov
 
WAD : A Module for Converting Fatal Extension Errors into Python Exceptions
WAD : A Module for Converting Fatal Extension Errors into Python ExceptionsWAD : A Module for Converting Fatal Extension Errors into Python Exceptions
WAD : A Module for Converting Fatal Extension Errors into Python ExceptionsDavid Beazley (Dabeaz LLC)
 
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Vincenzo Iozzo
 
Profiling your Applications using the Linux Perf Tools
Profiling your Applications using the Linux Perf ToolsProfiling your Applications using the Linux Perf Tools
Profiling your Applications using the Linux Perf ToolsemBO_Conference
 

Similaire à Debugging 2013- Poul henning-kamp (20)

NYU hacknight, april 6, 2016
NYU hacknight, april 6, 2016NYU hacknight, april 6, 2016
NYU hacknight, april 6, 2016
 
eBPF Tooling and Debugging Infrastructure
eBPF Tooling and Debugging InfrastructureeBPF Tooling and Debugging Infrastructure
eBPF Tooling and Debugging Infrastructure
 
Davide Berardi - Linux hardening and security measures against Memory corruption
Davide Berardi - Linux hardening and security measures against Memory corruptionDavide Berardi - Linux hardening and security measures against Memory corruption
Davide Berardi - Linux hardening and security measures against Memory corruption
 
PVS-Studio delved into the FreeBSD kernel
PVS-Studio delved into the FreeBSD kernelPVS-Studio delved into the FreeBSD kernel
PVS-Studio delved into the FreeBSD kernel
 
Hardwear.io 2018 BLE Security Essentials workshop
Hardwear.io 2018 BLE Security Essentials workshopHardwear.io 2018 BLE Security Essentials workshop
Hardwear.io 2018 BLE Security Essentials workshop
 
Power of linked list
Power of linked listPower of linked list
Power of linked list
 
PVS-Studio, a solution for resource intensive applications development
PVS-Studio, a solution for resource intensive applications developmentPVS-Studio, a solution for resource intensive applications development
PVS-Studio, a solution for resource intensive applications development
 
An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...
An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...
An Embedded Error Recovery and Debugging Mechanism for Scripting Language Ext...
 
Writing simple buffer_overflow_exploits
Writing simple buffer_overflow_exploitsWriting simple buffer_overflow_exploits
Writing simple buffer_overflow_exploits
 
Linux Kernel, tested by the Linux-version of PVS-Studio
Linux Kernel, tested by the Linux-version of PVS-StudioLinux Kernel, tested by the Linux-version of PVS-Studio
Linux Kernel, tested by the Linux-version of PVS-Studio
 
NativeBoost
NativeBoostNativeBoost
NativeBoost
 
smash the stack , Menna Essa
smash the stack , Menna Essasmash the stack , Menna Essa
smash the stack , Menna Essa
 
Analyzing the Blender project with PVS-Studio
Analyzing the Blender project with PVS-StudioAnalyzing the Blender project with PVS-Studio
Analyzing the Blender project with PVS-Studio
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correction
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correction
 
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)
 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects 100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects
 
WAD : A Module for Converting Fatal Extension Errors into Python Exceptions
WAD : A Module for Converting Fatal Extension Errors into Python ExceptionsWAD : A Module for Converting Fatal Extension Errors into Python Exceptions
WAD : A Module for Converting Fatal Extension Errors into Python Exceptions
 
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
 
Profiling your Applications using the Linux Perf Tools
Profiling your Applications using the Linux Perf ToolsProfiling your Applications using the Linux Perf Tools
Profiling your Applications using the Linux Perf Tools
 

Dernier

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 

Dernier (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 

Debugging 2013- Poul henning-kamp

  • 2. 1981 Debugging n. Removing a BUG, either by tinkering with the program or by amending the program specification so that the side effect of the bug is published as a desirable feature. See also: KLUDGE; ONE-LINE PATCH; STEPWISE REFINEMENT. - Stan Kelley-Bootle The Devil's D.P. Dictionary
  • 3. Varnish: A debugging nightmare * 40.000 threads * 1 TB common datastructures * 1.000.000 requests per second * 30 Gbit/s traffic
  • 4. 1949 As soon as we started programming, we found to our surprise that it wasn't as easy to get programs right as we had thought. Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs. - Maurice Wilkes
  • 5. 1974 Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. - Brian W. Kernighan and P. J. Plauger The Elements of Programming Style
  • 6. The crucial debugging insight: Q: Why are you debugging to begin with ? A: Because you are not a perfect programmer
  • 7. Todays task: Optimize this: void debug(input) { do { idea = think(input); if (idea != NO_IDEA) patch(idea); input += test(); } while (unhappy(input)); }
  • 8. ”Option” doesn't mean its optional If you don't use -Wall -Werror by default, your code sucks by default. Also consider: -Wstrict-prototypes -Wpointer-arith -Wcast-qual -Wswitch -Wcast-align -Wchar-subscripts -Wnested-externs -Wformat -Wno-missing-field-initializers -Wmissing-prototypes -Wreturn-type -Wwrite-strings -Wshadow -Wunused-parameter -Winline -Wredundant-decls -Wextra -Wno-sign-compare
  • 9. Get a second, third & fourth opinion * Use multiple compilers (LLVM vs. GCC) * lint(1) * FlexeLint ($1k) * Coverity * LLVM's static analysis tools * Different CPU/endianess/word-size
  • 10. Random FlexeLint example: if (!(dfu_root->flags |= DFU_IFF_DFU)) main.c 483 Info 820: Boolean test of a parenthesized assignment main.c 483 Info 774: Boolean within 'if' always evaluates to False [Reference: file main.c: line 483] main.c 483 Info 831: Reference cited in prior message
  • 11. 1979 The most effective debugging tool is still careful thought, coupled with judiciously placed print statements. - Brian W. Kernighan Unix for Beginners
  • 12. 2013 It's even easier to let the program just tell you where the bugs are. - Poul-Henning Kamp
  • 13. Proactively eliminate doubt #include <assert.h> if (*q != '0' && r == e) { if (b != vep->tag) { l = e - b; assert(l < sizeof vep->tag); memmove(vep->tag, b, l); vep->tag_i = l; } return (NULL); }
  • 14. Performance price List ● ● ● ● ● ● ● ● char *p += 5; strlen(p); memcpy(p, q, l); Locking System Call Context Switch Disk Access Filesystem 10-9s CPU Memory Protection 10-1s Mechanical
  • 15. What does assert() actually do ? #define assert(e) ((e) ? (void)0 : __assert( __func__, __FILE__, __LINE__, #e)) void __assert(const char *func, const char *file, int line, const char *failedexpr) { } (void)fprintf(stderr, "Assertion failed: ” ”(%s), function %s, file %s, line %d.n", failedexpr, func, file, line); abort(); /* NOTREACHED */
  • 16. Make your own asserts #define AZ(foo) do {assert((foo) == #define AN(foo) do {assert((foo) != #define XXXAZ(foo) do {xxxassert((foo) #define XXXAN(foo) do {xxxassert((foo) #define WRONG(expl) [...] #define INCOMPLETE(expl) [...] #define Lck_AssertHeld() [...] void WS_Assert(...); void MPL_Assert_Sane(...); void VTCP_Assert(...); ... 0);} while (0) 0);} while (0) == 0);} while (0) != 0);} while (0)
  • 17. If it can't happen, assert that AZ(pipe(vwe->pipes)); AZ(shutdown(sock, SHUT_WR)); AZ(close(fd)); AZ(fstatvfs(fd, &fsst)); AZ(pthread_mutex_lock(&vsm_mtx)); ... XXXAZ(unlink(vp->fname)); XXXAZ(setgid(mgt_param.gid)); ... sto = calloc(sizeof *sto, 1); XXXAN(sto); ...
  • 18. Assert the locking situation static void ban_reload(const uint8_t *ban, unsigned len) { struct ban *b, *b2; int duplicate = 0; double t0, t1, t2 = 9e99; ASSERT_CLI(); Lck_AssertHeld(&ban_mtx);
  • 19. Be constructively paranoid static enum req_fsm_nxt cnt_deliver(struct worker *wrk, struct req *req) { char time_str[30]; CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); CHECK_OBJ_NOTNULL(req, REQ_MAGIC); CHECK_OBJ_NOTNULL(req->obj, OBJECT_MAGIC); CHECK_OBJ_NOTNULL(req->obj->objcore, OBJCORE_MAGIC); CHECK_OBJ_NOTNULL(req->obj->objcore->objhead, OBJHEAD_MAG CHECK_OBJ_NOTNULL(req->vcl, VCL_CONF_MAGIC); assert(WRW_IsReleased(wrk)); assert(req->obj->objcore->refcnt > 0);
  • 20. (Un)trusted types struct http { unsigned #define HTTP_MAGIC magic; 0x6428b5c9 struct http_conn { unsigned #define HTTP_CONN_MAGIC magic; 0x3e19edd1 struct wrk_accept { unsigned #define WRK_ACCEPT_MAGIC magic; 0x8c4b4d59 struct objcore { unsigned #define OBJCORE_MAGIC magic; 0x4d301302
  • 21. Miniobj.h #define ALLOC_OBJ(to, type_magic) do { (to) = calloc(sizeof *(to), 1); if ((to) != NULL) (to)->magic = (type_magic); } while (0) #define FREE_OBJ(to) do { (to)->magic = (0); free(to); } while (0) #define CHECK_OBJ_NOTNULL(ptr, type_magic) do { assert((ptr) != NULL); assert((ptr)->magic == type_magic); } while (0)
  • 22. A more helpful assert() handler Panic from VCL: PANIC: Had Panic header: fetch thread = (cache-worker) ident = FreeBSD,10.0-ALPHA4,amd64,-smalloc,-smalloc,-hcritbi Backtrace: 0x44afeb: PAN_Init+3fb 0x806e05ef0: _end+80673e5b8 0x806c0201d: _end+80653a6e5 0x45f458: VCL_recv_method+7e8 0x4608f5: VCL_backend_response_method+1b5 0x42d3c2: VBF_Fetch+1e32 0x42c01b: VBF_Fetch+a8b 0x44ddd0: Pool_Work_Thread+500 0x474798: WRK_thread+1d8 0x4745ef: WRK_thread+2f
  • 23. ... even more helpful assert() handler busyobj = 0x803d3a020 { ws = 0x803d3a098 { id = "bo", {s,f,r,e} = {0x803d3bf98,+128,0x0,+57480}, }, do_stream bodystatus = 4 (length), }, http[bereq] = { ws = 0x803d3a098[bo] "GET", "/foo", "HTTP/1.1", "X-Forwarded-For: 127.0.0.1", "Accept-Encoding: gzip", "X-Varnish: 1004", "Host: 127.0.0.1", }, http[beresp] = { ws = 0x803d3a098[bo] "HTTP/1.1", "200", "Ok", "Panic: fetch", "Content-Length: 7", }, ws = 0x803d3a218 { id = "(null)", {s,f,r,e} = {0x0,0x0,0x0,0x0}, }, }
  • 24. How ? Use pthread_setspecific(3) to tie state to thread In your __assert() function: Use pthread_getspecific(3) to get that state See also backtrace(3) API (OS/Compiler dependent.)
  • 25. Test that your code works Automate running of your test-cases I mean, you do have test-cases ? right ? Right ?!
  • 26. Varnish testing Varnishtest(1) tool (5000 LOC) Interprets ”VTC” test-language: varnishtest "Does anything get through at all ?" server s1 { rxreq txresp -body "012345n" } -start varnish v1 -vcl+backend {} -start client c1 { txreq -url "/" rxresp expect resp.status == 200 } -run varnish v1 -expect n_object == 1 varnish v1 -expect sess_conn == 1
  • 27. Varnish testing 336 VTC testcases in 11 categories Important category: Regression tests for bugs ”make check” runs test-cases (~ 10 minutes) Jenkins tinderbox builds/tests ~10 platforms gcov(1) used to monitor test-coverage. (89%!)
  • 28. Preventive Debugging Summary * Code defensively * Use tools to improve your code & coding * Assert() that you know what's going on * Fail ASAP. * Dump useful info while you can * Know that your code works & can be executed
  • 29. Does that work ? Yes! Varnish delivers a LOT of web-pages We get approx 1 crash report every 2-3 weeks We almost never need gdb(1)
  • 30. 1946 Intet tab bør ramme os, som kan undgås ved rettidig omhu. - Skibsreder A.P. Møller