RPROM 2002-09-02 2, 2002 Lassi A. Tuura, Northeastern University Using Valgrind Lassi A. Tuura Northeastern University,

Slides:



Advertisements
Similar presentations
R4 Dynamically loading processes. Overview R4 is closely related to R3, much of what you have written for R3 applies to R4 In R3, we executed procedures.
Advertisements

CS 450 Module R4. R4 Overview Due on March 11 th along with R3. R4 is a small yet critical part of the MPX system. In this module, you will add the functionality.
Module R2 CS450. Next Week R1 is due next Friday ▫Bring manuals in a binder - make sure to have a cover page with group number, module, and date. You.
Prof. Necula CS 164 Lecture 141 Run-time Environments Lecture 8.
Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Various languages….  Could affect performance  Could affect reliability  Could affect language choice.
Tools for applications improvement George Bosilca.
Hastings Purify: Fast Detection of Memory Leaks and Access Errors.
CS 536 Spring Run-time organization Lecture 19.
Run-Time Storage Organization
CSE 303 Lecture 13a Debugging C programs
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
. Memory Management. Memory Organization u During run time, variables can be stored in one of three “pools”  Stack  Static heap  Dynamic heap.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
Chocolate Bar! luqili. Milestone 3 Speed 11% of final mark 7%: path quality and speed –Some cleverness required for full marks –Implement some A* techniques.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
15-740/ Oct. 17, 2012 Stefan Muller.  Problem: Software is buggy!  More specific problem: Want to make sure software doesn’t have bad property.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Stack and Heap Memory Stack resident variables include:
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Technical Module : Pointers #1 2000/01Scientific Computing in OOCourse code 3C59 Technical Module : Pointers In this module we will cover Pointers to primitives.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Storage Management. The stack and the heap Dynamic storage allocation refers to allocating space for variables at run time Most modern languages support.
Pointers review Let a variable aa be defined as ‘int *aa;’, what is stored in aa? Let a variable aa be defined as ‘int ** aa;’ what is stored in aa? Why.
ECE 353 Lab 1: Cache Simulation. Purpose Introduce C programming by means of a simple example Reinforce your knowledge of set associative caches.
Pointers OVERVIEW.
COP4020 Programming Languages Subroutines and Parameter Passing Prof. Xin Yuan.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Object-Oriented Programming in C++
® IBM Software Group © 2006 IBM Corporation PurifyPlus on Linux / Unix Vinay Kumar H S.
CSCI Rational Purify 1 Rational Purify Overview Michel Izygon - Jim Helm.
#include using namespace std; // Declare a function. void check(int, double, double); int main() { check(1, 2.3, 4.56); check(7, 8.9, 10.11); } void check(int.
Debugging 1/6/2016. Debugging 1/6/2016 Debugging  Debugging is a methodical process of finding and reducing the number of bugs, or defects, in a program.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 10 – C: the heap and manual memory management.
Object Oriented Software Development 4. C# data types, objects and references.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 Debugging (Part 2). “Programming in the Large” Steps Design & Implement Program & programming style (done) Common data structures and algorithms Modularity.
1 C Basics Monday, August 30, 2010 CS 241. Announcements MP1, a short machine problem, will be released today. Due: Tuesday, Sept. 7 th at 11:59pm via.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 3 is due Sunday, the 8 th at 7pm. Today: –Two simple binding examples. –Function Hiding.
Announcements You will receive your scores back for Assignment 2 this week. You will have an opportunity to correct your code and resubmit it for partial.
CSE 333 – SECTION 2 Memory Management. Questions, Comments, Concerns Do you have any? Exercises going ok? Lectures make sense? Homework 1 – START EARLY!
LECTURE 19 Subroutines and Parameter Passing. ABSTRACTION Recall: Abstraction is the process by which we can hide larger or more complex code fragments.
HP-SEE Valgrind Usage Josip Jakić Scientific Computing Laboratory Institute of Physics Belgrade The HP-SEE initiative.
Hank Childs, University of Oregon April 6 th, 2015 CIS 330: _ _ _ _ ______ _ _____ / / / /___ (_) __ ____ _____ ____/ / / ____/ _/_/ ____/__ __ / / / /
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Code improvement: Coverity static analysis Valgrind dynamic analysis GABRIELE COSMO CERN, EP/SFT.
Dynamic Instrumentation - Valgrind  Developed by Julian Seward at/around Cambridge University,UK  Google-O'Reilly Open Source Award for "Best Toolmaker"
Object Lifetime and Pointers
CMSC 341 Lecture 2 – Dynamic Memory and Pointers (Review)
Chapter 7: User-Defined Functions II
YAHMD - Yet Another Heap Memory Debugger
Debugging Memory Issues
Valgrind Overview What is Valgrind?
Chapter 2: System Structures
Programmazione I a.a. 2017/2018.
Memory Allocation CS 217.
Test Case Test case Describes an input Description and an expected output Description. Test case ID Section 1: Before execution Section 2: After execution.
Valgrind Overview What is Valgrind?
Makefiles, GDB, Valgrind
Dynamic Binary Translators and Instrumenters
CSE 303 Concepts and Tools for Software Development
Presentation transcript:

