SlideShare a Scribd company logo
Static analysis
as means of improving code quality
Sergey Vasiliev
PVS-Studio
vasiliev@viva64.com
Density of errors (per 1 KLOC)
0
20
40
60
80
100
< 2 2-16 16-64 64-512 > 512
Vulnerabilities ~ bugs
The National Institute of Standards
and Technology (NIST) reports that
64% of software vulnerabilities
stem from programming errors
and not a lack of security features.
Number of vulnerabilities
0
3000
6000
9000
12000
15000
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
Number of vulnerabilities
0
3000
6000
9000
12000
15000
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
Cost of fixing a security defect
0
1000
2000
3000
4000
5000
6000
7000
8000
Development Build QA Release Phase
Key points
• Error density increases non-linearly.
• Cost of fixing a problem increases with time.
• Vulnerabilities often are
simple programming errors.
Static analysis
Advantages:
• Early detection of problems.
• Full code coverage.
• Great at detecting various patterns of errors.
Disadvantages:
• False positives.
• Accurate level of error severity is unknown.
Terminology
• CWE (Common Weakness Enumeration) –
potential vulnerabilities that can become real.
• CVE (Common Vulnerabilities and Exposures) –
real vulnerabilities, discovered in applications.
Дублирующиеся подвыражения
PascalABC.Net
if (File.Exists(pdbFileName) &&
File.Exists(pdbFileName)) {
....
}
Duplicated subexpressions
PascalABC.Net
if (File.Exists(pdbFileName) &&
File.Exists(pdbFileName)) {
....
}
SonarC# warning: Identical sub-expressions on both sides of operator "&&".
Duplicated subexpressions
PascalABC.Net
if (File.Exists(pdbFileName) &&
File.Exists(pdbFileName)) {
....
}
SonarC# warning: Identical sub-expressions on both sides of operator "&&".
Ошибка? Уязвимость!
CVE-2014-1266
iOS
if ((err = SSLHashSHA1.update(
&hashCtx, &signedParams)) != 0)
goto fail;
goto fail;
PVS-Studio warnings:
• CWE-483 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.
• CWE-561 V779 Unreachable code detected. It is possible that an error is
present.
Error? Vulnerability!
CVE-2014-1266
iOS
if ((err = SSLHashSHA1.update(
&hashCtx, &signedParams)) != 0)
goto fail;
goto fail;
PVS-Studio warnings:
• CWE-483 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.
• CWE-561 V779 Unreachable code detected. It is possible that an error is
present.
Error? Vulnerability!
CVE-2014-1266
iOS
if ((err = SSLHashSHA1.update(
&hashCtx, &signedParams)) != 0)
goto fail;
goto fail;
PVS-Studio warnings:
• CWE-483 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.
• CWE-561 V779 Unreachable code detected. It is possible that an error is
present.
Неправильный вызов функции
Doom 3
void Sys_GetCurrentMemoryStatus(
sysMemoryStats_t &stats ) {
....
memset( &statex, sizeof( statex ), 0 );
....
}
CppCheck warning: memset() called to fill 0 bytes of '&'
Incorrect function call
Doom 3
void Sys_GetCurrentMemoryStatus(
sysMemoryStats_t &stats ) {
....
memset( &statex, sizeof( statex ), 0 );
....
}
CppCheck warning: memset() called to fill 0 bytes
Incorrect function call
Doom 3
void Sys_GetCurrentMemoryStatus(
sysMemoryStats_t &stats ) {
....
memset( &statex, sizeof( statex ), 0 );
....
}
CppCheck warning: memset() called to fill 0 bytes
Бессмысленная проверка
Jenkins
int cnt = 0;
for (R b = getLastBuild(); cnt<5 && b!=null;
b=b.getPreviousBuild()) {
FilePath ws = b.getWorkspace();
if (ws != null)
return b;
}
PVS-Studio warning: V6007 Expression 'cnt < 5' is always true.
Useless check
Jenkins
int cnt = 0;
for (R b = getLastBuild(); cnt<5 && b!=null;
b=b.getPreviousBuild()) {
FilePath ws = b.getWorkspace();
if (ws != null)
return b;
}
PVS-Studio warning: V6007 Expression 'cnt < 5' is always true.
Useless check
Jenkins
int cnt = 0;
for (R b = getLastBuild(); cnt<5 && b!=null;
b=b.getPreviousBuild()) {
FilePath ws = b.getWorkspace();
if (ws != null)
return b;
}
PVS-Studio warning: V6007 Expression 'cnt < 5' is always true.
Опасное разыменование указателя
Unreal Engine
bool FHeadMountedDisplay::IsInLowPersistenceMode() const
{
const auto frame = GetCurrentFrame();
const auto FrameSettings = frame->Settings;
return frame && FrameSettings->Flags.bLowPersistenceMode;
}
Klocwork warning: Suspicious dereference of pointer 'frame' before NULL check
Dangerous pointer dereference
Unreal Engine
bool FHeadMountedDisplay::IsInLowPersistenceMode() const
{
const auto frame = GetCurrentFrame();
const auto FrameSettings = frame->Settings;
return frame && FrameSettings->Flags.bLowPersistenceMode;
}
Klocwork warning: Suspicious dereference of pointer 'frame' before NULL check
Dangerous pointer dereference
Unreal Engine
bool FHeadMountedDisplay::IsInLowPersistenceMode() const
{
const auto frame = GetCurrentFrame();
const auto FrameSettings = frame->Settings;
return frame && FrameSettings->Flags.bLowPersistenceMode;
}
Klocwork warning: Suspicious dereference of pointer 'frame' before NULL check
Непроверенные входные данные
NcFTP
if (fgets(newname, sizeof(newname) - 1, stdin) == NULL)
newname[0] = '0';
newname[strlen(newname) - 1] = '0';
PVS-Studio warning: CWE-20 V1010 Unchecked tainted data is used in index:
'strlen(newname)'.
Unchecked input data
NcFTP
if (fgets(newname, sizeof(newname) - 1, stdin) == NULL)
newname[0] = '0';
newname[strlen(newname) - 1] = '0';
PVS-Studio warning: CWE-20 V1010 Unchecked tainted data is used in index:
'strlen(newname)'.
Unchecked input data
NcFTP
if (fgets(newname, sizeof(newname) - 1, stdin) == NULL)
newname[0] = '0';
newname[strlen(newname) - 1] = '0';
Unchecked input data
NcFTP
if (fgets(newname, sizeof(newname) - 1, stdin) == NULL)
newname[0] = '0';
newname[strlen(newname) - 1] = '0';
Unchecked input data
NcFTP
if (fgets(newname, sizeof(newname) - 1, stdin) == NULL)
newname[0] = '0';
newname[strlen(newname) - 1] = '0';
Unchecked input data
NcFTP
if (fgets(newname, sizeof(newname) - 1, stdin) == NULL)
newname[0] = '0';
newname[strlen(newname) - 1] = '0';
0???
-1
Reproducing the error
• Server connection.
• Downloading file from a server.
• Input of a string, starting with 'N'.
• Input '0'.
• ....
• PROFIT!
Reproducing the error
• ncftp.exe ftp://speedtest.tele2.net
• get 512KB.zip
• Now let's have some fun
• 0???
• ....
• PROFIT!
Static analysis as means of improving code quality
Myth:
static analysis is for newbies, professionals
don’t make mistakes
Myth:
static analysis is for newbies, professionals
don’t make mistakes
Single checks are ineffective
• ... but better than no checks at all.
• “Let’s check projects before the release!"
• Critical errors were fixed
for a higher price.
CVE-2015-8948
libidn
else if (fgets (
readbuf, BUFSIZ, stdin) == NULL) {
....
}
if (readbuf[strlen (readbuf) - 1] == 'n')
readbuf[strlen (readbuf) - 1] = '0';
PVS-Studio warning:
CWE-20 V1010 Unchecked tainted data is used in index: 'strlen(readbuf)'.
CVE-2016-6262
libidn
else if (getline (&line, &linelen, stdin) == -1) {
....
}
if (line[strlen (line) - 1] == 'n')
line[strlen (line) - 1] = '0';
PVS-Studio warning:
CWE-20 V1010 Unchecked tainted data is used in index: 'strlen(line)'.
CVE-2016-6262
libidn
else if (getline (&line, &linelen, stdin) == -1) {
....
}
if (strlen (line) > 0)
if (line[strlen (line) - 1] == 'n')
line[strlen (line) - 1] = '0';
CVE from libidn
CVE-2015-8948.
Commit, closing
this vulnerability: 10.08.2015
CVE-2016-6262.
Commit, closing
this vulnerability: 14.01.2016
Time difference – 5 months.
Use static analysis regularly.
Effective use
• Locally on developers’ computers.
• On a build server.
• Prompt fixing of errors.
• ...
• PROFIT!
Local use
• Cost of fixing an error is minimal.
• Developer is inside a context:
it’s easier to handle a warning.
• No one will find out about the problem
except you and the analyzer:)
Incremental analysis
• Analyzing only modified  newly written code.
• Reducing of analysis time.
• Great for early detection of errors.
Example from personal experience
• Analyzer developers also make mistakes :)
• Integration with Visual Studio +
incremental analysis.
Using on a build server
• Detecting errors, that got into a repository.
• Various scenarios of working with
analysis results:
• Distribution by mail;
• Generation of issues;
• Using in CI-systems;
• etc.
Example from personal experience
• Nightly analysis.
• Merging of logs,
filtration, conversion.
• Handling the analysis results:
• Mails distribution;
• Publication of results in Jenkins.
Analyze code on developer
machines and on a build server.
Deploying on a project
Deploying on a project
High Medium Low Total
1350 35943 45346 82639
Deploying on a project
• How did that even work?
• What should be fixed and
how can it be done?
• How to separate old warnings from
the new ones?
False positives
• Are triggered on correct code.
• Analysis logs are cluttered.
• Are inevitable.
"Redundant" analysis
• Third-party code is analyzed.
• Irrelevant project warnings
clutter the output.
Static analysis as means of improving code quality
Static analysis as means of improving code quality
Problems  solutions
Problem Solution
False positives Message suppression
Problems  solutions
Problem Solution
False positives Message suppression
"Explosion" after the first analysis "Freezing" of all warnings
Problems  solutions
Problem Solution
False positives Message suppression
"Explosion" after the first analysis "Freezing" of all warnings
Long analysis time Incremental analysis
Problems  solutions
Problem Solution
False positives Message suppression
"Explosion" after the first analysis "Freezing" of all warnings
Long analysis time Incremental analysis
Inconvenience of working with 'raw' logs Usage of auxiliary tools
Problems  solutions
Problem Solution
False positives Message suppression
"Explosion" after the first analysis "Freezing" of all warnings
Long analysis time Incremental analysis
Inconvenience of working with 'raw' logs Usage of auxiliary tools
Warnings on third-party code Excluding from the analysis
Problems  solutions
Problem Solution
False positives Message suppression
"Explosion" after the first analysis "Freezing" of all warnings
Long analysis time Incremental analysis
Inconvenience of working with 'raw' logs Usage of auxiliary tools
Warnings on third-party code Excluding from the analysis
Irrelevant diagnostics Disabling diagnostic rules
Investigate the tools that are
suggested
by developers of analyzer.
Deploying on a project
• "Freezing" of existing warnings.
• Configuring the analyzer.
• Don’t let new errors appear.
• Go back to old errors whenever spare
resources and time is available.
When deploying static analysis,
mark existing warnings as
irrelevant.
Recommended articles on the topic
"How the PVS-Studio Team
Improved Unreal Engine's Code"
https://bit.ly/2IKnnch
"Static Analysis as Part of the
Development Process in Unreal Engine"
https://bit.ly/2KL4ZAu
Reducing costs
0
1000
2000
3000
4000
5000
6000
7000
8000
Development Build QA Release Phase
Reducing costs
0
1000
2000
3000
4000
5000
6000
7000
8000
Development Build QA Release Phase
No Silver Bullet
• Static analysis is not a cure-all.
• Effectively complemented
by other tools.
Sergey Vasiliev
E-mail: vasiliev@viva64.com
PVS-Studio site: https://www.viva64.com

