DEV Community

Ahmet Can Gulmez
Ahmet Can Gulmez

Posted on

Safe and Secure Software - MISRA C:2012

We say that programming languages like C, C++, Rust as "general-purpose". That means that we can do everything (theoretically) with these. But in critical system development (let's say military or aerospace), we need some rules to use the languages safely and securely.

In this article, I'm gonna explain the MISRA C:2012 rules and example code blocks. Let's start!

Note: I'm gonna dive into the important rules in later posts.

A standard C environment

Rule 1.1: The program shall contain no violations of the standard C syntax and constraints, and shall not exceed the implementation's translation limits.

Rule 1.2: Language extensions should not be used.

void outer(void)
{
    printf("Outer function!\n");

    __extension__ void inner(void)  /* VIOLATION */
    {
        printf("Inner function!\n");
    }
    inner();
}
Enter fullscreen mode Exit fullscreen mode

Rule 1.3: There shall be no occurrence of undefined or critical unspecified behaviour.

Unused code

Rule 2.1: A project shall not contain unreachable code.

void main(int argc, char *argv[])
{
    int res;

    exit(EXIT_SUCCESS);

    res = 1;        /* VIOLATION */
}
Enter fullscreen mode Exit fullscreen mode

Rule 2.2: There shall be no dead code.
Rule 2.3/4/5: A project should not contain unused type/tag/macro declarations.

int func(void)
{
#define DATA    5
#define SIZE    10      /* VIOLATION */

    return DATA;
}
Enter fullscreen mode Exit fullscreen mode

Rule 2.6: A function should not contain unused label declarations.
Rule 2.7: There should be no unused parameters in functions.

Comments

Rule 3.1: The character sequences /* and // shall not be used within a comment.
Rule 3.2: Line-splicing shall not be used in // comments.

Character sets and lexical conventions

Rule 4.1: Octal and hexadecimal escape sequences shall not be terminated.
Rule 4.2: Trigraphs should not be used.

Identifiers

Rule 5.1: External identifiers shall be distinct.
Rule 5.2: Identifiers declared in the same scope and name space shall be distinct.
Rule 5.3: An identifier in an inner scope shall not hide an identifier declared in an outer scope.

int func(void)
{
    int i;
    {
        int i;  /* VIOLATION */

        i = 4;
    }
}
Enter fullscreen mode Exit fullscreen mode

Rule 5.4: Macro identifiers shall be distinct.
Rule 5.5: Identifiers shall be distinct from macro names.
Rule 5.6/7: A typedef/tag name shall be a unique identifier.
Rule 5.8/9: Identifiers that define objects or functions with external/internal linkage shall be unique.

Types

Rule 6.1: Bit-fields shall only be declared with an appropriate type.

struct s {
    unsigned int a:2;   
    int          b:2; /* VIOLATION (plain int not permitted) */
};
Enter fullscreen mode Exit fullscreen mode

Rule 6.2: Single-bit named bit fields shall not be of a signed type.

Literals and constants

Rule 7.1: Octal constants shall not be used.
Rule 7.2: A "u" or "U" suffix shall be applied to all integer constants that are represented in an unsigned type.
Rule 7.3: The lowercase character "l" shall not be used in a literal suffix.

const int64_t   a = 0L;
const int64_t   b = 0l;     /* VIOLATION */
const uint64_t c = 0Lu; 
const uint64_t d = 0lU;     /* VIOLATION */
Enter fullscreen mode Exit fullscreen mode

Rule 7.4: A string literal shall not be assigned to an object unless the object's type is "pointer to const-qualified char".

const volatile char *s1 = "string";
char *s2 = "string";                            /* VIOLATION */
Enter fullscreen mode Exit fullscreen mode

Declarations and definations

Rule 8.1: Types shall be explicitly specified.

extern          x;      /* VIOLATION (implicit int type) */
extern int16_t y;
const           z;      /* VIOLATION (implicit int type) */
extern int32_t q;
Enter fullscreen mode Exit fullscreen mode

Rule 8.2: Function types shall be in prototype form with named parameters.
Rule 8.3: All declarations of an object or function shall use the same names and type qualifiers.

extern f(signed int param);
         f(int param);              /* Okey */
