SlideShare a Scribd company logo
C++ in kernel mode
Roman Beleshev
About the author
• Solution architect at SolarWinds (former IASO)
• Online backup and recovery
• 17 years in production C++
About the project
• Backup is NOT just copying of files
• Customers don’t need a backup
• Minimize RPO (restore point objective)
• Minimize RTO (restore time objective)
• Driver development required
• RPO - being released
• RTO - secret project
User mode vs Kernel mode
User mode vs kernel mode: background
• Idea: reliability through restrictions
• no direct hardware access
• no direct memory access
• CPU enforced (protection rings)
• Similar for most OSes and CPUs
“If builders built buildings the way programmers write programs, then the first woodpecker
that came along would destroy civilization”
- Weinberg's Second Law
User mode vs kernel mode: relevant differences
• Code is mostly API calls
• API is different
• less functional, more verbose
• most of libraries are unavailable (including CRT)
• Drivers are callback-driven
• Performance critical
• Restrictions
• BSOD if something goes wrong
• IRQL
• spinlock 25 ms example
From C to C++
Why C++?
• Zero-overhead principle
• What you don’t use, you don’t pay for
• What you do use, you couldn’t hand code any better
• Strong typing
• Clearer, smaller and better structured code
• Less error-prone code (e.g. RAII)
• Motivates developers
Why C++?
HANDLE res1 = ::AllocateResource();
if (res1 == INVALID_HANDLE)
{
return FALSE;
}
HANDLE res2 = ::AllocateResource();
if (res2 == INVALID_HANDLE)
{
::FreeResource(res1);
return FALSE;
}
HANDLE res3 = ::AllocateResource();
if (res3 == INVALID_HANDLE)
{
::FreeResource(res2);
::FreeResource(res1);
return FALSE;
}
...
::FreeResource(res3);
::FreeResource(res2);
::FreeResource(res1);
return TRUE;
Handle res1(::AllocateResource());
Handle res2(::AllocateResource());
Handle res3(::AllocateResource());
...
BOOL result = TRUE;
HANDLE res1 = ::AllocateResource();
if (res1 == INVALID_HANDLE)
{
result = FALSE;
goto end;
}
HANDLE res2 = ::AllocateResource();
if (res2 == INVALID_HANDLE)
{
result = FALSE;
goto free_res1;
}
HANDLE res3 = ::AllocateResource();
if (res2 == INVALID_HANDLE)
{
result = FALSE;
goto free_res2;
}
...
free_res3: ::FreeResource(res3);
free_res2: ::FreeResource(res2);
free_res1: ::FreeResource(res1);
end: return result;
Compile driver in C++? Easy!
• Generate Filter Driver project
• Rename *.c file to *.cpp
• Make some corrections :)
• disable warnings
4510;4512;4610
• #undef ALLOC_PRAGMA
• extern “C” DriverEntry
What do we get for free
Pure language features and idioms
• automatic construction/destruction
• RAII
• templates
• three pillars of OOP
• strong typing
• lambdas
• constexpr
• many more (ask audience)
What is left
• Dynamic memory allocation
• Static variables initialization
• Exceptions
• Libraries
• CRT
• STL
Dynamic memory allocation
Dynamic memory allocation: solution
Overload new/delete
• globally
• for specific types
• do not forget new[] and
delete[]
// Kernel-mode allocation routines
PVOID ExAllocatePoolWithTag(
_In_ POOL_TYPE PoolType,
_In_ SIZE_T NumberOfBytes,
_In_ ULONG Tag
);
VOID ExFreePoolWithTag(
_In_ PVOID P,
_In_ ULONG Tag
);
Dynamic memory allocation: nuances
• Different pool types may be required
• Performance may be a concern
• Be careful with allocation block size
• Handle no memory case
Static objects initialization
Static variables initialization: problem
• Magic statics work
• Need to store global state
• Driver is callback-driven
• No CRT available
typedef void (*_PVFV)(void);
typedef int (*_PIFV)(void);
// C initializers
__declspec(allocate(".CRT$XIA")) _PIFV __xi_a[] = { 0 };
__declspec(allocate(".CRT$XIZ")) _PIFV __xi_z[] = { 0 };
// C++ initializers
__declspec(allocate(".CRT$XCA")) _PVFV __xc_a[] = { 0 };
__declspec(allocate(".CRT$XCZ")) _PVFV __xc_z[] = { 0 };
// C pre-terminators
__declspec(allocate(".CRT$XPA")) _PVFV __xp_a[] = { 0 };
__declspec(allocate(".CRT$XPZ")) _PVFV __xp_z[] = { 0 };
// C terminators
__declspec(allocate(".CRT$XTA")) _PVFV __xt_a[] = { 0 };
__declspec(allocate(".CRT$XTZ")) _PVFV __xt_z[] = { 0 };
Static variables initialization: solutions
• Singleton(s) based on magic statics
• how to uninitialize?
• Implement part of CRT
• looks elegant and native
• works if there are no initialization parameters
• Manually construct global state object(s)
• dynamically allocated
• in-place constructed
Exceptions
Exceptions: SEH
• Native Windows mechanism
• Compiler + API
• Performs stack unwinding
void WINAPI RaiseException(
_In_ DWORD dwExceptionCode,
_In_ DWORD dwExceptionFlags,
_In_ DWORD nNumberOfArguments,
_In_ const ULONG_PTR *lpArguments
);
// Whole picture
__try
{
::RaiseException(ERROR_CODE, 0, 0, NULL);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
PEXCEPTION_POINTERS e = ::GetExceptionInformation();
HandleException(e->ExceptionRecord->ExceptionCode);
}
Exceptions: C++
• C++ exceptions are based on SEH
• Throw:
• allocates memory and constructs exception object
• wraps C++ exception into SEH exception
• calls RaiseException
• Exception handler
• calls destructors
• filters exception through catch blocks
• decides if to pass exception
Exceptions: solution (limited)
• SEH is unavoidable
• Calling destructors on stack unwind is sufficient
• Turn on SEH compiler option
• Implement __CxxFrameHandler3
• Throw using function call
• Catch using SEH syntax in driver callbacks
• Possibly, use <system_error>
Libraries
CRT
• Partially available
• all headers are in place
• unsafe functions issue linker errors
• floating point
• malloc/free, I/O
• Use kernel API (RtlXxx)
• Reimplement or borrow
STL
• Some parts depend on CRT (I/O)
• Prognosis: good (for the rest)
• Brute-force attempt failed
• Alternative STL implementation
What’s next?
• Secret project is in progress
• Kernel-mode framework
• Kernel-mode coding guidelines
• Possibly open-source
Useful links
User-kernel modes
https://docs.microsoft.com/en-us/windows-hardware/drivers/gettingstarted/user-mode-and-kernel-mode
https://en.wikibooks.org/wiki/Windows_Programming/User_Mode_vs_Kernel_Mode
https://blog.codinghorror.com/understanding-user-and-kernel-mode/
Global objects initialization
https://msdn.microsoft.com/en-us/library/bb918180.aspx
https://gist.github.com/mmozeiko/ae38aeb10add7cb66be4c00f24f8e688
Exceptions
https://www.codeproject.com/Articles/22801/Drivers-Exceptions-and-C
Questions?
roman.beleshev@solarwinds.com
The SolarWinds and SolarWinds MSP trademarks are the
exclusive property of SolarWinds MSP UK Ltd. or its affiliates and
may be registered or pending registration with the U.S. Patent
and Trademark Office and in other countries. All other
SolarWinds MSP UK and SolarWinds trademarks, service marks,
and logos may be common law marks or are registered or
pending registration. All other trademarks mentioned herein are
used for identification purposes only and are trademarks (and
may be registered trademarks) of their respective companies.

