SlideShare ist ein Scribd-Unternehmen logo
1 von 13
Downloaden Sie, um offline zu lesen
Php Inspections (EA Extended)*:
If-statements optimization
* Intelligent Static Code Analyzer for JetBrains IDEs
Vladimir Reznichenko
Karlsruhe, 20 October 2016
What is Static Code Analysis about?
Static code analysis is about finding defects in source code *:
● Code Style violations (formatting, naming conventions and etc.);
● Implementation Defects (bugs, portability, performance and etc.);
● Security Issues (CVEs, API usage and etc.);
● Code Duplication;
● Code Metrics (e.g. Complexity, UTs coverage and etc.);
* and bytecode (e.g. FindBugs)
Php Inspections (EA Extended): what’s covered?
Challenges we met
● If-statements analysis:
○ Execution costs estimation;
○ Interconnected conditions; if (is_array($a) && $a[0] > 0) ;
○ Variadic constructions, booleans, identical sub-expressions detection and more;
● exceptions handling workflow analysis:
○ Simulation of the workflow for running analysis;
○ PhpDoc parsing: PHP is not supporting “throws” declarations;
○ Nested catch and finally has implementation issues in older PHP versions;
● analysis performance:
○ Concurrency (inspections are running in several independent threads);
○ GC: memory optimization (VisualVM, data structures);
○ Avoid low-performing analysis, stop as early as possible;
Challenges we met
● If-statements analysis:
○ Execution costs estimation;
○ Interconnected conditions;
○ Variadic constructions, booleans, identical sub-expressions detection and more;
If-statements analysis: patterns
● Execution costs: if ($var->method($a) && $b > 0) ;
● Identical operands: if ($a !== $a) ;
● Ambiguous type checks: if ($a instanceof Date || $a instanceof DateInterface) ;
● If ($a instanceof DateInterface && null !== $a) ;
● Variadic constructions: if (isset($a) && isset($b)) ; => if (isset($a, $b)) ;
● Hardcoded booleans: if ($a > 0 || true) ;
● Confusing conditions: if ($a > 0 || $a <= 0 && $a > $minValue) ;
● Duplicated expressions in elseif and nested ifs:
● If (is_array($a) || is_string($a)) {
● If (is_array($a) && count($a) > 0) ;
● }
Execution costs estimation: idea
The challenge has a name: “Shortest path problem” from Graphs theory (Discrete
mathematics).
Applying the problem e.g. to “if ($var->method($a) && $a > 0) ;” we have 2 paths:
● $var->method($a)
○ Method lookup ;
○ Calls stack: push and pop ;
○ Complex operation, therefore high execution costs ;
● $a > 0
○ Primitive operation, therefore low execution costs ;
Execution costs estimation: example
Let’s take more common case: if-else construct.
If (<conditions>) {
<operation 1>;
} else {
<operation 2>;
}
Formula for if-else construction cost estimation will be*:
C(<if-else>) = C(<conditions>) + max(C(<operation 1>), C(<operation 2>))
* The theory of parsing, translation, and compiling
Execution costs estimation: C() function
This is most important part: which weight to assign to different constructs?
For this you need know your compiler/interpreter internals and language
capabilities.
Example weights specific for PHP:
● Binary/Unary operations: 0 ; (primitive operations)
● Array access: +1 (hash-maps based arrays implementation) ;
● Method/function reference: +5 (call stack invocation) ;
● Lambdas: +10 (no JIT compiler, dynamically allocated) ;
● etc.
Code samples: hooking into IDE
public class NotOptimalIfConditionsInspection extends BasePhpInspection {
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new BasePhpElementVisitor() {
public void visitPhpIf(If ifStatement) {
/* we are visiting a branch of AST-tree here, analyze it */
}
/* other visitors here */
};
}
}
Code samples: processing conditions
LinkedList<PsiElement> conditions = <extraction_method>(ifStatement.getCondition(), operationHolder);
if (null != conditions ) {
allConditions.addAll(conditions);
/* invoke strategies */
conditions.clear();
}
for (ElseIf objElseIf : ifStatement.getElseIfBranches()) {
conditions = <extraction_method>(objElseIf.getCondition(), operationHolder);
if (null != conditions) {
allConditions.addAll(conditions);
/* invoke strategies */
conditions.clear();
}
}
<nested_ifs_duplicates_strategy>(allConditions, ifStatement);
Code samples: execution costs estimation
How to calculate execution costs for expression “$a->getConfig()[‘waf’]”
if (expression instanceof ArrayAccessExpression) {
final ArrayAccessExpression arrayAccess = (ArrayAccessExpression) expression;
final ArrayIndex arrayIndex = arrayAccess.getIndex();
int ownCosts = getExpressionCost(arrayAccess.getValue()); /* recursion: $a->getConfig() -> 5 */
if (null != arrayIndex) {
ownCosts += getExpressionCost(arrayIndex.getValue()); /* recursion: ‘waf’ -> 0 */
}
return (1 + ownCosts); /* -> 6 */
}
Thank you

