16. Static Code Analysis

Embed Size (px)

DESCRIPTION

v

Citation preview

  • CS 308: Software Engineering 23/11/2013

    1

    STATIC TECHNIQUESDr Atul Gupta

    Static Techniques Powerful way to improve quality and productivity of

    software development Finds defects early in the development process Complementary with dynamic approach

    Finds defects rather than failures Performed manually or using static analysis tools Includes

    Peer review Walkthrough Code Inspection Static analysis

    HarryHighlight

  • CS 308: Software Engineering 23/11/2013

    2

    Common Coding Errors Memory Leaks

    char* foo(int s){

    char *output;if (s>0)

    output=(char*) malloc (size);if (s==l)

    return NULL; /* if s==l then memory leaked */return(output);

    }

    When an application dynamically allocates memory, and does not free that memory when it is finished using it, that program has a memory leak.

    void func() { char *p = new char[10]; some_function_which_may_throw(p); delete [ ] p;

    }

    try {

    int* pValue = new int(); if (someCondition) { throw 42; } delete pValue;

    } catch (int&) { }

    Common Coding Errors Freeing an already freed resource

    main (){

    char *str;str = (char *)malloc (10);if (global==0)

    free(str) ;free (str) ; /* str already freed

    }

  • CS 308: Software Engineering 23/11/2013

    3

    Common Coding Errors Null dereferencing

    char *ch=NULL;if (x>0){

    ch='c ' ;}printf ("\%C" , *ch); /* ch may be NULL*ch=malloc(size);ch = 'c'; /* ch will be NULL if malloc returns NULL

    switch(i){case 0: s=OBJECT_l; break;case 1: s=0BJECT_2;break;}return(s); /* s not initialized for values other than 0 or 1 */

    Common Coding Errors Synchronization errors

    Deadlocks, Race conditions Array index out of bound Arithmetic exceptions

    Divide by zero, floating point String handling errors Use of & in place of &&

    if (object != null & object.getTitle( ) != null)/* Here second operation can cause a null dereference */

  • CS 308: Software Engineering 23/11/2013

    4

    Common Coding Errors Buffer Oveflow

    char A[8] = {}; unsigned short B = 1979;

    strcpy(A, "excessive");

    variable name

    A B

    value [null string] 1979

    hex value 00 00 00 00 00 00 00 00 07 BB

    variable name

    A B

    value e x c e s s I v 25856

    hex value 65 78 63 65 73 73 69 76 65 00

    Source: Wikipedia

    Static Techniques Inspection (Reviews)

    Formal Inspection Peer-Reviews Walkthrough Informal reviews

    Program Analysis Static analysis Dynamic analysis

  • CS 308: Software Engineering 23/11/2013

    5

    Inspection A general verification approach Earlier applied to code, later to design and requirements Can start early in the SDLC Complementary to testing

    Non conformance of the artifact, missing requirements, design defects, inconsistent interface specifications

    Other advantages Increase communication Better understanding Increase productivity Improve quality

    Code Inspection (CI) Aim is to identify defects in the code Generally applied when code is successfully compiled

    and other for static analysis is performed Approaches

    Check-list based Perspective based Scenario based Stepwise abstraction

  • CS 308: Software Engineering 23/11/2013

    6

    Check-List based Code Inspection Do all the pointers point to some object? (Are there any

    "dangling pointers"?) Are the pointers set to NULL where needed? Are pointers being checked for NULL when being used? Are all the array indexes within bound? Are indexes properly initialized? Are all the branch conditions desirable (not too weak, not

    too strong)? Will a loop always terminate (no infinite loops)? Is the loop termination condition correct?

    Check-List based CI cont Where applicable, are the divisors tested for zero? Are imported data tested for validity? Do actual and formal interface parameters match? Are all variables used? Are all output variables assigned? Can statements placed in the loop be placed outside the

    loop? Are the labels unreferenced? Will the requirements of execution time be met? Are the local coding standards met?

    HarryHighlight

    HarryHighlight

    HarryHighlight

    HarryHighlight

    HarryHighlight

    HarryHighlight

    HarryHighlight

    HarryHighlight

    HarryHighlight

    HarryHighlight

    HarryHighlight

    HarryHighlight

    HarryHighlight

    HarryHighlight

  • CS 308: Software Engineering 23/11/2013

    7

    Inspection Process Phases in a formal review Planning Kick-off Preparation Review meeting Rework Follow-up

    Team structure Moderator Author Writer Reviewer (roles)

    Code Inspection Effective but time consuming An alternative is Code Reading (Desk-review or Peer-

    code-review)

    HarryHighlight

  • CS 308: Software Engineering 23/11/2013

    8

    Static Analysis Automated code review techniques Focuses on detecting errors in the code without knowing

    about what it is supposed to do Two variants

    Detect error patterns Detect errors

    Identified problems may or may not be (leading) to errors False positive (Soundness) False Negative (Completeness)

    Goal is to be as sound and complete as possible Usually performed using software tools

    Static Analysis: Detecting Error Patterns Performed through Dataflow and Control-flow analysis,

    Symbolic execution, Model checking, and others Identify anomalies like

    Idempotent operations Assignments that were never read Dead code Conditional branches that were never taken Null dereferencing Index out-of-bound Divide by zero Release resources like memory, files Buffer overflows .

    HarryHighlight

    HarryRectangle

    HarryRectangle

    HarryHighlight

    HarryHighlight

    HarryTypewriter??

    HarryTypewriter

    HarryHighlight

    HarryHighlight

    HarryHighlight

    HarryHighlight

    HarryHighlight

  • CS 308: Software Engineering 23/11/2013

    9

    void print_to_file (string filename){

    if (path_exists(filename)) {// FILENAME exists; ask user to confirm overwritebool confirmed = confirm_loss(filename);if (!confirmed)

    return;}// Proceed printing to FILENAME...

    Correctness Property

    P

    Model

    Property

    P

    Implies

    (automatic

    test of logical

    inference)Automatically

    construct

    models for

    analysis

    Class Structure And Inheritance

    State MachineModel

    Control/Data FlowGraph

    Automatic check

    of derived model

    Manual Inspection?(impractical or impossible)

    should haveHow Static Analysis Works?

    /* Dead code /for (cl; c2; c3) {

    if (C) {break; }

    else {break; }

    stmt; /*this is unreachable*/

    Static Analysis: Detecting Error Patterns/* idempotent operation */for (i=0; i< size; i++) {

    if (pv[i] != -1 && pv[i] >= val)pv[i] = pv[i]++ ; /*error*/

    } /* Redundant assignment */do {

    if (signal_pending(current)){ err = - ERRSTARTSYS; break; }

    } while (condition);return 0; /*value of err lost*/

    /* Unnecessary check */if (!(error && ... && ...)){

    return -1; }if (error) /*redundant check*/{ ... }

    HarryHighlight

    HarryHighlight

  • CS 308: Software Engineering 23/11/2013

    10

    Static Analysis: Detecting Errors Directly look for errors Many tools of this type are commercially available or developed

    in-house Level of false positive is lower PREFIX identifies

    Using uninitialized memory Dereferencing uninitialized pointer Dereferencing NULL pointer Dereferencing invalid pointer Dereferencing or returning pointer to freed memory Leaking memory or some other resource like a file Returning pointer to local stack variable Divide by zero

    PREFIX results1. #include 2. #include 3. char *f(int size)4. {5 . char *result;6. if (size>0)7. result = (char *)malloc(size) ;8. if (size==l)9. return NULL;10. result [0] = 0 ;11. return result ;12. }

    8: leaking memory (path: 5 6 7 8)

    10: dereferencing NULL pointer 'result'

    (path: 5 6 7 10)

    HarryHighlight

    HarryHighlight

    HarryHighlight

    HarryHighlight

    HarryHighlight

    HarryHighlight

    HarryHighlight

    HarryHighlight

    HarryHighlight

  • CS 308: Software Engineering 23/11/2013

    11

    Static Analysis Tools Language Dependent Ex: Java (Open Source Tools)

    FindBugs (University of Maryland) http://findbugs.sourceforge.net/

    Googles CodePro PMD

    http://pmd.sourceforge.net/ UCDetector CheckStyle

    http://checkstyle.sourceforge.net/

    Different Tools find different Bugs

  • CS 308: Software Engineering 23/11/2013

    12

    Summary Besides testing, other defect finding techniques include

    Inspection Static analysis Dynamic analysis

    Inspection can be employed early in the development and has many advantages

    Tool supported static analysis can be another effective way of identify defects in the code, however, high value of false positive may not justify the efforts worth doing it.

    References Pankaj Jalote. An integrated Approach to Software

    Engineering, Narosa 2005