Course on "Quality and Certification" - MISRA C coding standard for software quality - RCL Dipartimento di Sistemi e ...

Page created by Nathan Douglas
 
CONTINUE READING
Course on "Quality and Certification" - MISRA C coding standard for software quality - RCL Dipartimento di Sistemi e ...
MISRA C coding standard for
      software quality

   Course on "Quality and
       Certification"

        University of Florence
Department of Mathematics and Informatics
              Florence, Italy
Course on "Quality and Certification" - MISRA C coding standard for software quality - RCL Dipartimento di Sistemi e ...
The background for the MISRA-C - 1

Programmers make mistakes
With the syntax of C it is relatively easy to
make typing mistakes that lead to valid code.
  – E.g., type “=” (assignment) instead of “==”
  – Or an extra semi-column in an “if(expression);“

The philosophy of C is to assume that the
programmers know what they are doing
  – particularly weak for “type checking” e.g., store a
    floating-point number in an integer that is used to
    represent a true/false value.
AA 2019-2020             Quality and Certification
Course on "Quality and Certification" - MISRA C coding standard for software quality - RCL Dipartimento di Sistemi e ...
The background for the MISRA-C - 1
Compiler doesn’t do what the programmer expects
  – a programmer can assume one thing about the meaning
    of a construct, while the compiler can interpret it
    quite differently
  – C undefined behaviours
The compiler contains errors
  – They may, for example, not comply with the language
    standard in certain situations, or they may simply
    contain “bugs”
Run-time errors
  – C is generally poor in providing run-time checking e.g.,
    divide by zero, overflow, etc.
AA 2019-2020              Quality and Certification
Course on "Quality and Certification" - MISRA C coding standard for software quality - RCL Dipartimento di Sistemi e ...
We try an example…

auth_overflow.c : bad SW coding…

                  What is the
               «REAL PROBLEM»?

AA 2019-2020        Quality and Certification
Course on "Quality and Certification" - MISRA C coding standard for software quality - RCL Dipartimento di Sistemi e ...
AA 2019-2020   Quality and Certification
Course on "Quality and Certification" - MISRA C coding standard for software quality - RCL Dipartimento di Sistemi e ...
Avoid the problems!

Roughly 80% of software defects when using
the C or C++ language, are attributable to the
incorrect usage of 20% of the language
constructs
  If the usage of the language
  can be restricted to avoid
  this subset that is known to
  be problematic, then
    – the quality of the ensuing
      software is going to greatly
      increase
AA 2019-2020                Quality and Certification
Keep it simple!

It is easy to write code that is difficult to
read
Prevent developers from writing “clever”
code
  – Especially in safety-critical contexts!

Write code that is:
  – easy to understand
  – easy to maintain
  – easy to test
AA 2019-2020             Quality and Certification
What is a Coding Standard

Coding Standards can be composed of:
  – Common sense rules
     Eg: Don’t mix signed and unsigned types
  – Reduced language subset
     Eg: Ensure that «goto» or «malloc» is not used
  – Style guidelines
     Eg: Ensure that the “tab” character is not used
  – Naming conventions
     Eg: Ensure that all public functions start with _
  – Quality & complexity metrics
     Eg: Ensure that all functions have a low cyclomatic complexity

AA 2019-2020                       Quality and Certification
Which coding standard?

                                               VDC Research White
                                               Paper, 2011.
                                               Surveyed 600
                                               developers of
                                               systems and
                                               embedded sw

AA 2019-2020       Quality and Certification
MISRA
Motor     Industry                 Software        Reliability
Association
  – manufacturers, component suppliers and
    engineering consultancies

Their goal:
  – promote best practice and assist in developing
    safety-related electronic systems in road vehicles
    and other embedded systems.

AA 2019-2020           Quality and Certification
MISRA-C: Myths and Legends

Does Not
  – Find bugs
  – Define style or metric guidelines
  – Stop developers writing code
  – Say the rules must be followed all the time
Does
  – Require controlled deviations
  – Require style and metrics be applied
  – Force developers to think

AA 2019-2020           Quality and Certification
MISRA-C a bit of history

MISRA-C:1998 (aka MISRA-C1)
  – “Guidelines for the use of the C language in vehicle
    based software”
  – Compatible with ISO/IEC 9899:1990 (aka C90)
MISRA-C:2004(aka MISRA-C2)
  – “Guidelines for the use of the C language in critical
    systems”
  – Remains compatible with ISO/IEC 9899:1990 (aka
    C90)
MISRA C:2012 (aka MISRA-C3)
  – “Guidelines for the use of the C language in critical
    systems”
  – Adds compatibility with ISO/IEC 9899:1999 (aka C99)
AA 2019-2020              Quality and Certification
MISRA-C –The 2012 Edition

Published early 2013
159 Guidelines in total
  – 16 Directives
     • 9 Required
     • 7 Advisory
  – 143 Rules
     • 10 Mandatory
     • 101 Required
     • 32 Advisory

