学习MISRA C之二

合集下载

学习MISRAC规范

学习MISRAC规范

学习MISRAC规范学习MISRAC邵贝贝等编者按:C语言是开发嵌入式应用的主要工具,然而C语言并非是专门为嵌入式系统设计,相当多的嵌入式系统较一般计算机系统对软件安全性有更苛刻的要求。

1998 年,MISRA指出,一些在C看来可以接受,却存在安全隐患的地方有127处之多。

2004年,MISRA 对C的限制增加到141条。

嵌入式系统应用工程师借用计算机专家创建的C语言,使嵌入式系统应用得以飞速发展,而MISRAC是嵌入式系统应用工程师对C语言嵌入式应用做出的贡献。

如今MISRA C已经被越来越多的企业接受,成为用于嵌入式系统的C语言标准,特别是对安全性要求极高的嵌入式系统,软件应符合MISRA标准。

本文将分6讲,与读者共同学习MISRAC。

第一讲:“…安全第一?的C语言编程规范”,简述MISRAC的概况。

第二讲:“跨越数据类型的重重陷阱”,介绍规范的数据定义和操作方式,重点在隐式数据类型转换中的问题。

第三讲:“指针、结构体、联合体的安全规范”,解析如何安全而高效地应用指针、结构体和联合体。

第四讲:“防范表达式的失控”,剖析MISRAC中关于表达式、函数声明和定义等的不良使用习惯,最大限度地减小各类潜在错误。

第五讲:“准确的程序流控制”,表述C语言中控制表达式和程序流控制的规范做法。

第六讲:“构建安全的编译环境”,讲解与编译器相关的规范编写方式,避免来自编译器的隐患。

学习MISRAC之一:“安全第一”的C语言编程规范C/C++语言无疑是当今嵌入式开发中最为常见的语言。

早期的嵌入式程序大都是用汇编语言开发的,但人们很快就意识到汇编语言所带来的问题——难移植、难复用、难维护和可读性极差。

很多程序会因为当初开发人员的离开而必须重新编写,许多程序员甚至连他们自己几个月前写成的代码都看不懂。

C/C+ +语言恰恰可以解决这些问题。

作为一种相对“低级”的高级语言,C/C++语言能够让嵌入式程序员更自由地控制底层硬件,同时享受高级语言带来的便利。

MISRA--工业标准的C编程规范

MISRA--工业标准的C编程规范

