ONE DEFINITION RULE – HOW TO LIVE WITH IT
Alexey Kutumov
Software engineer at Kaspersky Lab
CONTENTS
2
И ЦИЯ
И Е Ы
CLANG/ODR-CHECK3
2
1
И ЦИЯ
ODR-CHECK
4
Compilation/linking
compile
compile
compile
.cpp .obj .exe
.cpp .obj
.cpp .obj
ar
.lib
link
И ЦИЯ
5
enumeration
enum Foo {
e1,
e2,
eCount
};
const char* FooToString(Foo x);
int main() {
std::cout << FooToString(e2) << std::endl;
return 0;
}
enum Foo {
e1,
eCount
};
const char xxx [] = «can you see me?!!»
const char* msg [eCount] = {
«e1»
};
const char* canYouSeeMe = xxx;
const char* FooToString(Foo x) {return msg[x];}
И ЦИЯ
6
struct A : private boost::noncopyable {
A() : x(«0») {}
const std::string x;
int y;
};
void Modify(A& a);
int main() {
A a;
Modify(a);
std::cout << a.x << std::endl;
return 0;
}
struct A : private boost::noncopyable {
A();
int x;
const std::string y;
};
void Modify(A& a) {
a.x += 1;
}
И ЦИЯ
7
pragma pack
#pragma pack(push, 1)
struct C {
char c;
uint32_t x;
};
#pragma pack(pop)
void Modify(C* c, size_t pos);
int main() {
std::string x = «0»;
C c[8] = {0};
Modify(c, 6);
std::cout << x << std::endl;
return 0;
}
struct C {
char c;
uint32_t x;
};
void Modify(C* c, size_t pos) {
c[pos].x += 1;
}
И ЦИЯ
8
К
• , ,
• + Х assert, core dump, ,
• - « »
•Code review
• - ,
•gcc –Wodr, gold –detect-odr-violations
• +
• - , false positive
•Amalgamation (sqlite)
• +
• -
• -
И Е Ы
И Е Ы
10
3.2 C++
• , , ,
• non-inline ODR-
used
• , ,
complete.
И Е Ы
11
3.2 C++
• non-inline
ODR-used.
• , , inline external
linkage, , . :
• К
• В , TU
И Е Ы
12
3.2 C++
Undefined Behavior
И Е Ы
13
Т
•А
•
•Т IDE, .
И Е Ы
14
#pragma detect_mismatch
#pragma detect_mismatch(«my_name», «my_value1») /// cpp1.cpp
#pragma detect_mismatch(«my_name», «my_value2») /// cpp2.cpp
cpp2.obj : error LNK2038: mismatch detected for 'my_name': value ‘my_value ' doesn't match value ‘my_value '
in cpp1.obj
dumpbin /ALL cpp1.obj
Linker Directives
-----------------
/FAILIFMISMATCH:"my_name=my_value1"
/DEFAULTLIB:"MSVCRTD"
/DEFAULTLIB:"OLDNAMES"
CLANG/ODR-CHECK
CLANG
16
clang
ODR-CHECK
17
Compilation/linking
compile
compile
compile
.cpp .obj .exe
.cpp .obj
.cpp .obj
ar
.lib
link
ODR-CHECK
18
Checking for ODR violations
emit-ast
emit-ast
emit-ast
.cpp .ast .ast
.cpp .ast
.cpp .ast
merge-ast
.ast
merge-ast
ODR-CHECK
19
Compilation
http://clang.llvm.org/docs/IntroductionToTheClangAST.html
http://clang.llvm.org/docs/InternalsManual.html
.cpp
token
stream
ASTContext
Preprocessor/Lexer Sema
LLVM IR
ASTFrontendAction
(CodeGenAction)
ODR-CHECK
20
Storing AST to file
.cpp
token
stream
ASTContext
Preprocessor/Lexer Sema
.ast
ASTFrontendAction
(GeneratePCHAction)
ODR-CHECK
21
Merging ASTs
cannot import unsupportОН noНО: …
.ast
.ast
.ast
.ast
ASTMergeAction
ODR-CHECK
22
Merging ASTs
• :
•
•
• ODR,
•
ODR-CHECK
23
RecursiveASTVisitor
namespace m {
struct X {
int a;
};
}
clang ../main.cpp -Xclang -ast-dump -fsyntax-only
http://clang.llvm.org/docs/RAVFrontendAction.html
ODR-CHECK
24
ASTImporter
TranslationUnitDecl (From) TranslationUnitDecl (To)
|-Node |-Node
`-Node `-Node
`-Node `-Node
ASTNodeImporter
ODR-CHECK
25
ASTNodeImporter
namespace m { /// 4. NamespaceDecl(NamedDecl, DeclContext)
namespace n { /// 3. NamespaceDecl (NamedDecl, DeclContext)
struct X { /// 2. CXXRecordDecl (..., TypeDecl, DeclContext)
struct Y { /// 1. CXXRecordDecl (..., TypeDecl, DeclContext)
int a; /// <- IMPORT
};
};
}
}
ODR-CHECK
26
StructuralEquivalenceContext
namespace m {
struct X {
int a;
long b;
};
struct Y {
X x;
int b;
};
struct Z {
int b;
};
}
namespace m {
struct X {
int a;
long b;
};
struct Y {
X x;
long b;
};
struct Z {
int a;
};
}
ODR-CHECK
27
И cmake
clang++ -DMY_SUPER_DEFINE –Wall –I/my/include –emit-ast source_file.cpp –o source_file.ast
clang++ -cc1 –emit-pch –o lib_file.ast -ast-merge source_file1.ast –ast-merge source_file2.ast
cmake ../src -DCMAKE_TOOLCHAIN_FILE=d:/tools/ClangOdrCheckToolchain.cmake –D...
make
ODR-CHECK
28
Sample output
namespace m {
struct X {
int x;
#if defined (M1)
int z;
#endif /* M1 */
};
}
ODR-CHECK
29
Sample output
In file included from d:pixelprojectsodr-checkodr-check-testsrcdatasrcm1.cpp:3:
d:pixelprojectsodr-checkodr-check-testsrcdatasrc/h1.h:11:8: warning: type 'struct m::X' has
incompatible definitions in different translation units
struct X
^
d:pixelprojectsodr-checkodr-check-testsrcdatasrc/h1.h:16:7: note: field 'z' has type 'int' here
int z;
^
d:pixelprojectsodr-checkodr-check-testsrcdatasrc/h1.h:11:8: note: no corresponding field here
struct X
^
ODR-CHECK
30
ИТ
• PoC: https://github.com/prograholic/clang/tree/odr-check
• Production Ready (milestone: check tool on some Boost libraries)
• Memory consumption (huge ASTs)
• Minimize import amount (static, unnamed namespaces, templates)
•Merge changes to clang/master
LET'S TALK?
mail: alexey.kutumov@gmail.com
twitter: @prograholic
https://github.com/prograholic/odr-check
https://github.com/prograholic/clang/tree/odr-check

