SlideShare une entreprise Scribd logo
1  sur  36
STATIC CODE ANALYSIS:
WHAT? HOW? WHY?
Maxim Stefanov
PVS-Studio, C++/Java developer, Tula
1
About The Speaker
• Maxim Stefanov (stefanov@viva64.com)
• C++/Java developer in PVS-Studio
• Duties:
• Develops C++ core of the analyzer
• Develops Java analyzer
2
• Theory
 The importance of code quality (bugs, vulnerabilities, ...)
 Defect prevention methods
• From code review to static code analysis
 Code review VS Static code analysis
• Static code analysis techniques
• Some examples of defects in real projects
• More about static analysis
• Summary
3
We’ll Talk About...
• Perception
• Enhancement
• Support
• Absence of bugs
• ... et cetera
4
High-Quality Code
•It prevents technical debt if the project is new
•It helps not to lose users if the project is mature
5
Why Is Code Quality Important?
Cost to Fix a Defect
•Helps to find high-level bugs without shooting
yourself in the foot
•Allows to share experience with padawans
•Together you’ll learn some new things about
the project and its secrets
7
Code review
•Code review is very expensive:
– Expectation: «We’ll review this edit for
10-15 min»
– Reality – sometimes code review takes
hours
•You get tired quickly
8
But...
Pros Cons
Finds defects before code review You can’t find high-level
errors
An analyzer can’t get tired, it’s ready to work at any time False positives
You can find errors without even knowing about such a
pattern
You can find errors which are difficult to notice
9
Static Code Analysis Comes to Rescue
•Pattern-based analysis
•Type inference
•Method annotations
•Data-flow analysis
•Symbolic execution
10
Static Code Analysis Techniques
@Override
public boolean equals(Object obj) {
....
return index.equals(other.index)
&& type.equals(other.type)
&& version == other.version
&& found == other.found
&& tookInMillis == tookInMillis
&& Objects.equals(terms, other.terms);
}
11
Pattern-based analysis
Type inference
interface Human { .... }
class Parent implements Human{ .... }
class Child extends Parent { .... }
....
class Animal { ... }
....
boolean someMethod(List<Child> list, Animal animal)
{
if (list.remove(animal))
return false;
....
} 12
Method annotations
Class("java.lang.Math")
- Function("max", Type::Int32, Type::Int32)
.Pure()
.Set(FunctionClassification::NoDiscard)
.Requires(NotEquals(Arg1, Arg2))
.Returns(Arg1, Arg2,[](const Int &v1,
const Int &v2)
{
return v1.Max(v2);
})
13
Method annotations
Class("java.lang.Math")
- Function("max", Type::Int32, Type::Int32)
.Pure()
.Set(FunctionClassification::NoDiscard)
.Requires(NotEquals(Arg1, Arg2))
.Returns(Arg1, Arg2,[](const Int &v1,
const Int &v2)
{
return v1.Max(v2);
})
14
Method annotations
Class("java.lang.Math")
- Function("max", Type::Int32, Type::Int32)
.Pure()
.Set(FunctionClassification::NoDiscard)
.Requires(NotEquals(Arg1, Arg2))
.Returns(Arg1, Arg2,[](const Int &v1,
const Int &v2)
{
return v1.Max(v2);
})
15
Method annotations
Class("java.lang.Math")
- Function("max", Type::Int32, Type::Int32)
.Pure()
.Set(FunctionClassification::NoDiscard)
.Requires(NotEquals(Arg1, Arg2))
.Returns(Arg1, Arg2,[](const Int &v1,
const Int &v2)
{
return v1.Max(v2);
})
16
Method annotations
Class("java.lang.Math")
- Function("max", Type::Int32, Type::Int32)
.Pure()
.Set(FunctionClassification::NoDiscard)
.Requires(NotEquals(Arg1, Arg2))
.Returns(Arg1, Arg2,[](const Int &v1,
const Int &v2)
{
return v1.Max(v2);
})
17
Method annotations
Class("java.lang.Math")
- Function("max", Type::Int32, Type::Int32)
.Pure()
.Set(FunctionClassification::NoDiscard)
.Requires(NotEquals(Arg1, Arg2))
.Returns(Arg1, Arg2,[](const Int &v1,
const Int &v2)
{
return v1.Max(v2);
})
18
int test(int a, int b) {
....
Math.max(a, b);
....
}
19
Method annotations
int test(int a, int b)
{
....
return Math.max(a, a);
}
20
Method annotations
int test(int a, int b)
{
if (a > 5 && b < 2) {
// a = [6..INT_MAX]
// b = [INT_MIN..1]
if (Math.max(a, b) > 0)
{....}
}
....
}
21
Method annotations
Data-flow analysis
void func(int x) {
// x: [-2147483648..2147483647] //1
if (x > 3) {
// x: [4..2147483647] //2
if (x < 10) {
// x: [4..9] //3
}
} else {
// x: [-2147483648..3] //4
}
}
22
Symbolic execution
int someMethod(int A, int B)
{
if (A == B)
return 10 / (A - B);
return 1;
}
23
Some Examples of Defects in Real Projects
24
PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header,
uintptr_t header_mask, int value)
{
char buf[128];
sprintf(buf, "%d", value);
return set_value_buffer(dest, header, header_mask, buf);
}
StarEngine, C++
PVS-Studio: V614 Uninitialized buffer 'buf' used. pugixml.cpp 3362
It Came Up Unexpectedly...
25
It Came Up Unexpectedly...
PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header,
uintptr_t header_mask, int value)
{
char buf[128];
sprintf(buf, "%d", value);
return set_value_buffer(dest, header, header_mask, buf);
}
PVS-Studio: V614 Uninitialized buffer 'buf' used. pugixml.cpp 3362
#define schar char
#define suchar unsigned schar
#define sprintf std::printf
#define satof atof
#define satoi atoi
26
StarEngine, C++
PVS-Studio: V6007 Expression 'StringUtils.isNotEmpty("handleTabKey")' is always true.
SourceCodeEditorLoader.java 60
Copy Paste
public void loadComponent() {
....
String handleTabKey = element.attributeValue("handleTabKey");
if (StringUtils.isNotEmpty("handleTabKey")) {
resultComponent.setHandleTabKey(....);
}
....
}
27
CUBA Platform, Java
V778 Two similar code fragments were found. Perhaps, this is a typo and 'cap_resy'
variable should be used instead of 'cap_resx'. cyapa.c 1458
Copy Paste
static int
cyapa_raw_input(struct cyapa_softc *sc, ....)
{
....
if (sc->delta_x > sc->cap_resx) sc->delta_x = sc->cap_resx;
if (sc->delta_x < -sc->cap_resx) sc->delta_x = -sc->cap_resx;
if (sc->delta_y > sc->cap_resx) sc->delta_y = sc->cap_resy;
if (sc->delta_y < -sc->cap_resy) sc->delta_y = -sc->cap_resy;
....
}
28
FreeBSD Kernel, C
V778 Two similar code fragments were found. Perhaps, this is a typo and 'cap_resy'
variable should be used instead of 'cap_resx'. cyapa.c 1458
Copy Paste
static int
cyapa_raw_input(struct cyapa_softc *sc, ....)
{
....
if (sc->delta_x > sc->cap_resx) sc->delta_x = sc->cap_resx;
if (sc->delta_x < -sc->cap_resx) sc->delta_x = -sc->cap_resx;
if (sc->delta_y > sc->cap_resx) sc->delta_y = sc->cap_resy;
if (sc->delta_y < -sc->cap_resy) sc->delta_y = -sc->cap_resy;
....
}
29
FreeBSD Kernel, C
char c;
printf("%s .... ");
rewind(blk_alloc_file);
while ((c = fgetc(blk_alloc_file)) != EOF)
{
fputc(c, base_fs_file);
}
Android, C
PVS-Studio: V739 CWE-20 EOF should not be compared with a value of the 'char' type. The
'(c = fgetc(blk_alloc_file))' should be of the 'int' type. blk_alloc_to_base_fs.c 61
30
Unlucky Character
Compiler Deletes Code to Wipe Buffer
static void FwdLockGlue_InitializeRoundKeys() {
unsigned char keyEncryptionKey[KEY_SIZE];
....
memset(keyEncryptionKey, 0, KEY_SIZE); // Zero out key data.
}
PVS-Studio: V597 CWE-14 The compiler could delete the 'memset' function call, which is
used to flush 'keyEncryptionKey' buffer. The memset_s() function should be used to erase
the private data. FwdLockGlue.c 102
31
Android, C
How to Blend Static Analysis into Software
Development Process
• Every developer has a static analysis tool in their
workplace
• Analysis of the entire codebase during night builds. If
suspicious code is found, the guilty one will receive an
email
32
How to Start Using Static Analysis Tools in Big
Projects and Keep Your Cool
1. Check the project
2. Put all issued warnings in a special suppression file to indicate that
now you are not interested in all issued warnings
3. Put the markup file into the version control system
4. Run the analyzer and receive warnings only for new or changed
code
5. PROFIT!
33
Summary
• Static analysis helps to immediately find some errors while the cost to
fix them is low
• Static analysis should be used regularly
• You can start using the analysis right away and fix some old errors
after
• Static analysis is not a silver bullet, it’s important to use different
techniques
34
Thank you for your attention!
35
Useful Links
The podcast about static analysis
with PVS-Studio founders [RU]
The list of static analysis tools
The PVS-Studio site