More Related Content

What's hot (20)

PDF
Q2.12: Debugging with GDB
Linaro
 
PPTX
OpenCL Heterogeneous Parallel Computing
João Paulo Leonidas Fernandes Dias da Silva
 
PDF
Efficient Bytecode Analysis: Linespeed Shellcode Detection
Georg Wicherski
 
PPTX
Optimizing Communicating Event-Loop Languages with Truffle
Stefan Marr
 
PDF
OpenCL Programming 101
Yoss Cohen
 
PPTX
node.js and native code extensions by example
Philipp Fehre
 
PPTX
Introduction to .NET
Lorenzo Dematté
 
PDF
[231] the simplicity of cluster apps with circuit
NAVER D2
 
PDF
Metasepi team meeting #7: Snatch application on tiny OS
Kiwamu Okabe
 
PDF
Solving some of the scalability problems at booking.com
Ivan Kruglov
 
PDF
OSNoise Tracer: Who Is Stealing My CPU Time?
ScyllaDB
 
PDF
Run Go applications on Pico using TinyGo
Yu-Shuan Hsieh
 
PPTX
Choosing the right parallel compute architecture
corehard_by
 
PDF
Introduction to OpenCL
Unai Lopez-Novoa
 
PDF
The impact of supercomputers on MSR
Yasutaka Kamei
 