More Related Content

PDF
Architecture for Massively Parallel HDL Simulations
PDF
Алексей Кутумов, Coroutines everywhere
PDF
Антон Бикинеев, Writing good std::future&lt; C++ >
PDF
TVM VTA (TSIM)
PPT
Евгений Крутько, Многопоточные вычисления, современный подход.
PPTX
Дмитрий Демчук. Кроссплатформенный краш-репорт
PDF
Антон Наумович, Система автоматической крэш-аналитики своими средствами
PPTX
C++17 now
Architecture for Massively Parallel HDL Simulations
Алексей Кутумов, Coroutines everywhere
Антон Бикинеев, Writing good std::future&lt; C++ >
TVM VTA (TSIM)
Евгений Крутько, Многопоточные вычисления, современный подход.
Дмитрий Демчук. Кроссплатформенный краш-репорт
Антон Наумович, Система автоматической крэш-аналитики своими средствами
C++17 now

What's hot (20)

PDF
Clang tidy
PDF
TensorFlow XLA RPC
PDF
Qt Rest Server
PDF
Работа с реляционными базами данных в C++
PDF
C++ Programming - 11th Study
PPTX
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
PDF
How to make a large C++-code base manageable
PDF
ESCMAScript 6: Get Ready For The Future. Now
PDF
Windbg랑 친해지기
PDF
ITGM #9 - Коварный CodeType, или от segfault'а к работающему коду
PDF
C&cpu
PDF
Rust LDN 24 7 19 Oxidising the Command Line
PPTX
Scope and closures
PDF
CppCat Checks OpenMW: Not All is Fine in the Morrowind Universe
PPT
Whats new in_csharp4
PDF
Kirk Shoop, Reactive programming in C++
PDF
[FT-11][suhorng] “Poor Man's” Undergraduate Compilers
PPTX
Best Bugs from Games: Fellow Programmers' Mistakes
PDF
Антон Бикинеев, Reflection in C++Next
PDF
Top 10 bugs in C++ open source projects, checked in 2016
Clang tidy
TensorFlow XLA RPC
Qt Rest Server
Работа с реляционными базами данных в C++
C++ Programming - 11th Study
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
How to make a large C++-code base manageable
ESCMAScript 6: Get Ready For The Future. Now
Windbg랑 친해지기
ITGM #9 - Коварный CodeType, или от segfault'а к работающему коду
C&cpu
Rust LDN 24 7 19 Oxidising the Command Line
Scope and closures
CppCat Checks OpenMW: Not All is Fine in the Morrowind Universe
Whats new in_csharp4
Kirk Shoop, Reactive programming in C++
[FT-11][suhorng] “Poor Man's” Undergraduate Compilers
Best Bugs from Games: Fellow Programmers' Mistakes
Антон Бикинеев, Reflection in C++Next
Top 10 bugs in C++ open source projects, checked in 2016
Ad