More Related Content

What's hot (20)

PDF
Integration testing with spring @JAX Mainz
Victor Rentea
 
PDF
Effective code reviews
Sebastian Marek
 
PDF
Bugs found in GCC with the help of PVS-Studio
PVS-Studio
 
PDF
How PVS-Studio does the bug search: methods and technologies
PVS-Studio
 
PPTX
We Make Debugging Sucks Less
Alon Fliess
 
PDF
Checking Clang 11 with PVS-Studio
Andrey Karpov
 
PDF
Test Dependencies and the Future of Build Acceleration
New York City College of Technology Computer Systems Technology Colloquium
 
PDF
A Long-Awaited Check of Unreal Engine 4
Andrey Karpov
 
PDF
Definitive Guide to Working With Exceptions in Java
Victor Rentea
 
PDF
Testing, Learning and Professionalism — 20171214
David Rodenas
 
PDF
TDD CrashCourse Part3: TDD Techniques
David Rodenas
 
PPTX
Introduction to aop
Dror Helper
 
PDF
Integration testing with spring @snow one
Victor Rentea
 
PDF
Unit-testing and E2E testing in JS
Michael Haberman
 
PDF
We continue checking Microsoft projects: analysis of PowerShell
PVS-Studio
 
PDF
Pragmatic Code Coverage
Alexandre (Shura) Iline
 
