MISRA Compliance 2016
MISRA Compliance 2016
MISRA Compliance:2016
Achieving compliance with
MISRA Coding Guidelines
April 2016
First published April 2016 by HORIBA MIRA Limited
Watling Street
Nuneaton
Warwickshire
CV10 0TU
UK
www.misra.org.uk
“MISRA”, “MISRA C” and the triangle logo are registered trademarks owned by HORIBA MIRA Ltd, held
on behalf of the MISRA Consortium. Other product or brand names are trademarks or registered
trademarks of their respective holders and no endorsement or recommendation of these products
by MISRA is implied.
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system or
transmitted in any form or by any means, electronic, mechanical or photocopying, recording or
otherwise without the prior written permission of the Publisher.
i
MISRA Mission Statement
We provide world-leading best practice guidelines for the safe and secure application of both
embedded control systems and standalone software.
Disclaimer
Adherence to the requirements of this document does not in itself ensure error-free robust software or
guarantee portability and re-use.
Compliance with the requirements of this document, or any other standard, does not of itself confer
immunity from legal obligations.
ii
Foreword
Ever since MISRA C first appeared, it has been recognised that circumstances sometimes occur when
it is impracticable or unreasonable to follow the requirements of a guideline. However, the concept of
approved violations, known as deviations, has caused much debate, especially when discussing their
effect on a claim of MISRA compliance. A myriad of approaches to compliance have been proposed
within projects, ranging from a “no deviations allowed” policy through to the liberal use of deviations
in an attempt to justify areas of non-compliance.
● Provides a mechanism for tailoring the classification of the guidelines to match the needs of
a project;
● Requires that a standardised declaration be issued to show the final level of compliance
claimed by a project.
This guidance will become the standard approach for all future editions of both the MISRA C and
MISRA C++ Guidelines. It is also an optional enhancement to, and fully compatible with, all existing
editions of the MISRA language guidelines.
I encourage all users, and all organisations, to consider adoption at the earliest opportunity.
iii
Acknowledgements
The MISRA consortium wishes to acknowledge the contribution made by the Japan Automobile
Manufacturers Association to the preparation of this document.
The MISRA consortium would like to thank the following individuals for their significant contribution
to the writing of this document:
The MISRA consortium also wishes to acknowledge contributions from the following members of the
MISRA C Working Group during the development and review process:
The MISRA consortium also wishes to acknowledge contributions from the following individuals
during the development and review process:
iv
Contents
1 Introduction 1
2 The context 2
2.1 The development contract 2
2.2 The software development process 2
4 Deviations 7
4.1 The role of deviations 7
4.2 Deviation records 7
4.3 Deviation permits 7
4.4 Justifying a deviation 8
6 Adopted Code 12
6.1 The nature of adopted code 12
6.2 System wide analysis scope 12
6.3 Adopted binary code 13
6.4 Adopted source code 13
6.5 Adopted header files 14
6.6 The Standard Library 14
8 References 19
Appendix C Glossary 24 v
1 Introduction
The MISRA language documents [1], [2], [3] and [4] (“The Guidelines”) are compilations of guidelines
for coding in the C and C++ languages. They are widely used in the development of critical software
systems when the requirements of a quality standard must be met. Many software projects specify
that code quality should be assured by meeting the requirements of The Guidelines. However, the
meaning of the phrase “MISRA compliant” needs to be carefully defined.
The Guideline documents recognise that, in some situations, it is unreasonable or even impossible to
comply with a coding guideline and that it is necessary to deviate. The freedom to deviate does not
necessarily compromise claims of compliance but it does carry with it great responsibility. In the
absence of a disciplined development process, it is easy for that freedom to be abused. At best, that
will undermine the credibility of any claims of MISRA compliance; at worst, it will compromise code
quality, safety or security. It is therefore important to emphasise that a credible claim of compliance
with The Guidelines can only be made when code is developed under a process which meets the
principles laid out in this document.
The guidance given in this document supersedes the compliance, deviation and process
requirements published previously in the various MISRA Guidelines.
Note: The various MISRA Guideline documents have been refined and revised over a number of years.
This document uses examples and extracts from both the MISRA C:2004 and MISRA C:2012
Guidelines, but the issues discussed are equally relevant to all of the guidelines published by MISRA.
1
2 The context
1. The software requirements, including any safety or security requirements, are complete,
unambiguous and correct;
2. The design specifications reaching the coding phase are correct, consistent with the
requirements and do not contain any other functionality;
3. The object modules produced by the compiler behave as specified in the corresponding
designs;
4. The object modules have been tested, individually and together, to identify and eliminate
errors.
A full discussion of the requirements for software development processes is outside the scope of this
document. Further information may be found in standards such as ISO/IEC 12207:2008 [5],
IEC 61508:2010 [6], ISO 26262:2011 [7], DO-178C [8], EN 50128:2011 [9] and IEC 62304:2006 [10].
Compliance with MISRA Guidelines must be an integral component of the code development phase
and compliance requirements need to be satisfied before code is submitted for review or unit
testing. A project that attempts to check for compliance late in its lifecycle is likely to spend a
considerable amount of time in re-coding, re-reviewing and re-testing, and it is easy for this rework to
introduce defects by accident. Code shall be checked for compliance as it is developed and not as
part of a “tick-box” exercise to be completed as part of the final delivery phase.
If a project is building on code that already has a proven track record, then the benefits of gaining
compliance by refactoring existing code may be outweighed by the risks of introducing a defect. In
such cases a judgement needs to be made based on the net benefit likely to be obtained.
2
3 Fundamental elements of compliance
A rule is a guideline which imposes requirements on the source code which are complete, objective,
unambiguous and independent of any process, design-documentation or functional requirement.
Analysis tools are capable of checking compliance with rules, subject to the limitations described later
in Section 3.5.
A directive is a guideline which is not defined with reference to the source code alone. Analysis tools
may be able to assist in checking compliance, but a directive will also refer to, or impose requirements
on processes, documentation or functional requirements. The requirements of a directive may also
introduce a degree of subjective judgement and different tools will therefore sometimes place
different interpretations on what constitutes a non-compliance.
The majority of guidelines in MISRA C:2012 are classified as rules. Earlier versions of the MISRA
Guidelines used no such distinction, and, in fact, consist almost entirely of rules.
For example, a rule such as “Every switch statement shall have a default value”, is a Single Translation
Unit rule. It can be reliably verified by analysing the source code in each translation unit in isolation.
On the other hand, a rule such as “An identifier with external linkage shall have exactly one external
definition” is a System rule. It can only be verified with certainty by analysis of the entire body of
source code.
A guideline enforcement plan (GEP) listing each guideline within the MISRA Guidelines shall be produced
to indicate how compliance with the guidelines is to be checked. The supplier will make the GEP
available to the acquirer so that the suitability and robustness of the checking that has been
undertaken can be assessed. An example is provided below:
3
Section 3: Fundamental elements of compliance
Compilers Analysis tools
Guideline Manual review
‘A’ ‘B’ ‘A’ ‘B’
Dir 1.1 Procedure x
Dir 2.1 no errors no errors
…
Rule 4.1 message 38
Rule 4.2 warning 97
Rule 5.1 warning 347
…
Rule 12.1 message 79
Rule 12.2 message 432 Procedure y
Rule 12.3 message 103
Rule 12.4 message 27
The following information shall be recorded in support of the guideline enforcement plan:
1.4 Evidence proving that the tool is able to detect violations of the guidelines for which it is to
check compliance.
The preferred remedy for any messages in category (1) is to correct the source code in order to make
it compliant with The Guidelines. If it is undesirable or impossible to render the code compliant, then
guideline violations may need to be authorised as shown in Section 4.
Any messages in the other categories should be investigated. Sometimes, the easiest and quickest
solution will be to modify the source code to eliminate the message. However, this may not always be
possible or desirable, in which case a record of the investigation should be kept. The purpose of the
record is to:
4
Section 3: Fundamental elements of compliance
● Category (2) — Explain why the code is compliant despite diagnosis of a possible violation;
● Category (3) — Explain and, if possible, obtain the tool developer’s agreement that the tool
diagnosis is incorrect;
All records of such investigations should be reviewed and approved by an appropriately qualified
technical authority.
3.5 Decidability
As discussed in Section 3.1, a rule is defined as a guideline for which compliance is dependent entirely
on the source code and not on any design considerations or external documentation. Rules are
therefore guidelines which are amenable to enforcement using static analysis and the role of an
analysis tool will be to answer the compliance question “Does this code comply with this rule?”.
Unfortunately there are some rules for which an answer cannot be provided in all circumstances and
rules have to be classified as either decidable or undecidable.
Decidable rules
A rule is decidable if it is always possible to answer the compliance question with an unequivocal “Yes”
or “No” answer. Decidable rules are particularly effective because, providing the analysis tool is
configured correctly and is free of defects, it is always possible to verify compliance with certainty.
Undecidable rules
A rule is undecidable if an analysis tool cannot guarantee to respond to the compliance question with
a “Yes” or a “No” in every situation. There may be situations when an analysis tool can respond with a
“Yes” or a “No”; but there will also be some situations where the only possible response is “Possibly”
(i.e. compliance is uncertain).
A review of the theory of computation, on which the decidability classification is based, is beyond the
scope of this document, but a rule is likely to be undecidable if detecting violations depends on run-
time properties such as:
Most undecidable rules need to be checked on a system-wide basis because, in the general case,
information about the behaviour of other translation units will be needed. Consider, for example, the
requirement to check a rule such as “The value of an object with automatic storage duration shall not
be read before it has been set”, as shown in the following:
uint16_t g ( void )
{
uint16_t x; /* x is not given a value */
It will not be possible to verify compliance in the function g without examining the behaviour of the
function f, which may be defined in another translation unit.
5
Section 3: Fundamental elements of compliance
Complying with undecidable rules
When a rule is undecidable, no analysis tool, however sophisticated, can guarantee to respond
unequivocally to the question “Does this code comply with this rule?” in every situation. Depending
on the nature of the code, a tool may be able to report “Yes” or “No”, but in many cases it may only be
able to report “Possibly”. (Of course, the actual response will be expressed in different ways by
different tools and the absence of a diagnostic does not necessarily imply a response of “Yes”).
The nature of undecidability is such that the task of verifying compliance to an undecidable rule by
static analysis alone is often impossible. Even in coding situations where the task is theoretically
provable, the necessary analysis may be very complex and may require computing resources which
are unmanageable. Tools vary widely in their capability to diagnose non-compliance to undecidable
rules. What is important is the degree to which a tool is successful in distinguishing and reporting
definite violations as well as possible violations, thereby managing to avoid both false positives and
false negatives.
Particular attention should be paid to the process for reviewing compliance to undecidable rules. The
fact that static analysis cannot ensure compliance in the general case does not mean that
compliance cannot be guaranteed for any code. If an analysis tool is reliable in identifying possible
violations, it may be feasible to eliminate such uncertainties by adopting conservative and defensive
coding techniques at the development stage.
6
4 Deviations
The management of guideline violations is a critical issue. Violations are sometimes unavoidable and a
claim of compliance can only be meaningful when they are authorized through a clearly defined
process and supported by deviation records.
5. A set of requirements to include any risk assessment procedures and precautions which
must be observed.
In addition, it is important to be able to identify where the deviation is being applied. A deviation may
be associated with a single violation or with a number of similar violations which conform to a
common use-case. Where there are multiple violations to consider, the deviation record may consist of
a body of common documentation supported by a register of locations where the deviation is being
applied. This register may be in the form of a detailed list of file names and line numbers, a more
general description of the context in which the deviation is applied (e.g. in specific files or in the
expansion of a specific macro) or define a unique identifier that can be used to tag one or more
locations within the code. However, the ability to identify every instance where the guideline is violated
will be essential in order to support a robust review process. It should also be noted that in the case
of some guidelines, a single violation may be associated with two or more locations in the code. This
would occur, for example, where conflicting declarations of the same entity are identified.
A deviation permit is not the same as a deviation record but it can supply much of the material which is
required in a deviation record. A deviation permit defines a use-case under which a violation may be
justified and specifies the documentation and process requirements which must be supplied in the
7
deviation record.
Section 4: Deviations
The effort associated with compiling and reviewing deviations can be substantial and it is a task that
requires the input of experienced and well qualified staff. This effort can be significantly reduced by
developing a repository of approved deviation permits, a task which can be scheduled in advance of
any code development. The use of deviation permits makes it possible to:
A further advantage to be gained by such advance planning is that the deviation permit repository can
be the subject of negotiated agreement between supplier and acquirer at an early stage in the project,
thereby reducing the likelihood of later disagreement when the code is reviewed by the acquirer.
MISRA publishes public deviation permits in separate documents for the various versions of the MISRA
Guidelines. These address guidelines where violations can most reasonably be justified and provide
examples of best practice which may be followed when additional deviation permits are drafted.
Note: Publication of common use-cases as deviation permits by MISRA does not imply that they are
acceptable within a particular project and their use in support of a deviation must be subjected to the
same balances and measures as for any other deviation.
● When a reasonable alternative coding strategy would make the need for a violation
unnecessary;
In addition, a proposed deviation should only be approved if it can be justified on the basis of one or
more of the following reasons:
The Guidelines address code quality with a particular emphasis on issues of safety and security.
ISO/IEC 25010 [11] formally defines a more extensive list of characteristics and sub-characteristics of
software quality in the form of a “Product Quality Model”, as shown in the following table:
8
Section 4: Deviations
Characteristic Sub-characteristic
Functional suitability Functional completeness, Functional correctness, Functional appropriateness
Performance efficiency Time behaviour, Resource utilization, Capacity
Compatibility Co-existence, Interoperability
Appropriateness recognizability, Learnability, Operability, User error protection,
Usability
User interface aesthetics, Accessibility
Reliability Maturity, Availability, Fault tolerance, Recoverability
Security Confidentiality, Integrity, Non-repudiation, Accountability, Authenticity
Maintainability Modularity, Reusability, Analysability, Modifiability, Testability
Portability Adaptability, Installability, Replaceability
These characteristics are described fully in Section 4.5 of ISO/IEC 25010 [11]. They encompass many
different aspects of software quality and only some are associated with coding practices. The key
MISRA objectives of safety and security are most closely aligned with the “Functional suitability” and
“Reliability” characteristics. However, a guideline addressing an issue of safety or security can
sometimes have a negative impact on characteristics such as “Maintainability”, “Portability” or
“Performance efficiency”. Similarly, it can be impossible to implement some defensive coding
measures (in accordance with the “Fault tolerance” characteristic) when complying with guidelines
which prohibit invariant expressions and infeasible code.
In such situations it may be reasonable to introduce a violation of a guideline in order to improve code
quality with respect to the characteristic that has been compromised, but only if safety and security
are maintained and the result can be justified on the grounds that better overall quality is achieved.
As with any deviation, the rationale behind the guideline must be clearly understood and the risks and
merits of a non-compliant approach must be carefully weighed.
Compiler-specific extensions to the language are often necessary in embedded software systems
where low-level access to hardware functionality cannot be provided by the standard language
syntax. As with any code which has implementation-defined behaviour, it is important for the purposes
of maintainability that it should be encapsulated and isolated as much as possible.
It is possible for two individual translation units to be compliant with a guideline when viewed in
isolation, but for violations of that guideline to emerge as a result of combining the translation units in
the same system.
The significance of adopted code is described in Section 6. When introducing such code into a system,
it may be impossible, impractical, or simply unwise to resolve the problem by rewriting existing code
and, in those circumstances, providing suitable precautions are observed, it may be appropriate for a
deviation to be authorized.
When adopted code has not been developed with any intention to make it compliant with MISRA
Guidelines, it will be meaningless to associate a deviation with any of the reasons listed above. The
violation may have to be justified simply on the basis that the code is adopted and that it can be
demonstrated that the violation does not compromise safety or security (see Section 6).
Similar considerations may arise when adopted code has been written to be compliant with a different
version of The Guidelines. 9
5 The guideline re-categorization plan
Successive versions of The Guidelines have all presented a system of guideline categorization. Earlier
versions drew a simple distinction between those categorized as Required and those categorized as
Advisory. Subsequently, MISRA C:2012 introduced the Mandatory category. These categories define
the policy to be followed in determining whether a guideline may be violated or not and whether a
deviation is required:
● Required Guidelines — Guidelines which can only be violated when supported by a deviation
defining a set of clear restrictions, requirements and precautions;
5.1 Re-categorization
At the outset of a development project, the acquirer and supplier shall agree a guideline re-
categorization plan (GRP) to determine how The Guidelines are to be applied. The GRP reflects the
following issues:
1. It is recognised that in some projects there may be some Advisory guidelines which are to be
ignored altogether. An additional category, “Disapplied”, is therefore introduced to describe
this condition. Of course, any decision to disapply a guideline should not be taken lightly and
the rationale shall therefore be documented in the GRP.
2. A principle that has been observed during the evolution of the various versions of The
Guidelines is that there are only a small number of Required guidelines for which a compelling
justification for deviation ever arises. This means that, in practice, it is quite possible to treat a
high proportion of the Required guidelines as Mandatory. Any such re-categorization can only
be introduced in the light of experience and some careful investigation; but this discipline
can be used very effectively to curb the proliferation of violations. A similar approach can be
applied to Advisory guidelines. If an Advisory guideline is considered to be of significant
importance, it may be helpful to re-categorize it as a Required guideline or even as a
Mandatory guideline.
A GRP can therefore be used to supersede the original system of categorization defined in The
Guidelines with a system which differs in the following ways:
Revised category
MISRA category
Mandatory Required Advisory Disapplied
Mandatory Permitted
Required Permitted Permitted
Advisory Permitted Permitted Permitted Permitted
Notes:
Note: A project may wish to establish more than one GRP for different aspects of a project but in
doing so it must be recognised that some guidelines have to be applied across the entire system and
therefore should be categorized consistently.
11
6 Adopted Code
● The Standard Library — The library code and header files specified by The Language
Standard and provided with the compiler;
● Device driver files — Code either included with the compiler or supplied by a semiconductor
manufacturer providing an interface to device peripherals;
● Automatically generated code — Code generated by modelling tools, UML tools, etc.;
● Legacy code — Code developed for other projects or previous versions of the current
project.
The impact of adopted code on the integrity of a system must never be overlooked or assumed to be
benign. There are two distinct issues to consider:
1. Has the adopted code been developed to a verifiably adequate level of safety and security?
2. Has the adopted code been developed to be compliant with MISRA Guidelines?
These two issues are not equivalent. Compliance with MISRA Guidelines is neither a necessary nor a
sufficient condition to ensure the quality of adopted code.
Applying MISRA Guidelines to a project in the presence of adopted code introduces a number of
difficulties. If adopted code has not been developed to exactly the same compliance criteria as the
native code, claims of MISRA Compliance will inevitably be compromised. In practice, adopted code
may have been written without MISRA compliance as an objective, but even if it has, it may have been
written to comply with a different version of the Guidelines or with different compliance criteria (e.g. a
different GRP).
12
6.3 Adopted binary code
The supplier may be willing to issue a statement of MISRA compliance when adopted binary code has
been developed to comply with MISRA Guidelines. Alternatively, organizations that are collaborating
closely may:
● Agree upon a common procedure and tools that each will apply to their own source code;
● Supply each other with stub versions of source code to permit cross-organizational checks to
be made.
However, without access to the entire body of source code, the acquirer will still be restricted in their
ability to verify compliance with those guidelines which apply at system level.
When source code is unavailable for analysis, other avenues need to be explored in order to ensure
that quality standards are maintained, such as, for example, the use of static or dynamic analysis of
the binary code.
Note: some process standards may include wider requirements for managing multi-organization
developments, for example Part 8 Clause 5 “Interfaces in distributed development” of
ISO 26262:2011 [7].
● Advisory guidelines re-categorized as Required are violated and the use-case is not covered by
a deviation.
Since adopted code cannot be modified, it may be necessary to adopt an alternative, less stringent
GRP. There will then be distinct GRP’s, for native code and for the adopted code. In practice, if there are
several distinct units of adopted code, it may be appropriate to introduce additional GRP’s. The fact
that an adopted code GRP is more permissive than a native code GRP does not imply that the
commitment to quality, safety and security is any less stringent for adopted code. Having a guideline
categorized as Mandatory in the native code GRP and Required in the adopted code simply means that
there will be additional violations to be reviewed.
Note: Code which does not comply with a guideline originally categorized as Mandatory in the MISRA
Guidelines can never be classified as compliant.
/* API.h */
#define NOT_NULL( a ) ( ( a ) != 0 )
/* Native.c */
#include API.h
void f ( char * p )
{
if ( NOT_NULL( p ) ) /* Expansion violates MISRA C:2012 Rule 11.9 */
{
use( p );
}
}
The macro NOT_NULL defined within the API header file is itself perfectly compliant, but when the
macro is invoked with a pointer argument, a violation results within the native code. In order for the
code to be compliant, the macro would need to be written as:
2. Pointer arithmetic;
As it is part of the implementation, and its functionality and interface are defined in The Standard,
Standard Library code is not required to comply with MISRA Guidelines. Unless otherwise specified in
the individual guidelines, the contents of standard header files, and any files that are included during
processing of a standard header file, are not required to comply with MISRA C. However, guidelines
that rely on the interface provided by standard header declarations and macros are still applicable.
For example, the guidelines related to type checking of function arguments and return values apply to
those functions specified in The Standard Library.
Note: Where a project decides it is of benefit, The Standard Library may be treated in exactly the same
way as any other piece of adopted code.
14
7 Claiming MISRA compliance
A project cannot be described as “MISRA Compliant” unless development has been conducted in
accordance with the process and principles described in this document. A range of complex issues
have been described and these must be appropriately addressed and documented.
Staff who are developing code should receive appropriate training so that they are competent in
understanding both the The Guidelines and the relevant language issues. The supplier shall maintain
staff competence records to allow an acquirer to confirm that the staff responsible for the project's
MISRA related activities have the relevant skills and experience. Staff involved in the approval of
deviations, within both the supplier and acquirer organisations, need to be especially knowledgeable
and experienced.
During the development phase, the processes by which deviation permits (where adopted) are
compiled and deviations are authorized will be of critical importance if development is not to be
unduly disrupted. These processes may or may not involve the acquirer, but even within the supplier
organization a clear chain of responsibility must be established with the involvement of suitably
competent staff.
When a development contract is negotiated, constraints may be introduced to limit the freedom
which the supplier has for introducing deviations. These constraints are enforced by:
These constraints will commonly be imposed by the acquirer as a means of exercising control over
the development, but they may also be supplemented by additional restrictions introduced internally
by the supplier.
15
Section 7: Claiming MISRA compliance
Consider the two contrasting examples provided below:
Example 1
The supplier is given the responsibility to create his own deviations and GRP, and these are reviewed
by the acquirer at agreed milestones during the project. This process:
● Incurs a greater risk of deviations being introduced which the acquirer later considers to be
unreasonable;
● May require rework by the supplier if deviations are deemed unacceptable by the acquirer.
Example 2
The contract imposes a restrictive GRP in which the majority of guidelines are re-categorized as
Mandatory and where any violation of a Required guideline must be covered by a deviation which
complies with an approved deviation permit. These deviation permits will be agreed between acquirer
and supplier at the start of the project, except in exceptional circumstances when they may be the
subject of negotiated agreement during the development phase. This process:
● Potentially incurs greater disruption in development if approval for a new deviation permit has
to be sought from the acquirer.
Both of these examples describe valid processes and both depend on the necessary review activities
being administered responsibly and efficiently. The essential difference between the two approaches
is the degree of freedom granted by the acquirer to the supplier in the introduction of deviations.
At the conclusion of a project, a guideline compliance summary (GCS) shall be produced to record the
final compliance level claimed by a project in its totality. The GCS includes an entry for each guideline
within The Guidelines and records the level of compliance with it, as permitted by its MISRA category.
2. Deviations — There are violations of the guideline within the project which are all supported
by deviations;
3. Violations — There are violations of the guideline within the project which are not supported
by deviations;
16 4. Disapplied — No checks have been made for compliance with the guideline.
The compliance level that may be declared for each guideline depends on its MISRA category:
These levels allow the extent to which compliance has been achieved across the project to be
reflected, capturing the worst-case enforcement permitted by the GRPs that have been applied.
Note: Where multiple GRPs are used within a project, it may be easier to maintain a GCS for each GRP.
These can then be used to produce a combined GCS at the conclusion of the project.
Examples
1. A Required guideline is re-categorized as Mandatory within the native code GRP and is left as
Required within an adopted code GRP. The GCS would claim a compliance level of Deviations
as there were deviations in at least one component (the adopted code);
2. An Advisory guideline is re-categorized as Required within the native code GRP and as
Disapplied within an adopted code GRP. The GCS would claim a compliance level of Disapplied
as compliance was not checked in at least one component (the adopted code).
1.1 The documentation listed in Section 3.3, demonstrating how compliance has been
enforced;
1.2 Documentary evidence proving which tool checks have been performed;
These documents will be supplied to the acquirer in the first instance, but may also be used to
provide evidence to any other party who may subsequently use the developed code.
18
8 References
[1] Guidelines for the Use of the C Language In Vehicle Based Software, ISBN 0-9524159-9-0, Motor
Industry Research Association, Nuneaton, April 1998
[2] MISRA-C:2004, Guidelines for the use of the C language in critical systems, ISBN 978-0-9524156-2-
6, MIRA Limited, Nuneaton, October 2004
[3] MISRA C:2012, Guidelines for the use of the C language in critical systems, ISBN 978-1-906400-10-
1, MIRA Limited, Nuneaton, March 2013
[4] MISRA C++:2008, Guidelines for the use of the C++ language in critical systems, ISBN 978-1-
906400-03-3, MIRA Limited, Nuneaton, June 2008
[5] ISO/IEC 12207:2008, Systems and software engineering — Software life cycle processes, ISO, 2008
[8] DO-178C/ED-12C, Software Considerations in Airborne Systems and Equipment Certification, RTCA,
2011
[10] IEC 62304:2006, Medical device software — Software life cycle processes, IEC, 2006
[11] ISO/IEC 25010:2011, Systems and software Quality Requirements and Evaluation (SQuaRE) —
System and software quality models, ISO, 2011
19
Appendix A Example deviation record
Project F10_BCM
Deviation ID D_00102 Status Approved
Permit Permit / Example / C:2012 / R.10.6.A.1
The value of a composite expression shall not be assigned to an object with wider
Rule 10.6
essential type
The value of a composite expression is assigned to an object of wider essential
Use-case
type to avoid sub-optimal compiler code generation
Code Quality
Reason Scope Project
(Time behaviour)
Tracing tags D_00102_1 to D_00102_10
E C Unwin D B Stevens
Raised by Approved by
Signature Signature
Position Software Team Leader Position Engineering Director
Date 14-Mar-2015 Date 12-Apr-2015
A.1 Summary
The rationale for MISRA C:2012 Rule 10.6 is that it avoids potential developer confusion regarding the
type in which some arithmetic operations take place. Unfortunately, because of a “feature” of the
compiler being used on this project, it is not possible to make the code comply with the rule without
incurring serious run-time performance degradation. The impact of this is that the software’s timing
requirements cannot be satisfied in all cases and there is a significant risk that the vehicle’s legislated
hydrocarbon emissions target will not be met.
Since the C compiler in use on this project implements the int type in 32-bits, the code to compute
the 32-bit product is:
Clearly, even though the operands of the multiplication operator are 32-bit, there is no possibility that
the product is too large for 32-bits because both operands were zero-extended from 16-bits.
In accordance with our standard development procedures, all object modules are passed through a
worst-case execution time analysis tool to ensure that each function meets its execution time budget
as specified in the architectural design. The analyser highlighted that the code generated for these
integrators was far in excess of the budget laid out for them. Investigation revealed that the reason
for the excessive execution time was that the compiler was generating a call to a “shift-and-add” style
of long multiplication routine. This is surprising because the processor is equipped with an IMUL
instruction that is capable of multiplying two 16-bit unsigned integers to deliver a 32-bit result in a
single clock cycle. Although the multiplication operands are 32-bit, the compiler has the means to
20 know that the most significant 16-bits of these operands are 0 so it should be capable of selecting
the IMUL instruction.
Experimentation with the compiler suggests that it will select the IMUL instruction provided that the
This is particularly odd because the behaviour of the code as described by the C Standard is
independent of whether the conversion is implicit or explicit. While the program will generate the
same results regardless of whether IMUL or a library call is used for multiplication, the library call
requires a worst case of 100 cycles to execute. The compiler vendor has confirmed in writing that this
is the behaviour they expect under the circumstances.
A.3 Justification
Since this type of integrator is used in several functions in the project and is executed at least once
every 100 microseconds on average, the performance of the library function is not acceptable. At the
specified CPU internal frequency of 25 MHz this means that 4% of the time is spent just on these
multiplications. This in itself is insignificant and can be contained in the headroom available in the
overall timing budget. However, the design specifies that the integrator shall make its result available
within a maximum of 10 microseconds in order to satisfy timing requirements of other functions. The
failure to meet this requirement means that there is significant risk in achieving the emissions target,
the commercial implications of which are in excess of $10m.
Our preferred solution to this problem is to write the integrators using implicit conversions. This
would require deviation against MISRA C:2012 Rule 10.6 for instances of such an integrator. The code
is functionally identical to that generated by the MISRA-compliant code but executes up to 100 times
faster.
● Increase the clock speed — to achieve the required performance would require a 10-fold
increase in clock but the processor’s maximum PLL frequency is 100 MHz;
● Change processor — not commercially viable given that hardware design validation is well
underway; the additional costs to the project would be around $250,000 and there would be
a timing impact too;
● Change compiler — there is no other commercially recognized compiler for this processor;
there is an unsupported public domain compiler but it is not considered of suitable quality
for this project;
● Recode the library routine — the library uses a base-2 long multiplication; it could be
recoded to implement a base-65 536 long multiplication using 3 IMUL instructions but we are
reluctant to make changes to the compiler vendor’s code; we have sought their views on this
approach and received the response that “they could not support us making changes to their
library”.
A.4 Scope
This deviation applies to all instances of variable time-step integrators within the project.
There are no additional verification and validation requirements resulting from this deviation.
a macro can be used to implement the integrator and suppress the warning. The following macro will
be used to implement the multiplication and assignment of its result to the product term:
Although this macro could be implemented as a function, the overhead of the call and return is
excessive given the simplicity of the operation being performed. A macro is therefore preferred to a
function in this instance even though this means violating Dir 4.9.
22
Appendix B Example deviation permit
Rule 10.6 The value of a composite expression shall not be assigned to an object
with wider essential type
Background
The assignment of a composite expression to a wider essential type is generally not permitted as it is
unclear if the expression is expected to be evaluated in the narrower type of the operands or the
wider type of the result.
The “ABC” compiler produces inefficient, slow code when two 16-bit operands are multiplied to
produce a 32-bit result when either or both of the operands are cast to a 32-bit type as required to
make the expression comply with Rule 10.6.
Performing such multiplications in the absence of the casts yields exactly the same result (due to the
effects of integer promotion) with a significant reduction in execution time as a single instruction is
used rather than a call to a shift-and-add style long multiplication routine.
Requirements
1. The wider essential type shall have a size of 32 bits (i.e. the same as the size of int);
4. The composite expression shall only contain the arithmetic multiplication operator;
23
Appendix C Glossary
Acquirer
Organisation or person that enters into an agreement to acquire or procure a product or service
from a supplier.
Adopted code
Code that has been developed outside the scope of the current project which may or may not have
been developed so as to comply with The Guidelines applied to the project.
Deviation
Deviation permit
The specification of a use-case and a set of requirements which may be applied to justify a deviation.
Deviation record
Guideline
A policy agreed between the acquirer and the supplier whereby the MISRA category assigned to each
guideline within The Guidelines is reviewed and in some cases superseded by a more stringent
category.
A record of the level of compliance achieved by indicating where guidelines have been Disapplied,
where violations are present and where deviations have been introduced.
The Guidelines
A generic term denoting one of the MISRA guideline documents (currently [1], [2], [3] and [4]).
MISRA category
A classification (Mandatory, Required or Advisory) applied to every guideline within The Guidelines that
establishes the conditions under which a violation may or may not be permitted.
Native code
Code that has been developed within the scope of the current project which has been developed so
as to comply with The Guidelines applied to the project.
Revised category
The classification (Mandatory, Required, Advisory or Disapplied) applied to every guideline within the
24
guideline re-categorization plan as a result of guideline re-categorization.
The Standard
Appendix C: Glossary
A generic term denoting the ISO language standard referenced by a MISRA coding guideline
document.
Supplier
Organisation or person that enters into an agreement with the acquirer for the supply of a product or
service.
Violation
25