Weitere ähnliche Inhalte

Was ist angesagt?

11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage class
kapil078
 
11 2. variable-scope rule,-storage_class
11 2. variable-scope rule,-storage_class11 2. variable-scope rule,-storage_class
11 2. variable-scope rule,-storage_class
웅식 전
 

Was ist angesagt? (20)

Storage class in C Language
Storage class in C LanguageStorage class in C Language
Storage class in C Language
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Array strings
Array stringsArray strings
Array strings
 
Programming basics
Programming basicsProgramming basics
Programming basics
 
Storage classes
Storage classesStorage classes
Storage classes
 
Exception handling
Exception handlingException handling
Exception handling
 
11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage class
 
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
 
Storage classes in C
Storage classes in C Storage classes in C
Storage classes in C
 
[C++ korea] effective modern c++ study item 3 understand decltype +이동우
[C++ korea] effective modern c++ study   item 3 understand decltype +이동우[C++ korea] effective modern c++ study   item 3 understand decltype +이동우
[C++ korea] effective modern c++ study item 3 understand decltype +이동우
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing Insanity
 
Storage classes
Storage classesStorage classes
Storage classes
 
11 2. variable-scope rule,-storage_class
11 2. variable-scope rule,-storage_class11 2. variable-scope rule,-storage_class
11 2. variable-scope rule,-storage_class
 
1 introduction to c program
1 introduction to c program1 introduction to c program
1 introduction to c program
 
Storage classes
Storage classesStorage classes
Storage classes
 
Paradigmas de Linguagens de Programacao - Aula #5
Paradigmas de Linguagens de Programacao - Aula #5Paradigmas de Linguagens de Programacao - Aula #5
Paradigmas de Linguagens de Programacao - Aula #5
 
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
 
Scala laboratory: Globus. iteration #2
Scala laboratory: Globus. iteration #2Scala laboratory: Globus. iteration #2
Scala laboratory: Globus. iteration #2
 
Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 
Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]
 

Andere mochten auch

EvolvingIntoNextGenerationTravelRetailing_APR_2005
EvolvingIntoNextGenerationTravelRetailing_APR_2005EvolvingIntoNextGenerationTravelRetailing_APR_2005
EvolvingIntoNextGenerationTravelRetailing_APR_2005
Yannis Karmis
 

Andere mochten auch (16)

PROCESO ENFERMERO DE ALZHEIMER.
PROCESO ENFERMERO DE ALZHEIMER.PROCESO ENFERMERO DE ALZHEIMER.
PROCESO ENFERMERO DE ALZHEIMER.
 
PROCESO ENFERMERO DE ALZHEIMER.
PROCESO ENFERMERO DE ALZHEIMER.PROCESO ENFERMERO DE ALZHEIMER.
PROCESO ENFERMERO DE ALZHEIMER.
 
INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.
INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.
INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.
 
EvolvingIntoNextGenerationTravelRetailing_APR_2005
EvolvingIntoNextGenerationTravelRetailing_APR_2005EvolvingIntoNextGenerationTravelRetailing_APR_2005
EvolvingIntoNextGenerationTravelRetailing_APR_2005
 
