llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
29.13k stars 12.01k forks source link

UBSan failure on NtCurrentTeb() #42140

Open JVApen opened 5 years ago

JVApen commented 5 years ago
Bugzilla Link 42795
Version trunk
OS Windows NT
CC @JVApen,@zygoloid,@rnk

Extended Description

UBSan seems to fail when calling NtCurrentTeb. As I don't have enough knowledge of implementation, I can't tell is this is a result of clang not initializing some information correctly OR something strange in the MSVC implementation.

// C:\DevStudio\LLVM_7_0_0\bin\clang-cl.exe /EHsc /std:c++17 -fcolor-diagnostics -ferror-limit=1 -fsanitize=undefined -fno-sanitize-recover=all m.cpp

include

include

int main(int, char *) { std::cout << static_cast<void>(NtCurrentTeb()) << std::endl; return 0; }

Result: C:\Program Files (x86)\Windows Kits\10\Include\10.0.17763.0\um\winnt.h:22426:41: runtime error: member access within null pointer of type 'NT_TIB' (aka '_NT_TIB')

rnk commented 5 years ago

NtCurrentTeb seems to exercise UB:

define FIELD_OFFSET(type, field) ((LONG)(LONG_PTR)&(((type *)0)->field))

...

__forceinline struct _TEB * NtCurrentTeb ( VOID )

{ return (struct _TEB *)__readgsqword(FIELD_OFFSET(NT_TIB, Self)); }

I think this is working as intended from clang's perspective. There may be some way to disable ubsan on this file with -fsanitize-blacklist.

JVApen commented 2 years ago

Seems to be fixed in Windows Kit 10.0.22000.0 by:

#ifdef __has_builtin
#if __has_builtin(__builtin_offsetof)
#define FIELD_OFFSET(type, field) ((LONG)__builtin_offsetof(type, field))

From what I can see in https://github.com/llvm-mirror/clang/blob/master/include/clang/Basic/Builtins.def clang doesn't provide this built-in