You are on page 1of 32

Automotive Software

Programming of Safety-Critical Systems: MISRA-C

Department of Automotive Engineering, HYU

Soonmin Hwang
E-mail : soonminh@hanyang.ac.kr
Safety-Critical Systems
Definition
• Refer to systems whose failure or malfunction
poses a significant risk to human life, health,
or the environment

The challenges continue to increases


• Demands to incorporate competencies in
‒ Network connectivity
‒ Artificial intelligence (AI)
‒ Other performance improvements
è Have increased code complexity
and heightened the risk of security vulnerabilities and safety hazards

2
Embedded Safety-Critical Systems
The aviation and space industry
• Ada programming language
: well-defined semantics & parallel programming

The telecommunication industry


• Functional programming languages (Haskell or Erlang)
even if the safety criticality is not that crucial there.

The automotive industry


• C/C++ code is the most common
‒ relatively well known
‒ relatively simple if needed and with good compiler support
à The code can be ported easily between different operating systems,
as the majority of the safety critical OSs have the Unix kernel at their core 3
Safety-Critical Code: NASA’s Principles
NASA’s missions
• Often require safety-critical software to steer
their devices such as space shuttles/satellites

NASA’s Jet Propulsion Laboratory


• Initial reliability research has been done
• In 2006, Holtzman presented ten rules of safety-critical programming,
which come from NASA, but apply to all safety-critical software

4
Safety-Critical Code: NASA’s Principles
Ten rules of safety-critical programming
1. Restriction: very simple control flow constructs
‒ Do not use goto/setjmp/longjmp constructs
‒ Do not use recursion

Complex control flow in recursive functions

2. Give all loops a fixed upper bound


‒ Prove that the loop cannot exceed a preset upper bound
on the number of iterations
‒ If a tool cannot prove the loop bound,
the rule is considered violated

5
Safety-Critical Code: NASA’s Principles
Ten rules of safety-critical programming
3. Do not use dynamic memory allocation
‒ Need to deallocate it as well
‒ Risk of memory leaks è system crash

4. No function should be longer than a single sheet of paper


‒ One line per statement and one line per declaration
‒ Typically, this means no more than about 60 lines of code per function

6
Safety-Critical Code: NASA’s Principles
Ten rules of safety-critical programming
5. Two assertions per function in average
‒ Assertions: check for anomalous conditions that should never happen
‒ Must be side effect-free and should be defined as Boolean tests
‒ When an assertion fails, an explicit recovery action must be taken

6. Declare all data objects at the smallest possible level of scope


‒ For example, do not overuse global variable

7. Function calls
‒ Must check the return value
‒ The validity of all parameters provided by the caller

7
Safety-Critical Code: NASA’s Principles
Ten rules of safety-critical programming
8. Limited use of the preprocessor
‒ Inclusion of header files & simple macro definitions
‒ Prohibited: token pasting, variable argument lists, recursive macro

9. Restricted use of pointers


‒ No more than one level of dereferencing
ü May not be hidden in macro definitions or inside typedef declarations
‒ Function pointers are not permitted

10. All code must be compiled


‒ From the first day of development, with all compiler warnings enabled
‒ All code must compile without warnings
‒ All code must also be checked daily with strong static source code analyzer
8
Safety-Critical Code: NASA’s Principles
Naturally captured by the MISRA rules
è Show the similarity of safety-critical systems regardless of the domain

The “heart” of these rules


• The safety-critical should be simple and modularized
• Show the difficulty of automatically checking for their violation
‒ For example, the principles #6 (“Declare all data objects at the smallest possible level of sc
ope”) requires parsing of the code to establish the boundary of the “smallest possible level
of scope”).

9
What Are Coding Rules and Guidelines?
Coding rules and guidelines ensure that software is:
• Safe: It can be used without causing harm
• Secure: It can’t be hacked
• Reliable: It functions as it should, every time
• Testable: It can be tested at the code level
• Maintainable: It can be maintained, even as your codebase grows
• Portable: It works the same in every environment

10
Coding Standards: Why is it important?
Every development team should use one. Even the most experienced
developer could introduce a coding defect — without realizing it.
And that one defect could lead to a minor glitch. Or worse, a serious
security breach.