extern g(int * const param);
         g(int * p);                /* VIOLATION */
Enter fullscreen mode Exit fullscreen mode

Rule 8.4: A compatible declaration shall be visible when an object or function with external linkage is defined.

extern int x;
         int x = 5;     /* OK */

int y = 3;              /* VIOLATION - no prior declaration */
Enter fullscreen mode Exit fullscreen mode

Rule 8.5: An external object or function shall be declared once in one or only one file.
Rule 8.6: An identifier with external linkage shall have exactly one external definition.
Rule 8.7: Functions and objects should not be defined with external linkage if they are referenced in only one translation unit.
Rule 8.8: The static storage class specifier shall be used in all declarations of objects and functions that have internal linkage.

static int32_t x = 0;
extern int32_t x;     /* VIOLATION */
Enter fullscreen mode Exit fullscreen mode

Rule 8.9: An object should be defined at block scope if its identifier only appears in a single function.
Rule 8.10: An inline function shall be declared with the static storage class.
Rule 8.11: When an array with external linkage is declared, its size should be explicitly specified.
Rule 8.12: Within an enumerator list, the value of an implicitly-specified enumeration constant shall be unique.
Rule 8.13: A pointer should point to a const-qualified type whether possible.
Rule 8.14: The restrict type qualifier shall not be used.

Initialization

Rule 9.1: The value of an object with automatic storage duration shall not be read before it has been set.

void f(bool_t b, uint16_t *p)
{
    if (b) {
        *p = 3U;
    }
}

void g(void)
{
    uint16_t u;

    f(false, &u);

    if (u == 3U) {
        /* VIOLATION - u has not be assigned a value */
    }
}
Enter fullscreen mode Exit fullscreen mode

Rule 9.2: The initializer for an aggregate or union shall be enclosed in braces.
Rule 9.3: Arrays shall not be partially initialized.
Rule 9.4: An element of an object shall not be initialized more than once.
Rule 9.5: Where designated initializers are used to initialize an array object, the size of the array shall be specified explicitly.

int a1[5] = {0};            /* OK */
int a2[] = {4, 7, 1};   /* VIOLATION */
Enter fullscreen mode Exit fullscreen mode

The essential type model

Rule 10.1: Operands shall not be of an inappropriate essential type. (I did not understand that yet 😂, look at page 82-84 at MISRA C:2012 Guidelines).
Rule 10.2: Expressions of essential character type shall not be used inappropriately in addition and subtraction operations.
Rule 10.3: The value of an expression shall not be assigned to an object with a narrower essential type or of a different essential type category.
Rule 10.4: Both operands of an operator in which the usual arithmetic conversions, are performed shall have the same essential type category.
Rule 10.5: The value of an expression should not be cast to an inappropriate essential type.
Rule 10.6: The value of a composite expression shall not be assigned to an object with wider essential type.
Rule 10.7: If a composite expression is used as one operand of an operator in which the usual arithmetic conversions are performed then the other operand shall not have wider essential type.
Rule 10.8: The value of a composite expression shall not be cast to a different essential type category or a wider essential type.

Pointer type conversions

Rule 11.1: Conversions shall not be performed between a pointer to function and any other type.

typedef void (*fp16) (int16_t n);
typedef void (*fp32) (int32_t n);

fp16 fp1 = NULL;                /* OK */
fp32 fp2 = (fp32) fp1;      /* VIOLATION - a function pointer to different one */

if (fp2 != NULL) {          /* OK */

}

fp16 fp3 = (fp16) 0x8000;   /* VIOLATION - integer into function pointer */
Enter fullscreen mode Exit fullscreen mode

Rule 11.2: Conversions shall not be performed between a pointer to an incomplete type and any other type.

struct s;
struct t;
struct s *sp;
struct t *tp;
int16_t *ip;

sp = NULL;                      /* OK */
ip = (int16_t *) sp;            /* VIOLATION */
sp = (struct s *) 1234;     /* VIOLATION */
tp = (struct t *) sp;       /* VIOLATION */
Enter fullscreen mode Exit fullscreen mode

Rule 11.3: A cast shall not be performed between a pointer to object type and a pointer to a different object type.

uint8_t *p1;
uint32_t *p2;