PDF
Presentations Unusual Java Bugs And Detecting Them Using Foss Tools
Ganesh Samarthyam
 
PDF
Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...
Victor Rentea
 
PDF
Unit Testing like a Pro - The Circle of Purity
Victor Rentea
 
PDF
Unit Testing - The Whys, Whens and Hows
atesgoral
 
Integration testing with spring @JAX Mainz
Victor Rentea
 
Effective code reviews
Sebastian Marek
 
Bugs found in GCC with the help of PVS-Studio
PVS-Studio
 
How PVS-Studio does the bug search: methods and technologies
PVS-Studio
 
We Make Debugging Sucks Less
Alon Fliess
 
Checking Clang 11 with PVS-Studio
Andrey Karpov
 
Test Dependencies and the Future of Build Acceleration
New York City College of Technology Computer Systems Technology Colloquium
 
A Long-Awaited Check of Unreal Engine 4
Andrey Karpov
 
Definitive Guide to Working With Exceptions in Java
Victor Rentea
 
Testing, Learning and Professionalism — 20171214
David Rodenas
 
TDD CrashCourse Part3: TDD Techniques
David Rodenas
 
Introduction to aop
Dror Helper
 
Integration testing with spring @snow one
Victor Rentea
 
Unit-testing and E2E testing in JS
Michael Haberman
 
