SlideShare a Scribd company logo
1 of 44
Static analysis and writing
C/C++ of high quality code for
embedded systems
Phillip Khandeliants, PVS-Studio
Speaker
2
• Phillip Khandeliants, 1994
• C++/C# developer in the PVS-Studio team
• 3 years of taking part in developing the
C++ analyzer core
• Authour of articles on checking
open source projects
Projected growth rate of IoT
3
15.41
17.68
20.35
23.14
26.66
30.73
35.82
42.62
51.11
62.12
75.44
2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025
Source: https://www.statista.com/statistics/471264/iot-number-of-connected-devices-worldwide/
And projects keep growing…
• RT-Thread 1.2.0: 1 810 000 lines of code
• RT-Thread 4.0.0 - 5.5 times larger: 9 903 000 lines
of code
• Linux kernel 1.0.0 : 177 000 lines of code
• Linux kernel 5.1-rc2 - 118 times larger:
20 896 000 lines of code
4
What is an error capable of?
5
What is an error capable of?
6
Fascinating bug
7
• A colleague made 4 robots
• They were controlled by a remote console
• They were playing football and
«catch the mice»
• One of the robots went crazy due to a
programming error
8
9
Source: https://www.nist.gov/sites/default/files/documents/director/planning/report02-3.pdf
Code review
• Helps to find errors of high level and not to
shoot off your legs waist-high
• Allows to share experience with padawans
• Together you’ll learn a lot of new secret
things about the project
10
But...
• Code review is to expensive:
– Expectation: «It’ll take us 10-15 mins
to review the edit»
– Reality – we stay long for hours
• You get tired too quickly from code viewing
11
Why code review doesn’t always work
12
static int EatWhitespace(FILE * InFile)
{
int c;
for (c = getc(InFile); isspace(c) && ('n' != c);
c = getc(InFile));
return (c);
}
Why code review doesn’t always work
13
#ifdef isspace
#undef isspace
#endif
....
#define isspace(c) ((c)==' ' || (c) == 't')
....
for (c = getc(InFile); ((c)==' ' || (c) == 't') && ('n' != c);
c = getc(InFile));
V560 A part of conditional expression is always true: ('n' != c). params.c 136.
Dynamic code analysis
• Debuggers
• Profilers
• Sanitizers (AddressSanitizer, ThreadSanitizer, ...)
• Found a bug? Let's run for fixing it!
14
But again...
• It’s not always simple to test and debug
embedded code
• Sanitizers and profilers are slow
• You’ll often need some special test
dataset
15
Static analysis for the rescue
• Automated code review by a machine
• A machine doesn’t get tired 
• You can find the most exciting error
patterns 
16
Where has the error crept?
17
static void SHA1Final(unsigned char digest[20],
SHA1_CTX *context)
{
u32 i;
unsigned char finalcount[8];
....
memset(context->count, 0, 8);
memset(finalcount, 0, 8);
}
Here it is!
18
CWE-14 V597 The compiler could delete the 'memset' function call, which is used to flush
'finalcount' buffer. The memset_s() function should be used to erase the private data.
wifi_generate_pin.c 185
static void SHA1Final(unsigned char digest[20],
SHA1_CTX *context)
{
u32 i;
unsigned char finalcount[8];
....
memset(context->count, 0, 8);
memset(finalcount, 0, 8);
}
Static Application Security Testing (SAST)
Programming
error
Real
vulnerability
19
• «Programming errors are boring to catch!»
• «You’d better catch vulnerabilities!»
• NIST: 64% of vulnerabilities are
programming errors
• Let’s start «intimidating» managers and
team leads with potential vulnerabilities
Potential
vulnerability
Two kinds of SAST
• Search for known vulnerabilities in code
• Preventive measures from potential vulnerabilities
20
• CWE™ is a community-developed list of common software security
weaknesses.
• Set of weaknesses/potential vulnerabilities, which can become real
vulnerabilities(CVE). One just needs to describe how to exploit them .
• Website: https://cwe.mitre.org
• CWE List Version 3.1 contains 716 potential vulnerabilities.
21
Common Weakness Enumeration (CWE)
Examples of potential vulnerabilities
according to CWE
• CWE-20: Improper Input Validation
• CWE-369: Divide By Zero
• CWE-457: Use of Uninitialized Variable
• CWE-467: Use of sizeof() on a Pointer Type
• CWE-562: Return of Stack Variable Address
22
CWE-20: Improper Input Validation
23
if (c < 0)
{
if (fgets(command_buf,
sizeof(command_buf) - 1,
stdin) != command_buf)
{
break;
}
command_buf[strlen(command_buf) - 1] = '0'; /* remove endline */
break;
}
CWE-20: Improper Input Validation
24
if (c < 0)
{
if (fgets(command_buf,
sizeof(command_buf) - 1,
stdin) != command_buf)
{
break;
}
command_buf[strlen(command_buf) - 1] = '0'; /* remove endline */
break;
}
'0'
0
-1
CWE-20 V1010 Unchecked tainted data is used in index: 'strlen(command_buf)'.
CWE-562: Return of Stack Variable Address
25
void SEMC_GetDefaultConfig(semc_config_t *config)
{
assert(config);
semc_axi_queueweight_t queueWeight; /*!< AXI queue weight. */
semc_queuea_weight_t queueaWeight;
semc_queueb_weight_t queuebWeight;
....
config->queueWeight.queueaWeight = &queueaWeight;
config->queueWeight.queuebWeight = &queuebWeight;
}
CWE-562: Return of Stack Variable Address
26
void SEMC_GetDefaultConfig(semc_config_t *config)
{
assert(config);
semc_axi_queueweight_t queueWeight; /*!< AXI queue weight. */
semc_queuea_weight_t queueaWeight;
semc_queueb_weight_t queuebWeight;
....
config->queueWeight.queueaWeight = &queueaWeight;
config->queueWeight.queuebWeight = &queuebWeight;
}
CWE-562 V506 Pointer to local variable 'queuebWeight' is stored outside the scope of
this variable. Such a pointer will become invalid. fsl_semc.c 257
Common Vulnerabilities and Exposures
(CVE)
• CVE — real vulnerabilities, there are confirmed
scenarios of their exploitation
• Main website: https://cve.mitre.org/
• Total CVE Entries: 114 282
27
CVE-2012-2122
28
typedef char my_bool;
my_bool check_scramble(const char *scramble_arg,
const char *message,
const uint8 *hash_stage2)
{
....
return memcmp(hash_stage2, hash_stage2_reassured, SHA1_HASH_SIZE);
}
V642 Saving the 'memcmp' function result inside the 'char' type variable is inappropriate.
The significant bits could be lost breaking the program's logic. password.c
CVE-2012-2122
29
typedef char my_bool;
my_bool check_scramble(const char *scramble_arg,
const char *message,
const uint8 *hash_stage2)
{
....
return memcmp(hash_stage2, hash_stage2_reassured, SHA1_HASH_SIZE);
}
V642 Saving the 'memcmp' function result inside the 'char' type variable is inappropriate.
The significant bits could be lost breaking the program's logic. password.c
CVE-2014-1266
30
static OSStatus SSLVerifySignedServerKeyExchange(....)
{
OSStatus err;
....
if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0)
goto fail;
if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
goto fail;
goto fail;
if ((err = SSLHashSHA1.final(&hashCtx, &hashOut)) != 0)
goto fail;
....
fail:
....;
}
CVE-2014-1266
31
static OSStatus SSLVerifySignedServerKeyExchange(....)
{
OSStatus err;
....
if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0)
goto fail;
if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
goto fail;
goto fail;
if ((err = SSLHashSHA1.final(&hashCtx, &hashOut)) != 0)
goto fail;
....
fail:
....;
}
• V640 The code's operational logic does not correspond with its formatting. The statement is indented
to the right, but it is always executed. It is possible that curly brackets are missing.
• V779 Unreachable code detected. It is possible that an error is present
A path from an «ordinary» error
to a vulnerability
32
SEI CERT coding standard
• Developed by CERT (CERT Coordination
Center, CERT/CC)
• Meant for C, C++, Java, Perl languages
• Is quite similar to CWE
33
Examples of rules from SEI CERT
• MSC06-C: Beware of compiler optimizations
• INT33-C: Ensure that division and remainder operations do
not result in divide-by-zero errors
• EXP33-C, EXP53-CPP: Do not read uninitialized memory
• ARR01-C: Do not apply the sizeof operator to a pointer when
taking the size of an array
• DCL30-C: Declare objects with appropriate storage durations
34
EXP34-C. Do not dereference null pointers, C/C++
35
EOLIAN void _evas_canvas_key_lock_add(
...., Evas_Public_Data *e, ....)
{
....
e->locks.lock.list = realloc(e->locks.lock.list,
e->locks.lock.count * sizeof(char *));
e->locks.lock.list[e->locks.lock.count - 1] = strdup(keyname);
eina_hash_free_buckets(e->locks.masks);
}
EXP34-C. Do not dereference null pointers, C/C++
36
EXP34-C V701 realloc() possible leak: when realloc() fails in allocating memory, original pointer
'e->locks.lock.list' is lost. Consider assigning realloc() to a temporary pointer. evas_key.c 142
EOLIAN void _evas_canvas_key_lock_add(
...., Evas_Public_Data *e, ....)
{
....
e->locks.lock.list = realloc(e->locks.lock.list,
e->locks.lock.count * sizeof(char *));
e->locks.lock.list[e->locks.lock.count - 1] = strdup(keyname);
eina_hash_free_buckets(e->locks.masks);
}
MISRA С/С++ coding standards
• You’ll have to pay for it
• MISRA C 2012 contains 143 rules, MISRA C++
2008 — 228 rules
• MISRA reduces the likelihood that an error
will get into the code base
37
Examples of MISRA-rules
• Don’t use octal constants
• Don’t use goto
• A function has to have single exit point
• Don’t use standard library functions
(atof/…/abort/exit/getenv/system/…)
• Don’t use dynamic allocations
• Don’t use unions
• Each case has to end with break or throw
38
Story about Toyota not following the MISRA standard
39
• NHTSA: in 2000-2010 89 people died and 57
– sustained injuries in accidents
• NHTSA and NASA carried out investigations
• 7134 violations have been detected
• Toyota: «You’re all wrong!»
• ….
• Toyota pays off 16 billions dollars in the pre-
trial order
How to use MISRA and static analysis incorrectly
40
How to do it right?
41
• In a perfect world you run it on a developer’s
machine
• The error doesn’t get into the version control
system
• The developer won’t be afraid of
embarrassment
• Additional defence line – night runs on a CI-
server
But 100500 warnings are still here!
42
• You just need to supress all of them after the
first run!
• Only the newly written code is analysed
• Gradually fix old warnings
Shall I use static analysis instead of other
methodologies?
• Static analysis is not a silver bullet
• Static analysis is the answer to the question:
"How to make our code better?"
• What does mean " better "? It will be easier to
maintain and develop it, eliminate problems in it
43
Q&A
44
Check your project using PVS-Studio for programming
errors and potential vulnerabilities!
C, C++, C#, Java
www.viva64.com