Contenu connexe

Tendances

Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"
Victor_Cr
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Robot Media
 
Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations
DVClub
 

Tendances (20)

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
 
модели акторов в с++ миф или реальность
модели акторов в с++ миф или реальностьмодели акторов в с++ миф или реальность
модели акторов в с++ миф или реальность
 
Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"
 
Linux version of PVS-Studio couldn't help checking CodeLite
Linux version of PVS-Studio couldn't help checking CodeLiteLinux version of PVS-Studio couldn't help checking CodeLite
Linux version of PVS-Studio couldn't help checking CodeLite
 
Android JNI
Android JNIAndroid JNI
Android JNI
 
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
 
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
 
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеДмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI веке
 
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
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
 
Checking Clang 11 with PVS-Studio
Checking Clang 11 with PVS-StudioChecking Clang 11 with PVS-Studio
Checking Clang 11 with PVS-Studio
 
Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016
 
GMock framework
GMock frameworkGMock framework
GMock framework
 
Analysis of bugs in Orchard CMS
Analysis of bugs in Orchard CMSAnalysis of bugs in Orchard CMS
Analysis of bugs in Orchard CMS
 
Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations
 
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
 
Introduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxIntroduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicox
 
Eric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build systemEric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build system
 
report
reportreport
report
 
Tesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition SoftwareTesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition Software
 