We continue checking Microsoft projects: analysis of PowerShell
PVS-Studio
 
Pragmatic Code Coverage
Alexandre (Shura) Iline
 
Presentations Unusual Java Bugs And Detecting Them Using Foss Tools
Ganesh Samarthyam
 
Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...
Victor Rentea
 
Unit Testing like a Pro - The Circle of Purity
Victor Rentea
 
Unit Testing - The Whys, Whens and Hows
atesgoral
 

Similar to Static analysis as means of improving code quality (20)

PPTX
Search for Vulnerabilities Using Static Code Analysis
Andrey Karpov
 
PPTX
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
Andrey Karpov
 
PPTX
Static analysis and writing C/C++ of high quality code for embedded systems
Andrey Karpov
 
PPTX
Static Code Analysis: Keeping the Cost of Bug Fixing Down
Andrey Karpov
 
PDF
Rechecking TortoiseSVN with the PVS-Studio Code Analyzer
Andrey Karpov
 
PPTX
PVS-Studio is ready to improve the code of Tizen operating system
Andrey Karpov
 
PPTX
Static analysis: looking for errors ... and vulnerabilities?
Andrey Karpov
 
PDF
PVS-Studio Meets Octave
PVS-Studio
 
PPTX
SAST, CWE, SEI CERT and other smart words from the information security world
Andrey Karpov
 
PPTX
The operation principles of PVS-Studio static code analyzer
Andrey Karpov
 
PDF
FITC - Here Be Dragons: Advanced JavaScript Debugging
Rami Sayar
 
PDF
Here Be Dragons – Advanced JavaScript Debugging
FITC
 
PPTX
SAST and Application Security: how to fight vulnerabilities in the code
Andrey Karpov
 
PDF
The Little Unicorn That Could
PVS-Studio
 
PPTX
Price of an Error
Andrey Karpov
 