More Related Content

What's hot

Sonar Tool - JAVA code analysis
Sonar Tool - JAVA code analysisSonar Tool - JAVA code analysis
Sonar Tool - JAVA code analysisPrashant Gupta
 
Verification Automation Using IPXACT
Verification Automation Using IPXACTVerification Automation Using IPXACT
Verification Automation Using IPXACTDVClub
 
CNIT 126: 10: Kernel Debugging with WinDbg
CNIT 126: 10: Kernel Debugging with WinDbgCNIT 126: 10: Kernel Debugging with WinDbg
CNIT 126: 10: Kernel Debugging with WinDbgSam Bowne
 
Code Review Tool Evaluation
Code Review Tool EvaluationCode Review Tool Evaluation
Code Review Tool EvaluationKate Semizhon
 
Continuous Testing Landscape.pptx
Continuous Testing Landscape.pptxContinuous Testing Landscape.pptx
Continuous Testing Landscape.pptxMarc Hornbeek
 
MISRA C in an ISO 26262 context
MISRA C in an ISO 26262 contextMISRA C in an ISO 26262 context
MISRA C in an ISO 26262 contextAdaCore
 
DES-lecture (1).ppt
DES-lecture (1).pptDES-lecture (1).ppt
DES-lecture (1).pptMrsPrabhaBV
 