Four key benefits of using coding standards


1. Compliance with industry standards (e.g., ISO)
2. Consistent code quality — no matter who writes the code
3. Software security from the start
4. Reduced development costs and accelerated time to market

11
What is MISRA?
MISRA (Motor Industry Software Reliability Association)
• A group founded by the British auto industry in the late 90’s
‒ To improve robustness and reliability in vehicle software
‒ That expansion is no longer used because “MISRA” no longer implies “automotive industry”
‒ Used in many other sectors, too

• Published guidelines that established coding rules


‒ Aim at “providing best practice guidelines for the safe and secure application of both embed
ded control systems and standalone software”
‒ Addressing ambiguities in the C programming language

• A collaboration: manufacturers, suppliers and engineering consultancies

12
MISRA-C: What is it?
Write Safer, Clearer C Code
• A comprehensive set of guidelines for using the C programming language
‒ Originally developed for a “restricted subset of a standardized programming language”
‒ To minimize potential errors, security vulnerabilities, and mistakes
that cause program failure or serious errors
• Today, the de facto standard for developing software in C
where safety, security and code quality are important

Consist of several “rules” and “directives”


• A common theme throughout all the MISRA rules: avoid implicit behavior
‒ Experience tells us that’s where many errors creep into systems.
• Contains “how to document embedded C code”
‒ Naming conventions, documentation and the use of certain programming constructs

https://misra.org.uk 13
MISRA-C: History

First Edition Third Edition Amendment 2 Amendment 4


(1998) (MISRA-C: 2012) (2020) (2023)

Second Edition Amendment 1 Amendment 3 Fourth Edition


(MISRA-C: 2004) (2016) (2022) (MISRA-C: 2023)

Amendment 1, Additional security guidelines for MISRA C:2012


Amendment 2, Updates for ISO/IEC 9899:2011 Core functionality
Amendment 3, Updates for ISO/IEC 9899:2011/2018 Phase 2
• New C11/C18 features
Amendment 4, Updates for ISO/IEC 9899:2011/2018 Phase 3
• Multi-threading and atomics
è Support for the new features introduced by C11, C18
and additional guidance on existing language features
14
MISRA-C: Vision
The vision for MISRA-C
• Enhance the existing guidance
‒ Correct any known issues with the previous editions
‒ Add new guidelines for which there is a strong rationale
‒ Improve the specification and the rationale for existing guidelines, where appropriate
‒ Remove any guidelines for which the rationale is insufficient
‒ Increase the number of guidelines that can be processed by static analysis tools,
by improving the decidability where possible

• Guidance on the applicability of the guidelines to automatically-generated code

15
MISRA-C: Background
The popularity of C is because:
• C compilers are readily available for many processors
• C programs can be compiled to efficient machine code
• Defined by an international standard
• Considerable body of experience with using C in critical systems
• Widely supported by static analysis and test tools

16
MISRA-C: Background
Disadvantages of C
• Language definition
‒ Intentionally, the C standard does not specify the language completely
to support many pre-existing implementations
‒ An implementation is free to choose its own behavior
è Hinder static analysis if it is not possible to configure the analyzer to handle it

• Language misuse/misunderstanding
• Error checking in run-time

17
MISRA-C: Why?
How do MISRA Guidelines help?
• Better portability through the avoidance of compiler-/ platform-specific things
• Avoid unexpected / unspecified / undefined application behavior
• Identify unreachable or infeasible code
‒ which often suggests a defect and a potential security vulnerability
• Reduce unsafe and insecure coding practices
‒ by prohibiting certain language constructs
• Measurably reduce program complexity
• Improve program testability
• Ease compliance with functional safety and security standards

https://misra.org.uk 18
MISRA-C: Guidelines – Classification
Classified as “Directive” or “Rule”
[Directive] Impossible to provide the full description
à Static analysis tools may be able to assist in checking compliance with directives
but different tools may place widely different interpretations on
what constitutes a non-compliance

[Rule] A complete description of the requirement has been provided


à Should be possible to check that source code complies with a rule
à Static analysis tools should be capable of checking compliance with rules