PDF
Introduction to asynchronous DB access using Node.js and MongoDB
Adrien Joly
 
PDF
ooc - OSDC 2010 - Amos Wenger
Amos Wenger
 
PDF
深層学習フレームワークにおけるIntel CPU/富岳向け最適化法
MITSUNARI Shigeo
 
PDF
"Развитие ветки PHP-7"
Badoo Development
 
PDF
Porting and Optimization of Numerical Libraries for ARM SVE
Linaro
 
Q2.12: Debugging with GDB
Linaro
 
OpenCL Heterogeneous Parallel Computing
João Paulo Leonidas Fernandes Dias da Silva
 
Efficient Bytecode Analysis: Linespeed Shellcode Detection
Georg Wicherski
 
Optimizing Communicating Event-Loop Languages with Truffle
Stefan Marr
 
OpenCL Programming 101
Yoss Cohen
 
node.js and native code extensions by example
Philipp Fehre
 
Introduction to .NET
Lorenzo Dematté
 
[231] the simplicity of cluster apps with circuit
NAVER D2
 
Metasepi team meeting #7: Snatch application on tiny OS
Kiwamu Okabe
 
Solving some of the scalability problems at booking.com
Ivan Kruglov
 
OSNoise Tracer: Who Is Stealing My CPU Time?
ScyllaDB
 
Run Go applications on Pico using TinyGo
Yu-Shuan Hsieh
 
Choosing the right parallel compute architecture
corehard_by
 
Introduction to OpenCL
Unai Lopez-Novoa
 
The impact of supercomputers on MSR
Yasutaka Kamei
 
Introduction to asynchronous DB access using Node.js and MongoDB
Adrien Joly
 
ooc - OSDC 2010 - Amos Wenger
Amos Wenger
 
深層学習フレームワークにおけるIntel CPU/富岳向け最適化法
MITSUNARI Shigeo
 
"Развитие ветки PHP-7"
Badoo Development
 
Porting and Optimization of Numerical Libraries for ARM SVE
Linaro
 

Viewers also liked (20)

PPTX
Ускоряем сборку С++ проектов. Практика использования unity-сборок
corehard_by
 
PPTX
C++ в играх, больших и не очень
corehard_by
 
PPTX
Mixing C++ & Python II: Pybind11
corehard_by
 
PDF
C++Now Trip Report
corehard_by
 
PPTX
C++ and Assembly: Debugging and Reverse Engineering
corehard_by
 
PPTX
Поиск уязвимостей с использованием статического анализа кода
corehard_by
 