UVM Ral model usage
UVM Ral model usageUVM Ral model usage
UVM Ral model usageParth Pandya
 
Code Review for Teams Too Busy to Review Code - Atlassian Summit 2010
Code Review for Teams Too Busy to Review Code - Atlassian Summit 2010Code Review for Teams Too Busy to Review Code - Atlassian Summit 2010
Code Review for Teams Too Busy to Review Code - Atlassian Summit 2010Atlassian
 
Cisco Addresses the Full Attack Continuum
Cisco Addresses the Full Attack ContinuumCisco Addresses the Full Attack Continuum
Cisco Addresses the Full Attack ContinuumCisco Security
 

What's hot (20)

Code Review
Code ReviewCode Review
Code Review
 
Code coverage
Code coverageCode coverage
Code coverage
 
Sonar
SonarSonar
Sonar
 
Sonar Tool - JAVA code analysis
Sonar Tool - JAVA code analysisSonar Tool - JAVA code analysis
Sonar Tool - JAVA code analysis
 
Verification Automation Using IPXACT
Verification Automation Using IPXACTVerification Automation Using IPXACT
Verification Automation Using IPXACT
 
IP Sec - Basic Concepts
IP Sec - Basic ConceptsIP Sec - Basic Concepts
IP Sec - Basic Concepts
 
CNIT 126: 10: Kernel Debugging with WinDbg
CNIT 126: 10: Kernel Debugging with WinDbgCNIT 126: 10: Kernel Debugging with WinDbg
CNIT 126: 10: Kernel Debugging with WinDbg
 
Code Review Tool Evaluation
Code Review Tool EvaluationCode Review Tool Evaluation
Code Review Tool Evaluation
 
Continuous Testing Landscape.pptx
Continuous Testing Landscape.pptxContinuous Testing Landscape.pptx
Continuous Testing Landscape.pptx
 
Classical Encryption Techniques
Classical Encryption TechniquesClassical Encryption Techniques
Classical Encryption Techniques
 
Sonar Review
Sonar ReviewSonar Review
Sonar Review
 
MISRA C in an ISO 26262 context
MISRA C in an ISO 26262 contextMISRA C in an ISO 26262 context
MISRA C in an ISO 26262 context
 
DES-lecture (1).ppt
DES-lecture (1).pptDES-lecture (1).ppt
DES-lecture (1).ppt
 
UVM Ral model usage
UVM Ral model usageUVM Ral model usage
UVM Ral model usage
 