Similaire à Static code analysis: what? how? why?

Similaire à Static code analysis: what? how? why? (20)

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
 
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMEREVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER
 
Static analysis: Around Java in 60 minutes
Static analysis: Around Java in 60 minutesStatic analysis: Around Java in 60 minutes
Static analysis: Around Java in 60 minutes
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project Analyzed
 
The Little Unicorn That Could
The Little Unicorn That CouldThe Little Unicorn That Could
The Little Unicorn That Could
 
PVS-Studio for Linux Went on a Tour Around Disney
PVS-Studio for Linux Went on a Tour Around DisneyPVS-Studio for Linux Went on a Tour Around Disney
PVS-Studio for Linux Went on a Tour Around Disney
 
Android ndk
Android ndkAndroid ndk
Android ndk
 
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
 
Headache from using mathematical software
Headache from using mathematical softwareHeadache from using mathematical software
Headache from using mathematical software
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correction
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correction
 
Picking Mushrooms after Cppcheck
Picking Mushrooms after CppcheckPicking Mushrooms after Cppcheck
Picking Mushrooms after Cppcheck
 
Checking the Source SDK Project
Checking the Source SDK ProjectChecking the Source SDK Project
Checking the Source SDK Project
 
Cross Platform App Development with C++
Cross Platform App Development with C++Cross Platform App Development with C++
Cross Platform App Development with C++
 
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
 