Viewers also liked (8)

PDF
Использование maven для сборки больших модульных c++ проектов на примере Odin...
PDF
Дракон в мешке: от LLVM к C++ и проблемам неопределенного поведения
PDF
DI в C++ тонкости и нюансы
PDF
Concepts lite
PDF
Функциональный микроскоп: линзы в C++
PDF
Визуализация автомобильных маршрутов
PPTX
Ranges calendar-novosibirsk-2015-08
PDF
HPX: C++11 runtime система для параллельных и распределённых вычислений
Использование maven для сборки больших модульных c++ проектов на примере Odin...
Дракон в мешке: от LLVM к C++ и проблемам неопределенного поведения
DI в C++ тонкости и нюансы
Concepts lite
Функциональный микроскоп: линзы в C++
Визуализация автомобильных маршрутов
Ranges calendar-novosibirsk-2015-08
HPX: C++11 runtime система для параллельных и распределённых вычислений
Ad

Similar to One definition rule - что это такое, и как с этим жить (20)

PDF
Facebook Glow Compiler のソースコードをグダグダ語る会
PDF
Analyzing Firebird 3.0
PDF
Analyzing Firebird 3.0
PPTX
cbybalaguruswami-e-180803051831.pptx
PPTX
cbybalaguruswami-e-180803051831.pptx
PDF
What comments hide
PDF
Rechecking Apache HTTP Server
PDF
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
PPTX
What static analyzers can do that programmers and testers cannot
PDF
OS_Compilation_Makefile_kt4jerb34834343553
PPT
EMBEDDED SYSTEMS 4&5
PDF
Picking Mushrooms after Cppcheck
PDF
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
PDF
SECCOM 2017 - Conan.io o gerente de pacote para C e C++
PPTX
C++ Core Guidelines
PPTX
A Replay Approach to Software Validation
PPTX
C Programming Homework Help
PDF
C++aptitude questions and answers
PDF
Efficient System Monitoring in Cloud Native Environments
PDF
A fresh eye on Oracle VM VirtualBox
Facebook Glow Compiler のソースコードをグダグダ語る会
Analyzing Firebird 3.0
Analyzing Firebird 3.0
cbybalaguruswami-e-180803051831.pptx
cbybalaguruswami-e-180803051831.pptx
What comments hide
Rechecking Apache HTTP Server
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
What static analyzers can do that programmers and testers cannot
OS_Compilation_Makefile_kt4jerb34834343553
EMBEDDED SYSTEMS 4&5
Picking Mushrooms after Cppcheck
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
SECCOM 2017 - Conan.io o gerente de pacote para C e C++
C++ Core Guidelines
A Replay Approach to Software Validation
C Programming Homework Help
C++aptitude questions and answers
Efficient System Monitoring in Cloud Native Environments
A fresh eye on Oracle VM VirtualBox

More from Platonov Sergey (20)

