| Task | Detail |
|---|---|
| Starting code | A CAN buffer module with 8+ MISRA violations (conversions, implicit types, missing return checks, missing default case) |
| Target | Zero mandatory violations; all required violations either fixed or deviated with written justification |
| Tools | Cppcheck --enable=all --misra-c=2012 (free); or PC-lint Plus (commercial) |
| Output | Fixed source file + deviation log for any remaining advisory violations |
Lab: Write and Validate a MISRA-Compliant Module
Exercise 1: Fix the Violations
/* Original code with MISRA violations — identify and fix all of them */
#include "can_buffer.h"
int g_buffer_count = 0; /* Violation 1: plain int (Rule 6.1 area + 8.5) */
unsigned char g_buffer[100]; /* Violation 2: unsigned char not uint8_t */
int can_buffer_push(unsigned char *data, int len) /* Violation 3,4: plain int */
{
if (len > 100) /* Violation 5: 100 not typed as 100u */
return -1; /* Violation 6: missing braces (Rule 15.6) */
for (int i = 0; i < len; i++) { /* Violation 7: plain int loop var */
g_buffer[g_buffer_count + i] = data[i]; /* Violation 8: no bounds check */
}
g_buffer_count += len; /* Violation 9: signed/unsigned arithmetic */
return 0;
}
/* Violation 10: no function documentation; Dir 4.3 advisory */
/* FIXED VERSION: implement below using MISRA-compliant types and patterns */Exercise 2: Write the Deviation Record
/* MISRA Deviation Record: CAN Buffer Module */
/* Module: can_buffer.c Version: 1.0 Author: Engineer Name Date: 2024-01-15 */
/* -----------------------------------------------------------------------
Deviation ID: DEV-CAN-001
Rule: MISRA-C:2012 Rule 11.5 (Advisory)
Location: can_buffer.c line 42
Code: void *pool = MemPool_Alloc(sizeof(CanFrame_t));
CanFrame_t *frame = (CanFrame_t *)pool;
Justification: MemPool_Alloc() returns void* by design to provide a
type-agnostic memory pool interface. The allocated block
is always sizeof(CanFrame_t) bytes, ensuring correct
alignment for CanFrame_t. This cast is safe and intentional.
Risk assessment: Low — size and alignment are correct by design; pool is
not externally accessible; no type confusion possible.
Alternative: A CanFrame_t-specific allocator would duplicate pool code
for each type; rejected on code size grounds.
Approved by: Jane Smith (SW Safety Manager), 2024-01-15
Reviewer: Bob Jones (MISRA Lead), 2024-01-15
Tool annotation: //lint -e9079 [DEV-CAN-001]
----------------------------------------------------------------------- */
/*lint -e9079 [DEV-CAN-001: void* to CanFrame_t* — see deviation record] */
void *pool = MemPool_Alloc(sizeof(CanFrame_t));
CanFrame_t *frame = (CanFrame_t *)pool;
/*lint +e9079 */Exercise 3: CI Pipeline Violation Count Gate
#!/bin/bash
# CI script: run Cppcheck MISRA check; fail if too many violations
SOURCE_DIR="src/"
ADDONS_DIR="/opt/cppcheck/addons"
MISRA_CFG="misra_c_2012.json"
# Run Cppcheck with MISRA addon
cppcheck --addon="$ADDONS_DIR/misra.py" --addon-python=python3 --enable=all --inconclusive --template="{file}:{line}: {severity}: {message} [{id}]" "$SOURCE_DIR" 2> misra_results.txt
# Count violation categories
MANDATORY=$(grep -c "mandatory" misra_results.txt 2>/dev/null || echo 0)
REQUIRED=$(grep -c "required" misra_results.txt 2>/dev/null || echo 0)
echo "MISRA Mandatory violations: $MANDATORY (must be 0)"
echo "MISRA Required violations: $REQUIRED (threshold: 10)"
if [ "$MANDATORY" -gt "0" ]; then
echo "FAIL: Mandatory violations must be fixed"
exit 1
fi
if [ "$REQUIRED" -gt "10" ]; then
echo "FAIL: Required violations exceed threshold"
exit 1
fi
echo "PASS: MISRA check within limits" Summary
The hands-on exercise covers the complete MISRA compliance workflow: identify violations with a tool, fix the fixable ones (wrong types, missing braces, implicit conversions), write formal deviation records for the ones that cannot be fixed without compromising design (type-agnostic pool interfaces), and gate the CI pipeline to prevent regressions. The key deliverable is the deviation log: a list of all remaining violations with written justification, risk assessment, and approval signatures. This document is what an ISO 26262 auditor will review — not just the zero-violation tool report.
🔬 Deep Dive — Core Concepts Expanded
This section builds on the foundational concepts covered above with additional technical depth, edge cases, and configuration nuances that separate competent engineers from experts. When working on production ECU projects, the details covered here are the ones most commonly responsible for integration delays and late-phase defects.
Key principles to reinforce:
- Configuration over coding: In AUTOSAR and automotive middleware environments, correctness is largely determined by ARXML configuration, not application code. A correctly implemented algorithm can produce wrong results due to a single misconfigured parameter.
- Traceability as a first-class concern: Every configuration decision should be traceable to a requirement, safety goal, or architecture decision. Undocumented configuration choices are a common source of regression defects when ECUs are updated.
- Cross-module dependencies: In tightly integrated automotive software stacks, changing one module's configuration often requires corresponding updates in dependent modules. Always perform a dependency impact analysis before submitting configuration changes.
🏭 How This Topic Appears in Production Projects
- Project integration phase: The concepts covered in this lesson are most commonly encountered during ECU integration testing — when multiple software components from different teams are combined for the first time. Issues that were invisible in unit tests frequently surface at this stage.
- Supplier/OEM interface: This is a topic that frequently appears in technical discussions between Tier-1 ECU suppliers and OEM system integrators. Engineers who can speak fluently about these details earn credibility and are often brought into critical design review meetings.
- Automotive tool ecosystem: Vector CANoe/CANalyzer, dSPACE tools, and ETAS INCA are the standard tools used to validate and measure the correct behaviour of the systems described in this lesson. Familiarity with these tools alongside the conceptual knowledge dramatically accelerates debugging in real projects.
⚠️ Common Mistakes and How to Avoid Them
- Assuming default configuration is correct: Automotive software tools ship with default configurations that are designed to compile and link, not to meet project-specific requirements. Every configuration parameter needs to be consciously set. 'It compiled' is not the same as 'it is correctly configured'.
- Skipping documentation of configuration rationale: In a 3-year ECU project with team turnover, undocumented configuration choices become tribal knowledge that disappears when engineers leave. Document why a parameter is set to a specific value, not just what it is set to.
- Testing only the happy path: Automotive ECUs must behave correctly under fault conditions, voltage variations, and communication errors. Always test the error handling paths as rigorously as the nominal operation. Many production escapes originate in untested error branches.
- Version mismatches between teams: In a multi-team project, the BSW team, SWC team, and system integration team may use different versions of the same ARXML file. Version management of all ARXML files in a shared repository is mandatory, not optional.
📊 Industry Note
Engineers who master both the theoretical concepts and the practical toolchain skills covered in this course are among the most sought-after professionals in the automotive software industry. The combination of AUTOSAR standards knowledge, safety engineering understanding, and hands-on configuration experience commands premium salaries at OEMs and Tier-1 suppliers globally.