p2 = (uint32_t *) p1;           /* VIOLATION */

const short *p;
const volatile short *q;

q = (const volatile short *) p; /* OK */
Enter fullscreen mode Exit fullscreen mode

Rule 11.4: A conversion should not be performed between a pointer to object and an integer type.

uint16_t *p;

int32_t addr = (int32_t) &p;        /* VOILATION */
uint8_t *q = (uint_t *) addr;       /* VIOLATION */
bool_t b = (bool_t) p;              /* VIOLATION */

enum tag {A, B, C};

enum tag e = (enum tag) p;          /* VIOLATION */
Enter fullscreen mode Exit fullscreen mode

Rule 11.5: A conversion should not be performed from pointer to void into pointer to object (except NULL).

uint32_t *p32;
void *p;
uint16_t *p16;

p = p32;                    /* OK */
p16 = p;                    /* VIOLATION */
p = (void*) p16;        /* OK */
p32 = (uint32_t *);     /* VIOLATION */ 
Enter fullscreen mode Exit fullscreen mode

Rule 11.6: A cast shall not be performed between pointer to void and an arithmetic type.

void *p;
uint32_t u;

p = (void *) 0x1234u;   /* VIOLATION */
u = (uint32_t) p;           /* VIOLATION */ 
Enter fullscreen mode Exit fullscreen mode

Rule 11.7: A cast shall be performed between pointer to object and a non-integer arithmetic type.

int16_t *p;
float32_t f;

f = (float32_t) p;  /* VIOLATION */
p = (int16_t *) f;  /* VIOLATION */
Enter fullscreen mode Exit fullscreen mode

Rule 11.8: A cast shall not remove const or volatile qualification from the type pointed to by a pointer.
Rule 11.9: The macro NULL shall be the only permitted form of integer null pointer constant.

int32_t *p1 = 0;                /* VIOLATION */
int32_t *p2 = (void *) 0;   /* OK */
Enter fullscreen mode Exit fullscreen mode

Expressions

Rule 12.1: The precedence of operators within expressions should be made explicit.
Rule 12.2: The right hand operand of a shift operator shall lie in the range zero to one less than the width in bits of the essential type of the left hand operand.
Rule 12.3: The comma operator should not be used.
Rule 12.4: Evaluation of constant expressions should not lead to unsigned integer wrap-around.

#define DELAY       10000u
#define WIDTH       60000u

void fixed_pulse(void)
{
    uint16_t off_time16 = DELAY + WIDTH;    /* VIOLATION */
}
Enter fullscreen mode Exit fullscreen mode

Side effects

Rule 13.1: Initializer lists shall not contain persistent side effects.

volatile uint16_t v1;

void f(void)
{
    uint16_t a[2] = {v1, 0};    /* VIOLATION - volatile is side effect */
}

void g(uint16_t x, uint16_t y)
{
    uint16_t a[2] = {x + y, x - y}; /* OK */
}
Enter fullscreen mode Exit fullscreen mode

Rule 13.2: The value of an expression and its persistent side effects shall be the same under all permitted evaluation orders.
Rule 13.3: A full expression containing an increment (++) or decrement (--) operator should have no other potential side effects other than that caused by the increment or decrement operator.

u8a = u8b++;                /* VIOLATION */
u8a = ++u8b + u8c--;        /* VIOLATION */
x++;                            /* OKEY */
a[i]++;                     /* OK */
c->x++;                     /* OK */
*p++;                           /* OKEY */
(*p)++;                     /* OK */
++(*p);                     /* OK */
Enter fullscreen mode Exit fullscreen mode

Rule 13.4: The result of an assignment operator should not be used.

x = y;              /* OK */
a[x] = a[x = y];    /* VIOLATION */
Enter fullscreen mode Exit fullscreen mode

Rule 13.5: The right hand operand of a logical && or || operator shall not contain persistent side effects.
Rule 13.6: The operand of the sizeof operand shall not contain any expression which has potential side effects.

Control statement expressions

Rule 14.1: A loop counter shall not have essential floating type.
Rule 14.2: A for loop shall be well-formed.
Rule 14.3: Controlling expressions shall not be invariant.
Rule 14.4: The controlling expression of an if statement and the controlling expression of an iteration-statement shall have essential Boolean type.

