Keeping Safe at C IAR Systems, Shanghai [email protected] www.iar.com Agenda • Functional Safety Certificate • C: Safe or Not • MISRA C • C-RUN: Runtime Analysis • Coding Tips: volatile • Stack Safety www.iar.com Functional Safety Certificate www.iar.com What is Functional Safety? • Simply put, it means that the overall safety of an embedded system depends on the equipment operating correctly in response to its inputs. • This includes erroneous inputs • Also includes hardware failures • Traditionally, only safety-critical industries have been interested in functional safety. • Automotive • Avionics • Medical • However, other industries are also seeing the benefit. www.iar.com Benefits of Functional Safety • • • • • • Reduce liability risks associated with your application. Reduce odds of product recall. Reduce the number of firmware updates. Ensure compliance with international standards and requirements. Protects your company’s reputation. Also protects your company’s bottom line. www.iar.com Functional Safety Standards www.iar.com The IEC 61508 Standard www.iar.com Certified Tools from IAR Systems Functional safety standards • IEC 61508 • ISO 26262 Simplified validation • Functional safety certificate • Report to the certificate • Safety Guide Guaranteed support and upgrade • Cover the product life cycle • Prioritized technical support • Validated service packs • Report of known problems www.iar.com/safety www.iar.com EWARMFS and EWRXFS • EWARMFS • Current • EWRXFS • Current • • edition: 6.50.4 edition: 2.42.4 Certified by TÜV SÜD Functional safety standards • IEC 61508-3:2010 (SIL 3) For electrical, electronic and programmable systems in all kinds of industry. • ISO 26262-8:2011 (ASIL D) Safety standard for road vehicles, derived from IEC 61508. www.iar.com What do I get from certified tools? • • • • Easier to earn the functional safety certificate for your own products. Functional safety editions of IAR Embedded Workbench are frozen so that you can be guaranteed that the tool does not change during the whole product life cycle. Special Support and Update Agreement (SUA) guarantees that as long as customers are under the contract for a certain version, any defects will be patched for that version. Prioritized technical support and regular report of known problems. www.iar.com What does tool certification mean? • Simply put, it means that the tools are developed with dependable, repeatable and certified processes. • Process for handling and resolving defects • Process for ensuring that defects do not resurface • Process for adding features to the product • Process for thoroughly and exhaustively testing releases • • In short, you can rest assured that your tools already have the utmost quality. You also know that the tools are backed by IAR Systems’ experience of more than 30 years. www.iar.com C: Safe or Not www.iar.com Why use C for Embedded Systems? • Widespread knowledge of the language • Virtually every developer knows C • Many languages are very similar to C • Widespread tools support for the language • Many different compilers for virtually any target • Many middleware options • Many static/dynamic analysis tools • Fairly close to the hardware • You can abstract to a higher level of interaction with the hardware • You can get all the way down to writing bits to ports www.iar.com The IEC 61508 Standard www.iar.com Suitable programming language Table C.4.5 of IEC 61508-7 gives a general description of “suitable programming language”: •The language should be fully and unambiguously defined. Well … according to some sources there are ~190 undefined behaviors in C99. •The language should be user- or problem-oriented rather than processor/platform machine-oriented. Hmm … “Fairly close to hardware” What do you think? •Widely used languages or their subsets are preferred to special-purpose languages. Widely used. OK! www.iar.com And it goes on … IEC 61508-7, Table C.4.5 continued: The language should encourage: The use of small and manageable software modules; • Restriction of access to data in specific software modules; • Definition of variable subranges; and • Any other type of error-limiting constructs. • www.iar.com Recommendation of languages With the right C subset, coding standard and the use of static analysis tools, C can be a Highly Recommended programming language for all 4 levels of SIL. NR: Not Recommended HR: Highly Recommended www.iar.com Language with Subset Table C.4.2 of IEC 61508-7 gives the aim and description of language subsets: Aim: • To reduce the probability of introducing programming faults; • Increase the probability of detecting any remaining faults. Description: • The language is examined to determine programming constructs which are either error-prone or difficult to analyze, for example, using static analysis methods. • A language subset is then defined which excludes these constructs. www.iar.com The IEC 61508 Standard www.iar.com MISRA C www.iar.com Definition of MISRA C MISRA C stands for “Motor Industry Software Reliability Association”, a consortium based out of Cambridge in UK that promotes standards to improve the safety, portability and reliability in the context of embedded systems. More importantly, MISRA C is: • A C language subset • Takes out the undefined behavior of C language • And your own coding standard • To avoid some of the pitfalls within C language www.iar.com MISRA C:2004 Rules 1. Environment(4:1) 2. Language extensions(3:1) 3. Documentation(4:2) 4. Character sets(2:0) 5. Identifiers(4:3) 6. Types(4:1) 7. Constants(1:0) 8. Declarations and definitions(12:0) 9. Initialization(3:0) 10. Arithmetic type conversion(6:0) 11. Pointer type conversion(3:2) 12. Expressions(9:4) 13. Control statement expessions(6:1) 14. Control flow(10:0) 15. Switch statements(5:0) 16. Functions(9:1) 17. Pointers and arrays(5:1) 18. Structures and unions(4:0) 19. Preprocessing directives(13:4) 20. Standard libraries(12:0) 21. Runtime failures(1:0) (required : advisory) www.iar.com Example of MISRA C:2004 Rules • Rule 6.3 (advisory): typedefs that indicate size and signedness should be used in place of basic types. • int x; /* rule violation */ • typedef • int int16_t /* explicitly showing the size and signedness */ Rule 10.6 (required): A “u” suffix shall be applied to all constants of unsigned type. • uint16_t myvar = 1; /* rule violation */ • uint16_t myvar = 1u; /* definitely intended to be unsigned */ • Rule 14.4 (required): The goto statement shall not be used. • Rule 14.8 (required): The statement forming the body of a switch, while, do ... while, or for statement shall be a compound statement. • Code www.iar.com executed within those statements should be explicitly encapsulated by { }. Example of MISRA C:2004 Rules • Rule 6.1 (required): The plain char type shall be used only for the storage and use of character values. void f1 (char c1) { if (c1 == ~0x80); /* rule violation; pointless comparison – always false */ } • Rule 8.5 (required): There shall be no definitions of objects or functions in a header file. /* foo.h */ uint16_t myGlobal; /* different linker treat this differently ... you might get multiple instances of myGlobal for each inclusion of foo.h */ • Rule 20.4 (required): Dynamic heap memory allocation shall not be used. • No www.iar.com use of library functions malloc, realloc, calloc or free in your application. MISRA C in IAR Embedded Workbench www.iar.com Result of MISRA C Checker int main (void) { int a; short b; scanf("%d", &a); b = a; return b; } www.iar.com MISRA C Summary • • • A set of programming rules to reduce potential faults Often good to use even when not mandatory Completely integrated within IAR Embedded Workbench • Rules can be enabled or disabled individually • Settings can be applied on the entire project or at file level • The checker generate messages and an optional log file • • • Recommended in IEC 61508 and ISO 26262 Should be used from the beginning, not as an add-on test “It is a set of guidelines, not a religion” • If www.iar.com some rule does not fit your need, don’t use it but document why. C-RUN: Runtime Analysis www.iar.com C-RUN – Runtime Analysis Tool • Static Analysis • • • Runtime Analysis • • • Analyze the code without executing them Usually by the compiler, linker or dedicated analysis tools Analyze the code dynamically during runtime execution Usually by the debugger or dedicated analysis tools What types of “difficult to find” bugs can C-RUN detect? • Arithmetic checking • • • • • www.iar.com Division by zero Erroneous shifts Integer overflows Out-of-bounds checking, which checks pointer accesses Heap checking, which checks dynamic memory management Static Analysis Tools Static Analysis Warnings / Errors Compile Link www.iar.com Launch C-SPY Execute Code & Debug C-RUN: Dynamic/Runtime Analysis Compile Link Launch C-SPY C-SPY Debug Log www.iar.com Execute Code & Debug C-RUN Analysis C-RUN in IAR Embedded Workbench www.iar.com Detecting Integer Overflow www.iar.com Detecting Integer Conversion www.iar.com Detecting Shift Overflow www.iar.com Detecting Division by Zero www.iar.com Detecting Unhandled Switch-Case www.iar.com Detecting Heap Errors www.iar.com Detecting Out-of-Bounds www.iar.com C-RUN Summary • • • • • • • C-RUN enables runtime error checking in resource constrained targets. C-RUN is intuitive and easy-to-use. C-RUN supports both C and C++ programming language. C-RUN taps into current development workflow and does not interfere with existing build process. C-RUN comes with fine grained control of individual checks and specific code location in each test run. C-RUN discovers vulnerabilities very early in the development cycle which enables catching of errors that usually show up in the test phase. C-RUN is fully integrated with IAR Embedded Workbench and provides immediate feedback in the daily code-and-test cycle. C-RUN – Find errors as early as possible! www.iar.com Coding Tips: volatile www.iar.com Why Use a volatile Variable? • volatile • The • object value can change beyond the compiler’s control. Avoid unwanted compiler optimization • Do not perform optimizations on the accesses to that object. • All access to the volatile object must be preserved. • Three reasons to declare a variable as volatile: • Shared access: the object is shared between several tasks in a multitasking environment. • Trigger access: as for a memory-mapped SFR where the access can have an effect. • Modified access: contents of the object can change in ways not known to the compiler. www.iar.com Rules for Accessing a volatile Variable • Abstract machine • The C standard defines an abstract machine which governs the behavior of accesses to volatile declared objects. • However, • the realistic behavior is implementation-defined. Rules of IAR C/C++ Compiler for ARM • All accesses are preserved. • All accesses are complete, that is, the whole object is accessed. • All accesses are performed in the same order as given. • All accesses are atomic, that is, they cannot be interrupted. Note: The compiler adheres to these rules for accesses to all 8-, 16-, and 32-bit aligned variables. Otherwise, only the first rule applies. www.iar.com Is It Atomic? volatile int32_t vol = 1; void f5 (void) { vol++; /* Is this atomic? */ } LDR.N LDR ADDS STR BX www.iar.com R0,??DataTable7 R1,[R0, #+0] R1, R1, #+1 R1,[R0, #+0] LR ;; ;; ;; ;; ;; Not Atomic! vol address 1st access: Atomic ADDS… 2nd access: Atomic return volatile Examples volatile Bool gLock; … while(gLock == False) /* spin lock */ continue; … __no_init volatile uint8_t PortA @ 0x555; __no_init volatile uint8_t PortB @ 0x2AA; … /* flash erasing sequence */ PortA = 0xAA; PortB = 0x55; PortA = 0x80; PortA = 0xAA; PortB = 0x55; … www.iar.com Stack Safety www.iar.com The Stack • • • • • A fixed block of continuous memory Allocated statically SP is initialized at reset S Usually grows downward P Contains local data for C functions • Local variables • Function parameters and return value • Compiler temporaries • Interrupt contexts • Saved processor registers • Life span: the duration of C function www.iar.com heap stack global/static variables Stack Overflow • Stack overflow • There is no protection on SP • SP might be moved out of the stack area • Application data destroyed: • Overwritten variables • Wild pointers • Corrupted return addresses S • Stack errors are hard to catch • Dynamically occurred at runtime • Related to the behavior of application • Select a proper stack size • Too small - overflow • Too big - waste of memory www.iar.com heap stack P S P danger zone! global/static variables Ways to Determine the Stack Size • Static stack usage analysis • Calculate the stack consumption after building. • Based on the analysis to the tree of function calls. • Find out the stack consumption in the worst case. • Stack usage tracking • Check the trace of stack usage at runtime. • Fill the entire stack area with a magic data pattern, e.g. 0xCD. • Execute the program under certain test conditions. • Find how far has SP ever reached by the amount of destroyed pattern. • Stack guard zone • Detect the stack overflow when (or slightly after) it happens. • Setup a dedicated memory guard zone following the stack area. • Monitor any memory accesses to the guard zone at runtime. www.iar.com Static Stack Usage Analysis • • • • Calculate the maximum stack usage for each call graph root (a function that is not called from another other functions). Supported by the linker or 3rd-party analysis tools. In usual the compiler will generate enough stack information for each C function, but in some cases additional directives must be provided: • Indirect calls – through function pointers • Recursion – number of iterations • Unobvious call graph roots – interrupts, threads/tasks, etc. • Assembly routines – must be annotated How to provide necessary directives for the calculation of stack usage: • #pragma directives in the source code • A separate stack usage control file www.iar.com Stack Usage Analysis in IAR Linker • • Enable stack usage analysis in the Advanced tab of Linker options. A STACK USAGE chapter will be generated in the map file, listing the maximum stack depth for each call graph root. www.iar.com Stack Usage Tracking in IAR Debugger Not real time: Can not detect a stack overflow when it happens. Can only detect the signs it left. www.iar.com • Enable graphical stack display and stack usage tracking in the Stack category of IDE Options dialog. • Open the Stack window from the View menu of the C-SPY debugging environment. Stack Guard Zone • Passive guard • Fill the guard area with a magic number. • Check at regular intervals, e.g. in a timer interrupt, to ensure the guard area is not overwritten. • Can be performed in either application or debugger. • stack Active guard • Use the memory protection unit; • Or enable data breakpoints / watchpoints in the guard area to catch the stack overflow actively. • Target hardware and debugger related. • heap Useful also in a deployed system www.iar.com guard global/static variables Summary Functional safety is important for all projects Gaining certification is tricky Certified tools can help you get through certification MISRA C checker is a static analysis tool to improve code safety C-RUN is a dynamic analysis tool to find runtime errors Using good coding practices can avoid safety pitfalls Working to avoid stack overflow as possible as you can Thanks for your attention ! www.iar.com
© Copyright 2024 ExpyDoc