How to fake_properly
How to fake_properlyHow to fake_properly
How to fake_properly
 
Does static analysis need machine learning?
Does static analysis need machine learning?Does static analysis need machine learning?
Does static analysis need machine learning?
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correction
 
"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 ...
 
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft EdgeChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
 

Plus de Andrey Karpov

Plus de 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 - 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...
 
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?
 
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++
 
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOpsPVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
 
PVS-Studio Static Analyzer as a Tool for Protection against Zero-Day Vulnerab...
PVS-Studio Static Analyzer as a Tool for Protection against Zero-Day Vulnerab...PVS-Studio Static Analyzer as a Tool for Protection against Zero-Day Vulnerab...
PVS-Studio Static Analyzer as a Tool for Protection against Zero-Day Vulnerab...
 
Analysis of commits and pull requests in Travis CI, Buddy and AppVeyor using ...
Analysis of commits and pull requests in Travis CI, Buddy and AppVeyor using ...Analysis of commits and pull requests in Travis CI, Buddy and AppVeyor using ...
Analysis of commits and pull requests in Travis CI, Buddy and AppVeyor using ...
 
PVS-Studio in the Clouds: CircleCI
PVS-Studio in the Clouds: CircleCIPVS-Studio in the Clouds: CircleCI
PVS-Studio in the Clouds: CircleCI
 
PVS-Studio in the Clouds: Azure DevOps
PVS-Studio in the Clouds: Azure DevOpsPVS-Studio in the Clouds: Azure DevOps
PVS-Studio in the Clouds: Azure DevOps
 
Errors that static code analysis does not find because it is not used
Errors that static code analysis does not find because it is not usedErrors that static code analysis does not find because it is not used
Errors that static code analysis does not find because it is not used
 

Dernier

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Dernier (20)

%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
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
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
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
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 