int32_t *p, *q;

while (p)               /* VIOLATION */
{
}

while (q != NULL)       /* OK */
{
}

while (true)            /* OK */
{
}
Enter fullscreen mode Exit fullscreen mode

Control flow

Rule 15.1: The goto statement should not be used.
Rule 15.2: The goto statement shall jump to a label declared later in the same function.
Rule 15.3: Any label referenced by a goto statement shall be declared in the same block, or in any block enclosing the goto statement.
Rule 15.4: There should be no more than one break or goto statement used to terminate any iteration statement.
Rule 15.5: A function should have a single point of exit at the end.
Rule 15.6: The body of an iteration-statement or a selection-statement shall be a compound-statement.

while (true)            /* VIOLATION */
    process_data();

while (true)            /* OK */
{
    process_data();
}
Enter fullscreen mode Exit fullscreen mode

Rule 15.7: All if ... else if constructs shall be terminated with an else statement.

Switch statements

Rule 16.1: All switch statements shall be well-formed.
Rule 16.2: A switch label shall only be used when the most closely-enclosing compound statement is the body of a switch statement.
Rule 16.3: An unconditional break statement shall terminate every switch-clause.

switch (x)
{
    case 0:         /* OK */
        break;  
    case 1:         /* OK */
    case 2:         /* OK */
        break;
    case 4:         /* VIOLATION */
        a = b;
    default:            /* VIOLATION - 'default' even should have 'break' */
        ;
}
Enter fullscreen mode Exit fullscreen mode

Rule 16.4: Every switch statement shall have a default label.
Rule 16.5: A default label shall appear as either the first or the last switch label of a switch statement.
Rule 16.6: Every switch statement shall have at least two switch-clauses.
Rule 16.7: A switch-expression shall not have essential Boolean type.

Functions

Rule 17.1: The features of <stdarg.h> shall not be used.
Rule 17.2: Functions shall not call themselves, either directly or indirectly.
Rule 17.3: A function shall not be declared implicitly.
Rule 17.4: All exit paths from a function with non-void return type shall have an explicit return statement with an expression.
Rule 17.5: The function argument corresponding to a parameter declared to have an array type shall have an appropriate number of elements.
Rule 17.6: The declaration of an array parameter shall not contain static keyword between the [].
Rule 17.7: The value returned by a function having non-void return type shall be used.
Rule 17.8: A function parameter should not be modified.

Pointers and arrays

Rule 18.1: A pointer resulting from arithmetic on a pointer operand shall address an element of the same array as that pointer operand.

void f(void)
{
    int32_t data = 0;
    int32_t b = 0;
    int32_t c[10] = {0};
    int32_t d[5][2] = {0};

    int32_t *p1 = &c[0];        /* OK */
    int32_t *p2 = &c[10];   /* OK (even) */
    int32_t *p3 = &c[11];   /* VIOLATION */

    data = *p2;                 /* VIOLATION */

    p1++;                           /*  OK */
    c[-1] = 0;                  /* VIOLATION */
}
Enter fullscreen mode Exit fullscreen mode

Rule 18.2: Subtraction between pointers shall only be applied to pointers that address elements of the same array.

void f(void)
{
    int32_t a1[10];
    int32_t a2[10];
    int32_t *p1 = &a1[1];
    int32_t *p2 = &a2[10];
    ptrdiff_t diff;

    diff = p1 - a1;     /* OK */
    diff = p2 - a2;     /* OK */
    diff = p1 - p2;     /* VIOLATION */
}
Enter fullscreen mode Exit fullscreen mode

Rule 18.3: The relational operators >, >=, < and <= shall not be applied to objects of pointer type except where they point into the same object.
Rule 18.4: The +, -, +=, -= operators should not be applied to an expression of pointer type.
Rule 18.5: Declarations should contain no more than two levels of pointer nesting.
Rule 18.6: The address of an object with automatic storage shall not be copied to another object that persists after the first object has ceased to exist.

int8_t *f(void)
{
    int8_t local;

    return &local;      /* VIOLATION */
}

uint16_t *sp;

void g(uint16_t *p)
{
    sp = p;             /* VIOLATION */
}
Enter fullscreen mode Exit fullscreen mode