ISR Guidelines For The Use Of TheC Language In Vehicle Based SoftwarePDF version 1.0© MIRA, 1998 This electronic version of the MISRA C Guidelines is issued solely for the use of member companies of the MISRA Consortium.MIRA grants permission for member companies to distribute this PDF file within their own companies. The file should not be altered in any way, nor should hard copies be made. No permission is given for use or distribution of this file by or to individuals or companies who are not members of the MISRA consortium, and any such use constitutes an infringement of copyright.MISRA gives no guarantees about the accuracy of the information contained in this PDF version of the Guidelines, and the published paper document should be taken as authoritative. Information is available from the MISRA web site on how to obtain printed copies of the document.First published April 1998by The Motor Industry Research AssociationWatling StreetNuneatonWarwickshire CV10 0TU/© The Motor Industry Research Association, 1998.“MISRA” and the triangle logo are registered trademarks of The Motor Industry Research Association, held on behalf of the MISRA Consortium.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.Available in paperback (ISBN 0 9524156 9 0)British Library Cataloguing in Publication Data.A catalogue record for this book is available from the British LibraryThe Motor Industry Software Reliability Association GuidelinesFor The UseOf TheC LanguageIn VehicleBasedSoftwareApril 1998(PDF version 1.0, July 1998)DisclaimerAdherence to the requirements of this document does not in itself ensure error-free robustsoftware or guarantee portability and re-use.Compliance with the requirements of this document, or any other standard, does not of itselfconfer immunity from legal obligations.Executive summaryThis document specifies a subset of the C programming language which is intended to be suitable for embedded automotive systems up to and including safety integrity level 3 (as defined in the MISRA Guidelines). It contains a list of rules concerning the use of the C programming language together with justifications and examples.In addition to these rules the document also briefly describes the reason why such a language subset is required and gives guidance on how to use it.It is recognised that these language issues are only a small part of the overall task of developing software, and guidance is given on what else needs to be addressed by the developer if they are to have a credible claim of ‘best practice’development.This document is not intended to be an introduction or training aid to the subjects it embraces. It is assumed that readers of this document are familiar with the ISO C programming language standard and associated tools, and also have access to the primary reference documents. It also assumes that users have received the appropriate training and are competent C language programmers.AcknowledgementsThe MISRA consortium would like to thank the following individuals for their contribution to the writing of this document:Paul Edwards Rover Group LtdSimon Fisher AB Automotive Electronics LtdGavin McCall Visteon Automotive Systems, an enterprise of Ford Motor Company Ltd David Newman Visteon Automotive Systems, an enterprise of Ford Motor Company Ltd Frank O’Neill Lucas Automotive ElectronicsRichard Pearman Lotus EngineeringRoger Rivett Rover Group LtdThe MISRA consortium also wishes to acknowledge contributions from the following individuals during the review process:David Blyth D. C. Hurst Steve MontgomeryDave Bowen Peter Jesty Tim MortimerMark Bradbury Derek Jones Edward NelsonKwok Chan Ian Kendall Frank PlaggeShane Cook Andreas Krüger Agneta SjögrenFrank Cooper Lawrence Lane Kevin TalbotDewi Daniels Chris Leiby Chris TappGavin Finnie Thomas Maier Lloyd ThomasJohn Fox Paul Martin Ken TindellKenshiro Hashimoto Neil Martin Ron WilsonRichard Hathway M. A. C. Mettes Chris WintersSteven Hughes Charlie MonkThe reviewers represented a broad cross-section of automotive developers and component suppliers originating from eight countries (Austria, Germany, Japan, Holland, Norway, Sweden, United Kingdom and United States of America) and the following types of organisations:•Vehicle manufacturers (8)•Component and system suppliers (7)•Software specialists and consultancies (6)•Compiler and static analyser suppliers (3)•Research and development organisations (3)•Universities (4)ContentsPage 1. Background – the use of C and issues with it (1)1.1 The use of C in the automotive industry (1)1.2 Language insecurities and the C language (1)1.2.1 The programmer makes mistakes (1)1.2.2 The programmer misunderstands the language (2)1.2.3 The compiler doesn’t do what the programmer expects (2)1.2.4 The compiler contains errors (2)1.2.5 Run-time errors (3)1.3 The use of C for safety-related systems (3)1.4 C standardization (4)2. MISRA C: The vision (5)2.1 Rationale for the production of MISRA C (5)2.2 Objectives of MISRA C (5)3. MISRA C: Developing the subset (6)4. MISRA C: Scope (7)4.1 Base language issues (7)4.2 Issues not addressed (7)4.3 Applicability (7)4.4 Safety Integrity Level issues (7)4.5 Prerequisite knowledge (8)4.6 C++ issues (8)4.7 Auto-generated code issues (8)5. Using MISRA C (9)5.1 The software engineering context (9)5.2 The programming language and coding context (9)5.2.1 Training (10)5.2.2 Style guide (10)5.2.3 Tool selection and validation (10)5.2.4 Source complexity metrics (12)5.2.5 Test coverage (12)5.3 Adopting the subset (12)5.3.1 Compliance matrix (13)5.3.2 Deviation procedure (13)5.3.3 Formalisation within quality system (14)5.3.4 Introducing the subset (14)5.4 Claiming compliance (15)5.5 Continuous improvement (15)Contents (continued)Page 6. Introduction to the rules (16)6.1 Rule classification (16)6.1.1 Required rules (16)6.1.2 Advisory rules (16)6.2 Organisation of rules (16)6.3 Redundancy in the rules (16)6.4 Presentation of rules (17)6.5 Understanding the source references (18)6.5.1 Key to the source references (18)6.5.2 Understanding Annex G references (19)7. Rules (20)7.1 Environment (20)7.2 Character Sets (22)7.3 Comments (23)7.4 Identifiers (23)7.5 Types (24)7.6 Constants (26)7.7 Declarations and Definitions (27)7.8 Initialisation (29)7.9 Operators (31)7.10 Conversions (34)7.11 Expressions (35)7.12 Control Flow (39)7.13 Functions (42)7.14 Pre-processing Directives (46)7.15 Pointers and Arrays (50)7.16 Structures and Unions (51)7.17 Standard Libraries (53)8. References (58)Appendix A: Summary of rules (59)Appendix B: Cross references to the ISO standard (67)1.Background1. Background – the use of C and issues with it1.1 The use of C in the automotive industryThe C programming language [1] is growing in importance and use for real-time embedded applications within the automotive industry. This is due largely to the inherent language flexibility, the extent of support and its potential for portability across a wide range of hardware. Specific reasons for its use include:•For many of the microprocessors in use, if there is any other language available besides assembly language then it is usually C. In many cases other languages are simply notavailable for the hardware.•C gives good support for the high-speed, low-level, input/output operations, which are essential to many automotive embedded systems.•Increased complexity of applications makes the use of a high-level language more appropriate than assembly language.•C can generate smaller and less RAM-intensive code than many other high-level languages.•A growth in portability requirements caused by competitive pressures to reduce hardware costs by porting software to new, and/or lower cost, processors at any stagein a project lifecycle.•A growth in the use of auto-generated C code from modelling packages.•Increasing interest in open systems and hosted environments.1.2 Language insecurities and the C languageNo programming language can guarantee that the final executable code will behave exactly as the programmer intended. There are a number of problems that can arise with any language, and these are broadly categorised below. Examples are given to illustrate insecurities in the C language.1.2.1 The programmer makes mistakesProgrammers make errors, which can be as simple as mis-typing a variable name, or might involve something more complicated like misunderstanding an algorithm. The programming language has a bearing on this type of error. Firstly the style and expressiveness of the language can assist or hinder the programmer in thinking clearly about the algorithm. Secondly the language can make it easy or hard for typing mistakes to turn one valid construct into another valid (but unintended) construct. Thirdly the language may or may not detect errors when they are made.Firstly, in terms of style and expressiveness C can be used to write well laid out, structured and expressive code. It can also be used to write perverse and extremely hard-to-understand code. Clearly the latter is not acceptable in a safety-related system.1.Background (continued)Secondly the syntax of C is such that it is relatively easy to make typing mistakes that lead to perfectly valid code. For example, it is all too easy to type ‘=’(assignment) instead of ‘==’(logical comparison) and the result is nearly always valid (but wrong), while an extra semi-colon on the end of an if statement can completely change the logic of the code.Thirdly the philosophy of C is to assume that the programmers know what they are doing, which can mean that if errors are made they are allowed to pass unnoticed by the language. An area in which C is particularly weak in this respect is that of ‘type checking’. C will not object, for example, if the programmer tries to store a floating-point number in an integer that they are using to represent a true/false value. Most such mismatches are simply forced to become compatible. IfC is presented with a square peg and a round hole it doesn’t complain, but makes them fit!1.2.2 The programmer misunderstands the languageProgrammers can misunderstand the effect of constructs in a language. Some languages are more open to such misunderstandings than others.There are quite a number of areas of the C language that are easily misunderstood by programmers. An example is the set of rules for operator precedence. These rules are well defined, but very complicated, and it is easy to make the wrong assumptions about the precedence that the operators will take in a particular expression.1.2.3 The compiler doesn’t do what the programmer expectsIf a language has features that are not completely defined, or are ambiguous, then a programmer can assume one thing about the meaning of a construct, while the compiler can interpret it quite differently.There are many areas of the C language which are not completely defined, and so behaviour may vary from one compiler to another. In some cases the behaviour can vary even within a single compiler, depending on the context. Altogether the C standard, in Annex G, lists 201 issues that may vary in this way. This can present a sizeable problem with the language, particularly when it comes to portability between compilers. However, in its favour, the C standard does at least list the issues, so they are known.1.2.4 The compiler contains errorsA language compiler (and associated linker etc.) is itself a software tool. Compilers may not always compile code correctly. They may, for example, not comply with the language standard in certain situations, or they may simply contain ‘bugs’.Because there are aspects of the C language that are hard to understand, compiler writers have been known to misinterpret the standard and implement it incorrectly. Some areas of the language are more prone to this than others. In addition, compiler writers sometimes consciously choose to vary from the standard.1.2.5 Run-time errorsA somewhat different language issue arises with code that has compiled correctly, but for reasons of the particular data supplied to it causes errors in the running of the code. Languages can build run-time checks into the executable code to detect many such errors and take appropriate action.C is generally poor in providing run-time checking. This is one of the reasons why the code generated by C tends to be small and efficient, but there is a price to pay in terms of detecting errors during execution. C compilers generally do not provide run-time checking for such common problems as arithmetic exceptions (e.g. divide by zero), overflow, validity of addresses for pointers, or array bound errors.1.3 The use of C for safety-related systemsIt should be clear from section 1.2 that great care needs to be exercised when using C within safety-related systems. Because of the kinds of issues identified above, various concerns have been expressed about the use of C on safety-related systems. Certainly it is clear that the full C language should not be used for programming safety-related systems.However in its favour as a language is the fact that C is very mature, and consequently well analysed and tried in practice. Therefore its deficiencies are known and understood. Also there is a large amount of tool support available commercially which can be used to statically check the C source code and warn the developer of the presence of many of the problematic aspects of the language.If, for practical reasons, it is necessary to use C on a safety-related system then the use of the language must be constrained to avoid, as far as is practicable, those aspects of the language which do give rise to concerns. This document provides one such set of constraints (often referred to as a ‘language subset’).Hatton [2] considers that, providing “... severe and automatically enforceable constraints ...” are imposed, C can be used to write “... software of at least as high intrinsic quality and consistency as with other commonly used languages”.Nonetheless, it should be recognised that there are other languages available which are in general better suited to safety-related systems, having (for example) fewer insecurities and better type checking. Examples of languages generally recognised to be more suitable than C are Ada and Modula 2. If such languages could be available for a proposed system then their use should be seriously considered in preference to C.Note also that assembly language is no more suitable for safety-related systems than C, and in some respects is worse. Use of assembly language in safety-related systems is not recommended, and generally if it is to be used then it needs to be subject to stringent constraints.1.4 C standardizationThe current full standard for the C programming language is ISO/IEC 9899:1990 [1] along with technical corrigendum 1 (1995), and this is the standard which has been adopted by this document. The standard is also published by BSI in the UK as BS EN 29899:1993 and Amendment 1.The same standard was originally published by ANSI as X3.159-1989 [3]. In content the ISO/IEC standard and the ANSI standard are identical, and equally acceptable for use with this document. Note, however, that the section numbering is different in the two standards, and this document follows the section numbering of the ISO standard.Also note that the ANSI standard [3] contains a useful appendix giving the rationale behind some of the decisions made by the standardization committee. This appendix does not appear in the ISO edition.2.The vision2. MISRA C: The vision2.1 Rationale for the production of MISRA CThe MISRA consortium published its Development Guidelines for Vehicle Based Software [4] in 1994. This document describes the full set of measures that should be used in software development. In particular, the choices of language, compiler and language features to be used, in relationship with integrity level, are recognised to be of major importance. Section 3.2.4.3 (b) and Table 3 of the MISRA Guidelines [4] address this. One of the measures recommended is the use of a subset of a standardized language, which is already established practice in the aerospace, nuclear and defence industries. This document addresses the definition of a suitable subset of C.2.2 Objectives of MISRA CIn publishing this document regarding the use of the C programming language, the MISRA consortium is not intending to promote the use of C in the automotive industry. Rather it recognises the already widespread use of C, and this document seeks only to promote the safest possible use of the language.It is the hope of the MISRA consortium that this document will gain industry acceptance and that the adoption of a safer subset will become established as best practice both by vehicle manufacturers and the many component suppliers. It should also encourage training and enhance competence in general C programming, and in this specific subset, at both an individual level and a company level.Great emphasis is placed on the use of static checking tools to enforce compliance with the subset and it is hoped that this too will become common practice by the developers of automotive embedded systems.Although much has been written by academics concerning languages and their pros and cons this information is not well known among automotive developers. Another goal of this document is that engineers and managers within the automotive industry will become much more aware of the language-choice issues.The availability of many tools to assist in the development of software, particularly tools to support the use of C, is a benefit. However there is always a concern over the robustness of their design and implementation, particularly when used for the development of safety-related software. It is hoped that the active approach of the automotive industry to establish software best practice (through the MISRA Guidelines [4] and this document) will encourage the commercial off-the-shelf (COTS) tool suppliers to be equally active in ensuring their products are suitable for application in the automotive industry.3.Developing the subset3. MISRA C: Developing the subsetThe list of rules for this document was developed in three main phases. Firstly, a survey was conducted of available source material; secondly, this information was filtered and adapted into rules; and thirdly, the resulting material was subject to expert review and revision.The initial information was collected from a variety of sources, both published and anecdotal. The aim at this stage was to collect as much information as possible on the concerns that people have with the C language and its ‘danger areas’. Published sources of information included:•The ‘portability’annex (Annex G) of the ISO C standard [1]•“Safer C” by Les Hatton [2]•“C Traps and Pitfalls” by Andrew Koenig [5]S tandards created in-house by member companies of the MISRA consortium were also collated to provide additional information based on experience. Finally, additional ideas were collected from individuals, course notes and other such sources.T his pool of gathered information provided, in some cases, direct ideas for rules, and in other cases issues or problems with the language or its use which ought to be addressed in some way. Thus the second stage, of producing the list of rules, involved filtering and refining existing rules, and developing rules to address other issues which were identified.A lthough there is no totally objective way of arriving at a given set of rules, the following principles were used to guide this stage of the process:•Issues of style were omitted, i.e. issues which were not believed to have any significant impact on code integrity, but which were more matters of preference.•As far as practicable, rules were to be enforceable by static tools. In some cases, however, rules which are not statically enforceable were retained because the advicethey give needs to be heeded by the programmer.4.Scope4. MISRA C: Scope4.1 Base language issuesThe MISRA Guidelines [4] (Table 3) requires that “a restricted subset of a standardized structured language” be used. For C, this means that the language must only be used as defined in the ISO standard. This therefore precludes the use of:•K&R C (as defined in the First Edition of “The C Programming language” by Kernighan and Ritchie)•C++•Proprietary extensions to the C language4.2 Issues not addressedIssues of style and code metrics are somewhat subjective. It would be hard for any group of people to agree on what was appropriate, and it would be inappropriate for MISRA to give definitive advice. What is important is not the exact style guidelines adopted by a user, or the particular metrics used, but rather that the user defines style guidelines and appropriate metrics and limits (see sections 5.2.2 and 5.2.4).The MISRA consortium is not in a position to recommend particular vendors or tools to enforce the restrictions adopted. The user of this document is free to choose tools, and vendors are encouraged to provide tools to enforce the rules. The onus is on the user of this document to demonstrate that their tool set enforces the rules adequately.4.3 ApplicabilityThis document is designed to be applied to production code in automotive embedded systems.In terms of the execution environments defined by ISO 9899 [1] (section 5.1.2), this document is aimed at a ‘free-standing environment’, although it also addresses library issues since some standard libraries will often be supplied with an embedded compiler.Most of the requirements of this document may be applicable to embedded systems in other sectors if such use is considered appropriate. The requirements of this document will not necessarily be applicable to hosted systems.It is also not necessary to apply the rules in full when performing compiler and static tool benchmarking. Sometimes it will be necessary to deliberately break the rules when benchmarking tools, so as to measure the tools’responses.4.4 Safety Integrity Level issuesThis document requires that all its provisions shall be adopted in systems classified as Integrity Levels 2 or 3 as defined in the MISRA Guidelines [4] (Debilitating or Difficult to control).4.Scope (continued)To be consistent with the MISRA Guidelines [4] (3.2.4.3b), no recommendations are made at this time for Integrity Level 4 (Uncontrollable).4.5 Prerequisite knowledgeThis document is not intended to be an introduction or training aid to the subjects it embraces. It is assumed that readers of this document are familiar with the ISO C programming language standard and associated tools, and also have access to the primary reference documents. It also assumes that users have received appropriate training and are competent C language programmers.4.6 C++ issuesC++ is a different language to C, and the scope of this document does not include the C++ language, nor does it attempt to comment on the suitability or otherwise of C++ for programming safety-related systems. However the following comments about the use of C++ compilers and code should be noted.C++ is not simply a super-set of C (i.e. C plus extra features). There are a few specific constructs which have different interpretations in C and C++. In addition, valid C code may contain identifiers which in C++ would be interpreted as reserved words. For both of these reasons, code written in C and conforming to the ISO C standard will not necessarily compile under a C++ compiler with the same results as under a true C compiler. Thus the use of C++ compilers for compiling C code is deprecated by this document. If, for reasons of availability, a C++ compiler must be used to compile C code then the areas of difference between the two languages must first be fully understood.However, the use of additional compilers as extra static checking tools is encouraged. For this purpose, where the executable code is of no interest, C++ compilers may be used, and indeed can offer benefits because of the greater type checking they have over C.Where a compiler which is marketed as ‘C++’has a strictly conforming ISO C mode of operation then this is equivalent to a C compiler and may be used as such (in the C mode only). The same is true of any other tool which includes a conforming ISO C compiler as part of its functionality.C++ comments should not be used in C code. Although many C compilers support this form of comment (denoted by //), they are not a part of ISO standard C (see Rule 1).4.7 Auto-generated code issuesIf a code-generating tool is to be used, then it will be necessary to select an appropriate tool and undertake validation. Apart from suggesting that adherence to the requirements of this document may provide one criterion for assessing a tool, no further guidance is given on this matter and the reader is referred to the HSE recommendations for COTS [6].No judgement on the suitability of auto-code generation for MISRA Integrity Levels 2 and 3 should be implied by the inclusion of the topic within this document. Auto-generated code must be treated in just the same manner as manually produced code for the purpose of validation (See MISRA Guidelines [4] 3.1.3, Planning for V&V).ing MISRA C5. Using MISRA C5.1 The software engineering contextUsing a programming language to produce source code is just one activity in the software development process. Adhering to best practice in this one activity is of very limited value if the other commonly accepted development issues are not addressed. This is especially true for the production of safety-related systems. These issues are all addressed in the MISRA Guidelines [4] and, for example, include:•Documented development process•Quality system capable of meeting the requirements of ISO9001/ISO9000-3/TickIT [7,8,9]•Project management•Configuration management•Hazard analysis•Requirements•Design•Coding•Verification•ValidationIt is necessary for the software developers to justify that the whole of their development process is appropriate for the type of system they are developing. This justification will be incomplete unless a hazard analysis activity has been performed to determine the safety integrity level of the system.5.2 The programming language and coding contextWithin the coding phase of the software development process, the language subset is just one aspect of many and again adhering to best practice in this aspect is of very limited value if the other issues are not addressed. Key issues, following choice of language, are:•Training•Style Guide•Compiler selection and validation•Checking tool validation•Metrics•Test coverageAll decisions made on these issues need to be documented, along with the reasons for those decisions, and appropriate records should be kept for any activities performed. Such documentation may then be included in a safety justification if required.5.2.1 TrainingIn order to ensure an appropriate level of skill and competence on the part of those who produce the C source code formal training should be provided for:•The use of the C programming language for embedded applications•The use of the C programming language for high-integrity and safety-related systems•The use of static checking tools used to enforce adherence to the subset5.2.2 Style guideIn addition to adopting the subset, an organisation should also have an in-house style guide. This will contain guidance on issues which do not directly affect the correctness of the code but rather define a ‘house style’for the appearance of the source code. These issues are likely to be subjective. Typical issues to be addressed by a style guide include:•code layout and use of indenting•layout of braces ‘{ }’and block structures•statement complexity•naming conventions•use of comment statements•inclusion of company name, copyright notice and other standard file header informationWhile some of the content of the style guide may only be advisory, some may be mandatory. However the enforcement of the style guide is outside the scope of this document.For further information on style guides see [10].5.2.3 Tool selection and validationWhen choosing a compiler (which should be understood to include the linker), an ISO C compliant compiler should be used whenever possible. Where the use of the language is reliant on an ‘implementation-defined’feature (as identified in Annex G.3 of the ISO standard [1]) then the developer must benchmark the compiler to establish that the implementation is as documented by the compiler writer. See section 6.5.2 for more explanation of Annex G.。

MISRA--C编程规范

MISRA--C编程规范

MISRA--作为工业标准的C编程规范(嵌入式c开发者必读)MISRA--作为工业标准的C编程规范MISRA (The Motor Industry Software Reliability Association 汽车工业软件可靠性联会) 是位于英国的一个跨国汽车工业协会,其成员包括了大部分欧美汽车生产商。

其核心使命是为汽车工业提供服务和协助,帮助厂方开发安全的、高可靠性的嵌入式软件。

这个组织最出名的成果是所谓的MISRA C Coding Standard,这一标准中包括了127条C语言编码标准,通常认为,如果能够完全遵守这些标准,则你的C代码是易读、可靠、可移植和易于维护的。

最近很多嵌入式开发者都以MISRA C来衡量自己的编码风格,比如著名的uC/OS-II就得意地宣称自己99%遵守MISRA标准。

而《嵌入式开发杂志》也专门载文号召大家学习。

编码规范通常是一个公司自定的“土政策”,居然有人去做标准,而且还得到广泛的认可,这不禁引起我强烈的兴趣。

可惜这份标准的文本需要花钱去买,而且短短几十页,要价非常昂贵。

MISRA 在网上公布了一些文档,其中有关于MISRA C Coding Standard的Clarification报告,从中间你可以大致猜到MISRA标准本身是什么。

我仔细阅读了这些文档,并且通过阅读其他一些介绍性文档,大致了解了MISRA标准的主要内容。

这些条款确有过人之处,对于C/C++语言工程项目的代码质量管理能够起到良好的指导性作用,对于大部分软件开发企业来说,在MISRA的基础上适当修改就可以形成自己的规范。

当然其中也有一些过于严苛的东西,这就需要各个开发部门灵活处理了。

我个人的体会,编码规范虽然很简单,但是要完全执行,不折不扣,需要开发部门有很高的组织性和纪律性,并且有很好的代码评审机制。

因此,如果能够严格地遵守编码规范,本身就是一个开发部门实力的证明。

这里不可能将所有规则一一列出(事实上正式文本我一条也没看到),只列出一些比较有意思的条款,让大家有机会了解MISRA的风格。

misra c 2012关于括号使用的规则

misra c 2012关于括号使用的规则

misra c 2012关于括号使用的规则
MISRA C 2012关于括号使用的规则主要如下:
1. 在宏的参数中不应出现类似预处理指令的符号。

2. 由宏参数扩展产生的表达式应用括号括起来。

3. if或elif预处理指令的控制表达式应赋值为0或1。

4. if或elif中控制表达式使用的标识符在赋值前应被define。

5. 预处理器操作符不应使用。

6. 宏参数在紧随后后续不得有操作符的操作数,这本身就是收到进一步的宏替换,应仅被用作这些操作符的操作数。

7. 以开头的一行应是有效的预处理指令。

8. 所有的else、elif和endif预处理指令应该同与他们相关的if或者ifdef 指令放在相同的文件中。

9. define和undef不得用于保留标识符或保留宏的名字。

10. 不应定义保留的标识符或宏名。

11. 不应使用标准头文件<>。

12. 标准库中的输入输出函数不应使用。

这些规则旨在确保代码的正确性和安全性,减少潜在的错误和风险,并符合MISRA C 2012标准的要求。

软件编程规范(MISRA_C)

软件编程规范(MISRA_C)

软件编程规范目录一环境二语言扩展三文档四字符集五标识符六类型七常量八声明与定义九初始化十数值类型转换十一指针类型转换十二表达式十三控制语句表达式十四控制流十五 switch语句十六函数十七指针和数组十八结构与联合十九预处理指令二十标准库二十一运行时错误一环境规则1.1(强制):所有代码都必须遵照ISO 9899:1990 “Programming languages - C”,由ISO/IEC 9899/COR1:1995,ISO/IEC 9899/AMD1:1995,和ISO/IEC9899/COR2:1996 修订。

规则1.2(强制):不能有对未定义行为或未指定行为的依赖性。

这项规则要求任何对未定义行为或未指定行为的依赖,除非在其他规则中做了特殊说明,都应该避免。

如果其他某项规则中声明了某个特殊行为,那么就只有这项特定规则在其需要时给出背离性。

规则1.3(强制):多个编译器和/或语言只能在为语言/编译器/汇编器所适合的目标代码定义了通用接口标准时使用。

如果一个模块是以非C 语言实现的或是以不同的C 编译器编译的,那么必须要保证该模块能够正确地同其他模块集成。

C 语言行为的某些特征依赖于编译器,于是这些行为必须能够为使用的编译器所理解。

例如:栈的使用、参数的传递和数据值的存储方式(长度、排列、别名、覆盖,等等)。

规则1.4(强制):编译器/链接器要确保31 个有效字符和大小写敏感能被外部标识符支持。

ISO 标准要求外部标识符的头6 个字符是截然不同的。

然而由于大多数编译器/链接器允许至少31 个有效字符(如同内部标识符),因此对这样严格而并不具有帮助性的限制的适应性被认为是不必要的。

必须检查编译器/链接器具有这种特性,如果编译器/链接器不能满足这种限制,就使用编译器本身的约束。

规则1.5(建议):浮点应用应该适应于已定义的浮点标准浮点运算会带来许多问题,一些问题(而不是全部)可以通过适应已定义的标准来克服。

misra c 2012 允许的标准库函数

misra c 2012 允许的标准库函数

Misra C 2012 标准对标准库函数有一些限制和建议,但没有列出允许的标准库函数的详细清单。

Misra C 2012 的目标是提供一套规则来促进代码的可移植性、可靠性和可维护性,并减少潜在的错误。

以下是 Misra C 2012 对标准库函数的一些限制和建议:
1. 不得使用 `<stdio.h>` 中的输入输出函数,如 `printf` 和 `scanf`。

这是因为这些函数会引入不确定的行为和难以预测的结果。

2. 应避免使用 `<stdlib.h>` 中的动态内存分配函数,如 `malloc` 和 `free`。

这是为了避免内存泄漏和内存错误。

3. 不得使用 `<float.h>` 中的浮点数函数,如 `sqrt` 和 `fabs`。

这是为了避免浮点数运算的误差和不确定性。

4. 应避免使用 `<string.h>` 中的字符串处理函数,如 `strcpy` 和 `strlen`。

这是为了避免缓冲区溢出和字符串拷贝错误。

5. 应避免使用 `<time.h>` 中的时间函数,如 `time` 和 `localtime`。

这是为了避免依赖于系统时间和时区的不确定性。

总之,Misra C 2012 鼓励程序员尽量避免使用标准库函数,特别是那些可能引入不确定性和潜在错误的函数。

相反,应该使用更安全、可靠和可移植的替代方案。

但具体的允许的标准库函数列表并没有在标准中明确规定,这需要根据项目和实际需求进行评估和决策。

建议在开发过程中参考 Misra C 2012 标准和相关文档,以便更好地理解和遵守规则。

misra-c 解读 -回复

misra-c 解读 -回复

misra-c 解读-回复[Misrac 解读] 是一种软件安全工程标准,旨在规范C编程语言的使用,以提高软件的可靠性和安全性。

Misrac(Motor Industry Software Reliability Association C)由汽车工业的软件开发专家组成的组织于1994年成立。

他们致力于解决汽车电子系统中的软件可靠性和安全性问题。

Misrac标准的目标是提供一套能够降低软件开发中存在的缺陷风险的指导原则。

这些原则主要包括了C编码规范、代码风格和编程实践等方面。

此外,Misrac标准还提供了一些软件工具来实现标准的检查和自动化,以确保开发人员能够遵守Misrac标准。

Misrac标准的内容相对详细和全面,涵盖了C语言中的许多特殊情况和编码规范。

根据Misrac标准,C编程应该遵循以下主要原则:1. 可移植性:Misrac标准强调编写可移植的代码,以便能够在不同的平台上运行。

这种可移植性是通过避免使用不可移植的功能和特性来实现的。

2. 确定性:Misrac标准鼓励编写确定性的代码,以确保代码在不受外界环境变化的情况下具有可预测的行为。

这要求编写代码时避免使用不确定的行为和依赖于底层实现的特性。

3. 可读性和可维护性:Misrac标准强调编写易于阅读和维护的代码。

它提供了一些规范和建议,如变量命名、代码布局、注释等,以提高代码的可读性和可维护性。

4. 安全性:Misrac标准重视编写安全的代码,以防止潜在的安全漏洞和攻击。

它提供了一些代码规范和最佳实践,如避免缓冲区溢出、使用安全的字符串处理函数等。

Misrac标准在汽车行业得到广泛应用,特别是在汽车电子系统的软件开发过程中。

这是因为汽车电子系统对软件可靠性和安全性有较高的要求,任何软件缺陷或漏洞可能导致严重的后果,如汽车故障或安全事故。

遵循Misrac标准有许多好处。

首先,它可以提高软件的质量和可靠性,减少软件缺陷和故障的概率。

其次,它可以提高软件开发过程的效率和一致性,使不同开发人员之间的代码风格和质量有更高的一致性。

MISRA准则细则

MISRA准则细则

MISRA准则细则
MISRA准则,全称为MISRA C:2024 Guidelines for the Use of the C Language in Critical Systems,是一套用于开发严格高可靠性、高可维护性嵌入式系统的准则。

本文将对MISRA准则的细则进行详细介绍。

1.数据类型和语言特性:
2.控制流和循环:
3.表达式和操作数:
MISRA准则对表达式进行了一系列限制,如要求将复杂的表达式拆分成多个简单的表达式,使用括号来明确操作符的优先级等。

准则还规定了一些禁止使用的操作符和表达式,如不允许在一个表达式中同时使用+=和-=等。

4.函数:
5.指针和数组:
6.编码风格和命名规范:
总的来说,MISRA准则旨在提高嵌入式系统的可靠性和可维护性,通过限制一些潜在的编程错误和不安全的操作,帮助开发人员编写更加健壮和安全的代码。

然而,也需要注意的是,MISRA准则并非适用于所有的项目,开发人员需要根据具体情况灵活应用,并结合项目的要求和约束进行决策。

在实际应用中,可以使用各种静态代码分析工具来辅助检查代码是否符合MISRA准则,如PC-lint、Coverity等。

这些工具能够自动检测代码
中的潜在问题和不符合准则的地方,并生成相应的警告或错误报告,提高代码质量和开发效率。

最后,MISRA准则是一套非常全面和细致的规范,通过遵循这些准则可以提高代码的质量和可维护性。

然而,准则只是一种指导性的建议,最终的代码质量和可维护性还需要开发团队的共同努力和严格执行。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

学习MISRA C之二:跨越数据类型的重重陷阱数据类型是编程语言中最基本的构成元素,但却是最易被忽略的一环,程序员愿意把几乎100%的精力都花在算法研究、程序流控制等大环节上,却很少在数据类型问题上反复斟酌。

细节决定成败,一个螺丝钉的失误可能导致一个飞行器的毁灭,一个数据类型的错误同样可以让庞大的软件系统崩溃。

MISRA—c中关于数据类型的规则主要分为两个方面。

一是数据类型相关的编程风格;二是不同数据类型之间的转换,后者是重点。

这里介绍MISRA_C关于数据类型的部分规则,更多的规则请参考《MISRA-C:2OO4)》一书。