Code Review for Teams Too Busy to Review Code - Atlassian Summit 2010
Code Review for Teams Too Busy to Review Code - Atlassian Summit 2010Code Review for Teams Too Busy to Review Code - Atlassian Summit 2010
Code Review for Teams Too Busy to Review Code - Atlassian Summit 2010
 
Cisco Addresses the Full Attack Continuum
Cisco Addresses the Full Attack ContinuumCisco Addresses the Full Attack Continuum
Cisco Addresses the Full Attack Continuum
 
SonarQube.pptx
SonarQube.pptxSonarQube.pptx
SonarQube.pptx
 
Code review
Code reviewCode review
Code review
 
Sonar qube
Sonar qubeSonar qube
Sonar qube
 
SonarQube Presentation.pptx
SonarQube Presentation.pptxSonarQube Presentation.pptx
SonarQube Presentation.pptx
 

Similar to Static analysis of embedded C/C++ code

PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017Andrey Karpov
 
200 Open Source Projects Later: Source Code Static Analysis Experience
200 Open Source Projects Later: Source Code Static Analysis Experience200 Open Source Projects Later: Source Code Static Analysis Experience
200 Open Source Projects Later: Source Code Static Analysis ExperienceAndrey Karpov
 
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ..."Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...PVS-Studio
 
The CppCat Analyzer Checks TortoiseGit
The CppCat Analyzer Checks TortoiseGitThe CppCat Analyzer Checks TortoiseGit
The CppCat Analyzer Checks TortoiseGitAndrey Karpov
 
Search for Vulnerabilities Using Static Code Analysis
Search for Vulnerabilities Using Static Code AnalysisSearch for Vulnerabilities Using Static Code Analysis
Search for Vulnerabilities Using Static Code AnalysisAndrey Karpov
 
Static analysis as means of improving code quality
Static analysis as means of improving code quality Static analysis as means of improving code quality
Static analysis as means of improving code quality Andrey Karpov
 
Rechecking TortoiseSVN with the PVS-Studio Code Analyzer
Rechecking TortoiseSVN with the PVS-Studio Code AnalyzerRechecking TortoiseSVN with the PVS-Studio Code Analyzer
Rechecking TortoiseSVN with the PVS-Studio Code AnalyzerAndrey Karpov
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerAndrey Karpov
 
PVS-Studio Meets Octave
PVS-Studio Meets Octave PVS-Studio Meets Octave
PVS-Studio Meets Octave PVS-Studio
 
SAST and Application Security: how to fight vulnerabilities in the code
SAST and Application Security: how to fight vulnerabilities in the codeSAST and Application Security: how to fight vulnerabilities in the code
SAST and Application Security: how to fight vulnerabilities in the codeAndrey Karpov
 
Writing Metasploit Plugins
Writing Metasploit PluginsWriting Metasploit Plugins
Writing Metasploit Pluginsamiable_indian
 
Static analysis: looking for errors ... and vulnerabilities?
Static analysis: looking for errors ... and vulnerabilities? Static analysis: looking for errors ... and vulnerabilities?
Static analysis: looking for errors ... and vulnerabilities? Andrey Karpov
 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects 100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects Andrey Karpov
 
Anomalies in X-Ray Engine
Anomalies in X-Ray EngineAnomalies in X-Ray Engine
Anomalies in X-Ray EnginePVS-Studio
 
What static analyzers can do that programmers and testers cannot
What static analyzers can do that programmers and testers cannotWhat static analyzers can do that programmers and testers cannot
What static analyzers can do that programmers and testers cannotAndrey Karpov
 
Detection of errors and potential vulnerabilities in C and C++ code using the...
Detection of errors and potential vulnerabilities in C and C++ code using the...Detection of errors and potential vulnerabilities in C and C++ code using the...
Detection of errors and potential vulnerabilities in C and C++ code using the...Andrey Karpov
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2PVS-Studio
 
Checking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xChecking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xAndrey Karpov
 
Mathematicians: Trust, but Verify
Mathematicians: Trust, but VerifyMathematicians: Trust, but Verify
Mathematicians: Trust, but VerifyAndrey Karpov
 

Similar to Static analysis of embedded C/C++ code (20)

PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
 
Price of an Error
Price of an ErrorPrice of an Error
Price of an Error
 
200 Open Source Projects Later: Source Code Static Analysis Experience
200 Open Source Projects Later: Source Code Static Analysis Experience200 Open Source Projects Later: Source Code Static Analysis Experience
200 Open Source Projects Later: Source Code Static Analysis Experience
 
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ..."Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
 
The CppCat Analyzer Checks TortoiseGit
The CppCat Analyzer Checks TortoiseGitThe CppCat Analyzer Checks TortoiseGit
The CppCat Analyzer Checks TortoiseGit
 
Search for Vulnerabilities Using Static Code Analysis
Search for Vulnerabilities Using Static Code AnalysisSearch for Vulnerabilities Using Static Code Analysis
Search for Vulnerabilities Using Static Code Analysis
 