Static code analysis: what? how? why?

  • 1. STATIC CODE ANALYSIS: WHAT? HOW? WHY? Maxim Stefanov PVS-Studio, C++/Java developer, Tula 1
  • 2. About The Speaker • Maxim Stefanov (stefanov@viva64.com) • C++/Java developer in PVS-Studio • Duties: • Develops C++ core of the analyzer • Develops Java analyzer 2
  • 3. • Theory  The importance of code quality (bugs, vulnerabilities, ...)  Defect prevention methods • From code review to static code analysis  Code review VS Static code analysis • Static code analysis techniques • Some examples of defects in real projects • More about static analysis • Summary 3 We’ll Talk About...
  • 4. • Perception • Enhancement • Support • Absence of bugs • ... et cetera 4 High-Quality Code
  • 5. •It prevents technical debt if the project is new •It helps not to lose users if the project is mature 5 Why Is Code Quality Important?
  • 6. Cost to Fix a Defect
  • 7. •Helps to find high-level bugs without shooting yourself in the foot •Allows to share experience with padawans •Together you’ll learn some new things about the project and its secrets 7 Code review
  • 8. •Code review is very expensive: – Expectation: «We’ll review this edit for 10-15 min» – Reality – sometimes code review takes hours •You get tired quickly 8 But...
  • 9. Pros Cons Finds defects before code review You can’t find high-level errors An analyzer can’t get tired, it’s ready to work at any time False positives You can find errors without even knowing about such a pattern You can find errors which are difficult to notice 9 Static Code Analysis Comes to Rescue
  • 10. •Pattern-based analysis •Type inference •Method annotations •Data-flow analysis •Symbolic execution 10 Static Code Analysis Techniques
  • 11. @Override public boolean equals(Object obj) { .... return index.equals(other.index) && type.equals(other.type) && version == other.version && found == other.found && tookInMillis == tookInMillis && Objects.equals(terms, other.terms); } 11 Pattern-based analysis
  • 12. Type inference interface Human { .... } class Parent implements Human{ .... } class Child extends Parent { .... } .... class Animal { ... } .... boolean someMethod(List<Child> list, Animal animal) { if (list.remove(animal)) return false; .... } 12
  • 13. Method annotations Class("java.lang.Math") - Function("max", Type::Int32, Type::Int32) .Pure() .Set(FunctionClassification::NoDiscard) .Requires(NotEquals(Arg1, Arg2)) .Returns(Arg1, Arg2,[](const Int &v1, const Int &v2) { return v1.Max(v2); }) 13
  • 14. Method annotations Class("java.lang.Math") - Function("max", Type::Int32, Type::Int32) .Pure() .Set(FunctionClassification::NoDiscard) .Requires(NotEquals(Arg1, Arg2)) .Returns(Arg1, Arg2,[](const Int &v1, const Int &v2) { return v1.Max(v2); }) 14
  • 15. Method annotations Class("java.lang.Math") - Function("max", Type::Int32, Type::Int32) .Pure() .Set(FunctionClassification::NoDiscard) .Requires(NotEquals(Arg1, Arg2)) .Returns(Arg1, Arg2,[](const Int &v1, const Int &v2) { return v1.Max(v2); }) 15
  • 16. Method annotations Class("java.lang.Math") - Function("max", Type::Int32, Type::Int32) .Pure() .Set(FunctionClassification::NoDiscard) .Requires(NotEquals(Arg1, Arg2)) .Returns(Arg1, Arg2,[](const Int &v1, const Int &v2) { return v1.Max(v2); }) 16
  • 17. Method annotations Class("java.lang.Math") - Function("max", Type::Int32, Type::Int32) .Pure() .Set(FunctionClassification::NoDiscard) .Requires(NotEquals(Arg1, Arg2)) .Returns(Arg1, Arg2,[](const Int &v1, const Int &v2) { return v1.Max(v2); }) 17
  • 18. Method annotations Class("java.lang.Math") - Function("max", Type::Int32, Type::Int32) .Pure() .Set(FunctionClassification::NoDiscard) .Requires(NotEquals(Arg1, Arg2)) .Returns(Arg1, Arg2,[](const Int &v1, const Int &v2) { return v1.Max(v2); }) 18
  • 19. int test(int a, int b) { .... Math.max(a, b); .... } 19 Method annotations
  • 20. int test(int a, int b) { .... return Math.max(a, a); } 20 Method annotations
  • 21. int test(int a, int b) { if (a > 5 && b < 2) { // a = [6..INT_MAX] // b = [INT_MIN..1] if (Math.max(a, b) > 0) {....} } .... } 21 Method annotations
  • 22. Data-flow analysis void func(int x) { // x: [-2147483648..2147483647] //1 if (x > 3) { // x: [4..2147483647] //2 if (x < 10) { // x: [4..9] //3 } } else { // x: [-2147483648..3] //4 } } 22
  • 23. Symbolic execution int someMethod(int A, int B) { if (A == B) return 10 / (A - B); return 1; } 23
  • 24. Some Examples of Defects in Real Projects 24
  • 25. PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, int value) { char buf[128]; sprintf(buf, "%d", value); return set_value_buffer(dest, header, header_mask, buf); } StarEngine, C++ PVS-Studio: V614 Uninitialized buffer 'buf' used. pugixml.cpp 3362 It Came Up Unexpectedly... 25
  • 26. It Came Up Unexpectedly... PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, int value) { char buf[128]; sprintf(buf, "%d", value); return set_value_buffer(dest, header, header_mask, buf); } PVS-Studio: V614 Uninitialized buffer 'buf' used. pugixml.cpp 3362 #define schar char #define suchar unsigned schar #define sprintf std::printf #define satof atof #define satoi atoi 26 StarEngine, C++
  • 27. PVS-Studio: V6007 Expression 'StringUtils.isNotEmpty("handleTabKey")' is always true. SourceCodeEditorLoader.java 60 Copy Paste public void loadComponent() { .... String handleTabKey = element.attributeValue("handleTabKey"); if (StringUtils.isNotEmpty("handleTabKey")) { resultComponent.setHandleTabKey(....); } .... } 27 CUBA Platform, Java
  • 28. V778 Two similar code fragments were found. Perhaps, this is a typo and 'cap_resy' variable should be used instead of 'cap_resx'. cyapa.c 1458 Copy Paste static int cyapa_raw_input(struct cyapa_softc *sc, ....) { .... if (sc->delta_x > sc->cap_resx) sc->delta_x = sc->cap_resx; if (sc->delta_x < -sc->cap_resx) sc->delta_x = -sc->cap_resx; if (sc->delta_y > sc->cap_resx) sc->delta_y = sc->cap_resy; if (sc->delta_y < -sc->cap_resy) sc->delta_y = -sc->cap_resy; .... } 28 FreeBSD Kernel, C
  • 29. V778 Two similar code fragments were found. Perhaps, this is a typo and 'cap_resy' variable should be used instead of 'cap_resx'. cyapa.c 1458 Copy Paste static int cyapa_raw_input(struct cyapa_softc *sc, ....) { .... if (sc->delta_x > sc->cap_resx) sc->delta_x = sc->cap_resx; if (sc->delta_x < -sc->cap_resx) sc->delta_x = -sc->cap_resx; if (sc->delta_y > sc->cap_resx) sc->delta_y = sc->cap_resy; if (sc->delta_y < -sc->cap_resy) sc->delta_y = -sc->cap_resy; .... } 29 FreeBSD Kernel, C
  • 30. char c; printf("%s .... "); rewind(blk_alloc_file); while ((c = fgetc(blk_alloc_file)) != EOF) { fputc(c, base_fs_file); } Android, C PVS-Studio: V739 CWE-20 EOF should not be compared with a value of the 'char' type. The '(c = fgetc(blk_alloc_file))' should be of the 'int' type. blk_alloc_to_base_fs.c 61 30 Unlucky Character
  • 31. Compiler Deletes Code to Wipe Buffer static void FwdLockGlue_InitializeRoundKeys() { unsigned char keyEncryptionKey[KEY_SIZE]; .... memset(keyEncryptionKey, 0, KEY_SIZE); // Zero out key data. } PVS-Studio: V597 CWE-14 The compiler could delete the 'memset' function call, which is used to flush 'keyEncryptionKey' buffer. The memset_s() function should be used to erase the private data. FwdLockGlue.c 102 31 Android, C
  • 32. How to Blend Static Analysis into Software Development Process • Every developer has a static analysis tool in their workplace • Analysis of the entire codebase during night builds. If suspicious code is found, the guilty one will receive an email 32
  • 33. How to Start Using Static Analysis Tools in Big Projects and Keep Your Cool 1. Check the project 2. Put all issued warnings in a special suppression file to indicate that now you are not interested in all issued warnings 3. Put the markup file into the version control system 4. Run the analyzer and receive warnings only for new or changed code 5. PROFIT! 33
  • 34. Summary • Static analysis helps to immediately find some errors while the cost to fix them is low • Static analysis should be used regularly • You can start using the analysis right away and fix some old errors after • Static analysis is not a silver bullet, it’s important to use different techniques 34
  • 35. Thank you for your attention! 35
  • 36. Useful Links The podcast about static analysis with PVS-Studio founders [RU] The list of static analysis tools The PVS-Studio site