PPTX
Static-Analysis-in-Industry.pptx
ShivashankarHR1
 
PDF
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
PVS-Studio
 
PPTX
Game Engine Code Quality: Is Everything Really That Bad?
Andrey Karpov
 
PDF
Re-checking the ReactOS project - a large report
PVS-Studio
 
Search for Vulnerabilities Using Static Code Analysis
Andrey Karpov
 
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
Andrey Karpov
 
Static analysis and writing C/C++ of high quality code for embedded systems
Andrey Karpov
 
Static Code Analysis: Keeping the Cost of Bug Fixing Down
Andrey Karpov
 
Rechecking TortoiseSVN with the PVS-Studio Code Analyzer
Andrey Karpov
 
PVS-Studio is ready to improve the code of Tizen operating system
Andrey Karpov
 
Static analysis: looking for errors ... and vulnerabilities?
Andrey Karpov
 
PVS-Studio Meets Octave
PVS-Studio
 
SAST, CWE, SEI CERT and other smart words from the information security world
Andrey Karpov
 
The operation principles of PVS-Studio static code analyzer
Andrey Karpov
 
FITC - Here Be Dragons: Advanced JavaScript Debugging
Rami Sayar
 
Here Be Dragons – Advanced JavaScript Debugging
FITC
 
SAST and Application Security: how to fight vulnerabilities in the code
Andrey Karpov
 
The Little Unicorn That Could
PVS-Studio
 
Price of an Error
Andrey Karpov
 
Static-Analysis-in-Industry.pptx
ShivashankarHR1
 
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
PVS-Studio
 
Game Engine Code Quality: Is Everything Really That Bad?
Andrey Karpov
 
Re-checking the ReactOS project - a large report
PVS-Studio
 
Ad

More from Andrey Karpov (20)

PDF
60 антипаттернов для С++ программиста
Andrey Karpov
 
PDF
60 terrible tips for a C++ developer
Andrey Karpov
 
PPTX
Ошибки, которые сложно заметить на code review, но которые находятся статичес...
Andrey Karpov
 
PDF
PVS-Studio in 2021 - Error Examples
Andrey Karpov
 
PDF
PVS-Studio in 2021 - Feature Overview
Andrey Karpov
 
PDF
PVS-Studio в 2021 - Примеры ошибок
Andrey Karpov
 
PDF
PVS-Studio в 2021
Andrey Karpov
 
PPTX
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...
Andrey Karpov
 
PPTX
Best Bugs from Games: Fellow Programmers' Mistakes
Andrey Karpov
 
PPTX
Does static analysis need machine learning?
Andrey Karpov
 
PPTX
Typical errors in code on the example of C++, C#, and Java
Andrey Karpov
 
PPTX
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)
Andrey Karpov
 
PPTX
C++ Code as Seen by a Hypercritical Reviewer
Andrey Karpov
 
PPTX
The Use of Static Code Analysis When Teaching or Developing Open-Source Software
Andrey Karpov
 
PPTX
Static Code Analysis for Projects, Built on Unreal Engine
Andrey Karpov
 
PPTX
The Great and Mighty C++
Andrey Karpov
 
PPTX
Static code analysis: what? how? why?
Andrey Karpov
 
PDF
Zero, one, two, Freddy's coming for you
Andrey Karpov
 
PDF
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
Andrey Karpov
 
PDF
PVS-Studio Static Analyzer as a Tool for Protection against Zero-Day Vulnerab...
Andrey Karpov
 
60 антипаттернов для С++ программиста
Andrey Karpov
 
60 terrible tips for a C++ developer
Andrey Karpov
 
Ошибки, которые сложно заметить на code review, но которые находятся статичес...
Andrey Karpov
 
PVS-Studio in 2021 - Error Examples
Andrey Karpov
 
PVS-Studio in 2021 - Feature Overview
Andrey Karpov
 
PVS-Studio в 2021 - Примеры ошибок
Andrey Karpov
 
PVS-Studio в 2021
Andrey Karpov
 
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...
Andrey Karpov
 
Best Bugs from Games: Fellow Programmers' Mistakes
Andrey Karpov
 
Does static analysis need machine learning?
Andrey Karpov
 
Typical errors in code on the example of C++, C#, and Java
Andrey Karpov
 
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)
Andrey Karpov
 