Static analysis as means of improving code quality
Static analysis as means of improving code quality Static analysis as means of improving code quality
Static analysis as means of improving code quality
 
Rechecking TortoiseSVN with the PVS-Studio Code Analyzer
Rechecking TortoiseSVN with the PVS-Studio Code AnalyzerRechecking TortoiseSVN with the PVS-Studio Code Analyzer
Rechecking TortoiseSVN with the PVS-Studio Code Analyzer
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzer
 
PVS-Studio Meets Octave
PVS-Studio Meets Octave PVS-Studio Meets Octave
PVS-Studio Meets Octave
 
SAST and Application Security: how to fight vulnerabilities in the code
SAST and Application Security: how to fight vulnerabilities in the codeSAST and Application Security: how to fight vulnerabilities in the code
SAST and Application Security: how to fight vulnerabilities in the code
 
Writing Metasploit Plugins
Writing Metasploit PluginsWriting Metasploit Plugins
Writing Metasploit Plugins
 
Static analysis: looking for errors ... and vulnerabilities?
Static analysis: looking for errors ... and vulnerabilities? Static analysis: looking for errors ... and vulnerabilities?
Static analysis: looking for errors ... and vulnerabilities?
 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects 100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects
 
Anomalies in X-Ray Engine
Anomalies in X-Ray EngineAnomalies in X-Ray Engine
Anomalies in X-Ray Engine
 
What static analyzers can do that programmers and testers cannot
What static analyzers can do that programmers and testers cannotWhat static analyzers can do that programmers and testers cannot
What static analyzers can do that programmers and testers cannot
 
Detection of errors and potential vulnerabilities in C and C++ code using the...
Detection of errors and potential vulnerabilities in C and C++ code using the...Detection of errors and potential vulnerabilities in C and C++ code using the...
Detection of errors and potential vulnerabilities in C and C++ code using the...
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
 
Checking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xChecking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-x
 
Mathematicians: Trust, but Verify
Mathematicians: Trust, but VerifyMathematicians: Trust, but Verify
Mathematicians: Trust, but Verify
 

More from Andrey Karpov

60 антипаттернов для С++ программиста
60 антипаттернов для С++ программиста60 антипаттернов для С++ программиста
60 антипаттернов для С++ программистаAndrey Karpov
 
60 terrible tips for a C++ developer
60 terrible tips for a C++ developer60 terrible tips for a C++ developer
60 terrible tips for a C++ developerAndrey Karpov
 
Ошибки, которые сложно заметить на code review, но которые находятся статичес...
Ошибки, которые сложно заметить на code review, но которые находятся статичес...Ошибки, которые сложно заметить на code review, но которые находятся статичес...
Ошибки, которые сложно заметить на code review, но которые находятся статичес...Andrey Karpov
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesAndrey Karpov
 
PVS-Studio in 2021 - Feature Overview
PVS-Studio in 2021 - Feature OverviewPVS-Studio in 2021 - Feature Overview
PVS-Studio in 2021 - Feature OverviewAndrey Karpov
 
PVS-Studio в 2021 - Примеры ошибок
PVS-Studio в 2021 - Примеры ошибокPVS-Studio в 2021 - Примеры ошибок
PVS-Studio в 2021 - Примеры ошибокAndrey Karpov
 
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...Andrey Karpov
 
Best Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesBest Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesAndrey Karpov
 
Does static analysis need machine learning?
Does static analysis need machine learning?Does static analysis need machine learning?
Does static analysis need machine learning?Andrey Karpov
 
Typical errors in code on the example of C++, C#, and Java
Typical errors in code on the example of C++, C#, and JavaTypical errors in code on the example of C++, C#, and Java
Typical errors in code on the example of C++, C#, and JavaAndrey Karpov
 
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)Andrey Karpov
 
Game Engine Code Quality: Is Everything Really That Bad?
Game Engine Code Quality: Is Everything Really That Bad?Game Engine Code Quality: Is Everything Really That Bad?
Game Engine Code Quality: Is Everything Really That Bad?Andrey Karpov
 
C++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerC++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerAndrey Karpov
 
The Use of Static Code Analysis When Teaching or Developing Open-Source Software
The Use of Static Code Analysis When Teaching or Developing Open-Source SoftwareThe Use of Static Code Analysis When Teaching or Developing Open-Source Software
The Use of Static Code Analysis When Teaching or Developing Open-Source SoftwareAndrey Karpov
 
Static Code Analysis for Projects, Built on Unreal Engine
Static Code Analysis for Projects, Built on Unreal EngineStatic Code Analysis for Projects, Built on Unreal Engine
Static Code Analysis for Projects, Built on Unreal EngineAndrey Karpov
 
Safety on the Max: How to Write Reliable C/C++ Code for Embedded Systems
Safety on the Max: How to Write Reliable C/C++ Code for Embedded SystemsSafety on the Max: How to Write Reliable C/C++ Code for Embedded Systems
Safety on the Max: How to Write Reliable C/C++ Code for Embedded SystemsAndrey Karpov
 