下文中凡是未加特殊说明的都是强制(required)规则.个别推荐(advisory)规则加了“推荐”标识。

在展开论述之前,先看两个问题,读者可以带着疑问阅读完本章内容。

问题1:执行以下程序,result_8的值是多少?uint8_t port = 0x5a ;uint8_t result_8 ;result_8 = (~port) > > 4 ;/*注:uint8_t表示8位无符号整型*/问题2:执行以下程序,d的值是多少?uint16_t a = 10 ;uint16_t b = 65531 ;uint32_t c = 0 ;uint32_t d ;d = a + b + c ;/*注:uintl6_t表示16位无符号整型,uint32_t表示32位无符号整型*/1 数据类型相关的编程风格规则6.3(推荐):必须用typedef显式标识出各数据类型的长度和符号特性,避免直接使用标准数据类型。

例如,一个32位的整数系统,可定义如下:typedef char chat_t;typedef sigrled char int8_t;typedef signed short intl6_t;typedef signed int int32_t;typedef signed long int64_t;typedef unsitgned chat uint8_t;typedef unsigned short uint16_t;typedef unsigned int uint32_t;typedef unsigned 1ong uint64_t;之所以用intl6_t和uint32_t等代替signed short和unsigned int等标准数据类型标识符,是由于不同的编译器对标准数据类型的长度定义是不一样的。