RPROM , 2002 Lassi A. Tuura, Northeastern University Using Valgrind Lassi A. Tuura Northeastern University, Boston

September 2, 2002 Lassi A. Tuura, Northeastern University 2 Valgrind Introduction v Valgrind is a tool for checking memory access errors r Use of uninitialised memory r Reading or writing memory after it has been freed r Reading or writing off the end of a dynamically allocated block r Reading or writing inappropriate areas on the stack r Memory leaks (pointer to dynamically allocated memory lost forever) r Passing uninitialised and/or unaddressable memory to system calls r Mismatched use of malloc/new/new[] vs. free/delete/delete[] r Some misuses of POSIX pthreads v Easy to use: just run, no instrumentation required $ valgrind ls -laF v Powerful and accurate r Good at trapping errors, by design r Low false alarm rate: I have yet to see one r Gives precise error location, down to source line

September 2, 2002 Lassi A. Tuura, Northeastern University 3 Valgrind Introduction... v Relatively modest processing requirements r Runs 20-50x slower—noticeable but not earth-shattering slowdown – Graphical applications like IGUANA are sluggish but remain usable – Unlike other tools which can take days to run instrumented code! r Uses 2.5x+ memory – 9 bits for every byte of memory to track validity and addressability – Plus other overhead (tracking memory block owners, code cache, …) r In other words – There is little reason not use it—use it early, use it often – OK on a properly equipped development machine (e.g. lxcmsc1, lxcmsc2) v Additional goodies r Finds memory leaks, with exact allocation traces r Performance measurement using cachegrind

September 2, 2002 Lassi A. Tuura, Northeastern University 4 How Does It Work? v Valgrind is not a toy! It works on huge systems such as OpenOffice, KDE, Mozilla, ORCA, OSCAR v Tracks only two kinds of basic memory access errors r Is the address valid? – Is it outside currently allocated memory, e.g. memory already freed? – Catches uses of illegitimate memory addresses r Is the value in memory initialised? – Tracks the validity of every memory bit – Catches uses of uninitialised values – Flags attempts to compute values that would depend on uninitialised values (copying data is ok, only attempts to compute values are bad) v Enough to discover all sorts of memory-management nasties!

September 2, 2002 Lassi A. Tuura, Northeastern University 5 How Does It Work? v Valgrind runs your program on a synthetic CPU r It virtualises the real CPU and runs your program on the synthetic one r An attempt to execute code causes it to be instrumented – Dynamic just-in-time instrumentation for small sections of the code at a time (cached, sort of like just-in-time compilation in Java) – Intercepts and checks every memory access the program makes – Intercepts and checks memory regions passed to system calls v Special mode for cache profiling r Does no error checking, but… r Instruments for the cache architecture – Keeps track of the D1, I1 and L2 caches – Determines memory references that miss the caches  Produces a cachegrind.out which can be used to annotate source code