PPTX
Субъекторная модель
corehard_by
 
PDF
Обработка потока данных на примере deep packet inspection: внутренняя архитек...
corehard_by
 
PDF
The beast is becoming functional
corehard_by
 
PPTX
Benchmark it
corehard_by
 
PPTX
Abseil - let the savior come?
corehard_by
 
PDF
Actors for fun and profit
corehard_by
 
PDF
Restinio - header-only http and websocket server
corehard_by
 
PDF
MxxRu::externals: Repositoryless Dependency Manager
corehard_by
 
PDF
(Не)чёткий поиск
corehard_by
 
PPTX
Analysis and interpretation of monitoring data
corehard_by
 
PPTX
Battle: BDD vs notBDD
COMAQA.BY
 
PDF
Метаданные для кластера: гонка key-value-героев / Руслан Рагимов, Светлана Ла...
Ontico
 
PPTX
Слои тестового фрамеворка. Что? Где? Когда?
COMAQA.BY
 
PDF
Честное перформанс-тестирование / Дмитрий Пивоваров (ZeroTurnaround)
Ontico
 
Ускоряем сборку С++ проектов. Практика использования unity-сборок
corehard_by
 
C++ в играх, больших и не очень
corehard_by
 
Mixing C++ & Python II: Pybind11
corehard_by
 
C++Now Trip Report
corehard_by
 
C++ and Assembly: Debugging and Reverse Engineering
corehard_by
 
Поиск уязвимостей с использованием статического анализа кода
corehard_by
 
Субъекторная модель
corehard_by
 
Обработка потока данных на примере deep packet inspection: внутренняя архитек...
corehard_by
 
The beast is becoming functional
corehard_by
 
Benchmark it
corehard_by
 
Abseil - let the savior come?
corehard_by
 
Actors for fun and profit
corehard_by
 
Restinio - header-only http and websocket server
corehard_by
 
MxxRu::externals: Repositoryless Dependency Manager
corehard_by
 
(Не)чёткий поиск
corehard_by
 
Analysis and interpretation of monitoring data
corehard_by
 
Battle: BDD vs notBDD
COMAQA.BY
 
Метаданные для кластера: гонка key-value-героев / Руслан Рагимов, Светлана Ла...
Ontico
 
Слои тестового фрамеворка. Что? Где? Когда?
COMAQA.BY
 
Честное перформанс-тестирование / Дмитрий Пивоваров (ZeroTurnaround)
Ontico
 
Ad

Similar to C++ in kernel mode (20)

PDF
Building High Performance Android Applications in Java and C++
Kenneth Geisshirt
 
PDF
Tips and tricks for building high performance android apps using native code
Kenneth Geisshirt
 
PDF
Typhoon Managed Execution Toolkit
Dimitry Snezhkov
 
PDF
MattsonTutorialSC14.pdf
George Papaioannou
 
PPTX
MattsonTutorialSC14.pptx
gopikahari7
 
PPTX
Ahead-Of-Time Compilation of Java Applications
Nikita Lipsky
 
PDF
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
Sang Don Kim
 
PDF
Code lifecycle in the jvm - TopConf Linz
Ivan Krylov
 
PDF
차세대컴파일러, VM의미래: 애플 오픈소스 LLVM
Jung Kim
 
PPTX
JIT vs. AOT: Unity And Conflict of Dynamic and Static Compilers
Nikita Lipsky
 
PDF
NSC #2 - D3 02 - Peter Hlavaty - Attack on the Core
NoSuchCon
 
PPTX
Effective C++
Andrey Karpov
 
PDF
Surge2012
davidapacheco
 
PPTX
Week1 Electronic System-level ESL Design and SystemC Begin
敬倫 林
 
PDF
TMPA-2017: A Survey of High-Performance Computing for Software Verification
Iosif Itkin
 
PPTX
Practical Windows Kernel Exploitation
zeroSteiner
 