Rule 18.7: Flexible array members shall not be declared.
Rule 18.8: Variable-length array types shall not be used.

Overlapping storage

Rule 19.1: An object shall not be assigned or copied to an overlapping object.

void f(void)
{
    union {
        int16_t i;
        int16_t j;
    } a = {0}, b = {1};

    a.j = a.i;      /* VIOLATION */
}
Enter fullscreen mode Exit fullscreen mode

Rule 19.2: The union keyword should not be used.

Preprocessing directives

Rule 20.1: #include directives should only be preceded by preprocessor directives or comments.
Rule 20.2: The ', " or \ characters and the /* or // character sequences shall not occur in a header file name.
Rule 20.3: The #include directive shall be followed by either a <filename> or "filename" sequence.
Rule 20.4: A macro shall not be defined with the same name as a keyword.
Rule 20.5: #undef should not be used.
Rule 20.6: Tokens that look like a preprocessing directive shall not occur with a macro argument.
Rule 20.7: Expressions resulting from the expansion of macro parameters shall be enclosed in parentheses.
Rule 20.8: The controlling expression of a #if or #elif preprocessing directive shall evaluate to 0 or 1.
Rule 20.9: All identifiers used in the controlling expression of #if or #elif preprocessing directives shall be #define'd before evaluation.
Rule 20.10: The # and ## preprocessor operators should not be used.
Rule 20.11: A macro parameter immediately following a # operator shall not immediately be followed by a ## operator.

#define A(x)        #x      /* OK */
#define B(x, y) x ## y  /* OK */
#define C(x, y)   #x ## y   /* VIOLATION */
Enter fullscreen mode Exit fullscreen mode

Rule 20.12: A macro parameter used as an operand to the # or ## operators, which is itself subject to further macro replacement, shall only be used as an operand to these operators.
Rule 20.13: A line whose first token is # shall be a valid preprocessing directive.
Rule 20.14: All #else, #elif and #endif preprocessor directives shall reside in the same file as the #if, #ifdef or #ifndef directive to which they are related.

Standard libraries

Rule 21.1: #define and #undef shall not be used on a reserved identifier or reserved macro name.

#undef __LINE__                 /* VIOLATION (begins with _) */
#define _GUARD_H    1               /* VIOLATION (begins with _) */

#define defined                 /* VIOLATION (reserved identifier) */
#define errno my errno          /* VIOLATION (library identifier) */
#define isneg(x)    ((x) < 0)   /* OKEY */
Enter fullscreen mode Exit fullscreen mode

Rule 21.2: A reserved identifier or macro name shall not be declared.
Rule 21.3: The memory allocation and deallocation functions of <stdlib.h> shall not be used.
Rule 21.4: The standard header file <setjmp.h> shall not be used.
Rule 21.5: The standard header file <signal.h> shall not be used.
Rule 21.6: The standard library input/output functions shall not be used.
Rule 21.7: The atof, atol, atoll functions of <stdlib.h> shall not be used.
Rule 21.8: The library functions abort, exit, getenv and system of <stdlib.h> shall not be used.
Rule 21.9: The library functions bsearch and qsort of <stdlib.h> shall not be used.
Rule 21.10: The standard library time and date functions shall not be used.
Rule 21.11: The standard header file <tgmath.h> shall not be used.
Rule 21.12: The exception handling features of <fenv.h> should not be used.

Resources

Rule 22.1: All resources obtained dynamically by means of standard library functions shall be explicitly released.

int f(void)
{
    void *a = malloc(40);

    /* VIOLATION - not released */
    return 1;
}

int g(void)
{
    FILE *fp = fopen("file", "r");

    /* VIOLATION - not closed */
    return 1;
}
Enter fullscreen mode Exit fullscreen mode

Rule 22.2: A block of memory shall only be freed if it was allocated by means of a standard library function.
Rule 22.3: The same file shall not be open for read and write access at the same time on different streams.
Rule 22.4: There shall no attempt to write to a stream which has been opened as read-only.
Rule 22.5: A pointer to a FILE object shall not be dereferenced.
Rule 22.6: The value of a pointer to a FILE shall not be used after the associated stream has been closed.

Top comments (0)