PPTX
Евгений Зуев, С++ в России: Стандарт языка и его реализация
PPTX
Алексей Кутумов, C++ без исключений, часть 3
PPTX
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
PDF
Тененёв Анатолий, Boost.Asio в алгоритмической торговле
PPTX
Павел Беликов, Опыт мигрирования крупного проекта с Windows-only на Linux
PDF
Дмитрий Кашицын, Вывод типов в динамических и не очень языках II
PDF
Дмитрий Кашицын, Вывод типов в динамических и не очень языках I
PDF
QML\Qt Quick на практике
PDF
C++ exceptions
PPTX
Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...
PPTX
Аскетичная разработка браузера
PDF
Денис Кормалев Метаобъектная система Qt
PDF
Максим Хижинский Lock-free maps
PPT
Владислав Шаклеин. Смешивание управляемого и неуправляемого C++ кода в Micros...
PDF
High quality library from scratch
PDF
С++ without new and delete
PDF
Categories for the Working C++ Programmer
PDF
Библиотека Boost с нуля на примере Boost.DLL
PPTX
Оптимизация трассирования с использованием Expression templates
PDF
Практика Lock-free. RealTime-сервер
Евгений Зуев, С++ в России: Стандарт языка и его реализация
Алексей Кутумов, C++ без исключений, часть 3
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Тененёв Анатолий, Boost.Asio в алгоритмической торговле
Павел Беликов, Опыт мигрирования крупного проекта с Windows-only на Linux
Дмитрий Кашицын, Вывод типов в динамических и не очень языках II
Дмитрий Кашицын, Вывод типов в динамических и не очень языках I
QML\Qt Quick на практике
C++ exceptions
Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...
Аскетичная разработка браузера
Денис Кормалев Метаобъектная система Qt
Максим Хижинский Lock-free maps
Владислав Шаклеин. Смешивание управляемого и неуправляемого C++ кода в Micros...
High quality library from scratch
С++ without new and delete
Categories for the Working C++ Programmer
Библиотека Boost с нуля на примере Boost.DLL
Оптимизация трассирования с использованием Expression templates
Практика Lock-free. RealTime-сервер

Recently uploaded (20)

DOCX
Modern SharePoint Intranet Templates That Boost Employee Engagement in 2025.docx
PDF
CapCut PRO for PC Crack New Download (Fully Activated 2025)
PPTX
R-Studio Crack Free Download 2025 Latest
PDF
How Tridens DevSecOps Ensures Compliance, Security, and Agility
DOC
UTEP毕业证学历认证,宾夕法尼亚克拉里恩大学毕业证未毕业
PDF
CCleaner 6.39.11548 Crack 2025 License Key
PDF
BoxLang Dynamic AWS Lambda - Japan Edition
PPTX
Plex Media Server 1.28.2.6151 With Crac5 2022 Free .
PPTX
Bista Solutions Advanced Accounting Package
PDF
What Makes a Great Data Visualization Consulting Service.pdf
PPTX
DevOpsDays Halifax 2025 - Building 10x Organizations Using Modern Productivit...
PDF
Introduction to Ragic - #1 No Code Tool For Digitalizing Your Business Proces...
PPTX
Cybersecurity: Protecting the Digital World
PDF
Practical Indispensable Project Management Tips for Delivering Successful Exp...
PPTX
Python is a high-level, interpreted programming language
PPTX
Computer Software - Technology and Livelihood Education
PDF
Internet Download Manager IDM Crack powerful download accelerator New Version...
PDF
Type Class Derivation in Scala 3 - Jose Luis Pintado Barbero
PDF
Sun and Bloombase Spitfire StoreSafe End-to-end Storage Security Solution
PPTX
Presentation by Samna Perveen And Subhan Afzal.pptx
Modern SharePoint Intranet Templates That Boost Employee Engagement in 2025.docx
CapCut PRO for PC Crack New Download (Fully Activated 2025)
R-Studio Crack Free Download 2025 Latest
How Tridens DevSecOps Ensures Compliance, Security, and Agility
UTEP毕业证学历认证,宾夕法尼亚克拉里恩大学毕业证未毕业
CCleaner 6.39.11548 Crack 2025 License Key
BoxLang Dynamic AWS Lambda - Japan Edition
Plex Media Server 1.28.2.6151 With Crac5 2022 Free .
Bista Solutions Advanced Accounting Package
What Makes a Great Data Visualization Consulting Service.pdf
DevOpsDays Halifax 2025 - Building 10x Organizations Using Modern Productivit...
Introduction to Ragic - #1 No Code Tool For Digitalizing Your Business Proces...
Cybersecurity: Protecting the Digital World
Practical Indispensable Project Management Tips for Delivering Successful Exp...
Python is a high-level, interpreted programming language
Computer Software - Technology and Livelihood Education
Internet Download Manager IDM Crack powerful download accelerator New Version...
Type Class Derivation in Scala 3 - Jose Luis Pintado Barbero
Sun and Bloombase Spitfire StoreSafe End-to-end Storage Security Solution
Presentation by Samna Perveen And Subhan Afzal.pptx

One definition rule - что это такое, и как с этим жить