September 2, 2002 Lassi A. Tuura, Northeastern University 6 Getting Started v Valgrind is part of CERN CMS environment  Installed for RH 6.x and 7.x Linux in /afs/cern.ch/cms/system r Automatically in your $PATH if you are in CMS group (zh) v Just prefix the normal command with “valgrind” cd /afs/cern.ch/cms/Releases/OSCAR/OSCAR_1_3_2/src eval `scram runtime -csh` valgrind iguana v Use a host equipped for development r Needs a linux box with enough memory and CPU power – Most new boxes qualify, 1+ GHz and 512+ MB is “enough” r CMS provides lxcmsc1, lxcmsc2 (RH 6.x) and lxcmsd1 (RH 7.x) r CERN provides lxplus (RH 6.x), lxplus7 (RH 7.x)

September 2, 2002 Lassi A. Tuura, Northeastern University 7 Valgrind Output v Valgrind output looks like this ==3949== valgrind-1.0.1, a memory error detector for x86 GNU/Linux. ==3949== Copyright (C) , and GNU GPL’d, by Julian Seward. ==3949== Estimated CPU clock rate is 601 MHz ==3949== For more details, rerun with: -v Program output follows v Each error produces similarly prefixed output, with r The type of the error (e.g. “Invalid write of size 4”) r A stack trace indicating where the error occurred r Information about the memory location – E.g. a stack trace of where it was allocated, or who last free’d it, etc. v At the end, you’ll see: ==3949== ERROR SUMMARY: 67 errors from 10 contexts (suppressed: 30 from 2) ==3949== malloc/free: in use at exit: bytes in 3858 blocks. ==3949== malloc/free: allocs, frees, bytes allocated. ==3949== For a detailed leak analysis, rerun with: --leak-check=yes ==3949== For counts of detected errors, rerun with: -v

September 2, 2002 Lassi A. Tuura, Northeastern University 8 Error Output v Example ==3949== Invalid write of size 4 ==3949== at 0x40460BEA: IgApplication::run(int, char **) (…/IgApplication.cc:148) ==3949== by 0x80496FA: main (…/Iguana.cpp:19) ==3949== by […] ==3949== Address 0x410BC1D4 is 0 bytes after a block of size 4 alloc’d ==3949== at 0x : __builtin_vec_new (…/vg_clientfuncs.c:156) ==3949== by 0x404608A6: IgApplication::run(int, char **) (…/IgApplication.cc:103) ==3949== by 0x80496FA: main (…/Iguana.cpp:19) ==3949== by […] v Which means: r The error type is “Invalid write” (not a valid address) “of size 4” (four bytes, thus either a pointer, int or a float)  The location of the error is in IgApplication.cc, line 148 (in method IgApplication::run(int, char **) ); this is followed by a stack trace, by default four levels but you can change it with a command-line option r The memory accessed was four bytes at 0x410BC1D4, which was 0 bytes after a block of 4 bytes that was allocated by IgApplication.cc, line 103 (= off- by-one error at the end of the memory block)

September 2, 2002 Lassi A. Tuura, Northeastern University 9 Valgrind Errors #1 v Invalid read/write of size X r The memory address is not valid – It is not part of program image, stack or dynamically allocated memory – Usually either an access past the end of an existing block  The address detail says X bytes after a block of size Y, plus stack trace of where that block of memory was allocated – … or an access to already freed memory  The address detail tells where the memory was freed – … or something completely bogus (beyond current stack top, …)  Returning pointers to locals out of scope or using other garbage r The “of size X” tells how many bytes the machine instruction was trying to access; it may help to deduce what type of data was accessed – Size 1 usually implies char (or byte) data – Size 2 usually implies short – Size 8 usually implies double – Size 4 could be an int, float or a pointer

September 2, 2002 Lassi A. Tuura, Northeastern University 10 Valgrind Errors #2 v Conditional jump or move depends on uninitialised value(s) r An attempt to use a value that derives from uninitialised memory r Valgrind permits program to copy junk (= uninitialised data) to its heart’s content; only using uninitialised values in computations cause errors – Locating the origin of uninitialised value may be non-trivial – However: most causes are relatively easy to determine  Uninitialised member variables  Uninitialised local variables  Contents of dynamically allocated memory not cleared before use