PPTX
lecture03_EmbeddedSoftware for Beginners
MahmoudElsamanty
 
PDF
Nodejs - Should Ruby Developers Care?
Felix Geisendörfer
 
PDF
Raffaele Rialdi
CodeFest
 
PDF
Finding Xori: Malware Analysis Triage with Automated Disassembly
Priyanka Aash
 
Building High Performance Android Applications in Java and C++
Kenneth Geisshirt
 
Tips and tricks for building high performance android apps using native code
Kenneth Geisshirt
 
Typhoon Managed Execution Toolkit
Dimitry Snezhkov
 
MattsonTutorialSC14.pdf
George Papaioannou
 
MattsonTutorialSC14.pptx
gopikahari7
 
Ahead-Of-Time Compilation of Java Applications
Nikita Lipsky
 
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
Sang Don Kim
 
Code lifecycle in the jvm - TopConf Linz
Ivan Krylov
 
차세대컴파일러, VM의미래: 애플 오픈소스 LLVM
Jung Kim
 
JIT vs. AOT: Unity And Conflict of Dynamic and Static Compilers
Nikita Lipsky
 
NSC #2 - D3 02 - Peter Hlavaty - Attack on the Core
NoSuchCon
 
Effective C++
Andrey Karpov
 
Surge2012
davidapacheco
 
Week1 Electronic System-level ESL Design and SystemC Begin
敬倫 林
 
TMPA-2017: A Survey of High-Performance Computing for Software Verification
Iosif Itkin
 
Practical Windows Kernel Exploitation
zeroSteiner
 
lecture03_EmbeddedSoftware for Beginners
MahmoudElsamanty
 
Nodejs - Should Ruby Developers Care?
Felix Geisendörfer
 
Raffaele Rialdi
CodeFest
 
Finding Xori: Malware Analysis Triage with Automated Disassembly
Priyanka Aash
 
Ad

More from corehard_by (20)

PPTX
C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...
corehard_by
 
PPTX
C++ CoreHard Autumn 2018. Что должен знать каждый C++ программист или Как про...
corehard_by
 
PDF
C++ CoreHard Autumn 2018. Actors vs CSP vs Tasks vs ... - Евгений Охотников
corehard_by
 
PPTX
C++ CoreHard Autumn 2018. Знай свое "железо": иерархия памяти - Александр Титов
corehard_by
 
PPTX
C++ CoreHard Autumn 2018. Информационная безопасность и разработка ПО - Евген...
corehard_by
 
PPTX
C++ CoreHard Autumn 2018. Заглядываем под капот «Поясов по C++» - Илья Шишков
corehard_by
 
PPTX
C++ CoreHard Autumn 2018. Ускорение сборки C++ проектов, способы и последстви...
corehard_by
 
PPTX
C++ CoreHard Autumn 2018. Метаклассы: воплощаем мечты в реальность - Сергей С...
corehard_by
 
PPTX
C++ CoreHard Autumn 2018. Что не умеет оптимизировать компилятор - Александр ...
corehard_by
 
PPTX
C++ CoreHard Autumn 2018. Кодогенерация C++ кроссплатформенно. Продолжение - ...
corehard_by
 
PDF
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
corehard_by
 
PPTX
C++ CoreHard Autumn 2018. Обработка списков на C++ в функциональном стиле - В...
corehard_by
 
PPTX
C++ Corehard Autumn 2018. Обучаем на Python, применяем на C++ - Павел Филонов
corehard_by
 
PDF
C++ CoreHard Autumn 2018. Asynchronous programming with ranges - Ivan Čukić
corehard_by
 
PDF
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
corehard_by
 
PDF
C++ CoreHard Autumn 2018. Полезный constexpr - Антон Полухин
corehard_by
 
PDF
C++ CoreHard Autumn 2018. Text Formatting For a Future Range-Based Standard L...
corehard_by
 