19
MISRA-C: Guidelines – Category
Categories: Mandatory, Required, Advisory
: All mandatory guidelines should be considered to be of equal importance

[Mandatory]
• Comply with EVERY mandatory guideline, exception is not permitted

[Required]
• Comply with EVERY required guideline, with a formal deviation required
• May treat any required guidelines as if it were mandatory

[Advisory]
• These are recommendations (does not mean that these items can be ignored)
• Should be followed as far as is reasonably practical

20
MISRA-C: Guidelines – Decidability of Rules
Each rule is classified as “decidable” or “undecidable”
: describes the theoretical ability of static analyzer to answer the question
“Does this code comply with this rule?”

[Decidable] Possible to answer the question with a ”yes” or “no” in EVERY CASE
• Useful properties with regard to static analysis
‒ A reported violation indicates a real violation
‒ No reported violation indicates there are no violations in the code being analyzed

[Undecidable] otherwise
• If detecting violations depends on run-time properties such as
‒ The value that an object holds
‒ Whether control reaches a particular point in the program
è Particular attention should be paid to the undecidable rules

* Directives are not classified in this way because it is impossible 21


MISRA-C: Guidelines – Scope of Analysis
[Single Translation Unit] Possible to detect all violations within a project
• By checking each translation unit independently
Example) the presence of “switch” statements that do not contain “default” labels (Rule 16.4)
has no effect on whether other translation units contain such switch statements

[System]
• Identifying violations of a rule requires checking more than the translation unit in question
‒ Best checked by analyzing all the source code
‒ Possible to identify some violations when checking a subset of the whole source
• All “undecidable” rules need to be checked on a “System” basis
‒ Because information about the behavior of other translation units will be needed

22
MISRA-C: Guidelines – Multi-organization Projects
Projects may involve code from various organizations
[The standard library]
• Likely to be concerned with efficiency of execution
• May rely on implementation details or unspecified behaviors such as
‒ Casting pointers to object types into pointers to other object types
‒ Layout of stack frames, and the locations of function parameters within those frames
‒ Embedding assembly language statements in C
• It is not required to comply with MISRA C
è Potential risk if we highly rely on the standard library to violate MISRA C
è However, guidelines that rely on the interface provided
by standard header declarations and macros are still applicable (e.g., essential type)

23
MISRA-C: Guidelines – Multi-organization Projects
Projects may involve code from various organizations
[All other code]
: low-level/high-level/OS driver codes, application code which may be shared

• Should comply with the MISRA C guidelines


• In many projects, it is not possible to obtain all the source code
‒ Collaborating organizations may share functional/interface specifications and object code
to protect their own intellectual property (IP) by not sharing source code

‒ When only part of the source code is available for analysis, organizations might
ü Agree upon a common procedure and tools: apply to their own source code
ü Supply each other with stub versions of source code to permit cross-organizational checks

24
MISRA-C: Guidelines – Automatically Generated Code
Responsibility for compliance
: Both the developer of the AGC tool and the developer of the model
• Several modeling packages exist, each of which may have several automatic code generators
‒ So, it is impossible to allocate this responsibility individually

25
MISRA-C: Presentation of Guidelines
Within the supporting text,
[Amplification]
• A more precise description of guideline
• Normative; if it conflicts with the headline,
the amplification takes precedence

[Exception]
• Situations in which the rule does not apply
• Permits the description of some guidelines
to be simplified

[Example]
• Followed by code snippets

[See also]
• A list of the other related guidelines
26
[MISRA C:2023] 18 Directives (5 Groups)

27
[MISRA C:2023] 200+ Rules (23 Groups)

28
[MISRA C:2023] Rules - Example

29
[MISRA C:2023] Rules - Example
[Rules 3.2] Line-splicing shall not be used in // comments
• Amplification
‒ Line-splicing occurs when the \ character is immediately followed by a new-line character. If
the source file contains multibyte characters, they are converted to the source character set
before any splicing occurs
• Rationale
‒ If the source line containing a // comments ends with a \ character in the source character
set, the next line becomes part of the comment. This may result in unintentional removal of
code

30
How to apply it - The MISRA standard and PVS-Studio

https://www.youtube.com/watch?v=01tEjvICh4k&t=42s 31
Thank you!

You might also like