SEI CERT C++ Coding Standard (2016 Edition)
Total Page:16
File Type:pdf, Size:1020Kb
SEI CERT C++ Coding Standard Rules for Developing Safe, Reliable, and Secure Systems in C++ 2016 Edition Aaron Ballman Copyright 2017 Carnegie Mellon University This material is based upon work funded and supported by the Department of Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University for the operation of the Software Engineering Institute, a federally funded research and development center. Any opinions, findings and conclusions or recommendations expressed in this material are those of the au- thor(s) and do not necessarily reflect the views of the United States Department of Defense. References herein to any specific commercial product, process, or service by trade name, trade mark, manu- facturer, or otherwise, does not necessarily constitute or imply its endorsement, recommendation, or favoring by Carnegie Mellon University or its Software Engineering Institute. This report was prepared for the SEI Administrative Agent AFLCMC/PZM 20 Schilling Circle, Bldg 1305, 3rd floor Hanscom AFB, MA 01731-2125 NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING INSTITUTE MATERIAL IS FURNISHED ON AN “AS-IS” BASIS. CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. [Distribution Statement A] This material has been approved for public release and unlimited distribution. Please see Copyright notice for non-US Government use and distribution. Internal use:* Permission to reproduce this material and to prepare derivative works from this material for in- ternal use is granted, provided the copyright and “No Warranty” statements are included with all reproductions and derivative works. External use:* This material may be reproduced in its entirety, without modification, and freely distributed in written or electronic form without requesting formal permission. Permission is required for any other external and/or commercial use. Requests for permission should be directed to the Software Engineering Institute at [email protected]. * These restrictions do not apply to U.S. government entities. Carnegie Mellon® and CERT® are registered marks of Carnegie Mellon University. DM-0004501 V01-20170309-0910 Table of Contents 1 Introduction 1 1.1 Scope 1 1.2 Audience 3 1.3 Usage 3 1.4 How this Coding Standard Is Organized 4 1.5 Relation to the CERT C Coding Standard 9 1.6 Rules Versus Recommendations 10 1.7 Tool Selection and Validation 11 1.8 Conformance Testing 12 1.9 Development Process 13 1.10 System Qualities 14 1.11 Automatically Generated Code 14 1.12 Government Regulations 15 1.13 Acknowledgments 17 2 Declarations and Initialization (DCL) 18 2.1 DCL50-CPP. Do not define a C-style variadic function 18 2.2 DCL51-CPP. Do not declare or define a reserved identifier 22 2.3 DCL52-CPP. Never qualify a reference type with const or volatile 28 2.4 DCL53-CPP. Do not write syntactically ambiguous declarations 31 2.5 DCL54-CPP. Overload allocation and deallocation functions as a pair in the same scope 37 2.6 DCL55-CPP. Avoid information leakage when passing a class object across a trust boundary 41 2.7 DCL56-CPP. Avoid cycles during initialization of static objects 51 2.8 DCL57-CPP. Do not let exceptions escape from destructors or deallocation functions 57 2.9 DCL58-CPP. Do not modify the standard namespaces 63 2.10 DCL59-CPP. Do not define an unnamed namespace in a header file 69 2.11 DCL60-CPP. Obey the one-definition rule 76 3 Expressions (EXP) 83 3.1 EXP50-CPP. Do not depend on the order of evaluation for side effects 83 3.2 EXP51-CPP. Do not delete an array through a pointer of the incorrect type 90 3.3 EXP52-CPP. Do not rely on side effects in unevaluated operands 92 3.4 EXP53-CPP. Do not read uninitialized memory 96 3.5 EXP54-CPP. Do not access an object outside of its lifetime 101 3.6 EXP55-CPP. Do not access a cv-qualified object through a cv-unqualified type 112 3.7 EXP56-CPP. Do not call a function with a mismatched language linkage 117 3.8 EXP57-CPP. Do not cast or delete pointers to incomplete classes 120 SEI CERT C++ CODING STANDARD (2016 EDITION) | V01 i Software Engineering Institute | Carnegie Mellon University [DISTRIBUTION STATEMENT A] Approved for public release and unlimited distribution. 3.9 EXP58-CPP. Pass an object of the correct type to va_start 126 3.10 EXP59-CPP. Use offsetof() on valid types and members 130 3.11 EXP60-CPP. Do not pass a nonstandard-layout type object across execution boundaries 134 3.12 EXP61-CPP. A lambda object must not outlive any of its reference captured objects 139 3.13 EXP62-CPP. Do not access the bits of an object representation that are not part of the object’s value representation 142 3.14 EXP63-CPP. Do not rely on the value of a moved-from object 147 4 Integers (INT) 153 4.1 INT50-CPP. Do not cast to an out-of-range enumeration value 153 5 Containers (CTR) 157 5.1 CTR50-CPP. Guarantee that container indices and iterators are within the valid range 157 5.2 CTR51-CPP. Use valid references, pointers, and iterators to reference elements of a container 163 5.3 CTR52-CPP. Guarantee that library functions do not overflow 170 5.4 CTR53-CPP. Use valid iterator ranges 174 5.5 CTR54-CPP. Do not subtract iterators that do not refer to the same container 177 5.6 CTR55-CPP. Do not use an additive operator on an iterator if the result would overflow 182 5.7 CTR56-CPP. Do not use pointer arithmetic on polymorphic objects 184 5.8 CTR57-CPP. Provide a valid ordering predicate 189 5.9 CTR58-CPP. Predicate function objects should not be mutable 193 6 Characters and Strings (STR) 198 6.1 STR50-CPP. Guarantee that storage for strings has sufficient space for character data and the null terminator 198 6.2 STR51-CPP. Do not attempt to create a std::string from a null pointer 201 6.3 STR52-CPP. Use valid references, pointers, and iterators to reference elements of a basic_string 205 6.4 STR53-CPP. Range check element access 209 7 Memory Management (MEM) 213 7.1 MEM50-CPP. Do not access freed memory 213 7.2 MEM51-CPP. Properly deallocate dynamically allocated resources 220 7.3 MEM52-CPP. Detect and handle memory allocation errors 233 7.4 MEM53-CPP. Explicitly construct and destruct objects when manually managing object lifetime 238 7.5 MEM54-CPP. Provide placement new with properly aligned pointers to sufficient storage capacity 243 7.6 MEM55-CPP. Honor replacement dynamic storage management requirements 249 7.7 MEM56-CPP. Do not store an already-owned pointer value in an unrelated smart pointer 253 7.8 MEM57-CPP. Avoid using default operator new for over-aligned types 258 SEI CERT C++ CODING STANDARD (2016 EDITION) | V01 ii Software Engineering Institute | Carnegie Mellon University [DISTRIBUTION STATEMENT A] Approved for public release and unlimited distribution. 8 Input Output (FIO) 261 8.1 FIO50-CPP. Do not alternately input and output from a file stream without an intervening positioning call 261 8.2 FIO51-CPP. Close files when they are no longer needed 264 9 Exceptions and Error Handling (ERR) 267 9.1 ERR50-CPP. Do not abruptly terminate the program 267 9.2 ERR51-CPP. Handle all exceptions 273 9.3 ERR52-CPP. Do not use setjmp() or longjmp() 276 9.4 ERR53-CPP. Do not reference base classes or class data members in a constructor or destructor function-try-block handler 280 9.5 ERR54-CPP. Catch handlers should order their parameter types from most derived to least derived 282 9.6 ERR55-CPP. Honor exception specifications 284 9.7 ERR56-CPP. Guarantee exception safety 288 9.8 ERR57-CPP. Do not leak resources when handling exceptions 292 9.9 ERR58-CPP. Handle all exceptions thrown before main() begins executing 298 9.10 ERR59-CPP. Do not throw an exception across execution boundaries 303 9.11 ERR60-CPP. Exception objects must be nothrow copy constructible 307 9.12 ERR61-CPP. Catch exceptions by lvalue reference 312 9.13 ERR62-CPP. Detect errors when converting a string to a number 316 10 Object Oriented Programming (OOP) 320 10.1 OOP50-CPP. Do not invoke virtual functions from constructors or destructors 320 10.2 OOP51-CPP. Do not slice derived objects 325 10.3 OOP52-CPP. Do not delete a polymorphic object without a virtual destructor 333 10.4 OOP53-CPP. Write constructor member initializers in the canonical order 336 10.5 OOP54-CPP. Gracefully handle self-copy assignment 340 10.6 OOP55-CPP. Do not use pointer-to-member operators to access nonexistent members 345 10.7 OOP56-CPP. Honor replacement handler requirements 350 10.8 OOP57-CPP. Prefer special member functions and overloaded operators to C Standard Library functions 353 10.9 OOP58-CPP. Copy operations must not mutate the source object 360 SEI CERT C++ CODING STANDARD (2016 EDITION) | V01 iii Software Engineering Institute | Carnegie Mellon University [DISTRIBUTION STATEMENT A] Approved for public release and unlimited distribution. 11 Concurrency (CON) 365 11.1 CON50-CPP. Do not destroy a mutex while it is locked 365 11.2 CON51-CPP. Ensure actively held locks are released on exceptional conditions 368 11.3 CON52-CPP. Prevent data races when accessing bit-fields from multiple threads 371 11.4 CON53-CPP.