比如说一个16位系统,很可能就把short和int都定义成16位,long定义成32位,这与上文32位系统中标准数据类型的长度就不一致。

用intl6_t和uint_32等标识符来定义变量,一方面增加了程序的可读性,使得程序员本人或其他读者都能对程序中数据的具体信息胸有成竹;另一方面也有助于程序在不同系统之间的移植,节省开发时间,减少隐患。

规则7 1:不得使用八进制常数(O除外)或八进制转义符。

思考如下数组:code[1]=109;code[2]=100;code[3]=O52code[4]=O71;/*注:八进制常数须在最高位加O*/code[3]的实际值是42(十进制),code[4]的实际值是57(十进制);但估计很多读者会把code[3]认成是52(十进制),code[4]认成是7l(十进制)。

八进制数在C程序中使用的频率远小于十进制数和十六进制数,为了保证程序的可读性和安全性,程序员不允许使用八进制数以及八进制转义符。

2 数据类型转换如果程序员对数据类型的转换有很清晰的认识,并且在必要的地方做了正确的显式强制转换,那程序是安全的。

但有时由于程序员的疏忽,或者是过于相信编译器的“智慧”程度,导致表达式中有很多隐式转换(即没有显式地强制转换),而这些隐式数据类型转换很可能就构成致命的漏洞。