The Great and Mighty C++
The Great and Mighty C++The Great and Mighty C++
The Great and Mighty C++Andrey Karpov
 
Static code analysis: what? how? why?
Static code analysis: what? how? why?Static code analysis: what? how? why?
Static code analysis: what? how? why?Andrey Karpov
 
Zero, one, two, Freddy's coming for you
Zero, one, two, Freddy's coming for youZero, one, two, Freddy's coming for you
Zero, one, two, Freddy's coming for youAndrey Karpov
 

More from Andrey Karpov (20)

60 антипаттернов для С++ программиста
60 антипаттернов для С++ программиста60 антипаттернов для С++ программиста
60 антипаттернов для С++ программиста
 
60 terrible tips for a C++ developer
60 terrible tips for a C++ developer60 terrible tips for a C++ developer
60 terrible tips for a C++ developer
 
Ошибки, которые сложно заметить на code review, но которые находятся статичес...
Ошибки, которые сложно заметить на code review, но которые находятся статичес...Ошибки, которые сложно заметить на code review, но которые находятся статичес...
Ошибки, которые сложно заметить на code review, но которые находятся статичес...
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error Examples
 
PVS-Studio in 2021 - Feature Overview
PVS-Studio in 2021 - Feature OverviewPVS-Studio in 2021 - Feature Overview
PVS-Studio in 2021 - Feature Overview
 
PVS-Studio в 2021 - Примеры ошибок
PVS-Studio в 2021 - Примеры ошибокPVS-Studio в 2021 - Примеры ошибок
PVS-Studio в 2021 - Примеры ошибок
 
PVS-Studio в 2021
PVS-Studio в 2021PVS-Studio в 2021
PVS-Studio в 2021
 
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...
 
Best Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesBest Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' Mistakes
 
Does static analysis need machine learning?
Does static analysis need machine learning?Does static analysis need machine learning?
Does static analysis need machine learning?
 
Typical errors in code on the example of C++, C#, and Java
Typical errors in code on the example of C++, C#, and JavaTypical errors in code on the example of C++, C#, and Java
Typical errors in code on the example of C++, C#, and Java
 
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)
 
Game Engine Code Quality: Is Everything Really That Bad?
Game Engine Code Quality: Is Everything Really That Bad?Game Engine Code Quality: Is Everything Really That Bad?
Game Engine Code Quality: Is Everything Really That Bad?
 
C++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerC++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical Reviewer
 
The Use of Static Code Analysis When Teaching or Developing Open-Source Software
The Use of Static Code Analysis When Teaching or Developing Open-Source SoftwareThe Use of Static Code Analysis When Teaching or Developing Open-Source Software
The Use of Static Code Analysis When Teaching or Developing Open-Source Software
 
Static Code Analysis for Projects, Built on Unreal Engine
Static Code Analysis for Projects, Built on Unreal EngineStatic Code Analysis for Projects, Built on Unreal Engine
Static Code Analysis for Projects, Built on Unreal Engine
 
Safety on the Max: How to Write Reliable C/C++ Code for Embedded Systems
Safety on the Max: How to Write Reliable C/C++ Code for Embedded SystemsSafety on the Max: How to Write Reliable C/C++ Code for Embedded Systems
Safety on the Max: How to Write Reliable C/C++ Code for Embedded Systems
 
The Great and Mighty C++
The Great and Mighty C++The Great and Mighty C++
The Great and Mighty C++
 
Static code analysis: what? how? why?
Static code analysis: what? how? why?Static code analysis: what? how? why?
Static code analysis: what? how? why?
 
Zero, one, two, Freddy's coming for you
Zero, one, two, Freddy's coming for youZero, one, two, Freddy's coming for you
Zero, one, two, Freddy's coming for you
 

Recently uploaded

DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 

Recently uploaded (20)

DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 