PPTX
Исключительная модель памяти. Алексей Ткаченко ➠ CoreHard Autumn 2019
corehard_by
 
PDF
Как помочь и как помешать компилятору. Андрей Олейников ➠ CoreHard Autumn 2019
corehard_by
 
PDF
Автоматизируй это. Кирилл Тихонов ➠ CoreHard Autumn 2019
corehard_by
 
C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...
corehard_by
 
C++ CoreHard Autumn 2018. Что должен знать каждый C++ программист или Как про...
corehard_by
 
C++ CoreHard Autumn 2018. Actors vs CSP vs Tasks vs ... - Евгений Охотников
corehard_by
 
C++ CoreHard Autumn 2018. Знай свое "железо": иерархия памяти - Александр Титов
corehard_by
 
C++ CoreHard Autumn 2018. Информационная безопасность и разработка ПО - Евген...
corehard_by
 
C++ CoreHard Autumn 2018. Заглядываем под капот «Поясов по C++» - Илья Шишков
corehard_by
 
C++ CoreHard Autumn 2018. Ускорение сборки C++ проектов, способы и последстви...
corehard_by
 
C++ CoreHard Autumn 2018. Метаклассы: воплощаем мечты в реальность - Сергей С...
corehard_by
 
C++ CoreHard Autumn 2018. Что не умеет оптимизировать компилятор - Александр ...
corehard_by
 
C++ CoreHard Autumn 2018. Кодогенерация C++ кроссплатформенно. Продолжение - ...
corehard_by
 
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
corehard_by
 
C++ CoreHard Autumn 2018. Обработка списков на C++ в функциональном стиле - В...
corehard_by
 
C++ Corehard Autumn 2018. Обучаем на Python, применяем на C++ - Павел Филонов
corehard_by
 
C++ CoreHard Autumn 2018. Asynchronous programming with ranges - Ivan Čukić
corehard_by
 
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
corehard_by
 
C++ CoreHard Autumn 2018. Полезный constexpr - Антон Полухин
corehard_by
 
C++ CoreHard Autumn 2018. Text Formatting For a Future Range-Based Standard L...
corehard_by
 
Исключительная модель памяти. Алексей Ткаченко ➠ CoreHard Autumn 2019
corehard_by
 
Как помочь и как помешать компилятору. Андрей Олейников ➠ CoreHard Autumn 2019
corehard_by
 
Автоматизируй это. Кирилл Тихонов ➠ CoreHard Autumn 2019
corehard_by
 

Recently uploaded (20)

PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PPTX
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PDF
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
PDF
The Future of Artificial Intelligence (AI)
Mukul
 
PDF
Build with AI and GDG Cloud Bydgoszcz- ADK .pdf
jaroslawgajewski1
 
PDF
introduction to computer hardware and sofeware
chauhanshraddha2007
 
PDF
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
PDF
NewMind AI Weekly Chronicles – July’25, Week III
NewMind AI
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PPTX
Simple and concise overview about Quantum computing..pptx
mughal641
 
PDF
TrustArc Webinar - Navigating Data Privacy in LATAM: Laws, Trends, and Compli...
TrustArc
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
RAT Builders - How to Catch Them All [DeepSec 2024]
malmoeb
 
PDF
State-Dependent Conformal Perception Bounds for Neuro-Symbolic Verification
Ivan Ruchkin
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
The Future of Artificial Intelligence (AI)
Mukul
 
Build with AI and GDG Cloud Bydgoszcz- ADK .pdf
jaroslawgajewski1
 
introduction to computer hardware and sofeware
chauhanshraddha2007
 
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
NewMind AI Weekly Chronicles – July’25, Week III
NewMind AI
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
Simple and concise overview about Quantum computing..pptx
mughal641
 
TrustArc Webinar - Navigating Data Privacy in LATAM: Laws, Trends, and Compli...
TrustArc
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
RAT Builders - How to Catch Them All [DeepSec 2024]
malmoeb
 
