当前位置:网站首页>Defensive C language programming in embedded development
Defensive C language programming in embedded development
2022-07-06 09:43:00 【Dafang teacher embedded】
Defensive in embedded development C Language programming
\\\ Insert a : There are surprises at the end of the article ~///
The reliability of embedded products is inseparable from hardware , But in terms of hardware 、 And without third-party testing , Code written using defensive programming ideas , It tends to be more stable .
Defensive programming first needs to recognize C All kinds of lack traps and traps of language ,C The language is very weak for runtime checking , Programmers need to carefully consider the code , Add judgment when necessary ; Another core idea of defensive programming is to assume that code runs on unreliable hardware , External interference may disrupt the order of program execution 、 change RAM Store data and so on .
1. Functions with formal parameters , It is necessary to judge whether the passed arguments are legal
The programmer may unconsciously pass the wrong parameters ; Strong external interference may modify the parameters transferred , Or call the function unexpectedly with random parameters , So before executing the body of the function , You need to first determine whether the arguments are legal .
2. Double check the return value of the function
The error code returned to the function , We should deal with it comprehensively and carefully , Make mistakes when necessary .
3. Prevent pointers from crossing
If you dynamically calculate an address , Make sure that the calculated address is reasonable and points to a meaningful place . Especially for pointers to the interior of a construct or array , When the pointer increases or changes, it still points to the same construct or array .
4. Prevent arrays from crossing bounds
The problem of array out of bounds has been discussed a lot , because C No efficient detection of arrays , Therefore, it is necessary to explicitly detect array out of bounds in applications . The following example can be used to interrupt and take over communication data .
When using some library functions , It is also necessary to check the boundary , If the following memset(RecBuf,0,len) Function RecBuf Refers to the front of the memory area pointed to len Byte usage 0 fill , If you don't pay attention len The length of , The array will be RecBuf The memory area outside is cleared :
5. Mathematical arithmetic
5.1 Division operations , Is it reliable to detect only divisor zero ?
Before division , It is almost a consensus to check whether the divisor is zero , But is it enough to just check that the divisor is zero ?
Consider dividing two integers , For one signed long Type variable , It can be expressed in the range of :-2147483648 ~+2147483647, If you let -2147483648/ -1, So the result should be +2147483648, But the result has gone beyond signedlong What can be expressed . therefore , under these circumstances , In addition to detecting whether the divisor is zero , Also check if division overflows .
#include
signed long sl1,sl2,result;
/* initialization sl1 and sl2*/
if((sl2==0)||(sl1==LONG_MIN && sl2==-1))
{
// Handling errors
}
else
{
result = sl1 / sl2;
}
5.2 Detect operation overflow
The addition, subtraction and multiplication of integers may overflow , When discussing undefined behavior , Given a signed integer addition overflow judgment code , Here is another code segment for judging the overflow of unsigned integer addition :
#include
unsigned int a,b,result;
/* initialization a,b*/
if(UINT_MAX-a<>
{
// Handling overflow
}
else
{
result=a+b;
}
Embedded hardware generally has no floating point processor , Floating point operation is also rare in embedded system, and overflow judgment relies heavily on C Library support , This is not about .
5.3 Detect displacement
When discussing undefined behavior , When it comes to signed numbers moving right 、 The number of shifts that are negative or greater than the number of operands is undefined behavior , It is also mentioned that there is no bit operation on signed numbers , But to detect whether the number of shifts is greater than the number of operands . Here is a code snippet of unsigned integer left shift detection :
unsigned int ui1;
unsigned int ui2;
unsigned int uresult;
/* initialization ui1,ui2*/
if(ui2>=sizeof(unsigned int)*CHAR_BIT)
{
// Handling errors
}
else
{
uresult=ui1<<>
}
6. If there is a hardware watchdog , Then use it
When everything else fails , The watchdog may be the last line of defense . Its principle is particularly simple , But it can greatly improve the reliability of the equipment . If the device has a hardware watchdog , Be sure to write a driver for it .
? Open the watchdog as early as possible
This is due to the time from the completion of power on reset to the opening of the watchdog , It is possible for the device to be disturbed and skip the watchdog initialization procedure , Cause the watchdog to fail . Open the watchdog as early as possible , Can reduce this probability ;
? Don't feed the dog in interruption , Unless there's another linkage
Feed the dog in the interrupt program , Because of the interference , The program may have been interrupted all the time , This will cause the watchdog to fail . If the flag bit is set in the main program , Interrupt the program when feeding the dog with this flag joint judgment , It's also allowed ;
? The feeding interval is related to the product demand , Not a specific length of time
The characteristics of the product determine the feeding interval . For safety not affected 、 Real time devices , The feeding interval is relatively loose , But the interval should not be too long , Otherwise, it will be perceived by users , It affects the user experience . For design safety 、 There are real-time control devices , The principle is to reset as quickly as possible , Otherwise it will cause an accident .
Clementine was on the second phase of her mission , Originally scheduled to fly from the moon to deep space Geographos Asteroid exploration , However, when the space probe flew to an asteroid, it was out of operation due to a lack of software 20 minute , Not only failed to reach the asteroid , Also due to the control nozzle burning 11 Minutes reduce the power supply , There is no way to control the detector through the remote end , Finally finish this task , But it also leads to a waste of resources and funds .
“ The failure of Clementine's space mission shocked me , In fact, it can avoid this accident through a simple watchdog timer in the hardware , However, due to the tight development time at that time , Programmers don't have time to write programs to start it ,”Ganssle say .
Unfortunately ,1998 The near earth spacecraft launched in (NEAR) The same thing happened . Because the programmers didn't take the advice , therefore , When the propeller reducer system fails ,29 Kilogram of reserve fuel will be reimbursed ── This is also a problem that could have been avoided by programming the watchdog timer , It also proves that it is not easy to learn from the mistakes of other programmers .
7. Key data stores multiple backups , Take data using “ Voting ”
RAM The data in may be changed under interference , The key data of the system should be cherished . Key data includes global variables 、 Static variables and data areas to cherish . The backup data should not be adjacent to the original data , Therefore, the backup data location should not be assigned by default by the compiler , It's up to the programmer to specify the storage area .
To be able to RAM It is divided into 3 Regions , The first area holds the original code , The second area holds the inverse code , The third area holds the XOR code , A certain amount of “ blank ”RAM As isolation . Capable of using compilers “ Distributed loading ” The mechanism stores variables separately in these areas . When reading is necessary , Simultaneous reading 3 And vote on it , Take at least two of the same values .
Assume that the equipment RAM from 0x1000_0000 initial , I need to be in RAM Of 0x1000_0000~0x10007FFF Store the original code in memory , stay 0x1000_9000~0x10009FFF Memory inverse code , stay 0x1000_B000~0x1000BFFF Memory 0xAA XOR code of , The decentralized loading of the compiler can be set to :
LR_IROM1 0x00000000 0x00080000 { ; load region size_region
ER_IROM1 0x00000000 0x00080000 { ; load address = execution address
*.o (RESET, +First)
*(InRoot$$Sections)
.ANY (+RO)
}
RW_IRAM1 0x10000000 0x00008000 { ; Save the original code
.ANY (+RW +ZI )
}
RW_IRAM3 0x10009000 0x00001000{ ; Save the inverse code
.ANY (MY_BK1)
}
RW_IRAM2 0x1000B000 0x00001000 { ; Save XOR code
.ANY (MY_BK2)
}
}
If a key variable needs multiple backups , You can define variables in the following way , Assign three variables to three uninterrupted RAM In the area , And define according to the original code 、 Inverse code 、0xAA The XOR code of .
uint32 plc_pc=0; // Original code
__attribute__((section("MY_BK1"))) uint32 plc_pc_not=~0x0; // Inverse code
__attribute__((section("MY_BK2"))) uint32 plc_pc_xor=0x0^0xAAAAAAAA; // XOR code
When you need to write this variable , All three locations need to be updated ; When reading variables , Read three values to judge , Take at least two of the same values .
Why choose XOR code instead of complement code ? This is because MDK The integer of is stored according to the complement , The complement of a positive number matches the original code
Write an article
keil Under the STM32 Program development deployment ( One )
Shi Qiang
https://github.com/freeeyes
? Pay attention to him
3 Many people agree with the article
Buy a piece STM32 The advanced edition of is very important , although STM32 Your old capital is insufficient 5 element , But the corresponding interface GPIO Output to different hardware connections , If you do it all by yourself, it's still a relatively large project , And of limited significance .
First download keil compiler , This and STM The cooperation is better .
Recommendation keil5, After downloading , Install it. STM Driver package .
It's best here STM All chip drivers of are installed , Because they are not big ,STM There are many small models , If common 103XX wait .
All the packets here , Install and keep the latest .
And then configure it keil Environmental Science .
Here are a few places to pay attention to .
First , Set up DEBUG Parameters of .
Here we have to choose ST-LInk, This is a small piece of hardware . Can and STM Learning board connection . You can go to Jingdong to search , There are , One thing to note here , for the first time ST-LInk Access board , Please update here ST-Link The driver , Buy in detail ST-LInk There is usually a small CD-ROM , Or directly ask the corresponding manufacturer for , because ST-LInk The old driver of keil5 Compatibility problem , After upgrading, you can .
One more thing, please pay attention to the following DEBUG To configure
Here you need to specify after connection , direct reset The board , Let the program take effect , such , When you burn the program , You can see the result soon .
in addition , It is recommended that beginners , Find one. keil To rewrite .
Because the file organization directory is learned .
If , The simplest .
The directory structure here . It's best to be consistent with your actual file directory structure .
All drivers are placed in one directory , The system files are placed in a directory .
Put your main program in a directory . The organization is relatively clear .
keil All the main entrances of are main, and C Code is consistent .
Then there is how to make the program run .
Here is the compiler
You can compile your code here .
Here's a tip . If your code is complex , You can use F12 Find your function definition and implementation .
The result of compilation , You can see in the output below
The last step , It's all right to wait for the translation .
Burn the program into STM Just use the board .
The above is the most fundamental keil5 and stm Board debugging method .
Back , I will slowly add some useful applet code and instructions .
How to use serial port to give STM32 Download program
Colored eggs : Recently, a classmate asked me for information about SCM , I deliberately spent a few months , Sum up my 10 Years of product development experience , The data package almost covers C Language 、 Single chip microcomputer 、 Analog digital electricity 、 Schematic and PCB Design 、 MCU advanced programming and so on , Very suitable for beginners and advanced . in addition to , Then share with tears what I pressed at the bottom of the box 22 A hot open source project , Include source code + Schematic diagram +PCB+ documentation , It is not the kind of course that is sold in the market , I don't think more tutorials are necessarily a good thing ,10 Years ago, I taught myself fast , In addition to its own execution , There are few tutorials . Don't be shy to be a party , Wait for a little red dot . In the later stage, I will also set up some small circles for pure technical exchange , Let everyone know more big guys , Have a good circle , Your understanding of the industry must be at the forefront .
边栏推荐
- 018. Valid palindromes
- 机械工程师和电气工程师方向哪个前景比较好?
- What is an R-value reference and what is the difference between it and an l-value?
- Global and Chinese market of electronic tubes 2022-2028: Research Report on technology, participants, trends, market size and share
- MySQL数据库优化的几种方式(笔面试必问)
- Lua script of redis
- MapReduce instance (VIII): Map end join
- DCDC power ripple test
- Take you back to spark ecosystem!
- 068. Find the insertion position -- binary search
猜你喜欢
随机推荐
小白带你重游Spark生态圈!
[Yu Yue education] Wuhan University of science and technology securities investment reference
Kratos ares microservice framework (II)
tn-c为何不可用2p断路器?
May brush question 26 - concurrent search
Global and Chinese market of cup masks 2022-2028: Research Report on technology, participants, trends, market size and share
Master slave replication of redis
运维,放过监控-也放过自己吧
Segmentation sémantique de l'apprentissage profond - résumé du code source
Kratos ares microservice framework (III)
Minio distributed file storage cluster for full stack development
Kratos ares microservice framework (I)
[Yu Yue education] reference materials of complex variable function and integral transformation of Shenyang University of Technology
五月刷题01——数组
Popularization of security knowledge - twelve moves to protect mobile phones from network attacks
《ASP.NET Core 6框架揭秘》样章发布[200页/5章]
手把手教您怎么编写第一个单片机程序
[deep learning] semantic segmentation: thesis reading (neurips 2021) maskformer: per pixel classification is not all you need
CAP理论
硬件工程师的真实前途我说出来可能你们不信