Static analysis of embedded C/C++ code

  • 1. Static analysis and writing C/C++ of high quality code for embedded systems Phillip Khandeliants, PVS-Studio
  • 2. Speaker 2 • Phillip Khandeliants, 1994 • C++/C# developer in the PVS-Studio team • 3 years of taking part in developing the C++ analyzer core • Authour of articles on checking open source projects
  • 3. Projected growth rate of IoT 3 15.41 17.68 20.35 23.14 26.66 30.73 35.82 42.62 51.11 62.12 75.44 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 Source: https://www.statista.com/statistics/471264/iot-number-of-connected-devices-worldwide/
  • 4. And projects keep growing… • RT-Thread 1.2.0: 1 810 000 lines of code • RT-Thread 4.0.0 - 5.5 times larger: 9 903 000 lines of code • Linux kernel 1.0.0 : 177 000 lines of code • Linux kernel 5.1-rc2 - 118 times larger: 20 896 000 lines of code 4
  • 5. What is an error capable of? 5
  • 6. What is an error capable of? 6
  • 7. Fascinating bug 7 • A colleague made 4 robots • They were controlled by a remote console • They were playing football and «catch the mice» • One of the robots went crazy due to a programming error
  • 8. 8
  • 10. Code review • Helps to find errors of high level and not to shoot off your legs waist-high • Allows to share experience with padawans • Together you’ll learn a lot of new secret things about the project 10
  • 11. But... • Code review is to expensive: – Expectation: «It’ll take us 10-15 mins to review the edit» – Reality – we stay long for hours • You get tired too quickly from code viewing 11
  • 12. Why code review doesn’t always work 12 static int EatWhitespace(FILE * InFile) { int c; for (c = getc(InFile); isspace(c) && ('n' != c); c = getc(InFile)); return (c); }
  • 13. Why code review doesn’t always work 13 #ifdef isspace #undef isspace #endif .... #define isspace(c) ((c)==' ' || (c) == 't') .... for (c = getc(InFile); ((c)==' ' || (c) == 't') && ('n' != c); c = getc(InFile)); V560 A part of conditional expression is always true: ('n' != c). params.c 136.
  • 14. Dynamic code analysis • Debuggers • Profilers • Sanitizers (AddressSanitizer, ThreadSanitizer, ...) • Found a bug? Let's run for fixing it! 14
  • 15. But again... • It’s not always simple to test and debug embedded code • Sanitizers and profilers are slow • You’ll often need some special test dataset 15
  • 16. Static analysis for the rescue • Automated code review by a machine • A machine doesn’t get tired  • You can find the most exciting error patterns  16
  • 17. Where has the error crept? 17 static void SHA1Final(unsigned char digest[20], SHA1_CTX *context) { u32 i; unsigned char finalcount[8]; .... memset(context->count, 0, 8); memset(finalcount, 0, 8); }
  • 18. Here it is! 18 CWE-14 V597 The compiler could delete the 'memset' function call, which is used to flush 'finalcount' buffer. The memset_s() function should be used to erase the private data. wifi_generate_pin.c 185 static void SHA1Final(unsigned char digest[20], SHA1_CTX *context) { u32 i; unsigned char finalcount[8]; .... memset(context->count, 0, 8); memset(finalcount, 0, 8); }
  • 19. Static Application Security Testing (SAST) Programming error Real vulnerability 19 • «Programming errors are boring to catch!» • «You’d better catch vulnerabilities!» • NIST: 64% of vulnerabilities are programming errors • Let’s start «intimidating» managers and team leads with potential vulnerabilities Potential vulnerability
  • 20. Two kinds of SAST • Search for known vulnerabilities in code • Preventive measures from potential vulnerabilities 20
  • 21. • CWE™ is a community-developed list of common software security weaknesses. • Set of weaknesses/potential vulnerabilities, which can become real vulnerabilities(CVE). One just needs to describe how to exploit them . • Website: https://cwe.mitre.org • CWE List Version 3.1 contains 716 potential vulnerabilities. 21 Common Weakness Enumeration (CWE)
  • 22. Examples of potential vulnerabilities according to CWE • CWE-20: Improper Input Validation • CWE-369: Divide By Zero • CWE-457: Use of Uninitialized Variable • CWE-467: Use of sizeof() on a Pointer Type • CWE-562: Return of Stack Variable Address 22
  • 23. CWE-20: Improper Input Validation 23 if (c < 0) { if (fgets(command_buf, sizeof(command_buf) - 1, stdin) != command_buf) { break; } command_buf[strlen(command_buf) - 1] = '0'; /* remove endline */ break; }
  • 24. CWE-20: Improper Input Validation 24 if (c < 0) { if (fgets(command_buf, sizeof(command_buf) - 1, stdin) != command_buf) { break; } command_buf[strlen(command_buf) - 1] = '0'; /* remove endline */ break; } '0' 0 -1 CWE-20 V1010 Unchecked tainted data is used in index: 'strlen(command_buf)'.
  • 25. CWE-562: Return of Stack Variable Address 25 void SEMC_GetDefaultConfig(semc_config_t *config) { assert(config); semc_axi_queueweight_t queueWeight; /*!< AXI queue weight. */ semc_queuea_weight_t queueaWeight; semc_queueb_weight_t queuebWeight; .... config->queueWeight.queueaWeight = &queueaWeight; config->queueWeight.queuebWeight = &queuebWeight; }
  • 26. CWE-562: Return of Stack Variable Address 26 void SEMC_GetDefaultConfig(semc_config_t *config) { assert(config); semc_axi_queueweight_t queueWeight; /*!< AXI queue weight. */ semc_queuea_weight_t queueaWeight; semc_queueb_weight_t queuebWeight; .... config->queueWeight.queueaWeight = &queueaWeight; config->queueWeight.queuebWeight = &queuebWeight; } CWE-562 V506 Pointer to local variable 'queuebWeight' is stored outside the scope of this variable. Such a pointer will become invalid. fsl_semc.c 257
  • 27. Common Vulnerabilities and Exposures (CVE) • CVE — real vulnerabilities, there are confirmed scenarios of their exploitation • Main website: https://cve.mitre.org/ • Total CVE Entries: 114 282 27
  • 28. CVE-2012-2122 28 typedef char my_bool; my_bool check_scramble(const char *scramble_arg, const char *message, const uint8 *hash_stage2) { .... return memcmp(hash_stage2, hash_stage2_reassured, SHA1_HASH_SIZE); } V642 Saving the 'memcmp' function result inside the 'char' type variable is inappropriate. The significant bits could be lost breaking the program's logic. password.c
  • 29. CVE-2012-2122 29 typedef char my_bool; my_bool check_scramble(const char *scramble_arg, const char *message, const uint8 *hash_stage2) { .... return memcmp(hash_stage2, hash_stage2_reassured, SHA1_HASH_SIZE); } V642 Saving the 'memcmp' function result inside the 'char' type variable is inappropriate. The significant bits could be lost breaking the program's logic. password.c
  • 30. CVE-2014-1266 30 static OSStatus SSLVerifySignedServerKeyExchange(....) { OSStatus err; .... if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0) goto fail; if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0) goto fail; goto fail; if ((err = SSLHashSHA1.final(&hashCtx, &hashOut)) != 0) goto fail; .... fail: ....; }
  • 31. CVE-2014-1266 31 static OSStatus SSLVerifySignedServerKeyExchange(....) { OSStatus err; .... if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0) goto fail; if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0) goto fail; goto fail; if ((err = SSLHashSHA1.final(&hashCtx, &hashOut)) != 0) goto fail; .... fail: ....; } • V640 The code's operational logic does not correspond with its formatting. The statement is indented to the right, but it is always executed. It is possible that curly brackets are missing. • V779 Unreachable code detected. It is possible that an error is present
  • 32. A path from an «ordinary» error to a vulnerability 32
  • 33. SEI CERT coding standard • Developed by CERT (CERT Coordination Center, CERT/CC) • Meant for C, C++, Java, Perl languages • Is quite similar to CWE 33
  • 34. Examples of rules from SEI CERT • MSC06-C: Beware of compiler optimizations • INT33-C: Ensure that division and remainder operations do not result in divide-by-zero errors • EXP33-C, EXP53-CPP: Do not read uninitialized memory • ARR01-C: Do not apply the sizeof operator to a pointer when taking the size of an array • DCL30-C: Declare objects with appropriate storage durations 34
  • 35. EXP34-C. Do not dereference null pointers, C/C++ 35 EOLIAN void _evas_canvas_key_lock_add( ...., Evas_Public_Data *e, ....) { .... e->locks.lock.list = realloc(e->locks.lock.list, e->locks.lock.count * sizeof(char *)); e->locks.lock.list[e->locks.lock.count - 1] = strdup(keyname); eina_hash_free_buckets(e->locks.masks); }
  • 36. EXP34-C. Do not dereference null pointers, C/C++ 36 EXP34-C V701 realloc() possible leak: when realloc() fails in allocating memory, original pointer 'e->locks.lock.list' is lost. Consider assigning realloc() to a temporary pointer. evas_key.c 142 EOLIAN void _evas_canvas_key_lock_add( ...., Evas_Public_Data *e, ....) { .... e->locks.lock.list = realloc(e->locks.lock.list, e->locks.lock.count * sizeof(char *)); e->locks.lock.list[e->locks.lock.count - 1] = strdup(keyname); eina_hash_free_buckets(e->locks.masks); }
  • 37. MISRA С/С++ coding standards • You’ll have to pay for it • MISRA C 2012 contains 143 rules, MISRA C++ 2008 — 228 rules • MISRA reduces the likelihood that an error will get into the code base 37
  • 38. Examples of MISRA-rules • Don’t use octal constants • Don’t use goto • A function has to have single exit point • Don’t use standard library functions (atof/…/abort/exit/getenv/system/…) • Don’t use dynamic allocations • Don’t use unions • Each case has to end with break or throw 38
  • 39. Story about Toyota not following the MISRA standard 39 • NHTSA: in 2000-2010 89 people died and 57 – sustained injuries in accidents • NHTSA and NASA carried out investigations • 7134 violations have been detected • Toyota: «You’re all wrong!» • …. • Toyota pays off 16 billions dollars in the pre- trial order
  • 40. How to use MISRA and static analysis incorrectly 40
  • 41. How to do it right? 41 • In a perfect world you run it on a developer’s machine • The error doesn’t get into the version control system • The developer won’t be afraid of embarrassment • Additional defence line – night runs on a CI- server
  • 42. But 100500 warnings are still here! 42 • You just need to supress all of them after the first run! • Only the newly written code is analysed • Gradually fix old warnings
  • 43. Shall I use static analysis instead of other methodologies? • Static analysis is not a silver bullet • Static analysis is the answer to the question: "How to make our code better?" • What does mean " better "? It will be easier to maintain and develop it, eliminate problems in it 43
  • 44. Q&A 44 Check your project using PVS-Studio for programming errors and potential vulnerabilities! C, C++, C#, Java www.viva64.com