MISRA—C中数据类型转换规则的着眼点,即是避免有漏洞的隐式数据转换。

在介绍MISRA—C关于数据类型转换的部分规则之前,先介绍整型操作数的“平衡(balance)”原则。

所谓整型操作数“平衡”原则,即对于隐式表达式,编译器会按照既定规则对操作数进行位数扩充,其中int和unsiglled int在整型表达式“平衡”过程中占重要地位。

下面分析一个简单的隐式整型表达式c=a+b(假设a的存储位数不大于b的存储位数),编译器是这样来处理这个表达式的:如果b是短整型(即位数少于int,比如char、short等)或者整型(int或unsigned int),那a也是短整型或者整型,执行“+”运算之前,a和b都将被扩充为整型(int或者unsigned int),然后相加的结果赋给c(如果c不是int或者unsigned int类型,则这个赋值操作也会包含隐式的扩充或截断操作)。

如果b是长整型(存储位数多于int),则a会被扩充为与b相当的长整型,再执行“+”运算,所得结果赋给c(可能包含隐式的扩充或截断操作)。

绝大部分的操作符用于整型运算的时候,都遵循上述“平衡”原则,比如:算术操作符、位操作符和关系运算符。

但逻辑操作符不遵循上述“平衡”原则。

此外左移(<<)和右移(>>)运算符也不遵循“平衡”原则,只和移位操作符左边的整型操作数相关。

