Repository navigation
Expand file tree
/
Copy pathdebugging.tex
More file actions
2534 lines (2220 loc) · 109 KB
/
Copy pathdebugging.tex
File metadata and controls
2534 lines (2220 loc) · 109 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% debugging/debugging.tex
\QuickQuizChapter{chp:Validation}{Validation}
%
\Epigraph{If it is not tested, it doesn't work.}{\emph{Unknown}}
I have had a few parallel programs work the first time, but that is only
because I have written a large number parallel programs over the past two
decades.
And I have had far more parallel programs that fooled me into thinking
that they were working correctly the first time than actually were working
the first time.
I have therefore had great need of validation for my parallel programs.
The basic trick behind parallel validation, as with other software
validation, is to realize that the computer knows what is wrong.
It is therefore your job to force it to tell you.
This chapter can therefore be thought of as a short course in
machine interrogation.\footnote{
But you can leave the thumbscrews and waterboards at home.
This chapter covers much more sophisticated and effective
methods, especially given that most computer
systems neither feel pain nor fear drowning.
At least as far as we know.}
A longer course may be found in many recent books on validation, as
well as at least one rather old but quite worthwhile
one~\cite{GlenfordJMyers1979}.
Validation is an extremely important topic that cuts across all forms
of software, and is therefore worth intensive study in its own right.
However, this book is primarily about concurrency, so this chapter
will necessarily do little more than scratch the surface of this
critically important topic.
Section~\ref{sec:debugging:Introduction}
introduces the philosophy of debugging.
Section~\ref{sec:debugging:Tracing}
discusses tracing,
Section~\ref{sec:debugging:Assertions}
discusses assertions, and
Section~\ref{sec:debugging:Static Analysis}
discusses static analysis.
Section~\ref{sec:debugging:Code Review}
describes some unconventional approaches to code review that can
be helpful when the fabled 10,000 eyes happen not to be looking at your code.
Section~\ref{sec:debugging:Probability and Heisenbugs}
overviews the use of probability for validating parallel software.
Because performance and scalability are first-class requirements
for parallel programming,
Section~\ref{sec:debugging:Performance Estimation} covers these
topics.
Finally,
Section~\ref{sec:debugging:Summary}
gives a fanciful summary and a short list of statistical traps to avoid.
But never forget that the two best debugging tools are a solid design
and a good night's sleep!
\section{Introduction}
\label{sec:debugging:Introduction}
%
\epigraph{The greatest mistake is to imagine that we never err.}
{\emph{Thomas Carlyle}}
Section~\ref{sec:debugging:Where Do Bugs Come From?}
discusses the sources of bugs, and
Section~\ref{sec:debugging:Required Mindset}
overviews the mindset required when validating software.
Section~\ref{sec:debugging:When Should Validation Start?}
discusses when you should start validation, and
Section~\ref{sec:debugging:The Open Source Way} describes the
surprisingly effective open-source regimen of code review and
community testing.
\subsection{Where Do Bugs Come From?}
\label{sec:debugging:Where Do Bugs Come From?}
Bugs come from developers.
The basic problem is that the human brain did not evolve with computer
software in mind.
Instead, the human brain evolved in concert with other human brains and
with animal brains.
Because of this history, the following three characteristics of computers
often come as a shock to human intuition:
\begin{enumerate}
\item Computers typically lack common sense, despite decades of research
sacrificed at the altar of artificial intelligence.
\item Computers generally fail to understand user intent, or more
formally, computers generally lack a theory of mind.
\item Computers usually cannot do anything useful with a fragmentary plan,
instead requiring that each and every detail of each and every
possible scenario be spelled out in full.
\end{enumerate}
The first two points should be uncontroversial, as they are illustrated
by any number of failed products, perhaps most famously Clippy and
Microsoft Bob.
By attempting to relate to users as people, these two products raised
common-sense and theory-of-mind expectations that they proved incapable
of meeting.
Perhaps the set of software assistants that have recently started appearing
on smartphones will fare better.
That said, the developers working on them by all accounts still develop
the old way: The assistants might well benefit end users, but not so
much their own developers.
This human love of fragmentary plans deserves more explanation,
especially given that it is a classic two-edged sword.
This love of fragmentary plans is apparently due to the assumption that
the person carrying out the plan will have (1)~common sense and (2)~a good
understanding of the intent behind the plan.
This latter assumption is especially likely to hold in the common case
where the person doing the planning and the person carrying out the plan
are one and the same: In this case, the plan will be revised almost
subconsciously as obstacles arise.
Therefore, the love of fragmentary plans has served human beings well,
in part because it is better to take random actions that have a high
probability of locating food than to starve to death while attempting
to plan the unplannable.
However, the past usefulness of fragmentary plans in everyday life is
no guarantee of their future usefulness in stored-program computers.
Furthermore, the need to follow fragmentary plans has had important effects
on the human psyche, due to the fact
that throughout much of human history, life was often difficult and dangerous.
It should come as no surprise that executing a fragmentary plan that has
a high probability of a violent encounter with sharp teeth and claws
requires almost insane levels of optimism---a level of optimism that actually
is present in most human beings.
These insane levels of optimism extend to self-assessments of programming
ability, as evidenced by the effectiveness of (and the controversy over)
interviewing techniques involving coding trivial
programs~\cite{RegBraithwaite2007FizzBuzz}.
In fact, the clinical term for a human being with less-than-insane
levels of optimism is ``clinically depressed.'' Such people usually have
extreme difficulty functioning in their daily lives, underscoring the
perhaps counter-intuitive importance of insane levels of optimism to a
normal, healthy life.
If you are not insanely optimistic, you are less likely to start a difficult
but worthwhile project.\footnote{
There are some famous exceptions to this rule of thumb.
One set of exceptions is people who take on difficult or risky
projects in order to make at least a temporary escape
from their depression.
Another set is people who have nothing to lose: the project is
literally a matter of life or death.}
\QuickQuiz{}
When in computing is the willingness to follow a fragmentary
plan critically important?
\QuickQuizAnswer{
There are any number of situations, but perhaps the most important
situation is when no one has ever created anything resembling
the program to be developed.
In this case, the only way to create a credible plan is to
implement the program, create the plan, and implement it a
second time.
But whoever implements the program for the first time has no
choice but to follow a fragmentary plan because any detailed
plan created in ignorance cannot survive first contact with
the real world.
And perhaps this is one reason why evolution has favored insanely
optimistic human beings who are happy to follow fragmentary plans!
} \QuickQuizEnd
An important special case is the project that, while valuable, is not
valuable enough to justify the time required to implement it.
This special case is quite common, and one early symptom is the
unwillingness of the decision-makers to invest enough to actually
implement the project.
A natural reaction is for the developers to produce an unrealistically
optimistic estimate in order to be permitted to start the project.
If the organization (be it open source or proprietary) is strong enough,
it might survive the resulting schedule slips and budget overruns,
so that the project might see the light of day.
However, if the organization is not strong enough and if the decision-makers
fail to cancel the project as soon as it becomes clear that the estimates
are garbage, then the project might well kill the organization.
This might result in another organization picking up the project and
either completing it, cancelling it, or being killed by it.
A given project might well succeed only after killing several
organizations.
One can only hope that the organization that eventually makes a success
of a serial-organization-killer project manages maintains a suitable
level of humility, lest it be killed by the next project.
Important though insane levels of optimism might be, they are a key source
of bugs (and perhaps failure of organizations).
The question is therefore ``How to maintain the optimism required to start
a large project while at the same time injecting enough reality to keep
the bugs down to a dull roar?''
The next section examines this conundrum.
\subsection{Required Mindset}
\label{sec:debugging:Required Mindset}
When carrying out any validation effort, you should keep the following
definitions in mind:
\begin{enumerate}
\item The only bug-free programs are trivial programs.
\item A reliable program has no known bugs.
\end{enumerate}
From these definitions, it logically follows that any reliable
non-trivial program contains at least one bug that you do not
know about.
Therefore, any validation effort undertaken on a non-trivial program
that fails to find any bugs is itself a failure.
A good validation is therefore an exercise in destruction.
This means that if you are the type of person who enjoys breaking things,
validation is just the right type of job for you.
\QuickQuiz{}
Suppose that you are writing a script that processes the
output of the \co{time} command, which looks as follows:
\begin{VerbatimU}
real 0m0.132s
user 0m0.040s
sys 0m0.008s
\end{VerbatimU}
The script is required to check its input for errors, and to
give appropriate diagnostics if fed erroneous \co{time} output.
What test inputs should you provide to this program to test it
for use with \co{time} output generated by single-threaded programs?
\QuickQuizAnswer{
\begin{enumerate}
\item Do you have a test case in which all the time is
consumed in user mode by a CPU-bound program?
\item Do you have a test case in which all the time is
consumed in system mode by a CPU-bound program?
\item Do you have a test case in which all three times
are zero?
\item Do you have a test case in which the ``user'' and ``sys''
times sum to more than the ``real'' time?
(This would of course be completely legitimate in
a multithreaded program.)
\item Do you have a set of tests cases in which one of the
times uses more than one second?
\item Do you have a set of tests cases in which one of the
times uses more than ten second?
\item Do you have a set of test cases in which one of the
times has non-zero minutes? (For example, ``15m36.342s''.)
\item Do you have a set of test cases in which one of the
times has a seconds value of greater than 60?
\item Do you have a set of test cases in which one of the
times overflows 32 bits of milliseconds? 64 bits of
milliseconds?
\item Do you have a set of test cases in which one of the
times is negative?
\item Do you have a set of test cases in which one of the
times has a positive minutes value but a negative
seconds value?
\item Do you have a set of test cases in which one of the
times omits the ``m'' or the ``s''?
\item Do you have a set of test cases in which one of the
times is non-numeric? (For example, ``Go Fish''.)
\item Do you have a set of test cases in which one of the
lines is omitted? (For example, where there is a
``real'' value and a ``sys'' value, but no ``user''
value.)
\item Do you have a set of test cases where one of the
lines is duplicated? Or duplicated, but with a
different time value for the duplicate?
\item Do you have a set of test cases where a given line
has more than one time value? (For example,
``real 0m0.132s 0m0.008s''.)
\item Do you have a set of test cases containing random
characters?
\item In all test cases involving invalid input, did you
generate all permutations?
\item For each test case, do you have an expected outcome
for that test?
\end{enumerate}
If you did not generate test data for a substantial number of
the above cases, you will need to cultivate a more destructive
attitude in order to have a chance of generating high-quality
tests.
Of course, one way to economize on destructiveness is to
generate the tests with the to-be-tested source code at hand,
which is called white-box testing (as opposed to black-box testing).
However, this is no panacea: You will find that it is all too
easy to find your thinking limited by what the program can handle,
thus failing to generate truly destructive inputs.
} \QuickQuizEnd
But perhaps you are a super-programmer whose code is always perfect
the first time every time.
If so, congratulations!
Feel free to skip this chapter, but
I do hope that you will forgive my skepticism.
You see, I have met far more people who claimed to be able
to write perfect code the first time than I have
people who were actually capable of carrying out this feat, which
is not too surprising given the previous discussion of optimism
and over-confidence.
And even if you really are a super-programmer, you just might
find yourself debugging lesser mortals' work.
One approach for the rest of us is to alternate between our normal
state of insane optimism
(Sure, I can program that!) and severe pessimism
(It seems to work, but I just know that there have to be more bugs hiding
in there somewhere!).
It helps if you enjoy breaking things.
If you don't, or if your joy in breaking things is limited to breaking
\emph{other} people's things, find someone who does love breaking your
code and get them to help you test it.
Another helpful frame of mind is to hate it when other people find bugs in
your code.
This hatred can help motivate you to torture your code beyond reason
in order to increase the probability that you find the bugs rather than
someone else.
One final frame of mind is to consider the possibility that someone's
life depends on your code being correct.
This can also motivate you to torture your code into revealing the
whereabouts of its bugs.
This wide variety of frames of mind opens the door to
the possibility of multiple people with different frames of
mind contributing to the project, with varying levels of optimism.
This can work well, if properly organized.
\begin{figure}[tb]
\centering
\resizebox{2in}{!}{\includegraphics{cartoons/TortureTux}}
\caption{Validation and the Geneva Convention}
\ContributedBy{Figure}{fig:debugging:Validation and the Geneva Convention}{Melissa Broussard}
\end{figure}
\begin{figure}[tb]
\centering
\resizebox{2in}{!}{\includegraphics{cartoons/TortureLaptop}}
\caption{Rationalizing Validation}
\ContributedBy{Figure}{fig:debugging:Rationalizing Validation}{Melissa Broussard}
\end{figure}
Some people might see vigorous validation as a form of torture, as
depicted in
Figure~\ref{fig:debugging:Validation and the Geneva Convention}.\footnote{
More cynical people might question whether these people are instead
merely afraid that validation will find bugs that they will then
be expected to fix.}
Such people might do well to remind themselves that, Tux cartoons aside,
they are really torturing an inanimate object, as shown in
Figure~\ref{fig:debugging:Rationalizing Validation}.
In addition, rest assured that those who fail to torture their code are
doomed to be tortured by it.
However, this leaves open the question of exactly when during the project
lifetime validation should start, a topic taken up by the next section.
\subsection{When Should Validation Start?}
\label{sec:debugging:When Should Validation Start?}
Validation should start at the same time that the project starts.
To see this, consider that tracking down a bug is much harder in a large
program than in a small one.
Therefore, to minimize the time and effort required to track down bugs,
you should test small units of code.
Although you won't find all the bugs this way, you will find a substantial
fraction, and it will be much easier to find and fix the ones you do find.
Testing at this level can also alert you to larger flaws in your overall
design, minimizing the time you waste writing code that is quite literally
broken by design.
But why wait until you have code before validating your design?\footnote{
The old saying ``First we must code, then we have incentive to
think'' notwithstanding.}
Hopefully reading Chapters~\ref{chp:Hardware and its Habits}
and~\ref{chp:Tools of the Trade} provided you with the information
required to avoid some regrettably common design flaws,
but discussing your design with a colleague or even simply writing it
down can help flush out additional flaws.
However, it is all too often the case that waiting to start validation
until you have a design is waiting too long.
Mightn't your natural level of optimism caused you to start the design
before you fully understood the requirements?
The answer to this question will almost always be ``yes''.
One good way to avoid flawed requirements is to get to know your users.
To really serve them well, you will have to live among them.
\QuickQuiz{}
You are asking me to do all this validation BS before
I even start coding???
That sounds like a great way to never get started!!!
\QuickQuizAnswer{
If it is your project, for example, a hobby, do what you like.
Any time you waste will be your own, and you have no one else
to answer to for it.
And there is a good chance that the time will not be completely
wasted.
For example, if you are embarking on a first-of-a-kind project,
the requirements are in some sense unknowable anyway.
In this case, the best approach might be to quickly prototype
a number of rough solutions, try them out, and see what works
best.
On the other hand, if you are being paid to produce a system that
is broadly similar to existing systems, you owe it to your users,
your employer, and your future self to validate early and often.
} \QuickQuizEnd
First-of-a-kind projects often use different methodologies such as
rapid prototyping or agile.
Here, the main goal of early prototypes are not to create correct
implementations, but rather to learn the project's requirements.
But this does not mean that you omit validation; it instead means that
you approach it differently.
One such approach takes a Darwinian view, with the validation suite
eliminating code that is not fit to solve the problem at hand.
From this viewpoint, a vigorous validation suite is essential to the
fitness of your software.
However, taking this approach to its logical conclusion is quite humbling,
as it requires us developers to admit that our carefully crafted changes
to the code base are, from a Darwinian standpoint, random mutations.
On the other hand, this conclusion is supported by long experience
indicating that seven percent of fixes introduce at least one
bug~\cite{RexBlack2012SQA}.
How vigorous should your validation suite be?
If the bugs it finds aren't threatening the very foundations of your
software design, then it is not yet vigorous enough.
After all, your design is just as prone to bugs as is your code, and
the earlier you find and fix the bugs in your design, the less time
you will waste coding those design bugs.
\QuickQuiz{}
Are you actually suggesting that it is possible to test
correctness into software???
Everyone knows that is impossible!!!
\QuickQuizAnswer{
Please note that the text used the word ``validation'' rather
than the word ``testing''.
The word ``validation'' includes formal methods as well as
testing, for more on which please see
Chapter~\ref{chp:Formal Verification}.
But as long as we are bringing up things that everyone should
know, let's remind ourselves that Darwinian evolution is
not about correctness, but rather about survival.
As is software.
My goal as a developer is not that my software be attractive
from a theoretical viewpoint, but rather that it survive
whatever its users throw at it.
Although the notion of correctness does have its uses, its
fundamental limitation is that the specification against which
correctness is judged will also have bugs.
This means nothing more nor less than that traditional correctness
proofs prove that the code in question contains the intended
set of bugs!
Alternative definitions of correctness instead focus on the
lack of problematic properties, for example, proving that the
software has no use-after-free bugs, no \co{NULL} pointer
dereferences, no array-out-of-bounds references, and so on.
Make no mistake, finding and eliminating such classes of bugs
can be highly useful.
But the fact remains that the lack of certain classes of bugs
does nothing to demonstrate fitness for any specific purpose.
Therefore, usage-driven validation remains critically important.
} \QuickQuizEnd
It is worth reiterating that this advice applies to first-of-a-kind
projects.
If you are instead doing a project in a well-explored area, you would
be quite foolish to refuse to learn from previous experience.
But you should still start validating right at the beginning of the
project, but hopefully guided by others' hard-won knowledge of both
requirements and pitfalls.
Now that we have established that you should start validation when you
start the project (if not earlier!), the following sections cover a
number of validation techniques and methods that have proven their worth.
\subsection{The Open Source Way}
\label{sec:debugging:The Open Source Way}
The open-source programming methodology has proven quite effective, and
includes a regimen of intense code review and testing.
I can personally attest to the effectiveness of the open-source community's
intense code review.
One of the first patches I prepared for the Linux kernel involved
a distributed filesystem where a user on one node writes to a given
file at a location that a user on another node has mapped into memory.
In this case, it is necessary to invalidate the affected pages from
the mapping in order to allow the filesystem to maintain coherence
during the write operation.
I coded up a first attempt at a patch, and, in keeping with the open-source
maxim ``post early, post often'', I posted the patch.
I then considered how I was going to test it.
But before I could even decide on an overall test strategy, I got a
reply to my posting pointing out a few bugs.
I fixed the bugs and reposted the patch, and returned to thinking
out my test strategy.
However, before I had a chance to write any test code, I received
a reply to my reposted patch, pointing out more bugs.
This process repeated itself many times, and I am not sure that I
ever got a chance to actually test the patch.
This experience brought home the truth of the open-source saying:
Given enough eyeballs, all bugs are shallow~\cite{EricSRaymond99b}.
However, when you post some code or a given patch, it is worth
asking a few questions:
\begin{enumerate}
\item How many of those eyeballs are actually going to look at your code?
\item How many will be experienced and clever enough to actually find
your bugs?
\item Exactly when are they going to look?
\end{enumerate}
I was lucky: There was someone out there who wanted the functionality
provided by my patch, who had long experience with distributed filesystems,
and who looked at my patch almost immediately.
If no one had looked at my patch, there would have been no review, and
therefore no finding of bugs.
If the people looking at my patch had lacked experience with distributed
filesystems, it is unlikely that they would have found all the bugs.
Had they waited months or even years to look, I likely would have forgotten
how the patch was supposed to work, making it much more difficult to
fix them.
However, we must not forget the second tenet of the open-source development,
namely intensive testing.
For example, a great many people test the Linux kernel.
Some test patches as they are submitted, perhaps even yours.
Others test the -next tree, which is helpful, but there is likely to be
several weeks or even months delay between the time that you write the
patch and the time that it appears in the -next tree, by which time the
patch will not be quite as fresh in your mind.
Still others test maintainer trees, which often have a similar time delay.
Quite a few people don't test code until it is committed to mainline,
or the master source tree (Linus's tree in the case of the Linux kernel).
If your maintainer won't accept your patch until it has been tested,
this presents you with a deadlock situation: your patch won't be accepted
until it is tested, but it won't be tested until it is accepted.
Nevertheless, people who test mainline code are still relatively
aggressive, given that many people and organizations do not test code
until it has been pulled into a Linux distro.
And even if someone does test your patch, there is no guarantee that they
will be running the hardware and software configuration and workload
required to locate your bugs.
Therefore, even when writing code for an open-source project, you need to
be prepared to develop and run your own test suite.
Test development is an underappreciated and very valuable skill, so be
sure to take full advantage of any existing test suites available to
you.
Important as test development is, we will leave further discussion of it
to books dedicated to that topic.
The following sections therefore discuss locating bugs in your code given that
you already have a good test suite.
\section{Tracing}
\label{sec:debugging:Tracing}
%
\epigraph{The machine knows what is wrong. Make it tell you.}{\emph{Unknown}}
When all else fails, add a \co{printk()}!
Or a \co{printf()}, if you are working with user-mode C-language applications.
The rationale is simple: If you cannot figure out how execution reached
a given point in the code, sprinkle print statements earlier in the
code to work out what happened.
You can get a similar effect, and with more convenience and flexibility,
by using a debugger such as gdb (for user applications) or kgdb
(for debugging Linux kernels).
Much more sophisticated tools exist, with some of the more recent
offering the ability to rewind backwards in time from the point
of failure.
These brute-force testing tools are all valuable, especially now
that typical systems have more than 64K of memory and CPUs running
faster than 4\,MHz.
Much has been
written about these tools, so this chapter will add little more.
However, these tools all have a serious shortcoming when the job at hand
is to convince a the fastpath of a high-performance parallel algorithm
to tell you what is going wrong, namely, they often have excessive
overheads.
There are special tracing technologies for this purpose, which typically
leverage data ownership techniques
(see Chapter~\ref{chp:Data Ownership})
to minimize the overhead of runtime data collection.
One example within the Linux kernel is
``trace events''~\cite{StevenRostedt2010perfTraceEventP1,StevenRostedt2010perfTraceEventP2,StevenRostedt2010perfTraceEventP3,StevenRostedt2010perfHP+DeathlyMacros},
which uses per-CPU buffers to allow data to be collected with
extremely low overhead.
Even so, enabling tracing can sometimes change timing enough to
hide bugs, resulting in \emph{heisenbugs}, which are discussed in
Section~\ref{sec:debugging:Probability and Heisenbugs}
and especially Section~\ref{sec:debugging:Hunting Heisenbugs}.
In userspace code, there is a huge number of tools that can help you.
One good starting point is Brendan Gregg's blog.\footnote{
\url{http://www.brendangregg.com/blog/}}
Even if you avoid heisenbugs, other pitfalls await you.
For example, although the machine really does know all,
what it knows is almost always way more than your head can hold.
For this reason, high-quality test suites normally come with sophisticated
scripts to analyze the voluminous output.
But beware---scripts won't necessarily notice surprising things.
My rcutorture scripts are a case in point: Early versions of those
scripts were quite satisfied with a test run in which RCU grace periods
stalled indefinitely.
This of course resulted in the scripts being modified to detect RCU
grace-period stalls, but this does not change the fact that the scripts
will only detects problems that I think to make them detect.
But note well that unless you have a solid design, you won't know what
your script should check for!
Another problem with tracing and especially with \co{printk()} calls
is that their overhead is often too much for production use.
In some such cases, assertions can be helpful.
\section{Assertions}
\label{sec:debugging:Assertions}
%
\epigraph{No man really becomes a fool until he stops asking questions.}
{\emph{Charles P. Steinmetz}}
Assertions are usually implemented in the following manner:
\begin{VerbatimN}
if (something_bad_is_happening())
complain();
\end{VerbatimN}
This pattern is often encapsulated into C-preprocessor macros or
language intrinsics, for example, in the Linux kernel, this might
be represented as \co{WARN_ON(something_bad_is_happening())}.
Of course, if \co{something_bad_is_happening()} quite frequently,
the resulting output might obscure reports of other problems,
in which case
\co{WARN_ON_ONCE(something_bad_is_happening())} might be more appropriate.
\QuickQuiz{}
How can you implement \co{WARN_ON_ONCE()}?
\QuickQuizAnswer{
If you don't mind having a \co{WARN_ON_ONCE()} that
will sometimes warn twice or three times, simply maintain
a static variable that is initialized to zero.
If the condition triggers, check the static variable, and
if it is non-zero, return.
Otherwise, set it to one, print the message, and return.
If you really need the message to never appear more than once,
perhaps because it is huge, you can use an atomic exchange
operation in place of ``set it to one'' above.
Print the message only if the atomic exchange operation returns
zero.
} \QuickQuizEnd
In parallel code, one especially bad something that might happen is that
a function expecting to be called under a particular lock might be called
without that lock being held.
Such functions sometimes have header comments stating something like
``The caller must hold \co{foo_lock} when calling this function'', but
such a comment does no good unless someone actually reads it.
An executable statement like \co{lock_is_held(&foo_lock)} carries far
more weight.
The Linux kernel's lockdep
facility~\cite{JonathanCorbet2006lockdep,StevenRostedt2011locdepCryptic}
takes this a step farther, reporting potential deadlocks as well as
allowing functions to verify that the proper locks are held.
Of course, this additional functionality incurs significant overhead,
so that lockdep is not necessarily appropriate for production use.
So what can be done in cases where checking is necessary, but where the
overhead of runtime checking cannot be tolerated?
One approach is static analysis, which is discussed in the next section.
\section{Static Analysis}
\label{sec:debugging:Static Analysis}
%
\epigraph{A lot of automation isn't a replacement of
humans but of mind-numbing behavior.}
{\emph{Summarized from Stewart Butterfield}}
Static analysis is a validation technique were one program takes a second
program as input, reporting errors and vulnerabilities located in this
second program.
Interestingly enough, almost all programs are subjected to static analysis
by their compilers or interpreters.
These tools are of course far from perfect, but their ability to locate
errors has improved immensely over the past few decades, in part because
they now have much more than 64K bytes of memory in which to carry out their
analysis.
The original UNIX \co{lint} tool~\cite{StephenJohnson1977lint} was
quite useful, though much of its functionality has since been incorporated
into C compilers.
There are nevertheless lint-like tools under development and in use to
this day.
The sparse static analyzer~\cite{JonathanCorbet2004sparse}
looks for higher-level issues in the Linux kernel, including:
\begin{enumerate}
\item Misuse of pointers to user-space structures.
\item Assignments from too-long constants.
\item Empty \co{switch} statements.
\item Mismatched lock acquisition and release primitives.
\item Misuse of per-CPU primitives.
\item Use of RCU primitives on non-RCU pointers and vice versa.
\end{enumerate}
Although it is likely that compilers will continue to increase their
static-analysis capabilities, the sparse static analyzer demonstrates
the benefits of static analysis outside of the compiler, particularly
for finding application-specific bugs.
\section{Code Review}
\label{sec:debugging:Code Review}
%
\epigraph{If a man speaks of my virtues, he steals from me;
if he speaks of my vices, then he is my teacher.}
{\emph{Chinese proverb}}
Various code-review activities are special cases of static analysis, but
with human beings doing the analysis.
This section covers inspection, walkthroughs, and self-inspection.
\subsection{Inspection}
\label{sec:debugging:Inspection}
Traditionally, formal code inspections take place in face-to-face meetings
with formally defined roles: moderator, developer, and one or two other
participants.
The developer reads through the code, explaining what it is doing and
why it works.
The one or two other participants ask questions and raise issues, while
the moderator's job is to resolve any conflicts and to take notes.
This process can be extremely effective at locating bugs, particularly
if all of the participants are familiar with the code at hand.
However, this face-to-face formal procedure does not necessarily
work well in the global Linux kernel community, although it might work
well via an IRC session.
Instead, individuals review code separately and provide comments via
email or IRC.
The note-taking is provided by email archives or IRC logs, and moderators
volunteer their services as appropriate.
Give or take the occasional flamewar, this process also works reasonably
well, particularly if all of the participants are familiar with the
code at hand.\footnote{
That said, one advantage of the Linux kernel community approach
over traditional formal inspections is the greater probability of
contributions from people \emph{not} familiar with the code,
who therefore might not be blinded by the invalid assumptions
harbored by those familiar with the code.}
It is quite likely that the Linux kernel community's review process
is ripe for improvement:
\begin{enumerate}
\item There is sometimes a shortage of people with the time and
expertise required to carry out an effective review.
\item Even though all review discussions are archived, they are
often ``lost'' in the sense that insights are forgotten and
people often fail to look up the discussions.
This can result in re-insertion of the same old bugs.
\item It is sometimes difficult to resolve flamewars when they do
break out, especially when the combatants have disjoint
goals, experience, and vocabulary.
\end{enumerate}
When reviewing, therefore, it is worthwhile to review relevant documentation
in commit logs, bug reports, and LWN articles.
\subsection{Walkthroughs}
\label{sec:debugging:Walkthroughs}
A traditional code walkthrough is similar to a formal inspection,
except that the group
``plays computer'' with the code, driven by specific test cases.
A typical walkthrough team has a moderator, a secretary (who records
bugs found), a testing expert (who generates the test cases) and
perhaps one to two others.
These can be extremely effective, albeit also extremely time-consuming.
It has been some decades since I have participated in a formal
walkthrough, and I suspect that a present-day walkthrough would
use single-stepping debuggers.
One could imagine a particularly sadistic procedure as follows:
\begin{enumerate}
\item The tester presents the test case.
\item The moderator starts the code under a debugger, using the
specified test case as input.
\item Before each statement is executed, the developer is required
to predict the outcome of the statement and explain why
this outcome is correct.
\item If the outcome differs from that predicted by the developer,
this is taken as evidence of a potential bug.
\item In parallel code, a ``concurrency shark'' asks what code
might execute concurrently with this code, and why such
concurrency is harmless.
\end{enumerate}
Sadistic, certainly.
Effective?
Maybe.
If the participants have a good understanding of the requirements,
software tools, data structures, and algorithms, then walkthroughs
can be extremely effective.
If not, walkthroughs are often a waste of time.
\subsection{Self-Inspection}
\label{sec:debugging:Self-Inspection}
Although developers are usually not all that effective at inspecting
their own code, there are a number of situations where there is no
reasonable alternative.
For example, the developer might be the only person authorized to look
at the code, other qualified developers might all be too busy, or
the code in question might be sufficiently bizarre that the developer
is unable to convince anyone else to take it seriously until after
demonstrating a prototype.
In these cases, the following procedure can be quite helpful,
especially for complex parallel code:
\begin{enumerate}
\item Write design document with requirements, diagrams for data structures,
and rationale for design choices.
\item Consult with experts, update the design document as needed.
\item Write the code in pen on paper, correct errors as you go.
Resist the temptation to refer to pre-existing nearly identical code
sequences, instead, copy them.
\item If there were errors, copy the code in pen on fresh paper, correcting
errors as you go.
Repeat until the last two copies are identical.
\item Produce proofs of correctness for any non-obvious code.
\item Use a source-code control system.
Commit early; commit often.
\item Where possible, test the code fragments from the bottom up.
\item When all the code is integrated (but preferably before),
do full-up functional and stress testing.
\item Once the code passes all tests, write code-level documentation,
perhaps as an extension to the design document discussed above.
Fix both the code and the test code as needed.
\end{enumerate}
When I faithfully follow this procedure for new RCU code, there are
normally only a few bugs left at the end.
With a few prominent (and embarrassing)
exceptions~\cite{PaulEMcKenney2011RCU3.0trainwreck},
I usually manage to locate these bugs before others do.
That said, this is getting more difficult over time as the number and
variety of Linux-kernel users increases.
\QuickQuiz{}
Why would anyone bother copying existing code in pen on paper???
Doesn't that just increase the probability of transcription errors?
\QuickQuizAnswer{
If you are worried about transcription errors, please allow me
to be the first to introduce you to a really cool tool named
\co{diff}.
In addition, carrying out the copying can be quite valuable:
\begin{enumerate}
\item If you are copying a lot of code, you are probably failing
to take advantage of an opportunity for abstraction.
The act of copying code can provide great motivation
for abstraction.
\item Copying the code gives you an opportunity to think about
whether the code really works in its new setting.
Is there some non-obvious constraint, such as the need
to disable interrupts or to hold some lock?
\item Copying the code also gives you time to consider whether
there is some better way to get the job done.
\end{enumerate}
So, yes, copy the code!
} \QuickQuizEnd
\QuickQuiz{}
This procedure is ridiculously over-engineered!
How can you expect to get a reasonable amount of software
written doing it this way???
\QuickQuizAnswer{
Indeed, repeatedly copying code by hand is laborious and slow.
However, when combined with heavy-duty stress testing and
proofs of correctness, this approach is also extremely effective
for complex parallel code where ultimate performance and
reliability are required and where debugging is difficult.
The Linux-kernel RCU implementation is a case in point.
On the other hand, if you are writing a simple single-threaded
shell script to manipulate some data, then you would be
best-served by a different methodology.
For example, you might enter each command one at a time
into an interactive shell with a test data set to make
sure that it did what you wanted, then copy-and-paste the
successful commands into your script.
Finally, test the script as a whole.
If you have a friend or colleague who is willing to help out,
pair programming can work very well, as can any number of
formal design- and code-review processes.
And if you are writing code as a hobby, then do whatever you like.
In short, different types of software need different development
methodologies.
} \QuickQuizEnd
\QuickQuiz{}
What do you do if, after all the pen-on-paper copying, you find
a bug while typing in the resulting code?
\QuickQuizAnswer{
The answer, as is often the case, is ``it depends''.
If the bug is a simple typo, it is best to fix that typo and
continue typing.
However, if the bug indicates a design flaw, it is best to
go back to the pen and paper.
} \QuickQuizEnd
The above procedure works well for new code, but what if you need to
inspect code that you have already written?
You can of course apply the above procedure for old code in the special
case where you wrote one to throw away~\cite{Brooks79},
but the following approach can also be helpful in less desperate
circumstances:
\begin{enumerate}
\item Using your favorite documentation tool (\LaTeX{}, HTML,
OpenOffice, or straight ASCII), describe the high-level
design of the code in question.
Use lots of diagrams to illustrate the data structures
and how these structures are updated.
\item Make a copy of the code, stripping away all comments.
\item Document what the code does statement by statement.
\item Fix bugs as you find them.
\end{enumerate}
This works because describing the code in detail is an excellent way to spot
bugs~\cite{GlenfordJMyers1979}.
Although this second procedure is also a good way to get your head around
someone else's code, in many cases, the first step suffices.
Although review and inspection by others is probably more efficient and
effective, the above procedures can be quite helpful in cases where
for whatever reason it is not feasible to involve others.
At this point, you might be wondering how to write parallel code without
having to do all this boring paperwork.
Here are some time-tested ways of accomplishing this:
\begin{enumerate}
\item Write a sequential program that scales through use of
available parallel library functions.
\item Write sequential plug-ins for a parallel framework,
such as map-reduce, BOINC, or a web-application server.
\item Do such a good job of parallel design that the problem
is fully partitioned, then just implement sequential
program(s) that run in parallel without communication.
\item Stick to one of the application areas (such as linear algebra)
where tools can automatically decompose and parallelize
the problem.
\item Make extremely disciplined use of parallel-programming
primitives, so that the resulting code is easily seen to be correct.
But beware: It is always tempting to break the rules
``just a little bit'' to gain better performance or
scalability.
Breaking the rules often results in general breakage.
That is, unless you carefully do the paperwork described in this
section.
\end{enumerate}
But the sad fact is that even if you do the paperwork or use one of
the above ways to more-or-less safely avoid paperwork,
there will be bugs.
If nothing else, more users and a greater variety of users will expose
more bugs more quickly, especially if those users are doing things
that the original developers did not consider.
The next section describes how to handle the probabilistic bugs that
occur all too commonly when validating parallel software.
\section{Probability and Heisenbugs}
\label{sec:debugging:Probability and Heisenbugs}