C++ Code as Seen by a Hypercritical Reviewer
Andrey Karpov
 
The Use of Static Code Analysis When Teaching or Developing Open-Source Software
Andrey Karpov
 
Static Code Analysis for Projects, Built on Unreal Engine
Andrey Karpov
 
The Great and Mighty C++
Andrey Karpov
 
Static code analysis: what? how? why?
Andrey Karpov
 
Zero, one, two, Freddy's coming for you
Andrey Karpov
 
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
Andrey Karpov
 
PVS-Studio Static Analyzer as a Tool for Protection against Zero-Day Vulnerab...
Andrey Karpov
 
Ad

Recently uploaded (20)

PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PPTX
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PPTX
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 

Static analysis as means of improving code quality

  • 1. Static analysis as means of improving code quality Sergey Vasiliev PVS-Studio [email protected]
  • 2. Density of errors (per 1 KLOC) 0 20 40 60 80 100 < 2 2-16 16-64 64-512 > 512
  • 3. Vulnerabilities ~ bugs The National Institute of Standards and Technology (NIST) reports that 64% of software vulnerabilities stem from programming errors and not a lack of security features.
  • 4. Number of vulnerabilities 0 3000 6000 9000 12000 15000 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
  • 5. Number of vulnerabilities 0 3000 6000 9000 12000 15000 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
  • 6. Cost of fixing a security defect 0 1000 2000 3000 4000 5000 6000 7000 8000 Development Build QA Release Phase
  • 7. Key points • Error density increases non-linearly. • Cost of fixing a problem increases with time. • Vulnerabilities often are simple programming errors.
  • 8. Static analysis Advantages: • Early detection of problems. • Full code coverage. • Great at detecting various patterns of errors. Disadvantages: • False positives. • Accurate level of error severity is unknown.
  • 9. Terminology • CWE (Common Weakness Enumeration) – potential vulnerabilities that can become real. • CVE (Common Vulnerabilities and Exposures) – real vulnerabilities, discovered in applications.
  • 11. Duplicated subexpressions PascalABC.Net if (File.Exists(pdbFileName) && File.Exists(pdbFileName)) { .... } SonarC# warning: Identical sub-expressions on both sides of operator "&&".
  • 12. Duplicated subexpressions PascalABC.Net if (File.Exists(pdbFileName) && File.Exists(pdbFileName)) { .... } SonarC# warning: Identical sub-expressions on both sides of operator "&&".
  • 13. Ошибка? Уязвимость! CVE-2014-1266 iOS if ((err = SSLHashSHA1.update( &hashCtx, &signedParams)) != 0) goto fail; goto fail; PVS-Studio warnings: • CWE-483 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. • CWE-561 V779 Unreachable code detected. It is possible that an error is present.
  • 14. Error? Vulnerability! CVE-2014-1266 iOS if ((err = SSLHashSHA1.update( &hashCtx, &signedParams)) != 0) goto fail; goto fail; PVS-Studio warnings: • CWE-483 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. • CWE-561 V779 Unreachable code detected. It is possible that an error is present.
  • 15. Error? Vulnerability! CVE-2014-1266 iOS if ((err = SSLHashSHA1.update( &hashCtx, &signedParams)) != 0) goto fail; goto fail; PVS-Studio warnings: • CWE-483 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. • CWE-561 V779 Unreachable code detected. It is possible that an error is present.
  • 16. Неправильный вызов функции Doom 3 void Sys_GetCurrentMemoryStatus( sysMemoryStats_t &stats ) { .... memset( &statex, sizeof( statex ), 0 ); .... } CppCheck warning: memset() called to fill 0 bytes of '&'
  • 17. Incorrect function call Doom 3 void Sys_GetCurrentMemoryStatus( sysMemoryStats_t &stats ) { .... memset( &statex, sizeof( statex ), 0 ); .... } CppCheck warning: memset() called to fill 0 bytes
  • 18. Incorrect function call Doom 3 void Sys_GetCurrentMemoryStatus( sysMemoryStats_t &stats ) { .... memset( &statex, sizeof( statex ), 0 ); .... } CppCheck warning: memset() called to fill 0 bytes
  • 19. Бессмысленная проверка Jenkins int cnt = 0; for (R b = getLastBuild(); cnt<5 && b!=null; b=b.getPreviousBuild()) { FilePath ws = b.getWorkspace(); if (ws != null) return b; } PVS-Studio warning: V6007 Expression 'cnt < 5' is always true.
  • 20. Useless check Jenkins int cnt = 0; for (R b = getLastBuild(); cnt<5 && b!=null; b=b.getPreviousBuild()) { FilePath ws = b.getWorkspace(); if (ws != null) return b; } PVS-Studio warning: V6007 Expression 'cnt < 5' is always true.
  • 21. Useless check Jenkins int cnt = 0; for (R b = getLastBuild(); cnt<5 && b!=null; b=b.getPreviousBuild()) { FilePath ws = b.getWorkspace(); if (ws != null) return b; } PVS-Studio warning: V6007 Expression 'cnt < 5' is always true.
  • 22. Опасное разыменование указателя Unreal Engine bool FHeadMountedDisplay::IsInLowPersistenceMode() const { const auto frame = GetCurrentFrame(); const auto FrameSettings = frame->Settings; return frame && FrameSettings->Flags.bLowPersistenceMode; } Klocwork warning: Suspicious dereference of pointer 'frame' before NULL check
  • 23. Dangerous pointer dereference Unreal Engine bool FHeadMountedDisplay::IsInLowPersistenceMode() const { const auto frame = GetCurrentFrame(); const auto FrameSettings = frame->Settings; return frame && FrameSettings->Flags.bLowPersistenceMode; } Klocwork warning: Suspicious dereference of pointer 'frame' before NULL check
  • 24. Dangerous pointer dereference Unreal Engine bool FHeadMountedDisplay::IsInLowPersistenceMode() const { const auto frame = GetCurrentFrame(); const auto FrameSettings = frame->Settings; return frame && FrameSettings->Flags.bLowPersistenceMode; } Klocwork warning: Suspicious dereference of pointer 'frame' before NULL check
  • 25. Непроверенные входные данные NcFTP if (fgets(newname, sizeof(newname) - 1, stdin) == NULL) newname[0] = '0'; newname[strlen(newname) - 1] = '0'; PVS-Studio warning: CWE-20 V1010 Unchecked tainted data is used in index: 'strlen(newname)'.
  • 26. Unchecked input data NcFTP if (fgets(newname, sizeof(newname) - 1, stdin) == NULL) newname[0] = '0'; newname[strlen(newname) - 1] = '0'; PVS-Studio warning: CWE-20 V1010 Unchecked tainted data is used in index: 'strlen(newname)'.
  • 27. Unchecked input data NcFTP if (fgets(newname, sizeof(newname) - 1, stdin) == NULL) newname[0] = '0'; newname[strlen(newname) - 1] = '0';
  • 28. Unchecked input data NcFTP if (fgets(newname, sizeof(newname) - 1, stdin) == NULL) newname[0] = '0'; newname[strlen(newname) - 1] = '0';
  • 29. Unchecked input data NcFTP if (fgets(newname, sizeof(newname) - 1, stdin) == NULL) newname[0] = '0'; newname[strlen(newname) - 1] = '0';
  • 30. Unchecked input data NcFTP if (fgets(newname, sizeof(newname) - 1, stdin) == NULL) newname[0] = '0'; newname[strlen(newname) - 1] = '0'; 0??? -1
  • 31. Reproducing the error • Server connection. • Downloading file from a server. • Input of a string, starting with 'N'. • Input '0'. • .... • PROFIT!
  • 32. Reproducing the error • ncftp.exe ftp://speedtest.tele2.net • get 512KB.zip • Now let's have some fun • 0??? • .... • PROFIT!
  • 34. Myth: static analysis is for newbies, professionals don’t make mistakes
  • 35. Myth: static analysis is for newbies, professionals don’t make mistakes
  • 36. Single checks are ineffective • ... but better than no checks at all. • “Let’s check projects before the release!" • Critical errors were fixed for a higher price.
  • 37. CVE-2015-8948 libidn else if (fgets ( readbuf, BUFSIZ, stdin) == NULL) { .... } if (readbuf[strlen (readbuf) - 1] == 'n') readbuf[strlen (readbuf) - 1] = '0'; PVS-Studio warning: CWE-20 V1010 Unchecked tainted data is used in index: 'strlen(readbuf)'.
  • 38. CVE-2016-6262 libidn else if (getline (&line, &linelen, stdin) == -1) { .... } if (line[strlen (line) - 1] == 'n') line[strlen (line) - 1] = '0'; PVS-Studio warning: CWE-20 V1010 Unchecked tainted data is used in index: 'strlen(line)'.
  • 39. CVE-2016-6262 libidn else if (getline (&line, &linelen, stdin) == -1) { .... } if (strlen (line) > 0) if (line[strlen (line) - 1] == 'n') line[strlen (line) - 1] = '0';
  • 40. CVE from libidn CVE-2015-8948. Commit, closing this vulnerability: 10.08.2015 CVE-2016-6262. Commit, closing this vulnerability: 14.01.2016 Time difference – 5 months.
  • 41. Use static analysis regularly.
  • 42. Effective use • Locally on developers’ computers. • On a build server. • Prompt fixing of errors. • ... • PROFIT!
  • 43. Local use • Cost of fixing an error is minimal. • Developer is inside a context: it’s easier to handle a warning. • No one will find out about the problem except you and the analyzer:)
  • 44. Incremental analysis • Analyzing only modified newly written code. • Reducing of analysis time. • Great for early detection of errors.
  • 45. Example from personal experience • Analyzer developers also make mistakes :) • Integration with Visual Studio + incremental analysis.
  • 46. Using on a build server • Detecting errors, that got into a repository. • Various scenarios of working with analysis results: • Distribution by mail; • Generation of issues; • Using in CI-systems; • etc.
  • 47. Example from personal experience • Nightly analysis. • Merging of logs, filtration, conversion. • Handling the analysis results: • Mails distribution; • Publication of results in Jenkins.
  • 48. Analyze code on developer machines and on a build server.
  • 49. Deploying on a project
  • 50. Deploying on a project High Medium Low Total 1350 35943 45346 82639
  • 51. Deploying on a project • How did that even work? • What should be fixed and how can it be done? • How to separate old warnings from the new ones?
  • 52. False positives • Are triggered on correct code. • Analysis logs are cluttered. • Are inevitable.
  • 53. "Redundant" analysis • Third-party code is analyzed. • Irrelevant project warnings clutter the output.
  • 56. Problems solutions Problem Solution False positives Message suppression
  • 57. Problems solutions Problem Solution False positives Message suppression "Explosion" after the first analysis "Freezing" of all warnings
  • 58. Problems solutions Problem Solution False positives Message suppression "Explosion" after the first analysis "Freezing" of all warnings Long analysis time Incremental analysis
  • 59. Problems solutions Problem Solution False positives Message suppression "Explosion" after the first analysis "Freezing" of all warnings Long analysis time Incremental analysis Inconvenience of working with 'raw' logs Usage of auxiliary tools
  • 60. Problems solutions Problem Solution False positives Message suppression "Explosion" after the first analysis "Freezing" of all warnings Long analysis time Incremental analysis Inconvenience of working with 'raw' logs Usage of auxiliary tools Warnings on third-party code Excluding from the analysis
  • 61. Problems solutions Problem Solution False positives Message suppression "Explosion" after the first analysis "Freezing" of all warnings Long analysis time Incremental analysis Inconvenience of working with 'raw' logs Usage of auxiliary tools Warnings on third-party code Excluding from the analysis Irrelevant diagnostics Disabling diagnostic rules
  • 62. Investigate the tools that are suggested by developers of analyzer.
  • 63. Deploying on a project • "Freezing" of existing warnings. • Configuring the analyzer. • Don’t let new errors appear. • Go back to old errors whenever spare resources and time is available.
  • 64. When deploying static analysis, mark existing warnings as irrelevant.
  • 65. Recommended articles on the topic "How the PVS-Studio Team Improved Unreal Engine's Code" https://bit.ly/2IKnnch "Static Analysis as Part of the Development Process in Unreal Engine" https://bit.ly/2KL4ZAu
  • 68. No Silver Bullet • Static analysis is not a cure-all. • Effectively complemented by other tools.
  • 69. Sergey Vasiliev E-mail: [email protected] PVS-Studio site: https://www.viva64.com