From 096e268764397f781e72619e3b5f546d5786cae1 Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Wed, 5 Aug 2020 10:21:21 +0200 Subject: Avoid UB in moc generated code Introduce a Q_OFFSETOF() macro that uses the optional support of offsetof() for non standard layout types and disables the corresponding compiler warnings. All our supported compilers support offsetof() on non standard layout types. Use the macro to do the offset calculations required in moc generated code to replace a manual offset calculation that was dereferencing a null pointer. Change-Id: I4aab3af3c8bbaa90372f2234aa1cf8399d023c22 Reviewed-by: Thiago Macieira --- src/corelib/global/qglobal.h | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'src/corelib/global/qglobal.h') diff --git a/src/corelib/global/qglobal.h b/src/corelib/global/qglobal.h index 539e3e7cda..94de9fd79e 100644 --- a/src/corelib/global/qglobal.h +++ b/src/corelib/global/qglobal.h @@ -1316,6 +1316,17 @@ template struct QEnableIf { typedef T Type; }; #define QT_DEFINE_PLATFORM_INTERFACE(...) QT_OVERLOADED_MACRO(QT_DEFINE_PLATFORM_INTERFACE, QPlatformInterface, __VA_ARGS__) #define QT_DEFINE_PRIVATE_PLATFORM_INTERFACE(...) QT_OVERLOADED_MACRO(QT_DEFINE_PLATFORM_INTERFACE, QPlatformInterface::Private, __VA_ARGS__) +// This macro can be used to calculate member offsets for types with a non standard layout. +// It uses the fact that offsetof() is allowed to support those types since C++17 as an optional +// feature. All our compilers do support this, but some issue a warning, so we wrap the offsetof() +// call in a macro that disables the compiler warning. +#define Q_OFFSETOF(Class, member) \ + []() -> size_t { \ + QT_WARNING_PUSH QT_WARNING_DISABLE_INVALID_OFFSETOF \ + return offsetof(Class, member); \ + QT_WARNING_POP \ + }() + QT_END_NAMESPACE // We need to keep QTypeInfo, QSysInfo, QFlags, qDebug & family in qglobal.h for compatibility with Qt 4. -- cgit v1.2.3