DEMOGRAFÍA DINÁMICA, VARIABLES DEMOGRÁFICAS, MORTALIDAD, FECUNDIDAD Y MOVIMIE...
DEMOGRAFÍA DINÁMICA, VARIABLES DEMOGRÁFICAS, MORTALIDAD, FECUNDIDAD Y MOVIMIE...DEMOGRAFÍA DINÁMICA, VARIABLES DEMOGRÁFICAS, MORTALIDAD, FECUNDIDAD Y MOVIMIE...
DEMOGRAFÍA DINÁMICA, VARIABLES DEMOGRÁFICAS, MORTALIDAD, FECUNDIDAD Y MOVIMIE...
 
15. bibliografía
15. bibliografía15. bibliografía
15. bibliografía
 
Notes from &quot;geology: earth history: mesozoic, cenozoic&quot;
Notes from &quot;geology: earth history: mesozoic, cenozoic&quot;Notes from &quot;geology: earth history: mesozoic, cenozoic&quot;
Notes from &quot;geology: earth history: mesozoic, cenozoic&quot;
 
INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.
INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.
INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.
 
Tangoが切り開く MRの世界と日本における最新開発事例
Tangoが切り開く MRの世界と日本における最新開発事例Tangoが切り開く MRの世界と日本における最新開発事例
Tangoが切り開く MRの世界と日本における最新開発事例
 
Slido - Audience Interaction Made Easy
Slido - Audience Interaction Made EasySlido - Audience Interaction Made Easy
Slido - Audience Interaction Made Easy
 
Space Explorations Around the World
Space Explorations Around the WorldSpace Explorations Around the World
Space Explorations Around the World
 
もっとデータ可視化をカジュアルに! OSSプロジェクト「E2D3」
もっとデータ可視化をカジュアルに! OSSプロジェクト「E2D3」もっとデータ可視化をカジュアルに! OSSプロジェクト「E2D3」
もっとデータ可視化をカジュアルに! OSSプロジェクト「E2D3」
 
Arabic 3: Basics on the nominal sentence
Arabic 3: Basics on the nominal sentence Arabic 3: Basics on the nominal sentence
Arabic 3: Basics on the nominal sentence
 
How to draw a water lily cach ve hoa sung
How to draw  a water lily   cach ve hoa sungHow to draw  a water lily   cach ve hoa sung
How to draw a water lily cach ve hoa sung
 
Aws x line x line bot awards
Aws x line x line bot awardsAws x line x line bot awards
Aws x line x line bot awards
 
How to draw a bottle - Vẽ cái chai
How to draw a bottle - Vẽ cái chaiHow to draw a bottle - Vẽ cái chai
How to draw a bottle - Vẽ cái chai
 

Ähnlich wie Php Inspections (EA Extended): if-conditions optimization

Node js
Node jsNode js
Node js
hazzaz
 

Ähnlich wie Php Inspections (EA Extended): if-conditions optimization (20)

Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing Speed
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
 
Core2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdfCore2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdf
 
Php basics
Php basicsPhp basics
Php basics
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
 
Apache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customizationApache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customization
 
Code metrics in PHP
Code metrics in PHPCode metrics in PHP
Code metrics in PHP
 
Maintainable JavaScript
Maintainable JavaScriptMaintainable JavaScript
Maintainable JavaScript
 
Node js
Node jsNode js
Node js
 
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
 
Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...
 
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tipsAndriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
 
Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your Code
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 

Kürzlich hochgeladen

Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Christo Ananth
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Christo Ananth
 

Kürzlich hochgeladen (20)

Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 

