Repository navigation
Memory Safety Evaluation
Audience: Programmers
Thread Context: Contracts/NonNull/SafeCast are zero-overhead in Release and operate wherever the wrapped code runs; no dedicated thread. Thread-safety annotations are explicitly deferred (see Known Gaps).
Platform/Backend Scope: Compiler hardening differs per toolchain —
-fstack-protector-strong/_FORTIFY_SOURCE=2/full RELRO on GCC/Clang; MSVC/GSis on by default. CI sanitizers (ASan+UBSan+LSan, TSan, MSan) run on Linux.
This page records the decision (made 2026-04-06) on whether SparkEngine should wait for C++26 memory-safety features or build custom safety utilities now. Decision: build now, design for C++26 forward-compatibility via bridge macros that adopt the standard attributes automatically once compilers ship them.
The comprehensive how-to guide for using these utilities lives in Memory Safety; this page is the rationale and the integration record.
- Smart pointers ubiquitous across the codebase (
unique_ptr/shared_ptr/ComPtr). -
MemoryDebugger(Utils/MemoryDebugger.h) — leak detection, allocation tracking. -
MemoryMonitor(Utils/MemoryMonitor.h) — anomaly detection, budget enforcement. -
ScopeGuard(Utils/ScopeGuard.h) — ScopeExit/Success/Fail RAII guards. -
Assert.h— assertion macros (ASSERT_BOUNDS,ASSERT_NOT_NULL,VERIFY, etc.). -
MemoryIntegrity(Engine/Security/MemoryIntegrity.h) — anti-tamper, branch guards (see Memory Integrity System). -
Platform.h— C++26 feature detection (SPARK_HAS_CONTRACTS,SPARK_HAS_REFLECTION). - CI sanitizers: ASan+UBSan+LSan, TSan, MSan.
- clang-tidy with bugprone/modernize/performance checks.
- Custom allocators:
FrameAllocator,LockFreeRingAllocator,ObjectPool.
-
Core/Contracts.h—SPARK_EXPECTS/SPARK_ENSURES/SPARK_INVARIANTmacros that bridge to C++26[[pre]]/[[post]]/[[assert]]attributes whenSPARK_HAS_CONTRACTSis defined, falling back toASSERT_MSGin debug. -
Core/NonNull.h—Spark::NonNull<T*>: compile-timenullptr_trejection, debug-mode null assertion, zero overhead in Release. -
Core/SafeCast.h—Spark::NarrowCast<To>(from)for checked narrowing,Spark::CheckedCast<Derived*>(base)for validated downcasts.
-
-fstack-protector-strongon GCC/Clang (all configs). -
_FORTIFY_SOURCE=2on GCC/Clang (optimized builds only). -
-Wl,-z,relro,-z,nowon Linux (full RELRO). - MSVC
/GSdocumented as enabled by default.
Contracts, NonNull, and SafeCast are wired across many files.
Contracts (SPARK_EXPECTS/SPARK_ENSURES): FixedTimestepAccumulator, ModuleManager, EngineContext (RegisterSystem), FrameAllocator (AllocRaw), ObjectPool (ctor), RingBuffer (operator[]), ConstantBufferRing (Initialize), RHIAdapter (Initialize), MaterialSystem (Initialize).
NonNull<T*>: ECSystems.h — RenderSystem, PhysicsUpdateSystem, AudioUpdateSystem constructors.
CheckedCast: MovementSystem.cpp (generator downcasts), Sequencer.cpp (track downcasts).
NarrowCast: SplinePath.cpp (size_t→int conversions).
A repo-wide grep on 2026-06-08 confirms these utilities are actively referenced across engine source (
SPARK_EXPECTS/SPARK_ENSURES,NonNull<,CheckedCast/NarrowCastall return live call sites). Exact counts will drift as integration expands — treat the file list above as representative, not exhaustive.
| Gap | Rationale |
|---|---|
| Borrow checker / lifetime tracker | Poor C++ fit; wait for C++26 Profiles |
EngineContext void* rewrite |
API already type-safe via GetTypeId<T>()
|
reinterpret_cast in socket/GPU/serialization |
Necessary for those domains |
| Thread-safety annotations | Better via Clang __attribute__((guarded_by))
|
Many files with reinterpret_cast / void*
|
Inherent to C++ interop |
C++26 contracts are not expected in compilers until ~2027–2028, and Profiles (the safe subset) may not even land in C++26. The bridge macros in Contracts.h ensure smooth, edit-free adoption when the attributes arrive.
- Original entry:
.claude/knowledge/memory-safety-evaluation.md(created 2026-04-06). - Verified against codebase 2026-06-08.
Status changes / verifications found during freshening:
-
Core/Contracts.h,Core/NonNull.h,Core/SafeCast.h— all confirmed present. - Compiler hardening confirmed in
CMakeLists.txt(-fstack-protector-strong,_FORTIFY_SOURCE=2,-Wl,-z,relro,-z,now). -
SPARK_EXPECTS/SPARK_ENSURES,NonNull<, andCheckedCast/NarrowCastall return live references across engine source. - The companion how-to page
wiki/advanced/Memory-Safety.mdexists and is linked from the sidebar. - No status changes; entry is current.
Published from 2b03dc797148. Edit the canonical source in wiki/.
- Documentation
- Docs route
- Wiki index
- Guides
- Tutorials
- Samples
- Examples
- API Reference
- API route
- Reference
- Build Guide
- Dependencies
- FAQ
- Changelog
- Roadmap
- Contributing
- Code of Conduct
- Home
- FAQ
- Getting Started
- Quick-Start Tutorial
- Making Your First Game
- Making Your First Multiplayer Game
- Artist Workflow Guide
- Editor Walkthrough
- Migration Guide
- How SparkEngine Works
- Architecture Overview
- Engine Architecture Flowchart
- Creating a Game Module
- Game Modules (catalog)
- Entity Component System
- Rendering and Graphics
- Physics
- Cloth Simulation
- Audio
- Input System
- Camera System
- Scripting with AngelScript
- Visual Scripting
- AI and Navigation
- Animation
- 2D Systems
- Networking
- Dedicated Server
- Multiplayer Quick Start
- Area Server Architecture
- Scene Management
- Large World Support
- Collaborative Editing
- Coroutine System
- Event System
- Event Response System
- Job System
- UI System
- UI Layout Extensions
- Localization
- Dialogue System
- Destruction System
- Replay System
- Achievement System
- Loading System
- Mod System
- Content Delivery
- Tween System
- Memory Integrity
- Gameplay Systems
- Terrain and Procedural Generation
- Save System
- Persistence System
- Day Night Cycle and Weather
- Cinematic Sequencer
- Runtime Prefabs
- SparkEditor
- Editor Tutorials
- SparkConsole
- SparkDaemon
- Shader Pipeline
- Asset Pipeline
- Asset Validation
- Asset Migration
- Game Packaging
- Online Services
- DataTable System
- Loot and Crafting System
- CSG System
- Font System
- Timer Manager
- Movie Render Pipeline
- HLOD and World Partition
- Remote Debug System
- Selection Manager
- Asset Dependency Graph
- Editor Automation
- File Watcher
- Project Templates
- System Requirements
- VR Support
- Mobile Platform
- Accessibility
- Platform Input
- Platform Certification
- Cross-Compilation: Wine Testing
- RHI Abstraction Layer
- D3D11 Backend
- D3D12 Backend
- Vulkan Backend
- OpenGL Backend
- Metal Backend
- DXR Raytracing
- Hybrid Ray Tracing
- Upscaling (DLSS/FSR)
- Render Graph
- Shader Graph
- GPU Particles
- GPU-Driven Rendering
- Volumetric Fog
- Volumetric Clouds
- Global Illumination
- Virtual Texturing
- Water Rendering
- Clustered Lighting
- Material System
- Post-Processing
- Shadow System
- Particle System
- Decal System
- Sky and Atmosphere
- Foliage System
- Mesh Shaders
- Neural Rendering
- Configuration Reference
- Performance Tips
- Benchmark Framework
- Threading Model
- Fuzz Policy and Parser Security
- Memory Safety
- Memory Management Patterns
- Build System and CMake Modules
- Profiler and Debugging
- Performance Profiling Guide
- Telemetry System
- Crash Reporting
- Golden Image Testing
- Utilities
- Testing
- Fuzz Policy and Parser Security
- Codebase Statistics
- Codebase Health
- Error Handling Patterns
- Hot Reload Overview
- Troubleshooting
- Contributing
- Workflow Patterns
- Build Optimizations
- CI Reproducible Builds
- GitHub API and PR Checks
- Git Rebase Conflicts
- Clang-Format
- Code Quality Violations
- AI Bloat Pattern
- MinGW + Wine Cross-Compilation
- Live Editor Testing
- Engine & Renderer Landscape
- DuetOS Portability Catalog
- Five-Engine Analysis
- Eleven-Engine Analysis
- ThorVG / Unity Graphics Analysis
- Advanced Techniques Catalog
- Third-Party Library Evaluation
- Engine Viability Evaluation
- Engine Feature Recommendations
- Project Recommendations
- Mac Compatibility Analysis
- Codebase Observations
- Codebase Bloat Audit
- Test Suite Audit
- Documentation Coverage Audit
- ThirdParty Dependencies Audit
- Load Test Baseline
- Gameplay Systems Status
- SparkGame Module Status
- Stub and Abandoned Features
- Memory Integrity System
- Memory Safety Evaluation
- Hardware Acceleration Systems
- Jolt Physics Integration
- GPU/CPU Separation Plan
- Daemon Services Architecture
- Reflection & Polymorphism Refactoring Plan
- SparkBuild In-Tree
- Wine No-JobSystem Breakthrough
- Wine Role and Fallback Tiers