State-Dependent Conformal Perception Bounds for Neuro-Symbolic Verification
Ivan Ruchkin
 

C++ in kernel mode

  • 1. C++ in kernel mode Roman Beleshev
  • 2. About the author • Solution architect at SolarWinds (former IASO) • Online backup and recovery • 17 years in production C++
  • 3. About the project • Backup is NOT just copying of files • Customers don’t need a backup • Minimize RPO (restore point objective) • Minimize RTO (restore time objective) • Driver development required • RPO - being released • RTO - secret project
  • 4. User mode vs Kernel mode
  • 5. User mode vs kernel mode: background • Idea: reliability through restrictions • no direct hardware access • no direct memory access • CPU enforced (protection rings) • Similar for most OSes and CPUs “If builders built buildings the way programmers write programs, then the first woodpecker that came along would destroy civilization” - Weinberg's Second Law
  • 6. User mode vs kernel mode: relevant differences • Code is mostly API calls • API is different • less functional, more verbose • most of libraries are unavailable (including CRT) • Drivers are callback-driven • Performance critical • Restrictions • BSOD if something goes wrong • IRQL • spinlock 25 ms example
  • 7. From C to C++
  • 8. Why C++? • Zero-overhead principle • What you don’t use, you don’t pay for • What you do use, you couldn’t hand code any better • Strong typing • Clearer, smaller and better structured code • Less error-prone code (e.g. RAII) • Motivates developers
  • 9. Why C++? HANDLE res1 = ::AllocateResource(); if (res1 == INVALID_HANDLE) { return FALSE; } HANDLE res2 = ::AllocateResource(); if (res2 == INVALID_HANDLE) { ::FreeResource(res1); return FALSE; } HANDLE res3 = ::AllocateResource(); if (res3 == INVALID_HANDLE) { ::FreeResource(res2); ::FreeResource(res1); return FALSE; } ... ::FreeResource(res3); ::FreeResource(res2); ::FreeResource(res1); return TRUE; Handle res1(::AllocateResource()); Handle res2(::AllocateResource()); Handle res3(::AllocateResource()); ... BOOL result = TRUE; HANDLE res1 = ::AllocateResource(); if (res1 == INVALID_HANDLE) { result = FALSE; goto end; } HANDLE res2 = ::AllocateResource(); if (res2 == INVALID_HANDLE) { result = FALSE; goto free_res1; } HANDLE res3 = ::AllocateResource(); if (res2 == INVALID_HANDLE) { result = FALSE; goto free_res2; } ... free_res3: ::FreeResource(res3); free_res2: ::FreeResource(res2); free_res1: ::FreeResource(res1); end: return result;
  • 10. Compile driver in C++? Easy! • Generate Filter Driver project • Rename *.c file to *.cpp • Make some corrections :) • disable warnings 4510;4512;4610 • #undef ALLOC_PRAGMA • extern “C” DriverEntry
  • 11. What do we get for free Pure language features and idioms • automatic construction/destruction • RAII • templates • three pillars of OOP • strong typing • lambdas • constexpr • many more (ask audience)
  • 12. What is left • Dynamic memory allocation • Static variables initialization • Exceptions • Libraries • CRT • STL
  • 14. Dynamic memory allocation: solution Overload new/delete • globally • for specific types • do not forget new[] and delete[] // Kernel-mode allocation routines PVOID ExAllocatePoolWithTag( _In_ POOL_TYPE PoolType, _In_ SIZE_T NumberOfBytes, _In_ ULONG Tag ); VOID ExFreePoolWithTag( _In_ PVOID P, _In_ ULONG Tag );
  • 15. Dynamic memory allocation: nuances • Different pool types may be required • Performance may be a concern • Be careful with allocation block size • Handle no memory case
  • 17. Static variables initialization: problem • Magic statics work • Need to store global state • Driver is callback-driven • No CRT available typedef void (*_PVFV)(void); typedef int (*_PIFV)(void); // C initializers __declspec(allocate(".CRT$XIA")) _PIFV __xi_a[] = { 0 }; __declspec(allocate(".CRT$XIZ")) _PIFV __xi_z[] = { 0 }; // C++ initializers __declspec(allocate(".CRT$XCA")) _PVFV __xc_a[] = { 0 }; __declspec(allocate(".CRT$XCZ")) _PVFV __xc_z[] = { 0 }; // C pre-terminators __declspec(allocate(".CRT$XPA")) _PVFV __xp_a[] = { 0 }; __declspec(allocate(".CRT$XPZ")) _PVFV __xp_z[] = { 0 }; // C terminators __declspec(allocate(".CRT$XTA")) _PVFV __xt_a[] = { 0 }; __declspec(allocate(".CRT$XTZ")) _PVFV __xt_z[] = { 0 };
  • 18. Static variables initialization: solutions • Singleton(s) based on magic statics • how to uninitialize? • Implement part of CRT • looks elegant and native • works if there are no initialization parameters • Manually construct global state object(s) • dynamically allocated • in-place constructed
  • 20. Exceptions: SEH • Native Windows mechanism • Compiler + API • Performs stack unwinding void WINAPI RaiseException( _In_ DWORD dwExceptionCode, _In_ DWORD dwExceptionFlags, _In_ DWORD nNumberOfArguments, _In_ const ULONG_PTR *lpArguments ); // Whole picture __try { ::RaiseException(ERROR_CODE, 0, 0, NULL); } __except(EXCEPTION_EXECUTE_HANDLER) { PEXCEPTION_POINTERS e = ::GetExceptionInformation(); HandleException(e->ExceptionRecord->ExceptionCode); }
  • 21. Exceptions: C++ • C++ exceptions are based on SEH • Throw: • allocates memory and constructs exception object • wraps C++ exception into SEH exception • calls RaiseException • Exception handler • calls destructors • filters exception through catch blocks • decides if to pass exception
  • 22. Exceptions: solution (limited) • SEH is unavoidable • Calling destructors on stack unwind is sufficient • Turn on SEH compiler option • Implement __CxxFrameHandler3 • Throw using function call • Catch using SEH syntax in driver callbacks • Possibly, use <system_error>
  • 24. CRT • Partially available • all headers are in place • unsafe functions issue linker errors • floating point • malloc/free, I/O • Use kernel API (RtlXxx) • Reimplement or borrow
  • 25. STL • Some parts depend on CRT (I/O) • Prognosis: good (for the rest) • Brute-force attempt failed • Alternative STL implementation
  • 26. What’s next? • Secret project is in progress • Kernel-mode framework • Kernel-mode coding guidelines • Possibly open-source
  • 27. Useful links User-kernel modes https://docs.microsoft.com/en-us/windows-hardware/drivers/gettingstarted/user-mode-and-kernel-mode https://en.wikibooks.org/wiki/Windows_Programming/User_Mode_vs_Kernel_Mode https://blog.codinghorror.com/understanding-user-and-kernel-mode/ Global objects initialization https://msdn.microsoft.com/en-us/library/bb918180.aspx https://gist.github.com/mmozeiko/ae38aeb10add7cb66be4c00f24f8e688 Exceptions https://www.codeproject.com/Articles/22801/Drivers-Exceptions-and-C
  • 29. The SolarWinds and SolarWinds MSP trademarks are the exclusive property of SolarWinds MSP UK Ltd. or its affiliates and may be registered or pending registration with the U.S. Patent and Trademark Office and in other countries. All other SolarWinds MSP UK and SolarWinds trademarks, service marks, and logos may be common law marks or are registered or pending registration. All other trademarks mentioned herein are used for identification purposes only and are trademarks (and may be registered trademarks) of their respective companies.