Php Inspections (EA Extended): if-conditions optimization

  • 1. Php Inspections (EA Extended)*: If-statements optimization * Intelligent Static Code Analyzer for JetBrains IDEs Vladimir Reznichenko Karlsruhe, 20 October 2016
  • 2. What is Static Code Analysis about? Static code analysis is about finding defects in source code *: ● Code Style violations (formatting, naming conventions and etc.); ● Implementation Defects (bugs, portability, performance and etc.); ● Security Issues (CVEs, API usage and etc.); ● Code Duplication; ● Code Metrics (e.g. Complexity, UTs coverage and etc.); * and bytecode (e.g. FindBugs)
  • 3. Php Inspections (EA Extended): what’s covered?
  • 4. Challenges we met ● If-statements analysis: ○ Execution costs estimation; ○ Interconnected conditions; if (is_array($a) && $a[0] > 0) ; ○ Variadic constructions, booleans, identical sub-expressions detection and more; ● exceptions handling workflow analysis: ○ Simulation of the workflow for running analysis; ○ PhpDoc parsing: PHP is not supporting “throws” declarations; ○ Nested catch and finally has implementation issues in older PHP versions; ● analysis performance: ○ Concurrency (inspections are running in several independent threads); ○ GC: memory optimization (VisualVM, data structures); ○ Avoid low-performing analysis, stop as early as possible;
  • 5. Challenges we met ● If-statements analysis: ○ Execution costs estimation; ○ Interconnected conditions; ○ Variadic constructions, booleans, identical sub-expressions detection and more;
  • 6. If-statements analysis: patterns ● Execution costs: if ($var->method($a) && $b > 0) ; ● Identical operands: if ($a !== $a) ; ● Ambiguous type checks: if ($a instanceof Date || $a instanceof DateInterface) ; ● If ($a instanceof DateInterface && null !== $a) ; ● Variadic constructions: if (isset($a) && isset($b)) ; => if (isset($a, $b)) ; ● Hardcoded booleans: if ($a > 0 || true) ; ● Confusing conditions: if ($a > 0 || $a <= 0 && $a > $minValue) ; ● Duplicated expressions in elseif and nested ifs: ● If (is_array($a) || is_string($a)) { ● If (is_array($a) && count($a) > 0) ; ● }
  • 7. Execution costs estimation: idea The challenge has a name: “Shortest path problem” from Graphs theory (Discrete mathematics). Applying the problem e.g. to “if ($var->method($a) && $a > 0) ;” we have 2 paths: ● $var->method($a) ○ Method lookup ; ○ Calls stack: push and pop ; ○ Complex operation, therefore high execution costs ; ● $a > 0 ○ Primitive operation, therefore low execution costs ;
  • 8. Execution costs estimation: example Let’s take more common case: if-else construct. If (<conditions>) { <operation 1>; } else { <operation 2>; } Formula for if-else construction cost estimation will be*: C(<if-else>) = C(<conditions>) + max(C(<operation 1>), C(<operation 2>)) * The theory of parsing, translation, and compiling
  • 9. Execution costs estimation: C() function This is most important part: which weight to assign to different constructs? For this you need know your compiler/interpreter internals and language capabilities. Example weights specific for PHP: ● Binary/Unary operations: 0 ; (primitive operations) ● Array access: +1 (hash-maps based arrays implementation) ; ● Method/function reference: +5 (call stack invocation) ; ● Lambdas: +10 (no JIT compiler, dynamically allocated) ; ● etc.
  • 10. Code samples: hooking into IDE public class NotOptimalIfConditionsInspection extends BasePhpInspection { @Override public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) { return new BasePhpElementVisitor() { public void visitPhpIf(If ifStatement) { /* we are visiting a branch of AST-tree here, analyze it */ } /* other visitors here */ }; } }
  • 11. Code samples: processing conditions LinkedList<PsiElement> conditions = <extraction_method>(ifStatement.getCondition(), operationHolder); if (null != conditions ) { allConditions.addAll(conditions); /* invoke strategies */ conditions.clear(); } for (ElseIf objElseIf : ifStatement.getElseIfBranches()) { conditions = <extraction_method>(objElseIf.getCondition(), operationHolder); if (null != conditions) { allConditions.addAll(conditions); /* invoke strategies */ conditions.clear(); } } <nested_ifs_duplicates_strategy>(allConditions, ifStatement);
  • 12. Code samples: execution costs estimation How to calculate execution costs for expression “$a->getConfig()[‘waf’]” if (expression instanceof ArrayAccessExpression) { final ArrayAccessExpression arrayAccess = (ArrayAccessExpression) expression; final ArrayIndex arrayIndex = arrayAccess.getIndex(); int ownCosts = getExpressionCost(arrayAccess.getValue()); /* recursion: $a->getConfig() -> 5 */ if (null != arrayIndex) { ownCosts += getExpressionCost(arrayIndex.getValue()); /* recursion: ‘waf’ -> 0 */ } return (1 + ownCosts); /* -> 6 */ }