Docsity

Why Programs Fail, Apuntes de Ingeniería Infórmatica

Vista previa parcial del texto

¡Descarga Why Programs Fail y más Apuntes en PDF de Ingeniería Infórmatica solo en Docsity!

Morgan Kaufmann Publishers is an imprint of Elsevier 30 Corporate Drive, Suite 400 Burlington, MA 01803

This book is printed on acid-free paper. ©

Copyright © 2009 by Elsevier Inc. All rights reserved. Designations used by companies to distinguish their products are often claimed as trademarks or registered trademarks. In all instances in which Morgan Kaufmann Publishers is aware of a claim, the product names appear in initial capital or all capital letters. Readers, however, should contact the appropriate companies for more complete information regarding trademarks and registration.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, scanning, or otherwise, without prior written permission of the publisher.

Permissions may be sought directly from Elsevier’s Science & Technology Rights Department in Oxford, UK: phone: (+44) 1865 843830, fax: (+44) 1865 853333, e-mail: [email protected]. You may also complete your request on-line via the Elsevier homepage ( http://elsevier.com ), by selecting “Support & Contact” then “Copyright and Permission” and then “Obtaining Permissions.”

Library of Congress Cataloging-in-Publication Data Application submitted.

ISBN-13: 978-0-12-374515-

For information on all Morgan Kaufmann publications, visit our Website at www.books.elsevier.com

Printed in the United States 08 09 10 11 12 10 9 8 7 6 5 4 3 2 1

xvi Foreword

author’s innovative techniques for isolating minimal input to reproduce an error and for tracking cause and effect through a program. Studying this book will make you a better programmer. You will be able to find and fix errors in your code (and your colleague’s code) faster and more effectively, a valuable skill that will enable you to finish projects earlier and produce programs with fewer defects. Also, if you read between the lines you will learn how to write code that is more easily tested and debugged, which further increases your ability to find and correct defects. And thinking hard about what can go wrong with your program can help you avoid mistakes in the first place, so you have less to debug.

James Larus Microsoft Research

Preface

This is a book about bugs in computer programs—how to reproduce them, how to find them, and how to fix them such that they do not occur. This book teaches a number of techniques that allow you to debug any program in a systematic, and sometimes even elegant, way. Moreover, the techniques can be widely automated, which allows you to let your computer do most of the debugging. Questions this book addresses include: ■ How can I reproduce failures faithfully? ■ How can I isolate what is relevant for the failure? ■ How does the failure come to be? ■ How can I fix the program in the best possible way? ■ How can I learn from mistakes to prevent future ones? Once you understand how debugging works,you will not think about debugging in the same way. Instead of seeing a wild mess of code, you will think about causes and effects, and you will systematically set up and refine hypotheses to track failure causes. Your insights may even make you set up your own automated debugging tool. All of this allows you to spend less time on debugging, which is why you are interested in automated debugging in the first place, right?

How This Book Came to Be Written Although I work as a researcher, I have always considered myself a programmer, because this is how I spend most of my time. During programming, I make mis- takes, and I have to debug my code. I would like to say that I am some type of überprogrammer —that I never make mistakes—but I am only human, just like anyone else. During my studies,I have learned that an ounce of prevention is more than worth a pound of cure. I have learned many ways of preventing mistakes. Today, I teach them to my students. However, in striving for prevention we must not forget about the cure. If we were doctors,we could not simply refuse treatment just because our patient had not taken all possible preventive measures. So, rather than designing yet another ultimate prevention, I have sought good cures. This same pragmatic attitude has been adopted by other researchers around the globe. I am happy to report that we have succeeded. Today, a number of advanced debugging techniques are available that widely automate the debugging process. These techniques not only automate debugging, but also turn debugging from a black art into a systematic and well-organized discipline that can be taught just like any software engineering topic. Thus, I created a course on automated debug- ging and reworked the lecture notes into a book. The result is what you see

before you. xvii

Preface xix

At the end of each chapter, you will find a section called “Concepts,” which summarizes the key concepts of the chapter. Some of these concepts are denoted “How To.” These summarize recipes that can be easily followed (they are also listed in the Contents). Furthermore, each chapter ends with practical exercises , for ver- ifying your knowledge, and a “Further Reading” section. This book is organized as follows.

Chapter 1: How Failures Come To Be

Your program fails. How can this be? The answer is that the programmer created a defect in the code. When the code is executed, the defect causes an infection in the program state, which later becomes visible as a failure. To find the defect, one must reason backward, starting with the failure. This chapter defines the essential concepts when talking about debugging, and hints at the techniques discussed subsequently—hopefully whetting your appetite for the remainder of this book.

Chapter 2: Tracking Problems

This chapter deals with the issue of how to manage problems as reported by users— how to track and manage problem reports, how to organize the debugging process, and how to keep track of multiple versions. This information constitutes the basic framework in which debugging takes place.

Chapter 3: Making Programs Fail

Before a program can be debugged,we must set it up such that it can be tested —that is, executed with the intent to make it fail. In this chapter, we review basic testing techniques, with a special focus on automation and isolation.

Chapter 4: Reproducing Problems

The first step in debugging is to reproduce the problem in question—that is,to create a test case that causes the program to fail in the specified way. The first reason is to bring it under control, such that it can be observed. The second reason is to verify the success of the fix. This chapter discusses typical strategies for reproducing an operating environment, including its history and problem symptoms.

Chapter 5: Simplifying Problems

Once we have reproduced a problem, we must simplify it—that is, we must find out which circumstances are not relevant to the problem and can thus be omitted. This process results in a test case that contains only the relevant circumstances. In the best case, a simplified test case report immediately pinpoints the defect. We introduce delta debugging , an automated debugging method that simplifies test cases automatically.

Chapter 6: Scientific Debugging

Once we have reproduced and simplified a problem, we must understand how the failure came to be. The process of arriving at a theory that explains some aspect of

xx Preface

the universe is known as scientific method. It is the appropriate process for obtain- ing problem diagnostics. We introduce basic techniques of creating and verifying hypotheses, creating experiments, conducting the process in a systematic fashion, and making the debugging process explicit.

Chapter 7: Deducing Errors

In this chapter, we begin exploring the techniques for creating hypotheses that were introduced in Chapter 6.We start with deduction techniques—reasoning from the abstract program code to the concrete program run. In particular, we present program slicing , an automated means of determining possible origins of a vari- able value. Using program slicing, one can effectively narrow down the number of possible infection sites.

Chapter 8: Observing Facts

Although deduction techniques do not take concrete runs into account,observation determines facts about what has happened in a concrete run. In this chapter, we look under the hood of the actual program execution and introduce widespread techniques for examining program executions and program states.These techniques include classical logging, interactive debuggers, and postmortem debugging—as well as eye-opening visualization and summarization techniques.

Chapter 9: Tracking Origins

Once we have observed an infection during debugging, we need to determine its origin. We discuss omniscient debugging , a technique that records an entire execu- tion history such that the user can explore arbitrary moments in time without ever restarting the program. Furthermore, we explore dynamic slicing , a technique that tracks the origins of specific values.

Chapter 10: Asserting Expectations

Observation alone is not enough for debugging. One must compare the observed facts with the expected program behavior. In this chapter, we discuss how to auto- mate such comparisons using well-known assertion techniques. We also show how to ensure the correct state of important system components such as memory.

Chapter 11: Detecting Anomalies

Although a single program run can tell you quite a bit, performing multiple runs for purpose of comparison offers several opportunities for locating commonalities and anomalies —anomalies that frequently help locate defects. In this chapter, we dis- cuss how to detect anomalies in code coverage and anomalies in data accesses. We also show how to infer invariants from multiple test runs automatically, in order to flag later invariant violations. All of these anomalies are good candidates for identification as infection sites.

xxii Preface

Supplements, Resources, and Web Extensions Much of the material covered in this book has never been discussed in a text- book before. The later chapters have not been widely tested in practice, and like any book on an evolving field, this one will benefit from more refinement and from further work. In other words, this book is full of bugs, and I wel- come any comments on it. You can write to me care of Morgan Kaufmann, or email me at [email protected]. There is also a Web page at http://www. whyprogramsfail.com for late-breaking information and updates (read: errata).

Advice for Instructors I have used this book for five graduate courses on automated debugging. Each course consisted of approximately 16 lectures of 60 to 90 minutes each. Essen- tially, there was one lecture per chapter. The exercises stem from these courses (and their exams). I have also used parts of the book for a number of tutorials on debugging, as well as for inclusion in programming and software engineering courses. For your convenience, my presentation slides for these courses are avail- able in Keynote and Powerpoint format. Instructions on how to access them are available at http://www.whyprogramsfail.com. If you prefer to make your own slides,all of the original illustrations for this book are also available at this site.

Advice for Readers

Typographics

To keep things simple, most examples in this book use simple input/output mechanisms—that is, the command line and the console. In all of these exam- ples, typewriter font stands for program output, and bold typewriter font for user input. The command-line prompt is denoted by a dollar sign ($), and the cursor by an underscore ( _ ). The following is a simple example. The user invokes the hello program, which prints the text Hello, world! on the console. $ ./hello Hello, world! $ _

Programming Environment

The concepts and techniques discussed in this book do not depend on a particular programming environment or operating system.To illustrate the techniques,though, I frequently use command-line tools , typically from the Linux/UNIX community. In addition to saving space,this is a matter of simplicity;these command-line tools pro- vide a functional core similar to that found in almost all sophisticated programming environments. Therefore, you should have no trouble transferring the examples to your personal programming workbench.

Preface xxiii

ACKNOWLEDGMENTS

Many people have had a part in the development of this book. I would like to thank everybody who reviewed drafts of the manuscript or parts of it: Philipp Bouillon, Holger Cleve, David Cok, Michael Ernst, David Evans, Clint Jeffery, Dieter Kranzlmüller, Jens Krinke, Raimondas Lencevicius, Bil Lewis, Ben Liblit, Christian Lindig, Edu Metz, Robert Muth, Stephan Neuhaus, Jeff Offutt, Kerstin Reese, Zoltan Somogyi, Peter Weißgerber, Thomas Zimmermann, and the students of the Auto- mated Debugging courses at Saarland University, the University of Washington, and ETH Zürich. Philipp Bouillon, Silvia Breu, Holger Cleve, Andreas Leitner, and Martin Mehlmann also helped with the conception of the exercises. Thanks to all readers who reported bugs in the first edition, in particular Martin Burger, Roland Illig, and Yong-Wu Wang. Christa Preisendanz of dpunkt Verlag and Tim Cox of Morgan Kaufmann Publishers were most helpful. And finally, my family has supported me enormously while writing this book—it’s great to have you with me. Have fun debugging!

For the Snark’s a peculiar creature, that won’t Be caught in a commonplace way. Do all that you know, and try all that you don’t: Not a chance must be wasted to-day!

  • L EWIS C ARROLL The Hunting of the Snark (1876)

2 CHAPTER 1 How Failures Come to Be

BUG STORY 1

The First Bug

We do not know when the first defect in a program was introduced. What we know, though,is when the first actual bug was found. It may have been in search of plant food, or a warm place to lay its eggs,or both. Now it wandered around in this humming,warm machine that constantly clicked and rattled. But suddenly,it got stuck between the metal contacts of a relay—actually, one of 13,000 high-performance relays commissioned for this particular machine. The current killed it instantly—and its remains caused the machine to fail. This first actual bug was a moth, retrieved by a technician from the Harvard Mark II machine on September 9,1947.The moth got taped into the logbook,with the comment “1545 Relay #70 Panel F (moth) in relay. First actual case of bug being found.”The moth thus became the living proof that computer problems could indeed be caused by actual bugs.

Although the sample output is sorted and contains the right number of items, some original arguments are missing and replaced by bogus numbers. Here, 14 is missing and replaced by 0. (Actual bogus numbers and behavior on your system may vary.) From the sample failure, we can deduce that sample has a bug (or, more precisely, a defect ). This brings us to the key question of this chapter:

H OW DOES A DEFECT CAUSE A FAILURE, AND HOW CAN WE FIX IT?

1.2 FROM DEFECTS TO FAILURES In general, a failure such as that in the sample program comes about in the four stages discussed in the following.

1. The programmer creates a defect. A defect is a piece of the code that can cause an infection. Because the defect is part of the code,and because every code is initially written by a programmer, the defect is technically created by the programmer. If the programmer creates a defect, does that mean the programmer was at fault? Not necessarily. Consider the following: ■ The original requirements did not foresee future changes.Think about theY2K problem, for instance. ■ A program behavior may become classified as a “failure” only when the user sees it for the first time. ■ In a modular program,a failure may happen because of incompatible interfaces of two modules. ■ In a distributed program, a failure may be the result of some unpredictable interaction of several components.

1.2 From Defects to Failures 3

BUG STORY 2

F-16 Problems

A programmer who works for General Dynamics in Ft. Worth,TX, wrote some of the code for the F-16, and he has reported some neato-whiz-bang bug/feature they keep finding in the F-16. ■ Because the F-16 is a fly-by-wire aircraft, the computer keeps the pilot from doing dumb things to himself. So if the pilot jerks hard over on the joystick, the computer will instruct the flight surfaces to make a nice and easy 4- or 5-G flip. But the plane can withstand a much higher flip than that. So when they were “flying” the F-16 in simulation over the equator, the computer got confused and instantly flipped the plane over, killing the pilot [in simulation]. And since it can fly forever upside down, it would do so until it ran out of fuel. The remaining bugs were actually found while flying, rather than in simulation. ■ One of the first things the Air Force test pilots tried on an early F-16 was to tell the computer to raise the landing gear while standing still on the runway. Guess what happened? Scratch one F-16. […] ■ The computer system onboard has a weapons management system that will attempt to keep the plane flying level by dispersing weapons and empty fuel tanks in a balanced fashion. So,if you ask to drop a bomb the computer will figure out whether to drop a port or starboard bomb in order to keep the load even. One of the early problems with that was the fact that you could flip the plane over and the computer would gladly let you drop a bomb or fuel tank. It would drop, dent the wing, and then roll off.

In such settings, deciding on who is to blame is a political, not a technical, ques- tion. Nobody made a mistake, and yet a failure occurred. (See Bug Story 2 for more on such failures.)

2. The defect causes an infection. The program is executed, and with it the defect. The defect now creates an infection —that is, after execution of the defect, the program state differs from what the programmer intended. A defect in the code does not necessarily cause an infection. The defective code must be executed, and it must be executed under such conditions that the infection actually occurs. 3. The infection propagates. Most functions result in errors when fed with erro- neous input. As the remaining program execution accesses the state, it generates further infections that can spread into later program states.An infection need not, however, propagate continuously. It may be overwritten, masked, or corrected by some later program action. 4. The infection causes a failure. A failure is an externally observable error in the program behavior. It is caused by an infection in the program state.

1.3 Lost in Time and Space 5

1.3 LOST IN TIME AND SPACE

In general, debugging of a program such as sample can be decomposed into seven steps (List 1.1), of which the initial letters form the word TRAFFIC.

1. Track the problem in the database. 2. Reproduce the failure. 3. Automate and simplify the test case. 4. Find possible infection origins. 5. Focus on the most likely origins. 6. Isolate the infection chain. 7. Correct the defect. Of these steps, tracking the problem in a problem database is mere bookkeeping (see also Chapter 2) and reproducing the problem is not that difficult for determin- istic programs such as sample. It can be difficult for nondeterministic programs and long-running programs, though, which is why Chapter 4 discusses the issues involved in reproducing failures. Automating the test case is also rather straightforward, and results in auto- matic simplification (see also Chapter 5). The last step, correcting the defect , is usually simple once you have understood how the defect causes the failure (see Chapter 15). The final three steps—from finding the infection origins to isolating the infection chain—are the steps concerned with understanding how the failure came to be.

LIST 1.1: Seven Steps in Debugging (TRAFFIC)

T rack the problem in the database.

R eproduce the failure.

A utomate and simplify the test case.

F ind possible infection origins.

F ocus on the most likely origins:

■ Known infections ■ Causes in state, code, and input ■ Anomalies ■ Code smells

I solate the infection chain.

C orrect the defect.

6 CHAPTER 1 How Failures Come to Be

This task requires by far the most time, as well as other resources. Understanding how the failure came to be is what the rest of this section, and the other chapters of this book, are about. Why is understanding the failure so difficult? Considering Figure 1.1,all one need do to find the defect is isolate the transition from a sane state (i.e., noninfected, as intended) to an infected state.This is a search in space (as we have to find out which part of the state is infected) as well as in time (as we have to find out when the infection takes place). However,examination of space and time are enormous tasks for even the simplest programs. Each state consists of dozens, thousands, or even millions of variables. For example, Figure 1.2 shows a visualization of the program state of the GNU compiler (GCC) while compiling a program. The program state consists of about 44,000 individual variables, each with a distinct value, and about 42,000 references between variables. (Chapter 14 discusses how to obtain and use such program states in debugging.) Not only is a single state quite large, a program execution consists of thousands, millions, or even billions of such states. Space and time thus form a wide area in which only two points are well known ( Figure 1.3): initially, the entire state is sane (), and eventually some part of the state is infected (). Within the area spanned by space and time, the aim of debugging is to locate the defect—a single transition from sane () to infected () that eventually causes the failure (Figure 1.4). Thinking about the dimensions of space and time, this may seem like searching for a needle in an endless row of haystacks—and indeed, the fact is that debugging

/Hash table/Hash table/Hash table /hash table Extend tabExtend tabExtend tabExtend tab

/yyvsa

FIGURE 1. A program state of the GNU compiler. The state consists of 44,000 individual variables (shown as vertices) and about 42,000 references between variables (shown as edges).

8 CHAPTER 1 How Failures Come to Be

Variables

Time

FIGURE 1. Deducing value origins. By analyzing the program code, we can find out that an infected variable value () can have originated only from a small number of earlier variables ().

Figure 1.5 illustrates this latter technique. The failure, to reiterate, can only have been caused by a small number of other variables in earlier states (denoted using the exclamation point, ), the values of which in turn can only have come from other earlier variables. One says that subsequent, variable values depend on earlier values.This results in a series of dependences from the failure back to earlier variable values.To locate the defect,it suffices to examine these values only—as other values could not have possibly caused the failure—and separate these values into sane and infected. If we find an infected value, we must find and fix the defect that causes it. Typically, this is the same defect that causes the original failure. Why is it that a variable value can be caused only by a small number of earlier variables? Good programming style dictates division of the state into units such that the information flow between these units is minimized.Typically,your programming language provides a means of structuring the state, just as it helps you to structure the program code. However, whether you divide the state into functions, modules, objects, packages, or components, the principle is the same: a divided state is much easier to conquer.

1.4 FROM FAILURES TO FIXES Let’s put our knowledge about states and dependences into practice, following the TRAFFIC steps (List 1.1).

1.4.1 Track the Problem The first step in debugging is to track the problem —that is, to file a problem report such that the defect will not go by unnoticed. In our case,we have already observed

1.4 From Failures to Fixes 9

the failure symptom: the output of sample, when invoked with arguments 11 and 14 , contains a zero. $ ./sample 11 14 Output: 0 11 $ _ An actual problem report would include this invocation as an instruction on how to reproduce the problem (see Chapter 2).

1.4.2 Reproduce the Failure In case of the sample program, reproducing the failure is easy. All you need do is reinvoke sample, as shown previously. In other cases, though, reproducing may require control over all possible input sources (techniques are described in Chapter 4).

1.4.3 Automate and Simplify the Test Case If sample were a more complex program, we would have to think about how to automate the failure (in that we want to reproduce the failure automatically) and how to simplify its input such that we obtain a minimal test case. In the case of sample,though,this is not necessary (for more complex programs,Chapter 5 covers the details).

1.4.4 Find Possible Infection Origins Where does the zero in the output come from?This is the fourth step in theTRAFFIC steps:We must find possible infection origins. To find possible origins, we need the actual C source code of sample, shown in Example 1.1. We quickly see that the program consists of two functions:shell_sort() (which implements the shell sort algorithm) and main,which realizes a simple test driver around shell_sort().The main function: ■ Allocates an array a[] (line 32). ■ Copies the command-line arguments into a[] (lines 33–34). ■ Sorts a[] by invoking shell_sort() (line 36). ■ Prints the content of a[] (lines 38–41). By matching the output to the appropriate code, we find that the 0 printed by sample is the value of the variable a[0], the first element of the array a[]. This is the infection we observe: at line 39 in sample.c, variable a[0] is obviously zero. Where does the zero in a[0] come from?Working our way backward from line 40, we find in line 36 the call shell_sort(a, argc), where the array a[] is passed by reference. This function might well be the point at which a[0] was assigned the infected value.