Includes              a   compliance                     and   deviation
policy.
AA 2019-2020                 Quality and Certification
Directives - What is a Directive?
A directive is a guideline for which it is NOT
possible to provide the full description necessary
to perform a check for compliance.
  – Additional information, such as might be provided in
    design documents or requirement specifications, is
    required in order to be able to perform the check.
►    In other words, rules whose compliance is more
     open to interpretation, or relates to process or
     procedural matters.

Note: Compliance is still required – just as for
the Rules.
AA 2019-2020             Quality and Certification
Directive example – 1 (Required)
Directive: Run-time failures shall be minimized.
Rationale
  – The C language was designed to provide very limited built-in
    run-time checking. This places the burden on the
    programmer...

What does this mean?
  – Techniques to avoid run-time failures should be planned and
    documented, for example in design standards, test plans
    and code review checklists.
  – Dynamic checks should be added wherever there is a
    potential for errors to occur

Problem areas
  – arithmetic errors (e.g., divide by 0), array bound errors,
    function parameters, pointer arithmetic/de-referencing
AA 2019-2020               Quality and Certification
Directive example – 2 (Required)

Directive. The validity of values passed to library
functions shall be checked.
Rationale
  – The C standard does not require the standard library
    to check the validity of parameters passed to them.

What does this mean?
  – Dynamic checks should be added wherever there is a
    potential for errors to occur

Problem areas
  – Libraries ctype.h, math.h, and string.h (and others!)
AA 2019-2020             Quality and Certification
Directive examples – 3 (Advisory)

Sections of code should not be “commented
out”
  – Use #if or #ifdef instead:

Why?

AA 2019-2020            Quality and Certification
Directive examples – 3 (Advisory)

Sections of code should not be “commented
out”
  – Use #if or #ifdef instead:
  – C does not support nested comments, it is
    dangerous to comment large portions of code.
#ifdef FLAG
/* These lines will be "commented out"
      if FLAG is undefined */
#endif

     Still risky – leaving #ifdefs in code after they’ve outlived
     their usefulness
AA 2019-2020                Quality and Certification
Directive examples – 4 (Required)

Dynamic memory allocation shall not be used
► This is a severe problem, everyone usually
  does malloc…
► Reasons:

AA 2019-2020            Quality and Certification
Directive examples – 4 (Required)

Dynamic memory allocation shall not be used

AA 2019-2020            Quality and Certification
Directive examples - 5 (Required)
Assembly language shall be encapsulated and
isolated

AA 2019-2020            Quality and Certification
Directive examples - 6 (Advisory)
typedefs that indicate size and signedness
should be used in place of the basic numerical
types

AA 2019-2020            Quality and Certification
Other directive examples (Required)

All source files shall compile without any
compilation errors

All code shall be traceable to documented
requirements

AA 2019-2020             Quality and Certification
Rules are about…
     1.        The Standard C environment
     2.        Unused code
     3.        Comments
     4.        Character sets and lexical conventions
     5.        Identifiers
     6.        Types
     7.        Literals and constants
     8.        Declarations and definitions
     9.        Initialization
     10.       The essential type model
     11.       Pointer type conversion
     12.       Expressions
     13.       Side effects
     14.       Control statement expressions
     15.       Control flow
     16.       Switch statements
     17.       Functions
     18.       Pointers and arrays
     19.       Overlapping storage
     20.       Preprocessing directives
     21.       Standard libraries
     22.       Resources

AA 2019-2020                                            Quality and Certification
Required rule example – standard C
                         environment
There shall be no occurrence of undefined or
critical unspecified behavior.

Explanation:
  – unspecified: must compile correctly, but compiler
    writer has some freedom – e.g. order of evaluation
     a = f(b) + g(b);
     x = b[i] + i++;
  – undefined: programming errors for which compiler not
    obliged to provide error messages – e.g. overflow when
    adding int values

Relying on such behavior limits portability
AA 2019-2020             Quality and Certification
Required rule example – unused code

A project shall not contain unreachable code
  – This refers to code that can be identified at compile time
    as unreachable. May indicate an error in the program’s
    logic.
  – The reachability problem may be “undecidable”! But many
    cases of unreachable code are easy to detect. A compiler is
    permitted to remove any unreachable code but it does not
    have to do so.
switch(event) {
case A:          do_a();
                 break;
                 do_more();                 /* unreachable */
...
AA 2019-2020                  Quality and Certification
… cont.

►    Example: see standard MISRA-C pag. 48
     rule 2.1

AA 2019-2020       Quality and Certification
Required rule example – comments

The character sequences /* // shall not be
used within a comment
  Exception: the sequence // is permitted within a //
  comment

AA 2019-2020            Quality and Certification
Required rule example - Identifiers

An identifier declared in an inner scope shall
not hide an identifier declared in an outer
scope.

  Example:
      int16_t i;
      {
      int16_t i;    /* This is a different variable */
                    /* This is not compliant */
      i = 3;        /* To which i this refers ?*/
      }

