Page
1
ptg18240117 From the Library of james shahan
Page
2
ptg18240117 i i “effective-debugging” — 2016/6/3 — 14:32 — page i — #1 i i i i i i Effective Debugging From the Library of james shahan
Page
3
ptg18240117 i i “effective-debugging” — 2016/6/3 — 14:32 — page ii — #2 i i i i i i The Effective Software Development Series provides expert advice on all aspects of modern software development. Titles in the series are well written, technically sound, and of lasting value. Each describes the critical things experts always do — or always avoid — to produce outstanding software. Scott Meyers, author of the best-selling books Effective C++ (now in its third edition), More Effective C++, and Effective STL (all available in both print and electronic versions), conceived of the series and acts as its consulting editor. Authors in the series work with Meyers to create essential reading in a format that is familiar and accessible for software developers of every stripe. Visit informit.com/esds for a complete list of available publications. Make sure to connect with us! informit.com/socialconnect The Effective Software Development Series Scott Meyers, Consulting Editor From the Library of james shahan
Page
4
ptg18240117 i i “effective-debugging” — 2016/6/3 — 14:32 — page iii — #3 i i i i i i Effective Debugging 66 SPECIFIC WAYS TO DEBUG SOFTWARE AND SYSTEMS Diomidis Spinellis Boston • Columbus • Indianapolis • New York • San Francisco • Amsterdam • Cape Town Dubai • London • Madrid • Milan • Munich • Paris • Montreal • Toronto • Delhi • Mexico City São Paulo • Sydney • Hong Kong • Seoul • Singapore • Taipei • Tokyo From the Library of james shahan
Page
5
ptg18240117 i i “effective-debugging” — 2016/6/3 — 14:32 — page iv — #4 i i i i i i Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals. The author and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. For information about buying this title in bulk quantities, or for special sales opportunities (which may include electronic versions; custom cover designs; and content particular to your business, training goals, marketing focus, or branding interests), please contact our corporate sales department at corpsales@pearsoned.com or (800) 382-3419. For government sales inquiries, please contact governmentsales@pearsoned.com. For questions about sales outside the U.S., please contact intlcs@pearson.com. Visit us on the Web: informit.com/aw Library of Congress Control Number: 2016937082 Copyright © 2017 Pearson Education, Inc. All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, request forms, and the appropriate contacts within the Pearson Education Global Rights & Permissions Department, please visit www.pearsoned.com/permissions/. ISBN-13: 978-0-13-439479-4 ISBN-10: 0-13-439479-8 Text printed in the United States at RR Donnelley in Crawfordsville, Indiana. First printing, July 2016 From the Library of james shahan
Page
6
ptg18240117 i i “effective-debugging” — 2016/6/3 — 14:32 — page v — #5 i i i i i i To my mentors, past and future From the Library of james shahan
Page
7
ptg18240117 This page intentionally left blank From the Library of james shahan
Page
8
ptg18240117 i i “effective-debugging” — 2016/6/3 — 14:32 — page vii — #7 i i i i i i Contents Figures xi Listings xiii Preface xv Acknowledgments xxiii About the Author xxviii Chapter 1: High-Level Strategies 1 Item 1: Handle All Problems through an Issue-Tracking System 1 Item 2: Use Focused Queries to Search the Web for Insights into Your Problem 3 Item 3: Confirm That Preconditions and Postconditions Are Satisfied 5 Item 4: Drill Up from the Problem to the Bug or Down from the Program’s Start to the Bug 7 Item 5: Find the Difference between a Known Good System and a Failing One 9 Item 6: Use the Software’s Debugging Facilities 12 Item 7: Diversify Your Build and Execution Environment 17 Item 8: Focus Your Work on the Most Important Problems 20 Chapter 2: General-Purpose Methods and Practices 23 Item 9: Set Yourself Up for Debugging Success 23 Item 10: Enable the Efficient Reproduction of the Problem 25 From the Library of james shahan
Page
9
ptg18240117 i i “effective-debugging” — 2016/6/3 — 14:32 — page viii — #8 i i i i i i viii Contents Item 11: Minimize the Turnaround Time from Your Changes to Their Result 28 Item 12: Automate Complex Testing Scenarios 29 Item 13: Enable a Comprehensive Overview of Your Debugging Data 32 Item 14: Consider Updating Your Software 33 Item 15: Consult Third-Party Source Code for Insights on Its Use 34 Item 16: Use Specialized Monitoring and Test Equipment 36 Item 17: Increase the Prominence of a Failure’s Effects 40 Item 18: Enable the Debugging of Unwieldy Systems from Your Desk 42 Item 19: Automate Debugging Tasks 44 Item 20: Houseclean Before and After Debugging 45 Item 21: Fix All Instances of a Problem Class 46 Chapter 3: General-Purpose Tools and Techniques 49 Item 22: Analyze Debug Data with Unix Command-Line Tools 49 Item 23: Utilize Command-Line Tool Options and Idioms 55 Item 24: Explore Debug Data with Your Editor 57 Item 25: Optimize Your Work Environment 59 Item 26: Hunt the Causes and History of Bugs with the Revision Control System 64 Item 27: Use Monitoring Tools on Systems Composed of Independent Processes 67 Chapter 4: Debugger Techniques 71 Item 28: Use Code Compiled for Symbolic Debugging 71 Item 29: Step through the Code 76 Item 30: Use Code and Data Breakpoints 77 Item 31: Familiarize Yourself with Reverse Debugging 80 Item 32: Navigate along the Calls between Routines 82 Item 33: Look for Errors by Examining the Values of Variables and Expressions 84 Item 34: Know How to Attach a Debugger to a Running Process 87 Item 35: Know How to Work with Core Dumps 89 Item 36: Tune Your Debugging Tools 92 Item 37: Know How to View Assembly Code and Raw Memory 95 From the Library of james shahan
Page
10
ptg18240117 i i “effective-debugging” — 2016/6/3 — 14:32 — page ix — #9 i i i i i i Contents ix Chapter 5: Programming Techniques 101 Item 38: Review and Manually Execute Suspect Code 101 Item 39: Go Over Your Code and Reasoning with a Colleague 103 Item 40: Add Debugging Functionality 104 Item 41: Add Logging Statements 108 Item 42: Use Unit Tests 112 Item 43: Use Assertions 116 Item 44: Verify Your Reasoning by Perturbing the Debugged Program 119 Item 45: Minimize the Differences between a Working Example and the Failing Code 120 Item 46: Simplify the Suspect Code 121 Item 47: Consider Rewriting the Suspect Code in Another Language 124 Item 48: Improve the Suspect Code’s Readability and Structure 126 Item 49: Fix the Bug’s Cause, Rather Than Its Symptom 129 Chapter 6: Compile-Time Techniques 133 Item 50: Examine Generated Code 133 Item 51: Use Static Program Analysis 136 Item 52: Configure Deterministic Builds and Executions 141 Item 53: Configure the Use of Debugging Libraries and Checks 143 Chapter 7: Runtime Techniques 149 Item 54: Find the Fault by Constructing a Test Case 149 Item 55: Fail Fast 153 Item 56: Examine Application Log Files 154 Item 57: Profile the Operation of Systems and Processes 158 Item 58: Trace the Code’s Execution 162 Item 59: Use Dynamic Program Analysis Tools 168 Chapter 8: Debugging Multi-threaded Code 171 Item 60: Analyze Deadlocks with Postmortem Debugging 171 Item 61: Capture and Replicate 178 Item 62: Uncover Deadlocks and Race Conditions with Specialized Tools 183 Item 63: Isolate and Remove Nondeterminism 188 From the Library of james shahan
Page
11
ptg18240117 i i “effective-debugging” — 2016/6/3 — 14:32 — page x — #10 i i i i i i x Contents Item 64: Investigate Scalability Issues by Looking at Contention 190 Item 65: Locate False Sharing by Using Performance Counters 193 Item 66: Consider Rewriting the Code Using Higher-Level Abstractions 197 Web Resources 207 Index 211 From the Library of james shahan
Page
12
ptg18240117 i i “effective-debugging” — 2016/6/3 — 14:32 — page xi — #11 i i i i i i Figures Figure 1.1 Output of the ssh daemon with debugging enabled 14 Figure 1.2 The output of an SQL explain statement on a query using an index and a query that doesn’t use one 15 Figure 2.1 A representation of how a log file will look: in the default editor setup and with a wide view 33 Figure 3.1 Nagios monitoring service status details 69 Figure 4.1 Doubly linked list visualization with Python Tutor 86 Figure 5.1 Hand-drawn calculations beside a 1970 listing of the PDP-7 Unix file system check program, the forerunner of fsck 102 Figure 5.2 Minecraft’s debug mode and debug world 106 Figure 7.1 A list of running processes obtained with top and the Windows Task Manager 159 Figure 7.2 An overview of hot packages and classes provided by Java Mission Control 162 Figure 8.1 Intel Inspector identifying race conditions 186 Figure 8.2 Analyzing a contention problem with Java Flight Recorder 193 From the Library of james shahan
Page
13
ptg18240117 This page intentionally left blank From the Library of james shahan
Page
14
ptg18240117 i i “effective-debugging” — 2016/6/3 — 14:32 — page xiii — #13 i i i i i i Listings Listing 2.1 Exporting C functions for testing through Lua 30 Listing 3.1 Example of a Nagios plugin 68 Listing 4.1 A gdb script that verifies lock ordering 94 Listing 4.2 A simple counting loop in C 96 Listing 4.3 C program compiled into (AT&T syntax) ARM assembly language 96 Listing 4.4 C program compiled into (Intel syntax) x86 assembly language 97 Listing 5.1 Logging with the Unix syslog interface 109 Listing 5.2 Logging with the Apple’s system log facility 109 Listing 5.3 Logging with the Windows ReportEvent function 110 Listing 5.4 Logging with the Java’s java.util.logging package 110 Listing 5.5 Logging with the Python’s logging module 111 Listing 5.6 A C++ class that tracks the text’s column position 113 Listing 5.7 Code running the CppUnit test suite text interface 114 Listing 5.8 Unit test code 114 Listing 5.9 Using assertions to check preconditions, postconditions, and invariants 117 Listing 6.1 Disassembled Java Code 135 Listing 8.1 A C++ program that deadlocks 172 Listing 8.2 A Java program that deadlocks 176 Listing 8.3 A program with a race condition 178 Listing 8.4 Using a counter from multiple threads 183 Listing 8.5 Multi-threaded key pair generation 190 Listing 8.6 Parallelizing function application in R 202 Listing 8.7 Stream-based IP address resolution 204 From the Library of james shahan
Page
15
ptg18240117 This page intentionally left blank From the Library of james shahan
Page
16
ptg18240117 i i “effective-debugging” — 2016/6/3 — 14:32 — page xv — #15 i i i i i i Preface When you develop software or administer systems that run it, you often face failures. These can range from a compiler error in your code, which you can fix in seconds, to downtime in a large-scale system, which costs your company millions (pick your currency) each hour. In both cases, as an effective professional, you’ll need to be able to quickly identify and fix the underlying fault. This is what debugging is all about, and that is this book’s topic. The book is aimed at experienced developers. It is not introductory, in the sense that it expects you to be able to understand small code ex- amples in diverse programming languages and use advanced GUI and command-line-based programming tools. On the other hand, the de- bugging techniques included in the book are described in detail, for I’ve seen that even experienced developers who are experts on some meth- ods may well need some hand-holding on others. Furthermore, if you’ve debugged problems on non-toy software for at least a few months, you’ll find it easier to appreciate the context behind some of the book’s more advanced items. What This Book Covers Debugging, as treated in this book, encompasses strategies, tools, and methods you can use to deal with the whole spectrum of problems that can arise when developing and operating a modern, sophisticated com- puting system. In the past, debugging mainly referred to detecting and fixing a program’s faults; however, nowadays a program rarely works in isolation. Even the smallest program will link (often dynamically) to ex- ternal libraries. More complex ones can run under an application server, call web services, use relational and NoSQL databases, obtain data from a directory server, run external programs, utilize other middleware, and incorporate numerous third-party packages. The operation of complete systems and services depends on the failure-free functioning of many From the Library of james shahan
Page
17
ptg18240117 i i “effective-debugging” — 2016/6/3 — 14:32 — page xvi — #16 i i i i i i xvi Preface in-house-developed and third-party components running on hosts that may span the whole planet. DevOps, the software development disci- pline that addresses this reality, emphasizes the roles of both developers and other IT professionals. This book aims to equip you for a similarly holistic view when facing failures, because in the most challenging prob- lems you’ll rarely be able to immediately identify the software component that’s the culprit. The material progresses from general topics to more specific ones. It starts with strategies (Chapter 1), methods (Chapter 2), and tools and techniques (Chapter 3) that can help you debug diverse software and systems failures. It then covers techniques that you apply at specific stages of your debugging work: when you use a debugger (Chapter 4), when you program (Chapter 5), when you compile the software (Chap- ter 6), and when you run the system (Chapter 7). A separate chapter (Chapter 8) focuses on the specialized tools and techniques you can use to hunt down those pesky bugs that are associated with multi-threaded and concurrent code. How to Use This Book Read the left page, read the right page, flip the right page, until you reach the end. Wait! Actually, there’s a better way. The advice contained in this book can be divided into three categories. ■ Strategies and methods you should know and practice when you face a failure. These are described in Chapter 1: “High-Level Strate- gies” and Chapter 2: “General-Purpose Methods and Practices.” In addition, many techniques included in Chapter 5: “Programming Techniques” also fall in this category. Read and understand these items, so that applying them gradually becomes a habit. While de- bugging, systematically reflect on the method you’re using. When you reach a dead end, knowing the avenue you’ve explored will help you identify other ways to get out of the maze. ■ Skills and tools you can invest in. These are mainly covered in Chapter 3: “General-Purpose Tools and Techniques” but also in- clude elements that apply to the problems you face on an everyday basis; for example, see Item 36: “Tune Your Debugging Tools.” Find time to learn and gradually apply in practice what these items de- scribe. This may mean abandoning the comfort of using tools you’re familiar with in order to conquer the steep learning curve of more advanced ones. It may be painful in the beginning, but in the long run this is what will distinguish you as a master of your craft. From the Library of james shahan
Page
18
ptg18240117 i i “effective-debugging” — 2016/6/3 — 14:32 — page xvii — #17 i i i i i i Preface xvii ■ Ideas for techniques to apply when things get tough. These are not things you’ll be using regularly, but they can save your day (or at least a few hours) when you encounter an unfathomable problem. For instance, if you can’t understand why your C and C++ code fail to compile, see Item 50: “Examine Generated Code.” Quickly go through these items to be aware of them as options. Study them carefully when the time comes to apply them. How to Live Your Life Although all items in this book offer advice for diagnosing failures and debugging existing faults, you can also apply many of them to mini- mize the number of bugs you encounter and make your life easier when one crops up. Rigorous debugging and software development practices feed on each other in a virtuous circle. This advice covers your (current or future) roles in software construction, software design, and software management. When designing software, do all of the following: ■ Use the highest-level mechanisms suitable for its role (Item 47: “Consider Rewriting the Suspect Code in Another Language” and Item 66:“Consider Rewriting the Code Using Higher-Level Abstractions”) ■ Offer a debugging mode (Item 6: “Use the Software’s Debugging Fa- cilities” and Item 40: “Add Debugging Functionality”) ■ Provide mechanisms to monitor and log the system’s operation (Item 27: “Use Monitoring Tools on Systems Composed of Indepen- dent Processes,” Item 41: “Add Logging Statements,” and Item 56: “Examine Application Log Files”) ■ Include an option to script components with Unix command-line tools (Item 22:“Analyze Debug Data with Unix Command-Line Tools”) ■ Make internal errors lead to visible failures rather than to instabil- ity (Item 55: “Fail Fast”) ■ Provide a method to obtain postmortem memory dumps (Item 35: “Know How to Work with Core Dumps” and Item 60: “Analyze Dead- locks with Postmortem Debugging”) ■ Minimize the sources and extent of nondeterminism in the soft- ware’s execution (Item 63: “Isolate and Remove Nondeterminism”) From the Library of james shahan
Page
19
ptg18240117 i i “effective-debugging” — 2016/6/3 — 14:32 — page xviii — #18 i i i i i i xviii Preface When constructing software, take the following steps: ■ Obtain feedback from your colleagues (Item 39: “Go Over Your Code and Reasoning with a Colleague”) ■ Create a unit test for each routine you write (Item 42: “Use Unit Tests”) ■ Use assertions to verify your assumptions and the code’s correct functioning (Item 43: “Use Assertions”) ■ Strive to write maintainable code—code that is readable, stable, and easy to analyze and change (Item 46: “Simplify the Suspect Code” and Item 48: “Improve the Suspect Code’s Readability and Structure”) ■ Avoid sources of nondeterminism in your builds (Item 52: “Config- ure Deterministic Builds and Executions”) Finally, when managing software development and operations (either a team or your own process), do the following: ■ Have issues recorded and followed through a suitable system (Item 1: “Handle All Problems through an Issue-Tracking System”) ■ Triage and prioritize the issues you work on (Item 8: “Focus Your Work on the Most Important Problems”) ■ Have software changes properly recorded in a well-maintained re- vision management system (Item 26: “Hunt the Causes and History of Bugs with the Revision Control System”) ■ Deploy software in a gradual fashion, allowing the old version to be compared with the new one (Item 5: “Find the Difference between a Known Good System and a Failing One”) ■ Strive for diversity in the tools you use and the environments you deploy (Item 7: “Diversify Your Build and Execution Environment”) ■ Update tools and libraries on a regular basis (Item 14: “Consider Updating Your Software”) ■ Purchase source code for any third-party libraries you use (Item 15: “Consult Third-Party Source Code for Insights on Its Use”) and buy the sophisticated tools needed to pin down elusive faults (Item 51: “Use Static Program Analysis”; Item 59: “Use Dynamic Program Analysis Tools”; Item 62: “Uncover Deadlocks and Race Conditions with Specialized Tools”; Item 64: “Investigate Scalability From the Library of james shahan
Page
20
ptg18240117 i i “effective-debugging” — 2016/6/3 — 14:32 — page xix — #19 i i i i i i Preface xix Issues by Looking at Contention”; Item 65: “Locate False Sharing by Using Performance Counters”) ■ Supply any specialized kit required for debugging hardware inter- faces and embedded systems (Item 16: “Use Specialized Monitoring and Test Equipment”) ■ Enable developers to debug software remotely (Item 18: “Enable the Debugging of Unwieldy Systems from Your Desk”) ■ Provide sufficient CPU and disk resources for demanding trou- bleshooting tasks (Item 19: “Automate Debugging Tasks”) ■ Encourage collaboration between developers through practices such as code reviews and mentoring (Item 39: “Go Over Your Code and Reasoning with a Colleague”) ■ Promote the adoption of test-driven development (Item 42: “Use Unit Tests”) ■ Include in the software’s build performance profiling, static analy- sis, and dynamic analysis, while maintaining a fast, lean, and mean build and test cycle (Item 57: “Profile the Operation of Systems and Processes”; Item 51: “Use Static Program Analysis”; Item 59: “Use Dynamic Program Analysis Tools” and Item 53: “Configure the Use of Debugging Libraries and Checks”; Item 11: “Minimize the Turn- around Time from Your Changes to Their Result”) A Few Notes on Terminology In this book, I use the term fault according to the following definition, which appears in ISO-24765-2010 (Systems and software engineering— Vocabulary): “an incorrect step, process, or data definition in a computer program.” This is also often called a defect. In everyday language, this is what we call a bug. Similarly, I use the term failure according to the fol- lowing definition from the same standard: “an event in which a system or system component does not perform a required function within spec- ified limits.” A failure can be a program that crashes, freezes, or gives a wrong result. Thus, a failure may be produced when a fault is encoun- tered or used. Confusingly, sometimes the terms fault and defect are also used to refer to failures, something that the ISO standard acknowl- edges. In this book I maintain the distinction I describe here. However, to avoid having the text read like a legal document when the meaning is clear from the context, I often use the word “problem” to refer to either faults (as in “a problem in your code”) or failures (as in “a reproducible problem”). From the Library of james shahan