假设一个8位的短整型变量值为Oxf5(十六进制),则右移4位所得结果是O xof(十六进制)。

明确了上述背景后,下面来关注本文一开始提出的“问题1”(代码参见前文)。

绝大部分拥有嵌人式C程序开发经验的人都明白这段代码的原意是将port的值取反后右移4 位赋值给result_8(在用I/O口控制共阳的LED时经常这么做),程序员期望的结果显然是resuIt_8=0xof。

然而,由于整型的“平衡” 原则,在16位编译器中,~port的值是Oxffa5;在32位编译器中,~pott的值是Oxffffffa5。

无论哪种情况,最后结果(右移4位后赋值给result_8的时候有一个截断操作)都是resuIt_8=Oxfa,而非程序员预期的result_8=OxOf。

倘若将最后一行代码改成result一8=((uin8_t)(~port))>>4,则result_8可取得预期的值。

针对以上情况,MISRA-c提出了相应规则。

规则10.5:如果位操作符~和移位操作符<<(或>>)联合作用于unsigned char或者unsigned short类型的操作数时,中间运算步骤的结果必须立刻显式强制转换为预期的短整型数据类型。

为了加深对“平衡”原则的理解,再来分析一下“问题2”。

如果用一个32位的编译器来编译这段程序,最终结果是d=6554l,程序员“幸运地”得到了预期的结果。

