SlideShare une entreprise Scribd logo
1  sur  30
Télécharger pour lire hors ligne
PVS-Studio в 2021
Примеры ошибок
󰏅 english version
Двойное освобождение ресурсов
Miranda NG
static INT_PTR ServiceCreateMergedFlagIcon(....)
{
HRGN hrgn;
....
if (hrgn!=NULL) {
SelectClipRgn(hdc,hrgn);
DeleteObject(hrgn);
....
DeleteObject(hrgn);
}
....
}
3
V586 The 'DeleteObject' function is called twice for deallocation of the same resource.
Недостижимый код
Bouncy Castle
public void testSignSHA256CompleteEvenHeight2() {
....
int height = 10;
....
for (int i = 0; i < (1 << height); i++) {
byte[] signature = xmss.sign(new byte[1024]);
switch (i) {
case 0x005b:
assertEquals(signatures[0], Hex.toHexString(signature));
break;
case 0x0822:
assertEquals(signatures[1], Hex.toHexString(signature));
break;
....
}
}
}
V6019 Unreachable code detected. It is possible that an error is present.
5
Некорректные операции сдвига
V8 JavaScript Engine
U_CFUNC int32_t U_CALLCONV
ucol_calcSortKey(....)
{
....
if((caseBits & 0xC0) == 0) {
*(cases-1) |= 1 << (--caseShift);
} else {
*(cases-1) |= 0 << (--caseShift);
....
}
V684 A value of the variable '* (cases - 1)' is not modified. Consider inspecting the expression. It is possible that '1'
should be present instead of '0'. 7
Неправильная работа с типами
Qemu
static inline uint32_t extract32(uint32_t value, int start, int length);
....
static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
ARMMMUIdx mmu_idx)
{
....
bool epd, hpd;
....
hpd &= extract32(tcr, 6, 1);
}
V1046 Unsafe usage of the 'bool' and 'unsigned int' types together in the operation '&='.
9
Azure SDK for .NET
public static class Tag
{
....
[Flags]
public enum BlocksUsing
{
MonitorEnter,
MonitorWait,
ManualResetEvent,
AutoResetEvent,
....
OtherInternalPrimitive,
OtherFrameworkPrimitive,
OtherInterop,
Other,
NonBlocking,
}
....
}
V3121 An enumeration 'BlocksUsing' was declared with 'Flags' aribute, but does not set any
initializers to override default values. 10
Неправильное представление о
работе метода / класса
ClickHouse
int mainEntryClickhousePerformanceTest(int argc, char ** argv) {
std::vector<std::string> input_files;
....
for (const auto filename : input_files) {
FS::path file(filename);
if (!FS::exists(file))
throw DB::Exception(....);
if (FS::is_directory(file)) {
input_files.erase(
std::remove(input_files.begin(), input_files.end(), filename),
input_files.end() );
getFilesFromDir(file, input_files, recursive);
}
....
}
....
}
V789 Iterators for the 'input_files' container, used in the range-based for loop, become invalid upon
the call of the 'erase' function. 12
Accord.Net
public class DenavitHartenbergNodeCollection :
Collection<DenavitHartenbergNode>
{ .... }
[Serializable]
public class DenavitHartenbergNode
{
....
public DenavitHartenbergNodeCollection Children
{
get;
private set;
}
....
}
V3097 Possible exception: the 'DenavitHartenbergNode' type marked by [Serializable] contains non-serializable
members not marked by [NonSerialized]. 13
GitExtensions
public override bool Equals(object obj)
{
return GetHashCode() == obj.GetHashCode();
}
V3115 Passing 'null' to 'Equals(object obj)' method should not result in 'NullReferenceException'.
14
Опечатки и copy-paste
LibreOice
inline bool equalFont( Style const & style1, Style const & style2 ) {
....
return ( f1.Name == f2.Name &&
f1.Height == f2.Height &&
f1.Width == f2.Width &&
f1.StyleName == f2.StyleName &&
f1.Family == f2.Family &&
f1.CharSet == f2.CharSet &&
f1.Pitch == f2.CharSet &&
f1.CharacterWidth == f2.CharacterWidth &&
f1.Weight == f2.Weight &&
.... &&
bool(f1.Kerning) == bool(f2.Kerning) &&
bool(f1.WordLineMode) == bool(f2.WordLineMode) &&
f1.Type == f2.Type &&
style1._fontRelief == style2._fontRelief &&
style1._fontEmphasisMark == style2._fontEmphasisMark
);
}
V1013 Suspicious subexpression f1.Pitch == f2.CharSet in a sequence of similar comparisons.
16
TON
int compute_compare(const VarDescr& x, const VarDescr& y, int mode) {
switch (mode) {
case 1: // >
return x.always_greater(y) ? 1 : (x.always_leq(y) ? 2 : 3);
case 2: // =
return x.always_equal(y) ? 1 : (x.always_neq(y) ? 2 : 3);
case 3: // >=
return x.always_geq(y) ? 1 : (x.always_less(y) ? 2 : 3);
....
case 5: // <>
return x.always_neq(y) ? 1 : (x.always_equal(y) ? 2 : 3);
case 6: // >=
return x.always_geq(y) ? 1 : (x.always_less(y) ? 2 : 3);
case 7: // <=>
return .... ;
default:
return 7;
}
}
V1037 Two or more case-branches perform the same actions.
17
Azure PowerShell
public class HelpMessages
{
public const string SubscriptionId = "Subscription Id of the subscription
associated with the management";
public const string GroupId = "Management Group Id";
public const string Recurse = "Recursively list the children of the
management group";
public const string ParentId = "Parent Id of the management group";
public const string GroupName = "Management Group Id";
public const string DisplayName = "Display Name of the management group";
public const string Expand = "Expand the output to list the children of the
management group";
public const string Force = "Force the action and skip confirmations";
public const string InputObject = "Input Object from the Get call";
public const string ParentObject = "Parent Object";
}
V3091 It is possible that a typo is present inside the string literal: "Management Group Id"
.
The 'Id' word is suspicious. 18
RunUO
private bool m_IsRewardItem;
[CommandProperty( AccessLevel.GameMaster )]
public bool IsRewardItem
{
get{ return m_IsRewardItem; }
set{ m_IsRewardItem = value; InvalidateProperties(); }
}
private bool m_East;
[CommandProperty( AccessLevel.GameMaster )]
public bool East
{
get{ return m_East; }
set{ m_IsRewardItem = value; InvalidateProperties(); }
}
V3140 Property accessors use dierent backing fields.
19
Ghidra
final static Map<Character, String> DELIMITER_NAME_MAP = new HashMap<>(20);
// Any non-alphanumeric char can be used as a delimiter.
static {
DELIMITER_NAME_MAP.put(' ', "Space");
DELIMITER_NAME_MAP.put('~', "Tilde");
DELIMITER_NAME_MAP.put('`', "Back quote");
DELIMITER_NAME_MAP.put('@', "Exclamation point");
DELIMITER_NAME_MAP.put('@', "At sign");
DELIMITER_NAME_MAP.put('#', "Pound sign");
DELIMITER_NAME_MAP.put('$', "Dollar sign");
DELIMITER_NAME_MAP.put('%', "Percent sign");
....
}
V6033 An item with the same key '@' has already been added.
20
Проблемы безопасности
Tor
int
crypto_pk_private_sign_digest(....)
{
char digest[DIGEST_LEN];
....
memset(digest, 0, sizeof(digest));
return r;
}
V597 The compiler could delete the 'memset' function call, which is used to flush 'digest' buer. The
RtlSecureZeroMemory() function should be used to erase the private data. 22
FreeRDP
BOOL certificate_data_replace(rdpCertificateStore* certificate_store,
rdpCertificateData* certificate_data)
{
HANDLE fp;
....
fp = CreateFileA(certificate_store->file, GENERIC_READ | GENERIC_WRITE, 0,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
....
if (size < 1) {
CloseHandle(fp);
return FALSE;
}
....
if (!data) {
fclose(fp);
return FALSE;
}
....
}
V1005 The resource was acquired using 'CreateFileA' function but was released using incompatible
'fclose' function. 23
.NET Core Libraries (CoreFX)
internal void SetSequence()
{
if (TypeDesc.IsRoot)
return;
StructMapping start = this;
// find first mapping that does not have the sequence set
while (!start.BaseMapping.IsSequence &&
start.BaseMapping != null &&
!start.BaseMapping.TypeDesc.IsRoot)
start = start.BaseMapping;
....
}
V3027 The variable 'start.BaseMapping' was utilized in the logical expression before it was
verified against null in the same logical expression. 24
Путаница с приоритетом операций
Spvolren
void ppmWrite(char *filename, PPMFile *ppmFile)
{
....
FILE *fp;
if (! (fp = fopen(filename, "wb")) == -1) {
perror("opening image file failed");
exit(1);
}
....
}
V562 It’s odd to compare a bool type value with a value of -1: !(fp = fopen (filename, "wb")) == - 1.
26
Media Portal 2
return config.EpisodesLoaded || !checkEpisodesLoaded &&
config.BannersLoaded || !checkBannersLoaded &&
config.ActorsLoaded || !checkActorsLoaded;
V3130 Priority of the '&&' operator is higher than that of the '||' operator. Possible missing
parentheses. 27
Как мы всё это
находим?
29
Анализ потока данных (data-flow analysis) используется для
вычисления ограничений, накладываемых на значения переменных
при обработке различных конструкций языка
Аннотирование методов (method annotations) предоставляет
больше информации об используемых метода, чем может быть
получено путем анализа только их объявления
Символьное выполнение (symbolic execution) позволяет вычислять
диапазоны значений переменных и проверять их состояния на
разных участках кода
Вывод типов (type inference) дает анализатору полную информацию о
всех переменных и выражениях, встречающихся в коде
Сопоставление с шаблоном (paern-based analysis) позволяет найти
участки в модели кода, которые похожи на уже известные типы
ошибок
Интересно?
узнайте больше на нашем сайте
🔗 Ещё больше примеров
🔗 Список всех диагностик
🔗 Подробнее о продукте
Обзор возможностей

Contenu connexe

Tendances

Максим Щепелин. "Unittesting. Как?"
Максим Щепелин. "Unittesting. Как?"Максим Щепелин. "Unittesting. Как?"
Максим Щепелин. "Unittesting. Как?"
Python Meetup
 
Объектно-Ориентированное Программирование на C++, Лекции 1 и 2
Объектно-Ориентированное Программирование на C++, Лекции 1 и 2Объектно-Ориентированное Программирование на C++, Лекции 1 и 2
Объектно-Ориентированное Программирование на C++, Лекции 1 и 2
Dima Dzuba
 
DevConf. Дмитрий Сошников - ECMAScript 6
DevConf. Дмитрий Сошников - ECMAScript 6DevConf. Дмитрий Сошников - ECMAScript 6
DevConf. Дмитрий Сошников - ECMAScript 6
Dmitry Soshnikov
 

Tendances (20)

Производительность в Django
Производительность в DjangoПроизводительность в Django
Производительность в Django
 
Очередной скучный доклад про логгирование
Очередной скучный доклад про логгированиеОчередной скучный доклад про логгирование
Очередной скучный доклад про логгирование
 
Максим Щепелин. "Unittesting. Как?"
Максим Щепелин. "Unittesting. Как?"Максим Щепелин. "Unittesting. Как?"
Максим Щепелин. "Unittesting. Как?"
 
Фитнес для вашего кода: как держать его в форме
Фитнес для вашего кода: как держать его в формеФитнес для вашего кода: как держать его в форме
Фитнес для вашего кода: как держать его в форме
 
Влад Ковташ — Yap Database
Влад Ковташ — Yap DatabaseВлад Ковташ — Yap Database
Влад Ковташ — Yap Database
 
Декораторы в Python и их практическое использование
Декораторы в Python и их практическое использование Декораторы в Python и их практическое использование
Декораторы в Python и их практическое использование
 
Объектно-ориентированное программирование. Лекции 9 и 10
Объектно-ориентированное программирование. Лекции 9 и 10Объектно-ориентированное программирование. Лекции 9 и 10
Объектно-ориентированное программирование. Лекции 9 и 10
 
Профилирование и отладка Django
Профилирование и отладка DjangoПрофилирование и отладка Django
Профилирование и отладка Django
 
Подробная презентация JavaScript 6 в 1
Подробная презентация JavaScript 6 в 1Подробная презентация JavaScript 6 в 1
Подробная презентация JavaScript 6 в 1
 
Объектно-Ориентированное Программирование на C++, Лекции 3 и 4
Объектно-Ориентированное Программирование на C++, Лекции  3 и 4 Объектно-Ориентированное Программирование на C++, Лекции  3 и 4
Объектно-Ориентированное Программирование на C++, Лекции 3 и 4
 
Javascript
JavascriptJavascript
Javascript
 
Python dict: прошлое, настоящее, будущее
Python dict: прошлое, настоящее, будущееPython dict: прошлое, настоящее, будущее
Python dict: прошлое, настоящее, будущее
 
Объектно-Ориентированное Программирование на C++, Лекции 1 и 2
Объектно-Ориентированное Программирование на C++, Лекции 1 и 2Объектно-Ориентированное Программирование на C++, Лекции 1 и 2
Объектно-Ориентированное Программирование на C++, Лекции 1 и 2
 
Подробная презентация JavaScript 6 в 1
Подробная презентация JavaScript 6 в 1Подробная презентация JavaScript 6 в 1
Подробная презентация JavaScript 6 в 1
 
Павел Беликов, Как избежать ошибок, используя современный C++
Павел Беликов, Как избежать ошибок, используя современный C++Павел Беликов, Как избежать ошибок, используя современный C++
Павел Беликов, Как избежать ошибок, используя современный C++
 
Магия метаклассов
Магия метаклассовМагия метаклассов
Магия метаклассов
 
Повседневный С++: алгоритмы и итераторы @ C++ Russia 2017
Повседневный С++: алгоритмы и итераторы @ C++ Russia 2017Повседневный С++: алгоритмы и итераторы @ C++ Russia 2017
Повседневный С++: алгоритмы и итераторы @ C++ Russia 2017
 
DevConf. Дмитрий Сошников - ECMAScript 6
DevConf. Дмитрий Сошников - ECMAScript 6DevConf. Дмитрий Сошников - ECMAScript 6
DevConf. Дмитрий Сошников - ECMAScript 6
 
[JAM 1.1] Clean Code (Paul Malikov)
[JAM 1.1] Clean Code (Paul Malikov)[JAM 1.1] Clean Code (Paul Malikov)
[JAM 1.1] Clean Code (Paul Malikov)
 
Unsafe: to be or to be removed?
Unsafe: to be or to be removed?Unsafe: to be or to be removed?
Unsafe: to be or to be removed?
 

Similaire à PVS-Studio в 2021 - Примеры ошибок

статический анализ кода
статический анализ кодастатический анализ кода
статический анализ кода
Andrey Karpov
 
Memory managment in i os (1)
Memory managment in i os (1)Memory managment in i os (1)
Memory managment in i os (1)
it-park
 
Memory managment in i os
Memory managment in i osMemory managment in i os
Memory managment in i os
it-park
 
Юнит-тестирование и Google Mock. Влад Лосев, Google
Юнит-тестирование и Google Mock. Влад Лосев, GoogleЮнит-тестирование и Google Mock. Влад Лосев, Google
Юнит-тестирование и Google Mock. Влад Лосев, Google
yaevents
 
20130429 dynamic c_c++_program_analysis-alexey_samsonov
20130429 dynamic c_c++_program_analysis-alexey_samsonov20130429 dynamic c_c++_program_analysis-alexey_samsonov
20130429 dynamic c_c++_program_analysis-alexey_samsonov
Computer Science Club
 

Similaire à PVS-Studio в 2021 - Примеры ошибок (20)

статический анализ кода
статический анализ кодастатический анализ кода
статический анализ кода
 
WebCamp: Developer Day: Parse'им бэкенд - Аким Халилов
WebCamp: Developer Day: Parse'им бэкенд - Аким ХалиловWebCamp: Developer Day: Parse'им бэкенд - Аким Халилов
WebCamp: Developer Day: Parse'им бэкенд - Аким Халилов
 
"Погружение в Robolectric" Дмитрий Костырев (Avito)
"Погружение в Robolectric"  Дмитрий Костырев (Avito)"Погружение в Robolectric"  Дмитрий Костырев (Avito)
"Погружение в Robolectric" Дмитрий Костырев (Avito)
 
Статический анализ кода: Что? Как? Зачем?
Статический анализ кода: Что? Как? Зачем?Статический анализ кода: Что? Как? Зачем?
Статический анализ кода: Что? Как? Зачем?
 
C sharp deep dive
C sharp deep diveC sharp deep dive
C sharp deep dive
 
C# Deep Dive
C# Deep DiveC# Deep Dive
C# Deep Dive
 
C#. От основ к эффективному коду
C#. От основ к эффективному кодуC#. От основ к эффективному коду
C#. От основ к эффективному коду
 
Статический и динамический полиморфизм в C++, Дмитрий Леванов
Статический и динамический полиморфизм в C++, Дмитрий ЛевановСтатический и динамический полиморфизм в C++, Дмитрий Леванов
Статический и динамический полиморфизм в C++, Дмитрий Леванов
 
Паттерны проектирования
Паттерны проектированияПаттерны проектирования
Паттерны проектирования
 
Веселая ферма. Соседи.
Веселая ферма. Соседи.Веселая ферма. Соседи.
Веселая ферма. Соседи.
 
Thread
ThreadThread
Thread
 
Memory managment in i os (1)
Memory managment in i os (1)Memory managment in i os (1)
Memory managment in i os (1)
 
Memory managment in i os
Memory managment in i osMemory managment in i os
Memory managment in i os
 
Юнит-тестирование и Google Mock. Влад Лосев, Google
Юнит-тестирование и Google Mock. Влад Лосев, GoogleЮнит-тестирование и Google Mock. Влад Лосев, Google
Юнит-тестирование и Google Mock. Влад Лосев, Google
 
Юрий Ефимочев, Компилируемые в реальном времени DSL для С++
Юрий Ефимочев, Компилируемые в реальном времени DSL для С++ Юрий Ефимочев, Компилируемые в реальном времени DSL для С++
Юрий Ефимочев, Компилируемые в реальном времени DSL для С++
 
Архитектура минимальных Ui компонент
Архитектура минимальных Ui компонентАрхитектура минимальных Ui компонент
Архитектура минимальных Ui компонент
 
Некоторые паттерны реализации полиморфного поведения в C++ – Дмитрий Леванов,...
Некоторые паттерны реализации полиморфного поведения в C++ – Дмитрий Леванов,...Некоторые паттерны реализации полиморфного поведения в C++ – Дмитрий Леванов,...
Некоторые паттерны реализации полиморфного поведения в C++ – Дмитрий Леванов,...
 
Database (Lecture 14 – database)
Database (Lecture 14 – database)Database (Lecture 14 – database)
Database (Lecture 14 – database)
 
Асинхронный JavaScript
Асинхронный JavaScriptАсинхронный JavaScript
Асинхронный JavaScript
 
20130429 dynamic c_c++_program_analysis-alexey_samsonov
20130429 dynamic c_c++_program_analysis-alexey_samsonov20130429 dynamic c_c++_program_analysis-alexey_samsonov
20130429 dynamic c_c++_program_analysis-alexey_samsonov
 

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

  • 1. PVS-Studio в 2021 Примеры ошибок 󰏅 english version
  • 3. Miranda NG static INT_PTR ServiceCreateMergedFlagIcon(....) { HRGN hrgn; .... if (hrgn!=NULL) { SelectClipRgn(hdc,hrgn); DeleteObject(hrgn); .... DeleteObject(hrgn); } .... } 3 V586 The 'DeleteObject' function is called twice for deallocation of the same resource.
  • 5. Bouncy Castle public void testSignSHA256CompleteEvenHeight2() { .... int height = 10; .... for (int i = 0; i < (1 << height); i++) { byte[] signature = xmss.sign(new byte[1024]); switch (i) { case 0x005b: assertEquals(signatures[0], Hex.toHexString(signature)); break; case 0x0822: assertEquals(signatures[1], Hex.toHexString(signature)); break; .... } } } V6019 Unreachable code detected. It is possible that an error is present. 5
  • 7. V8 JavaScript Engine U_CFUNC int32_t U_CALLCONV ucol_calcSortKey(....) { .... if((caseBits & 0xC0) == 0) { *(cases-1) |= 1 << (--caseShift); } else { *(cases-1) |= 0 << (--caseShift); .... } V684 A value of the variable '* (cases - 1)' is not modified. Consider inspecting the expression. It is possible that '1' should be present instead of '0'. 7
  • 9. Qemu static inline uint32_t extract32(uint32_t value, int start, int length); .... static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va, ARMMMUIdx mmu_idx) { .... bool epd, hpd; .... hpd &= extract32(tcr, 6, 1); } V1046 Unsafe usage of the 'bool' and 'unsigned int' types together in the operation '&='. 9
  • 10. Azure SDK for .NET public static class Tag { .... [Flags] public enum BlocksUsing { MonitorEnter, MonitorWait, ManualResetEvent, AutoResetEvent, .... OtherInternalPrimitive, OtherFrameworkPrimitive, OtherInterop, Other, NonBlocking, } .... } V3121 An enumeration 'BlocksUsing' was declared with 'Flags' aribute, but does not set any initializers to override default values. 10
  • 12. ClickHouse int mainEntryClickhousePerformanceTest(int argc, char ** argv) { std::vector<std::string> input_files; .... for (const auto filename : input_files) { FS::path file(filename); if (!FS::exists(file)) throw DB::Exception(....); if (FS::is_directory(file)) { input_files.erase( std::remove(input_files.begin(), input_files.end(), filename), input_files.end() ); getFilesFromDir(file, input_files, recursive); } .... } .... } V789 Iterators for the 'input_files' container, used in the range-based for loop, become invalid upon the call of the 'erase' function. 12
  • 13. Accord.Net public class DenavitHartenbergNodeCollection : Collection<DenavitHartenbergNode> { .... } [Serializable] public class DenavitHartenbergNode { .... public DenavitHartenbergNodeCollection Children { get; private set; } .... } V3097 Possible exception: the 'DenavitHartenbergNode' type marked by [Serializable] contains non-serializable members not marked by [NonSerialized]. 13
  • 14. GitExtensions public override bool Equals(object obj) { return GetHashCode() == obj.GetHashCode(); } V3115 Passing 'null' to 'Equals(object obj)' method should not result in 'NullReferenceException'. 14
  • 16. LibreOice inline bool equalFont( Style const & style1, Style const & style2 ) { .... return ( f1.Name == f2.Name && f1.Height == f2.Height && f1.Width == f2.Width && f1.StyleName == f2.StyleName && f1.Family == f2.Family && f1.CharSet == f2.CharSet && f1.Pitch == f2.CharSet && f1.CharacterWidth == f2.CharacterWidth && f1.Weight == f2.Weight && .... && bool(f1.Kerning) == bool(f2.Kerning) && bool(f1.WordLineMode) == bool(f2.WordLineMode) && f1.Type == f2.Type && style1._fontRelief == style2._fontRelief && style1._fontEmphasisMark == style2._fontEmphasisMark ); } V1013 Suspicious subexpression f1.Pitch == f2.CharSet in a sequence of similar comparisons. 16
  • 17. TON int compute_compare(const VarDescr& x, const VarDescr& y, int mode) { switch (mode) { case 1: // > return x.always_greater(y) ? 1 : (x.always_leq(y) ? 2 : 3); case 2: // = return x.always_equal(y) ? 1 : (x.always_neq(y) ? 2 : 3); case 3: // >= return x.always_geq(y) ? 1 : (x.always_less(y) ? 2 : 3); .... case 5: // <> return x.always_neq(y) ? 1 : (x.always_equal(y) ? 2 : 3); case 6: // >= return x.always_geq(y) ? 1 : (x.always_less(y) ? 2 : 3); case 7: // <=> return .... ; default: return 7; } } V1037 Two or more case-branches perform the same actions. 17
  • 18. Azure PowerShell public class HelpMessages { public const string SubscriptionId = "Subscription Id of the subscription associated with the management"; public const string GroupId = "Management Group Id"; public const string Recurse = "Recursively list the children of the management group"; public const string ParentId = "Parent Id of the management group"; public const string GroupName = "Management Group Id"; public const string DisplayName = "Display Name of the management group"; public const string Expand = "Expand the output to list the children of the management group"; public const string Force = "Force the action and skip confirmations"; public const string InputObject = "Input Object from the Get call"; public const string ParentObject = "Parent Object"; } V3091 It is possible that a typo is present inside the string literal: "Management Group Id" . The 'Id' word is suspicious. 18
  • 19. RunUO private bool m_IsRewardItem; [CommandProperty( AccessLevel.GameMaster )] public bool IsRewardItem { get{ return m_IsRewardItem; } set{ m_IsRewardItem = value; InvalidateProperties(); } } private bool m_East; [CommandProperty( AccessLevel.GameMaster )] public bool East { get{ return m_East; } set{ m_IsRewardItem = value; InvalidateProperties(); } } V3140 Property accessors use dierent backing fields. 19
  • 20. Ghidra final static Map<Character, String> DELIMITER_NAME_MAP = new HashMap<>(20); // Any non-alphanumeric char can be used as a delimiter. static { DELIMITER_NAME_MAP.put(' ', "Space"); DELIMITER_NAME_MAP.put('~', "Tilde"); DELIMITER_NAME_MAP.put('`', "Back quote"); DELIMITER_NAME_MAP.put('@', "Exclamation point"); DELIMITER_NAME_MAP.put('@', "At sign"); DELIMITER_NAME_MAP.put('#', "Pound sign"); DELIMITER_NAME_MAP.put('$', "Dollar sign"); DELIMITER_NAME_MAP.put('%', "Percent sign"); .... } V6033 An item with the same key '@' has already been added. 20
  • 22. Tor int crypto_pk_private_sign_digest(....) { char digest[DIGEST_LEN]; .... memset(digest, 0, sizeof(digest)); return r; } V597 The compiler could delete the 'memset' function call, which is used to flush 'digest' buer. The RtlSecureZeroMemory() function should be used to erase the private data. 22
  • 23. FreeRDP BOOL certificate_data_replace(rdpCertificateStore* certificate_store, rdpCertificateData* certificate_data) { HANDLE fp; .... fp = CreateFileA(certificate_store->file, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); .... if (size < 1) { CloseHandle(fp); return FALSE; } .... if (!data) { fclose(fp); return FALSE; } .... } V1005 The resource was acquired using 'CreateFileA' function but was released using incompatible 'fclose' function. 23
  • 24. .NET Core Libraries (CoreFX) internal void SetSequence() { if (TypeDesc.IsRoot) return; StructMapping start = this; // find first mapping that does not have the sequence set while (!start.BaseMapping.IsSequence && start.BaseMapping != null && !start.BaseMapping.TypeDesc.IsRoot) start = start.BaseMapping; .... } V3027 The variable 'start.BaseMapping' was utilized in the logical expression before it was verified against null in the same logical expression. 24
  • 26. Spvolren void ppmWrite(char *filename, PPMFile *ppmFile) { .... FILE *fp; if (! (fp = fopen(filename, "wb")) == -1) { perror("opening image file failed"); exit(1); } .... } V562 It’s odd to compare a bool type value with a value of -1: !(fp = fopen (filename, "wb")) == - 1. 26
  • 27. Media Portal 2 return config.EpisodesLoaded || !checkEpisodesLoaded && config.BannersLoaded || !checkBannersLoaded && config.ActorsLoaded || !checkActorsLoaded; V3130 Priority of the '&&' operator is higher than that of the '||' operator. Possible missing parentheses. 27
  • 28. Как мы всё это находим?
  • 29. 29 Анализ потока данных (data-flow analysis) используется для вычисления ограничений, накладываемых на значения переменных при обработке различных конструкций языка Аннотирование методов (method annotations) предоставляет больше информации об используемых метода, чем может быть получено путем анализа только их объявления Символьное выполнение (symbolic execution) позволяет вычислять диапазоны значений переменных и проверять их состояния на разных участках кода Вывод типов (type inference) дает анализатору полную информацию о всех переменных и выражениях, встречающихся в коде Сопоставление с шаблоном (paern-based analysis) позволяет найти участки в модели кода, которые похожи на уже известные типы ошибок
  • 30. Интересно? узнайте больше на нашем сайте 🔗 Ещё больше примеров 🔗 Список всех диагностик 🔗 Подробнее о продукте Обзор возможностей