Professional Documents
Culture Documents
Method C-Coding Standard
Method C-Coding Standard
22
Status: RELEASED
C-Coding Standard
Date: 17-Feb-2021
Page: 1 of 40
C-Coding Standard
Table of Contents
1 Introduction ....................................................................................................................................... 4
1.1 Purpose and Scope ................................................................................................................... 4
1.2 Acronyms .................................................................................................................................. 4
1.3 Interpretation of Terms .............................................................................................................. 4
1.4 Definitions.................................................................................................................................. 4
1.5 Conventions in this document ................................................................................................... 5
2 C programming language standard ................................................................................................ 6
2.1 Assembly code with C ............................................................................................................... 6
3 Naming Conventions ........................................................................................................................ 6
3.1 General Rules ........................................................................................................................... 6
3.2 Types......................................................................................................................................... 7
3.3 Variables ................................................................................................................................... 8
3.3.1 Global Variables.................................................................................................................... 9
3.3.2 Local Variables ..................................................................................................................... 9
3.4 Enums ..................................................................................................................................... 10
3.5 Structures / Unions .................................................................................................................. 10
3.6 Functions ................................................................................................................................. 12
3.7 Pointers ................................................................................................................................... 13
3.8 Constants ................................................................................................................................ 13
3.9 Defines / Macros ..................................................................................................................... 13
4 Layout ................................................................................................................................................ 15
4.1 General Rules ......................................................................................................................... 15
4.2 Line Rules ............................................................................................................................... 15
4.3 Code Blocks ............................................................................................................................ 15
4.4 Condition Statements .............................................................................................................. 15
4.5 Switch Statements .................................................................................................................. 16
4.6 Spaces .................................................................................................................................... 16
4.7 Parenthesis ............................................................................................................................. 17
4.8 Local variables ........................................................................................................................ 17
4.9 Temporary Code Blocks .......................................................................................................... 17
4.9.1 Based on temporary requirements or request .................................................................... 17
4.9.2 Related with bug-fixing of supplier code ............................................................................. 18
4.10 Engineering Code Blocks ........................................................................................................ 18
5 Documenting the code ..................................................................................................................... 20
5.1 General Rules ......................................................................................................................... 20
5.2 Used Doxygen Tags ................................................................................................................ 20
1 Introduction
1.1 Purpose and Scope
The purpose of this document is to define a mandatory C-code guidelines considering MISRA-C:2012, HIS,
ASPICE, AUTOSAR and ISO 26262-6. The guideline shall be followed to ensure uniformity in the code for
all ZF Division U: Electronics and ADAS projects. Such uniformity facilitates more effective design reviews
and minimizes the effort required for multiple engineers to work as a cohesive team.
The scope of this document is related to the content of C source code files.
1.2 Acronyms
Table 1. Acronyms
1.3 Interpretation of Terms
The following rules are observed within this document:
1.4 Definitions
Basic type / standard type Native C language types as defined in ISO/IEC 9899:1999 chapter
6.2.5
e.g. there are five standard signed integer types, designated as signed
char, short int, int, long int and long long int.
Code block / compound A block is a compound of one or several statements that begins with
statement ‘{‘ and ends with '}'.
File scope A variable or function that is only visible within one file.
Global scope A variable or function that is visible in more than one file.
Data type suffix Consists an abbreviation for the associated data type.
Table 2. Definitions
Example: Rule identifier shall not be changed over lifetime of this document.
Rule 000
If rule has to be removed, identifier shall be removed as well, without re-iterating remaining identifiers.
Removed identifiers shall be documented in revision history as well as in chapter 0.
Examples:
typedef struct Diag_SensorXType_Tag
{
uint8 Data_u8;
uint32 Crc_u32;
} Diag_SensorXType;
3 Naming Conventions
3.1 General Rules
Rule 007 a) The first letter and only the first letter of every word in a function or variable name shall be
uppercase unless it is a local variable (e.g. CounterBuffer, GetCounterBuffer()).
Rule 008 b) In function or variable name: the underscore separator (“_”) shall only be used to separate
SwComponentPrefix or DataTypeSufix – is not allowed to be used for other purposes.
Rule 009 c) Variables and types definition shall not share the same name, regardless if upper or lower case.
Rule 010 d) All the names of functions, variables, constants, macros, defines and comments shall be in
English.
Rule 011 e) For abbreviations of names, the use of upper case and lower case letters for differentiation shall
be used. For example, the 2 abbreviations TEE and SCS combined would be spelled as a variable:
TeeScs_u8
Rule 012 f) Identifiers defined in the same name space shall NOT differ by any combination of:
o the interchange of a lowercase character with its uppercase equivalent
3.2 Types
Rule 013 a) Each basic variable type shall be defined using typedef.
Rule 014 b) Custom type names shall be composed like <SwComponentPrefix>_<TypeName>Type.
Rule 015 c) All type definitions that are defined in a header file shall have a SwComponent prefix, except for
the basic types.
Rule 016 d) The following table shows the typedef names that shall be used for all basic variables. These types
are platform dependent and shall be defined in Platform_Types.h:
E_OK: 0, E_NOT_OK: 1
Examples:
typedef unsigned char uint8; /* Type definition in header file Platform_Types.h */
typedef signed short sint16; /* Type definition in header file Platform_Types.h */
typedef uint8 Std_ReturnType; /* Type definition in Std_Types.h*/
typedef uint8 SqSoc_SatelitesType; /* Type definition in <SwComponentName.h>*/
3.3 Variables
Rule 017 a) The scope of each variable shall be as limited as possible.
Rule 018 b) Variables which are only used in one code block shall be also declared at the beginning of this
code block.
Rule 019 c) Each variable shall be defined on a separate line.
Rule 020 d) Usage of global variables shall be avoided. For data exchange between functions within a C-unit
local function arguments or file scope static variable is recommended. (ISO26262-6:2018, Table 3
1d).
Rule 021 e) Each instance name shall end with a data type suffix, except:
o instances of self-defined types
o 1 letter local variable used for loop control (i, j, k) – see 3.3.2 0
Rule 022 f) The following table shows the data types suffixes that shall be used for variables:
Data type
Type Definition Example
suffix
uint8 data_au8[5U];
pointer to array _pa or _paX uint8 *pointer_pau8 = data_au8;
uint8 (*pointer_pau8)[5U];
function pointer - _pf to be used void (*foo_pf)();
_pf
for function pointer variables foo_pf();
Examples:
Purpose / Composition SwComponent Name File Name SwComponent Prefix Interface example
Examples:
void func()
{
uint8 loopCounter_u8; /* variable with local scope */
uint8 sigComKlemmen_u8; /* variable with local scope */
}
3.4 Enums
Rule 029 a) All enum identifiers that are defined in a header file shall have a SwComponent prefix.
Rule 030 b) Enum identifiers shall be written in upper case.
Rule 031 c) Enum identifiers shall have no suffix.
Examples:
typedef enum Diag_CrcDataType_Tag /* Enum type definition */
{
DIAG_CRC,
DIAG_ROM,
DIAG_END
} Diag_CrcDataType; /* enum type with SwComponent prefix */
enum MyEnum /* Enum that is not a type and not used globally */
{
MONDAY = 1,
TUESDAY
};
Examples:
typedef struct BitMaskType_Tag
{
uint32 Val1_b : 1; /* ISO-C standard states that bit-fields */
uint32 Val2_b : 1; /* can only be defined with type int or _Bool: */
uint32 Val3_b14 : 14; /* unsigned int, signed int or _Bool */
} BitMaskType;
Bitfields can have 2 types of 1-bit values. One is a single bit with the meaning of 0 and 1. The other is
a boolean, with values true and false. These are not the same and both have specific use cases.
Document Path in STAGES:
Methods > Software Development > Software Detailed Design, Implementation and Component Test > C-Coding Standard
ZF Proprietary: Printed copies are for reference only-controlled copy located in STAGES.
Revision: 1.22
Status: RELEASED
C-Coding Standard
Date: 17-Feb-2021
Page: 11 of 40
The single bit is usually used to map registers where the 32 bit value is split into smaller chunks.
The second is used to simply have a boolean value in the bitfield. The data type suffix depends on which
of the 2 case is used:
typedef struct BitMaskType2_Tag
{
uint32 SingleBit_b : 1; /* single bit - assigned values should be 0U or 1U */
bool BooleanValue_bo : 1; /* boolean – assigned values should be true or false */
uint32 LongerValue_b5 : 5; /* 5 bit value */
} BitMaskType2;
Diag_UnitType Diag_AirBag;
Diag_AirBag.FrontAct.Status_u8 = 1U;
Compiler is going to re-layout memory and add empty space of 7 bytes (padding) after speed_u8 (in order
to align address of “next_p” to 8-bytes boundary) and 6 bytes after temp_u16. Memory would be used as
shown below:
struct foo10
{
uint8 Speed_u8; /* 1 byte */
uint8 Pad1_u8[7]; /* 7 bytes */
struct foo10 *Next_p; /* 8 bytes */
uint16 Temp_u16; /* 2 bytes */
uint8 Pad2_u8[6]; /* 6 bytes */
};
Considering self-alignment, we see that none of the data fields need padding. This is because the stride
address for a (longer) field with stricter alignment is always a validly-aligned start address for a (shorter)
field with less strict requirements. All the repacked struct actually requires is trailing padding:
struct foo11
{
struct foo11 *Next_p; /* 8 bytes */
uint16 Temp_u16; /* 2 bytes */
uint8 Speed_u8; /* 1 byte */
uint8 Pad_u8[5]; /* 5 bytes */
};
3.6 Functions
Rule 038 a) The name of a function shall start with a SwComponent prefix (excluding static inline functions).
Rule 039 b) Type names for function pointers created with typedef shall have the suffix “Type”.
Examples:
File Name Purpose SwComponent Prefix
Rule 040 c) For the exchange of data between C-units (C-files) function calls shall be used (ISO26262-6:2018,
Table 3 1e).
Examples:
void TempSens_SetRawValue(sint16 rawTemp_s16); /* set the temperature raw value */
sint16 TempSens_GetTemp(void); /* get the result */
3.7 Pointers
Rule 041 a) Pointers (including pointers to function) are considered unsafe and should be avoided (ISO26262-
6:2011, Table 8 1f).
Rule 042 b) Pointers shall be declared with a space character between the type and the asterix (“*”) symbol
and no space between the “*” symbol and the variable name.
Rule 043 c) If there is another keyword (e.g. const) that follows the “*” symbol, there shall be no space between
the “*” symbol and the keyword.
Examples:
uint8 *hold_pu8 = NULL; /* Pointer to U8 variable */
const uint8 *numberOfAsics_pu8 = NULL; /* Pointer to U8 variable that is constant */
uint8 *const configuration_pu8 = NULL; /* Constant pointer to U8 variable */
const uint8 *const crc_pu8 = NULL; /* Constant pointer to U8 variable that is
constant */
static const uint8 *const buffer_pu8 = NULL; /* Constant pointer to static U8 variable
that is constant */
3.8 Constants
Rule 044 a) Suffix “U”, “UL”, and “ULL” for unsigned integer constants shall be written in upper case.
Rule 045 b) Suffix “L” and “LL” for long (long) integer constants shall be written in upper case.
Rule 046 c) Suffix “F” for single precision float constants shall be written in upper case.
Rule 047 d) Start hexadecimal numbers with 0x followed by digits (0…9) or uppercase letters (A…F).
Rule 048 e) Hexadecimal numbers shall be preceded with 0 to have length of multiple of 2 (e.g. 0x01 not 0x1)
Rule 049 f) Floating point numbers shall have at least one number on each side of the decimal point.
Rule 050 g) Floating point numbers represented with exponent format shall use upper case “E” as exponent-
part.
Rule 051 h) Use numeral system (dec or hex) which suits the most for represented value, hex is not always the
best option.
Examples:
var1_u8 = 070U; /* NOT OK: Octal is not allowed by MISRA */
var2_u8 = 70U; /* OK: decimal 70 */
var3_f32 = 5.0F; /* OK: one number on each side of the decimal point */
var4_f32 = 123E-2F; /* OK: floating 1.23 */
elapsedSeconds_u32 = 0x0BCDU; /* NOT OK: Decimal would be better for seconds */
Examples:
#define DIAG_THREE_HUNDRED (300U) /* NOT OK: spells out numeric; brackets */
#define DIAG_TEMP_OFFSET 300U /* OK: no semicolon at the end as well */
#define DIAG_CURRENT_STATE Diag_DiagnosticState_u8 /* NOT OK: macro hide an object */
4 Layout
4.1 General Rules
Rule 062 a) All files shall follow the outline as defined by Templates (REF-01)
Rule 063 b) There shall be only one coding statement per line.
Examples:
/* Split a string of conditionals before logical operators */
if ((TotalCount_u16 < Needed_u16)
&& (Needed_u16 <= MAX_ALLOT)
&& (NULL == p->Next_p))
{
}
Examples:
for (uint8 i = 0; i < LOOP_COUNT; ++i) /* Proper use of brackets and indentation */
{
if ((MyStruct_a[i].Voltage_u8 == ArgValue_u8)
&& ((MyStruct_a[i].DataFlag_b & ArgFlag_b) != 0))
{
ret_u8 = MyStruct_a[i].Counter_u8;
}
} /* comment this block */
Examples:
if (DIAG_TIMEOUT == timerCounter_u8) /* OK */
if (timerCounter_u8 == DIAG_TIMEOUT) /* NOT OK – constant on right side */
if (timerCounter_u8 >= DIAG_TIMEOUT) /* OK */
Examples:
switch (AxesColor_u8)
{
case GRAY: /* comment is necessary for this fall-through statement */
case BLACK:
Color_u8 = BLACK;
break;
case YELLOW:
Color_u8 = YELLOW;
break;
case RED:
Color_u8 = RED;
break;
default:
ErrorHandling(); /* prefer function call over extensive code in case block */
break;
}
4.6 Spaces
Rule 077 a) There shall be one space character between a keyword and an opening parenthesis.
Rule 078 b) There shall be one space character after each comma and semicolon within an expression.
Rule 079 c) Unary operators shall be written with no spaces between them and their operands (e.g. “n_u8++”,
”&n_u8”).
Rule 080 d) All non-unary assignment, arithmetic, logical and bitwise operators shall have one space before
and after them (e.g. “=”, “+”, “==”, “>>”).
Rule 081 e) The following operators shall have one space before and after them: “?”, “:” (conditional
expression).
Rule 082 f) The primary operators: -› , . , and [ ] shall not have spaces around them.
Rule 083 g) There shall be no space before an opening parenthesis following a function name.
Rule 084 h) There shall be no spaces between the parenthesis and an expression within the parenthesis.
Rule 085 i) There shall be no space between a cast and its operand.
Rule 086 j) Space rules could be ignored if would lead to worse readability of code (e.g. multiple lines of
variables initialization could adjust assignment operator “=”)
Examples:
if (Var1_u8 == Var2_u8) /* Spacing after “if” and around the non-unary operator “==” */
{
Function(Var1_u8, Var2_u8, Var3_u8); /* No space after function name. Space after comma */
Var4_u8++; /* Unary operator written without a space */
}
Var1_u8 = Var2_u8 + Var3_u8; /* Spacing before and after operator “=” and “+” */
4.7 Parenthesis
Rule 087 a) The objects of sizeof operator shall always have parenthesis around them.
Rule 088 b) The objects of return statement shall NOT have parenthesis around them.
Examples:
uint8 func()
{
uint8 size_u8 = sizeof(uint8); /* OK: sizeof always with brackets */
uint8 size_u8 = sizeof uint8; /* NOT OK: lack of brackets is not acceptable */
Examples:
void func()
{
uint8 localA_u8; /* Variable defined at the beginning of the block */
...
{
uint8 localB_u8; /* Variable defined at beginning of block */
... /* without control expression */
for (uint8 i = 0; i < RANGE_LIMIT; ++i)
{
...
}
}
...
}
Rule 121 a) Each temporary code block shall be enclosed between special markers / comments:
/*!--- TEMP_START: <REQUEST_CM_ITEM_ID> / RevertBy: <REVERT_CM_ITEM_ID> ---!*/
where:
<REQUEST_CM_ITEM_ID>: Change Management (CM) item reference, which request
temporary implementation. Format shall include CM tool
name.
<REVERT_CM_ITEM_ID>: Change Management (CM) item reference, which will be
used to revert the changes (to be agreed with Project
Management). Using this item, CI system will monitor
revert deadline. Format shall include CM tool name.
Example:
/*!--- TEMP_START: PTC_123456789 / RevertBy: PTC_987654321 ---!*/
Rule 122 a) Each supplier bug-fix code block shall be enclosed between special markers / comments:
/*!--- PATCH_START: <REQUEST_CM_ITEM_ID> / RevertBy: <REVERT_CM_ITEM_ID> ---!*/
where:
<REQUEST_CM_ITEM_ID>: Change Management item reference, which request
temporary implementation. Format shall include CM tool
name.
<REVERT_CM_ITEM_ID>: Change Management item reference, which will be used to
revert the changes (to be agreed with Project
Management). Using this item, CI system will monitor
revert deadline. Format shall include CM tool name.
Example:
/*!--- PATCH_START: PTC_123456789 / RevertBy: PTC_987654321 ---!*/
Watchdog reset disabling – for breakpoint usage purpose, to avoid side effects in
▪
case of debugger command
▪ Code to send debug information on bus (e.g. CAN, SPI, UART)
▪ Logging additional information about program or data flow
o Test Code – all code, which makes testing easier or possible. May cover implementation
like:
▪ Fault injections to test fault handling functionality
▪ Program control flow changes / flow enforcement
Rule 123 c) Each part of code that meets the criteria of the above categories shall be qualified as engineering
code to which all described by this chapter rules must be applied.
Rule 124 d) Each engineering code block shall be enclosed by preprocessor directives as follow:
#ifdef <EngineeringBlockIdentifier>
#warning This part of code is intended to be disabled for release
…
/* engineering code block */
…
#endif
where:
<EngineeringBlockIdentifier>: <CategorySpecificTag>_<SwComponentPrefix>
Examples:
#ifdef TEST_MESP
#warning This part of code is intended to be disabled for release
<code>
#endif
#ifdef DEBUG_ANALOGINPUT
#warning This part of code is intended to be disabled for release
<code>
#endif
Examples:
#if 0 /* NOT OK: code shall never be commented out */
void func()
{
/* if (Diag_LogErrors_bo) */ /* NOT OK: code shall never be commented out */
{
...
}
...
}
#endif
Examples:
/**
* @details description, don't copy name here!
* @param[in] arg1_s8 describe here what is the argument for, range, etc.
* @return explain the return information
*/
uint8 Component_RadarValid(const sint8 arg1_s8);
/**
* @details local variable description
* @MAX a max value
* @MIN a min value
* @UNIT the unit
* @RESOLUTION proper resolution
* @OFFSET the offset value
*/
static uint8 Component_TempData_u8;
Examples:
/**
* @details description, don't copy name here!
* whenever possible group defines into enum when they have a meaning together
*/
typedef enum Component_QualityType_Tag
{
COMPONENT_SIGNAL_BAD = 0, /** @brief short description */
COMPONENT_SIGNAL_GOOD /** @brief short description */
} Component_QualityType;
Examples:
while (EOF != var1_u8)
{
/* This is an example of an inline comment */
Function2(var1_u8);
Var1_u8 = Function1();
}
Examples:
if (speed_u8 < SPEED_LIMIT)
{
/* very large code block */
} /* speed below limit */
if (var1_u8 == var2_u8)
{
/* very large code block */
} /* (var1_u8 == var2_u8) */
Rule 127 b) While creating TODO comment following rules have to be followed:
o Change Management item has to be created and it’s ID has to be added to the comment.
o Description has to be: unambiguous, complete and consistent with surrounding code.
o This field cannot be used to justify bad solutions or errors.
o This is not a place for a discussion.
o TODO documentation in the source code shall have the following format:
where:
<Summary> Short, one sentence, summary of TODO item (displayed by IDE).
<FOLLOWUP_CM_ITEM_ID> Change Management (CM) item reference, which will be used to track
required effort and actions (e.g. assumption clarification). Format shall
include CM tool name.
<Description> Optional description of the related topic
Rule 128 c) FIXME and other similar tags are not allowed to be used.
Examples:
else if ((END_OF_SPEED_LIMIT == speed_value_u8)
|| (END_OF_ALL_RESTRICTIONS == speed_value_u8))
{
/* TODO: Clarify end of speed case for age_dist; PTC_4502722
* Case not clearly defined in the input requirement: SwRS_12345.
* This shall be clarified, for now the SL005_050 value is safe fallback solution.
*/
age_dist_u8 = TSM_AlgCal.AgeDist_SL005_050_u8;
}
Specific deviations will be suppressed in the code using the following syntax:
For MISRA Required, MISRA Mandatory or CERT-C Rules related QAC messages:
Document Path in STAGES:
Methods > Software Development > Software Detailed Design, Implementation and Component Test > C-Coding Standard
ZF Proprietary: Printed copies are for reference only-controlled copy located in STAGES.
Revision: 1.22
Status: RELEASED
C-Coding Standard
Date: 17-Feb-2021
Page: 23 of 40
Where:
<Deviation Number>: Change Request(s) ID of the used type of violation; could be “N/A” for MISRA
Advisory or CERT-C Recommendation related messages (see [REF-03]).
<Message description>: Short description of rule (e.g. QAC message text), preceded by Coding Standard
rule ID (e.g. MISRA or CERT-C) – this field could be multiline, especially when many rules are violated by
single code line
<Deviation Reason>: Reason / Justification for this violation; needs to also explain risk of violation – this
field could be multiline, especially when many rules are being violated by single code line
<Safety Justification>: Justification how safety is insured (this line should be left out completely if
an individual safety justification is not requested for the deviation request) – this filed could be multiline
“QAC CCB APPROVED”: Serve for easy identification that this justification had been approved by process
(see 4.8 a) – required for MISRA Required, MISRA Mandatory or CERT-C Rules related messages (see
[REF-03])
PRQA: QAC key word
S: QAC suppression command
<message number>: QAC message(s) number to suppress
<lines>: Number of physical lines to be suppressed
Examples:
/* QAC_DEVIATION: N/A
DESCRIPTION: MISRA 11.4: Cast between a pointer to volatile object and an integral type.
JUSTIFICATION: Conversion is required to get an access to memory mapped registers which are
not accessible with standard MCAL interfaces.
*/
/* QAC CCB NOT REQUIRED */ /* PRQA S 0303 1 */
volatile uint8 *regAdc_pu8 = (volatile uint8 *)ADC_REG_ADDR;
Rule 114 c) Documentation of justification in the source code shall have the following format:
g) Replace the key word (Kind1, Severity, etc.) with valued indicated in table below:
Replace Replace with
Kind1, Kind2,…, Kind[n] Use acronyms from the list. Multiple checks can be separated by comma
(i.e.: COR, ZDV).
Acronym Description
OVFL Overflow
Severity Text that indicates how critical you consider the defect. Enter one of the
following severity:
- Low (the violation that does not impact the functionality of the SW
Component containing it)
- Not a defect (the violation that you are sure that it’s not a defect and
you have proven it)
This text populates the Severity column on the Results List pane.
Status Text that indicates that the violation had been analysed and justified
This text populates the Status column on the Results List pane.
CCB Indication In case Polyspace CCB flow was required (red finding) and justification had
been approved use:
- CCB APPROVED
In case Polyspace CCB flow was not required (orange and gray findings)
use:
- CCB NOT REQ
CR No. The number of change request created in PTC Integrity for CCB approval or
“N/A” in case Polyspace CCB process was not required.
Justification reason Any text containing the justification described in details. Why it can’t be
fixed. Why it is not risk to justify it.
return messageId_u8;
}
(void)Psm_GetVoltage(PSH_IGNP, &(kl15_local_voltage_mV));
/* polyspace:end<RTE:ZDV:Low:Justified> */
6 Design Guidelines
This section provides additional guidelines, which shall be considered during C-code development.
6.1 MISRA based guidelines
Additional guidelines based on MISRA Coding Standard Directives and Rules, which cannot be enforced
by static code analysis, therefore have to be enforced by review of the code against the C-Coding Standard.
Rule 130 a) If function returns error information, then that error information shall be tested.
Rule 131
b) Functions which are designed to provide operations on a resource (e.g. semaphore) shall be called
in appropriate sequence (e.g. “obtain” first then “release” the semaphore).
Rule 132 c) Every loop on an external condition shall be protected with a timeout detection (e.g. waiting for
hardware signal/resource).
7 Supportive Guidelines
This section provides additional guidelines, which shall be considered during C-code development, but are
not definitive rules, as usually depends on context and actual use cases in project.
k) Make sure buffers can fit data you put into them (buffer overflow prevention) – make use of
bounds checking interfaces (e.g.: memcpy_s(), see C11 Annex K);
l) Make sure any code that deals with secret execute in constant time (assembly level);
m) Don’t implement cryptography by yourself, use well proven libraries;
n) Don’t use deprecated or broken algorithms for crypto primitives, e.g.: at least SHA2 for hash,
AES with 128-bit key, etc.;
o) Use True Random Number generator as entropy source;
p) For dealing with secrets use dedicated functions, e.g.: constant time comparison function, secure
memory clear;
q) Use HSM if available;
r) Use microcontroller trap and exception mechanism, for some level of error handling, if available.
Example (only) of trust boundaries, which might outcome from trust model definition:
1. Don’t trust data coming from “outside world” (e.g. CAN frames), verify against expected values.
2. Don’t trust data coming from 3rd party code (e.g. AUTOSAR), verify against expected values.
3. Invoked ZF code trusts invoking ZF code (cascading trust).
4. Data shall be validated at interface level (as soon ZF developed code is executed).
5. Pointers shall be verified against NULL value (however there are still many incorrect values, which
lead to abnormal program execution, e.g. 0xFFFF_FFFF or memory corruption)
6. If during runtime global pointer from ZF code can take NULL (or any other incorrect) value, then it
also needs to be re-verified before being used (“cascading trust”; does not apply in this case).
Those trust boundaries shall are always project specific and shall be defined by software
architecture.
Exceptions
a) Protect your program to contain the damage caused by errors
b) Protect by memory, area, RAM, ROM separation
Please ensure that chosen error handling technique or protection mechanism as well as trust
boundaries are aligned with software architecture definition / guidelines.
In case trust boundaries are not provided in the project, ask project management or direct supervisor for
guidance.
MISRA compliance matrix document [REF-08] provides detailed guideline on rules enforcement. Rules are
either enforced with usage of QA-C tool or by code review process against rules defined in this document.
The standard configuration of QA-C tool will be located in the project template (see [REF-06]). Referenced
tool project template already enforces rule set defined by process metric “MISRA compliance” [REF-08].
The following tables show how we address the topic of coding guidelines as discussed in this standard.
ISO26262 Part 6:2018(E) Compliance
1a Enforcement of low complexity HIS code metrics are applied and checked by QAC
1b Use of language subsets MISRA C rules are applied and checked by QAC
1c Enforcement of strong typing See in this document: Error! Reference source not found.
1d Use of defensive implementation techniques See chapter Error! Reference source not found.
1e Use of well-trusted design principles This topic is in relation to design guidelines rather than coding guidelines
and so is not addressed directly here.
1g Use of style guides See in this document: Layout and Error! Reference source not found.
1h Use on naming conventions See in this document: Error! Reference source not found.
1i Concurrency aspects This topic is in relation to design guidelines rather than coding guidelines
and so is not addressed directly here.
Section 8.4.5 – Table 6 – Design principles for software unit design and implementation
1a One entry and one exit point in subprograms and Supported by MISRA C rules analysis (15.5)
functions
1e Avoid global variables or else justify their usage Section 3.3.1 and 3.6
1h No hidden data flow or control flow Supported by MISRA C rules analysis (5.3)
8.5 AUTOSAR
See [REF-05] for further information.
Rules driven by this C-Coding Standard document shall be verified in process of code review (as part of
Work Step “Implement the SW Units of the Component“ [REF-01]).
Enforcement of rules related to style of the code (e.g. parenthesis; whitespaces) is supported by CFormatter
tool [REF-14]. Tool has been designed to be compliant with this Coding Standard and its output shall not
violate any of the defined rules. In case of lack of style rule definition, CFormatter output shall be considered
as valid guideline. In case of any identified conflict with this Coding Standard, please contact author of this
Coding Standard.
10 References
Table 7. Reference
1.2 2018-Jul-12 KwiatkowskiPa Adusumalli V., Provided more examples of QAC justification comment
Ahlawat M., Duecker
F., Peri K., Ravuri Chapter 3.2 point b) and c) were merged together
N., Subramanian K., Line length requirement (shall) changed to
Tamraz D., recommendation (should)
Removed rule 4.4 d) A block comment shall not have
stars (“*”) on the right hand side.
Added Polyspace violation justification (provided by
Martin Gerharz team)
1.3 2018-Aug-24 KwiatkowskiPa Adusumalli V., QAC Deviation Request process required only for level
Ahlawat M., Duecker 6-8 messages
F., Peri K., Ravuri
N., Subramanian K.,
Tamraz D.,
1.4 2018-Sep-09 KwiatkowskiPa Adusumalli V., Replaced “module” with “SwComponent” and sync
Ahlawat M., Duecker definition with STAGES glossary.
F., Peri K., Ravuri
N., Subramanian K., Enforcement of C99 standard
Tamraz D., Line length is now 200 characters
New rules for Defines and Constants
1 letter loop control variable rule
_Bool type suffix and bitfield
Fixed some inconsistencies in examples
1.5 2018-Sep-27 KwiatkowskiPa Adusumalli V., Updated after review with PSE:
Ahlawat M., Duecker
F., Leuschner S., Defined suffixed for pointers of array and array of
Peri K., Ravuri N., pointer
Subramanian K., Removed “unused” member of bitfield in example
Fix formatting as underscore (“_”) wasn’t visible
Removed casting from example
Updated Condition Statements rules
Polsypace justification comment
1.6 2018-Oct-17 KwiatkowskiPa Adusumalli V., Updated code comments general rules
Ahlawat M., Duecker
F., Leuschner S.,
Peri K., Ravuri N.,
Subramanian K.,
1.7 2018-Nov-02 KwiatkowskiPa Adusumalli V., Polyspace example changed to avoid showing code
Ahlawat M., Duecker with bug
F., Leuschner S.,
1.9 2018-Nov-21 KwiatkowskiPa Adusumalli V., Removed Standard comment rule b] Function
Ahlawat M., Duecker prototypes in header files shall have the same function
F., Leuschner S., comment as their bodies in the C-file.
Peri K., Ravuri N.,
Subramanian K., It was in conflict with template and rule a]
1.10 2018-Dec-06 KwiatkowskiPa Adusumalli V., Update of Adherence standard chapter with references
Ahlawat M., Duecker to STAGES.
F., Gihr W.,
Leuschner S., Peri Update dead links of References.
K., Ravuri N.,
Subramanian K.,
1.11 2018-Dec-12 KwiatkowskiPa Adusumalli V., Fix of 3.3.1 enumeration and clarify scope of global
Ahlawat M., Duecker variable in those rules.
F., Gihr W.,
Leuschner S., Peri Fix code mistake/typo in Chapter 4.4
K., Ravuri N., Removed misleading example of pointer to volatile
Subramanian K., constant in chapter 3.7
1.13 2019-Mar-15 KwiatkowskiPa Adusumalli V., Removed GEE prefix from document.
Ahlawat M., Duecker
F., Gihr W., Aligned line length to C-code templates
Leuschner S., Peri Rules for dynamically allocated memory and stdio
K., Ravuri N., library
Subramanian K.,
1.15 2019-Oct-01 KwiatkowskiPa W. Forbes Updates based on Functional Safety team review:
- Reviewer evidence
- Rephrased purpose and scope of document
- Removed some definitions to avoid conflict
with ISO/IEC 9899:1999
- Add rule to explicitly force MISRA
compliance
- New example for MISRA rule justification
- Removed assertions from defensive
programming
1.16 2019-Oct-14 KwiatkowskiPa Adusumalli V., Basic type definition to follow C99 ISO standard
Buehler D., Gihr W.,
Goetz G., Huelsken Updated reserved keywords to C99
M., Leuschner S., Updated to cover 26262-6 2nd edition
Muppalla S.,
Paetkau V., Peri K., Information that structure padding / data alignment is
Ravuri N., implementation dependent
Schoessow P.,
Seylan I., “boolean” typedef changed to “bool” to avoid conflict
Subramanian K., with AUTOSAR standard files
1.18 2020-May-26 KwiatkowskiPa Buehler D., Krug M., Unique identifier for each rule.
Muppalla S., Peri K.,
Schoessow P.,
Seylan I., New rules to support compliance with not statically
Thirakanam V., enforceable MISRA C 2012 guidelines:
- Dir-4.2 +Dir-4.3: Assembly code mixed with
Global Coding C (Rule 005 + 006)
Standard CCB: - Dir-4.5: Typographically unambiguous
identifiers (Rule 012)
17-Jun-2020:
- Dir-4.4: Code shall not be commented out
Marc Schaefer, (Rule 099)
Patrick Niedhart,
William Forbes
(FuSa), Stephan
Leuschner,
Narasimha
Dachepalli, Inanc
Seylan
1.19 2020-Aug-24 KwiatkowskiPa Global Coding Removed “QAC deviation list” as it was misleading
Standard CCB: wording.
26-Aug-2020: Replaced “deviation” by “violation” (in context of static
code analysis) as deviation was misleading.
Marc Schaefer,
William Forbes Changed rule 094 (C++ comments are allowed in C99)
(FuSa), Stephan
Leuschner, Matthias Added example for rule 099
1.20 2020-Sept-23 KwiatkowskiPa Global Coding Replaced “boolean” with “bool” in Table 4. Variable
Standard CCB: Suffixes (to be consistent with decision made in
revision 1.16)
23-Sept-2020:
Updated bit-fields example to use ZF types instead of
Marc Schaefer, native types (example consistency improvement)
Matthias Krug,
Narasimha Replaced references of QAC message levels with
Dachepalli, Ashok MISRA / CERT-C guideline names (e.g. level 5 =
Chintalapati, MISRA Advisory Rule)
1.21 2021-Feb-05 KwiatkowskiPa Global Coding Rules 121-126 for Temporary Code & Engineering
Standard CCB: Code blocks (Div. U QIP)
Rules 127-128 for TODO & FIXME comments
17-Feb-2021:
Marc Schaefer,
William Forbes,
Stephan Leuschner,
Ashok Chintalapati,
Inanc Seylan,
Matthias Krug,
Denis Tamraz
1.22 2021-Feb-05 KwiatkowskiPa Global Coding Rule 129 – do not mix standard structure members
Standard CCB: initialization with designated initializers [C99]
Rephrase of Rule 020 to avoid misunderstanding.
17-Feb-2021: Data exchange over function arguments is allowed.
Marc Schaefer, Remove bin numeral example in Rule 051 as not
William Forbes, supported in C99.
Stephan Leuschner,
Ashok Chintalapati, Added “ULL” case to Rule 044.
Inanc Seylan, New rules to support compliance with not statically
Matthias Krug, enforceable MISRA C 2012 guidelines:
Denis Tamraz
- Dir-4.7: Test error information (Rule 130)
- Dir-4.13: Enforce appropriate sequence on
resources (Rule 131)
- Dir-4.11: Validate data passed to external
library (new CyberSec guideline)
- Dir-4.1: Protect loops with timeout detection
in case of external conditions (Rule 131)