如果是16位的编译器,得到的结果却是d=5。

由于“+”运算是左结合的,所以d=a+b+c等效于d=(a+b)+c,即先执行a+b,所得的和再与c相加.最后结果赋值给d。

问题就出在a+b这个中间步骤中。

由于a和b都是16位整型(注意编译器也是16位的),故而a+b的结果也是16位整型,则a+b的值是Ox0005(有溢出);再扩充为32位整型Ox00000005和c相加赋值给d,d=5,这并非程序员预期的结果。

所以,在16位编译器中,问题2的那段代码很可能导致严重错误。

当然,如果程序员用()指定了运算优先级的话,即最后一行代码写成d=a+(b+c),也可以避免上述溢出错误,然而,这终究不是治本的办法。

只有明确每一个操作数的实际数据类型,才能保障代码的安全性。

MISRA-C中对于表达式中存在隐式数据类型转换的情况作了严格的限制。

规则10.1:以下情况下,整型表达式中不允许出现隐式数据类型转换。

①整型操作数不是被扩充为更多位数的同符号整数;②表达式是复杂表达式;③表达式不是常数表达式,且是函数的参数;④表达式不是常数表达式,且是函数的返回表达式。

规则10.2:以下情况下,浮点数表达式中不允许出现隐式数据类型转换。