AA 2019-2020               Quality and Certification
Required rule example – Literal and
                           constants
The lowercase character «l» shall not be used
in a literal suffix
  – Rationale: use L, avoid confusion with l, 1

AA 2019-2020             Quality and Certification
Required Rule example – Declarations
                         and definitions
When an array with external linkage is
declared, its size should be explicitly
specified.

extern int array1[10];
extern int array2[];                    /* Not compliant */
extern int array3[] = {0, 10, 15};

AA 2019-2020              Quality and Certification
Required rule example - Expressions

The right hand operand of a shift operator
shall lie in the range zero to one less than the
width in bits of the essential type of the left
hand operand.

AA 2019-2020             Quality and Certification
Advisory rule example – Side Effects
A full expression containing an increment (++) or
decrement (--) operator should have no other
potential side effects other than that caused by
the increment or decrement operator.
  A function call is considered to be a side effect for the
  purpose of this rule
  Can impair readability of the code and raise undefined
  behaviour

AA 2019-2020              Quality and Certification
Advisory rule example - Control flow

A function should have a single point of exit at
the end
  – A function should never have more than one return
    statement
  – For readability + predicting side effects in place
    (if a function has multiple exit points interspersed
    with statements that produced persistent side
    effects)

AA 2019-2020              Quality and Certification
Required rule example - Functions

Functions shall not call themselves, either
directly or indirectly

AA 2019-2020            Quality and Certification
Mandatory rule example - Functions

A function shall not be declared implicitly

AA 2019-2020             Quality and Certification
Required rule example – Pointers and
                              arrays
The address of an object with automatic storage
shall not be copied to another object that
persists after the first object has ceased to
exist.

AA 2019-2020              Quality and Certification
Required rule example – Pointers and
                              arrays
Conversions shall not be performed between a
pointer to a function and any other type.
  – Pointer to a function shall only be converted into or
    from a pointer to a function with a compatible type.
  – Problem is that undefined behavior is raised

AA 2019-2020              Quality and Certification
Mandatory rule example – overlapping
                             storage
An object shall not be assigned or copied to an
overlapping object
  (there are some exceptions to this rule…)

AA 2019-2020              Quality and Certification
Required rule – Standard libraries

The memory allocation and deallocation
functions of  shall not be used.

AA 2019-2020             Quality and Certification
Required rules - Resources

22.1 All resources obtained dynamically by
means of Standard Library functions shall be
explicitly released.
  – Malloc, calloc, realloc, fopen

22.3 The same file shall not be open for read
and write access at the same time on different
streams
  – The standard does not specify the behaviour if a
    file is read and written via different streams.

AA 2019-2020             Quality and Certification
AA 2019-2020   Quality and Certification
MISRA-C compliance

Goal: check that no rules have been broken
  – Use one or more static checking tools that are
    available commercially
     • BTW, over time engineers will tend to alter their habits and write
       compliant code
  – Where a rule cannot be checked by a tool, then a
    manual review will be required.

  – Sample tools: Understand++, Clockworks, LDRA,
    MATLAB Polyspace

AA 2019-2020                       Quality and Certification
MISRA-C compliance matrix
Produce a compliance matrix
  – it lists each rule
  – indicates how it is to be checked

AA 2019-2020           Quality and Certification
Deviation procedure

Strict adherence to all rules is unlikely
Sometimes it may be necessary to deviate
from the rules given in MISRA-C document
  – e.g. source code written to interface with the
    microprocessor hardware will inevitably require
    the use of proprietary extensions to the language

The use of a deviation must be justified on the
basis of both necessity and safety

AA 2019-2020           Quality and Certification
Deviation procedure

Deviations associated with individual situations
are admissible:
  Project Deviation: a permitted relaxation of rule
  requirements to be applied in specified
  circumstances. Usually agreed at the start of a
  project.

  Specific Deviation: defined for a specific instance
  of a rule violation in a single file and. Typically
  raised in response to circumstances which arise
  during the development process.

AA 2019-2020           Quality and Certification
Project Deviation Request

The software developer should submit a written
Project Deviation Request and agreement with the
customer, including:
  – Details of the deviation, i.e. the rule that is being
    violated
  – Circumstances in which the need for the deviation
    arises
  – Potential consequences which may result from the
    deviation
  – Justification for the deviation
  – A demonstration of how safety is assured

►    Analogous for Specific deviations
AA 2019-2020              Quality and Certification
Adopting the MISRA-C subset –
                         summary
In order to develop code that adheres to
the subset the following steps need to be
taken:
  – Produce a compliance matrix which states
    how each rule is enforced
  – Produce a deviation procedure
  – Formalize the working practices within the
    quality management system

AA 2019-2020           Quality and Certification
You can also read