Home

information

image

Contents

1. C C Build Process elt A brief review of steps involved in building and running a program gt Preprocessing header files inclusion and macro processing output in pure C C code gt Compiling translation of pure C C code to assembly language gt Assembling translation of assembly code into binary object code C C Build Process elt gt Linking linker combines a number of object files and libraries to produce executables or libraries gt Dynamic Loading libraries or library parts required by a dynamically linked executables are loaded prior to actual running the executables CERN School of Computing Preprocessor e The C C preprocessor expands macros declares dependencies drives conditional compilation Preprocessor operations are performed at textual level This can make tracking down missing declaration difficult or lead to semantic problem Preprocessor X e If you suspect a preprocessing problem let the preproccessor expand the file for examination e Example gcc E Stops after the preprocessing stage without running the compiler The output is preprocessed source code which is sent to the standard output Dynamic Storage Allocation dt e In C C you have to explicitly allocate and deallocate dynamic storage through malloc free or new delete e If memory is de allocated incorrectly it can cause problems at run time e g memory corruption memo
2. e Breakpoints stop a program when needed The program runs normally until it is about to execute the piece of code at the same address of the breakpoint at that point the program drops back into the debugger and we can look at variables or continue stepping through the code e Breakpoints are fundamental in interactive debugging iS Breakpoints dt e Breakpoints have many options They can be Set up on a specific line number at the beginning of a function at a specific address conditionally 40 Debugging Commands X After stopping e g at a breakpoint every debugger can e execute next program line stepping over any function calls in the line e execute next program line stepping into any function calls in the line e continuing running your program Watchpoints JY e Watchpoints are a particular type of breakpoints e A watchpoint stops the code whenever a variable changes even if the line doesn t reference the variable explicitly by name A watchpoint looks at the memory address of the variable and alerts you when something is written to it E Binary Split dt e In large programs adding breakpoints for every iteration of the loop is prohibitive e It is not necessary to step through each one in turn but employ a technique Known as binary split We place a breakpoint after the first of the code and run it If the problem has not showed up then it is likely
3. double malloc sizeof double 60 for int i 0 i lt 100 i histo i i i return 1 Compile the program with gcc g lefence Wall o memerror memerror cpp 96 Valgrind X e Valgrind checks every reading and writing operation on memory intercepting all calls to malloc free new delete e Valgrind can detect problems like usage of uninitialised memory reading from writing to freed memory reading from writing beyond the borders of allocated blocks Valgrind X e Valgrind tracks every byte of the memory with nine status bits one for the accessibility and the other eight for the content if valid e As a consequence Valgrind can detect uninitialised and does not report false errors on bitfield operations e Valgrind can debug almost all dynamically linked ELF x86 executables without any need for modification or recompilation Example Memory Error ES An array of 60 elements is created The program tries to fill it with 100 elements int main int argc char argv double histo new double 60 for int i 0 i lt 100 i histo i 2 i i return 1 Compile the program with g g Wall o memerror memerror cpp 99 Example Memory Error at valgrind gdb attach yes error limit no memerror 3252 Invalid write of size 8 3252 at 0x80483DA main memerror cpp 9 3252 by 0x4026F9B1 libc start main in lib libc so 6 3252 b
4. to be a fault with the last half E Binary Split dt From here we can ask the question again reducing the area under test to the first or the second quarter This question can be asked repeatedly until we re down to just one line or sufficiently small routine that we can step through line by line A binary split can limit the search area of a 1000 line program to just 10 steps 44 Advanced Software Development Engineering i DDD GUI for gdb ho oF compat EI Edit view Fregrm Grarirds Zomme Souree Dot Hh o ARRAS Date 1 bash Display Debugger ut rere E cod nr ckhun ids CECT Suri Powerful interface to gdb with extra features Pasta F 4 nz starter rr fnt dr f Fs z petri AA A A D K ts Se Sd a ae La E a Pacha e aor rra nit exltrd ee Seene CEA Tio kree Pi HI del dire nel called rew Fi Cpamesh r ine ne 53 na fetiiea dz FF Fr callan Fen file pacTesh ar ling 24 1 FEI Sn 01 allae Fro file t mzhl at line uc 24 ENEE at Tien Try it ON our zB SC Ma i ay fal 28 uz 4 fog bt zai ZY erit E I DEE first example lrash bc31 A dec ara is m bashdlic zz xm 4 d boshdb 32 A Su iti ines aiku dane CERN School of Computing Part Ill C C Related Problems and Solvers i Part Three C C Related elt Problems and Solvers A Preprocessor B Dynamic Storage Allocation C System Call Examination
5. message is greater than or equal to the priority of the category then logging takes place otherwise the message is ignored Log4cpp Example ES There are six initial steps to using a log4cpp log gt Instantiate an appender object that will append to a log file log4cpp Appender app new log4cpp FileAppender FileAppender logs testlog4cpp log gt Instantiate a layout object log4cpp Layout layout new log4cpp BasicLayout gt Attach the layout object to the appender app gt setLayout layout 28 Log4cpp Example Ear nea gt Instantiate a category object by calling the static function log4cpp Category main_cat log4cpp Category getlnstance main cat gt Attach the appender object to the category as an additional appender in addition to the default standard out appender or set Additivity to false first and install the appender as the one and only appender for that category main cat setAppender app Seta priority for the category main cat setPriority log4cpp Priority INFO 29 Log4cpp Example ES Some examples main_cat info This is some info main_cat debug This debug message will fail to write main_cat alert All hands abandon ship you can log by using a log method with a priority main_cat log log4cpp Priority WARN This will be a logged warning this would not be logged if priority DEBUG because the category priority is set to INFO ma
6. of Debugging e Part Il General Debugging e Part Ill C C Related Problems and Solvers 5 Advanced Software Development Engineering CERN School of Computing Part General Aspects of Debugging Part One General Aspects of ot Debugging The debugging process involves Localising a bug Classifying a bug e Understanding a bug e Repairing a bug Advanced Software Development Engineering KR fi Localising a Bug dt include lt iostream gt void c void A scoping example void c void function prototype Some other code X 10 intx 1 global variable Some other code j int main int x 5 local to main Some other code You know what your code should do while x 100 You notice it does not do that c Il c uses global SO Noticing a bug is easy Some other code you might say return O CERN Classifying a Bug dt e Since experiences with bugs have often a common background we may attempt a classification Syntactical Errors errors your compiler should catch Build Errors errors from using object files not rebuilt after a change in some source Basic Semantic Errors using uninitialized variables dead code type problems Semantic Errors using wrong variables exchanging operator e g amp instead of amp amp Classifying a Bug oS A funny physical classification Bohrbugs and Heisembugs Bohrbugs ar
7. CERN School of Computing Paolo Adragna Universita degli Studi di Siena MAR qu t E JN E DIN aie um e Gio gt Msz sya Debugging Techniques Why Debugging a Debugging is a fundamental part of programmers everyday activity but some people consider it an annoying option Advanced Software Development Engineering USS Yorktown 1998 sho oF Camper A crew member of the guided missile cruiser USS Yorktown mistakenly entered a zero for a data value which resulted in a division by zero The error cascaded and eventually shut down the ship s propulsion system The ship was dead in the water for several hours because a program didn t check for valid input reported in Scientific American November 1998 Mars Climate Orbiter 1999 tO The process did not specify The 125 million dollar Mars Climate P System of measurement Orbiter is assumed lost by officials at IO Pe used on the project As NASA The failure responsible for loss 2 SUll one of the of the orbiter is attributed to a failure of Ce V opment teams used NASA s system engineer process Imperial measurement while the other used the metric system When parameters from one module were passed to another during orbit navigation correction no conversion was performed resulting in the loss of the craft http mars jpl nasa gov msp9g orbiter 4 UU IS Lecture Programme Stel of Compt Part General Aspects
8. ENK ER Ze E Ge See Session Edit View Settings Hei Edit me Session Ed View Sms Mele Help Ladragnaf ipcatlas3 examples ll E total 55 E adragna atlas 1352 b charset cpp rwu r r adragna atlas 4928 58 charset out E ES ru r r adragna atlas 145 56 list tmp rw r r adragna atlas 1672 26 strace c rwu r r adragna atlas 1816 strace c Ern adragna atlas 87 6 716 strace out rWuxr xr x adragna atlas 19375 2 stracex Ladragnal pcatlas3 examples I stracex list Can t open input file list tmp adragnafipcatlas3 examples1 fj a New Mal Lal Shell Mo 2 CERN strace example D oF Campa Let s start strace strace o strace out stracex list brk 0x804a76c 0x804a76c brk 0x804b000 0x804b000 open list O RDONLY 2 1 ENOENT No such file or directory write 2 C 1 1 write 2 a 1 1 write 2 n 1 1 write 2 V 1 1 write 2 t 1 1 write 2 1 1 write 2 o 1 1 write 2 p 1 1 write 2 e 1 1 write 2 n 1 70 CERN Acknowledgments cb m would like to thank very much J H M Dassen and I G oprinkhuizen Kuyper for letting me use some of their material on debugging techniques A big thank also to P F Zema my collegue in ATLAS for useful technical comments and ideas exchange on Linux debugging Thanks to E Castorina for a critical review of the lecture slides 71 CERN Bibliography dt e For more
9. chnique is encountered too often t consists of ad hoc insertion of lot of printing statement to track the control flow and data values during the execution of a piece of code e Disadvantages Itis very ad hoc It clobbers the normal output Slows the program down considerably Often it does not help output buffered 20 The Abused cout Technique xx e If you consider using debugging check out the use of assertion and of a debugger much more effective and time saving e In some circumstances cout debugging is appropriate Some tips Produce output on standard error unbuffered Do not use printing statements directly define a macro around them Use debugging level to manage the amount of debugging information 24 cout Technique Example S ifndef DEBUG H define DEBUG H include lt stdarg h gt if defined NDEBUG SS defined _ GNUC _ gcc s cpp has extensions it allows for macros with a variable number of arguments We use this extension here to preprocess pmesg away define pmesg level format args void O else void pmesg int level char format print a message if it is considered significant enough Adapted from K amp R2 p 174 endif endif DEBUG_H 22 CERN Logging dt e Logging is a common aid to debugging e Heavily used by daemon and services e Itis a real solution to the cout technique It records information messages which monitor
10. e Club d Italia an Italian organisation that helps with car troubles Advanced Software Development Engineering ISS ACI Debugging Technique rm ACI not only a joke e Based on a simple principle the best way to learn thing is to teach them In ACI debugging you find a bystander and explain to her how your code works This forces you to rethink your assumption and explain what is really happening It can be a form of peer review se Engineering Walking through the Code ES This technique is similar to the ACI technique The recipe e Print your code eave your terminal e Go to cafeteria e Take the beverage of your choice if possible with caffeine and sugar e Read your code and annotate it carefully The Debugger dt e When every other checking tool fails detecting the problem then it is debugger s turn e A debugger allows to work through the code line by line to find out where and why it is going wrong e You can interactively control the program run Stop it at various times inspect variables change code flow whilst running CERN The Debugger dt e In order to make use of a debugger a program must be compiled with debugging information inserted debugging symbols Debugging symbols describe where the function and variables are stored in memory e An executables with debugging symbols can run as a normal program even if slightly slower Breakpoints dt
11. e deterministic a particular input will always manifest them Heisembugs are random difficult to reproduce reliably Understanding a Bug a e Understand a bug fully before attempting to fix it e Ask yourself some questions Have found the source of the problem or only a symptom Have made similar mistakes especially wrong assumptions elsewhere in the code Is this only a programming error or is there a more fundamental problem e g incorrect algorithm 11 n Repairing a Bug dt e Repairing a bug is more than modifying code Make sure you document your fix in the code and test it properly e After repair what did you earn from it How did you notice the bug This may help you writing a test case How did you track it down This will give you a better insight on the approach to choose in similar circumstances What type of bug did you encounter 12 n Repairing a Bug dt e After repair what did you learn from it Do you encounter this bug often If so what could you do to prevent it from re occurring What you have learnt is valuable try to communicate it with your collegues Unjustified assumptions e After repairing a bug write a test case to make sure it does not happen again Advanced Software Development Engineering CERN School of Computing Part Two General Debugging Part Two General Debugging SX A B C D E F ACI Debugging T
12. echnique G Walking Through The Code H The Debugger o Exploiting Compiler Feature Reading The Right Documentation ee ee The Abused cout Debugging Technique Logging Defensive Programming T _ UL Exploiting Compiler Features SO General A good compiler can do an amount of static analysis on your code the analysis of those aspects that can be studied without execution e Static analysis can help in detecting a number of basic semantic problems e g type mismatch dead code Exploiting Compiler Features ES gcc For gcc there are a number of options that affect which static analysis can be performed Wall W e Also recommended when writing new code Wshadow Wpointer arith Wcast equal Wcast align Wstrict prototype Exploiting Compiler Feature SO gcc e A number of optimizations are supported some of these trigger gcc to do extensive code flow analysis removing dead code e Recommended for normal use O2 Warning optimisation kills debugging so you have to choose Example gcc O3 or gcc g O0 i Sc Reading the Right ob Documentation e Take the time to find at your fingertips relevant documentation for your task your tools your libraries your algorithm e You do not need to know everything e You need to be aware what documentation Is relevant and what is its purpose The Abused cout Technique CERN School of Computing e This te
13. famous bugs take a look to Prof G Santor s site http infotech fanshawec on ca gsantor Computing FamousBu gs htm e J H M Dassen 1 G Sprinkhuizen Kuyper Debugging C and C code in a Unix environment Universiteit Leiden Leiden 1999 Parr Learn the essential of debugging IBM developerWorks journal Dec 2004 e S Best Mastering Linux debugging techniques IBM developerWorks journal Aug 2002 e S Goodwin The Pleasure Principle Linux Magazine 31 2003 64 69 72 Bibliography lS e gdb User Manual e gcc User Manual e Valgrind User Manual e F Rooms Some advanced techniques in C under Linux e W Mauerer Visual Debugging with ddd The Linux Gazette Jan 2001 M Budlong Logging and Tracing in C Simplified Sun Developers Technical Articles 2001 e S Goodwin D Wilson Walking Upright Linux Magazine 27 2003 76 80 e J World Using Log4c online at http jefficus usask ca 73 Advanced Software Development Engineering CERN School of Computing Backup Slides 74 N Localising a Bug dt e You know what your code should do you notice it does not do that so noticing a bug is easy you might say e Noticing a bug implies testing so this easiness is completely deceptive e In case of a test failure you have to see what went wrong so prepare your tests carefully i Introduction lS e When your program contains a bug it is likely that somewhere in the code a conditi
14. in cat log priority Importance depends on context Other example in the cited paper see Bibliography 30 i Sc Log4cpp Logfile Example soo oF Comput A tipical logfile 995871335 INFO main cat This is some info 995871335 PANIC main cat All hands abandon ship 995871335 WARN main cat This will be a logged warning 995871335 ALERT main cat Importance depends on context 995871335 ERROR main cat And this will be an error 995871335 INFO main cat info 995871335 NOTICE main cat notice 995871335 WARN main cat warn 31 Defensive Programming and dt the assert Macro e Take a look at your code in every part you make a lot of assumptions about other parts e Assertions are expressions you should evaluate to be true at a specific point in your code e f an assertion fails you have found a problem possibly in the assertion more likely in the code e t make no sense to execute after an assertion fails i Defensive Programming and AE the assert Macro e Writing assertions makes your assumptions explicit e In C C you can include lt assert h gt and write the expression you want to assert as macro argument e With assert macros your program will be aborted when an assertion fails e An assertion failure is reported by a message 33 Advanced Software Development Engineering ISS ACI Debugging Technique rm ACI only a joke he technique name derive from Automobil
15. loc in usr lib valgrind vgskin memcheck so 3252 by 0x80483A8 main memerror cpp 7 3252 by 0x4026F9B1 libc start main in lib libc so 6 3252 by 0x80482F0 start S 102 3252 Attach to GDB Return N n Y y C c 62 j Example Tracking Memory x Leak include lt string gt using namespace std string amp xform string copy const string amp input Typical Error Returning a Heference to uu a Dynamically int main int argc char argv Allocated Object std string original am an automatic variable string amp stringref xform string copy original string amp xform string copy const string amp input string xformed_p new string l will probably be leaked Il maybe do some processing here return xformed_p Callers will almost never free this object We i System Call Examination dt A System Call Tracer allows you to examine problems at the boundary between your code and operating system e The tracer shows what system calls a process makes with parameters and return value e A tracer cannot tell you where a system call was made in your code The exact place has to be reconstructed CERN strace the Linux System Tracer dt e strace is a powerful tool which shows all the system calls issued by a user space program e strace displays the arguments to the calls and returns values in symbolic form e s
16. on you believe to be true is actually false e Finding your bug is a process of confirming what you believe is true until you find something that is false e My program doesn t work is not an acceptable statement i Introduction lS e The importance of the way how to find errors and fix them in the life cycle of a software product is a task whose importance cannot be stressed enough over and over e Finding errors is not just an unavoidable part in the development cycle but vital part of every software system s lifespan
17. ry leak e Common errors are trying to use memory that has not been allocated yet to access memory already deallocated deallocating memory twice 52 i Memory Allocation Debugging 5 Tools When you have a memory problem the best it can happen is a program crash Basically two categories of tools e External libraries to be included and or linked MEMWATCH Electric Fence e Executables which controls program s run YAMD Valgrind CERN Electric Fence lS Electric Fence is C library for malloc debugging t exploits the virtual memory hardware of the system to check if and when a program exceeds the borders of a malloc buffer e At the borders of such buffer a red zone is added When the program enters this zone it is terminated immediately e The library can also detect when the program tries to access memory already released i Electric Fence lS Because Electric Fence uses the Virtual Memory hardware to detect errors the program will be stopped at the first instruction that causes a certain buffer to be exceeded e Therefore it becomes trivial to identify the instruction that caused the error with a debugger e When memory errors are fixed it is better to recompile the program without the library Example Memory Error ES An array of 60 elements is created The program tries to fill it with 100 elements int main int argc char argv double histo histo
18. the status of your program hey can even form the basis of software auditing A sensible method is to classify log messages and label them with a priority level 23 log4cpp C Logging c Log4cpp has 3 main components gt Categories gt Appenders gt Layouts A layout class controls what the output message is going to look like You may derive your own classes from Layout or use the provided SimpleLayout and BasicLayout 24 log4cpp C Logging a An appender class writes the trace message formatted by a layout object out to some device log4cpp comes with classes to append to standard output a named file or a string buffer gt FileAppender gt OstreamAppender gt StringQueueAppender Once again you may derive your own appender e g to a socket a shared memory buffer on log4cpp C Logging a A category class does the actual logging The two main parts of a category are its appenders and its priority The priority of a category can be set to 1 NOTSET 5 WARN 9 FATAL 2 DEBUG 6 ERROR EMERG in ascending order of importance level 3 INFO 7 CRIT 4 NOTICE 8 ALERT CERN log4cpp C Logging al Each message is logged to a category object The category object has a priority level Priority controls which messages can be logged by a particular class The message itself also has a priority level as it wends its way to the log If the priority of the
19. trace receives information from the kernel and does not require the kernel to be built in any special way i strace example z include lt iostream gt for I O include string for strings include fstream for file I O include lt cstdlib gt for exit using namespace std int main int argc char argv d string filename string basename string extname string tmpname const string suffix tmp 66 strace example dt for each command line argument which is an ordinary C string for int i21 i lt argc i filename argv i process argument as file name string size_type idx filename find search period in name if idx string npos file name does not contain any period tmpname filename HERE IS THE ERROR tmpname filename suffix j else tmpname filename print file name and temporary name cout filename 2 tmpname endl USEFUL j 67 strace example dt ifstream file tmpname c str if Ifile cerr lt lt Can t open input file lt lt filename lt lt tmp n exit EXIT FAILURE char c while file get c cout put c Create a simple text file and run the program e The program won t find the input file yx IC CA strace example n sie It is JJ adrag D El Hr at aS die Datal inve arte dcs Cleza ampli les ELE AM Kons Elise a ET j z
20. y 0x80482F0 start S 102 3252 Address 0x410B2204 is 0 bytes after a block of size 480 alloc d 3252 at 0x4002ACB4 malloc in usr lib valgrind vgskin memcheck so 3252 by 0x80483A8 main memerror cpp 7 3252 by 0x4026F9B1 libc start main in lib libc so 6 3252 by 0x80482F0 start S 102 3252 3252 Attach to GDB Return N n Y y C c 60 i Sc Example Forgetting the sho Computing Initialisation Consider the following simple program include lt iostream gt int main int argc char argv double k double interval atof argv 1 if interval 0 1 k 3 14 if interval 0 2 k 2 71 2 5 0 exp k std cout lt lt lt lt lt lt n return 1 Compile with g Im g o val3 initia1 cpp e he error doesn t cause a crash e The user has to give an argument as an input e f the input value is not equal to 0 1 or 0 2 the value is not initialized e We may get unexpected results i Sc Example Forgetting the sho Computing Initialisation valgrind gdb attach yes error limit no leak check yes memerror 3252 Invalid write of size 8 3252 at 0x80483DA main memerror cpp 9 3252 by 0x4026F9B1 libc start main in lib libc so 6 3252 by 0x80482F0 start S 102 3252 Address 0x410B2204 is 0 bytes after a block of size 480 alloc d 3252 at 0x4002ACB4 mal

Download Pdf Manuals

image

Related Search

Related Contents

Tschernobyl bis Fukushima - Hilfe für Kinder aus Tschernobyl  GE GFDN245 User's Manual    IFS MC201-1P/1FS User Manual  Kensington Folio SecureBack™ Protective Folio Case for New iPad & iPad2  Samsung 700T  組付・取扱説明書  Les Cahiers de la Fourmi - extrait de Batimo CM  

Copyright © All rights reserved.
Failed to retrieve file