①浮点型操作数不是被扩充为更多位数的同符号浮点数;②表达式是复杂表达式;③表达式是函数的参数;④表达式是函数的返回表达式。

整型表达式规则和浮点数表达式规则基本类似,只是浮点数表达式规则更为苛刻一些,对浮点型的常数也作了严格的限定。

这两条规则中,出现了“复杂表达式”的概念。

请注意,MISRA—C中“复杂表达式”的概念和其他介绍C编程规范书籍中“复杂表达式”的概念是不一样的。

在MISRA-C中,非“复杂表达式”基本只限制在常数表达式或者函数的返回值。

为了明确上述规则中关于“复杂表达式”和“返回表达式”的概念,此处举一例子。

定义一个函数uintl6_t foo(void),函数体如下:uintl6_t foo(void){return(a+b+c);函数体中最后一句return(a+b+c)中的a+b+c是返回表达式。

倘若在C程序的其他地方有a=foo()这样的语句,则用的是foo()函数的返回值。

在MISRA-c中,的资源,完成了采用USB接口技术的热敏打印机的开发,并对打印头作了充分的保护。

通过采用相应的算法实现这个赋值表达式不是“复杂表达式”。

至于表达式作为函数参数等情况,碍于篇幅的原因,此处就不再详细展开了。

权衡一下利弊,在涉及到数据类型转换的时候,与其花很大力气去区分一个隐式表达式是否在MISRA—C规则的“黑名单”中,还不如用强制转换符显式地标识出每个操作数的实际数据类型,这是最为稳妥的方法。

总而言之,MISRA—C关于数据类型转换规则的中心意思,是要求程序员明确任意一个操作数的实际数据类型。

个数据操作的关键,从而能写出最清晰易懂而又安全的代码。

MISRA—C关于数据类型的规则可保障程序员在迈出这一步的时候不会摔倒。

相关文档
最新文档