You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

coding_guild_cpp_en.md 28 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  1. <!-- TOC -->
  2. - [Note](#note)
  3. - [Scope](#scope)
  4. - [Code Style](#1-code-style)
  5. - [Naming](#11-naming)
  6. - [Format](#12-format)
  7. - [Comment](#13-comment)
  8. - [General Coding](#2-general-coding)
  9. - [Code Design](#21-code-design)
  10. - [Header File and Preprocessing](#22-header-file-and-preprocessing)
  11. - [Data Type](#23-data-type)
  12. - [Constant](#24-constant)
  13. - [Variable](#25-variable)
  14. - [Expression](#26-expression)
  15. - [Conversion](#27-conversion)
  16. - [Control Statement](#28-control-statement)
  17. - [Declaration and Initialization](#29-declaration-and-initialization)
  18. - [Pointer and Array](#210-pointer-and-array)
  19. - [String](#211-string)
  20. - [Assert](#212-assert)
  21. - [Class and Object](#213-class-and-object)
  22. - [Function Design](#214-function-design)
  23. - [Function Usage](#215-function-usage)
  24. - [Memory](#216-memory)
  25. - [File](#217-file)
  26. - [Secure Function](#218-secure-function)
  27. <!-- /TOC -->
  28. ## Note
  29. This document is developed based on [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html), Huawei C++ Coding Style Guide, Huawei secure coding standards, and industry consensus. To participate in the MindSpore community, please comply with this style guide, and then the Google C++ Style Guide.
  30. If you disagree with the rules, you are advised to submit an issue and provide reasons. The issue can take effect after being reviewed, accepted, and modified by the MindSpore community operation team.
  31. ## Scope
  32. MindSpore open source community
  33. ------------------
  34. ### <a name="csf">1. Code Style</a>
  35. #### <a name="nm">1.1 Naming</a>
  36. ##### Rule 1.1.1 File Naming
  37. C++ files are named in the format of lowercase letters + underscores (_). The file name extension is `.cc`. The header file name extension is `.h`. The unit test file name ends with `_test.cc`.
  38. > a_b_c.h
  39. > a_b_c.cc
  40. > a_b_c_test.cc
  41. ##### Rule 1.1.2 Use lowercase letters and underscores (_) to name local variables and parameters.
  42. ```cpp
  43. void FooBar(int func_param) {
  44. int local_var;
  45. }
  46. ```
  47. ##### Rule 1.1.3 Use lowercase letters and underscores (_) to name member variables, with an underscore (_) as the suffix.
  48. ```cpp
  49. class FooBar {
  50. public:
  51. int mamber_var_;
  52. };
  53. ```
  54. ##### Rule 1.1.4 Use uppercase letters and underscores (_) in macro names.
  55. ```cpp
  56. #define MS_LOG(...)
  57. ```
  58. ##### Rule 1.1.5 Name constants and enumerations in the CamelCase style starting with letterr "k."
  59. ```cpp
  60. const int kDaysInAWeek = 7;
  61. enum UrlTableErrors {
  62. kOk = 0,
  63. kErrorOutOfMemory,
  64. kErrorMalformedInput,
  65. };
  66. ```
  67. #### <a name="fmt">1.2 Format</a>
  68. ##### Recommendation 1.2.1 Each line contains a maximum of 120 characters.
  69. If a line contains more than 120 characters, start a new line properly.
  70. ##### Rule 1.2.2 Use spaces to indent, two at a time.
  71. ##### Rule 1.2.3 When declaring a pointer or referencing variables or parameters, follow variable names with `&` and `*` and place a space on the other side.
  72. ```cpp
  73. char *c;
  74. const std::string &str;
  75. ```
  76. ##### Rule 1.2.4 Use braces to include an if statement.
  77. ```cpp
  78. // Even if the if branch code is within one line, braces are required.
  79. if (cond) {
  80. single line code;
  81. }
  82. ```
  83. ##### Rule 1.2.5 Use braces for loop statements such as for and while statements, even if the loop body is empty or there is only one loop statement.
  84. ##### Rule 1.2.6 Keep a consistent line break style for expressions and ensure that operators are placed at the end of a line.
  85. ```cpp
  86. int a = a_very_long_expression +
  87. a_very_very_long_expression +
  88. a_very_very_very_long_expression;
  89. ```
  90. ##### Rule 1.2.7 Each variable definition or assignment statement occupies one line.
  91. ```cpp
  92. a = 1;
  93. b = 2;
  94. c = 3;
  95. ```
  96. #### <a name="nts">1.3 Comment</a>
  97. ##### Rule 1.3.1 File header comments contain copyright statements.
  98. All .h and .cc files must contain the following copyright statements:
  99. ```cpp
  100. /**
  101. * Copyright 2019 Huawei Technologies Co., Ltd
  102. *
  103. * Licensed under the Apache License, Version 2.0 (the "License");
  104. * you may not use this file except in compliance with the License.
  105. * You may obtain a copy of the License at
  106. *
  107. * http://www.apache.org/licenses/LICENSE-2.0
  108. *
  109. * Unless required by applicable law or agreed to in writing, software
  110. * distributed under the License is distributed on an "AS IS" BASIS,
  111. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  112. * See the License for the specific language governing permissions and
  113. * limitations under the License.
  114. */
  115. ```
  116. > Notes:
  117. > Files created in 2020 should contain `Copyright 2020 Huawei Technologies Co., Ltd`.
  118. > Files created in 2019 and modified in 2020 should contain `Copyright 2019-2020 Huawei Technologies Co., Ltd`.
  119. ##### Rule 1.3.2 A comment is placed above or to the right of the code. There must be a space between the comment character and the comment content, and at least one space between the code and its comment on the right. Use `//`, not `/**/`.
  120. ```cpp
  121. // this is multi-
  122. // line comment
  123. int foo; // this single-line comment
  124. ```
  125. ##### Rule 1.3.3 Do not use comments such as TODO, TBD, and FIXME in code. You are advised to submit an issue for tracking.
  126. ##### Recommendation 1.3.4 Function header comments with no content are forbidden.
  127. Not all functions require header comments. You are advised to use the name of the function as its comment and write header comments if there is the need. For the information that cannot be expressed by the function prototype but is expected to be known by readers, function header comments are required.
  128. Do not write useless or redundant function headers. The function header comments are optional, including but not limited to function description, return values, performance constraints, usage, memory conventions, algorithm implementation, and reentrant requirements.
  129. ### <a name="cc">2. General Coding</a>
  130. #### <a name="cdes">2.1 Code Design</a>
  131. ##### Rule 2.1.1 Check the validity of all external data, including but not limited to function input parameters, external input named lines, files, environment variables, and user data.
  132. ##### Rule 2.1.2 When transferring function execution results, preferentially use return values and avoid output parameters.
  133. ```cpp
  134. FooBar *Func(const std::string &in);
  135. ```
  136. ##### Rule 2.1.3 Delete invalid, redundant, or never-executed code.
  137. Although most modern compilers in many cases can alert you to invalid or never executed code, responding alarms should be identified and cleared.
  138. Identify and delete invalid statements or expressions from the code.
  139. ##### Rule 2.1.4 Follow additional specifications to the C++ exception mechanism.
  140. ###### Rule 2.1.4.1 Specify the types of exceptions to be captured. Do not capture all exceptions.
  141. ```cpp
  142. // Incorrect
  143. try {
  144. // do something;
  145. } catch (...) {
  146. // do something;
  147. }
  148. // Correct
  149. try {
  150. // do something;
  151. } catch (const std::bad_alloc &e) {
  152. // do something;
  153. }
  154. ```
  155. #### <a name="inc">2.2 Header File and Preprocessing</a>
  156. ##### Rule 2.2.1 Use the new standard C++ header file.
  157. ```cpp
  158. // Correct
  159. #include <cstdlib>
  160. // Incorrect
  161. #include <stdlib.h>
  162. ```
  163. ##### Rule 2.2.2 Header file cyclic dependency is forbidden.
  164. An example of cyclic dependency (also known as circular dependency) is: a.h contains b.h, b.h contains c.h, and c.h contains a.h. If any of these header files is modified, all code containing a.h, b.h, and c.h needs to be recompiled.
  165. The cyclic dependency of header files reflects an obviously unreasonable architecture design, which can be avoided through optimization.
  166. ##### Rule 2.2.3 Do not include unnecessary header files.
  167. ##### Rule 2.2.4 It is prohibited to reference external function interfaces and variables in extern declaration mode.
  168. ##### Rule 2.2.5 Do not include header files in extern "C".
  169. ##### Rule 2.2.6 Do not use "using" to import namespace in a header file or before #include statements.
  170. #### <a name="dtype">2.3 Data Type</a>
  171. ##### Recommendation 2.3.1 Do not abuse typedef or #define to alias basic types.
  172. ##### Rule 2.3.2 Use “using” instead of typedef to define the alias of a type to avoid shot-bomb modification caused by type changes.
  173. ```cpp
  174. // Correct
  175. using FooBarPtr = std::shared_ptr<FooBar>;
  176. // Incorrect
  177. typedef std::shared_ptr<FooBar> FooBarPtr;
  178. ```
  179. #### <a name="cons">2.4 Constant</a>
  180. ##### Rule 2.4.1 Do not use macros to replace constants.
  181. ##### Rule 2.4.2 Do not use magic numbers or character strings.
  182. ##### Recommendation 2.4.3 Ensure that a constant has only one responsibility.
  183. #### <a name="var">2.5 Variable</a>
  184. ##### Recommendation 2.5.1 Use namespaces to manage global constants. If the global constants are closely tied to a class, you can use static member constants to manage them.
  185. ```cpp
  186. namespace foo {
  187. int kGlobalVar;
  188. class Bar {
  189. private:
  190. static int static_member_var_;
  191. };
  192. }
  193. ```
  194. ##### Rule 2.5.2 Do not use global variables. Use the singleton pattern cautiously to avoid abuse.
  195. ##### Rule 2.5.3 A variable cannot be referenced again if it is contained in an increment or decrement operation in an expression.
  196. ##### Rule 2.5.4 After the resource is released, immediately assign a new value to the pointer variable that points to a resource handle or descriptor, or set the value to NULL.
  197. ##### Rule 2.5.5 Do not use uninitialized variables.
  198. #### <a name="exp">2.6 Expression</a>
  199. ##### Recommendation 2.6.1 When comparing expressions, follow the principle that the left side tends to change and the right side tends to remain unchanged.
  200. ```cpp
  201. // Correct
  202. if (ret != SUCCESS) {
  203. ...
  204. }
  205. // Incorrect
  206. if (SUCCESS != ret) {
  207. ...
  208. }
  209. ```
  210. ##### Rule 2.6.2 Use parentheses to specify the operator precedence to avoid rookie errors.
  211. ```cpp
  212. // Correct
  213. if (cond1 || (cond2 && cond3)) {
  214. ...
  215. }
  216. // Incorrect
  217. if (cond1 || cond2 && cond3) {
  218. ...
  219. }
  220. ```
  221. #### <a name="exc">2.7 Conversion</a>
  222. ##### Rule 2.7.1 Use the type casting provided by the C++ instead of the C style. Do not use const_cast and reinterpret_cast.
  223. #### <a name="ctrl">2.8 Control Statement</a>
  224. ##### Rule 2.8.1 A switch statement must have a default branch.
  225. #### <a name="init">2.9 Declaration and Initialization</a>
  226. ##### Rule 2.9.1 Do not use `memcpy_s` or `memset_s` to initialize non-POD objects.
  227. #### <a name="ptr">2.10 Pointer and Array</a>
  228. ##### Rule 2.10.1 Do not use the pointer returned by c_str () of std::string.
  229. ```cpp
  230. // Incorrect
  231. const char * a = std::to_string(12345).c_str();
  232. ```
  233. ##### Rule 2.10.2 Prefer `unique_ptr` to `shared_ptr`.
  234. ##### Rule 2.10.3 Create `shared_ptr` by using `std::make_shared` instead of `new`.
  235. ```cpp
  236. // Correct
  237. std::shared_ptr<FooBar> foo = std::make_shared<FooBar>();
  238. // Incorrect
  239. std::shared_ptr<FooBar> foo(new FooBar());
  240. ```
  241. ##### Rule 2.10.4 Use a smart pointer to manage objects. Do not use new or delete.
  242. ##### Rule 2.10.5 Do not use auto_ptr.
  243. ##### Rule 2.10.6 For formal parameters of pointer and reference types, if the parameters do not need to be modified, use const.
  244. ##### Rule 2.10.7 Use the array length as a function parameter when the array is a function parameter.
  245. ```cpp
  246. int ParseMsg(BYTE *msg, size_t msgLen) {
  247. ...
  248. }
  249. ```
  250. #### <a name="str">2.11 String</a>
  251. ##### Rule 2.11.1 When saving a string, ensure that it has '\0' at the end.
  252. #### <a name="ast">2.12 Assert</a>
  253. ##### Rule 2.12.1 Assert cannot be used to verify errors that may occur when the program is running. To handle possible running errors, use error processing code.
  254. #### <a name="cls">2.13 Class and Object</a>
  255. ##### Rule 2.13.1 When a single object is released, delete is used. When an array object is released, delete [] is used.
  256. ```cpp
  257. const int kSize = 5;
  258. int *number_array = new int[kSize];
  259. int *number = new int();
  260. ...
  261. delete[] number_array;
  262. number_array = nullptr;
  263. delete number;
  264. number = nullptr;
  265. ```
  266. ##### Rule 2.13.2 Do not use std::move to operate the const object.
  267. ##### Rule 2.13.3 Strictly use virtual/override/final to modify virtual functions.
  268. ```cpp
  269. class Base {
  270. public:
  271. virtual void Func();
  272. };
  273. class Derived : public Base {
  274. public:
  275. void Func() override;
  276. };
  277. class FinalDerived : public Derived {
  278. public:
  279. void Func() final;
  280. };
  281. ```
  282. #### <a name="fdes">2.14 Function Design</a>
  283. ##### Rule 2.14.1 Use the RAII feature to help track dynamic allocation.
  284. ```cpp
  285. // Correct
  286. {
  287. std::lock_guard<std::mutex> lock(mutex_);
  288. ...
  289. }
  290. ```
  291. ##### Rule 2.14.2 Avoid capturing by reference in lambdas that will not be used locally.
  292. ```cpp
  293. {
  294. int local_var = 1;
  295. auto func = [&]() { ...; std::cout << local_var << std::endl; };
  296. thread_pool.commit(func);
  297. }
  298. ```
  299. ##### Rule 2.14.3 Do not use default parameter values for virtual functions.
  300. ##### Recommendation 2.14.4 Use strongly typed parameters or member variables. Do not use void*.
  301. #### <a name="fuse">2.15 Function Usage</a>
  302. ##### Rule 2.15.1 The input parameter must be transferred before the output parameter.
  303. ```cpp
  304. bool Func(const std::string &in, FooBar *out1, FooBar *out2);
  305. ```
  306. ##### Rule 2.15.2 Use `const T &` as the input parameter and `T *` as the output parameter for function transfer.
  307. ```cpp
  308. bool Func(const std::string &in, FooBar *out1, FooBar *out2);
  309. ```
  310. ##### Rule 2.15.3 In the scenario where ownership is not involved, use T * or const T & instead of the smart pointer as the transfer parameter.
  311. ```cpp
  312. // Correct
  313. bool Func(const FooBar &in);
  314. // Incorrect
  315. bool Func(std::shared_ptr<FooBar> in);
  316. ```
  317. ##### Rule 2.15.4 To transfer the ownership, you are advised to use shared_ptr + move to transfer parameters.
  318. ```cpp
  319. class Foo {
  320. public:
  321. explicit Foo(shared_ptr<T> x):x_(std::move(x)){}
  322. private:
  323. shared_ptr<T> x_;
  324. };
  325. ```
  326. ##### Rule 2.15.5 Use explicit to modify single-parameter constructors and do not use explicit to modify multi-parameter constructors.
  327. ```cpp
  328. explicit Foo(int x); //good :white_check_mark:
  329. explicit Foo(int x, int y=0); //good :white_check_mark:
  330. Foo(int x, int y=0); //bad :x:
  331. explicit Foo(int x, int y); //bad :x:
  332. ```
  333. ##### Rule 2.15.6 Copy constructors and copy assignment operators should be implemented or hidden together.
  334. ```cpp
  335. class Foo {
  336. private:
  337. Foo(const Foo&) = default;
  338. Foo& operator=(const Foo&) = default;
  339. Foo(Foo&&) = delete;
  340. Foo& operator=(Foo&&) = delete;
  341. };
  342. ```
  343. ##### Rule 2.15.7 [Question] Do not save or delete pointer parameters.
  344. ##### Rule 2.15.8 [Question] Do not use insecure functions as listed.
  345. ##### Rule 2.15.9 [Question] Do not use insecure exit functions as listed.
  346. ```cpp
  347. {
  348. Kill(...); // If you invoke kill to forcibly terminate other processes (such as kill -9), the resources of other processes cannot be cleared.
  349. TerminateProcess(); // If you call the erminateProcess function to forcibly terminate other processes, the resources of other processes cannot be cleared.
  350. pthread_exit(); // Do not terminate a thread. The thread functions will exit automatically and safely after the execution is complete.
  351. ExitThread(); // Do not terminate a thread. The thread functions will exit automatically and safely after the execution is complete.
  352. exit(); // Do not call any function except the main function. The program must exit safely.
  353. ExitProcess(); // Do not call any function except the main function. The program must exit safely.
  354. abort(); //Forbidden. If abort is used, the program exits immediately and resources cannot be cleared.
  355. }
  356. ```
  357. ##### Rule 2.15.10 Do not use the rand function to generate pseudo-random numbers for security purposes.
  358. The rand() function in the C standard library generates pseudo-random numbers. To generate random numbers, use /dev/random.
  359. ##### Rule 2.15.11 Do not use the string class to store sensitive information.
  360. The string class is a character string management class defined in C++. If sensitive information such as passwords is operated through the string class, the sensitive information can be
  361. scattered in various places of the memory and cannot be cleared.
  362. In the following code, the Foo function obtains the password, saves it to the string variable password, and then transfers it to the VerifyPassword function. In this process,
  363. two copies of the password exist in the memory.
  364. ```cpp
  365. int VerifyPassword(string password) {
  366. //...
  367. }
  368. int Foo() {
  369. string password = GetPassword();
  370. VerifyPassword(password);
  371. ...
  372. }
  373. ```
  374. Sensitive information must be stored using char or unsigned char. For example:
  375. ```cpp
  376. int VerifyPassword(const char *password) {
  377. //...
  378. }
  379. int Foo() {
  380. char password[MAX_PASSWORD] = {0};
  381. GetPassword(password, sizeof(password));
  382. VerifyPassword(password);
  383. ...
  384. }
  385. ```
  386. ##### Rule 2.15.12 Clear sensitive information in the memory immediately after use.
  387. Sensitive information, such as passwords and keys, must be cleared immediately after being used to prevent attackers from obtaining the information.
  388. #### <a name="mem">2.16 Memory</a>
  389. ##### Rule 2.16.1 Check whether memory allocation is successful.
  390. If the memory allocation fails, the subsequent operations may have undefined behavior risks. For example, if malloc fails to be applied for and a null pointer is returned, dereference of the null pointer is an undefined behavior.
  391. ##### Rule 2.16.2 Do not reference uninitialized memory.
  392. The memory allocated by malloc and new is not initialized to 0. Ensure that the memory is initialized before being referenced.
  393. ##### Rule 2.16.3 Do not use the realloc() function.
  394. The behavior of the realloc function varies with parameters. This is not a well-designed function. Although it provides some convenience in coding, it can easily cause various bugs.
  395. ##### Rule 2.16.4 Do not use the alloca() function to apply for stack memory.
  396. Neither POSIX nor C99 defines the alloca() behavior. Some platforms do not support this function. Using alloca() reduces program compatibility and portability. This function requests memory in the stack frame. The requested size may exceed the stack boundary, affecting code execution.
  397. #### <a name="file">2.17 File</a>
  398. ##### Rule 2.17.1 File paths must be canonicalized before use.
  399. A file path that comes from external data must be canonicalized first. If the file path is not canonicalized, attackers can construct a malicious file path to access the file without authorization.
  400. For example, an attacker can construct “../../../etc/passwd” to access any file.
  401. Use the realpath() function in Linux and the PathCanonicalize() function in Windows for file path canonicalization.
  402. [Noncompliant Code Example]
  403. The following code obtains the file name from an external system, concatenates the file name into a file path, and directly reads the file content. As a result, the attacker can read the content of any file.
  404. ```cpp
  405. char *fileName = GetMsgFromRemote();
  406. ...
  407. sprintf_s(untrustPath, sizeof(untrustPath), "/tmp/%s", fileName);
  408. char *text = ReadFileContent(untrustPath); // Bad: Did not check whether the untrustPath can be accessed before the data is read.
  409. ```
  410. [Compliant Code Example]
  411. Canonicalize the file path and then check whether the path is valid in the program.
  412. ```cpp
  413. char *fileName = GetMsgFromRemote();
  414. ...
  415. sprintf_s(untrustPath, sizeof(untrustPath), "/tmp/%s", fileName);
  416. char path[PATH_MAX] = {0};
  417. if (realpath(untrustPath, path) == NULL) {
  418. //error
  419. ...
  420. }
  421. if (!IsValidPath(path)) { // Good: Check whether the file location is correct.
  422. //error
  423. ...
  424. }
  425. char *text = ReadFileContent(untrustPath);
  426. ```
  427. Exceptions:
  428. Command line programs that run on the console, or file paths that are manually entered on the console are exempted from this rule.
  429. ##### Rule 2.17.2 Do not create temporary files in the shared directory.
  430. Temporary files of a program must be exclusively used by itself. Otherwise, other users of the shared directory may obtain additional information about the program, resulting in information leakage. Therefore, do not create temporary files that should be used only by the program itself in any shared directory.
  431. For example, the /tmp directory in Linux is a shared directory that all users can access. Do not create temporary files that should be used only by the program itself in this directory.
  432. #### <a name="sf">2.18 Secure Function</a>
  433. <table>
  434. <thead>
  435. <tr>
  436. <th style="width: 100px; ">Secure Function Type</th>
  437. <th style="width: 150px; ">Description</th>
  438. <th>Remarks</th>
  439. </tr>
  440. </thead>
  441. <tr>
  442. <td rowspan="1">xxx_s</td>
  443. <td>Secure function API of Huawei Secure C library</td>
  444. <td> It can be used when the Huawei Secure C library is integrated.</td>
  445. </tr>
  446. <tr>
  447. <td rowspan="1">xxx_sp</td>
  448. <td> API of Huawei Secure C library with optimized secure function performance (macro implementation)</td>
  449. <td>
  450. If count, destMax, and strSrc are constants, the performance-optimized macro interface displays its effect. If they are variables, the performance optimization effect is not obvious. The macro interface usage policy is as follows: The _s interface is used by default. The _sp interface is restricted in performance-sensitive call sites. The restriction scenarios are as follows:
  451. a) memset_sp and memcpy_sp: destMax and count are constants.
  452. b) strcpy_sp or strcat_sp: destMax is a constant and strSrc is a literal.
  453. c) strncpy_sp or strncat_sp: destMax and count are constants and strSrc is a literal.</td>
  454. </tr>
  455. </table>
  456. ##### Rule 2.15.18 Use secure functions provided by the community in the secure function library. Do not use dangerous functions related to memory operations.
  457. <table>
  458. <thead>
  459. <tr>
  460. <th style="width: 100px; ">Function Type</th>
  461. <th style="width: 150px; ">Dangerous Function</th>
  462. <th>Secure Surrogate Function</th>
  463. </tr>
  464. </thead>
  465. <tr>
  466. <td rowspan="4">Memory copy</td>
  467. <td>memcpy or bcopy</td>
  468. <td>memcpy_s</td>
  469. </tr>
  470. <tr>
  471. <td>wmemcpy</td>
  472. <td>wmemcpy_s</td>
  473. </tr>
  474. <tr>
  475. <td>memmove</td>
  476. <td>memmove_s</td>
  477. </tr>
  478. <tr>
  479. <td>wmemmove</td>
  480. <td>wmemmove_s</td>
  481. </tr>
  482. <tr>
  483. <td rowspan="4">String copy</td>
  484. <td>strcpy</td>
  485. <td>strcpy_s</td>
  486. </tr>
  487. <tr>
  488. <td>wcscpy</td>
  489. <td>wcscpy_s</td>
  490. </tr>
  491. <tr>
  492. <td>strncpy</td>
  493. <td>strncpy_s</td>
  494. </tr>
  495. <tr>
  496. <td>wcsncpy</td>
  497. <td>wcsncpy_s</td>
  498. </tr>
  499. <tr>
  500. <td rowspan="4">Character string concatenation</td>
  501. <td>strcat</td>
  502. <td>strcat_s</td>
  503. </tr>
  504. <tr>
  505. <td>wcscat</td>
  506. <td>wcscat_s</td>
  507. </tr>
  508. <tr>
  509. <td>strncat</td>
  510. <td>strncat_s</td>
  511. </tr>
  512. <tr>
  513. <td>wcsncat</td>
  514. <td>wcsncat_s</td>
  515. </tr>
  516. <tr>
  517. <td rowspan="6">Format output</td>
  518. <td>sprintf</td>
  519. <td>sprintf_s</td>
  520. </tr>
  521. <tr>
  522. <td>swprintf</td>
  523. <td>swprintf_s</td>
  524. </tr>
  525. <tr>
  526. <td>vsprintf</td>
  527. <td>vsprintf_s</td>
  528. </tr>
  529. <tr>
  530. <td>vswprintf</td>
  531. <td>vswprintf_s</td>
  532. </tr>
  533. <tr>
  534. <td>snprintf</td>
  535. <td>snprintf_s or snprintf_truncated_s</td>
  536. </tr>
  537. <tr>
  538. <td>vsnprintf</td>
  539. <td>vsnprintf_s or vsnprintf_truncated_s</td>
  540. </tr>
  541. <tr>
  542. <td rowspan="12">Format input</td>
  543. <td>scanf</td>
  544. <td>scanf_s</td>
  545. </tr>
  546. <tr>
  547. <td>wscanf</td>
  548. <td>wscanf_s</td>
  549. </tr>
  550. <tr>
  551. <td>vscanf</td>
  552. <td>vscanf_s</td>
  553. </tr>
  554. <tr>
  555. <td>vwscanf</td>
  556. <td>vwscanf_s</td>
  557. </tr>
  558. <tr>
  559. <td>fscanf</td>
  560. <td>fscanf_s</td>
  561. </tr>
  562. <tr>
  563. <td>fwscanf</td>
  564. <td>fwscanf_s</td>
  565. </tr>
  566. <tr>
  567. <td>vfscanf</td>
  568. <td>vfscanf_s</td>
  569. </tr>
  570. <tr>
  571. <td>vfwscanf</td>
  572. <td>vfwscanf_s</td>
  573. </tr>
  574. <tr>
  575. <td>sscanf</td>
  576. <td>sscanf_s</td>
  577. </tr>
  578. <tr>
  579. <td>swscanf</td>
  580. <td>swscanf_s</td>
  581. </tr>
  582. <tr>
  583. <td>vsscanf</td>
  584. <td>vsscanf_s</td>
  585. </tr>
  586. <tr>
  587. <td>vswscanf</td>
  588. <td>vswscanf_s</td>
  589. </tr>
  590. <tr>
  591. <td rowspan="1">Standard input stream input</td>
  592. <td>gets</td>
  593. <td>gets_s</td>
  594. </tr>
  595. <tr>
  596. <td rowspan="1">Memory initialization</td>
  597. <td>memset</td>
  598. <td>memset_s</td>
  599. </tr>
  600. </table>
  601. ##### Rule 2.18.2 Correctly set the destMax parameter in secure functions.
  602. ##### Rule 2.18.3 Do not encapsulate secure functions.
  603. ##### Rule 2.18.4 Do not rename secure functions using macros.
  604. ```cpp
  605. #define XXX_memcpy_s memcpy_s
  606. #define SEC_MEM_CPY memcpy_s
  607. #define XX_memset_s(dst, dstMax, val, n) memset_s((dst), (dstMax), (val), (n))
  608. ```
  609. ##### Rule 2.18.5 Do not customize secure functions.
  610. Using macros to rename secure functions does not help static code scanning tools (non-compiled) customize rules for the misuse of secure functions. In addition, there are various naming styles.
  611. In addition, it is not conducive to reminding the code developer of the real usage of functions, and may easily cause misunderstanding of the code and misuse of the renamed secure functions. Renaming secure functions will not
  612. affect the checking capability of the secure functions.
  613. ```cpp
  614. void MemcpySafe(void *dest, unsigned int destMax, const void *src, unsigned int count) {
  615. ...
  616. }
  617. ```
  618. ##### Rule 2.18.6 Check the return values of secure functions and correctly process them.
  619. In principle, if a secure function is used, its return value must be checked. If the return value is ! = EOK, this function should be returned immediately,
  620. and cannot be continued.
  621. A secure function may have multiple erroneous return values. If a secure function returns a failure, perform the following operations (one or more) based on specific product scenario before it is returned
  622. :
  623. (1) Record logs.
  624. (2) Return an error.
  625. (3) Call abort to exit the program immediately.
  626. ```cpp
  627. {
  628. ...
  629. err = memcpy_s(destBuff, destMax, src, srcLen);
  630. if (err != EOK) {
  631. MS_LOG("memcpy_s failed, err = %d\n", err);
  632. return FALSE;
  633. }
  634. ...
  635. }
  636. ```
  637. ##### Rule 2.18.7 Do not use external controllable data as function parameters for starting processes, such as system, popen, WinExec, ShellExecute, execl, xeclp, execle, execv, execvp and CreateProcess.
  638. ##### Rule 2.18.8 Do not use external controllable data as parameters for module loading functions such as dlopen/LoadLibrary.
  639. ##### Rule 2.18.9 Do not call non-asynchronous secure functions in signal processing routines.
  640. Signal processing routines should be as simple as possible. If a non-asynchronous secure function is called in a signal processing routine, the execution of the function may not generate expected results.
  641. The signal handler in the following code writes logs by calling fprintf(), but the function is not asynchronous secure function.
  642. ```cpp
  643. void Handler(int sigNum) {
  644. ...
  645. fprintf(stderr, "%s\n", info);
  646. }
  647. ```
  648. ------------------------------------------