September 2, 2002 Lassi A. Tuura, Northeastern University 11 Valgrind Errors #3 v Illegal free r An attempt to free memory that isn’t dynamically allocated r Valgrind keeps track of every dynamically allocated block – It knows exactly which arguments to free, delete are valid r Typical reasons include – Attempting to double delete objects – Attempting to delete objects not on the heap (= statically or stack-allocated objects) – Attempting to free an object that wasn’t allocated (e.g. an interior pointer to another object, or a totally garbage pointer value)

September 2, 2002 Lassi A. Tuura, Northeastern University 12 Valgrind Errors #4 v Mismatched free() / delete / delete [] r An attempt to free memory in a way incompatible with its allocation – Memory allocated with malloc() must be freed with free() – Memory allocated with new must be freed with delete – Memory allocated with new[] must be freed with delete[] r Valgrind knows for each memory block how it was allocated and produces an error when you use an incompatible deallocation method – In general, if you encounter new[]/delete mismatches, the correct fix is to remove manual allocation completely and to use std::vector or some other appropriate container!

September 2, 2002 Lassi A. Tuura, Northeastern University 13 Valgrind Errors #5 v Syscall param write(buf) contains uninitialised or unaddressable byte(s) r Sort of like previous errors, but the program is attempting to pass something invalid or uninitialised to a system call instead of doing it yourself r Valgrind checks memory parameters at system call boundaries and checks them like if the program was trying to do the accesses itself

September 2, 2002 Lassi A. Tuura, Northeastern University 14 Valgrind Errors #6 v Valgrind suppresses errors after a certain limit r Valgrind reports only unique errors. After certain number of errors is reached, it becomes more conservative and begins to suppress errors. After even more errors, it suppresses error reporting completely. r Both limits are controlled by command line options; if you want to keep on looking for errors, use the options to allow valgrind to continue to look for errors (if the errors are in code you can’t modify, try using suppression files to squelch errors from those modules) r If you see More than 300 errors detected. I’m not reporting any more. Final error counts may be inaccurate. Go fix your program! …do as it says!

September 2, 2002 Lassi A. Tuura, Northeastern University 15Tips v Build the code you analyse with debugging information r Not required, but produces more accurate information for stack traces – With GCC, debugging information does not affect code generation! r Rebuild the modules in your work area with scram build CXXUSERFLAGS=“-g” r Optionally: build without optimisation to get even more accurate stack traces (avoids having to wade through 15 levels of inlining) – Remove the “CXXFLAGS += -O2” from config/compilers.mk v Test early and often r Make valgrind part of your standard development and debugging routine r Suggestions to subsystem coordinators – Run valgrind regularly, especially before submitting tags for releases – Don’t submit new code to releases if valgrind reports errors  Don’t use ORCA as garbage generator, “dd if=/dev/urandom of=blah.ntpl” is faster and incurs much less general frustration

September 2, 2002 Lassi A. Tuura, Northeastern University 16Limitations v The tool makes very few errors! r Understood errors we can do nothing about (e.g. system libraries) or potential fake alarms can be filtered out with suppression mechanism v Most important issue: valgrind is a dynamic checking tool r The checks made depend on the code covered r Thus: the more tests, the better – Provide as many tests as possible, from large programs down to unit tests – First write some tests, then make the ones you have better to cover more – You can use OVAL tests with valgrind and vice versa – Make sure test programs cover pathological cases, not just the easy paths through the code that everybody checks for anyway r Add more tests! The pay off hugely, the more the longer we run!

September 2, 2002 Lassi A. Tuura, Northeastern University 17Links v Valgrind home page v Julian Seward’s presentation on valgrind v Valgrind at CERN CMS  Installed in /afs/cern.ch/cms/system – bin/valgrind, cachegrind : front-end executables – bin/vg_annotate : tool for presenting cachegrind results – lib/valgrind : valgrind’s own files v What’s this error I don’t understand? r Read the user guide, it is good! r Send a mail to CCS developers will answer r Report bugs through cmc/BugsRS/bug_reporting_system.cgihttp://cmsdoc.cern.ch/cgi- cmc/BugsRS/bug_reporting_system.cgi