Importing rustc-1.45.2
Change-Id: Idd187dd729f3089d9529753a17db5fbb40bacdeb
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/CMakeLists.txt b/src/llvm-project/compiler-rt/lib/sanitizer_common/CMakeLists.txt
index e34cdae..0b9c4dc 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/CMakeLists.txt
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/CMakeLists.txt
@@ -2,89 +2,92 @@
# These components are shared between AddressSanitizer and ThreadSanitizer.
set(SANITIZER_SOURCES_NOTERMINATION
- sanitizer_allocator.cc
- sanitizer_common.cc
- sanitizer_deadlock_detector1.cc
- sanitizer_deadlock_detector2.cc
- sanitizer_errno.cc
- sanitizer_file.cc
- sanitizer_flags.cc
- sanitizer_flag_parser.cc
- sanitizer_fuchsia.cc
- sanitizer_libc.cc
- sanitizer_libignore.cc
- sanitizer_linux.cc
- sanitizer_linux_s390.cc
- sanitizer_mac.cc
- sanitizer_netbsd.cc
- sanitizer_openbsd.cc
- sanitizer_persistent_allocator.cc
- sanitizer_platform_limits_freebsd.cc
- sanitizer_platform_limits_linux.cc
- sanitizer_platform_limits_netbsd.cc
- sanitizer_platform_limits_openbsd.cc
- sanitizer_platform_limits_posix.cc
- sanitizer_platform_limits_solaris.cc
- sanitizer_posix.cc
- sanitizer_printf.cc
- sanitizer_procmaps_common.cc
- sanitizer_procmaps_bsd.cc
- sanitizer_procmaps_linux.cc
- sanitizer_procmaps_mac.cc
- sanitizer_procmaps_solaris.cc
- sanitizer_rtems.cc
- sanitizer_solaris.cc
- sanitizer_stoptheworld_mac.cc
- sanitizer_suppressions.cc
- sanitizer_tls_get_addr.cc
- sanitizer_thread_registry.cc
- sanitizer_type_traits.cc
- sanitizer_win.cc
+ sanitizer_allocator.cpp
+ sanitizer_common.cpp
+ sanitizer_deadlock_detector1.cpp
+ sanitizer_deadlock_detector2.cpp
+ sanitizer_errno.cpp
+ sanitizer_file.cpp
+ sanitizer_flags.cpp
+ sanitizer_flag_parser.cpp
+ sanitizer_fuchsia.cpp
+ sanitizer_libc.cpp
+ sanitizer_libignore.cpp
+ sanitizer_linux.cpp
+ sanitizer_linux_s390.cpp
+ sanitizer_mac.cpp
+ sanitizer_netbsd.cpp
+ sanitizer_openbsd.cpp
+ sanitizer_persistent_allocator.cpp
+ sanitizer_platform_limits_freebsd.cpp
+ sanitizer_platform_limits_linux.cpp
+ sanitizer_platform_limits_netbsd.cpp
+ sanitizer_platform_limits_openbsd.cpp
+ sanitizer_platform_limits_posix.cpp
+ sanitizer_platform_limits_solaris.cpp
+ sanitizer_posix.cpp
+ sanitizer_printf.cpp
+ sanitizer_procmaps_common.cpp
+ sanitizer_procmaps_bsd.cpp
+ sanitizer_procmaps_linux.cpp
+ sanitizer_procmaps_mac.cpp
+ sanitizer_procmaps_solaris.cpp
+ sanitizer_rtems.cpp
+ sanitizer_solaris.cpp
+ sanitizer_stoptheworld_mac.cpp
+ sanitizer_suppressions.cpp
+ sanitizer_tls_get_addr.cpp
+ sanitizer_thread_registry.cpp
+ sanitizer_type_traits.cpp
+ sanitizer_win.cpp
)
set(SANITIZER_SOURCES
- ${SANITIZER_SOURCES_NOTERMINATION} sanitizer_termination.cc)
+ ${SANITIZER_SOURCES_NOTERMINATION}
+ sanitizer_termination.cpp
+ )
# Libc functions stubs. These sources should be linked instead of
# SANITIZER_LIBCDEP_SOURCES when sanitizer_common library must not depend on
# libc.
set(SANITIZER_NOLIBC_SOURCES
- sanitizer_common_nolibc.cc)
+ sanitizer_common_nolibc.cpp
+ )
set(SANITIZER_LIBCDEP_SOURCES
- sanitizer_common_libcdep.cc
- sanitizer_allocator_checks.cc
- sanitizer_linux_libcdep.cc
- sanitizer_mac_libcdep.cc
- sanitizer_posix_libcdep.cc
- sanitizer_stoptheworld_linux_libcdep.cc
- sanitizer_stoptheworld_netbsd_libcdep.cc
+ sanitizer_common_libcdep.cpp
+ sanitizer_allocator_checks.cpp
+ sanitizer_linux_libcdep.cpp
+ sanitizer_mac_libcdep.cpp
+ sanitizer_posix_libcdep.cpp
+ sanitizer_stoptheworld_linux_libcdep.cpp
+ sanitizer_stoptheworld_netbsd_libcdep.cpp
)
set(SANITIZER_COVERAGE_SOURCES
- sancov_flags.cc
- sanitizer_coverage_fuchsia.cc
- sanitizer_coverage_libcdep_new.cc
- sanitizer_coverage_win_sections.cc
+ sancov_flags.cpp
+ sanitizer_coverage_fuchsia.cpp
+ sanitizer_coverage_libcdep_new.cpp
+ sanitizer_coverage_win_sections.cpp
)
set(SANITIZER_SYMBOLIZER_SOURCES
- sanitizer_allocator_report.cc
- sanitizer_stackdepot.cc
- sanitizer_stacktrace.cc
- sanitizer_stacktrace_libcdep.cc
- sanitizer_stacktrace_printer.cc
- sanitizer_stacktrace_sparc.cc
- sanitizer_symbolizer.cc
- sanitizer_symbolizer_libbacktrace.cc
- sanitizer_symbolizer_libcdep.cc
- sanitizer_symbolizer_mac.cc
- sanitizer_symbolizer_markup.cc
- sanitizer_symbolizer_posix_libcdep.cc
- sanitizer_symbolizer_report.cc
- sanitizer_symbolizer_win.cc
- sanitizer_unwind_linux_libcdep.cc
- sanitizer_unwind_win.cc
+ sanitizer_allocator_report.cpp
+ sanitizer_stackdepot.cpp
+ sanitizer_stacktrace.cpp
+ sanitizer_stacktrace_libcdep.cpp
+ sanitizer_stacktrace_printer.cpp
+ sanitizer_stacktrace_sparc.cpp
+ sanitizer_symbolizer.cpp
+ sanitizer_symbolizer_libbacktrace.cpp
+ sanitizer_symbolizer_libcdep.cpp
+ sanitizer_symbolizer_mac.cpp
+ sanitizer_symbolizer_markup.cpp
+ sanitizer_symbolizer_posix_libcdep.cpp
+ sanitizer_symbolizer_report.cpp
+ sanitizer_symbolizer_win.cpp
+ sanitizer_unwind_linux_libcdep.cpp
+ sanitizer_unwind_win.cpp
)
# Explicitly list all sanitizer_common headers. Not all of these are
@@ -278,27 +281,27 @@
add_compiler_rt_object_libraries(SanitizerCommonWeakInterception
${SANITIZER_COMMON_SUPPORTED_OS}
ARCHS ${SANITIZER_COMMON_SUPPORTED_ARCH}
- SOURCES sanitizer_win_weak_interception.cc
+ SOURCES sanitizer_win_weak_interception.cpp
CFLAGS ${SANITIZER_CFLAGS} -DSANITIZER_DYNAMIC
DEFS ${SANITIZER_COMMON_DEFINITIONS})
add_compiler_rt_object_libraries(SancovWeakInterception
${SANITIZER_COMMON_SUPPORTED_OS}
ARCHS ${SANITIZER_COMMON_SUPPORTED_ARCH}
- SOURCES sanitizer_coverage_win_weak_interception.cc
+ SOURCES sanitizer_coverage_win_weak_interception.cpp
CFLAGS ${SANITIZER_CFLAGS} -DSANITIZER_DYNAMIC
DEFS ${SANITIZER_COMMON_DEFINITIONS})
add_compiler_rt_object_libraries(SanitizerCommonDllThunk
${SANITIZER_COMMON_SUPPORTED_OS}
ARCHS ${SANITIZER_COMMON_SUPPORTED_ARCH}
- SOURCES sanitizer_win_dll_thunk.cc
+ SOURCES sanitizer_win_dll_thunk.cpp
CFLAGS ${SANITIZER_CFLAGS} -DSANITIZER_DLL_THUNK
DEFS ${SANITIZER_COMMON_DEFINITIONS})
add_compiler_rt_object_libraries(SancovDllThunk
${SANITIZER_COMMON_SUPPORTED_OS}
ARCHS ${SANITIZER_COMMON_SUPPORTED_ARCH}
- SOURCES sanitizer_coverage_win_dll_thunk.cc
- sanitizer_coverage_win_sections.cc
+ SOURCES sanitizer_coverage_win_dll_thunk.cpp
+ sanitizer_coverage_win_sections.cpp
CFLAGS ${SANITIZER_CFLAGS} -DSANITIZER_DLL_THUNK
DEFS ${SANITIZER_COMMON_DEFINITIONS})
@@ -311,14 +314,14 @@
add_compiler_rt_object_libraries(SanitizerCommonDynamicRuntimeThunk
${SANITIZER_COMMON_SUPPORTED_OS}
ARCHS ${SANITIZER_COMMON_SUPPORTED_ARCH}
- SOURCES sanitizer_win_dynamic_runtime_thunk.cc
+ SOURCES sanitizer_win_dynamic_runtime_thunk.cpp
CFLAGS ${SANITIZER_CFLAGS} ${DYNAMIC_RUNTIME_THUNK_CFLAGS}
DEFS ${SANITIZER_COMMON_DEFINITIONS})
add_compiler_rt_object_libraries(SancovDynamicRuntimeThunk
${SANITIZER_COMMON_SUPPORTED_OS}
ARCHS ${SANITIZER_COMMON_SUPPORTED_ARCH}
- SOURCES sanitizer_coverage_win_dynamic_runtime_thunk.cc
- sanitizer_coverage_win_sections.cc
+ SOURCES sanitizer_coverage_win_dynamic_runtime_thunk.cpp
+ sanitizer_coverage_win_sections.cpp
CFLAGS ${SANITIZER_CFLAGS} ${DYNAMIC_RUNTIME_THUNK_CFLAGS}
DEFS ${SANITIZER_COMMON_DEFINITIONS})
endif()
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sancov_flags.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sancov_flags.cpp
similarity index 95%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sancov_flags.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sancov_flags.cpp
index ec6c14b..ed46e88 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sancov_flags.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sancov_flags.cpp
@@ -1,4 +1,4 @@
-//===-- sancov_flags.cc -----------------------------------------*- C++ -*-===//
+//===-- sancov_flags.cpp ----------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator.cpp
index 1739bb6..906d4af 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_allocator.cc --------------------------------------------===//
+//===-- sanitizer_allocator.cpp -------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -213,7 +213,7 @@
// Align allocation size.
size = RoundUpTo(size, low_level_alloc_min_alignment);
if (allocated_end_ - allocated_current_ < (sptr)size) {
- uptr size_to_allocate = Max(size, GetPageSizeCached());
+ uptr size_to_allocate = RoundUpTo(size, GetPageSizeCached());
allocated_current_ =
(char*)MmapOrDie(size_to_allocate, __func__);
allocated_end_ = allocated_current_ + size_to_allocate;
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator_checks.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator_checks.cpp
similarity index 90%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator_checks.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator_checks.cpp
index bb56010..9d67f67 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator_checks.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator_checks.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_allocator_checks.cc ---------------------------*- C++ -*-===//
+//===-- sanitizer_allocator_checks.cpp --------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator_checks.h b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator_checks.h
index f436ce9..fc426f0 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator_checks.h
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator_checks.h
@@ -54,7 +54,7 @@
// and a multiple of sizeof(void *).
INLINE bool CheckPosixMemalignAlignment(uptr alignment) {
return alignment != 0 && IsPowerOfTwo(alignment) &&
- (alignment % sizeof(void *)) == 0; // NOLINT
+ (alignment % sizeof(void *)) == 0;
}
// Returns true if calloc(size, n) call overflows on size*n calculation.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator_report.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator_report.cpp
similarity index 93%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator_report.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator_report.cpp
index dfc41816..d74e080 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator_report.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_allocator_report.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_allocator_report.cc ---------------------------*- C++ -*-===//
+//===-- sanitizer_allocator_report.cpp --------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -106,10 +106,11 @@
{
ScopedAllocatorErrorReport report("invalid-posix-memalign-alignment",
stack);
- Report("ERROR: %s: invalid alignment requested in "
- "posix_memalign: %zd, alignment must be a power of two and a "
- "multiple of sizeof(void*) == %zd\n", SanitizerToolName, alignment,
- sizeof(void*)); // NOLINT
+ Report(
+ "ERROR: %s: invalid alignment requested in "
+ "posix_memalign: %zd, alignment must be a power of two and a "
+ "multiple of sizeof(void*) == %zd\n",
+ SanitizerToolName, alignment, sizeof(void *));
}
Die();
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_asm.h b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_asm.h
index 184d118..803af32 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_asm.h
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_asm.h
@@ -60,7 +60,9 @@
#if defined(__ELF__) && (defined(__GNU__) || defined(__FreeBSD__) || \
defined(__Fuchsia__) || defined(__linux__))
-#define NO_EXEC_STACK_DIRECTIVE .section .note.GNU-stack,"",%progbits // NOLINT
+// clang-format off
+#define NO_EXEC_STACK_DIRECTIVE .section .note.GNU-stack,"",%progbits // NOLINT
+// clang-format on
#else
#define NO_EXEC_STACK_DIRECTIVE
#endif
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_atomic_msvc.h b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_atomic_msvc.h
index a249657..6a7c546 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_atomic_msvc.h
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_atomic_msvc.h
@@ -20,44 +20,35 @@
#pragma intrinsic(_mm_mfence)
extern "C" void _mm_pause();
#pragma intrinsic(_mm_pause)
-extern "C" char _InterlockedExchange8( // NOLINT
- char volatile *Addend, char Value); // NOLINT
+extern "C" char _InterlockedExchange8(char volatile *Addend, char Value);
#pragma intrinsic(_InterlockedExchange8)
-extern "C" short _InterlockedExchange16( // NOLINT
- short volatile *Addend, short Value); // NOLINT
+extern "C" short _InterlockedExchange16(short volatile *Addend, short Value);
#pragma intrinsic(_InterlockedExchange16)
-extern "C" long _InterlockedExchange( // NOLINT
- long volatile *Addend, long Value); // NOLINT
+extern "C" long _InterlockedExchange(long volatile *Addend, long Value);
#pragma intrinsic(_InterlockedExchange)
-extern "C" long _InterlockedExchangeAdd( // NOLINT
- long volatile * Addend, long Value); // NOLINT
+extern "C" long _InterlockedExchangeAdd(long volatile *Addend, long Value);
#pragma intrinsic(_InterlockedExchangeAdd)
-extern "C" char _InterlockedCompareExchange8( // NOLINT
- char volatile *Destination, // NOLINT
- char Exchange, char Comparand); // NOLINT
+extern "C" char _InterlockedCompareExchange8(char volatile *Destination,
+ char Exchange, char Comparand);
#pragma intrinsic(_InterlockedCompareExchange8)
-extern "C" short _InterlockedCompareExchange16( // NOLINT
- short volatile *Destination, // NOLINT
- short Exchange, short Comparand); // NOLINT
+extern "C" short _InterlockedCompareExchange16(short volatile *Destination,
+ short Exchange, short Comparand);
#pragma intrinsic(_InterlockedCompareExchange16)
-extern "C"
-long long _InterlockedCompareExchange64( // NOLINT
- long long volatile *Destination, // NOLINT
- long long Exchange, long long Comparand); // NOLINT
+extern "C" long long _InterlockedCompareExchange64(
+ long long volatile *Destination, long long Exchange, long long Comparand);
#pragma intrinsic(_InterlockedCompareExchange64)
extern "C" void *_InterlockedCompareExchangePointer(
void *volatile *Destination,
void *Exchange, void *Comparand);
#pragma intrinsic(_InterlockedCompareExchangePointer)
-extern "C"
-long __cdecl _InterlockedCompareExchange( // NOLINT
- long volatile *Destination, // NOLINT
- long Exchange, long Comparand); // NOLINT
+extern "C" long __cdecl _InterlockedCompareExchange(long volatile *Destination,
+ long Exchange,
+ long Comparand);
#pragma intrinsic(_InterlockedCompareExchange)
#ifdef _WIN64
-extern "C" long long _InterlockedExchangeAdd64( // NOLINT
- long long volatile * Addend, long long Value); // NOLINT
+extern "C" long long _InterlockedExchangeAdd64(long long volatile *Addend,
+ long long Value);
#pragma intrinsic(_InterlockedExchangeAdd64)
#endif
@@ -115,8 +106,8 @@
u32 v, memory_order mo) {
(void)mo;
DCHECK(!((uptr)a % sizeof(*a)));
- return (u32)_InterlockedExchangeAdd(
- (volatile long*)&a->val_dont_use, (long)v); // NOLINT
+ return (u32)_InterlockedExchangeAdd((volatile long *)&a->val_dont_use,
+ (long)v);
}
INLINE uptr atomic_fetch_add(volatile atomic_uintptr_t *a,
@@ -124,11 +115,11 @@
(void)mo;
DCHECK(!((uptr)a % sizeof(*a)));
#ifdef _WIN64
- return (uptr)_InterlockedExchangeAdd64(
- (volatile long long*)&a->val_dont_use, (long long)v); // NOLINT
+ return (uptr)_InterlockedExchangeAdd64((volatile long long *)&a->val_dont_use,
+ (long long)v);
#else
- return (uptr)_InterlockedExchangeAdd(
- (volatile long*)&a->val_dont_use, (long)v); // NOLINT
+ return (uptr)_InterlockedExchangeAdd((volatile long *)&a->val_dont_use,
+ (long)v);
#endif
}
@@ -136,8 +127,8 @@
u32 v, memory_order mo) {
(void)mo;
DCHECK(!((uptr)a % sizeof(*a)));
- return (u32)_InterlockedExchangeAdd(
- (volatile long*)&a->val_dont_use, -(long)v); // NOLINT
+ return (u32)_InterlockedExchangeAdd((volatile long *)&a->val_dont_use,
+ -(long)v);
}
INLINE uptr atomic_fetch_sub(volatile atomic_uintptr_t *a,
@@ -145,11 +136,11 @@
(void)mo;
DCHECK(!((uptr)a % sizeof(*a)));
#ifdef _WIN64
- return (uptr)_InterlockedExchangeAdd64(
- (volatile long long*)&a->val_dont_use, -(long long)v); // NOLINT
+ return (uptr)_InterlockedExchangeAdd64((volatile long long *)&a->val_dont_use,
+ -(long long)v);
#else
- return (uptr)_InterlockedExchangeAdd(
- (volatile long*)&a->val_dont_use, -(long)v); // NOLINT
+ return (uptr)_InterlockedExchangeAdd((volatile long *)&a->val_dont_use,
+ -(long)v);
#endif
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common.cpp
index 80fb8f6..f5f9f49 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_common.cc -----------------------------------------------===//
+//===-- sanitizer_common.cpp ----------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -323,7 +323,7 @@
} // namespace __sanitizer
-using namespace __sanitizer; // NOLINT
+using namespace __sanitizer;
extern "C" {
SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_report_error_summary,
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common.h b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common.h
index 1703899..3b52172 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common.h
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common.h
@@ -100,6 +100,8 @@
void *MmapOrDieOnFatalError(uptr size, const char *mem_type);
bool MmapFixedNoReserve(uptr fixed_addr, uptr size, const char *name = nullptr)
WARN_UNUSED_RESULT;
+bool MmapFixedSuperNoReserve(uptr fixed_addr, uptr size,
+ const char *name = nullptr) WARN_UNUSED_RESULT;
void *MmapNoReserveOrDie(uptr size, const char *mem_type);
void *MmapFixedOrDie(uptr fixed_addr, uptr size, const char *name = nullptr);
// Behaves just like MmapFixedOrDie, but tolerates out of memory condition, in
@@ -131,7 +133,7 @@
void IncreaseTotalMmap(uptr size);
void DecreaseTotalMmap(uptr size);
uptr GetRSS();
-bool NoHugePagesInRegion(uptr addr, uptr length);
+void SetShadowRegionHugePageMode(uptr addr, uptr length);
bool DontDumpShadowMemory(uptr addr, uptr length);
// Check if the built VMA size matches the runtime one.
void CheckVMASize();
@@ -337,18 +339,18 @@
// Math
#if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__)
extern "C" {
-unsigned char _BitScanForward(unsigned long *index, unsigned long mask); // NOLINT
-unsigned char _BitScanReverse(unsigned long *index, unsigned long mask); // NOLINT
+unsigned char _BitScanForward(unsigned long *index, unsigned long mask);
+unsigned char _BitScanReverse(unsigned long *index, unsigned long mask);
#if defined(_WIN64)
-unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask); // NOLINT
-unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask); // NOLINT
+unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask);
+unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask);
#endif
}
#endif
INLINE uptr MostSignificantSetBitIndex(uptr x) {
CHECK_NE(x, 0U);
- unsigned long up; // NOLINT
+ unsigned long up;
#if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
# ifdef _WIN64
up = SANITIZER_WORDSIZE - 1 - __builtin_clzll(x);
@@ -365,7 +367,7 @@
INLINE uptr LeastSignificantSetBitIndex(uptr x) {
CHECK_NE(x, 0U);
- unsigned long up; // NOLINT
+ unsigned long up;
#if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
# ifdef _WIN64
up = __builtin_ctzll(x);
@@ -550,7 +552,7 @@
template<typename T>
class InternalMmapVector : public InternalMmapVectorNoCtor<T> {
public:
- InternalMmapVector() { InternalMmapVectorNoCtor<T>::Initialize(1); }
+ InternalMmapVector() { InternalMmapVectorNoCtor<T>::Initialize(0); }
explicit InternalMmapVector(uptr cnt) {
InternalMmapVectorNoCtor<T>::Initialize(cnt);
this->resize(cnt);
@@ -669,7 +671,7 @@
error_t *errno_p = nullptr);
// When adding a new architecture, don't forget to also update
-// script/asan_symbolize.py and sanitizer_symbolizer_libcdep.cc.
+// script/asan_symbolize.py and sanitizer_symbolizer_libcdep.cpp.
inline const char *ModuleArchToString(ModuleArch arch) {
switch (arch) {
case kModuleArchUnknown:
@@ -879,6 +881,11 @@
bool is_memory_access;
enum WriteFlag { UNKNOWN, READ, WRITE } write_flag;
+ // In some cases the kernel cannot provide the true faulting address; `addr`
+ // will be zero then. This field allows to distinguish between these cases
+ // and dereferences of null.
+ bool is_true_faulting_addr;
+
// VS2013 doesn't implement unrestricted unions, so we need a trivial default
// constructor
SignalContext() = default;
@@ -891,7 +898,8 @@
context(context),
addr(GetAddress()),
is_memory_access(IsMemoryAccess()),
- write_flag(GetWriteFlag()) {
+ write_flag(GetWriteFlag()),
+ is_true_faulting_addr(IsTrueFaultingAddress()) {
InitPcSpBp();
}
@@ -912,6 +920,7 @@
uptr GetAddress() const;
WriteFlag GetWriteFlag() const;
bool IsMemoryAccess() const;
+ bool IsTrueFaultingAddress() const;
};
void InitializePlatformEarly();
@@ -971,7 +980,7 @@
} // namespace __sanitizer
inline void *operator new(__sanitizer::operator_new_size_type size,
- __sanitizer::LowLevelAllocator &alloc) {
+ __sanitizer::LowLevelAllocator &alloc) { // NOLINT
return alloc.Allocate(size);
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors.inc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors.inc
index 9f5a91a..2a4ab7e 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors.inc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors.inc
@@ -36,6 +36,7 @@
// COMMON_INTERCEPTOR_MMAP_IMPL
// COMMON_INTERCEPTOR_COPY_STRING
// COMMON_INTERCEPTOR_STRNDUP_IMPL
+// COMMON_INTERCEPTOR_STRERROR
//===----------------------------------------------------------------------===//
#include "interception/interception.h"
@@ -78,13 +79,15 @@
#define devname __devname50
#define fgetpos __fgetpos50
#define fsetpos __fsetpos50
+#define fstatvfs __fstatvfs90
+#define fstatvfs1 __fstatvfs190
#define fts_children __fts_children60
#define fts_close __fts_close60
#define fts_open __fts_open60
#define fts_read __fts_read60
#define fts_set __fts_set60
#define getitimer __getitimer50
-#define getmntinfo __getmntinfo13
+#define getmntinfo __getmntinfo90
#define getpwent __getpwent50
#define getpwnam __getpwnam50
#define getpwnam_r __getpwnam_r50
@@ -94,6 +97,7 @@
#define getutxent __getutxent50
#define getutxid __getutxid50
#define getutxline __getutxline50
+#define getvfsstat __getvfsstat90
#define pututxline __pututxline50
#define glob __glob30
#define gmtime __gmtime50
@@ -115,6 +119,8 @@
#define sigprocmask __sigprocmask14
#define sigtimedwait __sigtimedwait50
#define stat __stat50
+#define statvfs __statvfs90
+#define statvfs1 __statvfs190
#define time __time50
#define times __times13
#define unvis __unvis50
@@ -301,6 +307,10 @@
return new_mem;
#endif
+#ifndef COMMON_INTERCEPTOR_STRERROR
+#define COMMON_INTERCEPTOR_STRERROR() {}
+#endif
+
struct FileMetadata {
// For open_memstream().
char **addr;
@@ -317,11 +327,11 @@
};
};
+#if SI_POSIX
typedef AddrHashMap<CommonInterceptorMetadata, 31051> MetadataHashMap;
static MetadataHashMap *interceptor_metadata_map;
-#if SI_POSIX
UNUSED static void SetInterceptorMetadata(__sanitizer_FILE *addr,
const FileMetadata &file) {
MetadataHashMap::Handle h(interceptor_metadata_map, (uptr)addr);
@@ -1241,8 +1251,9 @@
// libc file streams can call user-supplied functions, see fopencookie.
void *ctx;
COMMON_INTERCEPTOR_ENTER(ctx, fputs, s, file);
- if (!SANITIZER_MAC || s)
+ if (!SANITIZER_MAC || s) { // `fputs(NULL, file)` is supported on Darwin.
COMMON_INTERCEPTOR_READ_RANGE(ctx, s, REAL(strlen)(s) + 1);
+ }
return REAL(fputs)(s, file);
}
#define INIT_FPUTS COMMON_INTERCEPT_FUNCTION(fputs)
@@ -1255,8 +1266,9 @@
// libc file streams can call user-supplied functions, see fopencookie.
void *ctx;
COMMON_INTERCEPTOR_ENTER(ctx, puts, s);
- if (!SANITIZER_MAC || s)
+ if (!SANITIZER_MAC || s) { // `puts(NULL)` is supported on Darwin.
COMMON_INTERCEPTOR_READ_RANGE(ctx, s, REAL(strlen)(s) + 1);
+ }
return REAL(puts)(s);
}
#define INIT_PUTS COMMON_INTERCEPT_FUNCTION(puts)
@@ -1265,9 +1277,8 @@
#endif
#if SANITIZER_INTERCEPT_PRCTL
-INTERCEPTOR(int, prctl, int option, unsigned long arg2,
- unsigned long arg3, // NOLINT
- unsigned long arg4, unsigned long arg5) { // NOLINT
+INTERCEPTOR(int, prctl, int option, unsigned long arg2, unsigned long arg3,
+ unsigned long arg4, unsigned long arg5) {
void *ctx;
COMMON_INTERCEPTOR_ENTER(ctx, prctl, option, arg2, arg3, arg4, arg5);
static const int PR_SET_NAME = 15;
@@ -1699,13 +1710,13 @@
FORMAT_INTERCEPTOR_IMPL(__fprintf_chk, vfprintf, stream, format)
#endif
-INTERCEPTOR(int, sprintf, char *str, const char *format, ...) // NOLINT
-FORMAT_INTERCEPTOR_IMPL(sprintf, vsprintf, str, format) // NOLINT
+INTERCEPTOR(int, sprintf, char *str, const char *format, ...)
+FORMAT_INTERCEPTOR_IMPL(sprintf, vsprintf, str, format)
#if SANITIZER_INTERCEPT___PRINTF_CHK
INTERCEPTOR(int, __sprintf_chk, char *str, int flag, SIZE_T size_to,
- const char *format, ...) // NOLINT
-FORMAT_INTERCEPTOR_IMPL(__sprintf_chk, vsprintf, str, format) // NOLINT
+ const char *format, ...)
+FORMAT_INTERCEPTOR_IMPL(__sprintf_chk, vsprintf, str, format)
#endif
INTERCEPTOR(int, snprintf, char *str, SIZE_T size, const char *format, ...)
@@ -1713,8 +1724,8 @@
#if SANITIZER_INTERCEPT___PRINTF_CHK
INTERCEPTOR(int, __snprintf_chk, char *str, SIZE_T size, int flag,
- SIZE_T size_to, const char *format, ...) // NOLINT
-FORMAT_INTERCEPTOR_IMPL(__snprintf_chk, vsnprintf, str, size, format) // NOLINT
+ SIZE_T size_to, const char *format, ...)
+FORMAT_INTERCEPTOR_IMPL(__snprintf_chk, vsnprintf, str, size, format)
#endif
INTERCEPTOR(int, asprintf, char **strp, const char *format, ...)
@@ -3069,13 +3080,14 @@
COMMON_INTERCEPTOR_FD_RELEASE(ctx, fd);
}
int res = REAL(sendmmsg)(fd, msgvec, vlen, flags);
- if (res >= 0 && msgvec)
+ if (res >= 0 && msgvec) {
for (int i = 0; i < res; ++i) {
COMMON_INTERCEPTOR_WRITE_RANGE(ctx, &msgvec[i].msg_len,
sizeof(msgvec[i].msg_len));
if (common_flags()->intercept_send)
read_msghdr(ctx, &msgvec[i].msg_hdr, msgvec[i].msg_len);
}
+ }
return res;
}
#define INIT_SENDMMSG COMMON_INTERCEPT_FUNCTION(sendmmsg);
@@ -3206,20 +3218,21 @@
__sanitizer_iovec local_iovec;
if (data) {
- if (request == ptrace_setregs)
+ if (request == ptrace_setregs) {
COMMON_INTERCEPTOR_READ_RANGE(ctx, data, struct_user_regs_struct_sz);
- else if (request == ptrace_setfpregs)
+ } else if (request == ptrace_setfpregs) {
COMMON_INTERCEPTOR_READ_RANGE(ctx, data, struct_user_fpregs_struct_sz);
- else if (request == ptrace_setfpxregs)
+ } else if (request == ptrace_setfpxregs) {
COMMON_INTERCEPTOR_READ_RANGE(ctx, data, struct_user_fpxregs_struct_sz);
- else if (request == ptrace_setvfpregs)
+ } else if (request == ptrace_setvfpregs) {
COMMON_INTERCEPTOR_READ_RANGE(ctx, data, struct_user_vfpregs_struct_sz);
- else if (request == ptrace_setsiginfo)
+ } else if (request == ptrace_setsiginfo) {
COMMON_INTERCEPTOR_READ_RANGE(ctx, data, siginfo_t_sz);
+
// Some kernel might zero the iovec::iov_base in case of invalid
// write access. In this case copy the invalid address for further
// inspection.
- else if (request == ptrace_setregset || request == ptrace_getregset) {
+ } else if (request == ptrace_setregset || request == ptrace_getregset) {
__sanitizer_iovec *iovec = (__sanitizer_iovec*)data;
COMMON_INTERCEPTOR_READ_RANGE(ctx, iovec, sizeof(*iovec));
local_iovec = *iovec;
@@ -3236,19 +3249,19 @@
if (!res && data) {
// Note that PEEK* requests assign different meaning to the return value.
// This function does not handle them (nor does it need to).
- if (request == ptrace_getregs)
+ if (request == ptrace_getregs) {
COMMON_INTERCEPTOR_WRITE_RANGE(ctx, data, struct_user_regs_struct_sz);
- else if (request == ptrace_getfpregs)
+ } else if (request == ptrace_getfpregs) {
COMMON_INTERCEPTOR_WRITE_RANGE(ctx, data, struct_user_fpregs_struct_sz);
- else if (request == ptrace_getfpxregs)
+ } else if (request == ptrace_getfpxregs) {
COMMON_INTERCEPTOR_WRITE_RANGE(ctx, data, struct_user_fpxregs_struct_sz);
- else if (request == ptrace_getvfpregs)
+ } else if (request == ptrace_getvfpregs) {
COMMON_INTERCEPTOR_WRITE_RANGE(ctx, data, struct_user_vfpregs_struct_sz);
- else if (request == ptrace_getsiginfo)
+ } else if (request == ptrace_getsiginfo) {
COMMON_INTERCEPTOR_WRITE_RANGE(ctx, data, siginfo_t_sz);
- else if (request == ptrace_geteventmsg)
+ } else if (request == ptrace_geteventmsg) {
COMMON_INTERCEPTOR_WRITE_RANGE(ctx, data, sizeof(unsigned long));
- else if (request == ptrace_getregset) {
+ } else if (request == ptrace_getregset) {
__sanitizer_iovec *iovec = (__sanitizer_iovec*)data;
COMMON_INTERCEPTOR_WRITE_RANGE(ctx, iovec, sizeof(*iovec));
COMMON_INTERCEPTOR_WRITE_RANGE(ctx, local_iovec.iov_base,
@@ -3674,6 +3687,7 @@
INTERCEPTOR(char *, strerror, int errnum) {
void *ctx;
COMMON_INTERCEPTOR_ENTER(ctx, strerror, errnum);
+ COMMON_INTERCEPTOR_STRERROR();
char *res = REAL(strerror)(errnum);
if (res) COMMON_INTERCEPTOR_INITIALIZE_RANGE(res, REAL(strlen)(res) + 1);
return res;
@@ -4168,11 +4182,27 @@
#if SANITIZER_INTERCEPT___PTHREAD_MUTEX
INTERCEPTOR(int, __pthread_mutex_lock, void *m) {
- return WRAP(pthread_mutex_lock)(m);
+ void *ctx;
+ COMMON_INTERCEPTOR_ENTER(ctx, __pthread_mutex_lock, m);
+ COMMON_INTERCEPTOR_MUTEX_PRE_LOCK(ctx, m);
+ int res = REAL(__pthread_mutex_lock)(m);
+ if (res == errno_EOWNERDEAD)
+ COMMON_INTERCEPTOR_MUTEX_REPAIR(ctx, m);
+ if (res == 0 || res == errno_EOWNERDEAD)
+ COMMON_INTERCEPTOR_MUTEX_POST_LOCK(ctx, m);
+ if (res == errno_EINVAL)
+ COMMON_INTERCEPTOR_MUTEX_INVALID(ctx, m);
+ return res;
}
INTERCEPTOR(int, __pthread_mutex_unlock, void *m) {
- return WRAP(pthread_mutex_unlock)(m);
+ void *ctx;
+ COMMON_INTERCEPTOR_ENTER(ctx, __pthread_mutex_unlock, m);
+ COMMON_INTERCEPTOR_MUTEX_UNLOCK(ctx, m);
+ int res = REAL(__pthread_mutex_unlock)(m);
+ if (res == errno_EINVAL)
+ COMMON_INTERCEPTOR_MUTEX_INVALID(ctx, m);
+ return res;
}
#define INIT___PTHREAD_MUTEX_LOCK \
@@ -6714,7 +6744,7 @@
COMMON_INTERCEPTOR_READ_RANGE(ctx, dst, (dst_size + 1) * sizeof(wchar_t));
COMMON_INTERCEPTOR_WRITE_RANGE(ctx, dst + dst_size,
(src_size + 1) * sizeof(wchar_t));
- return REAL(wcscat)(dst, src); // NOLINT
+ return REAL(wcscat)(dst, src);
}
INTERCEPTOR(wchar_t *, wcsncat, wchar_t *dst, const wchar_t *src, SIZE_T n) {
@@ -6727,7 +6757,7 @@
COMMON_INTERCEPTOR_READ_RANGE(ctx, dst, (dst_size + 1) * sizeof(wchar_t));
COMMON_INTERCEPTOR_WRITE_RANGE(ctx, dst + dst_size,
(src_size + 1) * sizeof(wchar_t));
- return REAL(wcsncat)(dst, src, n); // NOLINT
+ return REAL(wcsncat)(dst, src, n);
}
#define INIT_WCSCAT \
COMMON_INTERCEPT_FUNCTION(wcscat); \
@@ -7841,10 +7871,11 @@
if (iov)
COMMON_INTERCEPTOR_WRITE_RANGE(
ctx, iov->iov_base, Min(iov_len, iov->iov_len));
- } else if (operation == modctl_exists)
+ } else if (operation == modctl_exists) {
ret = REAL(modctl)(operation, argp);
- else
+ } else {
ret = REAL(modctl)(operation, argp);
+ }
return ret;
}
@@ -9548,10 +9579,165 @@
#define INIT_SL_INIT
#endif
+#if SANITIZER_INTERCEPT_GETRANDOM
+INTERCEPTOR(SSIZE_T, getrandom, void *buf, SIZE_T buflen, unsigned int flags) {
+ void *ctx;
+ COMMON_INTERCEPTOR_ENTER(ctx, getrandom, buf, buflen, flags);
+ SSIZE_T n = REAL(getrandom)(buf, buflen, flags);
+ if (n > 0) {
+ COMMON_INTERCEPTOR_WRITE_RANGE(ctx, buf, n);
+ }
+ return n;
+}
+#define INIT_GETRANDOM COMMON_INTERCEPT_FUNCTION(getrandom)
+#else
+#define INIT_GETRANDOM
+#endif
+
+#if SANITIZER_INTERCEPT_CRYPT
+INTERCEPTOR(char *, crypt, char *key, char *salt) {
+ void *ctx;
+ COMMON_INTERCEPTOR_ENTER(ctx, crypt, key, salt);
+ COMMON_INTERCEPTOR_READ_RANGE(ctx, key, internal_strlen(key) + 1);
+ COMMON_INTERCEPTOR_READ_RANGE(ctx, salt, internal_strlen(salt) + 1);
+ char *res = REAL(crypt)(key, salt);
+ if (res != nullptr)
+ COMMON_INTERCEPTOR_INITIALIZE_RANGE(res, internal_strlen(res) + 1);
+ return res;
+}
+#define INIT_CRYPT COMMON_INTERCEPT_FUNCTION(crypt);
+#else
+#define INIT_CRYPT
+#endif
+
+#if SANITIZER_INTERCEPT_CRYPT_R
+INTERCEPTOR(char *, crypt_r, char *key, char *salt, void *data) {
+ void *ctx;
+ COMMON_INTERCEPTOR_ENTER(ctx, crypt_r, key, salt, data);
+ COMMON_INTERCEPTOR_READ_RANGE(ctx, key, internal_strlen(key) + 1);
+ COMMON_INTERCEPTOR_READ_RANGE(ctx, salt, internal_strlen(salt) + 1);
+ char *res = REAL(crypt_r)(key, salt, data);
+ if (res != nullptr) {
+ COMMON_INTERCEPTOR_WRITE_RANGE(ctx, data,
+ __sanitizer::struct_crypt_data_sz);
+ COMMON_INTERCEPTOR_INITIALIZE_RANGE(res, internal_strlen(res) + 1);
+ }
+ return res;
+}
+#define INIT_CRYPT_R COMMON_INTERCEPT_FUNCTION(crypt_r);
+#else
+#define INIT_CRYPT_R
+#endif
+
+#if SANITIZER_INTERCEPT_GETENTROPY
+INTERCEPTOR(int, getentropy, void *buf, SIZE_T buflen) {
+ void *ctx;
+ COMMON_INTERCEPTOR_ENTER(ctx, getentropy, buf, buflen);
+ int r = REAL(getentropy)(buf, buflen);
+ if (r == 0) {
+ COMMON_INTERCEPTOR_WRITE_RANGE(ctx, buf, buflen);
+ }
+ return r;
+}
+#define INIT_GETENTROPY COMMON_INTERCEPT_FUNCTION(getentropy)
+#else
+#define INIT_GETENTROPY
+#endif
+
+#if SANITIZER_INTERCEPT_QSORT
+// Glibc qsort uses a temporary buffer allocated either on stack or on heap.
+// Poisoned memory from there may get copied into the comparator arguments,
+// where it needs to be dealt with. But even that is not enough - the results of
+// the sort may be copied into the input/output array based on the results of
+// the comparator calls, but directly from the temp memory, bypassing the
+// unpoisoning done in wrapped_qsort_compar. We deal with this by, again,
+// unpoisoning the entire array after the sort is done.
+//
+// We can not check that the entire array is initialized at the beginning. IMHO,
+// it's fine for parts of the sorted objects to contain uninitialized memory,
+// ex. as padding in structs.
+typedef int (*qsort_compar_f)(const void *, const void *);
+static THREADLOCAL qsort_compar_f qsort_compar;
+static THREADLOCAL SIZE_T qsort_size;
+int wrapped_qsort_compar(const void *a, const void *b) {
+ COMMON_INTERCEPTOR_UNPOISON_PARAM(2);
+ COMMON_INTERCEPTOR_INITIALIZE_RANGE(a, qsort_size);
+ COMMON_INTERCEPTOR_INITIALIZE_RANGE(b, qsort_size);
+ return qsort_compar(a, b);
+}
+
+INTERCEPTOR(void, qsort, void *base, SIZE_T nmemb, SIZE_T size,
+ qsort_compar_f compar) {
+ void *ctx;
+ COMMON_INTERCEPTOR_ENTER(ctx, qsort, base, nmemb, size, compar);
+ // Run the comparator over all array elements to detect any memory issues.
+ if (nmemb > 1) {
+ for (SIZE_T i = 0; i < nmemb - 1; ++i) {
+ void *p = (void *)((char *)base + i * size);
+ void *q = (void *)((char *)base + (i + 1) * size);
+ COMMON_INTERCEPTOR_UNPOISON_PARAM(2);
+ compar(p, q);
+ }
+ }
+ qsort_compar_f old_compar = qsort_compar;
+ qsort_compar = compar;
+ SIZE_T old_size = qsort_size;
+ qsort_size = size;
+ REAL(qsort)(base, nmemb, size, wrapped_qsort_compar);
+ qsort_compar = old_compar;
+ qsort_size = old_size;
+ COMMON_INTERCEPTOR_WRITE_RANGE(ctx, base, nmemb * size);
+}
+#define INIT_QSORT COMMON_INTERCEPT_FUNCTION(qsort)
+#else
+#define INIT_QSORT
+#endif
+
+#if SANITIZER_INTERCEPT_QSORT_R
+typedef int (*qsort_r_compar_f)(const void *, const void *, void *);
+static THREADLOCAL qsort_r_compar_f qsort_r_compar;
+static THREADLOCAL SIZE_T qsort_r_size;
+int wrapped_qsort_r_compar(const void *a, const void *b, void *arg) {
+ COMMON_INTERCEPTOR_UNPOISON_PARAM(3);
+ COMMON_INTERCEPTOR_INITIALIZE_RANGE(a, qsort_r_size);
+ COMMON_INTERCEPTOR_INITIALIZE_RANGE(b, qsort_r_size);
+ return qsort_r_compar(a, b, arg);
+}
+
+INTERCEPTOR(void, qsort_r, void *base, SIZE_T nmemb, SIZE_T size,
+ qsort_r_compar_f compar, void *arg) {
+ void *ctx;
+ COMMON_INTERCEPTOR_ENTER(ctx, qsort_r, base, nmemb, size, compar, arg);
+ // Run the comparator over all array elements to detect any memory issues.
+ if (nmemb > 1) {
+ for (SIZE_T i = 0; i < nmemb - 1; ++i) {
+ void *p = (void *)((char *)base + i * size);
+ void *q = (void *)((char *)base + (i + 1) * size);
+ COMMON_INTERCEPTOR_UNPOISON_PARAM(3);
+ compar(p, q, arg);
+ }
+ }
+ qsort_r_compar_f old_compar = qsort_r_compar;
+ qsort_r_compar = compar;
+ SIZE_T old_size = qsort_r_size;
+ qsort_r_size = size;
+ REAL(qsort_r)(base, nmemb, size, wrapped_qsort_r_compar, arg);
+ qsort_r_compar = old_compar;
+ qsort_r_size = old_size;
+ COMMON_INTERCEPTOR_WRITE_RANGE(ctx, base, nmemb * size);
+}
+#define INIT_QSORT_R COMMON_INTERCEPT_FUNCTION(qsort_r)
+#else
+#define INIT_QSORT_R
+#endif
+
+#include "sanitizer_common_interceptors_netbsd_compat.inc"
+
static void InitializeCommonInterceptors() {
+#if SI_POSIX
static u64 metadata_mem[sizeof(MetadataHashMap) / sizeof(u64) + 1];
- interceptor_metadata_map =
- new ((void *)&metadata_mem) MetadataHashMap(); // NOLINT
+ interceptor_metadata_map = new ((void *)&metadata_mem) MetadataHashMap();
+#endif
INIT_MMAP;
INIT_MMAP64;
@@ -9844,6 +10030,12 @@
INIT_FDEVNAME;
INIT_GETUSERSHELL;
INIT_SL_INIT;
+ INIT_GETRANDOM;
+ INIT_CRYPT;
+ INIT_CRYPT_R;
+ INIT_GETENTROPY;
+ INIT_QSORT;
+ INIT_QSORT_R;
INIT___PRINTF_CHK;
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors_netbsd_compat.inc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors_netbsd_compat.inc
new file mode 100644
index 0000000..6aa73ec
--- /dev/null
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors_netbsd_compat.inc
@@ -0,0 +1,128 @@
+//===-- sanitizer_common_interceptors_netbsd_compat.inc ---------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Common function interceptors for tools like AddressSanitizer,
+// ThreadSanitizer, MemorySanitizer, etc.
+//
+// Interceptors for NetBSD old function calls that have been versioned.
+//
+// NetBSD minimal version supported 9.0.
+// NetBSD current version supported 9.99.26.
+//
+//===----------------------------------------------------------------------===//
+
+#if SANITIZER_NETBSD
+
+// First undef all mangled symbols.
+// Next, define compat interceptors.
+// Finally, undef INIT_ and redefine it.
+// This allows to avoid preprocessor issues.
+
+#undef fstatvfs
+#undef fstatvfs1
+#undef getmntinfo
+#undef getvfsstat
+#undef statvfs
+#undef statvfs1
+
+INTERCEPTOR(int, statvfs, char *path, void *buf) {
+ void *ctx;
+ COMMON_INTERCEPTOR_ENTER(ctx, statvfs, path, buf);
+ if (path) COMMON_INTERCEPTOR_READ_RANGE(ctx, path, REAL(strlen)(path) + 1);
+ // FIXME: under ASan the call below may write to freed memory and corrupt
+ // its metadata. See
+ // https://github.com/google/sanitizers/issues/321.
+ int res = REAL(statvfs)(path, buf);
+ if (!res) COMMON_INTERCEPTOR_WRITE_RANGE(ctx, buf, struct_statvfs90_sz);
+ return res;
+}
+
+INTERCEPTOR(int, fstatvfs, int fd, void *buf) {
+ void *ctx;
+ COMMON_INTERCEPTOR_ENTER(ctx, fstatvfs, fd, buf);
+ COMMON_INTERCEPTOR_FD_ACCESS(ctx, fd);
+ // FIXME: under ASan the call below may write to freed memory and corrupt
+ // its metadata. See
+ // https://github.com/google/sanitizers/issues/321.
+ int res = REAL(fstatvfs)(fd, buf);
+ if (!res) {
+ COMMON_INTERCEPTOR_WRITE_RANGE(ctx, buf, struct_statvfs90_sz);
+ if (fd >= 0)
+ COMMON_INTERCEPTOR_FD_ACQUIRE(ctx, fd);
+ }
+ return res;
+}
+
+#undef INIT_STATVFS
+#define INIT_STATVFS \
+ COMMON_INTERCEPT_FUNCTION(statvfs); \
+ COMMON_INTERCEPT_FUNCTION(fstatvfs); \
+ COMMON_INTERCEPT_FUNCTION(__statvfs90); \
+ COMMON_INTERCEPT_FUNCTION(__fstatvfs90)
+
+INTERCEPTOR(int, __getmntinfo13, void **mntbufp, int flags) {
+ void *ctx;
+ COMMON_INTERCEPTOR_ENTER(ctx, __getmntinfo13, mntbufp, flags);
+ int cnt = REAL(__getmntinfo13)(mntbufp, flags);
+ if (cnt > 0 && mntbufp) {
+ COMMON_INTERCEPTOR_WRITE_RANGE(ctx, mntbufp, sizeof(void *));
+ if (*mntbufp)
+ COMMON_INTERCEPTOR_WRITE_RANGE(ctx, *mntbufp, cnt * struct_statvfs90_sz);
+ }
+ return cnt;
+}
+
+#undef INIT_GETMNTINFO
+#define INIT_GETMNTINFO \
+ COMMON_INTERCEPT_FUNCTION(__getmntinfo13); \
+ COMMON_INTERCEPT_FUNCTION(__getmntinfo90)
+
+INTERCEPTOR(int, getvfsstat, void *buf, SIZE_T bufsize, int flags) {
+ void *ctx;
+ COMMON_INTERCEPTOR_ENTER(ctx, getvfsstat, buf, bufsize, flags);
+ int ret = REAL(getvfsstat)(buf, bufsize, flags);
+ if (buf && ret > 0)
+ COMMON_INTERCEPTOR_WRITE_RANGE(ctx, buf, ret * struct_statvfs90_sz);
+ return ret;
+}
+
+#undef INIT_GETVFSSTAT
+#define INIT_GETVFSSTAT \
+ COMMON_INTERCEPT_FUNCTION(getvfsstat); \
+ COMMON_INTERCEPT_FUNCTION(__getvfsstat90)
+
+INTERCEPTOR(int, statvfs1, const char *path, void *buf, int flags) {
+ void *ctx;
+ COMMON_INTERCEPTOR_ENTER(ctx, statvfs1, path, buf, flags);
+ if (path) COMMON_INTERCEPTOR_READ_RANGE(ctx, path, REAL(strlen)(path) + 1);
+ int res = REAL(statvfs1)(path, buf, flags);
+ if (!res) COMMON_INTERCEPTOR_WRITE_RANGE(ctx, buf, struct_statvfs90_sz);
+ return res;
+}
+
+INTERCEPTOR(int, fstatvfs1, int fd, void *buf, int flags) {
+ void *ctx;
+ COMMON_INTERCEPTOR_ENTER(ctx, fstatvfs1, fd, buf, flags);
+ COMMON_INTERCEPTOR_FD_ACCESS(ctx, fd);
+ int res = REAL(fstatvfs1)(fd, buf, flags);
+ if (!res) {
+ COMMON_INTERCEPTOR_WRITE_RANGE(ctx, buf, struct_statvfs90_sz);
+ if (fd >= 0)
+ COMMON_INTERCEPTOR_FD_ACQUIRE(ctx, fd);
+ }
+ return res;
+}
+
+#undef INIT_STATVFS1
+#define INIT_STATVFS1 \
+ COMMON_INTERCEPT_FUNCTION(statvfs1); \
+ COMMON_INTERCEPT_FUNCTION(fstatvfs1); \
+ COMMON_INTERCEPT_FUNCTION(__statvfs190); \
+ COMMON_INTERCEPT_FUNCTION(__fstatvfs190)
+
+#endif
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_interface.inc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_interface.inc
index c725549..c78b6e1 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_interface.inc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_interface.inc
@@ -14,6 +14,7 @@
INTERFACE_FUNCTION(__sanitizer_set_report_path)
INTERFACE_FUNCTION(__sanitizer_set_report_fd)
INTERFACE_FUNCTION(__sanitizer_verify_contiguous_container)
+INTERFACE_WEAK_FUNCTION(__sanitizer_on_print)
INTERFACE_WEAK_FUNCTION(__sanitizer_report_error_summary)
INTERFACE_WEAK_FUNCTION(__sanitizer_sandbox_on_notify)
// Sanitizer weak hooks
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_libcdep.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_libcdep.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_libcdep.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_libcdep.cpp
index 363eb4c..27d6a17 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_libcdep.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_libcdep.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_common_libcdep.cc ---------------------------------------===//
+//===-- sanitizer_common_libcdep.cpp --------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_nolibc.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_nolibc.cpp
similarity index 93%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_nolibc.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_nolibc.cpp
index fdd8587..3b278e0 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_nolibc.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_nolibc.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_common_nolibc.cc ----------------------------------------===//
+//===-- sanitizer_common_nolibc.cpp ---------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_syscalls.inc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_syscalls.inc
index 00bb2ae..31ff48c 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_syscalls.inc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_syscalls.inc
@@ -2873,6 +2873,18 @@
POST_WRITE(oldact, oldact_sz);
}
}
+
+PRE_SYSCALL(getrandom)(void *buf, uptr count, long flags) {
+ if (buf) {
+ PRE_WRITE(buf, count);
+ }
+}
+
+POST_SYSCALL(getrandom)(long res, void *buf, uptr count, long flags) {
+ if (res > 0 && buf) {
+ POST_WRITE(buf, res);
+ }
+}
} // extern "C"
#undef PRE_SYSCALL
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_fuchsia.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_fuchsia.cpp
similarity index 97%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_fuchsia.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_fuchsia.cpp
index 2c71801..f18cee6 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_fuchsia.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_fuchsia.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_coverage_fuchsia.cc -------------------------------------===//
+//===-- sanitizer_coverage_fuchsia.cpp ------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -36,7 +36,7 @@
#include <zircon/sanitizer.h>
#include <zircon/syscalls.h>
-using namespace __sanitizer; // NOLINT
+using namespace __sanitizer;
namespace __sancov {
namespace {
@@ -198,8 +198,8 @@
} // namespace __sanitizer
extern "C" {
-SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_dump_coverage( // NOLINT
- const uptr *pcs, uptr len) {
+SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_dump_coverage(const uptr *pcs,
+ uptr len) {
UNIMPLEMENTED();
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_libcdep_new.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_libcdep_new.cpp
similarity index 96%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_libcdep_new.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_libcdep_new.cpp
index 9dbf2eb..6a75792 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_libcdep_new.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_libcdep_new.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_coverage_libcdep_new.cc ---------------------------------===//
+//===-- sanitizer_coverage_libcdep_new.cpp --------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -166,8 +166,8 @@
} // namespace __sanitizer
extern "C" {
-SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_dump_coverage( // NOLINT
- const uptr* pcs, uptr len) {
+SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_dump_coverage(const uptr* pcs,
+ uptr len) {
return __sancov::SanitizerDumpCoverage(pcs, len);
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_dll_thunk.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_dll_thunk.cpp
similarity index 93%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_dll_thunk.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_dll_thunk.cpp
index 1f0f69d..d0bf8a4 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_dll_thunk.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_dll_thunk.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_coverage_win_dll_thunk.cc -------------------------------===//
+//===-- sanitizer_coverage_win_dll_thunk.cpp ------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_dynamic_runtime_thunk.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_dynamic_runtime_thunk.cpp
similarity index 94%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_dynamic_runtime_thunk.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_dynamic_runtime_thunk.cpp
index 2a41997..0bdf0c5 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_dynamic_runtime_thunk.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_dynamic_runtime_thunk.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_coverage_win_dynamic_runtime_thunk.cc -------------------===//
+//===-- sanitizer_coverage_win_dynamic_runtime_thunk.cpp ------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_sections.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_sections.cpp
similarity index 89%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_sections.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_sections.cpp
index 403d46c..e7d6563 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_sections.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_sections.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_coverage_win_sections.cc --------------------------------===//
+//===-- sanitizer_coverage_win_sections.cpp -------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -31,7 +31,7 @@
// Use uint64_t so the linker won't need to add any padding if it tries to word
// align the start of the 8-bit counters array. The array will always start 8
// bytes after __start_sancov_cntrs.
-#pragma section(".SCOV$CA", read, write) // NOLINT
+#pragma section(".SCOV$CA", read, write)
__declspec(allocate(".SCOV$CA")) uint64_t __start___sancov_cntrs = 0;
// Even though we said not to align __stop__sancov_cntrs (using the "align"
@@ -41,13 +41,13 @@
// padding would be added to align .SCOVP$Z, However, if .SCOV$CZ section is 1
// byte, the linker won't try to align it on an 8-byte boundary, so use a
// uint8_t for __stop_sancov_cntrs.
-#pragma section(".SCOV$CZ", read, write) // NOLINT
+#pragma section(".SCOV$CZ", read, write)
__declspec(allocate(".SCOV$CZ")) __declspec(align(1)) uint8_t
__stop___sancov_cntrs = 0;
-#pragma section(".SCOV$GA", read, write) // NOLINT
+#pragma section(".SCOV$GA", read, write)
__declspec(allocate(".SCOV$GA")) uint64_t __start___sancov_guards = 0;
-#pragma section(".SCOV$GZ", read, write) // NOLINT
+#pragma section(".SCOV$GZ", read, write)
__declspec(allocate(".SCOV$GZ")) __declspec(align(1)) uint8_t
__stop___sancov_guards = 0;
@@ -56,9 +56,9 @@
// constant it should be merged with the .rdata section.
#pragma comment(linker, "/MERGE:.SCOV=.data")
-#pragma section(".SCOVP$A", read) // NOLINT
+#pragma section(".SCOVP$A", read)
__declspec(allocate(".SCOVP$A")) uint64_t __start___sancov_pcs = 0;
-#pragma section(".SCOVP$Z", read) // NOLINT
+#pragma section(".SCOVP$Z", read)
__declspec(allocate(".SCOVP$Z")) __declspec(align(1)) uint8_t
__stop___sancov_pcs = 0;
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_weak_interception.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_weak_interception.cpp
similarity index 94%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_weak_interception.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_weak_interception.cpp
index 1fd10d5..5526398 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_weak_interception.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_coverage_win_weak_interception.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_coverage_win_weak_interception.cc -----------------------===//
+//===-- sanitizer_coverage_win_weak_interception.cpp ----------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_deadlock_detector1.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_deadlock_detector1.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_deadlock_detector1.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_deadlock_detector1.cpp
index a151a19..d4a325b 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_deadlock_detector1.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_deadlock_detector1.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_deadlock_detector1.cc -----------------------------------===//
+//===-- sanitizer_deadlock_detector1.cpp ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_deadlock_detector2.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_deadlock_detector2.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_deadlock_detector2.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_deadlock_detector2.cpp
index ed9ea26..4026739 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_deadlock_detector2.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_deadlock_detector2.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_deadlock_detector2.cc -----------------------------------===//
+//===-- sanitizer_deadlock_detector2.cpp ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_errno.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_errno.cpp
similarity index 93%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_errno.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_errno.cpp
index 1600de5..cbadf4d 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_errno.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_errno.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_errno.cc --------------------------------------*- C++ -*-===//
+//===-- sanitizer_errno.cpp -------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_file.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_file.cpp
similarity index 96%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_file.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_file.cpp
index 3cb4974..79930d7 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_file.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_file.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_file.cc ------------------------------------------------===//
+//===-- sanitizer_file.cpp -----------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -8,7 +8,7 @@
//
// This file is shared between AddressSanitizer and ThreadSanitizer
// run-time libraries. It defines filesystem-related interfaces. This
-// is separate from sanitizer_common.cc so that it's simpler to disable
+// is separate from sanitizer_common.cpp so that it's simpler to disable
// all the filesystem support code for a port that doesn't use it.
//
//===---------------------------------------------------------------------===//
@@ -199,7 +199,7 @@
} // namespace __sanitizer
-using namespace __sanitizer; // NOLINT
+using namespace __sanitizer;
extern "C" {
void __sanitizer_set_report_path(const char *path) {
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flag_parser.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flag_parser.cpp
similarity index 90%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flag_parser.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flag_parser.cpp
index e380d3b..9e27426 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flag_parser.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flag_parser.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_flag_parser.cc ------------------------------------------===//
+//===-- sanitizer_flag_parser.cpp -----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -56,9 +56,16 @@
}
void FlagParser::PrintFlagDescriptions() {
+ char buffer[128];
+ buffer[sizeof(buffer) - 1] = '\0';
Printf("Available flags for %s:\n", SanitizerToolName);
- for (int i = 0; i < n_flags_; ++i)
- Printf("\t%s\n\t\t- %s\n", flags_[i].name, flags_[i].desc);
+ for (int i = 0; i < n_flags_; ++i) {
+ bool truncated = !(flags_[i].handler->Format(buffer, sizeof(buffer)));
+ CHECK_EQ(buffer[sizeof(buffer) - 1], '\0');
+ const char *truncation_str = truncated ? " Truncated" : "";
+ Printf("\t%s\n\t\t- %s (Current Value%s: %s)\n", flags_[i].name,
+ flags_[i].desc, truncation_str, buffer);
+ }
}
void FlagParser::fatal_error(const char *err) {
@@ -83,8 +90,9 @@
Printf("%s: ERROR: expected '=' in %s\n", SanitizerToolName,
env_option_name);
Die();
- } else
+ } else {
fatal_error("expected '='");
+ }
}
char *name = ll_strndup(buf_ + name_start, pos_ - name_start);
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flag_parser.h b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flag_parser.h
index 8e12700..fac5dff 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flag_parser.h
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flag_parser.h
@@ -22,9 +22,23 @@
class FlagHandlerBase {
public:
virtual bool Parse(const char *value) { return false; }
+ // Write the C string representation of the current value (truncated to fit)
+ // into the buffer of size `size`. Returns false if truncation occurred and
+ // returns true otherwise.
+ virtual bool Format(char *buffer, uptr size) {
+ if (size > 0)
+ buffer[0] = '\0';
+ return false;
+ }
protected:
- ~FlagHandlerBase() {};
+ ~FlagHandlerBase() {}
+
+ inline bool FormatString(char *buffer, uptr size, const char *str_to_use) {
+ uptr num_symbols_should_write =
+ internal_snprintf(buffer, size, "%s", str_to_use);
+ return num_symbols_should_write < size;
+ }
};
template <typename T>
@@ -34,6 +48,7 @@
public:
explicit FlagHandler(T *t) : t_(t) {}
bool Parse(const char *value) final;
+ bool Format(char *buffer, uptr size) final;
};
inline bool ParseBool(const char *value, bool *b) {
@@ -60,6 +75,11 @@
}
template <>
+inline bool FlagHandler<bool>::Format(char *buffer, uptr size) {
+ return FormatString(buffer, size, *t_ ? "true" : "false");
+}
+
+template <>
inline bool FlagHandler<HandleSignalMode>::Parse(const char *value) {
bool b;
if (ParseBool(value, &b)) {
@@ -76,12 +96,23 @@
}
template <>
+inline bool FlagHandler<HandleSignalMode>::Format(char *buffer, uptr size) {
+ uptr num_symbols_should_write = internal_snprintf(buffer, size, "%d", *t_);
+ return num_symbols_should_write < size;
+}
+
+template <>
inline bool FlagHandler<const char *>::Parse(const char *value) {
*t_ = value;
return true;
}
template <>
+inline bool FlagHandler<const char *>::Format(char *buffer, uptr size) {
+ return FormatString(buffer, size, *t_);
+}
+
+template <>
inline bool FlagHandler<int>::Parse(const char *value) {
const char *value_end;
*t_ = internal_simple_strtoll(value, &value_end, 10);
@@ -91,6 +122,12 @@
}
template <>
+inline bool FlagHandler<int>::Format(char *buffer, uptr size) {
+ uptr num_symbols_should_write = internal_snprintf(buffer, size, "%d", *t_);
+ return num_symbols_should_write < size;
+}
+
+template <>
inline bool FlagHandler<uptr>::Parse(const char *value) {
const char *value_end;
*t_ = internal_simple_strtoll(value, &value_end, 10);
@@ -100,6 +137,12 @@
}
template <>
+inline bool FlagHandler<uptr>::Format(char *buffer, uptr size) {
+ uptr num_symbols_should_write = internal_snprintf(buffer, size, "%p", *t_);
+ return num_symbols_should_write < size;
+}
+
+template <>
inline bool FlagHandler<s64>::Parse(const char *value) {
const char *value_end;
*t_ = internal_simple_strtoll(value, &value_end, 10);
@@ -108,6 +151,12 @@
return ok;
}
+template <>
+inline bool FlagHandler<s64>::Format(char *buffer, uptr size) {
+ uptr num_symbols_should_write = internal_snprintf(buffer, size, "%lld", *t_);
+ return num_symbols_should_write < size;
+}
+
class FlagParser {
static const int kMaxFlags = 200;
struct Flag {
@@ -144,7 +193,7 @@
template <typename T>
static void RegisterFlag(FlagParser *parser, const char *name, const char *desc,
T *var) {
- FlagHandler<T> *fh = new (FlagParser::Alloc) FlagHandler<T>(var); // NOLINT
+ FlagHandler<T> *fh = new (FlagParser::Alloc) FlagHandler<T>(var);
parser->RegisterHandler(name, fh, desc);
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flags.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flags.cpp
similarity index 86%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flags.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flags.cpp
index c587b18..684ee1e 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flags.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flags.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_flags.cc ------------------------------------------------===//
+//===-- sanitizer_flags.cpp -----------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -75,11 +75,13 @@
class FlagHandlerInclude : public FlagHandlerBase {
FlagParser *parser_;
bool ignore_missing_;
+ const char *original_path_;
public:
explicit FlagHandlerInclude(FlagParser *parser, bool ignore_missing)
- : parser_(parser), ignore_missing_(ignore_missing) {}
+ : parser_(parser), ignore_missing_(ignore_missing), original_path_("") {}
bool Parse(const char *value) final {
+ original_path_ = value;
if (internal_strchr(value, '%')) {
char *buf = (char *)MmapOrDie(kMaxPathLength, "FlagHandlerInclude");
SubstituteForFlagValue(value, buf, kMaxPathLength);
@@ -89,14 +91,20 @@
}
return parser_->ParseFile(value, ignore_missing_);
}
+ bool Format(char *buffer, uptr size) {
+ // Note `original_path_` isn't actually what's parsed due to `%`
+ // substitutions. Printing the substituted path would require holding onto
+ // mmap'ed memory.
+ return FormatString(buffer, size, original_path_);
+ }
};
void RegisterIncludeFlags(FlagParser *parser, CommonFlags *cf) {
- FlagHandlerInclude *fh_include = new (FlagParser::Alloc) // NOLINT
+ FlagHandlerInclude *fh_include = new (FlagParser::Alloc)
FlagHandlerInclude(parser, /*ignore_missing*/ false);
parser->RegisterHandler("include", fh_include,
"read more options from the given file");
- FlagHandlerInclude *fh_include_if_exists = new (FlagParser::Alloc) // NOLINT
+ FlagHandlerInclude *fh_include_if_exists = new (FlagParser::Alloc)
FlagHandlerInclude(parser, /*ignore_missing*/ true);
parser->RegisterHandler(
"include_if_exists", fh_include_if_exists,
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flags.inc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flags.inc
index 7d592bd..065258a 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flags.inc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flags.inc
@@ -132,6 +132,9 @@
" until the RSS goes below the soft limit."
" This limit does not affect memory allocations other than"
" malloc/new.")
+COMMON_FLAG(uptr, max_allocation_size_mb, 0,
+ "If non-zero, malloc/new calls larger than this size will return "
+ "nullptr (or crash if allocator_may_return_null=false).")
COMMON_FLAG(bool, heap_profile, false, "Experimental heap profiler, asan-only")
COMMON_FLAG(s32, allocator_release_to_os_interval_ms,
((bool)SANITIZER_FUCHSIA || (bool)SANITIZER_WINDOWS) ? -1 : 5000,
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_fuchsia.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_fuchsia.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_fuchsia.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_fuchsia.cpp
index 9c032fa..6e2c613 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_fuchsia.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_fuchsia.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_fuchsia.cc ----------------------------------------------===//
+//===-- sanitizer_fuchsia.cpp ---------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -502,7 +502,7 @@
} // namespace __sanitizer
-using namespace __sanitizer; // NOLINT
+using namespace __sanitizer;
extern "C" {
void __sanitizer_startup_hook(int argc, char **argv, char **envp,
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_getauxval.h b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_getauxval.h
index cbd1af1..86ad3a5 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_getauxval.h
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_getauxval.h
@@ -9,6 +9,7 @@
// Common getauxval() guards and definitions.
// getauxval() is not defined until glibc version 2.16, or until API level 21
// for Android.
+// Implement the getauxval() compat function for NetBSD.
//
//===----------------------------------------------------------------------===//
@@ -16,15 +17,10 @@
#define SANITIZER_GETAUXVAL_H
#include "sanitizer_platform.h"
+#include "sanitizer_glibc_version.h"
#if SANITIZER_LINUX || SANITIZER_FUCHSIA
-# include <features.h>
-
-# ifndef __GLIBC_PREREQ
-# define __GLIBC_PREREQ(x, y) 0
-# endif
-
# if __GLIBC_PREREQ(2, 16) || (SANITIZER_ANDROID && __ANDROID_API__ >= 21) || \
SANITIZER_FUCHSIA
# define SANITIZER_USE_GETAUXVAL 1
@@ -38,10 +34,26 @@
// The weak getauxval definition allows to check for the function at runtime.
// This is useful for Android, when compiled at a lower API level yet running
// on a more recent platform that offers the function.
-extern "C" SANITIZER_WEAK_ATTRIBUTE
-unsigned long getauxval(unsigned long type); // NOLINT
+extern "C" SANITIZER_WEAK_ATTRIBUTE unsigned long getauxval(unsigned long type);
# endif
-#endif // SANITIZER_LINUX || SANITIZER_FUCHSIA
+#elif SANITIZER_NETBSD
+
+#define SANITIZER_USE_GETAUXVAL 1
+
+#include <dlfcn.h>
+#include <elf.h>
+
+static inline decltype(AuxInfo::a_v) getauxval(decltype(AuxInfo::a_type) type) {
+ for (const AuxInfo *aux = (const AuxInfo *)_dlauxinfo();
+ aux->a_type != AT_NULL; ++aux) {
+ if (type == aux->a_type)
+ return aux->a_v;
+ }
+
+ return 0;
+}
+
+#endif
#endif // SANITIZER_GETAUXVAL_H
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_glibc_version.h b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_glibc_version.h
new file mode 100644
index 0000000..47175f2
--- /dev/null
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_glibc_version.h
@@ -0,0 +1,26 @@
+//===-- sanitizer_glibc_version.h -----------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file is a part of Sanitizer common code.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef SANITIZER_GLIBC_VERSION_H
+#define SANITIZER_GLIBC_VERSION_H
+
+#include "sanitizer_platform.h"
+
+#if SANITIZER_LINUX || SANITIZER_FUCHSIA
+#include <features.h>
+#endif
+
+#ifndef __GLIBC_PREREQ
+#define __GLIBC_PREREQ(x, y) 0
+#endif
+
+#endif
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_interceptors_ioctl_netbsd.inc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_interceptors_ioctl_netbsd.inc
index 1ec7382..d0cc4da 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_interceptors_ioctl_netbsd.inc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_interceptors_ioctl_netbsd.inc
@@ -24,7 +24,7 @@
const char *name;
};
-const unsigned ioctl_table_max = 1236;
+const unsigned ioctl_table_max = 1238;
static ioctl_desc ioctl_table[ioctl_table_max];
static unsigned ioctl_table_size = 0;
@@ -166,9 +166,6 @@
_(FE_ENABLE_HIGH_LNB_VOLTAGE, READ, sizeof(int));
_(FE_SET_FRONTEND_TUNE_MODE, READ, sizeof(unsigned int));
_(FE_DISHNETWORK_SEND_LEGACY_CMD, READ, sizeof(unsigned long));
- /* Entries from file: dev/filemon/filemon.h */
- _(FILEMON_SET_FD, READWRITE, sizeof(int));
- _(FILEMON_SET_PID, READWRITE, sizeof(int));
/* Entries from file: dev/hdaudio/hdaudioio.h */
_(HDAUDIO_FGRP_INFO, READWRITE, struct_plistref_sz);
_(HDAUDIO_FGRP_GETCONFIG, READWRITE, struct_plistref_sz);
@@ -653,6 +650,7 @@
_(NVMM_IOC_MACHINE_CONFIGURE, READ, struct_nvmm_ioc_machine_configure_sz);
_(NVMM_IOC_VCPU_CREATE, READ, struct_nvmm_ioc_vcpu_create_sz);
_(NVMM_IOC_VCPU_DESTROY, READ, struct_nvmm_ioc_vcpu_destroy_sz);
+ _(NVMM_IOC_VCPU_CONFIGURE, READ, struct_nvmm_ioc_vcpu_configure_sz);
_(NVMM_IOC_VCPU_SETSTATE, READ, struct_nvmm_ioc_vcpu_setstate_sz);
_(NVMM_IOC_VCPU_GETSTATE, READ, struct_nvmm_ioc_vcpu_getstate_sz);
_(NVMM_IOC_VCPU_INJECT, READ, struct_nvmm_ioc_vcpu_inject_sz);
@@ -735,6 +733,7 @@
_(IOC_NPF_SAVE, WRITE, struct_nvlist_ref_sz);
_(IOC_NPF_RULE, READWRITE, struct_nvlist_ref_sz);
_(IOC_NPF_CONN_LOOKUP, READWRITE, struct_nvlist_ref_sz);
+ _(IOC_NPF_TABLE_REPLACE, READWRITE, struct_nvlist_ref_sz);
/* Entries from file: net/if_pppoe.h */
_(PPPOESETPARMS, READ, struct_pppoediscparms_sz);
_(PPPOEGETPARMS, READWRITE, struct_pppoediscparms_sz);
@@ -1403,8 +1402,11 @@
_(SNDCTL_DSP_SETRECVOL, READ, sizeof(unsigned int));
_(SNDCTL_DSP_SKIP, NONE, 0);
_(SNDCTL_DSP_SILENCE, NONE, 0);
+ /* Entries from file: dev/filemon/filemon.h (compat <= 9.99.26) */
+ _(FILEMON_SET_FD, READWRITE, sizeof(int));
+ _(FILEMON_SET_PID, READWRITE, sizeof(int));
#undef _
-}
+} // NOLINT
static bool ioctl_initialized = false;
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_internal_defs.h b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_internal_defs.h
index e0c6506..d0ffc79 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_internal_defs.h
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_internal_defs.h
@@ -105,7 +105,7 @@
// FIXME: do we have anything like this on Mac?
#ifndef SANITIZER_CAN_USE_PREINIT_ARRAY
#if ((SANITIZER_LINUX && !SANITIZER_ANDROID) || SANITIZER_OPENBSD || \
- SANITIZER_FUCHSIA) && !defined(PIC)
+ SANITIZER_FUCHSIA || SANITIZER_NETBSD) && !defined(PIC)
#define SANITIZER_CAN_USE_PREINIT_ARRAY 1
// Before Solaris 11.4, .preinit_array is fully supported only with GNU ld.
// FIXME: Check for those conditions.
@@ -133,27 +133,27 @@
#if defined(_WIN64)
// 64-bit Windows uses LLP64 data model.
-typedef unsigned long long uptr; // NOLINT
-typedef signed long long sptr; // NOLINT
+typedef unsigned long long uptr;
+typedef signed long long sptr;
#else
-typedef unsigned long uptr; // NOLINT
-typedef signed long sptr; // NOLINT
+typedef unsigned long uptr;
+typedef signed long sptr;
#endif // defined(_WIN64)
#if defined(__x86_64__)
// Since x32 uses ILP32 data model in 64-bit hardware mode, we must use
// 64-bit pointer to unwind stack frame.
-typedef unsigned long long uhwptr; // NOLINT
+typedef unsigned long long uhwptr;
#else
-typedef uptr uhwptr; // NOLINT
+typedef uptr uhwptr;
#endif
typedef unsigned char u8;
-typedef unsigned short u16; // NOLINT
+typedef unsigned short u16;
typedef unsigned int u32;
-typedef unsigned long long u64; // NOLINT
-typedef signed char s8;
-typedef signed short s16; // NOLINT
-typedef signed int s32;
-typedef signed long long s64; // NOLINT
+typedef unsigned long long u64;
+typedef signed char s8;
+typedef signed short s16;
+typedef signed int s32;
+typedef signed long long s64;
#if SANITIZER_WINDOWS
// On Windows, files are HANDLE, which is a synonim of void*.
// Use void* to avoid including <windows.h> everywhere.
@@ -264,7 +264,7 @@
#if SANITIZER_WINDOWS
} // namespace __sanitizer
-typedef unsigned long DWORD; // NOLINT
+typedef unsigned long DWORD;
namespace __sanitizer {
typedef DWORD thread_return_t;
# define THREAD_CALLING_CONV __stdcall
@@ -419,18 +419,41 @@
} // namespace __sanitizer
-namespace __asan { using namespace __sanitizer; } // NOLINT
-namespace __dsan { using namespace __sanitizer; } // NOLINT
-namespace __dfsan { using namespace __sanitizer; } // NOLINT
-namespace __lsan { using namespace __sanitizer; } // NOLINT
-namespace __msan { using namespace __sanitizer; } // NOLINT
-namespace __hwasan { using namespace __sanitizer; } // NOLINT
-namespace __tsan { using namespace __sanitizer; } // NOLINT
-namespace __scudo { using namespace __sanitizer; } // NOLINT
-namespace __ubsan { using namespace __sanitizer; } // NOLINT
-namespace __xray { using namespace __sanitizer; } // NOLINT
-namespace __interception { using namespace __sanitizer; } // NOLINT
-namespace __hwasan { using namespace __sanitizer; } // NOLINT
-
+namespace __asan {
+using namespace __sanitizer;
+}
+namespace __dsan {
+using namespace __sanitizer;
+}
+namespace __dfsan {
+using namespace __sanitizer;
+}
+namespace __lsan {
+using namespace __sanitizer;
+}
+namespace __msan {
+using namespace __sanitizer;
+}
+namespace __hwasan {
+using namespace __sanitizer;
+}
+namespace __tsan {
+using namespace __sanitizer;
+}
+namespace __scudo {
+using namespace __sanitizer;
+}
+namespace __ubsan {
+using namespace __sanitizer;
+}
+namespace __xray {
+using namespace __sanitizer;
+}
+namespace __interception {
+using namespace __sanitizer;
+}
+namespace __hwasan {
+using namespace __sanitizer;
+}
#endif // SANITIZER_DEFS_H
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_libc.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_libc.cpp
similarity index 95%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_libc.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_libc.cpp
index 95c7444..4bc04b4 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_libc.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_libc.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_libc.cc -------------------------------------------------===//
+//===-- sanitizer_libc.cpp ------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -63,10 +63,11 @@
for (i = 0; i < signed_n; ++i)
d[i] = s[i];
} else {
- if (d > s && signed_n > 0)
- for (i = signed_n - 1; i >= 0 ; --i) {
+ if (d > s && signed_n > 0) {
+ for (i = signed_n - 1; i >= 0; --i) {
d[i] = s[i];
}
+ }
}
return dest;
}
@@ -270,9 +271,9 @@
for (; aligned_beg < aligned_end; aligned_beg++)
all |= *aligned_beg;
// Epilogue.
- if ((char*)aligned_end >= beg)
- for (const char *mem = (char*)aligned_end; mem < end; mem++)
- all |= *mem;
+ if ((char *)aligned_end >= beg) {
+ for (const char *mem = (char *)aligned_end; mem < end; mem++) all |= *mem;
+ }
return all == 0;
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_libignore.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_libignore.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_libignore.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_libignore.cpp
index 6c7c132..eb9bb76 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_libignore.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_libignore.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_libignore.cc --------------------------------------------===//
+//===-- sanitizer_libignore.cpp -------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp
index 73960fe..84453f1 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_linux.cc ------------------------------------------------===//
+//===-- sanitizer_linux.cpp -----------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -166,7 +166,7 @@
#if !SANITIZER_SOLARIS && !SANITIZER_NETBSD
#if !SANITIZER_S390 && !SANITIZER_OPENBSD
uptr internal_mmap(void *addr, uptr length, int prot, int flags, int fd,
- OFF_T offset) {
+ u64 offset) {
#if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
return internal_syscall(SYSCALL(mmap), (uptr)addr, length, prot, flags, fd,
offset);
@@ -407,7 +407,10 @@
}
uptr internal_rename(const char *oldpath, const char *newpath) {
-#if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS || SANITIZER_OPENBSD
+#if defined(__riscv)
+ return internal_syscall(SYSCALL(renameat2), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
+ (uptr)newpath, 0);
+#elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS || SANITIZER_OPENBSD
return internal_syscall(SYSCALL(renameat), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
(uptr)newpath);
#else
@@ -1062,8 +1065,6 @@
uptr GetPageSize() {
#if SANITIZER_LINUX && (defined(__x86_64__) || defined(__i386__))
return EXEC_PAGESIZE;
-#elif SANITIZER_USE_GETAUXVAL
- return getauxval(AT_PAGESZ);
#elif SANITIZER_FREEBSD || SANITIZER_NETBSD
// Use sysctl as sysconf can trigger interceptors internally.
int pz = 0;
@@ -1072,6 +1073,8 @@
int rv = internal_sysctl(mib, 2, &pz, &pzl, nullptr, 0);
CHECK_EQ(rv, 0);
return (uptr)pz;
+#elif SANITIZER_USE_GETAUXVAL
+ return getauxval(AT_PAGESZ);
#else
return sysconf(_SC_PAGESIZE); // EXEC_PAGESIZE may not be trustworthy.
#endif
@@ -1849,6 +1852,12 @@
#endif
}
+bool SignalContext::IsTrueFaultingAddress() const {
+ auto si = static_cast<const siginfo_t *>(siginfo);
+ // SIGSEGV signals without a true fault address have si_code set to 128.
+ return si->si_signo == SIGSEGV && si->si_code != 128;
+}
+
void SignalContext::DumpAllRegisters(void *context) {
// FIXME: Implement this.
}
@@ -1966,6 +1975,11 @@
# endif
*bp = ucontext->uc_mcontext.gregs[11];
*sp = ucontext->uc_mcontext.gregs[15];
+#elif defined(__riscv)
+ ucontext_t *ucontext = (ucontext_t*)context;
+ *pc = ucontext->uc_mcontext.__gregs[REG_PC];
+ *bp = ucontext->uc_mcontext.__gregs[REG_S0];
+ *sp = ucontext->uc_mcontext.__gregs[REG_SP];
#else
# error "Unsupported arch"
#endif
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux_libcdep.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux_libcdep.cpp
similarity index 97%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux_libcdep.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux_libcdep.cpp
index 49bd5b0..ccb95e6 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux_libcdep.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux_libcdep.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_linux_libcdep.cc ----------------------------------------===//
+//===-- sanitizer_linux_libcdep.cpp ---------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -23,6 +23,7 @@
#include "sanitizer_flags.h"
#include "sanitizer_freebsd.h"
#include "sanitizer_getauxval.h"
+#include "sanitizer_glibc_version.h"
#include "sanitizer_linux.h"
#include "sanitizer_placement_new.h"
#include "sanitizer_procmaps.h"
@@ -49,6 +50,7 @@
#if SANITIZER_NETBSD
#include <sys/sysctl.h>
#include <sys/tls.h>
+#include <lwp.h>
#endif
#if SANITIZER_SOLARIS
@@ -188,11 +190,7 @@
static uptr g_tls_size;
#ifdef __i386__
-# ifndef __GLIBC_PREREQ
-# define CHECK_GET_TLS_STATIC_INFO_VERSION 1
-# else
-# define CHECK_GET_TLS_STATIC_INFO_VERSION (!__GLIBC_PREREQ(2, 27))
-# endif
+# define CHECK_GET_TLS_STATIC_INFO_VERSION (!__GLIBC_PREREQ(2, 27))
#else
# define CHECK_GET_TLS_STATIC_INFO_VERSION 0
#endif
@@ -402,13 +400,7 @@
#if SANITIZER_NETBSD
static struct tls_tcb * ThreadSelfTlsTcb() {
- struct tls_tcb * tcb;
-# ifdef __HAVE___LWP_GETTCB_FAST
- tcb = (struct tls_tcb *)__lwp_gettcb_fast();
-# elif defined(__HAVE___LWP_GETPRIVATE_FAST)
- tcb = (struct tls_tcb *)__lwp_getprivate_fast();
-# endif
- return tcb;
+ return (struct tls_tcb *)_lwp_getprivate();
}
uptr ThreadSelf() {
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux_s390.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux_s390.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux_s390.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux_s390.cpp
index b681bef..9e3b4f1 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux_s390.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux_s390.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_linux_s390.cc -------------------------------------------===//
+//===-- sanitizer_linux_s390.cpp ------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -27,7 +27,7 @@
// --------------- sanitizer_libc.h
uptr internal_mmap(void *addr, uptr length, int prot, int flags, int fd,
- OFF_T offset) {
+ u64 offset) {
struct s390_mmap_params {
unsigned long addr;
unsigned long length;
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_mac.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_mac.cpp
similarity index 90%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_mac.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_mac.cpp
index d9b7c4b..ea4bd02 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_mac.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_mac.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_mac.cc --------------------------------------------------===//
+//===-- sanitizer_mac.cpp -------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -13,6 +13,7 @@
#include "sanitizer_platform.h"
#if SANITIZER_MAC
#include "sanitizer_mac.h"
+#include "interception/interception.h"
// Use 64-bit inodes in file operations. ASan does not support OS X 10.5, so
// the clients will most certainly use 64-bit ones as well.
@@ -64,7 +65,9 @@
#include <pthread.h>
#include <sched.h>
#include <signal.h>
+#include <spawn.h>
#include <stdlib.h>
+#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <sys/stat.h>
@@ -239,27 +242,102 @@
(size_t)newlen);
}
-int internal_forkpty(int *aparent) {
- int parent, worker;
- if (openpty(&parent, &worker, nullptr, nullptr, nullptr) == -1) return -1;
- int pid = internal_fork();
- if (pid == -1) {
- close(parent);
- close(worker);
- return -1;
+static fd_t internal_spawn_impl(const char *argv[], pid_t *pid) {
+ fd_t master_fd = kInvalidFd;
+ fd_t slave_fd = kInvalidFd;
+
+ auto fd_closer = at_scope_exit([&] {
+ internal_close(master_fd);
+ internal_close(slave_fd);
+ });
+
+ // We need a new pseudoterminal to avoid buffering problems. The 'atos' tool
+ // in particular detects when it's talking to a pipe and forgets to flush the
+ // output stream after sending a response.
+ master_fd = posix_openpt(O_RDWR);
+ if (master_fd == kInvalidFd) return kInvalidFd;
+
+ int res = grantpt(master_fd) || unlockpt(master_fd);
+ if (res != 0) return kInvalidFd;
+
+ // Use TIOCPTYGNAME instead of ptsname() to avoid threading problems.
+ char slave_pty_name[128];
+ res = ioctl(master_fd, TIOCPTYGNAME, slave_pty_name);
+ if (res == -1) return kInvalidFd;
+
+ slave_fd = internal_open(slave_pty_name, O_RDWR);
+ if (slave_fd == kInvalidFd) return kInvalidFd;
+
+ // File descriptor actions
+ posix_spawn_file_actions_t acts;
+ res = posix_spawn_file_actions_init(&acts);
+ if (res != 0) return kInvalidFd;
+
+ auto acts_cleanup = at_scope_exit([&] {
+ posix_spawn_file_actions_destroy(&acts);
+ });
+
+ res = posix_spawn_file_actions_adddup2(&acts, slave_fd, STDIN_FILENO) ||
+ posix_spawn_file_actions_adddup2(&acts, slave_fd, STDOUT_FILENO) ||
+ posix_spawn_file_actions_addclose(&acts, slave_fd);
+ if (res != 0) return kInvalidFd;
+
+ // Spawn attributes
+ posix_spawnattr_t attrs;
+ res = posix_spawnattr_init(&attrs);
+ if (res != 0) return kInvalidFd;
+
+ auto attrs_cleanup = at_scope_exit([&] {
+ posix_spawnattr_destroy(&attrs);
+ });
+
+ // In the spawned process, close all file descriptors that are not explicitly
+ // described by the file actions object. This is Darwin-specific extension.
+ res = posix_spawnattr_setflags(&attrs, POSIX_SPAWN_CLOEXEC_DEFAULT);
+ if (res != 0) return kInvalidFd;
+
+ // posix_spawn
+ char **argv_casted = const_cast<char **>(argv);
+ char **env = GetEnviron();
+ res = posix_spawn(pid, argv[0], &acts, &attrs, argv_casted, env);
+ if (res != 0) return kInvalidFd;
+
+ // Disable echo in the new terminal, disable CR.
+ struct termios termflags;
+ tcgetattr(master_fd, &termflags);
+ termflags.c_oflag &= ~ONLCR;
+ termflags.c_lflag &= ~ECHO;
+ tcsetattr(master_fd, TCSANOW, &termflags);
+
+ // On success, do not close master_fd on scope exit.
+ fd_t fd = master_fd;
+ master_fd = kInvalidFd;
+
+ return fd;
+}
+
+fd_t internal_spawn(const char *argv[], pid_t *pid) {
+ // The client program may close its stdin and/or stdout and/or stderr thus
+ // allowing open/posix_openpt to reuse file descriptors 0, 1 or 2. In this
+ // case the communication is broken if either the parent or the child tries to
+ // close or duplicate these descriptors. We temporarily reserve these
+ // descriptors here to prevent this.
+ fd_t low_fds[3];
+ size_t count = 0;
+
+ for (; count < 3; count++) {
+ low_fds[count] = posix_openpt(O_RDWR);
+ if (low_fds[count] >= STDERR_FILENO)
+ break;
}
- if (pid == 0) {
- close(parent);
- if (login_tty(worker) != 0) {
- // We already forked, there's not much we can do. Let's quit.
- Report("login_tty failed (errno %d)\n", errno);
- internal__exit(1);
- }
- } else {
- *aparent = parent;
- close(worker);
+
+ fd_t fd = internal_spawn_impl(argv, pid);
+
+ for (; count > 0; count--) {
+ internal_close(low_fds[count]);
}
- return pid;
+
+ return fd;
}
uptr internal_rename(const char *oldpath, const char *newpath) {
@@ -676,6 +754,12 @@
#endif
}
+bool SignalContext::IsTrueFaultingAddress() const {
+ auto si = static_cast<const siginfo_t *>(siginfo);
+ // "Real" SIGSEGV codes (e.g., SEGV_MAPERR, SEGV_MAPERR) are non-zero.
+ return si->si_signo == SIGSEGV && si->si_code != 0;
+}
+
static void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
ucontext_t *ucontext = (ucontext_t*)context;
# if defined(__aarch64__)
@@ -1122,7 +1206,7 @@
if (!buffer || !length || length > 256)
return false;
// arc4random never fails.
- arc4random_buf(buffer, length);
+ REAL(arc4random_buf)(buffer, length);
return true;
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_mac_libcdep.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_mac_libcdep.cpp
similarity index 92%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_mac_libcdep.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_mac_libcdep.cpp
index 93fb5b2..ac7e328 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_mac_libcdep.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_mac_libcdep.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_mac_libcdep.cc ------------------------------------------===//
+//===-- sanitizer_mac_libcdep.cpp -----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_malloc_mac.inc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_malloc_mac.inc
index 3f3581e..11adbe5 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_malloc_mac.inc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_malloc_mac.inc
@@ -91,6 +91,15 @@
return &sanitizer_zone;
}
+INTERCEPTOR(malloc_zone_t *, malloc_zone_from_ptr, const void *ptr) {
+ COMMON_MALLOC_ENTER();
+ size_t size = sanitizer_zone.size(&sanitizer_zone, ptr);
+ if (size) { // Claimed by sanitizer zone?
+ return &sanitizer_zone;
+ }
+ return REAL(malloc_zone_from_ptr)(ptr);
+}
+
INTERCEPTOR(malloc_zone_t *, malloc_default_purgeable_zone, void) {
// FIXME: ASan should support purgeable allocations.
// https://github.com/google/sanitizers/issues/139
@@ -226,7 +235,7 @@
}
#define GET_ZONE_FOR_PTR(ptr) \
- malloc_zone_t *zone_ptr = malloc_zone_from_ptr(ptr); \
+ malloc_zone_t *zone_ptr = WRAP(malloc_zone_from_ptr)(ptr); \
const char *zone_name = (zone_ptr == 0) ? 0 : zone_ptr->zone_name
extern "C"
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_netbsd.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_netbsd.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_netbsd.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_netbsd.cpp
index 385008e..49a951e 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_netbsd.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_netbsd.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_netbsd.cc -----------------------------------------------===//
+//===-- sanitizer_netbsd.cpp ----------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -95,7 +95,7 @@
// --------------- sanitizer_libc.h
uptr internal_mmap(void *addr, uptr length, int prot, int flags, int fd,
- OFF_T offset) {
+ u64 offset) {
CHECK(&__mmap);
return (uptr)__mmap(addr, length, prot, flags, fd, 0, offset);
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_openbsd.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_openbsd.cpp
similarity index 97%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_openbsd.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_openbsd.cpp
index b6e9bdf..ed2d8ed 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_openbsd.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_openbsd.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_openbsd.cc ----------------------------------------------===//
+//===-- sanitizer_openbsd.cpp ---------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_persistent_allocator.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_persistent_allocator.cpp
similarity index 90%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_persistent_allocator.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_persistent_allocator.cpp
index ddd9ae9..1ca0375 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_persistent_allocator.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_persistent_allocator.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_persistent_allocator.cc -----------------------*- C++ -*-===//
+//===-- sanitizer_persistent_allocator.cpp ----------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform.h b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform.h
index b45c975..c68bfa2 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform.h
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform.h
@@ -255,11 +255,11 @@
#define SANITIZER_SIGN_EXTENDED_ADDRESSES 0
#endif
-// The AArch64 linux port uses the canonical syscall set as mandated by
-// the upstream linux community for all new ports. Other ports may still
-// use legacy syscalls.
+// The AArch64 and RISC-V linux ports use the canonical syscall set as
+// mandated by the upstream linux community for all new ports. Other ports
+// may still use legacy syscalls.
#ifndef SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
-# if defined(__aarch64__) && SANITIZER_LINUX
+# if (defined(__aarch64__) || defined(__riscv)) && SANITIZER_LINUX
# define SANITIZER_USES_CANONICAL_LINUX_SYSCALLS 1
# else
# define SANITIZER_USES_CANONICAL_LINUX_SYSCALLS 0
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_interceptors.h b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_interceptors.h
index 817d24b..4cc69af 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_interceptors.h
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_interceptors.h
@@ -13,6 +13,7 @@
#ifndef SANITIZER_PLATFORM_INTERCEPTORS_H
#define SANITIZER_PLATFORM_INTERCEPTORS_H
+#include "sanitizer_glibc_version.h"
#include "sanitizer_internal_defs.h"
#if SANITIZER_POSIX
@@ -89,6 +90,24 @@
# define SI_IOS 0
#endif
+#if SANITIZER_IOSSIM
+# define SI_IOSSIM 1
+#else
+# define SI_IOSSIM 0
+#endif
+
+#if SANITIZER_WATCHOS
+# define SI_WATCHOS 1
+#else
+# define SI_WATCHOS 0
+#endif
+
+#if SANITIZER_TVOS
+# define SI_TVOS 1
+#else
+# define SI_TVOS 0
+#endif
+
#if SANITIZER_FUCHSIA
# define SI_NOT_FUCHSIA 0
#else
@@ -331,10 +350,9 @@
#define SANITIZER_INTERCEPT_ETHER_HOST \
(SI_FREEBSD || SI_MAC || SI_LINUX_NOT_ANDROID)
#define SANITIZER_INTERCEPT_ETHER_R (SI_FREEBSD || SI_LINUX_NOT_ANDROID)
-#define SANITIZER_INTERCEPT_SHMCTL \
- (SI_NETBSD || SI_OPENBSD || SI_SOLARIS || \
- ((SI_FREEBSD || SI_LINUX_NOT_ANDROID) && \
- SANITIZER_WORDSIZE == 64)) // NOLINT
+#define SANITIZER_INTERCEPT_SHMCTL \
+ (((SI_FREEBSD || SI_LINUX_NOT_ANDROID) && SANITIZER_WORDSIZE == 64) || \
+ SI_NETBSD || SI_OPENBSD || SI_SOLARIS) // NOLINT
#define SANITIZER_INTERCEPT_RANDOM_R SI_LINUX_NOT_ANDROID
#define SANITIZER_INTERCEPT_PTHREAD_ATTR_GET SI_POSIX
#define SANITIZER_INTERCEPT_PTHREAD_ATTR_GETINHERITSCHED \
@@ -489,7 +507,8 @@
SI_NOT_RTEMS)
#define SANITIZER_INTERCEPT_REALLOCARRAY SI_POSIX
#define SANITIZER_INTERCEPT_ALIGNED_ALLOC (!SI_MAC && SI_NOT_RTEMS)
-#define SANITIZER_INTERCEPT_MALLOC_USABLE_SIZE (!SI_MAC && !SI_OPENBSD)
+#define SANITIZER_INTERCEPT_MALLOC_USABLE_SIZE \
+ (!SI_MAC && !SI_OPENBSD && !SI_NETBSD)
#define SANITIZER_INTERCEPT_MCHECK_MPROBE SI_LINUX_NOT_ANDROID
#define SANITIZER_INTERCEPT_WCSCAT SI_POSIX
#define SANITIZER_INTERCEPT_WCSDUP SI_POSIX
@@ -561,9 +580,21 @@
#define SANITIZER_INTERCEPT_FUNOPEN (SI_NETBSD || SI_FREEBSD)
#define SANITIZER_INTERCEPT_FUNOPEN2 SI_NETBSD
#define SANITIZER_INTERCEPT_GETFSENT (SI_FREEBSD || SI_NETBSD || SI_MAC)
-#define SANITIZER_INTERCEPT_ARC4RANDOM (SI_FREEBSD || SI_NETBSD)
+#define SANITIZER_INTERCEPT_ARC4RANDOM (SI_FREEBSD || SI_NETBSD || SI_MAC)
#define SANITIZER_INTERCEPT_FDEVNAME SI_FREEBSD
-#define SANITIZER_INTERCEPT_GETUSERSHELL (SI_POSIX && !SI_POSIX)
+#define SANITIZER_INTERCEPT_GETUSERSHELL (SI_POSIX && !SI_ANDROID)
#define SANITIZER_INTERCEPT_SL_INIT (SI_FREEBSD || SI_NETBSD)
+#define SANITIZER_INTERCEPT_CRYPT (SI_POSIX && !SI_ANDROID)
+#define SANITIZER_INTERCEPT_CRYPT_R (SI_LINUX && !SI_ANDROID)
+
+#define SANITIZER_INTERCEPT_GETRANDOM \
+ ((SI_LINUX && __GLIBC_PREREQ(2, 25)) || SI_FREEBSD)
+#define SANITIZER_INTERCEPT___CXA_ATEXIT SI_NETBSD
+#define SANITIZER_INTERCEPT_ATEXIT SI_NETBSD
+#define SANITIZER_INTERCEPT_PTHREAD_ATFORK SI_NETBSD
+#define SANITIZER_INTERCEPT_GETENTROPY SI_FREEBSD
+#define SANITIZER_INTERCEPT_QSORT \
+ (SI_POSIX && !SI_IOSSIM && !SI_WATCHOS && !SI_TVOS)
+#define SANITIZER_INTERCEPT_QSORT_R (SI_LINUX && !SI_ANDROID)
#endif // #ifndef SANITIZER_PLATFORM_INTERCEPTORS_H
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_freebsd.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_freebsd.cpp
similarity index 99%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_freebsd.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_freebsd.cpp
index 0348487..2d1bb1a 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_freebsd.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_freebsd.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_platform_limits_freebsd.cc ------------------------------===//
+//===-- sanitizer_platform_limits_freebsd.cpp -----------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_freebsd.h b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_freebsd.h
index 7e162a5..71cf5b9 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_freebsd.h
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_freebsd.h
@@ -30,373 +30,373 @@
#include <sys/_types.h>
namespace __sanitizer {
- extern unsigned struct_utsname_sz;
- extern unsigned struct_stat_sz;
+extern unsigned struct_utsname_sz;
+extern unsigned struct_stat_sz;
#if defined(__powerpc64__)
- const unsigned struct___old_kernel_stat_sz = 0;
+const unsigned struct___old_kernel_stat_sz = 0;
#else
- const unsigned struct___old_kernel_stat_sz = 32;
+const unsigned struct___old_kernel_stat_sz = 32;
#endif
- extern unsigned struct_rusage_sz;
- extern unsigned siginfo_t_sz;
- extern unsigned struct_itimerval_sz;
- extern unsigned pthread_t_sz;
- extern unsigned pthread_mutex_t_sz;
- extern unsigned pthread_cond_t_sz;
- extern unsigned pid_t_sz;
- extern unsigned timeval_sz;
- extern unsigned uid_t_sz;
- extern unsigned gid_t_sz;
- extern unsigned fpos_t_sz;
- extern unsigned mbstate_t_sz;
- extern unsigned struct_timezone_sz;
- extern unsigned struct_tms_sz;
- extern unsigned struct_itimerspec_sz;
- extern unsigned struct_sigevent_sz;
- extern unsigned struct_sched_param_sz;
- extern unsigned struct_statfs64_sz;
- extern unsigned struct_statfs_sz;
- extern unsigned struct_sockaddr_sz;
- extern unsigned ucontext_t_sz;
- extern unsigned struct_rlimit_sz;
- extern unsigned struct_utimbuf_sz;
- extern unsigned struct_timespec_sz;
- extern unsigned struct_regmatch_sz;
- extern unsigned struct_regex_sz;
- extern unsigned struct_FTS_sz;
- extern unsigned struct_FTSENT_sz;
- extern const int unvis_valid;
- extern const int unvis_validpush;
+extern unsigned struct_rusage_sz;
+extern unsigned siginfo_t_sz;
+extern unsigned struct_itimerval_sz;
+extern unsigned pthread_t_sz;
+extern unsigned pthread_mutex_t_sz;
+extern unsigned pthread_cond_t_sz;
+extern unsigned pid_t_sz;
+extern unsigned timeval_sz;
+extern unsigned uid_t_sz;
+extern unsigned gid_t_sz;
+extern unsigned fpos_t_sz;
+extern unsigned mbstate_t_sz;
+extern unsigned struct_timezone_sz;
+extern unsigned struct_tms_sz;
+extern unsigned struct_itimerspec_sz;
+extern unsigned struct_sigevent_sz;
+extern unsigned struct_sched_param_sz;
+extern unsigned struct_statfs64_sz;
+extern unsigned struct_statfs_sz;
+extern unsigned struct_sockaddr_sz;
+extern unsigned ucontext_t_sz;
+extern unsigned struct_rlimit_sz;
+extern unsigned struct_utimbuf_sz;
+extern unsigned struct_timespec_sz;
+extern unsigned struct_regmatch_sz;
+extern unsigned struct_regex_sz;
+extern unsigned struct_FTS_sz;
+extern unsigned struct_FTSENT_sz;
+extern const int unvis_valid;
+extern const int unvis_validpush;
- struct __sanitizer_iocb {
- u64 aio_data;
- u32 aio_key_or_aio_reserved1; // Simply crazy.
- u32 aio_reserved1_or_aio_key; // Luckily, we don't need these.
- u16 aio_lio_opcode;
- s16 aio_reqprio;
- u32 aio_fildes;
- u64 aio_buf;
- u64 aio_nbytes;
- s64 aio_offset;
- u64 aio_reserved2;
- u64 aio_reserved3;
- };
+struct __sanitizer_iocb {
+ u64 aio_data;
+ u32 aio_key_or_aio_reserved1; // Simply crazy.
+ u32 aio_reserved1_or_aio_key; // Luckily, we don't need these.
+ u16 aio_lio_opcode;
+ s16 aio_reqprio;
+ u32 aio_fildes;
+ u64 aio_buf;
+ u64 aio_nbytes;
+ s64 aio_offset;
+ u64 aio_reserved2;
+ u64 aio_reserved3;
+};
- struct __sanitizer_io_event {
- u64 data;
- u64 obj;
- u64 res;
- u64 res2;
- };
+struct __sanitizer_io_event {
+ u64 data;
+ u64 obj;
+ u64 res;
+ u64 res2;
+};
- const unsigned iocb_cmd_pread = 0;
- const unsigned iocb_cmd_pwrite = 1;
- const unsigned iocb_cmd_preadv = 7;
- const unsigned iocb_cmd_pwritev = 8;
+const unsigned iocb_cmd_pread = 0;
+const unsigned iocb_cmd_pwrite = 1;
+const unsigned iocb_cmd_preadv = 7;
+const unsigned iocb_cmd_pwritev = 8;
- struct __sanitizer___sysctl_args {
- int *name;
- int nlen;
- void *oldval;
- uptr *oldlenp;
- void *newval;
- uptr newlen;
- unsigned long ___unused[4];
- };
+struct __sanitizer___sysctl_args {
+ int *name;
+ int nlen;
+ void *oldval;
+ uptr *oldlenp;
+ void *newval;
+ uptr newlen;
+ unsigned long ___unused[4];
+};
- struct __sanitizer_ipc_perm {
- unsigned int cuid;
- unsigned int cgid;
- unsigned int uid;
- unsigned int gid;
- unsigned short mode;
- unsigned short seq;
- long key;
- };
+struct __sanitizer_ipc_perm {
+ unsigned int cuid;
+ unsigned int cgid;
+ unsigned int uid;
+ unsigned int gid;
+ unsigned short mode;
+ unsigned short seq;
+ long key;
+};
- struct __sanitizer_shmid_ds {
- __sanitizer_ipc_perm shm_perm;
- unsigned long shm_segsz;
- unsigned int shm_lpid;
- unsigned int shm_cpid;
- int shm_nattch;
- unsigned long shm_atime;
- unsigned long shm_dtime;
- unsigned long shm_ctime;
- };
+#if !defined(__i386__)
+typedef long long __sanitizer_time_t;
+#else
+typedef long __sanitizer_time_t;
+#endif
- extern unsigned struct_msqid_ds_sz;
- extern unsigned struct_mq_attr_sz;
- extern unsigned struct_timeb_sz;
- extern unsigned struct_statvfs_sz;
+struct __sanitizer_shmid_ds {
+ __sanitizer_ipc_perm shm_perm;
+ unsigned long shm_segsz;
+ unsigned int shm_lpid;
+ unsigned int shm_cpid;
+ int shm_nattch;
+ __sanitizer_time_t shm_atime;
+ __sanitizer_time_t shm_dtime;
+ __sanitizer_time_t shm_ctime;
+};
- struct __sanitizer_iovec {
- void *iov_base;
- uptr iov_len;
- };
+extern unsigned struct_msqid_ds_sz;
+extern unsigned struct_mq_attr_sz;
+extern unsigned struct_timeb_sz;
+extern unsigned struct_statvfs_sz;
- struct __sanitizer_ifaddrs {
- struct __sanitizer_ifaddrs *ifa_next;
- char *ifa_name;
- unsigned int ifa_flags;
- void *ifa_addr; // (struct sockaddr *)
- void *ifa_netmask; // (struct sockaddr *)
+struct __sanitizer_iovec {
+ void *iov_base;
+ uptr iov_len;
+};
+
+struct __sanitizer_ifaddrs {
+ struct __sanitizer_ifaddrs *ifa_next;
+ char *ifa_name;
+ unsigned int ifa_flags;
+ void *ifa_addr; // (struct sockaddr *)
+ void *ifa_netmask; // (struct sockaddr *)
# undef ifa_dstaddr
- void *ifa_dstaddr; // (struct sockaddr *)
- void *ifa_data;
- };
+ void *ifa_dstaddr; // (struct sockaddr *)
+ void *ifa_data;
+};
- typedef unsigned __sanitizer_pthread_key_t;
+typedef unsigned __sanitizer_pthread_key_t;
- struct __sanitizer_passwd {
- char *pw_name;
- char *pw_passwd;
- int pw_uid;
- int pw_gid;
- long pw_change;
- char *pw_class;
- char *pw_gecos;
- char *pw_dir;
- char *pw_shell;
- long pw_expire;
- int pw_fields;
- };
+struct __sanitizer_passwd {
+ char *pw_name;
+ char *pw_passwd;
+ int pw_uid;
+ int pw_gid;
+ __sanitizer_time_t pw_change;
+ char *pw_class;
+ char *pw_gecos;
+ char *pw_dir;
+ char *pw_shell;
+ __sanitizer_time_t pw_expire;
+ int pw_fields;
+};
- struct __sanitizer_group {
- char *gr_name;
- char *gr_passwd;
- int gr_gid;
- char **gr_mem;
- };
+struct __sanitizer_group {
+ char *gr_name;
+ char *gr_passwd;
+ int gr_gid;
+ char **gr_mem;
+};
-#if defined(__LP64___)
- typedef long long __sanitizer_time_t;
-#else
- typedef long __sanitizer_time_t;
-#endif
+typedef long __sanitizer_suseconds_t;
- typedef long __sanitizer_suseconds_t;
+struct __sanitizer_timeval {
+ __sanitizer_time_t tv_sec;
+ __sanitizer_suseconds_t tv_usec;
+};
- struct __sanitizer_timeval {
- __sanitizer_time_t tv_sec;
- __sanitizer_suseconds_t tv_usec;
- };
+struct __sanitizer_itimerval {
+ struct __sanitizer_timeval it_interval;
+ struct __sanitizer_timeval it_value;
+};
- struct __sanitizer_itimerval {
- struct __sanitizer_timeval it_interval;
- struct __sanitizer_timeval it_value;
- };
+struct __sanitizer_timeb {
+ __sanitizer_time_t time;
+ unsigned short millitm;
+ short timezone;
+ short dstflag;
+};
- struct __sanitizer_timeb {
- __sanitizer_time_t time;
- unsigned short millitm;
- short timezone;
- short dstflag;
- };
+struct __sanitizer_ether_addr {
+ u8 octet[6];
+};
- struct __sanitizer_ether_addr {
- u8 octet[6];
- };
+struct __sanitizer_tm {
+ int tm_sec;
+ int tm_min;
+ int tm_hour;
+ int tm_mday;
+ int tm_mon;
+ int tm_year;
+ int tm_wday;
+ int tm_yday;
+ int tm_isdst;
+ long int tm_gmtoff;
+ const char *tm_zone;
+};
- struct __sanitizer_tm {
- int tm_sec;
- int tm_min;
- int tm_hour;
- int tm_mday;
- int tm_mon;
- int tm_year;
- int tm_wday;
- int tm_yday;
- int tm_isdst;
- long int tm_gmtoff;
- const char *tm_zone;
- };
+struct __sanitizer_msghdr {
+ void *msg_name;
+ unsigned msg_namelen;
+ struct __sanitizer_iovec *msg_iov;
+ unsigned msg_iovlen;
+ void *msg_control;
+ unsigned msg_controllen;
+ int msg_flags;
+};
- struct __sanitizer_msghdr {
- void *msg_name;
- unsigned msg_namelen;
- struct __sanitizer_iovec *msg_iov;
- unsigned msg_iovlen;
- void *msg_control;
- unsigned msg_controllen;
- int msg_flags;
- };
+struct __sanitizer_cmsghdr {
+ unsigned cmsg_len;
+ int cmsg_level;
+ int cmsg_type;
+};
- struct __sanitizer_cmsghdr {
- unsigned cmsg_len;
- int cmsg_level;
- int cmsg_type;
- };
-
- struct __sanitizer_dirent {
+struct __sanitizer_dirent {
#if defined(__INO64)
- unsigned long long d_fileno;
- unsigned long long d_off;
+ unsigned long long d_fileno;
+ unsigned long long d_off;
#else
- unsigned int d_fileno;
+ unsigned int d_fileno;
#endif
- unsigned short d_reclen;
- // more fields that we don't care about
- };
+ unsigned short d_reclen;
+ // more fields that we don't care about
+};
// 'clock_t' is 32 bits wide on x64 FreeBSD
- typedef int __sanitizer_clock_t;
- typedef int __sanitizer_clockid_t;
+typedef int __sanitizer_clock_t;
+typedef int __sanitizer_clockid_t;
-#if defined(_LP64) || defined(__x86_64__) || defined(__powerpc__)\
- || defined(__mips__)
- typedef unsigned __sanitizer___kernel_uid_t;
- typedef unsigned __sanitizer___kernel_gid_t;
+#if defined(_LP64) || defined(__x86_64__) || defined(__powerpc__) || \
+ defined(__mips__)
+typedef unsigned __sanitizer___kernel_uid_t;
+typedef unsigned __sanitizer___kernel_gid_t;
#else
- typedef unsigned short __sanitizer___kernel_uid_t;
- typedef unsigned short __sanitizer___kernel_gid_t;
+typedef unsigned short __sanitizer___kernel_uid_t;
+typedef unsigned short __sanitizer___kernel_gid_t;
#endif
- typedef long long __sanitizer___kernel_off_t;
+typedef long long __sanitizer___kernel_off_t;
#if defined(__powerpc__) || defined(__mips__)
- typedef unsigned int __sanitizer___kernel_old_uid_t;
- typedef unsigned int __sanitizer___kernel_old_gid_t;
+typedef unsigned int __sanitizer___kernel_old_uid_t;
+typedef unsigned int __sanitizer___kernel_old_gid_t;
#else
- typedef unsigned short __sanitizer___kernel_old_uid_t;
- typedef unsigned short __sanitizer___kernel_old_gid_t;
+typedef unsigned short __sanitizer___kernel_old_uid_t;
+typedef unsigned short __sanitizer___kernel_old_gid_t;
#endif
- typedef long long __sanitizer___kernel_loff_t;
- typedef struct {
- unsigned long fds_bits[1024 / (8 * sizeof(long))];
- } __sanitizer___kernel_fd_set;
+typedef long long __sanitizer___kernel_loff_t;
+typedef struct {
+ unsigned long fds_bits[1024 / (8 * sizeof(long))];
+} __sanitizer___kernel_fd_set;
- // This thing depends on the platform. We are only interested in the upper
- // limit. Verified with a compiler assert in .cc.
- const int pthread_attr_t_max_sz = 128;
- union __sanitizer_pthread_attr_t {
- char size[pthread_attr_t_max_sz]; // NOLINT
- void *align;
+// This thing depends on the platform. We are only interested in the upper
+// limit. Verified with a compiler assert in .cpp.
+union __sanitizer_pthread_attr_t {
+ char size[128];
+ void *align;
+};
+
+const unsigned old_sigset_t_sz = sizeof(unsigned long);
+
+struct __sanitizer_sigset_t {
+ // uint32_t * 4
+ unsigned int __bits[4];
+};
+
+typedef __sanitizer_sigset_t __sanitizer_kernel_sigset_t;
+
+struct __sanitizer_siginfo {
+ // The size is determined by looking at sizeof of real siginfo_t on linux.
+ u64 opaque[128 / sizeof(u64)];
+};
+
+using __sanitizer_sighandler_ptr = void (*)(int sig);
+using __sanitizer_sigactionhandler_ptr = void (*)(int sig,
+ __sanitizer_siginfo *siginfo,
+ void *uctx);
+
+struct __sanitizer_sigaction {
+ union {
+ __sanitizer_sigactionhandler_ptr sigaction;
+ __sanitizer_sighandler_ptr handler;
};
+ int sa_flags;
+ __sanitizer_sigset_t sa_mask;
+};
- const unsigned old_sigset_t_sz = sizeof(unsigned long);
+struct __sanitizer_sem_t {
+ u32 data[4];
+};
- struct __sanitizer_sigset_t {
- // uint32_t * 4
- unsigned int __bits[4];
- };
+extern const uptr sig_ign;
+extern const uptr sig_dfl;
+extern const uptr sig_err;
+extern const uptr sa_siginfo;
- typedef __sanitizer_sigset_t __sanitizer_kernel_sigset_t;
+extern int af_inet;
+extern int af_inet6;
+uptr __sanitizer_in_addr_sz(int af);
- struct __sanitizer_siginfo {
- // The size is determined by looking at sizeof of real siginfo_t on linux.
- u64 opaque[128 / sizeof(u64)];
- };
+struct __sanitizer_dl_phdr_info {
+ uptr dlpi_addr;
+ const char *dlpi_name;
+ const void *dlpi_phdr;
+ short dlpi_phnum;
+};
- using __sanitizer_sighandler_ptr = void (*)(int sig);
- using __sanitizer_sigactionhandler_ptr =
- void (*)(int sig, __sanitizer_siginfo *siginfo, void *uctx);
+extern unsigned struct_ElfW_Phdr_sz;
- struct __sanitizer_sigaction {
- union {
- __sanitizer_sigactionhandler_ptr sigaction;
- __sanitizer_sighandler_ptr handler;
- };
- int sa_flags;
- __sanitizer_sigset_t sa_mask;
- };
+struct __sanitizer_addrinfo {
+ int ai_flags;
+ int ai_family;
+ int ai_socktype;
+ int ai_protocol;
+ unsigned ai_addrlen;
+ char *ai_canonname;
+ void *ai_addr;
+ struct __sanitizer_addrinfo *ai_next;
+};
- struct __sanitizer_sem_t {
- u32 data[4];
- };
+struct __sanitizer_hostent {
+ char *h_name;
+ char **h_aliases;
+ int h_addrtype;
+ int h_length;
+ char **h_addr_list;
+};
- extern const uptr sig_ign;
- extern const uptr sig_dfl;
- extern const uptr sig_err;
- extern const uptr sa_siginfo;
+struct __sanitizer_pollfd {
+ int fd;
+ short events;
+ short revents;
+};
- extern int af_inet;
- extern int af_inet6;
- uptr __sanitizer_in_addr_sz(int af);
+typedef unsigned __sanitizer_nfds_t;
- struct __sanitizer_dl_phdr_info {
- uptr dlpi_addr;
- const char *dlpi_name;
- const void *dlpi_phdr;
- short dlpi_phnum;
- };
+struct __sanitizer_glob_t {
+ uptr gl_pathc;
+ uptr gl_matchc;
+ uptr gl_offs;
+ int gl_flags;
+ char **gl_pathv;
+ int (*gl_errfunc)(const char *, int);
+ void (*gl_closedir)(void *dirp);
+ struct dirent *(*gl_readdir)(void *dirp);
+ void *(*gl_opendir)(const char *);
+ int (*gl_lstat)(const char *, void * /* struct stat* */);
+ int (*gl_stat)(const char *, void * /* struct stat* */);
+};
- extern unsigned struct_ElfW_Phdr_sz;
+extern int glob_nomatch;
+extern int glob_altdirfunc;
- struct __sanitizer_addrinfo {
- int ai_flags;
- int ai_family;
- int ai_socktype;
- int ai_protocol;
- unsigned ai_addrlen;
- char *ai_canonname;
- void *ai_addr;
- struct __sanitizer_addrinfo *ai_next;
- };
+extern unsigned path_max;
- struct __sanitizer_hostent {
- char *h_name;
- char **h_aliases;
- int h_addrtype;
- int h_length;
- char **h_addr_list;
- };
+struct __sanitizer_wordexp_t {
+ uptr we_wordc;
+ char **we_wordv;
+ uptr we_offs;
+ char *we_strings;
+ uptr we_nbytes;
+};
- struct __sanitizer_pollfd {
- int fd;
- short events;
- short revents;
- };
+typedef void __sanitizer_FILE;
- typedef unsigned __sanitizer_nfds_t;
+extern unsigned struct_shminfo_sz;
+extern unsigned struct_shm_info_sz;
+extern int shmctl_ipc_stat;
+extern int shmctl_ipc_info;
+extern int shmctl_shm_info;
+extern int shmctl_shm_stat;
- struct __sanitizer_glob_t {
- uptr gl_pathc;
- uptr gl_matchc;
- uptr gl_offs;
- int gl_flags;
- char **gl_pathv;
- int (*gl_errfunc)(const char*, int);
- void (*gl_closedir)(void *dirp);
- struct dirent *(*gl_readdir)(void *dirp);
- void *(*gl_opendir)(const char*);
- int (*gl_lstat)(const char*, void* /* struct stat* */);
- int (*gl_stat)(const char*, void* /* struct stat* */);
- };
+extern unsigned struct_utmpx_sz;
- extern int glob_nomatch;
- extern int glob_altdirfunc;
+extern int map_fixed;
- extern unsigned path_max;
-
- struct __sanitizer_wordexp_t {
- uptr we_wordc;
- char **we_wordv;
- uptr we_offs;
- char *we_strings;
- uptr we_nbytes;
- };
-
- typedef void __sanitizer_FILE;
-
- extern unsigned struct_shminfo_sz;
- extern unsigned struct_shm_info_sz;
- extern int shmctl_ipc_stat;
- extern int shmctl_ipc_info;
- extern int shmctl_shm_info;
- extern int shmctl_shm_stat;
-
- extern unsigned struct_utmpx_sz;
-
- extern int map_fixed;
-
- // ioctl arguments
- struct __sanitizer_ifconf {
- int ifc_len;
- union {
- void *ifcu_req;
- } ifc_ifcu;
- };
+// ioctl arguments
+struct __sanitizer_ifconf {
+ int ifc_len;
+ union {
+ void *ifcu_req;
+ } ifc_ifcu;
+};
#define IOC_NRBITS 8
#define IOC_TYPEBITS 8
@@ -432,204 +432,204 @@
#define IOC_NR(nr) (((nr) >> IOC_NRSHIFT) & IOC_NRMASK)
#define IOC_SIZE(nr) (((nr) >> IOC_SIZESHIFT) & IOC_SIZEMASK)
- extern unsigned struct_ifreq_sz;
- extern unsigned struct_termios_sz;
- extern unsigned struct_winsize_sz;
+extern unsigned struct_ifreq_sz;
+extern unsigned struct_termios_sz;
+extern unsigned struct_winsize_sz;
- extern unsigned struct_copr_buffer_sz;
- extern unsigned struct_copr_debug_buf_sz;
- extern unsigned struct_copr_msg_sz;
- extern unsigned struct_midi_info_sz;
- extern unsigned struct_mtget_sz;
- extern unsigned struct_mtop_sz;
- extern unsigned struct_rtentry_sz;
- extern unsigned struct_sbi_instrument_sz;
- extern unsigned struct_seq_event_rec_sz;
- extern unsigned struct_synth_info_sz;
- extern unsigned struct_vt_mode_sz;
+extern unsigned struct_copr_buffer_sz;
+extern unsigned struct_copr_debug_buf_sz;
+extern unsigned struct_copr_msg_sz;
+extern unsigned struct_midi_info_sz;
+extern unsigned struct_mtget_sz;
+extern unsigned struct_mtop_sz;
+extern unsigned struct_rtentry_sz;
+extern unsigned struct_sbi_instrument_sz;
+extern unsigned struct_seq_event_rec_sz;
+extern unsigned struct_synth_info_sz;
+extern unsigned struct_vt_mode_sz;
- extern const unsigned long __sanitizer_bufsiz;
- extern unsigned struct_audio_buf_info_sz;
- extern unsigned struct_ppp_stats_sz;
- extern unsigned struct_sioc_sg_req_sz;
- extern unsigned struct_sioc_vif_req_sz;
+extern const unsigned long __sanitizer_bufsiz;
+extern unsigned struct_audio_buf_info_sz;
+extern unsigned struct_ppp_stats_sz;
+extern unsigned struct_sioc_sg_req_sz;
+extern unsigned struct_sioc_vif_req_sz;
- // ioctl request identifiers
+// ioctl request identifiers
- // A special value to mark ioctls that are not present on the target platform,
- // when it can not be determined without including any system headers.
- extern const unsigned IOCTL_NOT_PRESENT;
+// A special value to mark ioctls that are not present on the target platform,
+// when it can not be determined without including any system headers.
+extern const unsigned IOCTL_NOT_PRESENT;
- extern unsigned IOCTL_FIOASYNC;
- extern unsigned IOCTL_FIOCLEX;
- extern unsigned IOCTL_FIOGETOWN;
- extern unsigned IOCTL_FIONBIO;
- extern unsigned IOCTL_FIONCLEX;
- extern unsigned IOCTL_FIOSETOWN;
- extern unsigned IOCTL_SIOCADDMULTI;
- extern unsigned IOCTL_SIOCATMARK;
- extern unsigned IOCTL_SIOCDELMULTI;
- extern unsigned IOCTL_SIOCGIFADDR;
- extern unsigned IOCTL_SIOCGIFBRDADDR;
- extern unsigned IOCTL_SIOCGIFCONF;
- extern unsigned IOCTL_SIOCGIFDSTADDR;
- extern unsigned IOCTL_SIOCGIFFLAGS;
- extern unsigned IOCTL_SIOCGIFMETRIC;
- extern unsigned IOCTL_SIOCGIFMTU;
- extern unsigned IOCTL_SIOCGIFNETMASK;
- extern unsigned IOCTL_SIOCGPGRP;
- extern unsigned IOCTL_SIOCSIFADDR;
- extern unsigned IOCTL_SIOCSIFBRDADDR;
- extern unsigned IOCTL_SIOCSIFDSTADDR;
- extern unsigned IOCTL_SIOCSIFFLAGS;
- extern unsigned IOCTL_SIOCSIFMETRIC;
- extern unsigned IOCTL_SIOCSIFMTU;
- extern unsigned IOCTL_SIOCSIFNETMASK;
- extern unsigned IOCTL_SIOCSPGRP;
- extern unsigned IOCTL_TIOCCONS;
- extern unsigned IOCTL_TIOCEXCL;
- extern unsigned IOCTL_TIOCGETD;
- extern unsigned IOCTL_TIOCGPGRP;
- extern unsigned IOCTL_TIOCGWINSZ;
- extern unsigned IOCTL_TIOCMBIC;
- extern unsigned IOCTL_TIOCMBIS;
- extern unsigned IOCTL_TIOCMGET;
- extern unsigned IOCTL_TIOCMSET;
- extern unsigned IOCTL_TIOCNOTTY;
- extern unsigned IOCTL_TIOCNXCL;
- extern unsigned IOCTL_TIOCOUTQ;
- extern unsigned IOCTL_TIOCPKT;
- extern unsigned IOCTL_TIOCSCTTY;
- extern unsigned IOCTL_TIOCSETD;
- extern unsigned IOCTL_TIOCSPGRP;
- extern unsigned IOCTL_TIOCSTI;
- extern unsigned IOCTL_TIOCSWINSZ;
- extern unsigned IOCTL_SIOCGETSGCNT;
- extern unsigned IOCTL_SIOCGETVIFCNT;
- extern unsigned IOCTL_MTIOCGET;
- extern unsigned IOCTL_MTIOCTOP;
- extern unsigned IOCTL_SIOCADDRT;
- extern unsigned IOCTL_SIOCDELRT;
- extern unsigned IOCTL_SNDCTL_DSP_GETBLKSIZE;
- extern unsigned IOCTL_SNDCTL_DSP_GETFMTS;
- extern unsigned IOCTL_SNDCTL_DSP_NONBLOCK;
- extern unsigned IOCTL_SNDCTL_DSP_POST;
- extern unsigned IOCTL_SNDCTL_DSP_RESET;
- extern unsigned IOCTL_SNDCTL_DSP_SETFMT;
- extern unsigned IOCTL_SNDCTL_DSP_SETFRAGMENT;
- extern unsigned IOCTL_SNDCTL_DSP_SPEED;
- extern unsigned IOCTL_SNDCTL_DSP_STEREO;
- extern unsigned IOCTL_SNDCTL_DSP_SUBDIVIDE;
- extern unsigned IOCTL_SNDCTL_DSP_SYNC;
- extern unsigned IOCTL_SNDCTL_FM_4OP_ENABLE;
- extern unsigned IOCTL_SNDCTL_FM_LOAD_INSTR;
- extern unsigned IOCTL_SNDCTL_MIDI_INFO;
- extern unsigned IOCTL_SNDCTL_MIDI_PRETIME;
- extern unsigned IOCTL_SNDCTL_SEQ_CTRLRATE;
- extern unsigned IOCTL_SNDCTL_SEQ_GETINCOUNT;
- extern unsigned IOCTL_SNDCTL_SEQ_GETOUTCOUNT;
- extern unsigned IOCTL_SNDCTL_SEQ_NRMIDIS;
- extern unsigned IOCTL_SNDCTL_SEQ_NRSYNTHS;
- extern unsigned IOCTL_SNDCTL_SEQ_OUTOFBAND;
- extern unsigned IOCTL_SNDCTL_SEQ_PANIC;
- extern unsigned IOCTL_SNDCTL_SEQ_PERCMODE;
- extern unsigned IOCTL_SNDCTL_SEQ_RESET;
- extern unsigned IOCTL_SNDCTL_SEQ_RESETSAMPLES;
- extern unsigned IOCTL_SNDCTL_SEQ_SYNC;
- extern unsigned IOCTL_SNDCTL_SEQ_TESTMIDI;
- extern unsigned IOCTL_SNDCTL_SEQ_THRESHOLD;
- extern unsigned IOCTL_SNDCTL_SYNTH_INFO;
- extern unsigned IOCTL_SNDCTL_SYNTH_MEMAVL;
- extern unsigned IOCTL_SNDCTL_TMR_CONTINUE;
- extern unsigned IOCTL_SNDCTL_TMR_METRONOME;
- extern unsigned IOCTL_SNDCTL_TMR_SELECT;
- extern unsigned IOCTL_SNDCTL_TMR_SOURCE;
- extern unsigned IOCTL_SNDCTL_TMR_START;
- extern unsigned IOCTL_SNDCTL_TMR_STOP;
- extern unsigned IOCTL_SNDCTL_TMR_TEMPO;
- extern unsigned IOCTL_SNDCTL_TMR_TIMEBASE;
- extern unsigned IOCTL_SOUND_MIXER_READ_ALTPCM;
- extern unsigned IOCTL_SOUND_MIXER_READ_BASS;
- extern unsigned IOCTL_SOUND_MIXER_READ_CAPS;
- extern unsigned IOCTL_SOUND_MIXER_READ_CD;
- extern unsigned IOCTL_SOUND_MIXER_READ_DEVMASK;
- extern unsigned IOCTL_SOUND_MIXER_READ_ENHANCE;
- extern unsigned IOCTL_SOUND_MIXER_READ_IGAIN;
- extern unsigned IOCTL_SOUND_MIXER_READ_IMIX;
- extern unsigned IOCTL_SOUND_MIXER_READ_LINE1;
- extern unsigned IOCTL_SOUND_MIXER_READ_LINE2;
- extern unsigned IOCTL_SOUND_MIXER_READ_LINE3;
- extern unsigned IOCTL_SOUND_MIXER_READ_LINE;
- extern unsigned IOCTL_SOUND_MIXER_READ_LOUD;
- extern unsigned IOCTL_SOUND_MIXER_READ_MIC;
- extern unsigned IOCTL_SOUND_MIXER_READ_MUTE;
- extern unsigned IOCTL_SOUND_MIXER_READ_OGAIN;
- extern unsigned IOCTL_SOUND_MIXER_READ_PCM;
- extern unsigned IOCTL_SOUND_MIXER_READ_RECLEV;
- extern unsigned IOCTL_SOUND_MIXER_READ_RECMASK;
- extern unsigned IOCTL_SOUND_MIXER_READ_RECSRC;
- extern unsigned IOCTL_SOUND_MIXER_READ_SPEAKER;
- extern unsigned IOCTL_SOUND_MIXER_READ_STEREODEVS;
- extern unsigned IOCTL_SOUND_MIXER_READ_SYNTH;
- extern unsigned IOCTL_SOUND_MIXER_READ_TREBLE;
- extern unsigned IOCTL_SOUND_MIXER_READ_VOLUME;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_ALTPCM;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_BASS;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_CD;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_ENHANCE;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_IGAIN;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_IMIX;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_LINE1;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_LINE2;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_LINE3;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_LINE;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_LOUD;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_MIC;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_MUTE;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_OGAIN;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_PCM;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_RECLEV;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_RECSRC;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_SPEAKER;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_SYNTH;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_TREBLE;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_VOLUME;
- extern unsigned IOCTL_SOUND_PCM_READ_BITS;
- extern unsigned IOCTL_SOUND_PCM_READ_CHANNELS;
- extern unsigned IOCTL_SOUND_PCM_READ_FILTER;
- extern unsigned IOCTL_SOUND_PCM_READ_RATE;
- extern unsigned IOCTL_SOUND_PCM_WRITE_CHANNELS;
- extern unsigned IOCTL_SOUND_PCM_WRITE_FILTER;
- extern unsigned IOCTL_VT_ACTIVATE;
- extern unsigned IOCTL_VT_GETMODE;
- extern unsigned IOCTL_VT_OPENQRY;
- extern unsigned IOCTL_VT_RELDISP;
- extern unsigned IOCTL_VT_SETMODE;
- extern unsigned IOCTL_VT_WAITACTIVE;
- extern unsigned IOCTL_GIO_SCRNMAP;
- extern unsigned IOCTL_KDDISABIO;
- extern unsigned IOCTL_KDENABIO;
- extern unsigned IOCTL_KDGETLED;
- extern unsigned IOCTL_KDGETMODE;
- extern unsigned IOCTL_KDGKBMODE;
- extern unsigned IOCTL_KDGKBTYPE;
- extern unsigned IOCTL_KDMKTONE;
- extern unsigned IOCTL_KDSETLED;
- extern unsigned IOCTL_KDSETMODE;
- extern unsigned IOCTL_KDSKBMODE;
+extern unsigned IOCTL_FIOASYNC;
+extern unsigned IOCTL_FIOCLEX;
+extern unsigned IOCTL_FIOGETOWN;
+extern unsigned IOCTL_FIONBIO;
+extern unsigned IOCTL_FIONCLEX;
+extern unsigned IOCTL_FIOSETOWN;
+extern unsigned IOCTL_SIOCADDMULTI;
+extern unsigned IOCTL_SIOCATMARK;
+extern unsigned IOCTL_SIOCDELMULTI;
+extern unsigned IOCTL_SIOCGIFADDR;
+extern unsigned IOCTL_SIOCGIFBRDADDR;
+extern unsigned IOCTL_SIOCGIFCONF;
+extern unsigned IOCTL_SIOCGIFDSTADDR;
+extern unsigned IOCTL_SIOCGIFFLAGS;
+extern unsigned IOCTL_SIOCGIFMETRIC;
+extern unsigned IOCTL_SIOCGIFMTU;
+extern unsigned IOCTL_SIOCGIFNETMASK;
+extern unsigned IOCTL_SIOCGPGRP;
+extern unsigned IOCTL_SIOCSIFADDR;
+extern unsigned IOCTL_SIOCSIFBRDADDR;
+extern unsigned IOCTL_SIOCSIFDSTADDR;
+extern unsigned IOCTL_SIOCSIFFLAGS;
+extern unsigned IOCTL_SIOCSIFMETRIC;
+extern unsigned IOCTL_SIOCSIFMTU;
+extern unsigned IOCTL_SIOCSIFNETMASK;
+extern unsigned IOCTL_SIOCSPGRP;
+extern unsigned IOCTL_TIOCCONS;
+extern unsigned IOCTL_TIOCEXCL;
+extern unsigned IOCTL_TIOCGETD;
+extern unsigned IOCTL_TIOCGPGRP;
+extern unsigned IOCTL_TIOCGWINSZ;
+extern unsigned IOCTL_TIOCMBIC;
+extern unsigned IOCTL_TIOCMBIS;
+extern unsigned IOCTL_TIOCMGET;
+extern unsigned IOCTL_TIOCMSET;
+extern unsigned IOCTL_TIOCNOTTY;
+extern unsigned IOCTL_TIOCNXCL;
+extern unsigned IOCTL_TIOCOUTQ;
+extern unsigned IOCTL_TIOCPKT;
+extern unsigned IOCTL_TIOCSCTTY;
+extern unsigned IOCTL_TIOCSETD;
+extern unsigned IOCTL_TIOCSPGRP;
+extern unsigned IOCTL_TIOCSTI;
+extern unsigned IOCTL_TIOCSWINSZ;
+extern unsigned IOCTL_SIOCGETSGCNT;
+extern unsigned IOCTL_SIOCGETVIFCNT;
+extern unsigned IOCTL_MTIOCGET;
+extern unsigned IOCTL_MTIOCTOP;
+extern unsigned IOCTL_SIOCADDRT;
+extern unsigned IOCTL_SIOCDELRT;
+extern unsigned IOCTL_SNDCTL_DSP_GETBLKSIZE;
+extern unsigned IOCTL_SNDCTL_DSP_GETFMTS;
+extern unsigned IOCTL_SNDCTL_DSP_NONBLOCK;
+extern unsigned IOCTL_SNDCTL_DSP_POST;
+extern unsigned IOCTL_SNDCTL_DSP_RESET;
+extern unsigned IOCTL_SNDCTL_DSP_SETFMT;
+extern unsigned IOCTL_SNDCTL_DSP_SETFRAGMENT;
+extern unsigned IOCTL_SNDCTL_DSP_SPEED;
+extern unsigned IOCTL_SNDCTL_DSP_STEREO;
+extern unsigned IOCTL_SNDCTL_DSP_SUBDIVIDE;
+extern unsigned IOCTL_SNDCTL_DSP_SYNC;
+extern unsigned IOCTL_SNDCTL_FM_4OP_ENABLE;
+extern unsigned IOCTL_SNDCTL_FM_LOAD_INSTR;
+extern unsigned IOCTL_SNDCTL_MIDI_INFO;
+extern unsigned IOCTL_SNDCTL_MIDI_PRETIME;
+extern unsigned IOCTL_SNDCTL_SEQ_CTRLRATE;
+extern unsigned IOCTL_SNDCTL_SEQ_GETINCOUNT;
+extern unsigned IOCTL_SNDCTL_SEQ_GETOUTCOUNT;
+extern unsigned IOCTL_SNDCTL_SEQ_NRMIDIS;
+extern unsigned IOCTL_SNDCTL_SEQ_NRSYNTHS;
+extern unsigned IOCTL_SNDCTL_SEQ_OUTOFBAND;
+extern unsigned IOCTL_SNDCTL_SEQ_PANIC;
+extern unsigned IOCTL_SNDCTL_SEQ_PERCMODE;
+extern unsigned IOCTL_SNDCTL_SEQ_RESET;
+extern unsigned IOCTL_SNDCTL_SEQ_RESETSAMPLES;
+extern unsigned IOCTL_SNDCTL_SEQ_SYNC;
+extern unsigned IOCTL_SNDCTL_SEQ_TESTMIDI;
+extern unsigned IOCTL_SNDCTL_SEQ_THRESHOLD;
+extern unsigned IOCTL_SNDCTL_SYNTH_INFO;
+extern unsigned IOCTL_SNDCTL_SYNTH_MEMAVL;
+extern unsigned IOCTL_SNDCTL_TMR_CONTINUE;
+extern unsigned IOCTL_SNDCTL_TMR_METRONOME;
+extern unsigned IOCTL_SNDCTL_TMR_SELECT;
+extern unsigned IOCTL_SNDCTL_TMR_SOURCE;
+extern unsigned IOCTL_SNDCTL_TMR_START;
+extern unsigned IOCTL_SNDCTL_TMR_STOP;
+extern unsigned IOCTL_SNDCTL_TMR_TEMPO;
+extern unsigned IOCTL_SNDCTL_TMR_TIMEBASE;
+extern unsigned IOCTL_SOUND_MIXER_READ_ALTPCM;
+extern unsigned IOCTL_SOUND_MIXER_READ_BASS;
+extern unsigned IOCTL_SOUND_MIXER_READ_CAPS;
+extern unsigned IOCTL_SOUND_MIXER_READ_CD;
+extern unsigned IOCTL_SOUND_MIXER_READ_DEVMASK;
+extern unsigned IOCTL_SOUND_MIXER_READ_ENHANCE;
+extern unsigned IOCTL_SOUND_MIXER_READ_IGAIN;
+extern unsigned IOCTL_SOUND_MIXER_READ_IMIX;
+extern unsigned IOCTL_SOUND_MIXER_READ_LINE1;
+extern unsigned IOCTL_SOUND_MIXER_READ_LINE2;
+extern unsigned IOCTL_SOUND_MIXER_READ_LINE3;
+extern unsigned IOCTL_SOUND_MIXER_READ_LINE;
+extern unsigned IOCTL_SOUND_MIXER_READ_LOUD;
+extern unsigned IOCTL_SOUND_MIXER_READ_MIC;
+extern unsigned IOCTL_SOUND_MIXER_READ_MUTE;
+extern unsigned IOCTL_SOUND_MIXER_READ_OGAIN;
+extern unsigned IOCTL_SOUND_MIXER_READ_PCM;
+extern unsigned IOCTL_SOUND_MIXER_READ_RECLEV;
+extern unsigned IOCTL_SOUND_MIXER_READ_RECMASK;
+extern unsigned IOCTL_SOUND_MIXER_READ_RECSRC;
+extern unsigned IOCTL_SOUND_MIXER_READ_SPEAKER;
+extern unsigned IOCTL_SOUND_MIXER_READ_STEREODEVS;
+extern unsigned IOCTL_SOUND_MIXER_READ_SYNTH;
+extern unsigned IOCTL_SOUND_MIXER_READ_TREBLE;
+extern unsigned IOCTL_SOUND_MIXER_READ_VOLUME;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_ALTPCM;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_BASS;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_CD;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_ENHANCE;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_IGAIN;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_IMIX;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_LINE1;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_LINE2;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_LINE3;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_LINE;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_LOUD;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_MIC;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_MUTE;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_OGAIN;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_PCM;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_RECLEV;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_RECSRC;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_SPEAKER;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_SYNTH;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_TREBLE;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_VOLUME;
+extern unsigned IOCTL_SOUND_PCM_READ_BITS;
+extern unsigned IOCTL_SOUND_PCM_READ_CHANNELS;
+extern unsigned IOCTL_SOUND_PCM_READ_FILTER;
+extern unsigned IOCTL_SOUND_PCM_READ_RATE;
+extern unsigned IOCTL_SOUND_PCM_WRITE_CHANNELS;
+extern unsigned IOCTL_SOUND_PCM_WRITE_FILTER;
+extern unsigned IOCTL_VT_ACTIVATE;
+extern unsigned IOCTL_VT_GETMODE;
+extern unsigned IOCTL_VT_OPENQRY;
+extern unsigned IOCTL_VT_RELDISP;
+extern unsigned IOCTL_VT_SETMODE;
+extern unsigned IOCTL_VT_WAITACTIVE;
+extern unsigned IOCTL_GIO_SCRNMAP;
+extern unsigned IOCTL_KDDISABIO;
+extern unsigned IOCTL_KDENABIO;
+extern unsigned IOCTL_KDGETLED;
+extern unsigned IOCTL_KDGETMODE;
+extern unsigned IOCTL_KDGKBMODE;
+extern unsigned IOCTL_KDGKBTYPE;
+extern unsigned IOCTL_KDMKTONE;
+extern unsigned IOCTL_KDSETLED;
+extern unsigned IOCTL_KDSETMODE;
+extern unsigned IOCTL_KDSKBMODE;
- extern const int si_SEGV_MAPERR;
- extern const int si_SEGV_ACCERR;
+extern const int si_SEGV_MAPERR;
+extern const int si_SEGV_ACCERR;
- struct __sanitizer_cap_rights {
- u64 cr_rights[2];
- };
+struct __sanitizer_cap_rights {
+ u64 cr_rights[2];
+};
- typedef struct __sanitizer_cap_rights __sanitizer_cap_rights_t;
- extern unsigned struct_cap_rights_sz;
+typedef struct __sanitizer_cap_rights __sanitizer_cap_rights_t;
+extern unsigned struct_cap_rights_sz;
- extern unsigned struct_fstab_sz;
- extern unsigned struct_StringList_sz;
+extern unsigned struct_fstab_sz;
+extern unsigned struct_StringList_sz;
} // namespace __sanitizer
#define CHECK_TYPE_SIZE(TYPE) \
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_linux.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_linux.cpp
similarity index 95%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_linux.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_linux.cpp
index 14b0821..c51327e 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_linux.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_linux.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_platform_limits_linux.cc --------------------------------===//
+//===-- sanitizer_platform_limits_linux.cpp -------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -13,7 +13,7 @@
// This is a separate compilation unit for linux headers that conflict with
// userspace headers.
-// Most "normal" includes go in sanitizer_platform_limits_posix.cc
+// Most "normal" includes go in sanitizer_platform_limits_posix.cpp
#include "sanitizer_platform.h"
#if SANITIZER_LINUX
@@ -65,7 +65,7 @@
#if !defined(__powerpc64__) && !defined(__x86_64__) && !defined(__aarch64__)\
&& !defined(__mips__) && !defined(__s390__)\
- && !defined(__sparc__)
+ && !defined(__sparc__) && !defined(__riscv)
COMPILER_CHECK(struct___old_kernel_stat_sz == sizeof(struct __old_kernel_stat));
#endif
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_netbsd.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_netbsd.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_netbsd.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_netbsd.cpp
index 87a55e5..48a78c8 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_netbsd.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_netbsd.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_platform_limits_netbsd.cc -------------------------------===//
+//===-- sanitizer_platform_limits_netbsd.cpp ------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -17,6 +17,7 @@
#define _KMEMUSER
#define RAY_DO_SIGLEV
+#define __LEGACY_PT_LWPINFO
// clang-format off
#include <sys/param.h>
@@ -71,6 +72,15 @@
#include <sys/msg.h>
#include <sys/mtio.h>
#include <sys/ptrace.h>
+
+// Compat for NetBSD < 9.99.30.
+#ifndef PT_LWPSTATUS
+#define PT_LWPSTATUS 24
+#endif
+#ifndef PT_LWPNEXT
+#define PT_LWPNEXT 25
+#endif
+
#include <sys/resource.h>
#include <sys/sem.h>
#include <sys/sha1.h>
@@ -109,7 +119,12 @@
#include <dev/dmover/dmover_io.h>
#include <dev/dtv/dtvio_demux.h>
#include <dev/dtv/dtvio_frontend.h>
+#if !__NetBSD_Prereq__(9, 99, 26)
#include <dev/filemon/filemon.h>
+#else
+#define FILEMON_SET_FD _IOWR('S', 1, int)
+#define FILEMON_SET_PID _IOWR('S', 2, pid_t)
+#endif
#include <dev/hdaudio/hdaudioio.h>
#include <dev/hdmicec/hdmicecio.h>
#include <dev/hpc/hpcfbio.h>
@@ -287,6 +302,8 @@
int ptrace_pt_get_process_state = PT_GET_PROCESS_STATE;
int ptrace_pt_set_siginfo = PT_SET_SIGINFO;
int ptrace_pt_get_siginfo = PT_GET_SIGINFO;
+int ptrace_pt_lwpstatus = PT_LWPSTATUS;
+int ptrace_pt_lwpnext = PT_LWPNEXT;
int ptrace_piod_read_d = PIOD_READ_D;
int ptrace_piod_write_d = PIOD_WRITE_D;
int ptrace_piod_read_i = PIOD_READ_I;
@@ -319,6 +336,8 @@
unsigned struct_ptrace_ptrace_io_desc_struct_sz = sizeof(struct ptrace_io_desc);
unsigned struct_ptrace_ptrace_lwpinfo_struct_sz = sizeof(struct ptrace_lwpinfo);
+unsigned struct_ptrace_ptrace_lwpstatus_struct_sz =
+ sizeof(struct __sanitizer_ptrace_lwpstatus);
unsigned struct_ptrace_ptrace_event_struct_sz = sizeof(ptrace_event_t);
unsigned struct_ptrace_ptrace_siginfo_struct_sz = sizeof(ptrace_siginfo_t);
@@ -698,6 +717,7 @@
sizeof(nvmm_ioc_machine_configure);
unsigned struct_nvmm_ioc_vcpu_create_sz = sizeof(nvmm_ioc_vcpu_create);
unsigned struct_nvmm_ioc_vcpu_destroy_sz = sizeof(nvmm_ioc_vcpu_destroy);
+unsigned struct_nvmm_ioc_vcpu_configure_sz = sizeof(nvmm_ioc_vcpu_configure);
unsigned struct_nvmm_ioc_vcpu_setstate_sz = sizeof(nvmm_ioc_vcpu_destroy);
unsigned struct_nvmm_ioc_vcpu_getstate_sz = sizeof(nvmm_ioc_vcpu_getstate);
unsigned struct_nvmm_ioc_vcpu_inject_sz = sizeof(nvmm_ioc_vcpu_inject);
@@ -1458,6 +1478,7 @@
unsigned IOCTL_NVMM_IOC_MACHINE_CONFIGURE = NVMM_IOC_MACHINE_CONFIGURE;
unsigned IOCTL_NVMM_IOC_VCPU_CREATE = NVMM_IOC_VCPU_CREATE;
unsigned IOCTL_NVMM_IOC_VCPU_DESTROY = NVMM_IOC_VCPU_DESTROY;
+unsigned IOCTL_NVMM_IOC_VCPU_CONFIGURE = NVMM_IOC_VCPU_CONFIGURE;
unsigned IOCTL_NVMM_IOC_VCPU_SETSTATE = NVMM_IOC_VCPU_SETSTATE;
unsigned IOCTL_NVMM_IOC_VCPU_GETSTATE = NVMM_IOC_VCPU_GETSTATE;
unsigned IOCTL_NVMM_IOC_VCPU_INJECT = NVMM_IOC_VCPU_INJECT;
@@ -1534,6 +1555,7 @@
unsigned IOCTL_IOC_NPF_SAVE = IOC_NPF_SAVE;
unsigned IOCTL_IOC_NPF_RULE = IOC_NPF_RULE;
unsigned IOCTL_IOC_NPF_CONN_LOOKUP = IOC_NPF_CONN_LOOKUP;
+unsigned IOCTL_IOC_NPF_TABLE_REPLACE = IOC_NPF_TABLE_REPLACE;
unsigned IOCTL_PPPOESETPARMS = PPPOESETPARMS;
unsigned IOCTL_PPPOEGETPARMS = PPPOEGETPARMS;
unsigned IOCTL_PPPOEGETSESSION = PPPOEGETSESSION;
@@ -2392,4 +2414,42 @@
CHECK_SIZE_AND_OFFSET(modctl_load_t, ml_props);
CHECK_SIZE_AND_OFFSET(modctl_load_t, ml_propslen);
+// Compat with 9.0
+struct statvfs90 {
+ unsigned long f_flag;
+ unsigned long f_bsize;
+ unsigned long f_frsize;
+ unsigned long f_iosize;
+
+ u64 f_blocks;
+ u64 f_bfree;
+ u64 f_bavail;
+ u64 f_bresvd;
+
+ u64 f_files;
+ u64 f_ffree;
+ u64 f_favail;
+ u64 f_fresvd;
+
+ u64 f_syncreads;
+ u64 f_syncwrites;
+
+ u64 f_asyncreads;
+ u64 f_asyncwrites;
+
+ struct {
+ s32 __fsid_val[2];
+ } f_fsidx;
+ unsigned long f_fsid;
+ unsigned long f_namemax;
+ u32 f_owner;
+
+ u32 f_spare[4];
+
+ char f_fstypename[32];
+ char f_mntonname[32];
+ char f_mntfromname[32];
+};
+unsigned struct_statvfs90_sz = sizeof(struct statvfs90);
+
#endif // SANITIZER_NETBSD
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_netbsd.h b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_netbsd.h
index 4fb3b8c..794efdb 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_netbsd.h
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_netbsd.h
@@ -354,7 +354,13 @@
int ai_family;
int ai_socktype;
int ai_protocol;
+#if defined(__sparc__) && defined(_LP64)
+ int __ai_pad0;
+#endif
unsigned ai_addrlen;
+#if defined(__alpha__) || (defined(__i386__) && defined(_LP64))
+ int __ai_pad0;
+#endif
char *ai_canonname;
void *ai_addr;
struct __sanitizer_addrinfo *ai_next;
@@ -406,6 +412,8 @@
extern int ptrace_pt_get_process_state;
extern int ptrace_pt_set_siginfo;
extern int ptrace_pt_get_siginfo;
+extern int ptrace_pt_lwpstatus;
+extern int ptrace_pt_lwpnext;
extern int ptrace_piod_read_d;
extern int ptrace_piod_write_d;
extern int ptrace_piod_read_i;
@@ -430,8 +438,17 @@
int pl_event;
};
+struct __sanitizer_ptrace_lwpstatus {
+ __sanitizer_lwpid_t pl_lwpid;
+ __sanitizer_sigset_t pl_sigpend;
+ __sanitizer_sigset_t pl_sigmask;
+ char pl_name[20];
+ void *pl_private;
+};
+
extern unsigned struct_ptrace_ptrace_io_desc_struct_sz;
extern unsigned struct_ptrace_ptrace_lwpinfo_struct_sz;
+extern unsigned struct_ptrace_ptrace_lwpstatus_struct_sz;
extern unsigned struct_ptrace_ptrace_event_struct_sz;
extern unsigned struct_ptrace_ptrace_siginfo_struct_sz;
@@ -856,6 +873,7 @@
extern unsigned struct_nvmm_ioc_machine_configure_sz;
extern unsigned struct_nvmm_ioc_vcpu_create_sz;
extern unsigned struct_nvmm_ioc_vcpu_destroy_sz;
+extern unsigned struct_nvmm_ioc_vcpu_configure_sz;
extern unsigned struct_nvmm_ioc_vcpu_setstate_sz;
extern unsigned struct_nvmm_ioc_vcpu_getstate_sz;
extern unsigned struct_nvmm_ioc_vcpu_inject_sz;
@@ -1605,6 +1623,7 @@
extern unsigned IOCTL_NVMM_IOC_MACHINE_CONFIGURE;
extern unsigned IOCTL_NVMM_IOC_VCPU_CREATE;
extern unsigned IOCTL_NVMM_IOC_VCPU_DESTROY;
+extern unsigned IOCTL_NVMM_IOC_VCPU_CONFIGURE;
extern unsigned IOCTL_NVMM_IOC_VCPU_SETSTATE;
extern unsigned IOCTL_NVMM_IOC_VCPU_GETSTATE;
extern unsigned IOCTL_NVMM_IOC_VCPU_INJECT;
@@ -1679,6 +1698,7 @@
extern unsigned IOCTL_IOC_NPF_SAVE;
extern unsigned IOCTL_IOC_NPF_RULE;
extern unsigned IOCTL_IOC_NPF_CONN_LOOKUP;
+extern unsigned IOCTL_IOC_NPF_TABLE_REPLACE;
extern unsigned IOCTL_PPPOESETPARMS;
extern unsigned IOCTL_PPPOEGETPARMS;
extern unsigned IOCTL_PPPOEGETSESSION;
@@ -2400,6 +2420,9 @@
#define SIGACTION_SYMNAME __sigaction14
+// Compat with 9.0
+extern unsigned struct_statvfs90_sz;
+
#endif // SANITIZER_NETBSD
#endif
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_openbsd.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_openbsd.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_openbsd.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_openbsd.cpp
index 5a1b07f..1251562 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_openbsd.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_openbsd.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_platform_limits_openbsd.cc ------------------------------===//
+//===-- sanitizer_platform_limits_openbsd.cpp -----------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_posix.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_posix.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_posix.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_posix.cpp
index e9c1b1a..8419d27 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_posix.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_posix.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_platform_limits_posix.cc --------------------------------===//
+//===-- sanitizer_platform_limits_posix.cpp -------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -22,6 +22,10 @@
#ifdef _FILE_OFFSET_BITS
#undef _FILE_OFFSET_BITS
#endif
+
+// Must go after undef _FILE_OFFSET_BITS.
+#include "sanitizer_glibc_version.h"
+
#include <arpa/inet.h>
#include <dirent.h>
#include <grp.h>
@@ -137,6 +141,7 @@
#include <linux/serial.h>
#include <sys/msg.h>
#include <sys/ipc.h>
+#include <crypt.h>
#endif // SANITIZER_LINUX && !SANITIZER_ANDROID
#if SANITIZER_ANDROID
@@ -226,7 +231,7 @@
// has been removed from glibc 2.28.
#if defined(__aarch64__) || defined(__s390x__) || defined (__mips64) \
|| defined(__powerpc64__) || defined(__arch64__) || defined(__sparcv9) \
- || defined(__x86_64__)
+ || defined(__x86_64__) || (defined(__riscv) && __riscv_xlen == 64)
#define SIZEOF_STRUCT_USTAT 32
#elif defined(__arm__) || defined(__i386__) || defined(__mips__) \
|| defined(__powerpc__) || defined(__s390__) || defined(__sparc__)
@@ -237,6 +242,7 @@
unsigned struct_ustat_sz = SIZEOF_STRUCT_USTAT;
unsigned struct_rlimit64_sz = sizeof(struct rlimit64);
unsigned struct_statvfs64_sz = sizeof(struct statvfs64);
+ unsigned struct_crypt_data_sz = sizeof(struct crypt_data);
#endif // SANITIZER_LINUX && !SANITIZER_ANDROID
#if SANITIZER_LINUX && !SANITIZER_ANDROID
@@ -1006,10 +1012,6 @@
CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_level);
CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_type);
-#ifndef __GLIBC_PREREQ
-#define __GLIBC_PREREQ(x, y) 0
-#endif
-
#if SANITIZER_LINUX && (__ANDROID_API__ >= 21 || __GLIBC_PREREQ (2, 14))
// CHECK_TYPE_SIZE(mmsghdr);
// CHECK_SIZE_AND_OFFSET(mmsghdr, msg_hdr);
@@ -1127,11 +1129,11 @@
CHECK_SIZE_AND_OFFSET(ipc_perm, gid);
CHECK_SIZE_AND_OFFSET(ipc_perm, cuid);
CHECK_SIZE_AND_OFFSET(ipc_perm, cgid);
-// This patch is no longer necessary on LLVM 10.
-// #if !defined(__aarch64__) || !SANITIZER_LINUX || __GLIBC_PREREQ (2, 21)
-// /* On aarch64 glibc 2.20 and earlier provided incorrect mode field. */
-// CHECK_SIZE_AND_OFFSET(ipc_perm, mode);
-// #endif
+#if !SANITIZER_LINUX || __GLIBC_PREREQ (2, 31)
+/* glibc 2.30 and earlier provided 16-bit mode field instead of 32-bit
+ on many architectures. */
+CHECK_SIZE_AND_OFFSET(ipc_perm, mode);
+#endif
CHECK_TYPE_SIZE(shmid_ds);
CHECK_SIZE_AND_OFFSET(shmid_ds, shm_perm);
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_posix.h b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_posix.h
index f1a4fd7..5337b26 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_posix.h
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_posix.h
@@ -19,844 +19,836 @@
#include "sanitizer_internal_defs.h"
#include "sanitizer_platform.h"
+#if defined(__sparc__)
+// FIXME: This can't be included from tsan which does not support sparc yet.
+#include "sanitizer_glibc_version.h"
+#endif
+
# define GET_LINK_MAP_BY_DLOPEN_HANDLE(handle) ((link_map*)(handle))
-#ifndef __GLIBC_PREREQ
-#define __GLIBC_PREREQ(x, y) 0
-#endif
-
namespace __sanitizer {
- extern unsigned struct_utsname_sz;
- extern unsigned struct_stat_sz;
+extern unsigned struct_utsname_sz;
+extern unsigned struct_stat_sz;
#if !SANITIZER_IOS
- extern unsigned struct_stat64_sz;
+extern unsigned struct_stat64_sz;
#endif
- extern unsigned struct_rusage_sz;
- extern unsigned siginfo_t_sz;
- extern unsigned struct_itimerval_sz;
- extern unsigned pthread_t_sz;
- extern unsigned pthread_mutex_t_sz;
- extern unsigned pthread_cond_t_sz;
- extern unsigned pid_t_sz;
- extern unsigned timeval_sz;
- extern unsigned uid_t_sz;
- extern unsigned gid_t_sz;
- extern unsigned mbstate_t_sz;
- extern unsigned struct_timezone_sz;
- extern unsigned struct_tms_sz;
- extern unsigned struct_itimerspec_sz;
- extern unsigned struct_sigevent_sz;
- extern unsigned struct_sched_param_sz;
- extern unsigned struct_statfs64_sz;
- extern unsigned struct_regex_sz;
- extern unsigned struct_regmatch_sz;
+extern unsigned struct_rusage_sz;
+extern unsigned siginfo_t_sz;
+extern unsigned struct_itimerval_sz;
+extern unsigned pthread_t_sz;
+extern unsigned pthread_mutex_t_sz;
+extern unsigned pthread_cond_t_sz;
+extern unsigned pid_t_sz;
+extern unsigned timeval_sz;
+extern unsigned uid_t_sz;
+extern unsigned gid_t_sz;
+extern unsigned mbstate_t_sz;
+extern unsigned struct_timezone_sz;
+extern unsigned struct_tms_sz;
+extern unsigned struct_itimerspec_sz;
+extern unsigned struct_sigevent_sz;
+extern unsigned struct_sched_param_sz;
+extern unsigned struct_statfs64_sz;
+extern unsigned struct_regex_sz;
+extern unsigned struct_regmatch_sz;
#if !SANITIZER_ANDROID
- extern unsigned struct_fstab_sz;
- extern unsigned struct_statfs_sz;
- extern unsigned struct_sockaddr_sz;
- extern unsigned ucontext_t_sz;
+extern unsigned struct_fstab_sz;
+extern unsigned struct_statfs_sz;
+extern unsigned struct_sockaddr_sz;
+extern unsigned ucontext_t_sz;
#endif // !SANITIZER_ANDROID
#if SANITIZER_LINUX
#if defined(__x86_64__)
- const unsigned struct_kernel_stat_sz = 144;
- const unsigned struct_kernel_stat64_sz = 0;
+const unsigned struct_kernel_stat_sz = 144;
+const unsigned struct_kernel_stat64_sz = 0;
#elif defined(__i386__)
- const unsigned struct_kernel_stat_sz = 64;
- const unsigned struct_kernel_stat64_sz = 96;
+const unsigned struct_kernel_stat_sz = 64;
+const unsigned struct_kernel_stat64_sz = 96;
#elif defined(__arm__)
- const unsigned struct_kernel_stat_sz = 64;
- const unsigned struct_kernel_stat64_sz = 104;
+const unsigned struct_kernel_stat_sz = 64;
+const unsigned struct_kernel_stat64_sz = 104;
#elif defined(__aarch64__)
- const unsigned struct_kernel_stat_sz = 128;
- const unsigned struct_kernel_stat64_sz = 104;
+const unsigned struct_kernel_stat_sz = 128;
+const unsigned struct_kernel_stat64_sz = 104;
#elif defined(__powerpc__) && !defined(__powerpc64__)
- const unsigned struct_kernel_stat_sz = 72;
- const unsigned struct_kernel_stat64_sz = 104;
+const unsigned struct_kernel_stat_sz = 72;
+const unsigned struct_kernel_stat64_sz = 104;
#elif defined(__powerpc64__)
- const unsigned struct_kernel_stat_sz = 144;
- const unsigned struct_kernel_stat64_sz = 104;
+const unsigned struct_kernel_stat_sz = 144;
+const unsigned struct_kernel_stat64_sz = 104;
#elif defined(__mips__)
- const unsigned struct_kernel_stat_sz =
- SANITIZER_ANDROID ? FIRST_32_SECOND_64(104, 128) :
- FIRST_32_SECOND_64(160, 216);
- const unsigned struct_kernel_stat64_sz = 104;
+const unsigned struct_kernel_stat_sz = SANITIZER_ANDROID
+ ? FIRST_32_SECOND_64(104, 128)
+ : FIRST_32_SECOND_64(160, 216);
+const unsigned struct_kernel_stat64_sz = 104;
#elif defined(__s390__) && !defined(__s390x__)
- const unsigned struct_kernel_stat_sz = 64;
- const unsigned struct_kernel_stat64_sz = 104;
+const unsigned struct_kernel_stat_sz = 64;
+const unsigned struct_kernel_stat64_sz = 104;
#elif defined(__s390x__)
- const unsigned struct_kernel_stat_sz = 144;
- const unsigned struct_kernel_stat64_sz = 0;
+const unsigned struct_kernel_stat_sz = 144;
+const unsigned struct_kernel_stat64_sz = 0;
#elif defined(__sparc__) && defined(__arch64__)
- const unsigned struct___old_kernel_stat_sz = 0;
- const unsigned struct_kernel_stat_sz = 104;
- const unsigned struct_kernel_stat64_sz = 144;
+const unsigned struct___old_kernel_stat_sz = 0;
+const unsigned struct_kernel_stat_sz = 104;
+const unsigned struct_kernel_stat64_sz = 144;
#elif defined(__sparc__) && !defined(__arch64__)
- const unsigned struct___old_kernel_stat_sz = 0;
- const unsigned struct_kernel_stat_sz = 64;
- const unsigned struct_kernel_stat64_sz = 104;
+const unsigned struct___old_kernel_stat_sz = 0;
+const unsigned struct_kernel_stat_sz = 64;
+const unsigned struct_kernel_stat64_sz = 104;
+#elif defined(__riscv) && __riscv_xlen == 64
+const unsigned struct_kernel_stat_sz = 128;
+const unsigned struct_kernel_stat64_sz = 104;
#endif
- struct __sanitizer_perf_event_attr {
- unsigned type;
- unsigned size;
- // More fields that vary with the kernel version.
- };
+struct __sanitizer_perf_event_attr {
+ unsigned type;
+ unsigned size;
+ // More fields that vary with the kernel version.
+};
- extern unsigned struct_epoll_event_sz;
- extern unsigned struct_sysinfo_sz;
- extern unsigned __user_cap_header_struct_sz;
- extern unsigned __user_cap_data_struct_sz;
- extern unsigned struct_new_utsname_sz;
- extern unsigned struct_old_utsname_sz;
- extern unsigned struct_oldold_utsname_sz;
+extern unsigned struct_epoll_event_sz;
+extern unsigned struct_sysinfo_sz;
+extern unsigned __user_cap_header_struct_sz;
+extern unsigned __user_cap_data_struct_sz;
+extern unsigned struct_new_utsname_sz;
+extern unsigned struct_old_utsname_sz;
+extern unsigned struct_oldold_utsname_sz;
- const unsigned struct_kexec_segment_sz = 4 * sizeof(unsigned long);
+const unsigned struct_kexec_segment_sz = 4 * sizeof(unsigned long);
#endif // SANITIZER_LINUX
#if SANITIZER_LINUX
#if defined(__powerpc64__) || defined(__s390__)
- const unsigned struct___old_kernel_stat_sz = 0;
+const unsigned struct___old_kernel_stat_sz = 0;
#elif !defined(__sparc__)
- const unsigned struct___old_kernel_stat_sz = 32;
+const unsigned struct___old_kernel_stat_sz = 32;
#endif
- extern unsigned struct_rlimit_sz;
- extern unsigned struct_utimbuf_sz;
- extern unsigned struct_timespec_sz;
+extern unsigned struct_rlimit_sz;
+extern unsigned struct_utimbuf_sz;
+extern unsigned struct_timespec_sz;
- struct __sanitizer_iocb {
- u64 aio_data;
- u32 aio_key_or_aio_reserved1; // Simply crazy.
- u32 aio_reserved1_or_aio_key; // Luckily, we don't need these.
- u16 aio_lio_opcode;
- s16 aio_reqprio;
- u32 aio_fildes;
- u64 aio_buf;
- u64 aio_nbytes;
- s64 aio_offset;
- u64 aio_reserved2;
- u64 aio_reserved3;
- };
+struct __sanitizer_iocb {
+ u64 aio_data;
+ u32 aio_key_or_aio_reserved1; // Simply crazy.
+ u32 aio_reserved1_or_aio_key; // Luckily, we don't need these.
+ u16 aio_lio_opcode;
+ s16 aio_reqprio;
+ u32 aio_fildes;
+ u64 aio_buf;
+ u64 aio_nbytes;
+ s64 aio_offset;
+ u64 aio_reserved2;
+ u64 aio_reserved3;
+};
- struct __sanitizer_io_event {
- u64 data;
- u64 obj;
- u64 res;
- u64 res2;
- };
+struct __sanitizer_io_event {
+ u64 data;
+ u64 obj;
+ u64 res;
+ u64 res2;
+};
- const unsigned iocb_cmd_pread = 0;
- const unsigned iocb_cmd_pwrite = 1;
- const unsigned iocb_cmd_preadv = 7;
- const unsigned iocb_cmd_pwritev = 8;
+const unsigned iocb_cmd_pread = 0;
+const unsigned iocb_cmd_pwrite = 1;
+const unsigned iocb_cmd_preadv = 7;
+const unsigned iocb_cmd_pwritev = 8;
- struct __sanitizer___sysctl_args {
- int *name;
- int nlen;
- void *oldval;
- uptr *oldlenp;
- void *newval;
- uptr newlen;
- unsigned long ___unused[4];
- };
+struct __sanitizer___sysctl_args {
+ int *name;
+ int nlen;
+ void *oldval;
+ uptr *oldlenp;
+ void *newval;
+ uptr newlen;
+ unsigned long ___unused[4];
+};
- const unsigned old_sigset_t_sz = sizeof(unsigned long);
+const unsigned old_sigset_t_sz = sizeof(unsigned long);
- struct __sanitizer_sem_t {
+struct __sanitizer_sem_t {
#if SANITIZER_ANDROID && defined(_LP64)
- int data[4];
+ int data[4];
#elif SANITIZER_ANDROID && !defined(_LP64)
- int data;
+ int data;
#elif SANITIZER_LINUX
- uptr data[4];
+ uptr data[4];
#endif
- };
+};
#endif // SANITIZER_LINUX
#if SANITIZER_ANDROID
- struct __sanitizer_struct_mallinfo {
- uptr v[10];
- };
+struct __sanitizer_struct_mallinfo {
+ uptr v[10];
+};
#endif
#if SANITIZER_LINUX && !SANITIZER_ANDROID
- struct __sanitizer_struct_mallinfo {
- int v[10];
- };
+struct __sanitizer_struct_mallinfo {
+ int v[10];
+};
- extern unsigned struct_ustat_sz;
- extern unsigned struct_rlimit64_sz;
- extern unsigned struct_statvfs64_sz;
+extern unsigned struct_ustat_sz;
+extern unsigned struct_rlimit64_sz;
+extern unsigned struct_statvfs64_sz;
- struct __sanitizer_ipc_perm {
- int __key;
- int uid;
- int gid;
- int cuid;
- int cgid;
+struct __sanitizer_ipc_perm {
+ int __key;
+ int uid;
+ int gid;
+ int cuid;
+ int cgid;
#ifdef __powerpc__
- unsigned mode;
- unsigned __seq;
- u64 __unused1;
- u64 __unused2;
+ unsigned mode;
+ unsigned __seq;
+ u64 __unused1;
+ u64 __unused2;
#elif defined(__sparc__)
-#if defined(__arch64__)
- unsigned mode;
- unsigned short __pad1;
+ unsigned mode;
+ unsigned short __pad2;
+ unsigned short __seq;
+ unsigned long long __unused1;
+ unsigned long long __unused2;
#else
- unsigned short __pad1;
- unsigned short mode;
- unsigned short __pad2;
-#endif
- unsigned short __seq;
- unsigned long long __unused1;
- unsigned long long __unused2;
-#elif defined(__mips__) || defined(__aarch64__) || defined(__s390x__)
- unsigned int mode;
- unsigned short __seq;
- unsigned short __pad1;
- unsigned long __unused1;
- unsigned long __unused2;
-#else
- unsigned short mode;
- unsigned short __pad1;
- unsigned short __seq;
- unsigned short __pad2;
+ unsigned int mode;
+ unsigned short __seq;
+ unsigned short __pad2;
#if defined(__x86_64__) && !defined(_LP64)
- u64 __unused1;
- u64 __unused2;
+ u64 __unused1;
+ u64 __unused2;
#else
- unsigned long __unused1;
- unsigned long __unused2;
+ unsigned long __unused1;
+ unsigned long __unused2;
#endif
#endif
- };
+};
- struct __sanitizer_shmid_ds {
- __sanitizer_ipc_perm shm_perm;
- #if defined(__sparc__)
- #if !defined(__arch64__)
- u32 __pad1;
- #endif
- long shm_atime;
- #if !defined(__arch64__)
- u32 __pad2;
- #endif
- long shm_dtime;
- #if !defined(__arch64__)
- u32 __pad3;
- #endif
- long shm_ctime;
- uptr shm_segsz;
- int shm_cpid;
- int shm_lpid;
- unsigned long shm_nattch;
- unsigned long __glibc_reserved1;
- unsigned long __glibc_reserved2;
- #else
- #ifndef __powerpc__
- uptr shm_segsz;
- #elif !defined(__powerpc64__)
- uptr __unused0;
- #endif
- #if defined(__x86_64__) && !defined(_LP64)
- u64 shm_atime;
- u64 shm_dtime;
- u64 shm_ctime;
- #else
- uptr shm_atime;
- #if !defined(_LP64) && !defined(__mips__)
- uptr __unused1;
- #endif
- uptr shm_dtime;
- #if !defined(_LP64) && !defined(__mips__)
- uptr __unused2;
- #endif
- uptr shm_ctime;
- #if !defined(_LP64) && !defined(__mips__)
- uptr __unused3;
- #endif
- #endif
- #ifdef __powerpc__
- uptr shm_segsz;
- #endif
- int shm_cpid;
- int shm_lpid;
- #if defined(__x86_64__) && !defined(_LP64)
- u64 shm_nattch;
- u64 __unused4;
- u64 __unused5;
- #else
- uptr shm_nattch;
- uptr __unused4;
- uptr __unused5;
- #endif
+struct __sanitizer_shmid_ds {
+ __sanitizer_ipc_perm shm_perm;
+#if defined(__sparc__)
+#if !defined(__arch64__)
+ u32 __pad1;
#endif
- };
+ long shm_atime;
+#if !defined(__arch64__)
+ u32 __pad2;
+#endif
+ long shm_dtime;
+#if !defined(__arch64__)
+ u32 __pad3;
+#endif
+ long shm_ctime;
+ uptr shm_segsz;
+ int shm_cpid;
+ int shm_lpid;
+ unsigned long shm_nattch;
+ unsigned long __glibc_reserved1;
+ unsigned long __glibc_reserved2;
+#else
+#ifndef __powerpc__
+ uptr shm_segsz;
+#elif !defined(__powerpc64__)
+ uptr __unused0;
+#endif
+#if defined(__x86_64__) && !defined(_LP64)
+ u64 shm_atime;
+ u64 shm_dtime;
+ u64 shm_ctime;
+#else
+ uptr shm_atime;
+#if !defined(_LP64) && !defined(__mips__)
+ uptr __unused1;
+#endif
+ uptr shm_dtime;
+#if !defined(_LP64) && !defined(__mips__)
+ uptr __unused2;
+#endif
+ uptr shm_ctime;
+#if !defined(_LP64) && !defined(__mips__)
+ uptr __unused3;
+#endif
+#endif
+#ifdef __powerpc__
+ uptr shm_segsz;
+#endif
+ int shm_cpid;
+ int shm_lpid;
+#if defined(__x86_64__) && !defined(_LP64)
+ u64 shm_nattch;
+ u64 __unused4;
+ u64 __unused5;
+#else
+ uptr shm_nattch;
+ uptr __unused4;
+ uptr __unused5;
+#endif
+#endif
+};
#endif
#if SANITIZER_LINUX && !SANITIZER_ANDROID
- extern unsigned struct_msqid_ds_sz;
- extern unsigned struct_mq_attr_sz;
- extern unsigned struct_timex_sz;
- extern unsigned struct_statvfs_sz;
+extern unsigned struct_msqid_ds_sz;
+extern unsigned struct_mq_attr_sz;
+extern unsigned struct_timex_sz;
+extern unsigned struct_statvfs_sz;
+extern unsigned struct_crypt_data_sz;
#endif // SANITIZER_LINUX && !SANITIZER_ANDROID
- struct __sanitizer_iovec {
- void *iov_base;
- uptr iov_len;
- };
+struct __sanitizer_iovec {
+ void *iov_base;
+ uptr iov_len;
+};
#if !SANITIZER_ANDROID
- struct __sanitizer_ifaddrs {
- struct __sanitizer_ifaddrs *ifa_next;
- char *ifa_name;
- unsigned int ifa_flags;
- void *ifa_addr; // (struct sockaddr *)
- void *ifa_netmask; // (struct sockaddr *)
- // This is a union on Linux.
+struct __sanitizer_ifaddrs {
+ struct __sanitizer_ifaddrs *ifa_next;
+ char *ifa_name;
+ unsigned int ifa_flags;
+ void *ifa_addr; // (struct sockaddr *)
+ void *ifa_netmask; // (struct sockaddr *)
+ // This is a union on Linux.
# ifdef ifa_dstaddr
# undef ifa_dstaddr
# endif
- void *ifa_dstaddr; // (struct sockaddr *)
- void *ifa_data;
- };
+ void *ifa_dstaddr; // (struct sockaddr *)
+ void *ifa_data;
+};
#endif // !SANITIZER_ANDROID
#if SANITIZER_MAC
- typedef unsigned long __sanitizer_pthread_key_t;
+typedef unsigned long __sanitizer_pthread_key_t;
#else
- typedef unsigned __sanitizer_pthread_key_t;
+typedef unsigned __sanitizer_pthread_key_t;
#endif
#if SANITIZER_LINUX && !SANITIZER_ANDROID
- struct __sanitizer_XDR {
- int x_op;
- void *x_ops;
- uptr x_public;
- uptr x_private;
- uptr x_base;
- unsigned x_handy;
- };
+struct __sanitizer_XDR {
+ int x_op;
+ void *x_ops;
+ uptr x_public;
+ uptr x_private;
+ uptr x_base;
+ unsigned x_handy;
+};
- const int __sanitizer_XDR_ENCODE = 0;
- const int __sanitizer_XDR_DECODE = 1;
- const int __sanitizer_XDR_FREE = 2;
+const int __sanitizer_XDR_ENCODE = 0;
+const int __sanitizer_XDR_DECODE = 1;
+const int __sanitizer_XDR_FREE = 2;
#endif
- struct __sanitizer_passwd {
- char *pw_name;
- char *pw_passwd;
- int pw_uid;
- int pw_gid;
+struct __sanitizer_passwd {
+ char *pw_name;
+ char *pw_passwd;
+ int pw_uid;
+ int pw_gid;
#if SANITIZER_MAC
- long pw_change;
- char *pw_class;
+ long pw_change;
+ char *pw_class;
#endif
#if !(SANITIZER_ANDROID && (SANITIZER_WORDSIZE == 32))
- char *pw_gecos;
+ char *pw_gecos;
#endif
- char *pw_dir;
- char *pw_shell;
+ char *pw_dir;
+ char *pw_shell;
#if SANITIZER_MAC
- long pw_expire;
+ long pw_expire;
#endif
- };
+};
- struct __sanitizer_group {
- char *gr_name;
- char *gr_passwd;
- int gr_gid;
- char **gr_mem;
- };
+struct __sanitizer_group {
+ char *gr_name;
+ char *gr_passwd;
+ int gr_gid;
+ char **gr_mem;
+};
#if defined(__x86_64__) && !defined(_LP64)
- typedef long long __sanitizer_time_t;
+typedef long long __sanitizer_time_t;
#else
- typedef long __sanitizer_time_t;
+typedef long __sanitizer_time_t;
#endif
- typedef long __sanitizer_suseconds_t;
+typedef long __sanitizer_suseconds_t;
- struct __sanitizer_timeval {
- __sanitizer_time_t tv_sec;
- __sanitizer_suseconds_t tv_usec;
- };
+struct __sanitizer_timeval {
+ __sanitizer_time_t tv_sec;
+ __sanitizer_suseconds_t tv_usec;
+};
- struct __sanitizer_itimerval {
- struct __sanitizer_timeval it_interval;
- struct __sanitizer_timeval it_value;
- };
+struct __sanitizer_itimerval {
+ struct __sanitizer_timeval it_interval;
+ struct __sanitizer_timeval it_value;
+};
- struct __sanitizer_timeb {
- __sanitizer_time_t time;
- unsigned short millitm;
- short timezone;
- short dstflag;
- };
+struct __sanitizer_timeb {
+ __sanitizer_time_t time;
+ unsigned short millitm;
+ short timezone;
+ short dstflag;
+};
- struct __sanitizer_ether_addr {
- u8 octet[6];
- };
+struct __sanitizer_ether_addr {
+ u8 octet[6];
+};
- struct __sanitizer_tm {
- int tm_sec;
- int tm_min;
- int tm_hour;
- int tm_mday;
- int tm_mon;
- int tm_year;
- int tm_wday;
- int tm_yday;
- int tm_isdst;
- long int tm_gmtoff;
- const char *tm_zone;
- };
+struct __sanitizer_tm {
+ int tm_sec;
+ int tm_min;
+ int tm_hour;
+ int tm_mday;
+ int tm_mon;
+ int tm_year;
+ int tm_wday;
+ int tm_yday;
+ int tm_isdst;
+ long int tm_gmtoff;
+ const char *tm_zone;
+};
#if SANITIZER_LINUX
- struct __sanitizer_mntent {
- char *mnt_fsname;
- char *mnt_dir;
- char *mnt_type;
- char *mnt_opts;
- int mnt_freq;
- int mnt_passno;
- };
+struct __sanitizer_mntent {
+ char *mnt_fsname;
+ char *mnt_dir;
+ char *mnt_type;
+ char *mnt_opts;
+ int mnt_freq;
+ int mnt_passno;
+};
- struct __sanitizer_file_handle {
- unsigned int handle_bytes;
- int handle_type;
- unsigned char f_handle[1]; // variable sized
- };
+struct __sanitizer_file_handle {
+ unsigned int handle_bytes;
+ int handle_type;
+ unsigned char f_handle[1]; // variable sized
+};
#endif
#if SANITIZER_MAC
- struct __sanitizer_msghdr {
- void *msg_name;
- unsigned msg_namelen;
- struct __sanitizer_iovec *msg_iov;
- unsigned msg_iovlen;
- void *msg_control;
- unsigned msg_controllen;
- int msg_flags;
- };
- struct __sanitizer_cmsghdr {
- unsigned cmsg_len;
- int cmsg_level;
- int cmsg_type;
- };
+struct __sanitizer_msghdr {
+ void *msg_name;
+ unsigned msg_namelen;
+ struct __sanitizer_iovec *msg_iov;
+ unsigned msg_iovlen;
+ void *msg_control;
+ unsigned msg_controllen;
+ int msg_flags;
+};
+struct __sanitizer_cmsghdr {
+ unsigned cmsg_len;
+ int cmsg_level;
+ int cmsg_type;
+};
#else
- struct __sanitizer_msghdr {
- void *msg_name;
- unsigned msg_namelen;
- struct __sanitizer_iovec *msg_iov;
- uptr msg_iovlen;
- void *msg_control;
- uptr msg_controllen;
- int msg_flags;
- };
- struct __sanitizer_cmsghdr {
- uptr cmsg_len;
- int cmsg_level;
- int cmsg_type;
- };
+struct __sanitizer_msghdr {
+ void *msg_name;
+ unsigned msg_namelen;
+ struct __sanitizer_iovec *msg_iov;
+ uptr msg_iovlen;
+ void *msg_control;
+ uptr msg_controllen;
+ int msg_flags;
+};
+struct __sanitizer_cmsghdr {
+ uptr cmsg_len;
+ int cmsg_level;
+ int cmsg_type;
+};
#endif
#if SANITIZER_LINUX
- struct __sanitizer_mmsghdr {
- __sanitizer_msghdr msg_hdr;
- unsigned int msg_len;
- };
+struct __sanitizer_mmsghdr {
+ __sanitizer_msghdr msg_hdr;
+ unsigned int msg_len;
+};
#endif
#if SANITIZER_MAC
- struct __sanitizer_dirent {
- unsigned long long d_ino;
- unsigned long long d_seekoff;
- unsigned short d_reclen;
- // more fields that we don't care about
- };
+struct __sanitizer_dirent {
+ unsigned long long d_ino;
+ unsigned long long d_seekoff;
+ unsigned short d_reclen;
+ // more fields that we don't care about
+};
#elif SANITIZER_ANDROID || defined(__x86_64__)
- struct __sanitizer_dirent {
- unsigned long long d_ino;
- unsigned long long d_off;
- unsigned short d_reclen;
- // more fields that we don't care about
- };
+struct __sanitizer_dirent {
+ unsigned long long d_ino;
+ unsigned long long d_off;
+ unsigned short d_reclen;
+ // more fields that we don't care about
+};
#else
- struct __sanitizer_dirent {
- uptr d_ino;
- uptr d_off;
- unsigned short d_reclen;
- // more fields that we don't care about
- };
+struct __sanitizer_dirent {
+ uptr d_ino;
+ uptr d_off;
+ unsigned short d_reclen;
+ // more fields that we don't care about
+};
#endif
#if SANITIZER_LINUX && !SANITIZER_ANDROID
- struct __sanitizer_dirent64 {
- unsigned long long d_ino;
- unsigned long long d_off;
- unsigned short d_reclen;
- // more fields that we don't care about
- };
+struct __sanitizer_dirent64 {
+ unsigned long long d_ino;
+ unsigned long long d_off;
+ unsigned short d_reclen;
+ // more fields that we don't care about
+};
#endif
#if defined(__x86_64__) && !defined(_LP64)
- typedef long long __sanitizer_clock_t;
+typedef long long __sanitizer_clock_t;
#else
- typedef long __sanitizer_clock_t;
+typedef long __sanitizer_clock_t;
#endif
#if SANITIZER_LINUX
- typedef int __sanitizer_clockid_t;
+typedef int __sanitizer_clockid_t;
#endif
#if SANITIZER_LINUX
-#if defined(_LP64) || defined(__x86_64__) || defined(__powerpc__)\
- || defined(__mips__)
- typedef unsigned __sanitizer___kernel_uid_t;
- typedef unsigned __sanitizer___kernel_gid_t;
+#if defined(_LP64) || defined(__x86_64__) || defined(__powerpc__) || \
+ defined(__mips__)
+typedef unsigned __sanitizer___kernel_uid_t;
+typedef unsigned __sanitizer___kernel_gid_t;
#else
- typedef unsigned short __sanitizer___kernel_uid_t;
- typedef unsigned short __sanitizer___kernel_gid_t;
+typedef unsigned short __sanitizer___kernel_uid_t;
+typedef unsigned short __sanitizer___kernel_gid_t;
#endif
#if defined(__x86_64__) && !defined(_LP64)
- typedef long long __sanitizer___kernel_off_t;
+typedef long long __sanitizer___kernel_off_t;
#else
- typedef long __sanitizer___kernel_off_t;
+typedef long __sanitizer___kernel_off_t;
#endif
#if defined(__powerpc__) || defined(__mips__)
- typedef unsigned int __sanitizer___kernel_old_uid_t;
- typedef unsigned int __sanitizer___kernel_old_gid_t;
+typedef unsigned int __sanitizer___kernel_old_uid_t;
+typedef unsigned int __sanitizer___kernel_old_gid_t;
#else
- typedef unsigned short __sanitizer___kernel_old_uid_t;
- typedef unsigned short __sanitizer___kernel_old_gid_t;
+typedef unsigned short __sanitizer___kernel_old_uid_t;
+typedef unsigned short __sanitizer___kernel_old_gid_t;
#endif
- typedef long long __sanitizer___kernel_loff_t;
- typedef struct {
- unsigned long fds_bits[1024 / (8 * sizeof(long))];
- } __sanitizer___kernel_fd_set;
+typedef long long __sanitizer___kernel_loff_t;
+typedef struct {
+ unsigned long fds_bits[1024 / (8 * sizeof(long))];
+} __sanitizer___kernel_fd_set;
#endif
- // This thing depends on the platform. We are only interested in the upper
- // limit. Verified with a compiler assert in .cc.
- const int pthread_attr_t_max_sz = 128;
- union __sanitizer_pthread_attr_t {
- char size[pthread_attr_t_max_sz]; // NOLINT
- void *align;
- };
+// This thing depends on the platform. We are only interested in the upper
+// limit. Verified with a compiler assert in .cpp.
+union __sanitizer_pthread_attr_t {
+ char size[128];
+ void *align;
+};
#if SANITIZER_ANDROID
# if SANITIZER_MIPS
- typedef unsigned long __sanitizer_sigset_t[16/sizeof(unsigned long)];
+typedef unsigned long __sanitizer_sigset_t[16 / sizeof(unsigned long)];
# else
- typedef unsigned long __sanitizer_sigset_t;
+typedef unsigned long __sanitizer_sigset_t;
# endif
#elif SANITIZER_MAC
- typedef unsigned __sanitizer_sigset_t;
+typedef unsigned __sanitizer_sigset_t;
#elif SANITIZER_LINUX
- struct __sanitizer_sigset_t {
- // The size is determined by looking at sizeof of real sigset_t on linux.
- uptr val[128 / sizeof(uptr)];
- };
+struct __sanitizer_sigset_t {
+ // The size is determined by looking at sizeof of real sigset_t on linux.
+ uptr val[128 / sizeof(uptr)];
+};
#endif
- struct __sanitizer_siginfo {
- // The size is determined by looking at sizeof of real siginfo_t on linux.
- u64 opaque[128 / sizeof(u64)];
- };
+struct __sanitizer_siginfo {
+ // The size is determined by looking at sizeof of real siginfo_t on linux.
+ u64 opaque[128 / sizeof(u64)];
+};
- using __sanitizer_sighandler_ptr = void (*)(int sig);
- using __sanitizer_sigactionhandler_ptr =
- void (*)(int sig, __sanitizer_siginfo *siginfo, void *uctx);
+using __sanitizer_sighandler_ptr = void (*)(int sig);
+using __sanitizer_sigactionhandler_ptr = void (*)(int sig,
+ __sanitizer_siginfo *siginfo,
+ void *uctx);
- // Linux system headers define the 'sa_handler' and 'sa_sigaction' macros.
+// Linux system headers define the 'sa_handler' and 'sa_sigaction' macros.
#if SANITIZER_ANDROID && (SANITIZER_WORDSIZE == 64)
- struct __sanitizer_sigaction {
- unsigned sa_flags;
- union {
- __sanitizer_sigactionhandler_ptr sigaction;
- __sanitizer_sighandler_ptr handler;
- };
- __sanitizer_sigset_t sa_mask;
- void (*sa_restorer)();
+struct __sanitizer_sigaction {
+ unsigned sa_flags;
+ union {
+ __sanitizer_sigactionhandler_ptr sigaction;
+ __sanitizer_sighandler_ptr handler;
};
+ __sanitizer_sigset_t sa_mask;
+ void (*sa_restorer)();
+};
#elif SANITIZER_ANDROID && SANITIZER_MIPS32 // check this before WORDSIZE == 32
- struct __sanitizer_sigaction {
- unsigned sa_flags;
- union {
- __sanitizer_sigactionhandler_ptr sigaction;
- __sanitizer_sighandler_ptr handler;
- };
- __sanitizer_sigset_t sa_mask;
+struct __sanitizer_sigaction {
+ unsigned sa_flags;
+ union {
+ __sanitizer_sigactionhandler_ptr sigaction;
+ __sanitizer_sighandler_ptr handler;
};
+ __sanitizer_sigset_t sa_mask;
+};
#elif SANITIZER_ANDROID && (SANITIZER_WORDSIZE == 32)
- struct __sanitizer_sigaction {
- union {
- __sanitizer_sigactionhandler_ptr sigaction;
- __sanitizer_sighandler_ptr handler;
- };
- __sanitizer_sigset_t sa_mask;
- uptr sa_flags;
- void (*sa_restorer)();
+struct __sanitizer_sigaction {
+ union {
+ __sanitizer_sigactionhandler_ptr sigaction;
+ __sanitizer_sighandler_ptr handler;
};
+ __sanitizer_sigset_t sa_mask;
+ uptr sa_flags;
+ void (*sa_restorer)();
+};
#else // !SANITIZER_ANDROID
- struct __sanitizer_sigaction {
+struct __sanitizer_sigaction {
#if defined(__mips__) && !SANITIZER_FREEBSD
- unsigned int sa_flags;
+ unsigned int sa_flags;
#endif
- union {
- __sanitizer_sigactionhandler_ptr sigaction;
- __sanitizer_sighandler_ptr handler;
- };
+ union {
+ __sanitizer_sigactionhandler_ptr sigaction;
+ __sanitizer_sighandler_ptr handler;
+ };
#if SANITIZER_FREEBSD
- int sa_flags;
- __sanitizer_sigset_t sa_mask;
+ int sa_flags;
+ __sanitizer_sigset_t sa_mask;
#else
#if defined(__s390x__)
- int sa_resv;
+ int sa_resv;
#else
- __sanitizer_sigset_t sa_mask;
+ __sanitizer_sigset_t sa_mask;
#endif
#ifndef __mips__
#if defined(__sparc__)
#if __GLIBC_PREREQ (2, 20)
- // On sparc glibc 2.19 and earlier sa_flags was unsigned long.
+ // On sparc glibc 2.19 and earlier sa_flags was unsigned long.
#if defined(__arch64__)
- // To maintain ABI compatibility on sparc64 when switching to an int,
- // __glibc_reserved0 was added.
- int __glibc_reserved0;
+ // To maintain ABI compatibility on sparc64 when switching to an int,
+ // __glibc_reserved0 was added.
+ int __glibc_reserved0;
#endif
- int sa_flags;
+ int sa_flags;
#else
- unsigned long sa_flags;
+ unsigned long sa_flags;
#endif
#else
- int sa_flags;
+ int sa_flags;
#endif
#endif
#endif
#if SANITIZER_LINUX
- void (*sa_restorer)();
+ void (*sa_restorer)();
#endif
#if defined(__mips__) && (SANITIZER_WORDSIZE == 32)
- int sa_resv[1];
+ int sa_resv[1];
#endif
#if defined(__s390x__)
- __sanitizer_sigset_t sa_mask;
+ __sanitizer_sigset_t sa_mask;
#endif
- };
+};
#endif // !SANITIZER_ANDROID
#if defined(__mips__)
- struct __sanitizer_kernel_sigset_t {
- uptr sig[2];
- };
+struct __sanitizer_kernel_sigset_t {
+ uptr sig[2];
+};
#else
- struct __sanitizer_kernel_sigset_t {
- u8 sig[8];
- };
+struct __sanitizer_kernel_sigset_t {
+ u8 sig[8];
+};
#endif
- // Linux system headers define the 'sa_handler' and 'sa_sigaction' macros.
+// Linux system headers define the 'sa_handler' and 'sa_sigaction' macros.
#if SANITIZER_MIPS
- struct __sanitizer_kernel_sigaction_t {
- unsigned int sa_flags;
- union {
- void (*handler)(int signo);
- void (*sigaction)(int signo, __sanitizer_siginfo *info, void *ctx);
- };
- __sanitizer_kernel_sigset_t sa_mask;
- void (*sa_restorer)(void);
+struct __sanitizer_kernel_sigaction_t {
+ unsigned int sa_flags;
+ union {
+ void (*handler)(int signo);
+ void (*sigaction)(int signo, __sanitizer_siginfo *info, void *ctx);
};
+ __sanitizer_kernel_sigset_t sa_mask;
+ void (*sa_restorer)(void);
+};
#else
- struct __sanitizer_kernel_sigaction_t {
- union {
- void (*handler)(int signo);
- void (*sigaction)(int signo, __sanitizer_siginfo *info, void *ctx);
- };
- unsigned long sa_flags;
- void (*sa_restorer)(void);
- __sanitizer_kernel_sigset_t sa_mask;
+struct __sanitizer_kernel_sigaction_t {
+ union {
+ void (*handler)(int signo);
+ void (*sigaction)(int signo, __sanitizer_siginfo *info, void *ctx);
};
+ unsigned long sa_flags;
+ void (*sa_restorer)(void);
+ __sanitizer_kernel_sigset_t sa_mask;
+};
#endif
- extern const uptr sig_ign;
- extern const uptr sig_dfl;
- extern const uptr sig_err;
- extern const uptr sa_siginfo;
+extern const uptr sig_ign;
+extern const uptr sig_dfl;
+extern const uptr sig_err;
+extern const uptr sa_siginfo;
#if SANITIZER_LINUX
- extern int e_tabsz;
+extern int e_tabsz;
#endif
- extern int af_inet;
- extern int af_inet6;
- uptr __sanitizer_in_addr_sz(int af);
+extern int af_inet;
+extern int af_inet6;
+uptr __sanitizer_in_addr_sz(int af);
#if SANITIZER_LINUX
- struct __sanitizer_dl_phdr_info {
- uptr dlpi_addr;
- const char *dlpi_name;
- const void *dlpi_phdr;
- short dlpi_phnum;
- };
+struct __sanitizer_dl_phdr_info {
+ uptr dlpi_addr;
+ const char *dlpi_name;
+ const void *dlpi_phdr;
+ short dlpi_phnum;
+};
- extern unsigned struct_ElfW_Phdr_sz;
+extern unsigned struct_ElfW_Phdr_sz;
#endif
- struct __sanitizer_addrinfo {
- int ai_flags;
- int ai_family;
- int ai_socktype;
- int ai_protocol;
+struct __sanitizer_addrinfo {
+ int ai_flags;
+ int ai_family;
+ int ai_socktype;
+ int ai_protocol;
#if SANITIZER_ANDROID || SANITIZER_MAC
- unsigned ai_addrlen;
- char *ai_canonname;
- void *ai_addr;
+ unsigned ai_addrlen;
+ char *ai_canonname;
+ void *ai_addr;
#else // LINUX
- unsigned ai_addrlen;
- void *ai_addr;
- char *ai_canonname;
+ unsigned ai_addrlen;
+ void *ai_addr;
+ char *ai_canonname;
#endif
- struct __sanitizer_addrinfo *ai_next;
- };
+ struct __sanitizer_addrinfo *ai_next;
+};
- struct __sanitizer_hostent {
- char *h_name;
- char **h_aliases;
- int h_addrtype;
- int h_length;
- char **h_addr_list;
- };
+struct __sanitizer_hostent {
+ char *h_name;
+ char **h_aliases;
+ int h_addrtype;
+ int h_length;
+ char **h_addr_list;
+};
- struct __sanitizer_pollfd {
- int fd;
- short events;
- short revents;
- };
+struct __sanitizer_pollfd {
+ int fd;
+ short events;
+ short revents;
+};
#if SANITIZER_ANDROID || SANITIZER_MAC
- typedef unsigned __sanitizer_nfds_t;
+typedef unsigned __sanitizer_nfds_t;
#else
- typedef unsigned long __sanitizer_nfds_t;
+typedef unsigned long __sanitizer_nfds_t;
#endif
#if !SANITIZER_ANDROID
# if SANITIZER_LINUX
- struct __sanitizer_glob_t {
- uptr gl_pathc;
- char **gl_pathv;
- uptr gl_offs;
- int gl_flags;
+struct __sanitizer_glob_t {
+ uptr gl_pathc;
+ char **gl_pathv;
+ uptr gl_offs;
+ int gl_flags;
- void (*gl_closedir)(void *dirp);
- void *(*gl_readdir)(void *dirp);
- void *(*gl_opendir)(const char *);
- int (*gl_lstat)(const char *, void *);
- int (*gl_stat)(const char *, void *);
- };
+ void (*gl_closedir)(void *dirp);
+ void *(*gl_readdir)(void *dirp);
+ void *(*gl_opendir)(const char *);
+ int (*gl_lstat)(const char *, void *);
+ int (*gl_stat)(const char *, void *);
+};
# endif // SANITIZER_LINUX
# if SANITIZER_LINUX
- extern int glob_nomatch;
- extern int glob_altdirfunc;
+extern int glob_nomatch;
+extern int glob_altdirfunc;
# endif
#endif // !SANITIZER_ANDROID
- extern unsigned path_max;
+extern unsigned path_max;
- struct __sanitizer_wordexp_t {
- uptr we_wordc;
- char **we_wordv;
- uptr we_offs;
- };
+struct __sanitizer_wordexp_t {
+ uptr we_wordc;
+ char **we_wordv;
+ uptr we_offs;
+};
#if SANITIZER_LINUX && !SANITIZER_ANDROID
- struct __sanitizer_FILE {
- int _flags;
- char *_IO_read_ptr;
- char *_IO_read_end;
- char *_IO_read_base;
- char *_IO_write_base;
- char *_IO_write_ptr;
- char *_IO_write_end;
- char *_IO_buf_base;
- char *_IO_buf_end;
- char *_IO_save_base;
- char *_IO_backup_base;
- char *_IO_save_end;
- void *_markers;
- __sanitizer_FILE *_chain;
- int _fileno;
- };
+struct __sanitizer_FILE {
+ int _flags;
+ char *_IO_read_ptr;
+ char *_IO_read_end;
+ char *_IO_read_base;
+ char *_IO_write_base;
+ char *_IO_write_ptr;
+ char *_IO_write_end;
+ char *_IO_buf_base;
+ char *_IO_buf_end;
+ char *_IO_save_base;
+ char *_IO_backup_base;
+ char *_IO_save_end;
+ void *_markers;
+ __sanitizer_FILE *_chain;
+ int _fileno;
+};
# define SANITIZER_HAS_STRUCT_FILE 1
#else
- typedef void __sanitizer_FILE;
+typedef void __sanitizer_FILE;
# define SANITIZER_HAS_STRUCT_FILE 0
#endif
-#if SANITIZER_LINUX && !SANITIZER_ANDROID && \
- (defined(__i386) || defined(__x86_64) || defined(__mips64) || \
- defined(__powerpc64__) || defined(__aarch64__) || defined(__arm__) || \
- defined(__s390__))
- extern unsigned struct_user_regs_struct_sz;
- extern unsigned struct_user_fpregs_struct_sz;
- extern unsigned struct_user_fpxregs_struct_sz;
- extern unsigned struct_user_vfpregs_struct_sz;
+#if SANITIZER_LINUX && !SANITIZER_ANDROID && \
+ (defined(__i386) || defined(__x86_64) || defined(__mips64) || \
+ defined(__powerpc64__) || defined(__aarch64__) || defined(__arm__) || \
+ defined(__s390__))
+extern unsigned struct_user_regs_struct_sz;
+extern unsigned struct_user_fpregs_struct_sz;
+extern unsigned struct_user_fpxregs_struct_sz;
+extern unsigned struct_user_vfpregs_struct_sz;
- extern int ptrace_peektext;
- extern int ptrace_peekdata;
- extern int ptrace_peekuser;
- extern int ptrace_getregs;
- extern int ptrace_setregs;
- extern int ptrace_getfpregs;
- extern int ptrace_setfpregs;
- extern int ptrace_getfpxregs;
- extern int ptrace_setfpxregs;
- extern int ptrace_getvfpregs;
- extern int ptrace_setvfpregs;
- extern int ptrace_getsiginfo;
- extern int ptrace_setsiginfo;
- extern int ptrace_getregset;
- extern int ptrace_setregset;
- extern int ptrace_geteventmsg;
+extern int ptrace_peektext;
+extern int ptrace_peekdata;
+extern int ptrace_peekuser;
+extern int ptrace_getregs;
+extern int ptrace_setregs;
+extern int ptrace_getfpregs;
+extern int ptrace_setfpregs;
+extern int ptrace_getfpxregs;
+extern int ptrace_setfpxregs;
+extern int ptrace_getvfpregs;
+extern int ptrace_setvfpregs;
+extern int ptrace_getsiginfo;
+extern int ptrace_setsiginfo;
+extern int ptrace_getregset;
+extern int ptrace_setregset;
+extern int ptrace_geteventmsg;
#endif
#if SANITIZER_LINUX && !SANITIZER_ANDROID
- extern unsigned struct_shminfo_sz;
- extern unsigned struct_shm_info_sz;
- extern int shmctl_ipc_stat;
- extern int shmctl_ipc_info;
- extern int shmctl_shm_info;
- extern int shmctl_shm_stat;
+extern unsigned struct_shminfo_sz;
+extern unsigned struct_shm_info_sz;
+extern int shmctl_ipc_stat;
+extern int shmctl_ipc_info;
+extern int shmctl_shm_info;
+extern int shmctl_shm_stat;
#endif
#if !SANITIZER_MAC && !SANITIZER_FREEBSD
- extern unsigned struct_utmp_sz;
+extern unsigned struct_utmp_sz;
#endif
#if !SANITIZER_ANDROID
- extern unsigned struct_utmpx_sz;
+extern unsigned struct_utmpx_sz;
#endif
- extern int map_fixed;
+extern int map_fixed;
- // ioctl arguments
- struct __sanitizer_ifconf {
- int ifc_len;
- union {
- void *ifcu_req;
- } ifc_ifcu;
+// ioctl arguments
+struct __sanitizer_ifconf {
+ int ifc_len;
+ union {
+ void *ifcu_req;
+ } ifc_ifcu;
#if SANITIZER_MAC
- } __attribute__((packed));
+} __attribute__((packed));
#else
- };
+};
#endif
#if SANITIZER_LINUX && !SANITIZER_ANDROID
@@ -932,519 +924,519 @@
#define IOC_SIZE(nr) (((nr) >> IOC_SIZESHIFT) & IOC_SIZEMASK)
#endif
- extern unsigned struct_ifreq_sz;
- extern unsigned struct_termios_sz;
- extern unsigned struct_winsize_sz;
+extern unsigned struct_ifreq_sz;
+extern unsigned struct_termios_sz;
+extern unsigned struct_winsize_sz;
#if SANITIZER_LINUX
- extern unsigned struct_arpreq_sz;
- extern unsigned struct_cdrom_msf_sz;
- extern unsigned struct_cdrom_multisession_sz;
- extern unsigned struct_cdrom_read_audio_sz;
- extern unsigned struct_cdrom_subchnl_sz;
- extern unsigned struct_cdrom_ti_sz;
- extern unsigned struct_cdrom_tocentry_sz;
- extern unsigned struct_cdrom_tochdr_sz;
- extern unsigned struct_cdrom_volctrl_sz;
- extern unsigned struct_ff_effect_sz;
- extern unsigned struct_floppy_drive_params_sz;
- extern unsigned struct_floppy_drive_struct_sz;
- extern unsigned struct_floppy_fdc_state_sz;
- extern unsigned struct_floppy_max_errors_sz;
- extern unsigned struct_floppy_raw_cmd_sz;
- extern unsigned struct_floppy_struct_sz;
- extern unsigned struct_floppy_write_errors_sz;
- extern unsigned struct_format_descr_sz;
- extern unsigned struct_hd_driveid_sz;
- extern unsigned struct_hd_geometry_sz;
- extern unsigned struct_input_absinfo_sz;
- extern unsigned struct_input_id_sz;
- extern unsigned struct_mtpos_sz;
- extern unsigned struct_termio_sz;
- extern unsigned struct_vt_consize_sz;
- extern unsigned struct_vt_sizes_sz;
- extern unsigned struct_vt_stat_sz;
+extern unsigned struct_arpreq_sz;
+extern unsigned struct_cdrom_msf_sz;
+extern unsigned struct_cdrom_multisession_sz;
+extern unsigned struct_cdrom_read_audio_sz;
+extern unsigned struct_cdrom_subchnl_sz;
+extern unsigned struct_cdrom_ti_sz;
+extern unsigned struct_cdrom_tocentry_sz;
+extern unsigned struct_cdrom_tochdr_sz;
+extern unsigned struct_cdrom_volctrl_sz;
+extern unsigned struct_ff_effect_sz;
+extern unsigned struct_floppy_drive_params_sz;
+extern unsigned struct_floppy_drive_struct_sz;
+extern unsigned struct_floppy_fdc_state_sz;
+extern unsigned struct_floppy_max_errors_sz;
+extern unsigned struct_floppy_raw_cmd_sz;
+extern unsigned struct_floppy_struct_sz;
+extern unsigned struct_floppy_write_errors_sz;
+extern unsigned struct_format_descr_sz;
+extern unsigned struct_hd_driveid_sz;
+extern unsigned struct_hd_geometry_sz;
+extern unsigned struct_input_absinfo_sz;
+extern unsigned struct_input_id_sz;
+extern unsigned struct_mtpos_sz;
+extern unsigned struct_termio_sz;
+extern unsigned struct_vt_consize_sz;
+extern unsigned struct_vt_sizes_sz;
+extern unsigned struct_vt_stat_sz;
#endif // SANITIZER_LINUX
#if SANITIZER_LINUX
- extern unsigned struct_copr_buffer_sz;
- extern unsigned struct_copr_debug_buf_sz;
- extern unsigned struct_copr_msg_sz;
- extern unsigned struct_midi_info_sz;
- extern unsigned struct_mtget_sz;
- extern unsigned struct_mtop_sz;
- extern unsigned struct_rtentry_sz;
- extern unsigned struct_sbi_instrument_sz;
- extern unsigned struct_seq_event_rec_sz;
- extern unsigned struct_synth_info_sz;
- extern unsigned struct_vt_mode_sz;
+extern unsigned struct_copr_buffer_sz;
+extern unsigned struct_copr_debug_buf_sz;
+extern unsigned struct_copr_msg_sz;
+extern unsigned struct_midi_info_sz;
+extern unsigned struct_mtget_sz;
+extern unsigned struct_mtop_sz;
+extern unsigned struct_rtentry_sz;
+extern unsigned struct_sbi_instrument_sz;
+extern unsigned struct_seq_event_rec_sz;
+extern unsigned struct_synth_info_sz;
+extern unsigned struct_vt_mode_sz;
#endif // SANITIZER_LINUX
#if SANITIZER_LINUX && !SANITIZER_ANDROID
- extern unsigned struct_ax25_parms_struct_sz;
- extern unsigned struct_cyclades_monitor_sz;
- extern unsigned struct_input_keymap_entry_sz;
- extern unsigned struct_ipx_config_data_sz;
- extern unsigned struct_kbdiacrs_sz;
- extern unsigned struct_kbentry_sz;
- extern unsigned struct_kbkeycode_sz;
- extern unsigned struct_kbsentry_sz;
- extern unsigned struct_mtconfiginfo_sz;
- extern unsigned struct_nr_parms_struct_sz;
- extern unsigned struct_scc_modem_sz;
- extern unsigned struct_scc_stat_sz;
- extern unsigned struct_serial_multiport_struct_sz;
- extern unsigned struct_serial_struct_sz;
- extern unsigned struct_sockaddr_ax25_sz;
- extern unsigned struct_unimapdesc_sz;
- extern unsigned struct_unimapinit_sz;
+extern unsigned struct_ax25_parms_struct_sz;
+extern unsigned struct_cyclades_monitor_sz;
+extern unsigned struct_input_keymap_entry_sz;
+extern unsigned struct_ipx_config_data_sz;
+extern unsigned struct_kbdiacrs_sz;
+extern unsigned struct_kbentry_sz;
+extern unsigned struct_kbkeycode_sz;
+extern unsigned struct_kbsentry_sz;
+extern unsigned struct_mtconfiginfo_sz;
+extern unsigned struct_nr_parms_struct_sz;
+extern unsigned struct_scc_modem_sz;
+extern unsigned struct_scc_stat_sz;
+extern unsigned struct_serial_multiport_struct_sz;
+extern unsigned struct_serial_struct_sz;
+extern unsigned struct_sockaddr_ax25_sz;
+extern unsigned struct_unimapdesc_sz;
+extern unsigned struct_unimapinit_sz;
#endif // SANITIZER_LINUX && !SANITIZER_ANDROID
- extern const unsigned long __sanitizer_bufsiz;
+extern const unsigned long __sanitizer_bufsiz;
#if SANITIZER_LINUX && !SANITIZER_ANDROID
- extern unsigned struct_audio_buf_info_sz;
- extern unsigned struct_ppp_stats_sz;
+extern unsigned struct_audio_buf_info_sz;
+extern unsigned struct_ppp_stats_sz;
#endif // (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID
#if !SANITIZER_ANDROID && !SANITIZER_MAC
- extern unsigned struct_sioc_sg_req_sz;
- extern unsigned struct_sioc_vif_req_sz;
+extern unsigned struct_sioc_sg_req_sz;
+extern unsigned struct_sioc_vif_req_sz;
#endif
- // ioctl request identifiers
+// ioctl request identifiers
- // A special value to mark ioctls that are not present on the target platform,
- // when it can not be determined without including any system headers.
- extern const unsigned IOCTL_NOT_PRESENT;
+// A special value to mark ioctls that are not present on the target platform,
+// when it can not be determined without including any system headers.
+extern const unsigned IOCTL_NOT_PRESENT;
- extern unsigned IOCTL_FIOASYNC;
- extern unsigned IOCTL_FIOCLEX;
- extern unsigned IOCTL_FIOGETOWN;
- extern unsigned IOCTL_FIONBIO;
- extern unsigned IOCTL_FIONCLEX;
- extern unsigned IOCTL_FIOSETOWN;
- extern unsigned IOCTL_SIOCADDMULTI;
- extern unsigned IOCTL_SIOCATMARK;
- extern unsigned IOCTL_SIOCDELMULTI;
- extern unsigned IOCTL_SIOCGIFADDR;
- extern unsigned IOCTL_SIOCGIFBRDADDR;
- extern unsigned IOCTL_SIOCGIFCONF;
- extern unsigned IOCTL_SIOCGIFDSTADDR;
- extern unsigned IOCTL_SIOCGIFFLAGS;
- extern unsigned IOCTL_SIOCGIFMETRIC;
- extern unsigned IOCTL_SIOCGIFMTU;
- extern unsigned IOCTL_SIOCGIFNETMASK;
- extern unsigned IOCTL_SIOCGPGRP;
- extern unsigned IOCTL_SIOCSIFADDR;
- extern unsigned IOCTL_SIOCSIFBRDADDR;
- extern unsigned IOCTL_SIOCSIFDSTADDR;
- extern unsigned IOCTL_SIOCSIFFLAGS;
- extern unsigned IOCTL_SIOCSIFMETRIC;
- extern unsigned IOCTL_SIOCSIFMTU;
- extern unsigned IOCTL_SIOCSIFNETMASK;
- extern unsigned IOCTL_SIOCSPGRP;
- extern unsigned IOCTL_TIOCCONS;
- extern unsigned IOCTL_TIOCEXCL;
- extern unsigned IOCTL_TIOCGETD;
- extern unsigned IOCTL_TIOCGPGRP;
- extern unsigned IOCTL_TIOCGWINSZ;
- extern unsigned IOCTL_TIOCMBIC;
- extern unsigned IOCTL_TIOCMBIS;
- extern unsigned IOCTL_TIOCMGET;
- extern unsigned IOCTL_TIOCMSET;
- extern unsigned IOCTL_TIOCNOTTY;
- extern unsigned IOCTL_TIOCNXCL;
- extern unsigned IOCTL_TIOCOUTQ;
- extern unsigned IOCTL_TIOCPKT;
- extern unsigned IOCTL_TIOCSCTTY;
- extern unsigned IOCTL_TIOCSETD;
- extern unsigned IOCTL_TIOCSPGRP;
- extern unsigned IOCTL_TIOCSTI;
- extern unsigned IOCTL_TIOCSWINSZ;
+extern unsigned IOCTL_FIOASYNC;
+extern unsigned IOCTL_FIOCLEX;
+extern unsigned IOCTL_FIOGETOWN;
+extern unsigned IOCTL_FIONBIO;
+extern unsigned IOCTL_FIONCLEX;
+extern unsigned IOCTL_FIOSETOWN;
+extern unsigned IOCTL_SIOCADDMULTI;
+extern unsigned IOCTL_SIOCATMARK;
+extern unsigned IOCTL_SIOCDELMULTI;
+extern unsigned IOCTL_SIOCGIFADDR;
+extern unsigned IOCTL_SIOCGIFBRDADDR;
+extern unsigned IOCTL_SIOCGIFCONF;
+extern unsigned IOCTL_SIOCGIFDSTADDR;
+extern unsigned IOCTL_SIOCGIFFLAGS;
+extern unsigned IOCTL_SIOCGIFMETRIC;
+extern unsigned IOCTL_SIOCGIFMTU;
+extern unsigned IOCTL_SIOCGIFNETMASK;
+extern unsigned IOCTL_SIOCGPGRP;
+extern unsigned IOCTL_SIOCSIFADDR;
+extern unsigned IOCTL_SIOCSIFBRDADDR;
+extern unsigned IOCTL_SIOCSIFDSTADDR;
+extern unsigned IOCTL_SIOCSIFFLAGS;
+extern unsigned IOCTL_SIOCSIFMETRIC;
+extern unsigned IOCTL_SIOCSIFMTU;
+extern unsigned IOCTL_SIOCSIFNETMASK;
+extern unsigned IOCTL_SIOCSPGRP;
+extern unsigned IOCTL_TIOCCONS;
+extern unsigned IOCTL_TIOCEXCL;
+extern unsigned IOCTL_TIOCGETD;
+extern unsigned IOCTL_TIOCGPGRP;
+extern unsigned IOCTL_TIOCGWINSZ;
+extern unsigned IOCTL_TIOCMBIC;
+extern unsigned IOCTL_TIOCMBIS;
+extern unsigned IOCTL_TIOCMGET;
+extern unsigned IOCTL_TIOCMSET;
+extern unsigned IOCTL_TIOCNOTTY;
+extern unsigned IOCTL_TIOCNXCL;
+extern unsigned IOCTL_TIOCOUTQ;
+extern unsigned IOCTL_TIOCPKT;
+extern unsigned IOCTL_TIOCSCTTY;
+extern unsigned IOCTL_TIOCSETD;
+extern unsigned IOCTL_TIOCSPGRP;
+extern unsigned IOCTL_TIOCSTI;
+extern unsigned IOCTL_TIOCSWINSZ;
#if SANITIZER_LINUX && !SANITIZER_ANDROID
- extern unsigned IOCTL_SIOCGETSGCNT;
- extern unsigned IOCTL_SIOCGETVIFCNT;
+extern unsigned IOCTL_SIOCGETSGCNT;
+extern unsigned IOCTL_SIOCGETVIFCNT;
#endif
#if SANITIZER_LINUX
- extern unsigned IOCTL_EVIOCGABS;
- extern unsigned IOCTL_EVIOCGBIT;
- extern unsigned IOCTL_EVIOCGEFFECTS;
- extern unsigned IOCTL_EVIOCGID;
- extern unsigned IOCTL_EVIOCGKEY;
- extern unsigned IOCTL_EVIOCGKEYCODE;
- extern unsigned IOCTL_EVIOCGLED;
- extern unsigned IOCTL_EVIOCGNAME;
- extern unsigned IOCTL_EVIOCGPHYS;
- extern unsigned IOCTL_EVIOCGRAB;
- extern unsigned IOCTL_EVIOCGREP;
- extern unsigned IOCTL_EVIOCGSND;
- extern unsigned IOCTL_EVIOCGSW;
- extern unsigned IOCTL_EVIOCGUNIQ;
- extern unsigned IOCTL_EVIOCGVERSION;
- extern unsigned IOCTL_EVIOCRMFF;
- extern unsigned IOCTL_EVIOCSABS;
- extern unsigned IOCTL_EVIOCSFF;
- extern unsigned IOCTL_EVIOCSKEYCODE;
- extern unsigned IOCTL_EVIOCSREP;
- extern unsigned IOCTL_BLKFLSBUF;
- extern unsigned IOCTL_BLKGETSIZE;
- extern unsigned IOCTL_BLKRAGET;
- extern unsigned IOCTL_BLKRASET;
- extern unsigned IOCTL_BLKROGET;
- extern unsigned IOCTL_BLKROSET;
- extern unsigned IOCTL_BLKRRPART;
- extern unsigned IOCTL_CDROMAUDIOBUFSIZ;
- extern unsigned IOCTL_CDROMEJECT;
- extern unsigned IOCTL_CDROMEJECT_SW;
- extern unsigned IOCTL_CDROMMULTISESSION;
- extern unsigned IOCTL_CDROMPAUSE;
- extern unsigned IOCTL_CDROMPLAYMSF;
- extern unsigned IOCTL_CDROMPLAYTRKIND;
- extern unsigned IOCTL_CDROMREADAUDIO;
- extern unsigned IOCTL_CDROMREADCOOKED;
- extern unsigned IOCTL_CDROMREADMODE1;
- extern unsigned IOCTL_CDROMREADMODE2;
- extern unsigned IOCTL_CDROMREADRAW;
- extern unsigned IOCTL_CDROMREADTOCENTRY;
- extern unsigned IOCTL_CDROMREADTOCHDR;
- extern unsigned IOCTL_CDROMRESET;
- extern unsigned IOCTL_CDROMRESUME;
- extern unsigned IOCTL_CDROMSEEK;
- extern unsigned IOCTL_CDROMSTART;
- extern unsigned IOCTL_CDROMSTOP;
- extern unsigned IOCTL_CDROMSUBCHNL;
- extern unsigned IOCTL_CDROMVOLCTRL;
- extern unsigned IOCTL_CDROMVOLREAD;
- extern unsigned IOCTL_CDROM_GET_UPC;
- extern unsigned IOCTL_FDCLRPRM;
- extern unsigned IOCTL_FDDEFPRM;
- extern unsigned IOCTL_FDFLUSH;
- extern unsigned IOCTL_FDFMTBEG;
- extern unsigned IOCTL_FDFMTEND;
- extern unsigned IOCTL_FDFMTTRK;
- extern unsigned IOCTL_FDGETDRVPRM;
- extern unsigned IOCTL_FDGETDRVSTAT;
- extern unsigned IOCTL_FDGETDRVTYP;
- extern unsigned IOCTL_FDGETFDCSTAT;
- extern unsigned IOCTL_FDGETMAXERRS;
- extern unsigned IOCTL_FDGETPRM;
- extern unsigned IOCTL_FDMSGOFF;
- extern unsigned IOCTL_FDMSGON;
- extern unsigned IOCTL_FDPOLLDRVSTAT;
- extern unsigned IOCTL_FDRAWCMD;
- extern unsigned IOCTL_FDRESET;
- extern unsigned IOCTL_FDSETDRVPRM;
- extern unsigned IOCTL_FDSETEMSGTRESH;
- extern unsigned IOCTL_FDSETMAXERRS;
- extern unsigned IOCTL_FDSETPRM;
- extern unsigned IOCTL_FDTWADDLE;
- extern unsigned IOCTL_FDWERRORCLR;
- extern unsigned IOCTL_FDWERRORGET;
- extern unsigned IOCTL_HDIO_DRIVE_CMD;
- extern unsigned IOCTL_HDIO_GETGEO;
- extern unsigned IOCTL_HDIO_GET_32BIT;
- extern unsigned IOCTL_HDIO_GET_DMA;
- extern unsigned IOCTL_HDIO_GET_IDENTITY;
- extern unsigned IOCTL_HDIO_GET_KEEPSETTINGS;
- extern unsigned IOCTL_HDIO_GET_MULTCOUNT;
- extern unsigned IOCTL_HDIO_GET_NOWERR;
- extern unsigned IOCTL_HDIO_GET_UNMASKINTR;
- extern unsigned IOCTL_HDIO_SET_32BIT;
- extern unsigned IOCTL_HDIO_SET_DMA;
- extern unsigned IOCTL_HDIO_SET_KEEPSETTINGS;
- extern unsigned IOCTL_HDIO_SET_MULTCOUNT;
- extern unsigned IOCTL_HDIO_SET_NOWERR;
- extern unsigned IOCTL_HDIO_SET_UNMASKINTR;
- extern unsigned IOCTL_MTIOCPOS;
- extern unsigned IOCTL_PPPIOCGASYNCMAP;
- extern unsigned IOCTL_PPPIOCGDEBUG;
- extern unsigned IOCTL_PPPIOCGFLAGS;
- extern unsigned IOCTL_PPPIOCGUNIT;
- extern unsigned IOCTL_PPPIOCGXASYNCMAP;
- extern unsigned IOCTL_PPPIOCSASYNCMAP;
- extern unsigned IOCTL_PPPIOCSDEBUG;
- extern unsigned IOCTL_PPPIOCSFLAGS;
- extern unsigned IOCTL_PPPIOCSMAXCID;
- extern unsigned IOCTL_PPPIOCSMRU;
- extern unsigned IOCTL_PPPIOCSXASYNCMAP;
- extern unsigned IOCTL_SIOCDARP;
- extern unsigned IOCTL_SIOCDRARP;
- extern unsigned IOCTL_SIOCGARP;
- extern unsigned IOCTL_SIOCGIFENCAP;
- extern unsigned IOCTL_SIOCGIFHWADDR;
- extern unsigned IOCTL_SIOCGIFMAP;
- extern unsigned IOCTL_SIOCGIFMEM;
- extern unsigned IOCTL_SIOCGIFNAME;
- extern unsigned IOCTL_SIOCGIFSLAVE;
- extern unsigned IOCTL_SIOCGRARP;
- extern unsigned IOCTL_SIOCGSTAMP;
- extern unsigned IOCTL_SIOCSARP;
- extern unsigned IOCTL_SIOCSIFENCAP;
- extern unsigned IOCTL_SIOCSIFHWADDR;
- extern unsigned IOCTL_SIOCSIFLINK;
- extern unsigned IOCTL_SIOCSIFMAP;
- extern unsigned IOCTL_SIOCSIFMEM;
- extern unsigned IOCTL_SIOCSIFSLAVE;
- extern unsigned IOCTL_SIOCSRARP;
- extern unsigned IOCTL_SNDCTL_COPR_HALT;
- extern unsigned IOCTL_SNDCTL_COPR_LOAD;
- extern unsigned IOCTL_SNDCTL_COPR_RCODE;
- extern unsigned IOCTL_SNDCTL_COPR_RCVMSG;
- extern unsigned IOCTL_SNDCTL_COPR_RDATA;
- extern unsigned IOCTL_SNDCTL_COPR_RESET;
- extern unsigned IOCTL_SNDCTL_COPR_RUN;
- extern unsigned IOCTL_SNDCTL_COPR_SENDMSG;
- extern unsigned IOCTL_SNDCTL_COPR_WCODE;
- extern unsigned IOCTL_SNDCTL_COPR_WDATA;
- extern unsigned IOCTL_TCFLSH;
- extern unsigned IOCTL_TCGETA;
- extern unsigned IOCTL_TCGETS;
- extern unsigned IOCTL_TCSBRK;
- extern unsigned IOCTL_TCSBRKP;
- extern unsigned IOCTL_TCSETA;
- extern unsigned IOCTL_TCSETAF;
- extern unsigned IOCTL_TCSETAW;
- extern unsigned IOCTL_TCSETS;
- extern unsigned IOCTL_TCSETSF;
- extern unsigned IOCTL_TCSETSW;
- extern unsigned IOCTL_TCXONC;
- extern unsigned IOCTL_TIOCGLCKTRMIOS;
- extern unsigned IOCTL_TIOCGSOFTCAR;
- extern unsigned IOCTL_TIOCINQ;
- extern unsigned IOCTL_TIOCLINUX;
- extern unsigned IOCTL_TIOCSERCONFIG;
- extern unsigned IOCTL_TIOCSERGETLSR;
- extern unsigned IOCTL_TIOCSERGWILD;
- extern unsigned IOCTL_TIOCSERSWILD;
- extern unsigned IOCTL_TIOCSLCKTRMIOS;
- extern unsigned IOCTL_TIOCSSOFTCAR;
- extern unsigned IOCTL_VT_DISALLOCATE;
- extern unsigned IOCTL_VT_GETSTATE;
- extern unsigned IOCTL_VT_RESIZE;
- extern unsigned IOCTL_VT_RESIZEX;
- extern unsigned IOCTL_VT_SENDSIG;
- extern unsigned IOCTL_MTIOCGET;
- extern unsigned IOCTL_MTIOCTOP;
- extern unsigned IOCTL_SIOCADDRT;
- extern unsigned IOCTL_SIOCDELRT;
- extern unsigned IOCTL_SNDCTL_DSP_GETBLKSIZE;
- extern unsigned IOCTL_SNDCTL_DSP_GETFMTS;
- extern unsigned IOCTL_SNDCTL_DSP_NONBLOCK;
- extern unsigned IOCTL_SNDCTL_DSP_POST;
- extern unsigned IOCTL_SNDCTL_DSP_RESET;
- extern unsigned IOCTL_SNDCTL_DSP_SETFMT;
- extern unsigned IOCTL_SNDCTL_DSP_SETFRAGMENT;
- extern unsigned IOCTL_SNDCTL_DSP_SPEED;
- extern unsigned IOCTL_SNDCTL_DSP_STEREO;
- extern unsigned IOCTL_SNDCTL_DSP_SUBDIVIDE;
- extern unsigned IOCTL_SNDCTL_DSP_SYNC;
- extern unsigned IOCTL_SNDCTL_FM_4OP_ENABLE;
- extern unsigned IOCTL_SNDCTL_FM_LOAD_INSTR;
- extern unsigned IOCTL_SNDCTL_MIDI_INFO;
- extern unsigned IOCTL_SNDCTL_MIDI_PRETIME;
- extern unsigned IOCTL_SNDCTL_SEQ_CTRLRATE;
- extern unsigned IOCTL_SNDCTL_SEQ_GETINCOUNT;
- extern unsigned IOCTL_SNDCTL_SEQ_GETOUTCOUNT;
- extern unsigned IOCTL_SNDCTL_SEQ_NRMIDIS;
- extern unsigned IOCTL_SNDCTL_SEQ_NRSYNTHS;
- extern unsigned IOCTL_SNDCTL_SEQ_OUTOFBAND;
- extern unsigned IOCTL_SNDCTL_SEQ_PANIC;
- extern unsigned IOCTL_SNDCTL_SEQ_PERCMODE;
- extern unsigned IOCTL_SNDCTL_SEQ_RESET;
- extern unsigned IOCTL_SNDCTL_SEQ_RESETSAMPLES;
- extern unsigned IOCTL_SNDCTL_SEQ_SYNC;
- extern unsigned IOCTL_SNDCTL_SEQ_TESTMIDI;
- extern unsigned IOCTL_SNDCTL_SEQ_THRESHOLD;
- extern unsigned IOCTL_SNDCTL_SYNTH_INFO;
- extern unsigned IOCTL_SNDCTL_SYNTH_MEMAVL;
- extern unsigned IOCTL_SNDCTL_TMR_CONTINUE;
- extern unsigned IOCTL_SNDCTL_TMR_METRONOME;
- extern unsigned IOCTL_SNDCTL_TMR_SELECT;
- extern unsigned IOCTL_SNDCTL_TMR_SOURCE;
- extern unsigned IOCTL_SNDCTL_TMR_START;
- extern unsigned IOCTL_SNDCTL_TMR_STOP;
- extern unsigned IOCTL_SNDCTL_TMR_TEMPO;
- extern unsigned IOCTL_SNDCTL_TMR_TIMEBASE;
- extern unsigned IOCTL_SOUND_MIXER_READ_ALTPCM;
- extern unsigned IOCTL_SOUND_MIXER_READ_BASS;
- extern unsigned IOCTL_SOUND_MIXER_READ_CAPS;
- extern unsigned IOCTL_SOUND_MIXER_READ_CD;
- extern unsigned IOCTL_SOUND_MIXER_READ_DEVMASK;
- extern unsigned IOCTL_SOUND_MIXER_READ_ENHANCE;
- extern unsigned IOCTL_SOUND_MIXER_READ_IGAIN;
- extern unsigned IOCTL_SOUND_MIXER_READ_IMIX;
- extern unsigned IOCTL_SOUND_MIXER_READ_LINE1;
- extern unsigned IOCTL_SOUND_MIXER_READ_LINE2;
- extern unsigned IOCTL_SOUND_MIXER_READ_LINE3;
- extern unsigned IOCTL_SOUND_MIXER_READ_LINE;
- extern unsigned IOCTL_SOUND_MIXER_READ_LOUD;
- extern unsigned IOCTL_SOUND_MIXER_READ_MIC;
- extern unsigned IOCTL_SOUND_MIXER_READ_MUTE;
- extern unsigned IOCTL_SOUND_MIXER_READ_OGAIN;
- extern unsigned IOCTL_SOUND_MIXER_READ_PCM;
- extern unsigned IOCTL_SOUND_MIXER_READ_RECLEV;
- extern unsigned IOCTL_SOUND_MIXER_READ_RECMASK;
- extern unsigned IOCTL_SOUND_MIXER_READ_RECSRC;
- extern unsigned IOCTL_SOUND_MIXER_READ_SPEAKER;
- extern unsigned IOCTL_SOUND_MIXER_READ_STEREODEVS;
- extern unsigned IOCTL_SOUND_MIXER_READ_SYNTH;
- extern unsigned IOCTL_SOUND_MIXER_READ_TREBLE;
- extern unsigned IOCTL_SOUND_MIXER_READ_VOLUME;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_ALTPCM;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_BASS;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_CD;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_ENHANCE;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_IGAIN;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_IMIX;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_LINE1;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_LINE2;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_LINE3;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_LINE;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_LOUD;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_MIC;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_MUTE;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_OGAIN;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_PCM;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_RECLEV;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_RECSRC;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_SPEAKER;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_SYNTH;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_TREBLE;
- extern unsigned IOCTL_SOUND_MIXER_WRITE_VOLUME;
- extern unsigned IOCTL_SOUND_PCM_READ_BITS;
- extern unsigned IOCTL_SOUND_PCM_READ_CHANNELS;
- extern unsigned IOCTL_SOUND_PCM_READ_FILTER;
- extern unsigned IOCTL_SOUND_PCM_READ_RATE;
- extern unsigned IOCTL_SOUND_PCM_WRITE_CHANNELS;
- extern unsigned IOCTL_SOUND_PCM_WRITE_FILTER;
- extern unsigned IOCTL_VT_ACTIVATE;
- extern unsigned IOCTL_VT_GETMODE;
- extern unsigned IOCTL_VT_OPENQRY;
- extern unsigned IOCTL_VT_RELDISP;
- extern unsigned IOCTL_VT_SETMODE;
- extern unsigned IOCTL_VT_WAITACTIVE;
+extern unsigned IOCTL_EVIOCGABS;
+extern unsigned IOCTL_EVIOCGBIT;
+extern unsigned IOCTL_EVIOCGEFFECTS;
+extern unsigned IOCTL_EVIOCGID;
+extern unsigned IOCTL_EVIOCGKEY;
+extern unsigned IOCTL_EVIOCGKEYCODE;
+extern unsigned IOCTL_EVIOCGLED;
+extern unsigned IOCTL_EVIOCGNAME;
+extern unsigned IOCTL_EVIOCGPHYS;
+extern unsigned IOCTL_EVIOCGRAB;
+extern unsigned IOCTL_EVIOCGREP;
+extern unsigned IOCTL_EVIOCGSND;
+extern unsigned IOCTL_EVIOCGSW;
+extern unsigned IOCTL_EVIOCGUNIQ;
+extern unsigned IOCTL_EVIOCGVERSION;
+extern unsigned IOCTL_EVIOCRMFF;
+extern unsigned IOCTL_EVIOCSABS;
+extern unsigned IOCTL_EVIOCSFF;
+extern unsigned IOCTL_EVIOCSKEYCODE;
+extern unsigned IOCTL_EVIOCSREP;
+extern unsigned IOCTL_BLKFLSBUF;
+extern unsigned IOCTL_BLKGETSIZE;
+extern unsigned IOCTL_BLKRAGET;
+extern unsigned IOCTL_BLKRASET;
+extern unsigned IOCTL_BLKROGET;
+extern unsigned IOCTL_BLKROSET;
+extern unsigned IOCTL_BLKRRPART;
+extern unsigned IOCTL_CDROMAUDIOBUFSIZ;
+extern unsigned IOCTL_CDROMEJECT;
+extern unsigned IOCTL_CDROMEJECT_SW;
+extern unsigned IOCTL_CDROMMULTISESSION;
+extern unsigned IOCTL_CDROMPAUSE;
+extern unsigned IOCTL_CDROMPLAYMSF;
+extern unsigned IOCTL_CDROMPLAYTRKIND;
+extern unsigned IOCTL_CDROMREADAUDIO;
+extern unsigned IOCTL_CDROMREADCOOKED;
+extern unsigned IOCTL_CDROMREADMODE1;
+extern unsigned IOCTL_CDROMREADMODE2;
+extern unsigned IOCTL_CDROMREADRAW;
+extern unsigned IOCTL_CDROMREADTOCENTRY;
+extern unsigned IOCTL_CDROMREADTOCHDR;
+extern unsigned IOCTL_CDROMRESET;
+extern unsigned IOCTL_CDROMRESUME;
+extern unsigned IOCTL_CDROMSEEK;
+extern unsigned IOCTL_CDROMSTART;
+extern unsigned IOCTL_CDROMSTOP;
+extern unsigned IOCTL_CDROMSUBCHNL;
+extern unsigned IOCTL_CDROMVOLCTRL;
+extern unsigned IOCTL_CDROMVOLREAD;
+extern unsigned IOCTL_CDROM_GET_UPC;
+extern unsigned IOCTL_FDCLRPRM;
+extern unsigned IOCTL_FDDEFPRM;
+extern unsigned IOCTL_FDFLUSH;
+extern unsigned IOCTL_FDFMTBEG;
+extern unsigned IOCTL_FDFMTEND;
+extern unsigned IOCTL_FDFMTTRK;
+extern unsigned IOCTL_FDGETDRVPRM;
+extern unsigned IOCTL_FDGETDRVSTAT;
+extern unsigned IOCTL_FDGETDRVTYP;
+extern unsigned IOCTL_FDGETFDCSTAT;
+extern unsigned IOCTL_FDGETMAXERRS;
+extern unsigned IOCTL_FDGETPRM;
+extern unsigned IOCTL_FDMSGOFF;
+extern unsigned IOCTL_FDMSGON;
+extern unsigned IOCTL_FDPOLLDRVSTAT;
+extern unsigned IOCTL_FDRAWCMD;
+extern unsigned IOCTL_FDRESET;
+extern unsigned IOCTL_FDSETDRVPRM;
+extern unsigned IOCTL_FDSETEMSGTRESH;
+extern unsigned IOCTL_FDSETMAXERRS;
+extern unsigned IOCTL_FDSETPRM;
+extern unsigned IOCTL_FDTWADDLE;
+extern unsigned IOCTL_FDWERRORCLR;
+extern unsigned IOCTL_FDWERRORGET;
+extern unsigned IOCTL_HDIO_DRIVE_CMD;
+extern unsigned IOCTL_HDIO_GETGEO;
+extern unsigned IOCTL_HDIO_GET_32BIT;
+extern unsigned IOCTL_HDIO_GET_DMA;
+extern unsigned IOCTL_HDIO_GET_IDENTITY;
+extern unsigned IOCTL_HDIO_GET_KEEPSETTINGS;
+extern unsigned IOCTL_HDIO_GET_MULTCOUNT;
+extern unsigned IOCTL_HDIO_GET_NOWERR;
+extern unsigned IOCTL_HDIO_GET_UNMASKINTR;
+extern unsigned IOCTL_HDIO_SET_32BIT;
+extern unsigned IOCTL_HDIO_SET_DMA;
+extern unsigned IOCTL_HDIO_SET_KEEPSETTINGS;
+extern unsigned IOCTL_HDIO_SET_MULTCOUNT;
+extern unsigned IOCTL_HDIO_SET_NOWERR;
+extern unsigned IOCTL_HDIO_SET_UNMASKINTR;
+extern unsigned IOCTL_MTIOCPOS;
+extern unsigned IOCTL_PPPIOCGASYNCMAP;
+extern unsigned IOCTL_PPPIOCGDEBUG;
+extern unsigned IOCTL_PPPIOCGFLAGS;
+extern unsigned IOCTL_PPPIOCGUNIT;
+extern unsigned IOCTL_PPPIOCGXASYNCMAP;
+extern unsigned IOCTL_PPPIOCSASYNCMAP;
+extern unsigned IOCTL_PPPIOCSDEBUG;
+extern unsigned IOCTL_PPPIOCSFLAGS;
+extern unsigned IOCTL_PPPIOCSMAXCID;
+extern unsigned IOCTL_PPPIOCSMRU;
+extern unsigned IOCTL_PPPIOCSXASYNCMAP;
+extern unsigned IOCTL_SIOCDARP;
+extern unsigned IOCTL_SIOCDRARP;
+extern unsigned IOCTL_SIOCGARP;
+extern unsigned IOCTL_SIOCGIFENCAP;
+extern unsigned IOCTL_SIOCGIFHWADDR;
+extern unsigned IOCTL_SIOCGIFMAP;
+extern unsigned IOCTL_SIOCGIFMEM;
+extern unsigned IOCTL_SIOCGIFNAME;
+extern unsigned IOCTL_SIOCGIFSLAVE;
+extern unsigned IOCTL_SIOCGRARP;
+extern unsigned IOCTL_SIOCGSTAMP;
+extern unsigned IOCTL_SIOCSARP;
+extern unsigned IOCTL_SIOCSIFENCAP;
+extern unsigned IOCTL_SIOCSIFHWADDR;
+extern unsigned IOCTL_SIOCSIFLINK;
+extern unsigned IOCTL_SIOCSIFMAP;
+extern unsigned IOCTL_SIOCSIFMEM;
+extern unsigned IOCTL_SIOCSIFSLAVE;
+extern unsigned IOCTL_SIOCSRARP;
+extern unsigned IOCTL_SNDCTL_COPR_HALT;
+extern unsigned IOCTL_SNDCTL_COPR_LOAD;
+extern unsigned IOCTL_SNDCTL_COPR_RCODE;
+extern unsigned IOCTL_SNDCTL_COPR_RCVMSG;
+extern unsigned IOCTL_SNDCTL_COPR_RDATA;
+extern unsigned IOCTL_SNDCTL_COPR_RESET;
+extern unsigned IOCTL_SNDCTL_COPR_RUN;
+extern unsigned IOCTL_SNDCTL_COPR_SENDMSG;
+extern unsigned IOCTL_SNDCTL_COPR_WCODE;
+extern unsigned IOCTL_SNDCTL_COPR_WDATA;
+extern unsigned IOCTL_TCFLSH;
+extern unsigned IOCTL_TCGETA;
+extern unsigned IOCTL_TCGETS;
+extern unsigned IOCTL_TCSBRK;
+extern unsigned IOCTL_TCSBRKP;
+extern unsigned IOCTL_TCSETA;
+extern unsigned IOCTL_TCSETAF;
+extern unsigned IOCTL_TCSETAW;
+extern unsigned IOCTL_TCSETS;
+extern unsigned IOCTL_TCSETSF;
+extern unsigned IOCTL_TCSETSW;
+extern unsigned IOCTL_TCXONC;
+extern unsigned IOCTL_TIOCGLCKTRMIOS;
+extern unsigned IOCTL_TIOCGSOFTCAR;
+extern unsigned IOCTL_TIOCINQ;
+extern unsigned IOCTL_TIOCLINUX;
+extern unsigned IOCTL_TIOCSERCONFIG;
+extern unsigned IOCTL_TIOCSERGETLSR;
+extern unsigned IOCTL_TIOCSERGWILD;
+extern unsigned IOCTL_TIOCSERSWILD;
+extern unsigned IOCTL_TIOCSLCKTRMIOS;
+extern unsigned IOCTL_TIOCSSOFTCAR;
+extern unsigned IOCTL_VT_DISALLOCATE;
+extern unsigned IOCTL_VT_GETSTATE;
+extern unsigned IOCTL_VT_RESIZE;
+extern unsigned IOCTL_VT_RESIZEX;
+extern unsigned IOCTL_VT_SENDSIG;
+extern unsigned IOCTL_MTIOCGET;
+extern unsigned IOCTL_MTIOCTOP;
+extern unsigned IOCTL_SIOCADDRT;
+extern unsigned IOCTL_SIOCDELRT;
+extern unsigned IOCTL_SNDCTL_DSP_GETBLKSIZE;
+extern unsigned IOCTL_SNDCTL_DSP_GETFMTS;
+extern unsigned IOCTL_SNDCTL_DSP_NONBLOCK;
+extern unsigned IOCTL_SNDCTL_DSP_POST;
+extern unsigned IOCTL_SNDCTL_DSP_RESET;
+extern unsigned IOCTL_SNDCTL_DSP_SETFMT;
+extern unsigned IOCTL_SNDCTL_DSP_SETFRAGMENT;
+extern unsigned IOCTL_SNDCTL_DSP_SPEED;
+extern unsigned IOCTL_SNDCTL_DSP_STEREO;
+extern unsigned IOCTL_SNDCTL_DSP_SUBDIVIDE;
+extern unsigned IOCTL_SNDCTL_DSP_SYNC;
+extern unsigned IOCTL_SNDCTL_FM_4OP_ENABLE;
+extern unsigned IOCTL_SNDCTL_FM_LOAD_INSTR;
+extern unsigned IOCTL_SNDCTL_MIDI_INFO;
+extern unsigned IOCTL_SNDCTL_MIDI_PRETIME;
+extern unsigned IOCTL_SNDCTL_SEQ_CTRLRATE;
+extern unsigned IOCTL_SNDCTL_SEQ_GETINCOUNT;
+extern unsigned IOCTL_SNDCTL_SEQ_GETOUTCOUNT;
+extern unsigned IOCTL_SNDCTL_SEQ_NRMIDIS;
+extern unsigned IOCTL_SNDCTL_SEQ_NRSYNTHS;
+extern unsigned IOCTL_SNDCTL_SEQ_OUTOFBAND;
+extern unsigned IOCTL_SNDCTL_SEQ_PANIC;
+extern unsigned IOCTL_SNDCTL_SEQ_PERCMODE;
+extern unsigned IOCTL_SNDCTL_SEQ_RESET;
+extern unsigned IOCTL_SNDCTL_SEQ_RESETSAMPLES;
+extern unsigned IOCTL_SNDCTL_SEQ_SYNC;
+extern unsigned IOCTL_SNDCTL_SEQ_TESTMIDI;
+extern unsigned IOCTL_SNDCTL_SEQ_THRESHOLD;
+extern unsigned IOCTL_SNDCTL_SYNTH_INFO;
+extern unsigned IOCTL_SNDCTL_SYNTH_MEMAVL;
+extern unsigned IOCTL_SNDCTL_TMR_CONTINUE;
+extern unsigned IOCTL_SNDCTL_TMR_METRONOME;
+extern unsigned IOCTL_SNDCTL_TMR_SELECT;
+extern unsigned IOCTL_SNDCTL_TMR_SOURCE;
+extern unsigned IOCTL_SNDCTL_TMR_START;
+extern unsigned IOCTL_SNDCTL_TMR_STOP;
+extern unsigned IOCTL_SNDCTL_TMR_TEMPO;
+extern unsigned IOCTL_SNDCTL_TMR_TIMEBASE;
+extern unsigned IOCTL_SOUND_MIXER_READ_ALTPCM;
+extern unsigned IOCTL_SOUND_MIXER_READ_BASS;
+extern unsigned IOCTL_SOUND_MIXER_READ_CAPS;
+extern unsigned IOCTL_SOUND_MIXER_READ_CD;
+extern unsigned IOCTL_SOUND_MIXER_READ_DEVMASK;
+extern unsigned IOCTL_SOUND_MIXER_READ_ENHANCE;
+extern unsigned IOCTL_SOUND_MIXER_READ_IGAIN;
+extern unsigned IOCTL_SOUND_MIXER_READ_IMIX;
+extern unsigned IOCTL_SOUND_MIXER_READ_LINE1;
+extern unsigned IOCTL_SOUND_MIXER_READ_LINE2;
+extern unsigned IOCTL_SOUND_MIXER_READ_LINE3;
+extern unsigned IOCTL_SOUND_MIXER_READ_LINE;
+extern unsigned IOCTL_SOUND_MIXER_READ_LOUD;
+extern unsigned IOCTL_SOUND_MIXER_READ_MIC;
+extern unsigned IOCTL_SOUND_MIXER_READ_MUTE;
+extern unsigned IOCTL_SOUND_MIXER_READ_OGAIN;
+extern unsigned IOCTL_SOUND_MIXER_READ_PCM;
+extern unsigned IOCTL_SOUND_MIXER_READ_RECLEV;
+extern unsigned IOCTL_SOUND_MIXER_READ_RECMASK;
+extern unsigned IOCTL_SOUND_MIXER_READ_RECSRC;
+extern unsigned IOCTL_SOUND_MIXER_READ_SPEAKER;
+extern unsigned IOCTL_SOUND_MIXER_READ_STEREODEVS;
+extern unsigned IOCTL_SOUND_MIXER_READ_SYNTH;
+extern unsigned IOCTL_SOUND_MIXER_READ_TREBLE;
+extern unsigned IOCTL_SOUND_MIXER_READ_VOLUME;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_ALTPCM;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_BASS;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_CD;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_ENHANCE;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_IGAIN;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_IMIX;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_LINE1;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_LINE2;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_LINE3;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_LINE;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_LOUD;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_MIC;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_MUTE;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_OGAIN;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_PCM;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_RECLEV;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_RECSRC;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_SPEAKER;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_SYNTH;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_TREBLE;
+extern unsigned IOCTL_SOUND_MIXER_WRITE_VOLUME;
+extern unsigned IOCTL_SOUND_PCM_READ_BITS;
+extern unsigned IOCTL_SOUND_PCM_READ_CHANNELS;
+extern unsigned IOCTL_SOUND_PCM_READ_FILTER;
+extern unsigned IOCTL_SOUND_PCM_READ_RATE;
+extern unsigned IOCTL_SOUND_PCM_WRITE_CHANNELS;
+extern unsigned IOCTL_SOUND_PCM_WRITE_FILTER;
+extern unsigned IOCTL_VT_ACTIVATE;
+extern unsigned IOCTL_VT_GETMODE;
+extern unsigned IOCTL_VT_OPENQRY;
+extern unsigned IOCTL_VT_RELDISP;
+extern unsigned IOCTL_VT_SETMODE;
+extern unsigned IOCTL_VT_WAITACTIVE;
#endif // SANITIZER_LINUX
#if SANITIZER_LINUX && !SANITIZER_ANDROID
- extern unsigned IOCTL_CYGETDEFTHRESH;
- extern unsigned IOCTL_CYGETDEFTIMEOUT;
- extern unsigned IOCTL_CYGETMON;
- extern unsigned IOCTL_CYGETTHRESH;
- extern unsigned IOCTL_CYGETTIMEOUT;
- extern unsigned IOCTL_CYSETDEFTHRESH;
- extern unsigned IOCTL_CYSETDEFTIMEOUT;
- extern unsigned IOCTL_CYSETTHRESH;
- extern unsigned IOCTL_CYSETTIMEOUT;
- extern unsigned IOCTL_EQL_EMANCIPATE;
- extern unsigned IOCTL_EQL_ENSLAVE;
- extern unsigned IOCTL_EQL_GETMASTRCFG;
- extern unsigned IOCTL_EQL_GETSLAVECFG;
- extern unsigned IOCTL_EQL_SETMASTRCFG;
- extern unsigned IOCTL_EQL_SETSLAVECFG;
- extern unsigned IOCTL_EVIOCGKEYCODE_V2;
- extern unsigned IOCTL_EVIOCGPROP;
- extern unsigned IOCTL_EVIOCSKEYCODE_V2;
- extern unsigned IOCTL_FS_IOC_GETFLAGS;
- extern unsigned IOCTL_FS_IOC_GETVERSION;
- extern unsigned IOCTL_FS_IOC_SETFLAGS;
- extern unsigned IOCTL_FS_IOC_SETVERSION;
- extern unsigned IOCTL_GIO_CMAP;
- extern unsigned IOCTL_GIO_FONT;
- extern unsigned IOCTL_GIO_UNIMAP;
- extern unsigned IOCTL_GIO_UNISCRNMAP;
- extern unsigned IOCTL_KDADDIO;
- extern unsigned IOCTL_KDDELIO;
- extern unsigned IOCTL_KDGETKEYCODE;
- extern unsigned IOCTL_KDGKBDIACR;
- extern unsigned IOCTL_KDGKBENT;
- extern unsigned IOCTL_KDGKBLED;
- extern unsigned IOCTL_KDGKBMETA;
- extern unsigned IOCTL_KDGKBSENT;
- extern unsigned IOCTL_KDMAPDISP;
- extern unsigned IOCTL_KDSETKEYCODE;
- extern unsigned IOCTL_KDSIGACCEPT;
- extern unsigned IOCTL_KDSKBDIACR;
- extern unsigned IOCTL_KDSKBENT;
- extern unsigned IOCTL_KDSKBLED;
- extern unsigned IOCTL_KDSKBMETA;
- extern unsigned IOCTL_KDSKBSENT;
- extern unsigned IOCTL_KDUNMAPDISP;
- extern unsigned IOCTL_LPABORT;
- extern unsigned IOCTL_LPABORTOPEN;
- extern unsigned IOCTL_LPCAREFUL;
- extern unsigned IOCTL_LPCHAR;
- extern unsigned IOCTL_LPGETIRQ;
- extern unsigned IOCTL_LPGETSTATUS;
- extern unsigned IOCTL_LPRESET;
- extern unsigned IOCTL_LPSETIRQ;
- extern unsigned IOCTL_LPTIME;
- extern unsigned IOCTL_LPWAIT;
- extern unsigned IOCTL_MTIOCGETCONFIG;
- extern unsigned IOCTL_MTIOCSETCONFIG;
- extern unsigned IOCTL_PIO_CMAP;
- extern unsigned IOCTL_PIO_FONT;
- extern unsigned IOCTL_PIO_UNIMAP;
- extern unsigned IOCTL_PIO_UNIMAPCLR;
- extern unsigned IOCTL_PIO_UNISCRNMAP;
- extern unsigned IOCTL_SCSI_IOCTL_GET_IDLUN;
- extern unsigned IOCTL_SCSI_IOCTL_PROBE_HOST;
- extern unsigned IOCTL_SCSI_IOCTL_TAGGED_DISABLE;
- extern unsigned IOCTL_SCSI_IOCTL_TAGGED_ENABLE;
- extern unsigned IOCTL_SIOCAIPXITFCRT;
- extern unsigned IOCTL_SIOCAIPXPRISLT;
- extern unsigned IOCTL_SIOCAX25ADDUID;
- extern unsigned IOCTL_SIOCAX25DELUID;
- extern unsigned IOCTL_SIOCAX25GETPARMS;
- extern unsigned IOCTL_SIOCAX25GETUID;
- extern unsigned IOCTL_SIOCAX25NOUID;
- extern unsigned IOCTL_SIOCAX25SETPARMS;
- extern unsigned IOCTL_SIOCDEVPLIP;
- extern unsigned IOCTL_SIOCIPXCFGDATA;
- extern unsigned IOCTL_SIOCNRDECOBS;
- extern unsigned IOCTL_SIOCNRGETPARMS;
- extern unsigned IOCTL_SIOCNRRTCTL;
- extern unsigned IOCTL_SIOCNRSETPARMS;
- extern unsigned IOCTL_SNDCTL_DSP_GETISPACE;
- extern unsigned IOCTL_SNDCTL_DSP_GETOSPACE;
- extern unsigned IOCTL_TIOCGSERIAL;
- extern unsigned IOCTL_TIOCSERGETMULTI;
- extern unsigned IOCTL_TIOCSERSETMULTI;
- extern unsigned IOCTL_TIOCSSERIAL;
- extern unsigned IOCTL_GIO_SCRNMAP;
- extern unsigned IOCTL_KDDISABIO;
- extern unsigned IOCTL_KDENABIO;
- extern unsigned IOCTL_KDGETLED;
- extern unsigned IOCTL_KDGETMODE;
- extern unsigned IOCTL_KDGKBMODE;
- extern unsigned IOCTL_KDGKBTYPE;
- extern unsigned IOCTL_KDMKTONE;
- extern unsigned IOCTL_KDSETLED;
- extern unsigned IOCTL_KDSETMODE;
- extern unsigned IOCTL_KDSKBMODE;
- extern unsigned IOCTL_KIOCSOUND;
- extern unsigned IOCTL_PIO_SCRNMAP;
+extern unsigned IOCTL_CYGETDEFTHRESH;
+extern unsigned IOCTL_CYGETDEFTIMEOUT;
+extern unsigned IOCTL_CYGETMON;
+extern unsigned IOCTL_CYGETTHRESH;
+extern unsigned IOCTL_CYGETTIMEOUT;
+extern unsigned IOCTL_CYSETDEFTHRESH;
+extern unsigned IOCTL_CYSETDEFTIMEOUT;
+extern unsigned IOCTL_CYSETTHRESH;
+extern unsigned IOCTL_CYSETTIMEOUT;
+extern unsigned IOCTL_EQL_EMANCIPATE;
+extern unsigned IOCTL_EQL_ENSLAVE;
+extern unsigned IOCTL_EQL_GETMASTRCFG;
+extern unsigned IOCTL_EQL_GETSLAVECFG;
+extern unsigned IOCTL_EQL_SETMASTRCFG;
+extern unsigned IOCTL_EQL_SETSLAVECFG;
+extern unsigned IOCTL_EVIOCGKEYCODE_V2;
+extern unsigned IOCTL_EVIOCGPROP;
+extern unsigned IOCTL_EVIOCSKEYCODE_V2;
+extern unsigned IOCTL_FS_IOC_GETFLAGS;
+extern unsigned IOCTL_FS_IOC_GETVERSION;
+extern unsigned IOCTL_FS_IOC_SETFLAGS;
+extern unsigned IOCTL_FS_IOC_SETVERSION;
+extern unsigned IOCTL_GIO_CMAP;
+extern unsigned IOCTL_GIO_FONT;
+extern unsigned IOCTL_GIO_UNIMAP;
+extern unsigned IOCTL_GIO_UNISCRNMAP;
+extern unsigned IOCTL_KDADDIO;
+extern unsigned IOCTL_KDDELIO;
+extern unsigned IOCTL_KDGETKEYCODE;
+extern unsigned IOCTL_KDGKBDIACR;
+extern unsigned IOCTL_KDGKBENT;
+extern unsigned IOCTL_KDGKBLED;
+extern unsigned IOCTL_KDGKBMETA;
+extern unsigned IOCTL_KDGKBSENT;
+extern unsigned IOCTL_KDMAPDISP;
+extern unsigned IOCTL_KDSETKEYCODE;
+extern unsigned IOCTL_KDSIGACCEPT;
+extern unsigned IOCTL_KDSKBDIACR;
+extern unsigned IOCTL_KDSKBENT;
+extern unsigned IOCTL_KDSKBLED;
+extern unsigned IOCTL_KDSKBMETA;
+extern unsigned IOCTL_KDSKBSENT;
+extern unsigned IOCTL_KDUNMAPDISP;
+extern unsigned IOCTL_LPABORT;
+extern unsigned IOCTL_LPABORTOPEN;
+extern unsigned IOCTL_LPCAREFUL;
+extern unsigned IOCTL_LPCHAR;
+extern unsigned IOCTL_LPGETIRQ;
+extern unsigned IOCTL_LPGETSTATUS;
+extern unsigned IOCTL_LPRESET;
+extern unsigned IOCTL_LPSETIRQ;
+extern unsigned IOCTL_LPTIME;
+extern unsigned IOCTL_LPWAIT;
+extern unsigned IOCTL_MTIOCGETCONFIG;
+extern unsigned IOCTL_MTIOCSETCONFIG;
+extern unsigned IOCTL_PIO_CMAP;
+extern unsigned IOCTL_PIO_FONT;
+extern unsigned IOCTL_PIO_UNIMAP;
+extern unsigned IOCTL_PIO_UNIMAPCLR;
+extern unsigned IOCTL_PIO_UNISCRNMAP;
+extern unsigned IOCTL_SCSI_IOCTL_GET_IDLUN;
+extern unsigned IOCTL_SCSI_IOCTL_PROBE_HOST;
+extern unsigned IOCTL_SCSI_IOCTL_TAGGED_DISABLE;
+extern unsigned IOCTL_SCSI_IOCTL_TAGGED_ENABLE;
+extern unsigned IOCTL_SIOCAIPXITFCRT;
+extern unsigned IOCTL_SIOCAIPXPRISLT;
+extern unsigned IOCTL_SIOCAX25ADDUID;
+extern unsigned IOCTL_SIOCAX25DELUID;
+extern unsigned IOCTL_SIOCAX25GETPARMS;
+extern unsigned IOCTL_SIOCAX25GETUID;
+extern unsigned IOCTL_SIOCAX25NOUID;
+extern unsigned IOCTL_SIOCAX25SETPARMS;
+extern unsigned IOCTL_SIOCDEVPLIP;
+extern unsigned IOCTL_SIOCIPXCFGDATA;
+extern unsigned IOCTL_SIOCNRDECOBS;
+extern unsigned IOCTL_SIOCNRGETPARMS;
+extern unsigned IOCTL_SIOCNRRTCTL;
+extern unsigned IOCTL_SIOCNRSETPARMS;
+extern unsigned IOCTL_SNDCTL_DSP_GETISPACE;
+extern unsigned IOCTL_SNDCTL_DSP_GETOSPACE;
+extern unsigned IOCTL_TIOCGSERIAL;
+extern unsigned IOCTL_TIOCSERGETMULTI;
+extern unsigned IOCTL_TIOCSERSETMULTI;
+extern unsigned IOCTL_TIOCSSERIAL;
+extern unsigned IOCTL_GIO_SCRNMAP;
+extern unsigned IOCTL_KDDISABIO;
+extern unsigned IOCTL_KDENABIO;
+extern unsigned IOCTL_KDGETLED;
+extern unsigned IOCTL_KDGETMODE;
+extern unsigned IOCTL_KDGKBMODE;
+extern unsigned IOCTL_KDGKBTYPE;
+extern unsigned IOCTL_KDMKTONE;
+extern unsigned IOCTL_KDSETLED;
+extern unsigned IOCTL_KDSETMODE;
+extern unsigned IOCTL_KDSKBMODE;
+extern unsigned IOCTL_KIOCSOUND;
+extern unsigned IOCTL_PIO_SCRNMAP;
#endif
- extern const int si_SEGV_MAPERR;
- extern const int si_SEGV_ACCERR;
+extern const int si_SEGV_MAPERR;
+extern const int si_SEGV_ACCERR;
} // namespace __sanitizer
#define CHECK_TYPE_SIZE(TYPE) \
COMPILER_CHECK(sizeof(__sanitizer_##TYPE) == sizeof(TYPE))
-#define CHECK_SIZE_AND_OFFSET(CLASS, MEMBER) \
- COMPILER_CHECK(sizeof(((__sanitizer_##CLASS *) NULL)->MEMBER) == \
- sizeof(((CLASS *) NULL)->MEMBER)); \
- COMPILER_CHECK(offsetof(__sanitizer_##CLASS, MEMBER) == \
+#define CHECK_SIZE_AND_OFFSET(CLASS, MEMBER) \
+ COMPILER_CHECK(sizeof(((__sanitizer_##CLASS *)NULL)->MEMBER) == \
+ sizeof(((CLASS *)NULL)->MEMBER)); \
+ COMPILER_CHECK(offsetof(__sanitizer_##CLASS, MEMBER) == \
offsetof(CLASS, MEMBER))
// For sigaction, which is a function and struct at the same time,
// and thus requires explicit "struct" in sizeof() expression.
-#define CHECK_STRUCT_SIZE_AND_OFFSET(CLASS, MEMBER) \
- COMPILER_CHECK(sizeof(((struct __sanitizer_##CLASS *) NULL)->MEMBER) == \
- sizeof(((struct CLASS *) NULL)->MEMBER)); \
- COMPILER_CHECK(offsetof(struct __sanitizer_##CLASS, MEMBER) == \
+#define CHECK_STRUCT_SIZE_AND_OFFSET(CLASS, MEMBER) \
+ COMPILER_CHECK(sizeof(((struct __sanitizer_##CLASS *)NULL)->MEMBER) == \
+ sizeof(((struct CLASS *)NULL)->MEMBER)); \
+ COMPILER_CHECK(offsetof(struct __sanitizer_##CLASS, MEMBER) == \
offsetof(struct CLASS, MEMBER))
#define SIGACTION_SYMNAME sigaction
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_solaris.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_solaris.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_solaris.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_solaris.cpp
index 3503eb2..9717d98 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_solaris.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_solaris.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_platform_limits_solaris.cc ------------------------------===//
+//===-- sanitizer_platform_limits_solaris.cpp -----------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_solaris.h b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_solaris.h
index eb5c585..77ae6e6 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_solaris.h
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_solaris.h
@@ -68,7 +68,7 @@
#if !defined(_LP64)
int pad[4];
#endif
- };
+};
struct __sanitizer_shmid_ds {
__sanitizer_ipc_perm shm_perm;
@@ -236,10 +236,9 @@
typedef int __sanitizer_clockid_t;
// This thing depends on the platform. We are only interested in the upper
-// limit. Verified with a compiler assert in .cc.
-const int pthread_attr_t_max_sz = 128;
+// limit. Verified with a compiler assert in .cpp.
union __sanitizer_pthread_attr_t {
- char size[pthread_attr_t_max_sz]; // NOLINT
+ char size[128];
void *align;
};
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_posix.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_posix.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_posix.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_posix.cpp
index ac9db98..c7f5557 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_posix.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_posix.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_posix.cc ------------------------------------------------===//
+//===-- sanitizer_posix.cpp -----------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -312,6 +312,8 @@
return "SEGV";
case SIGBUS:
return "BUS";
+ case SIGTRAP:
+ return "TRAP";
}
return "UNKNOWN SIGNAL";
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_posix.h b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_posix.h
index 6cf5ce7..70c71f0 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_posix.h
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_posix.h
@@ -39,7 +39,7 @@
// Memory
uptr internal_mmap(void *addr, uptr length, int prot, int flags,
- int fd, OFF_T offset);
+ int fd, u64 offset);
uptr internal_munmap(void *addr, uptr length);
int internal_mprotect(void *addr, uptr length, int prot);
@@ -63,7 +63,7 @@
uptr internal_waitpid(int pid, int *status, int options);
int internal_fork();
-int internal_forkpty(int *amaster);
+fd_t internal_spawn(const char *argv[], pid_t *pid);
int internal_sysctl(const int *name, unsigned int namelen, void *oldp,
uptr *oldlenp, const void *newp, uptr newlen);
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_posix_libcdep.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_posix_libcdep.cpp
similarity index 93%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_posix_libcdep.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_posix_libcdep.cpp
index 23a2f84..304b3a0 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_posix_libcdep.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_posix_libcdep.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_posix_libcdep.cc ----------------------------------------===//
+//===-- sanitizer_posix_libcdep.cpp ---------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -68,11 +68,12 @@
SANITIZER_MADVISE_DONTNEED);
}
-bool NoHugePagesInRegion(uptr addr, uptr size) {
+void SetShadowRegionHugePageMode(uptr addr, uptr size) {
#ifdef MADV_NOHUGEPAGE // May not be defined on old systems.
- return madvise((char *)addr, size, MADV_NOHUGEPAGE) == 0;
-#else
- return true;
+ if (common_flags()->no_huge_pages_for_shadow)
+ madvise((char *)addr, size, MADV_NOHUGEPAGE);
+ else
+ madvise((char *)addr, size, MADV_HUGEPAGE);
#endif // MADV_NOHUGEPAGE
}
@@ -303,11 +304,13 @@
MemoryMappingLayout::CacheMemoryMappings();
}
-bool MmapFixedNoReserve(uptr fixed_addr, uptr size, const char *name) {
+static bool MmapFixed(uptr fixed_addr, uptr size, int additional_flags,
+ const char *name) {
size = RoundUpTo(size, GetPageSizeCached());
fixed_addr = RoundDownTo(fixed_addr, GetPageSizeCached());
- uptr p = MmapNamed((void *)fixed_addr, size, PROT_READ | PROT_WRITE,
- MAP_PRIVATE | MAP_FIXED | MAP_NORESERVE | MAP_ANON, name);
+ uptr p =
+ MmapNamed((void *)fixed_addr, size, PROT_READ | PROT_WRITE,
+ MAP_PRIVATE | MAP_FIXED | additional_flags | MAP_ANON, name);
int reserrno;
if (internal_iserror(p, &reserrno)) {
Report("ERROR: %s failed to "
@@ -319,6 +322,24 @@
return true;
}
+bool MmapFixedNoReserve(uptr fixed_addr, uptr size, const char *name) {
+ return MmapFixed(fixed_addr, size, MAP_NORESERVE, name);
+}
+
+bool MmapFixedSuperNoReserve(uptr fixed_addr, uptr size, const char *name) {
+#if SANITIZER_FREEBSD
+ if (common_flags()->no_huge_pages_for_shadow)
+ return MmapFixedNoReserve(fixed_addr, size, name);
+ // MAP_NORESERVE is implicit with FreeBSD
+ return MmapFixed(fixed_addr, size, MAP_ALIGNED_SUPER, name);
+#else
+ bool r = MmapFixedNoReserve(fixed_addr, size, name);
+ if (r)
+ SetShadowRegionHugePageMode(fixed_addr, size);
+ return r;
+#endif
+}
+
uptr ReservedAddressRange::Init(uptr size, const char *name, uptr fixed_addr) {
base_ = fixed_addr ? MmapFixedNoAccess(fixed_addr, size, name)
: MmapNoAccess(size);
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_printf.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_printf.cpp
similarity index 97%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_printf.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_printf.cpp
index f4e17a8..a032787 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_printf.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_printf.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_printf.cc -----------------------------------------------===//
+//===-- sanitizer_printf.cpp ----------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -229,15 +229,15 @@
// Can be overriden in frontend.
#if SANITIZER_GO && defined(TSAN_EXTERNAL_HOOKS)
// Implementation must be defined in frontend.
-extern "C" void OnPrint(const char *str);
+extern "C" void __sanitizer_on_print(const char *str);
#else
-SANITIZER_INTERFACE_WEAK_DEF(void, OnPrint, const char *str) {
+SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_on_print, const char *str) {
(void)str;
}
#endif
static void CallPrintfAndReportCallback(const char *str) {
- OnPrint(str);
+ __sanitizer_on_print(str);
if (PrintfAndReportCallback)
PrintfAndReportCallback(str);
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps.h b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps.h
index 0520271..d0e5245 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps.h
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps.h
@@ -37,7 +37,7 @@
class MemoryMappedSegment {
public:
- MemoryMappedSegment(char *buff = nullptr, uptr size = 0)
+ explicit MemoryMappedSegment(char *buff = nullptr, uptr size = 0)
: filename(buff), filename_size(size), data_(nullptr) {}
~MemoryMappedSegment() {}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_bsd.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_bsd.cpp
similarity index 97%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_bsd.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_bsd.cpp
index c38bafd..02ff7c0 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_bsd.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_bsd.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_procmaps_bsd.cc -----------------------------------------===//
+//===-- sanitizer_procmaps_bsd.cpp ----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_common.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_common.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_common.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_common.cpp
index 4a2b0a0..e0cb47f 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_common.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_common.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_procmaps_common.cc --------------------------------------===//
+//===-- sanitizer_procmaps_common.cpp -------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_linux.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_linux.cpp
similarity index 97%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_linux.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_linux.cpp
index fd5e036..c7af573 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_linux.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_linux.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_procmaps_linux.cc ---------------------------------------===//
+//===-- sanitizer_procmaps_linux.cpp --------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_mac.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_mac.cpp
similarity index 93%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_mac.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_mac.cpp
index 148910f..d02afcf 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_mac.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_mac.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_procmaps_mac.cc -----------------------------------------===//
+//===-- sanitizer_procmaps_mac.cpp ----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -181,13 +181,14 @@
// Note that the segment addresses are not necessarily sorted.
template <u32 kLCSegment, typename SegmentCommand>
static bool NextSegmentLoad(MemoryMappedSegment *segment,
-MemoryMappedSegmentData *seg_data, MemoryMappingLayoutData &layout_data) {
- const char *lc = layout_data.current_load_cmd_addr;
- layout_data.current_load_cmd_addr += ((const load_command *)lc)->cmdsize;
+ MemoryMappedSegmentData *seg_data,
+ MemoryMappingLayoutData *layout_data) {
+ const char *lc = layout_data->current_load_cmd_addr;
+ layout_data->current_load_cmd_addr += ((const load_command *)lc)->cmdsize;
if (((const load_command *)lc)->cmd == kLCSegment) {
const SegmentCommand* sc = (const SegmentCommand *)lc;
uptr base_virt_addr, addr_mask;
- if (layout_data.current_image == kDyldImageIdx) {
+ if (layout_data->current_image == kDyldImageIdx) {
base_virt_addr = (uptr)get_dyld_hdr();
// vmaddr is masked with 0xfffff because on macOS versions < 10.12,
// it contains an absolute address rather than an offset for dyld.
@@ -198,7 +199,7 @@
addr_mask = 0xfffff;
} else {
base_virt_addr =
- (uptr)_dyld_get_image_vmaddr_slide(layout_data.current_image);
+ (uptr)_dyld_get_image_vmaddr_slide(layout_data->current_image);
addr_mask = ~0;
}
@@ -219,18 +220,18 @@
// Return the initial protection.
segment->protection = sc->initprot;
- segment->offset = (layout_data.current_filetype ==
+ segment->offset = (layout_data->current_filetype ==
/*MH_EXECUTE*/ 0x2)
? sc->vmaddr
: sc->fileoff;
if (segment->filename) {
- const char *src = (layout_data.current_image == kDyldImageIdx)
+ const char *src = (layout_data->current_image == kDyldImageIdx)
? kDyldPath
- : _dyld_get_image_name(layout_data.current_image);
+ : _dyld_get_image_name(layout_data->current_image);
internal_strncpy(segment->filename, src, segment->filename_size);
}
- segment->arch = layout_data.current_arch;
- internal_memcpy(segment->uuid, layout_data.current_uuid, kModuleUUIDSize);
+ segment->arch = layout_data->current_arch;
+ internal_memcpy(segment->uuid, layout_data->current_uuid, kModuleUUIDSize);
return true;
}
return false;
@@ -331,14 +332,14 @@
#ifdef MH_MAGIC_64
case MH_MAGIC_64: {
if (NextSegmentLoad<LC_SEGMENT_64, struct segment_command_64>(
- segment, segment->data_, data_))
+ segment, segment->data_, &data_))
return true;
break;
}
#endif
case MH_MAGIC: {
if (NextSegmentLoad<LC_SEGMENT, struct segment_command>(
- segment, segment->data_, data_))
+ segment, segment->data_, &data_))
return true;
break;
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_solaris.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_solaris.cpp
similarity index 96%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_solaris.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_solaris.cpp
index b5df6fe..8793423 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_solaris.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_solaris.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_procmaps_solaris.cc -------------------------------------===//
+//===-- sanitizer_procmaps_solaris.cpp ------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_rtems.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_rtems.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_rtems.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_rtems.cpp
index ffc21b9..0d2576c 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_rtems.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_rtems.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_rtems.cc ------------------------------------------------===//
+//===-- sanitizer_rtems.cpp -----------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_solaris.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_solaris.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_solaris.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_solaris.cpp
index 37b50c6..035f2d0 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_solaris.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_solaris.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_solaris.cc ----------------------------------------------===//
+//===-- sanitizer_solaris.cpp ---------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stackdepot.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stackdepot.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stackdepot.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stackdepot.cpp
index 1cdedfa..30073a9 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stackdepot.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stackdepot.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_stackdepot.cc -------------------------------------------===//
+//===-- sanitizer_stackdepot.cpp ------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace.cpp
index 2647403..ef14fb7 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_stacktrace.cc -------------------------------------------===//
+//===-- sanitizer_stacktrace.cpp ------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace_libcdep.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace_libcdep.cpp
similarity index 94%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace_libcdep.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace_libcdep.cpp
index 859032b..4ef305c 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace_libcdep.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace_libcdep.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_stacktrace_libcdep.cc -----------------------------------===//
+//===-- sanitizer_stacktrace_libcdep.cpp ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -150,8 +150,9 @@
}
SANITIZER_INTERFACE_ATTRIBUTE
-int __sanitizer_get_module_and_offset_for_pc( // NOLINT
- uptr pc, char *module_name, uptr module_name_len, uptr *pc_offset) {
+int __sanitizer_get_module_and_offset_for_pc(uptr pc, char *module_name,
+ uptr module_name_len,
+ uptr *pc_offset) {
return __sanitizer::GetModuleAndOffsetForPc(pc, module_name, module_name_len,
pc_offset);
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace_printer.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace_printer.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace_printer.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace_printer.cpp
index 17bbf6c..150ff47 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace_printer.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace_printer.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_common.cc -----------------------------------------------===//
+//===-- sanitizer_common.cpp ----------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -16,7 +16,7 @@
namespace __sanitizer {
-// sanitizer_symbolizer_markup.cc implements these differently.
+// sanitizer_symbolizer_markup.cpp implements these differently.
#if !SANITIZER_SYMBOLIZER_MARKUP
static const char *StripFunctionName(const char *function, const char *prefix) {
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace_sparc.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace_sparc.cpp
similarity index 97%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace_sparc.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace_sparc.cpp
index b238cfb..34190fb 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace_sparc.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace_sparc.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_stacktrace_sparc.cc -------------------------------------===//
+//===-- sanitizer_stacktrace_sparc.cpp ------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_linux_libcdep.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_linux_libcdep.cpp
similarity index 99%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_linux_libcdep.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_linux_libcdep.cpp
index 716f0d2..651d505 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_linux_libcdep.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_linux_libcdep.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_stoptheworld_linux_libcdep.cc ---------------------------===//
+//===-- sanitizer_stoptheworld_linux_libcdep.cpp --------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -223,10 +223,11 @@
case ThreadLister::Ok:
break;
}
- for (tid_t tid : threads)
+ for (tid_t tid : threads) {
if (SuspendThread(tid))
retry = true;
- };
+ }
+ }
return suspended_threads_list_.ThreadCount();
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_mac.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_mac.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_mac.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_mac.cpp
index e79edc4..9dffd21 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_mac.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_mac.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_stoptheworld_mac.cc -------------------------------------===//
+//===-- sanitizer_stoptheworld_mac.cpp ------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_netbsd_libcdep.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_netbsd_libcdep.cpp
similarity index 96%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_netbsd_libcdep.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_netbsd_libcdep.cpp
index 7a8d14a..1ed2134 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_netbsd_libcdep.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_netbsd_libcdep.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_stoptheworld_netbsd_libcdep.cc --------------------------===//
+//===-- sanitizer_stoptheworld_netbsd_libcdep.cpp -------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -10,7 +10,7 @@
// This implementation was inspired by Markus Gutschke's linuxthreads.cc.
//
// This is a NetBSD variation of Linux stoptheworld implementation
-// See sanitizer_stoptheworld_linux_libcdep.cc for code comments.
+// See sanitizer_stoptheworld_linux_libcdep.cpp for code comments.
//
//===----------------------------------------------------------------------===//
@@ -120,10 +120,18 @@
VReport(2, "Attached to process %d.\n", pid_);
+#ifdef PT_LWPNEXT
+ struct ptrace_lwpstatus pl;
+ int op = PT_LWPNEXT;
+#else
struct ptrace_lwpinfo pl;
- int val;
+ int op = PT_LWPINFO;
+#endif
+
pl.pl_lwpid = 0;
- while ((val = ptrace(PT_LWPINFO, pid_, (void *)&pl, sizeof(pl))) != -1 &&
+
+ int val;
+ while ((val = ptrace(op, pid_, (void *)&pl, sizeof(pl))) != -1 &&
pl.pl_lwpid != 0) {
suspended_threads_list_.Append(pl.pl_lwpid);
VReport(2, "Appended thread %d in process %d.\n", pl.pl_lwpid, pid_);
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_suppressions.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_suppressions.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_suppressions.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_suppressions.cpp
index 12ecd9a..44c83a6 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_suppressions.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_suppressions.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_suppressions.cc -----------------------------------------===//
+//===-- sanitizer_suppressions.cpp ----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_suppressions.h b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_suppressions.h
index f9da7af..2d88b1f 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_suppressions.h
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_suppressions.h
@@ -42,7 +42,7 @@
void GetMatched(InternalMmapVector<Suppression *> *matched);
private:
- static const int kMaxSuppressionTypes = 32;
+ static const int kMaxSuppressionTypes = 64;
const char **const suppression_types_;
const int suppression_types_num_;
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer.cpp
similarity index 97%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer.cpp
index 216ce58..ce2ece5 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_symbolizer.cc -------------------------------------------===//
+//===-- sanitizer_symbolizer.cpp ------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_internal.h b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_internal.h
index 4611b7d..c04797d 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_internal.h
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_internal.h
@@ -76,30 +76,31 @@
// SymbolizerProcess may not be used from two threads simultaneously.
class SymbolizerProcess {
public:
- explicit SymbolizerProcess(const char *path, bool use_forkpty = false);
+ explicit SymbolizerProcess(const char *path, bool use_posix_spawn = false);
const char *SendCommand(const char *command);
protected:
+ /// The maximum number of arguments required to invoke a tool process.
+ static const unsigned kArgVMax = 6;
+
+ // Customizable by subclasses.
+ virtual bool StartSymbolizerSubprocess();
+ virtual bool ReadFromSymbolizer(char *buffer, uptr max_length);
+
+ private:
virtual bool ReachedEndOfOutput(const char *buffer, uptr length) const {
UNIMPLEMENTED();
}
- /// The maximum number of arguments required to invoke a tool process.
- enum { kArgVMax = 6 };
-
/// Fill in an argv array to invoke the child process.
virtual void GetArgV(const char *path_to_binary,
const char *(&argv)[kArgVMax]) const {
UNIMPLEMENTED();
}
- virtual bool ReadFromSymbolizer(char *buffer, uptr max_length);
-
- private:
bool Restart();
const char *SendCommandImpl(const char *command);
bool WriteToSymbolizer(const char *buffer, uptr length);
- bool StartSymbolizerSubprocess();
const char *path_;
fd_t input_fd_;
@@ -113,7 +114,7 @@
uptr times_restarted_;
bool failed_to_start_;
bool reported_invalid_path_;
- bool use_forkpty_;
+ bool use_posix_spawn_;
};
class LLVMSymbolizerProcess;
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_libbacktrace.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_libbacktrace.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_libbacktrace.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_libbacktrace.cpp
index 8a20e06..27ed222 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_libbacktrace.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_libbacktrace.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_symbolizer_libbacktrace.cc ------------------------------===//
+//===-- sanitizer_symbolizer_libbacktrace.cpp -----------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_libcdep.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_libcdep.cpp
similarity index 97%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_libcdep.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_libcdep.cpp
index 7f5bc55..3b19a683 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_libcdep.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_libcdep.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_symbolizer_libcdep.cc -----------------------------------===//
+//===-- sanitizer_symbolizer_libcdep.cpp ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -25,7 +25,7 @@
return symbolizer_;
}
-// See sanitizer_symbolizer_markup.cc.
+// See sanitizer_symbolizer_markup.cpp.
#if !SANITIZER_SYMBOLIZER_MARKUP
const char *ExtractToken(const char *str, const char *delims, char **result) {
@@ -238,7 +238,8 @@
// <empty line>
class LLVMSymbolizerProcess : public SymbolizerProcess {
public:
- explicit LLVMSymbolizerProcess(const char *path) : SymbolizerProcess(path) {}
+ explicit LLVMSymbolizerProcess(const char *path)
+ : SymbolizerProcess(path, /*use_posix_spawn=*/SANITIZER_MAC) {}
private:
bool ReachedEndOfOutput(const char *buffer, uptr length) const override {
@@ -452,14 +453,14 @@
return symbolizer_process_->SendCommand(buffer_);
}
-SymbolizerProcess::SymbolizerProcess(const char *path, bool use_forkpty)
+SymbolizerProcess::SymbolizerProcess(const char *path, bool use_posix_spawn)
: path_(path),
input_fd_(kInvalidFd),
output_fd_(kInvalidFd),
times_restarted_(0),
failed_to_start_(false),
reported_invalid_path_(false),
- use_forkpty_(use_forkpty) {
+ use_posix_spawn_(use_posix_spawn) {
CHECK(path_);
CHECK_NE(path_[0], '\0');
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_mac.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_mac.cpp
similarity index 82%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_mac.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_mac.cpp
index d356657..f26efe5 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_mac.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_mac.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_symbolizer_mac.cc ---------------------------------------===//
+//===-- sanitizer_symbolizer_mac.cpp --------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -31,6 +31,9 @@
Dl_info info;
int result = dladdr((const void *)addr, &info);
if (!result) return false;
+
+ CHECK(addr >= reinterpret_cast<uptr>(info.dli_saddr));
+ stack->info.function_offset = addr - reinterpret_cast<uptr>(info.dli_saddr);
const char *demangled = DemangleSwiftAndCXX(info.dli_sname);
if (!demangled) return false;
stack->info.function = internal_strdup(demangled);
@@ -50,13 +53,18 @@
class AtosSymbolizerProcess : public SymbolizerProcess {
public:
explicit AtosSymbolizerProcess(const char *path, pid_t parent_pid)
- : SymbolizerProcess(path, /*use_forkpty*/ true) {
+ : SymbolizerProcess(path, /*use_posix_spawn*/ true) {
// Put the string command line argument in the object so that it outlives
// the call to GetArgV.
internal_snprintf(pid_str_, sizeof(pid_str_), "%d", parent_pid);
}
private:
+ bool StartSymbolizerSubprocess() override {
+ // Configure sandbox before starting atos process.
+ return SymbolizerProcess::StartSymbolizerSubprocess();
+ }
+
bool ReachedEndOfOutput(const char *buffer, uptr length) const override {
return (length >= 1 && buffer[length - 1] == '\n');
}
@@ -140,12 +148,29 @@
const char *buf = process_->SendCommand(command);
if (!buf) return false;
uptr line;
+ uptr start_address = AddressInfo::kUnknown;
if (!ParseCommandOutput(buf, addr, &stack->info.function, &stack->info.module,
- &stack->info.file, &line, nullptr)) {
+ &stack->info.file, &line, &start_address)) {
process_ = nullptr;
return false;
}
stack->info.line = (int)line;
+
+ if (start_address == AddressInfo::kUnknown) {
+ // Fallback to dladdr() to get function start address if atos doesn't report
+ // it.
+ Dl_info info;
+ int result = dladdr((const void *)addr, &info);
+ if (result)
+ start_address = reinterpret_cast<uptr>(info.dli_saddr);
+ }
+
+ // Only assig to `function_offset` if we were able to get the function's
+ // start address.
+ if (start_address != AddressInfo::kUnknown) {
+ CHECK(addr >= start_address);
+ stack->info.function_offset = addr - start_address;
+ }
return true;
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_markup.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_markup.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_markup.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_markup.cpp
index aee49b4..57b4d0c9 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_markup.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_markup.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_symbolizer_markup.cc ------------------------------------===//
+//===-- sanitizer_symbolizer_markup.cpp -----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_posix_libcdep.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_posix_libcdep.cpp
similarity index 88%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_posix_libcdep.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_posix_libcdep.cpp
index 2df3a90..c123ecb 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_posix_libcdep.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_posix_libcdep.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_symbolizer_posix_libcdep.cc -----------------------------===//
+//===-- sanitizer_symbolizer_posix_libcdep.cpp ----------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -33,10 +33,6 @@
#include <sys/wait.h>
#include <unistd.h>
-#if SANITIZER_MAC
-#include <util.h> // for forkpty()
-#endif // SANITIZER_MAC
-
// C++ demangling function, as required by Itanium C++ ABI. This is weak,
// because we do not require a C++ ABI library to be linked to a program
// using sanitizers; if it's not present, we'll just use the mangled name.
@@ -151,80 +147,32 @@
return false;
}
- int pid = -1;
+ const char *argv[kArgVMax];
+ GetArgV(path_, argv);
+ pid_t pid;
- int infd[2];
- internal_memset(&infd, 0, sizeof(infd));
- int outfd[2];
- internal_memset(&outfd, 0, sizeof(outfd));
- if (!CreateTwoHighNumberedPipes(infd, outfd)) {
- Report("WARNING: Can't create a socket pair to start "
- "external symbolizer (errno: %d)\n", errno);
- return false;
- }
-
- if (use_forkpty_) {
+ if (use_posix_spawn_) {
#if SANITIZER_MAC
- fd_t fd = kInvalidFd;
-
- // forkpty redirects stdout and stderr into a single stream, so we would
- // receive error messages as standard replies. To avoid that, let's dup
- // stderr and restore it in the child.
- int saved_stderr = dup(STDERR_FILENO);
- CHECK_GE(saved_stderr, 0);
-
- // We only need one pipe, for stdin of the child.
- close(outfd[0]);
- close(outfd[1]);
-
- // Use forkpty to disable buffering in the new terminal.
- pid = internal_forkpty(&fd);
- if (pid == -1) {
- // forkpty() failed.
- Report("WARNING: failed to fork external symbolizer (errno: %d)\n",
+ fd_t fd = internal_spawn(argv, &pid);
+ if (fd == kInvalidFd) {
+ Report("WARNING: failed to spawn external symbolizer (errno: %d)\n",
errno);
return false;
- } else if (pid == 0) {
- // Child subprocess.
-
- // infd[0] is the child's reading end.
- close(infd[1]);
-
- // Set up stdin to read from the pipe.
- CHECK_GE(dup2(infd[0], STDIN_FILENO), 0);
- close(infd[0]);
-
- // Restore stderr.
- CHECK_GE(dup2(saved_stderr, STDERR_FILENO), 0);
- close(saved_stderr);
-
- const char *argv[kArgVMax];
- GetArgV(path_, argv);
- execv(path_, const_cast<char **>(&argv[0]));
- internal__exit(1);
}
- // Input for the child, infd[1] is our writing end.
- output_fd_ = infd[1];
- close(infd[0]);
-
- // Continue execution in parent process.
input_fd_ = fd;
-
- close(saved_stderr);
-
- // Disable echo in the new terminal, disable CR.
- struct termios termflags;
- tcgetattr(fd, &termflags);
- termflags.c_oflag &= ~ONLCR;
- termflags.c_lflag &= ~ECHO;
- tcsetattr(fd, TCSANOW, &termflags);
+ output_fd_ = fd;
#else // SANITIZER_MAC
UNIMPLEMENTED();
#endif // SANITIZER_MAC
} else {
- const char *argv[kArgVMax];
- GetArgV(path_, argv);
+ fd_t infd[2] = {}, outfd[2] = {};
+ if (!CreateTwoHighNumberedPipes(infd, outfd)) {
+ Report("WARNING: Can't create a socket pair to start "
+ "external symbolizer (errno: %d)\n", errno);
+ return false;
+ }
+
pid = StartSubprocess(path_, argv, /* stdin */ outfd[0],
/* stdout */ infd[1]);
if (pid < 0) {
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_report.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_report.cpp
similarity index 91%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_report.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_report.cpp
index f4167d1..c26724c 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_report.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_report.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_symbolizer_report.cc ------------------------------------===//
+//===-- sanitizer_symbolizer_report.cpp -----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -106,8 +106,9 @@
if (StackTrace::WillUseFastUnwind(fast)) {
GetThreadStackTopAndBottom(false, &top, &bottom);
stack->Unwind(kStackTraceMax, pc, bp, nullptr, top, bottom, true);
- } else
+ } else {
stack->Unwind(kStackTraceMax, pc, 0, nullptr, 0, 0, false);
+ }
Printf("%s", d.Warning());
Report("WARNING: %s: writable-executable page usage\n", SanitizerToolName);
@@ -190,9 +191,14 @@
SanitizerCommonDecorator d;
Printf("%s", d.Warning());
const char *description = sig.Describe();
- Report("ERROR: %s: %s on unknown address %p (pc %p bp %p sp %p T%d)\n",
- SanitizerToolName, description, (void *)sig.addr, (void *)sig.pc,
- (void *)sig.bp, (void *)sig.sp, tid);
+ if (sig.is_memory_access && !sig.is_true_faulting_addr)
+ Report("ERROR: %s: %s on unknown address (pc %p bp %p sp %p T%d)\n",
+ SanitizerToolName, description, (void *)sig.pc, (void *)sig.bp,
+ (void *)sig.sp, tid);
+ else
+ Report("ERROR: %s: %s on unknown address %p (pc %p bp %p sp %p T%d)\n",
+ SanitizerToolName, description, (void *)sig.addr, (void *)sig.pc,
+ (void *)sig.bp, (void *)sig.sp, tid);
Printf("%s", d.Default());
if (sig.pc < GetPageSizeCached())
Report("Hint: pc points to the zero page.\n");
@@ -202,7 +208,11 @@
? "WRITE"
: (sig.write_flag == SignalContext::READ ? "READ" : "UNKNOWN");
Report("The signal is caused by a %s memory access.\n", access_type);
- if (sig.addr < GetPageSizeCached())
+ if (!sig.is_true_faulting_addr)
+ Report("Hint: this fault was caused by a dereference of a high value "
+ "address (see register values below). Dissassemble the provided "
+ "pc to learn which register was used.\n");
+ else if (sig.addr < GetPageSizeCached())
Report("Hint: address points to the zero page.\n");
}
MaybeReportNonExecRegion(sig.pc);
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_win.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_win.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_win.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_win.cpp
index 1badcf5..2808779 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_win.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_win.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_symbolizer_win.cc ---------------------------------------===//
+//===-- sanitizer_symbolizer_win.cpp --------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_syscalls_netbsd.inc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_syscalls_netbsd.inc
index 21b5216..02b7e11 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_syscalls_netbsd.inc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_syscalls_netbsd.inc
@@ -42,8 +42,8 @@
// DO NOT EDIT! THIS FILE HAS BEEN GENERATED!
//
// Generated with: generate_netbsd_syscalls.awk
-// Generated date: 2018-10-30
-// Generated from: syscalls.master,v 1.293 2018/07/31 13:00:13 rjs Exp
+// Generated date: 2019-12-24
+// Generated from: syscalls.master,v 1.296 2019/09/22 22:59:39 christos Exp
//
//===----------------------------------------------------------------------===//
@@ -323,6 +323,16 @@
PRE_READ(addr_, struct_ptrace_ptrace_siginfo_struct_sz);
} else if (req_ == ptrace_pt_get_siginfo) {
PRE_WRITE(addr_, struct_ptrace_ptrace_siginfo_struct_sz);
+ } else if (req_ == ptrace_pt_lwpstatus) {
+ struct __sanitizer_ptrace_lwpstatus *addr =
+ (struct __sanitizer_ptrace_lwpstatus *)addr_;
+ PRE_READ(&addr->pl_lwpid, sizeof(__sanitizer_lwpid_t));
+ PRE_WRITE(addr, struct_ptrace_ptrace_lwpstatus_struct_sz);
+ } else if (req_ == ptrace_pt_lwpnext) {
+ struct __sanitizer_ptrace_lwpstatus *addr =
+ (struct __sanitizer_ptrace_lwpstatus *)addr_;
+ PRE_READ(&addr->pl_lwpid, sizeof(__sanitizer_lwpid_t));
+ PRE_WRITE(addr, struct_ptrace_ptrace_lwpstatus_struct_sz);
} else if (req_ == ptrace_pt_setregs) {
PRE_READ(addr_, struct_ptrace_reg_struct_sz);
} else if (req_ == ptrace_pt_getregs) {
@@ -366,6 +376,16 @@
POST_READ(addr_, struct_ptrace_ptrace_siginfo_struct_sz);
} else if (req_ == ptrace_pt_get_siginfo) {
POST_WRITE(addr_, struct_ptrace_ptrace_siginfo_struct_sz);
+ } else if (req_ == ptrace_pt_lwpstatus) {
+ struct __sanitizer_ptrace_lwpstatus *addr =
+ (struct __sanitizer_ptrace_lwpstatus *)addr_;
+ POST_READ(&addr->pl_lwpid, sizeof(__sanitizer_lwpid_t));
+ POST_WRITE(addr, struct_ptrace_ptrace_lwpstatus_struct_sz);
+ } else if (req_ == ptrace_pt_lwpnext) {
+ struct __sanitizer_ptrace_lwpstatus *addr =
+ (struct __sanitizer_ptrace_lwpstatus *)addr_;
+ POST_READ(&addr->pl_lwpid, sizeof(__sanitizer_lwpid_t));
+ POST_WRITE(addr, struct_ptrace_ptrace_lwpstatus_struct_sz);
} else if (req_ == ptrace_pt_setregs) {
POST_READ(addr_, struct_ptrace_reg_struct_sz);
} else if (req_ == ptrace_pt_getregs) {
@@ -2433,30 +2453,31 @@
POST_SYSCALL(uuidgen)(long long res, void *store_, long long count_) {
/* Nothing to do */
}
-PRE_SYSCALL(getvfsstat)(void *buf_, long long bufsize_, long long flags_) {
+PRE_SYSCALL(compat_90_getvfsstat)
+(void *buf_, long long bufsize_, long long flags_) {
/* Nothing to do */
}
-POST_SYSCALL(getvfsstat)
+POST_SYSCALL(compat_90_getvfsstat)
(long long res, void *buf_, long long bufsize_, long long flags_) {
/* Nothing to do */
}
-PRE_SYSCALL(statvfs1)(void *path_, void *buf_, long long flags_) {
+PRE_SYSCALL(compat_90_statvfs1)(void *path_, void *buf_, long long flags_) {
const char *path = (const char *)path_;
if (path) {
PRE_READ(path, __sanitizer::internal_strlen(path) + 1);
}
}
-POST_SYSCALL(statvfs1)
+POST_SYSCALL(compat_90_statvfs1)
(long long res, void *path_, void *buf_, long long flags_) {
const char *path = (const char *)path_;
if (path) {
POST_READ(path, __sanitizer::internal_strlen(path) + 1);
}
}
-PRE_SYSCALL(fstatvfs1)(long long fd_, void *buf_, long long flags_) {
+PRE_SYSCALL(compat_90_fstatvfs1)(long long fd_, void *buf_, long long flags_) {
/* Nothing to do */
}
-POST_SYSCALL(fstatvfs1)
+POST_SYSCALL(compat_90_fstatvfs1)
(long long res, long long fd_, void *buf_, long long flags_) {
/* Nothing to do */
}
@@ -2853,13 +2874,13 @@
}
POST_SYSCALL(__fhopen40)
(long long res, void *fhp_, long long fh_size_, long long flags_) {}
-PRE_SYSCALL(__fhstatvfs140)
+PRE_SYSCALL(compat_90_fhstatvfs1)
(void *fhp_, long long fh_size_, void *buf_, long long flags_) {
if (fhp_) {
PRE_READ(fhp_, fh_size_);
}
}
-POST_SYSCALL(__fhstatvfs140)
+POST_SYSCALL(compat_90_fhstatvfs1)
(long long res, void *fhp_, long long fh_size_, void *buf_, long long flags_) {}
PRE_SYSCALL(compat_50___fhstat40)(void *fhp_, long long fh_size_, void *sb_) {
if (fhp_) {
@@ -3768,6 +3789,41 @@
(long long res, long long idtype_, long long id_, void *clock_id_) {
/* Nothing to do */
}
+PRE_SYSCALL(__getvfsstat90)(void *buf_, long long bufsize_, long long flags_) {
+ /* Nothing to do */
+}
+POST_SYSCALL(__getvfsstat90)
+(long long res, void *buf_, long long bufsize_, long long flags_) {
+ /* Nothing to do */
+}
+PRE_SYSCALL(__statvfs190)(void *path_, void *buf_, long long flags_) {
+ const char *path = (const char *)path_;
+ if (path) {
+ PRE_READ(path, __sanitizer::internal_strlen(path) + 1);
+ }
+}
+POST_SYSCALL(__statvfs190)
+(long long res, void *path_, void *buf_, long long flags_) {
+ const char *path = (const char *)path_;
+ if (path) {
+ POST_READ(path, __sanitizer::internal_strlen(path) + 1);
+ }
+}
+PRE_SYSCALL(__fstatvfs190)(long long fd_, void *buf_, long long flags_) {
+ /* Nothing to do */
+}
+POST_SYSCALL(__fstatvfs190)
+(long long res, long long fd_, void *buf_, long long flags_) {
+ /* Nothing to do */
+}
+PRE_SYSCALL(__fhstatvfs190)
+(void *fhp_, long long fh_size_, void *buf_, long long flags_) {
+ if (fhp_) {
+ PRE_READ(fhp_, fh_size_);
+ }
+}
+POST_SYSCALL(__fhstatvfs190)
+(long long res, void *fhp_, long long fh_size_, void *buf_, long long flags_) {}
#undef SYS_MAXSYSARGS
} // extern "C"
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_termination.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_termination.cpp
similarity index 95%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_termination.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_termination.cpp
index a011cce..84be6fc 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_termination.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_termination.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_termination.cc --------------------------------*- C++ -*-===//
+//===-- sanitizer_termination.cpp -------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -84,7 +84,7 @@
} // namespace __sanitizer
-using namespace __sanitizer; // NOLINT
+using namespace __sanitizer;
extern "C" {
SANITIZER_INTERFACE_ATTRIBUTE
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_thread_registry.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_thread_registry.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_thread_registry.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_thread_registry.cpp
index 0269128..f2c6f27 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_thread_registry.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_thread_registry.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_thread_registry.cc --------------------------------------===//
+//===-- sanitizer_thread_registry.cpp -------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_tls_get_addr.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_tls_get_addr.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_tls_get_addr.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_tls_get_addr.cpp
index 5e33e2a..9ca898a 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_tls_get_addr.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_tls_get_addr.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_tls_get_addr.cc -----------------------------------------===//
+//===-- sanitizer_tls_get_addr.cpp ----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_tls_get_addr.h b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_tls_get_addr.h
index cc178d3..c7cd5a8 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_tls_get_addr.h
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_tls_get_addr.h
@@ -42,7 +42,7 @@
uptr dtv_size;
DTV *dtv; // dtv_size elements, allocated by MmapOrDie.
- // Auxiliary fields, don't access them outside sanitizer_tls_get_addr.cc
+ // Auxiliary fields, don't access them outside sanitizer_tls_get_addr.cpp
uptr last_memalign_size;
uptr last_memalign_ptr;
};
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_type_traits.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_type_traits.cpp
similarity index 90%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_type_traits.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_type_traits.cpp
index e3e431a1..5ee37d7 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_type_traits.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_type_traits.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_type_traits.cc --------------------------------*- C++ -*-===//
+//===-- sanitizer_type_traits.cpp -------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_unwind_linux_libcdep.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_unwind_linux_libcdep.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_unwind_linux_libcdep.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_unwind_linux_libcdep.cpp
index 30581e8..b2628dc 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_unwind_linux_libcdep.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_unwind_linux_libcdep.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_unwind_linux_libcdep.cc ---------------------------------===//
+//===-- sanitizer_unwind_linux_libcdep.cpp --------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -27,6 +27,8 @@
namespace __sanitizer {
+namespace {
+
//---------------------------- UnwindSlow --------------------------------------
typedef struct {
@@ -46,38 +48,6 @@
unwind_backtrace_signal_arch_func unwind_backtrace_signal_arch;
} // extern "C"
-#if SANITIZER_ANDROID
-void SanitizerInitializeUnwinder() {
- if (AndroidGetApiLevel() >= ANDROID_LOLLIPOP_MR1) return;
-
- // Pre-lollipop Android can not unwind through signal handler frames with
- // libgcc unwinder, but it has a libcorkscrew.so library with the necessary
- // workarounds.
- void *p = dlopen("libcorkscrew.so", RTLD_LAZY);
- if (!p) {
- VReport(1,
- "Failed to open libcorkscrew.so. You may see broken stack traces "
- "in SEGV reports.");
- return;
- }
- acquire_my_map_info_list =
- (acquire_my_map_info_list_func)(uptr)dlsym(p, "acquire_my_map_info_list");
- release_my_map_info_list =
- (release_my_map_info_list_func)(uptr)dlsym(p, "release_my_map_info_list");
- unwind_backtrace_signal_arch = (unwind_backtrace_signal_arch_func)(uptr)dlsym(
- p, "unwind_backtrace_signal_arch");
- if (!acquire_my_map_info_list || !release_my_map_info_list ||
- !unwind_backtrace_signal_arch) {
- VReport(1,
- "Failed to find one of the required symbols in libcorkscrew.so. "
- "You may see broken stack traces in SEGV reports.");
- acquire_my_map_info_list = 0;
- unwind_backtrace_signal_arch = 0;
- release_my_map_info_list = 0;
- }
-}
-#endif
-
#if defined(__arm__) && !SANITIZER_NETBSD
// NetBSD uses dwarf EH
#define UNWIND_STOP _URC_END_OF_STACK
@@ -119,6 +89,40 @@
return UNWIND_CONTINUE;
}
+} // namespace
+
+#if SANITIZER_ANDROID
+void SanitizerInitializeUnwinder() {
+ if (AndroidGetApiLevel() >= ANDROID_LOLLIPOP_MR1) return;
+
+ // Pre-lollipop Android can not unwind through signal handler frames with
+ // libgcc unwinder, but it has a libcorkscrew.so library with the necessary
+ // workarounds.
+ void *p = dlopen("libcorkscrew.so", RTLD_LAZY);
+ if (!p) {
+ VReport(1,
+ "Failed to open libcorkscrew.so. You may see broken stack traces "
+ "in SEGV reports.");
+ return;
+ }
+ acquire_my_map_info_list =
+ (acquire_my_map_info_list_func)(uptr)dlsym(p, "acquire_my_map_info_list");
+ release_my_map_info_list =
+ (release_my_map_info_list_func)(uptr)dlsym(p, "release_my_map_info_list");
+ unwind_backtrace_signal_arch = (unwind_backtrace_signal_arch_func)(uptr)dlsym(
+ p, "unwind_backtrace_signal_arch");
+ if (!acquire_my_map_info_list || !release_my_map_info_list ||
+ !unwind_backtrace_signal_arch) {
+ VReport(1,
+ "Failed to find one of the required symbols in libcorkscrew.so. "
+ "You may see broken stack traces in SEGV reports.");
+ acquire_my_map_info_list = 0;
+ unwind_backtrace_signal_arch = 0;
+ release_my_map_info_list = 0;
+ }
+}
+#endif
+
void BufferedStackTrace::UnwindSlow(uptr pc, u32 max_depth) {
CHECK_GE(max_depth, 2);
size = 0;
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_unwind_win.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_unwind_win.cpp
similarity index 96%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_unwind_win.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_unwind_win.cpp
index 93908ab..8e06940 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_unwind_win.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_unwind_win.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_unwind_win.cc -------------------------------------------===//
+//===-- sanitizer_unwind_win.cpp ------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_vector.h b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_vector.h
index 4b9ae7d..31216f3 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_vector.h
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_vector.h
@@ -23,11 +23,7 @@
template<typename T>
class Vector {
public:
- explicit Vector()
- : begin_()
- , end_()
- , last_() {
- }
+ Vector() : begin_(), end_(), last_() {}
~Vector() {
if (begin_)
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win.cpp
similarity index 97%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win.cpp
index 457cecb..36dde49 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_win.cc --------------------------------------------------===//
+//===-- sanitizer_win.cpp -------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -239,6 +239,11 @@
return true;
}
+bool MmapFixedSuperNoReserve(uptr fixed_addr, uptr size, const char *name) {
+ // FIXME: Windows support large pages too. Might be worth checking
+ return MmapFixedNoReserve(fixed_addr, size, name);
+}
+
// Memory space mapped by 'MmapFixedOrDie' must have been reserved by
// 'MmapFixedNoAccess'.
void *MmapFixedOrDie(uptr fixed_addr, uptr size, const char *name) {
@@ -329,9 +334,8 @@
// FIXME: add madvise-analog when we move to 64-bits.
}
-bool NoHugePagesInRegion(uptr addr, uptr size) {
+void SetShadowRegionHugePageMode(uptr addr, uptr size) {
// FIXME: probably similar to ReleaseMemoryToOS.
- return true;
}
bool DontDumpShadowMemory(uptr addr, uptr length) {
@@ -672,7 +676,7 @@
return ret;
}
-#pragma section(".CRT$XID", long, read) // NOLINT
+#pragma section(".CRT$XID", long, read)
__declspec(allocate(".CRT$XID")) int (*__run_atexit)() = RunAtexit;
#endif
@@ -941,6 +945,11 @@
return GetWriteFlag() != SignalContext::UNKNOWN;
}
+bool SignalContext::IsTrueFaultingAddress() const {
+ // FIXME: Provide real implementation for this. See Linux and Mac variants.
+ return IsMemoryAccess();
+}
+
SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
// The contents of this array are documented at
@@ -1055,7 +1064,7 @@
// FIXME: implement on this platform
// Should be implemented based on
// SymbolizerProcess::StarAtSymbolizerSubprocess
- // from lib/sanitizer_common/sanitizer_symbolizer_win.cc.
+ // from lib/sanitizer_common/sanitizer_symbolizer_win.cpp.
return -1;
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_defs.h b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_defs.h
index bcd94a0..bfe38a3 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_defs.h
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_defs.h
@@ -43,6 +43,8 @@
#define STRINGIFY_(A) #A
#define STRINGIFY(A) STRINGIFY_(A)
+#if !SANITIZER_GO
+
// ----------------- A workaround for the absence of weak symbols --------------
// We don't have a direct equivalent of weak symbols when using MSVC, but we can
// use the /alternatename directive to tell the linker to default a specific
@@ -158,5 +160,15 @@
// return a >= b;
// }
//
+
+#else // SANITIZER_GO
+
+// Go neither needs nor wants weak references.
+// The shenanigans above don't work for gcc.
+# define WIN_WEAK_EXPORT_DEF(ReturnType, Name, ...) \
+ extern "C" ReturnType Name(__VA_ARGS__)
+
+#endif // SANITIZER_GO
+
#endif // SANITIZER_WINDOWS
#endif // SANITIZER_WIN_DEFS_H
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_dll_thunk.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_dll_thunk.cpp
similarity index 92%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_dll_thunk.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_dll_thunk.cpp
index 5a94791..1562c16 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_dll_thunk.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_dll_thunk.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_win_dll_thunk.cc ----------------------------------------===//
+//===-- sanitizer_win_dll_thunk.cpp ---------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -54,8 +54,8 @@
#define INTERFACE_WEAK_FUNCTION(Name) INTERCEPT_SANITIZER_WEAK_FUNCTION(Name)
#include "sanitizer_common_interface.inc"
-#pragma section(".DLLTH$A", read) // NOLINT
-#pragma section(".DLLTH$Z", read) // NOLINT
+#pragma section(".DLLTH$A", read)
+#pragma section(".DLLTH$Z", read)
typedef void (*DllThunkCB)();
extern "C" {
@@ -85,7 +85,7 @@
// We want to call dll_thunk_init before C/C++ initializers / constructors are
// executed, otherwise functions like memset might be invoked.
-#pragma section(".CRT$XIB", long, read) // NOLINT
+#pragma section(".CRT$XIB", long, read)
__declspec(allocate(".CRT$XIB")) int (*__dll_thunk_preinit)() =
__dll_thunk_init;
@@ -94,7 +94,7 @@
if (reason == /*DLL_PROCESS_ATTACH=*/1) __dll_thunk_init();
}
-#pragma section(".CRT$XLAB", long, read) // NOLINT
+#pragma section(".CRT$XLAB", long, read)
__declspec(allocate(".CRT$XLAB")) void (WINAPI *__dll_thunk_tls_init)(void *,
unsigned long, void *) = dll_thunk_thread_init;
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_dynamic_runtime_thunk.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_dynamic_runtime_thunk.cpp
similarity index 94%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_dynamic_runtime_thunk.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_dynamic_runtime_thunk.cpp
index 89756f1..87c032c 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_dynamic_runtime_thunk.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_dynamic_runtime_thunk.cpp
@@ -1,4 +1,4 @@
-//===-- santizer_win_dynamic_runtime_thunk.cc -----------------------------===//
+//===-- santizer_win_dynamic_runtime_thunk.cpp ----------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_weak_interception.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_weak_interception.cpp
similarity index 92%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_weak_interception.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_weak_interception.cpp
index b1ac44d..b14bbf7 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_weak_interception.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win_weak_interception.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_win_weak_interception.cc --------------------------------===//
+//===-- sanitizer_win_weak_interception.cpp -------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -38,6 +38,7 @@
// Declare weak hooks.
extern "C" {
+void __sanitizer_on_print(const char *str);
void __sanitizer_weak_hook_memcmp(uptr called_pc, const void *s1,
const void *s2, uptr n, int result);
void __sanitizer_weak_hook_strcmp(uptr called_pc, const char *s1,
@@ -53,8 +54,8 @@
#define INTERFACE_WEAK_FUNCTION(Name) INTERCEPT_SANITIZER_WEAK_FUNCTION(Name)
#include "sanitizer_common_interface.inc"
-#pragma section(".WEAK$A", read) // NOLINT
-#pragma section(".WEAK$Z", read) // NOLINT
+#pragma section(".WEAK$A", read)
+#pragma section(".WEAK$Z", read)
typedef void (*InterceptCB)();
extern "C" {
@@ -77,7 +78,7 @@
return 0;
}
-#pragma section(".CRT$XIB", long, read) // NOLINT
+#pragma section(".CRT$XIB", long, read)
__declspec(allocate(".CRT$XIB")) int (*__weak_intercept_preinit)() =
weak_intercept_init;
@@ -86,7 +87,7 @@
if (reason == /*DLL_PROCESS_ATTACH=*/1) weak_intercept_init();
}
-#pragma section(".CRT$XLAB", long, read) // NOLINT
+#pragma section(".CRT$XLAB", long, read)
__declspec(allocate(".CRT$XLAB")) void(WINAPI *__weak_intercept_tls_init)(
void *, unsigned long, void *) = weak_intercept_thread_init;
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/scripts/check_lint.sh b/src/llvm-project/compiler-rt/lib/sanitizer_common/scripts/check_lint.sh
index ec07138..4a2feba 100755
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/scripts/check_lint.sh
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/scripts/check_lint.sh
@@ -2,9 +2,8 @@
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
-# Guess path to LLVM_CHECKOUT if not provided
-if [ "${LLVM_CHECKOUT}" = "" ]; then
- LLVM_CHECKOUT="${SCRIPT_DIR}/../../../../../"
+if [ "${COMPILER_RT}" = "" ]; then
+ COMPILER_RT=$(readlink -f $SCRIPT_DIR/../../..)
fi
# python tools setup
@@ -18,20 +17,29 @@
# Filters
# TODO: remove some of these filters
COMMON_LINT_FILTER=-build/include,-build/header_guard,-legal/copyright,-whitespace/comments,-readability/casting,\
--build/namespaces,-readability/braces
-ASAN_RTL_LINT_FILTER=${COMMON_LINT_FILTER},-runtime/int
-ASAN_TEST_LINT_FILTER=${COMMON_LINT_FILTER},-runtime/sizeof,-runtime/int,-runtime/printf,-runtime/threadsafe_fn
-ASAN_LIT_TEST_LINT_FILTER=${ASAN_TEST_LINT_FILTER},-whitespace/line_length
-TSAN_RTL_LINT_FILTER=${COMMON_LINT_FILTER}
-TSAN_TEST_LINT_FILTER=${TSAN_RTL_LINT_FILTER},-runtime/threadsafe_fn,-runtime/int
-TSAN_LIT_TEST_LINT_FILTER=${TSAN_TEST_LINT_FILTER},-whitespace/line_length
+-build/namespaces,-build/c++11,-runtime/int
+
+COMMON_LIT_TEST_LINT_FILTER=-whitespace/indent,-whitespace/line_length,-runtime/arrays
+
+ASAN_RTL_LINT_FILTER=${COMMON_LINT_FILTER}
+ASAN_TEST_LINT_FILTER=${COMMON_LINT_FILTER},-runtime/printf,-runtime/threadsafe_fn
+ASAN_LIT_TEST_LINT_FILTER=${ASAN_TEST_LINT_FILTER},${COMMON_LIT_TEST_LINT_FILTER}
+
+TSAN_RTL_LINT_FILTER=${COMMON_LINT_FILTER},-readability/braces
+TSAN_TEST_LINT_FILTER=${TSAN_RTL_LINT_FILTER},-runtime/threadsafe_fn
+TSAN_LIT_TEST_LINT_FILTER=${TSAN_TEST_LINT_FILTER},${COMMON_LIT_TEST_LINT_FILTER}
+
MSAN_RTL_LINT_FILTER=${COMMON_LINT_FILTER}
+
LSAN_RTL_LINT_FILTER=${COMMON_LINT_FILTER}
-LSAN_LIT_TEST_LINT_FILTER=${LSAN_RTL_LINT_FILTER},-whitespace/line_length
-DFSAN_RTL_LINT_FILTER=${COMMON_LINT_FILTER},-runtime/int,-runtime/printf,-runtime/references,-readability/function
+LSAN_LIT_TEST_LINT_FILTER=${LSAN_RTL_LINT_FILTER},${COMMON_LIT_TEST_LINT_FILTER}
+
+DFSAN_RTL_LINT_FILTER=${COMMON_LINT_FILTER}
SCUDO_RTL_LINT_FILTER=${COMMON_LINT_FILTER}
-COMMON_RTL_INC_LINT_FILTER=${COMMON_LINT_FILTER},-runtime/int,-runtime/sizeof,-runtime/printf,-readability/fn_size
-SANITIZER_INCLUDES_LINT_FILTER=${COMMON_LINT_FILTER},-runtime/int
+
+COMMON_RTL_INC_LINT_FILTER=${COMMON_LINT_FILTER}
+
+SANITIZER_INCLUDES_LINT_FILTER=${COMMON_LINT_FILTER}
MKTEMP_DIR=$(mktemp -qd /tmp/check_lint.XXXXXXXXXX)
MKTEMP="mktemp -q ${MKTEMP_DIR}/tmp.XXXXXXXXXX"
@@ -40,8 +48,6 @@
}
trap cleanup EXIT
-cd ${LLVM_CHECKOUT}
-
EXITSTATUS=0
ERROR_LOG=$(${MKTEMP})
@@ -49,7 +55,7 @@
FILTER=$1
shift
TASK_LOG=$(${MKTEMP})
- ${CPPLINT} --filter=${FILTER} "$@" 2>$TASK_LOG
+ ${CPPLINT} --filter=${FILTER} "$@" > $TASK_LOG 2>&1
if [ "$?" != "0" ]; then
cat $TASK_LOG | grep -v "Done processing" | grep -v "Total errors found" \
| grep -v "Skipping input" >> $ERROR_LOG
@@ -60,56 +66,55 @@
${LITLINT} "$@" 2>>$ERROR_LOG
}
-if [ "${COMPILER_RT}" = "" ]; then
- COMPILER_RT=projects/compiler-rt
-fi
LIT_TESTS=${COMPILER_RT}/test
# Headers
SANITIZER_INCLUDES=${COMPILER_RT}/include/sanitizer
-run_lint ${SANITIZER_INCLUDES_LINT_FILTER} ${SANITIZER_INCLUDES}/*.h &
+FUZZER_INCLUDES=${COMPILER_RT}/include/fuzzer
+run_lint ${SANITIZER_INCLUDES_LINT_FILTER} ${SANITIZER_INCLUDES}/*.h \
+ ${FUZZER_INCLUDES}/*.h &
# Sanitizer_common
COMMON_RTL=${COMPILER_RT}/lib/sanitizer_common
-run_lint ${COMMON_RTL_INC_LINT_FILTER} ${COMMON_RTL}/*.cc \
+run_lint ${COMMON_RTL_INC_LINT_FILTER} ${COMMON_RTL}/*.cpp \
${COMMON_RTL}/*.h \
- ${COMMON_RTL}/tests/*.cc &
+ ${COMMON_RTL}/tests/*.cpp &
# Interception
INTERCEPTION=${COMPILER_RT}/lib/interception
-run_lint ${ASAN_RTL_LINT_FILTER} ${INTERCEPTION}/*.cc \
+run_lint ${ASAN_RTL_LINT_FILTER} ${INTERCEPTION}/*.cpp \
${INTERCEPTION}/*.h &
# ASan
ASAN_RTL=${COMPILER_RT}/lib/asan
-run_lint ${ASAN_RTL_LINT_FILTER} ${ASAN_RTL}/*.cc \
+run_lint ${ASAN_RTL_LINT_FILTER} ${ASAN_RTL}/*.cpp \
${ASAN_RTL}/*.h &
-run_lint ${ASAN_TEST_LINT_FILTER} ${ASAN_RTL}/tests/*.cc \
+run_lint ${ASAN_TEST_LINT_FILTER} ${ASAN_RTL}/tests/*.cpp \
${ASAN_RTL}/tests/*.h &
-run_lint ${ASAN_LIT_TEST_LINT_FILTER} ${LIT_TESTS}/asan/*/*.cc &
+run_lint ${ASAN_LIT_TEST_LINT_FILTER} ${LIT_TESTS}/asan/*/*.cpp &
# TSan
TSAN_RTL=${COMPILER_RT}/lib/tsan
-run_lint ${TSAN_RTL_LINT_FILTER} ${TSAN_RTL}/rtl/*.cc \
+run_lint ${TSAN_RTL_LINT_FILTER} ${TSAN_RTL}/rtl/*.cpp \
${TSAN_RTL}/rtl/*.h &
-run_lint ${TSAN_TEST_LINT_FILTER} ${TSAN_RTL}/tests/rtl/*.cc \
+run_lint ${TSAN_TEST_LINT_FILTER} ${TSAN_RTL}/tests/rtl/*.cpp \
${TSAN_RTL}/tests/rtl/*.h \
- ${TSAN_RTL}/tests/unit/*.cc &
-run_lint ${TSAN_LIT_TEST_LINT_FILTER} ${LIT_TESTS}/tsan/*.cc &
+ ${TSAN_RTL}/tests/unit/*.cpp &
+run_lint ${TSAN_LIT_TEST_LINT_FILTER} ${LIT_TESTS}/tsan/*.cpp &
# MSan
MSAN_RTL=${COMPILER_RT}/lib/msan
-run_lint ${MSAN_RTL_LINT_FILTER} ${MSAN_RTL}/*.cc \
+run_lint ${MSAN_RTL_LINT_FILTER} ${MSAN_RTL}/*.cpp \
${MSAN_RTL}/*.h &
# LSan
LSAN_RTL=${COMPILER_RT}/lib/lsan
-run_lint ${LSAN_RTL_LINT_FILTER} ${LSAN_RTL}/*.cc \
+run_lint ${LSAN_RTL_LINT_FILTER} ${LSAN_RTL}/*.cpp \
${LSAN_RTL}/*.h &
-run_lint ${LSAN_LIT_TEST_LINT_FILTER} ${LIT_TESTS}/lsan/*/*.cc &
+run_lint ${LSAN_LIT_TEST_LINT_FILTER} ${LIT_TESTS}/lsan/*/*.cpp &
# DFSan
DFSAN_RTL=${COMPILER_RT}/lib/dfsan
-run_lint ${DFSAN_RTL_LINT_FILTER} ${DFSAN_RTL}/*.cc \
+run_lint ${DFSAN_RTL_LINT_FILTER} ${DFSAN_RTL}/*.cpp \
${DFSAN_RTL}/*.h &
${DFSAN_RTL}/scripts/check_custom_wrappers.sh >> $ERROR_LOG
@@ -119,21 +124,15 @@
${SCUDO_RTL}/*.h &
# Misc files
-FILES=${COMMON_RTL}/*.inc
-TMPFILES=""
-for FILE in $FILES; do
- TMPFILE="$(${MKTEMP}).$(basename ${FILE}).cc"
- cp -f $FILE $TMPFILE
- run_lint ${COMMON_RTL_INC_LINT_FILTER} $TMPFILE &
- TMPFILES="$TMPFILES $TMPFILE"
-done
+(
+rsync -a --prune-empty-dirs --exclude='*/profile/*' --exclude='*/builtins/*' --exclude='*/xray/*' --include='*/' --include='*.inc' --exclude='*' "${COMPILER_RT}/" "${MKTEMP_DIR}/"
+find ${MKTEMP_DIR} -type f -name '*.inc' -exec mv {} {}.cpp \;
+( ERROR_LOG=${ERROR_LOG}.inc run_lint ${COMMON_RTL_INC_LINT_FILTER} $(find ${MKTEMP_DIR} -type f -name '*.inc.cpp') )
+sed "s|${MKTEMP_DIR}|${COMPILER_RT}|g" ${ERROR_LOG}.inc | sed "s|.inc.cpp|.inc|g" >> ${ERROR_LOG}
+) &
wait
-for temp in $TMPFILES; do
- rm -f $temp
-done
-
if [ -s $ERROR_LOG ]; then
cat $ERROR_LOG
exit 1
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/scripts/cpplint.py b/src/llvm-project/compiler-rt/lib/sanitizer_common/scripts/cpplint.py
index d45c47f..65baa6c 100755
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/scripts/cpplint.py
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/scripts/cpplint.py
@@ -28,40 +28,6 @@
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-# Here are some issues that I've had people identify in my code during reviews,
-# that I think are possible to flag automatically in a lint tool. If these were
-# caught by lint, it would save time both for myself and that of my reviewers.
-# Most likely, some of these are beyond the scope of the current lint framework,
-# but I think it is valuable to retain these wish-list items even if they cannot
-# be immediately implemented.
-#
-# Suggestions
-# -----------
-# - Check for no 'explicit' for multi-arg ctor
-# - Check for boolean assign RHS in parens
-# - Check for ctor initializer-list colon position and spacing
-# - Check that if there's a ctor, there should be a dtor
-# - Check accessors that return non-pointer member variables are
-# declared const
-# - Check accessors that return non-const pointer member vars are
-# *not* declared const
-# - Check for using public includes for testing
-# - Check for spaces between brackets in one-line inline method
-# - Check for no assert()
-# - Check for spaces surrounding operators
-# - Check for 0 in pointer context (should be NULL)
-# - Check for 0 in char context (should be '\0')
-# - Check for camel-case method name conventions for methods
-# that are not simple inline getters and setters
-# - Do not indent namespace contents
-# - Avoid inlining non-trivial constructors in header files
-# - Check for old-school (void) cast for call-sites of functions
-# ignored return value
-# - Check gUnit usage of anonymous namespace
-# - Check for class declaration order (typedefs, consts, enums,
-# ctor(s?), dtor, friend declarations, methods, member vars)
-#
-
"""Does google-lint on c++ files.
The goal of this script is to identify places in the code that *may*
@@ -85,15 +51,23 @@
import string
import sys
import unicodedata
+import sysconfig
+
+try:
+ xrange # Python 2
+except NameError:
+ xrange = range # Python 3
_USAGE = """
Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...]
- [--counting=total|toplevel|detailed]
+ [--counting=total|toplevel|detailed] [--root=subdir]
+ [--linelength=digits] [--headers=x,y,...]
+ [--quiet]
<file> [file] ...
The style guidelines this tries to follow are those in
- http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
+ https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
Every problem is given a confidence score from 1-5, with 5 meaning we are
certain of the problem, and 1 meaning it could be a legitimate construct.
@@ -104,7 +78,8 @@
suppresses errors of all categories on that line.
The files passed in will be linted; at least one file must be provided.
- Linted extensions are .cc, .cpp, and .h. Other file types will be ignored.
+ Default linted extensions are .cc, .cpp, .cu, .cuh and .h. Change the
+ extensions with the --extensions flag.
Flags:
@@ -115,6 +90,9 @@
verbose=#
Specify a number 0-5 to restrict errors to certain verbosity levels.
+ quiet
+ Don't print anything if no errors are found.
+
filter=-x,+y,...
Specify a comma-separated list of category-filters to apply: only
error messages whose category names pass the filters will be printed.
@@ -146,132 +124,350 @@
ignored.
Examples:
- Assuing that src/.git exists, the header guard CPP variables for
- src/chrome/browser/ui/browser.h are:
+ Assuming that top/src/.git exists (and cwd=top/src), the header guard
+ CPP variables for top/src/chrome/browser/ui/browser.h are:
No flag => CHROME_BROWSER_UI_BROWSER_H_
--root=chrome => BROWSER_UI_BROWSER_H_
--root=chrome/browser => UI_BROWSER_H_
+ --root=.. => SRC_CHROME_BROWSER_UI_BROWSER_H_
+
+ linelength=digits
+ This is the allowed line length for the project. The default value is
+ 80 characters.
+
+ Examples:
+ --linelength=120
+
+ extensions=extension,extension,...
+ The allowed file extensions that cpplint will check
+
+ Examples:
+ --extensions=hpp,cpp
+
+ headers=x,y,...
+ The header extensions that cpplint will treat as .h in checks. Values are
+ automatically added to --extensions list.
+
+ Examples:
+ --headers=hpp,hxx
+ --headers=hpp
+
+ cpplint.py supports per-directory configurations specified in CPPLINT.cfg
+ files. CPPLINT.cfg file can contain a number of key=value pairs.
+ Currently the following options are supported:
+
+ set noparent
+ filter=+filter1,-filter2,...
+ exclude_files=regex
+ linelength=80
+ root=subdir
+ headers=x,y,...
+
+ "set noparent" option prevents cpplint from traversing directory tree
+ upwards looking for more .cfg files in parent directories. This option
+ is usually placed in the top-level project directory.
+
+ The "filter" option is similar in function to --filter flag. It specifies
+ message filters in addition to the |_DEFAULT_FILTERS| and those specified
+ through --filter command-line flag.
+
+ "exclude_files" allows to specify a regular expression to be matched against
+ a file name. If the expression matches, the file is skipped and not run
+ through liner.
+
+ "linelength" allows to specify the allowed line length for the project.
+
+ The "root" option is similar in function to the --root flag (see example
+ above). Paths are relative to the directory of the CPPLINT.cfg.
+
+ The "headers" option is similar in function to the --headers flag
+ (see example above).
+
+ CPPLINT.cfg has an effect on files in the same directory and all
+ sub-directories, unless overridden by a nested configuration file.
+
+ Example file:
+ filter=-build/include_order,+build/include_alpha
+ exclude_files=.*\.cc
+
+ The above example disables build/include_order warning and enables
+ build/include_alpha as well as excludes all .cc from being
+ processed by linter, in the current directory (where the .cfg
+ file is located) and all sub-directories.
"""
# We categorize each error message we print. Here are the categories.
# We want an explicit list so we can list them all in cpplint --filter=.
# If you add a new error message with a new category, add it to the list
# here! cpplint_unittest.py should tell you if you forget to do this.
-# \ used for clearer layout -- pylint: disable-msg=C6013
_ERROR_CATEGORIES = [
- 'build/class',
- 'build/deprecated',
- 'build/endif_comment',
- 'build/explicit_make_pair',
- 'build/forward_decl',
- 'build/header_guard',
- 'build/include',
- 'build/include_alpha',
- 'build/include_order',
- 'build/include_what_you_use',
- 'build/namespaces',
- 'build/printf_format',
- 'build/storage_class',
- 'legal/copyright',
- 'readability/alt_tokens',
- 'readability/braces',
- 'readability/casting',
- 'readability/check',
- 'readability/constructors',
- 'readability/fn_size',
- 'readability/function',
- 'readability/multiline_comment',
- 'readability/multiline_string',
- 'readability/namespace',
- 'readability/nolint',
- 'readability/streams',
- 'readability/todo',
- 'readability/utf8',
- 'runtime/arrays',
- 'runtime/casting',
- 'runtime/explicit',
- 'runtime/int',
- 'runtime/init',
- 'runtime/invalid_increment',
- 'runtime/member_string_references',
- 'runtime/memset',
- 'runtime/operator',
- 'runtime/printf',
- 'runtime/printf_format',
- 'runtime/references',
- 'runtime/rtti',
- 'runtime/sizeof',
- 'runtime/string',
- 'runtime/threadsafe_fn',
- 'whitespace/blank_line',
- 'whitespace/braces',
- 'whitespace/comma',
- 'whitespace/comments',
- 'whitespace/empty_loop_body',
- 'whitespace/end_of_line',
- 'whitespace/ending_newline',
- 'whitespace/forcolon',
- 'whitespace/indent',
- 'whitespace/labels',
- 'whitespace/line_length',
- 'whitespace/newline',
- 'whitespace/operators',
- 'whitespace/parens',
- 'whitespace/semicolon',
- 'whitespace/tab',
- 'whitespace/todo'
- ]
+ 'build/class',
+ 'build/c++11',
+ 'build/c++14',
+ 'build/c++tr1',
+ 'build/deprecated',
+ 'build/endif_comment',
+ 'build/explicit_make_pair',
+ 'build/forward_decl',
+ 'build/header_guard',
+ 'build/include',
+ 'build/include_alpha',
+ 'build/include_order',
+ 'build/include_what_you_use',
+ 'build/namespaces',
+ 'build/printf_format',
+ 'build/storage_class',
+ 'legal/copyright',
+ 'readability/alt_tokens',
+ 'readability/braces',
+ 'readability/casting',
+ 'readability/check',
+ 'readability/constructors',
+ 'readability/fn_size',
+ 'readability/inheritance',
+ 'readability/multiline_comment',
+ 'readability/multiline_string',
+ 'readability/namespace',
+ 'readability/nolint',
+ 'readability/nul',
+ 'readability/strings',
+ 'readability/todo',
+ 'readability/utf8',
+ 'runtime/arrays',
+ 'runtime/casting',
+ 'runtime/explicit',
+ 'runtime/int',
+ 'runtime/init',
+ 'runtime/invalid_increment',
+ 'runtime/member_string_references',
+ 'runtime/memset',
+ 'runtime/indentation_namespace',
+ 'runtime/operator',
+ 'runtime/printf',
+ 'runtime/printf_format',
+ 'runtime/references',
+ 'runtime/string',
+ 'runtime/threadsafe_fn',
+ 'runtime/vlog',
+ 'whitespace/blank_line',
+ 'whitespace/braces',
+ 'whitespace/comma',
+ 'whitespace/comments',
+ 'whitespace/empty_conditional_body',
+ 'whitespace/empty_if_body',
+ 'whitespace/empty_loop_body',
+ 'whitespace/end_of_line',
+ 'whitespace/ending_newline',
+ 'whitespace/forcolon',
+ 'whitespace/indent',
+ 'whitespace/line_length',
+ 'whitespace/newline',
+ 'whitespace/operators',
+ 'whitespace/parens',
+ 'whitespace/semicolon',
+ 'whitespace/tab',
+ 'whitespace/todo',
+ ]
-# The default state of the category filter. This is overrided by the --filter=
+# These error categories are no longer enforced by cpplint, but for backwards-
+# compatibility they may still appear in NOLINT comments.
+_LEGACY_ERROR_CATEGORIES = [
+ 'readability/streams',
+ 'readability/function',
+ ]
+
+# The default state of the category filter. This is overridden by the --filter=
# flag. By default all errors are on, so only add here categories that should be
# off by default (i.e., categories that must be enabled by the --filter= flags).
# All entries here should start with a '-' or '+', as in the --filter= flag.
_DEFAULT_FILTERS = ['-build/include_alpha']
+# The default list of categories suppressed for C (not C++) files.
+_DEFAULT_C_SUPPRESSED_CATEGORIES = [
+ 'readability/casting',
+ ]
+
+# The default list of categories suppressed for Linux Kernel files.
+_DEFAULT_KERNEL_SUPPRESSED_CATEGORIES = [
+ 'whitespace/tab',
+ ]
+
# We used to check for high-bit characters, but after much discussion we
# decided those were OK, as long as they were in UTF-8 and didn't represent
# hard-coded international strings, which belong in a separate i18n file.
-# Headers that we consider STL headers.
-_STL_HEADERS = frozenset([
- 'algobase.h', 'algorithm', 'alloc.h', 'bitset', 'deque', 'exception',
- 'function.h', 'functional', 'hash_map', 'hash_map.h', 'hash_set',
- 'hash_set.h', 'iterator', 'list', 'list.h', 'map', 'memory', 'new',
- 'pair.h', 'pthread_alloc', 'queue', 'set', 'set.h', 'sstream', 'stack',
- 'stl_alloc.h', 'stl_relops.h', 'type_traits.h',
- 'utility', 'vector', 'vector.h',
- ])
-
-
-# Non-STL C++ system headers.
+# C++ headers
_CPP_HEADERS = frozenset([
- 'algo.h', 'builtinbuf.h', 'bvector.h', 'cassert', 'cctype',
- 'cerrno', 'cfloat', 'ciso646', 'climits', 'clocale', 'cmath',
- 'complex', 'complex.h', 'csetjmp', 'csignal', 'cstdarg', 'cstddef',
- 'cstdio', 'cstdlib', 'cstring', 'ctime', 'cwchar', 'cwctype',
- 'defalloc.h', 'deque.h', 'editbuf.h', 'exception', 'fstream',
- 'fstream.h', 'hashtable.h', 'heap.h', 'indstream.h', 'iomanip',
- 'iomanip.h', 'ios', 'iosfwd', 'iostream', 'iostream.h', 'istream',
- 'istream.h', 'iterator.h', 'limits', 'map.h', 'multimap.h', 'multiset.h',
- 'numeric', 'ostream', 'ostream.h', 'parsestream.h', 'pfstream.h',
- 'PlotFile.h', 'procbuf.h', 'pthread_alloc.h', 'rope', 'rope.h',
- 'ropeimpl.h', 'SFile.h', 'slist', 'slist.h', 'stack.h', 'stdexcept',
- 'stdiostream.h', 'streambuf', 'streambuf.h', 'stream.h', 'strfile.h',
- 'string', 'strstream', 'strstream.h', 'tempbuf.h', 'tree.h', 'typeinfo',
+ # Legacy
+ 'algobase.h',
+ 'algo.h',
+ 'alloc.h',
+ 'builtinbuf.h',
+ 'bvector.h',
+ 'complex.h',
+ 'defalloc.h',
+ 'deque.h',
+ 'editbuf.h',
+ 'fstream.h',
+ 'function.h',
+ 'hash_map',
+ 'hash_map.h',
+ 'hash_set',
+ 'hash_set.h',
+ 'hashtable.h',
+ 'heap.h',
+ 'indstream.h',
+ 'iomanip.h',
+ 'iostream.h',
+ 'istream.h',
+ 'iterator.h',
+ 'list.h',
+ 'map.h',
+ 'multimap.h',
+ 'multiset.h',
+ 'ostream.h',
+ 'pair.h',
+ 'parsestream.h',
+ 'pfstream.h',
+ 'procbuf.h',
+ 'pthread_alloc',
+ 'pthread_alloc.h',
+ 'rope',
+ 'rope.h',
+ 'ropeimpl.h',
+ 'set.h',
+ 'slist',
+ 'slist.h',
+ 'stack.h',
+ 'stdiostream.h',
+ 'stl_alloc.h',
+ 'stl_relops.h',
+ 'streambuf.h',
+ 'stream.h',
+ 'strfile.h',
+ 'strstream.h',
+ 'tempbuf.h',
+ 'tree.h',
+ 'type_traits.h',
+ 'vector.h',
+ # 17.6.1.2 C++ library headers
+ 'algorithm',
+ 'array',
+ 'atomic',
+ 'bitset',
+ 'chrono',
+ 'codecvt',
+ 'complex',
+ 'condition_variable',
+ 'deque',
+ 'exception',
+ 'forward_list',
+ 'fstream',
+ 'functional',
+ 'future',
+ 'initializer_list',
+ 'iomanip',
+ 'ios',
+ 'iosfwd',
+ 'iostream',
+ 'istream',
+ 'iterator',
+ 'limits',
+ 'list',
+ 'locale',
+ 'map',
+ 'memory',
+ 'mutex',
+ 'new',
+ 'numeric',
+ 'ostream',
+ 'queue',
+ 'random',
+ 'ratio',
+ 'regex',
+ 'scoped_allocator',
+ 'set',
+ 'sstream',
+ 'stack',
+ 'stdexcept',
+ 'streambuf',
+ 'string',
+ 'strstream',
+ 'system_error',
+ 'thread',
+ 'tuple',
+ 'typeindex',
+ 'typeinfo',
+ 'type_traits',
+ 'unordered_map',
+ 'unordered_set',
+ 'utility',
'valarray',
+ 'vector',
+ # 17.6.1.2 C++ headers for C library facilities
+ 'cassert',
+ 'ccomplex',
+ 'cctype',
+ 'cerrno',
+ 'cfenv',
+ 'cfloat',
+ 'cinttypes',
+ 'ciso646',
+ 'climits',
+ 'clocale',
+ 'cmath',
+ 'csetjmp',
+ 'csignal',
+ 'cstdalign',
+ 'cstdarg',
+ 'cstdbool',
+ 'cstddef',
+ 'cstdint',
+ 'cstdio',
+ 'cstdlib',
+ 'cstring',
+ 'ctgmath',
+ 'ctime',
+ 'cuchar',
+ 'cwchar',
+ 'cwctype',
])
+# Type names
+_TYPES = re.compile(
+ r'^(?:'
+ # [dcl.type.simple]
+ r'(char(16_t|32_t)?)|wchar_t|'
+ r'bool|short|int|long|signed|unsigned|float|double|'
+ # [support.types]
+ r'(ptrdiff_t|size_t|max_align_t|nullptr_t)|'
+ # [cstdint.syn]
+ r'(u?int(_fast|_least)?(8|16|32|64)_t)|'
+ r'(u?int(max|ptr)_t)|'
+ r')$')
+
+
+# These headers are excluded from [build/include] and [build/include_order]
+# checks:
+# - Anything not following google file name conventions (containing an
+# uppercase character, such as Python.h or nsStringAPI.h, for example).
+# - Lua headers.
+_THIRD_PARTY_HEADERS_PATTERN = re.compile(
+ r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$')
+
+# Pattern for matching FileInfo.BaseName() against test file name
+_TEST_FILE_SUFFIX = r'(_test|_unittest|_regtest)$'
+
+# Pattern that matches only complete whitespace, possibly across multiple lines.
+_EMPTY_CONDITIONAL_BODY_PATTERN = re.compile(r'^\s*$', re.DOTALL)
# Assertion macros. These are defined in base/logging.h and
-# testing/base/gunit.h. Note that the _M versions need to come first
-# for substring matching to work.
+# testing/base/public/gunit.h.
_CHECK_MACROS = [
'DCHECK', 'CHECK',
- 'EXPECT_TRUE_M', 'EXPECT_TRUE',
- 'ASSERT_TRUE_M', 'ASSERT_TRUE',
- 'EXPECT_FALSE_M', 'EXPECT_FALSE',
- 'ASSERT_FALSE_M', 'ASSERT_FALSE',
+ 'EXPECT_TRUE', 'ASSERT_TRUE',
+ 'EXPECT_FALSE', 'ASSERT_FALSE',
]
# Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
@@ -284,16 +480,12 @@
_CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
_CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement
_CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement
- _CHECK_REPLACEMENT['EXPECT_TRUE_M'][op] = 'EXPECT_%s_M' % replacement
- _CHECK_REPLACEMENT['ASSERT_TRUE_M'][op] = 'ASSERT_%s_M' % replacement
for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),
('>=', 'LT'), ('>', 'LE'),
('<=', 'GT'), ('<', 'GE')]:
_CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement
_CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement
- _CHECK_REPLACEMENT['EXPECT_FALSE_M'][op] = 'EXPECT_%s_M' % inv_replacement
- _CHECK_REPLACEMENT['ASSERT_FALSE_M'][op] = 'ASSERT_%s_M' % inv_replacement
# Alternative tokens and their replacements. For full list, see section 2.5
# Alternative tokens [lex.digraph] in the C++ standard.
@@ -317,9 +509,8 @@
# Compile regular expression that matches all the above keywords. The "[ =()]"
# bit is meant to avoid matching these keywords outside of boolean expressions.
#
-# False positives include C-style multi-line comments (http://go/nsiut )
-# and multi-line strings (http://go/beujw ), but those have always been
-# troublesome for cpplint.
+# False positives include C-style multi-line comments and multi-line strings
+# but those have always been troublesome for cpplint.
_ALT_TOKEN_REPLACEMENT_PATTERN = re.compile(
r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)')
@@ -343,12 +534,15 @@
r'(?:\s+(volatile|__volatile__))?'
r'\s*[{(]')
+# Match strings that indicate we're working on a C (not C++) file.
+_SEARCH_C_FILE = re.compile(r'\b(?:LINT_C_FILE|'
+ r'vim?:\s*.*(\s*|:)filetype=c(\s*|:|$))')
+
+# Match string that indicates we're working on a Linux Kernel file.
+_SEARCH_KERNEL_FILE = re.compile(r'\b(?:LINT_KERNEL_FILE)')
_regexp_compile_cache = {}
-# Finds occurrences of NOLINT or NOLINT(...).
-_RE_SUPPRESSION = re.compile(r'\bNOLINT\b(\([^)]*\))?')
-
# {str, set(int)}: a map from error categories to sets of linenumbers
# on which those errors are expected and should be suppressed.
_error_suppressions = {}
@@ -356,9 +550,38 @@
# The root directory used for deriving header guard CPP variable.
# This is set by --root flag.
_root = None
+_root_debug = False
+
+# The allowed line length of files.
+# This is set by --linelength flag.
+_line_length = 80
+
+# The allowed extensions for file names
+# This is set by --extensions flag.
+_valid_extensions = set(['cc', 'h', 'cpp', 'cu', 'cuh'])
+
+# Treat all headers starting with 'h' equally: .h, .hpp, .hxx etc.
+# This is set by --headers flag.
+_hpp_headers = set(['h'])
+
+# {str, bool}: a map from error categories to booleans which indicate if the
+# category should be suppressed for every line.
+_global_error_suppressions = {}
+
+def ProcessHppHeadersOption(val):
+ global _hpp_headers
+ try:
+ _hpp_headers = set(val.split(','))
+ # Automatically append to extensions list so it does not have to be set 2 times
+ _valid_extensions.update(_hpp_headers)
+ except ValueError:
+ PrintUsage('Header extensions must be comma separated list.')
+
+def IsHeaderExtension(file_extension):
+ return file_extension in _hpp_headers
def ParseNolintSuppressions(filename, raw_line, linenum, error):
- """Updates the global list of error-suppressions.
+ """Updates the global list of line error-suppressions.
Parses any NOLINT comments on the current line, updating the global
error_suppressions store. Reports an error if the NOLINT comment
@@ -370,64 +593,113 @@
linenum: int, the number of the current line.
error: function, an error handler.
"""
- # FIXME(adonovan): "NOLINT(" is misparsed as NOLINT(*).
- matched = _RE_SUPPRESSION.search(raw_line)
+ matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line)
if matched:
- category = matched.group(1)
+ if matched.group(1):
+ suppressed_line = linenum + 1
+ else:
+ suppressed_line = linenum
+ category = matched.group(2)
if category in (None, '(*)'): # => "suppress all"
- _error_suppressions.setdefault(None, set()).add(linenum)
+ _error_suppressions.setdefault(None, set()).add(suppressed_line)
else:
if category.startswith('(') and category.endswith(')'):
category = category[1:-1]
if category in _ERROR_CATEGORIES:
- _error_suppressions.setdefault(category, set()).add(linenum)
- else:
+ _error_suppressions.setdefault(category, set()).add(suppressed_line)
+ elif category not in _LEGACY_ERROR_CATEGORIES:
error(filename, linenum, 'readability/nolint', 5,
'Unknown NOLINT error category: %s' % category)
+def ProcessGlobalSuppresions(lines):
+ """Updates the list of global error suppressions.
+
+ Parses any lint directives in the file that have global effect.
+
+ Args:
+ lines: An array of strings, each representing a line of the file, with the
+ last element being empty if the file is terminated with a newline.
+ """
+ for line in lines:
+ if _SEARCH_C_FILE.search(line):
+ for category in _DEFAULT_C_SUPPRESSED_CATEGORIES:
+ _global_error_suppressions[category] = True
+ if _SEARCH_KERNEL_FILE.search(line):
+ for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES:
+ _global_error_suppressions[category] = True
+
+
def ResetNolintSuppressions():
- "Resets the set of NOLINT suppressions to empty."
+ """Resets the set of NOLINT suppressions to empty."""
_error_suppressions.clear()
+ _global_error_suppressions.clear()
def IsErrorSuppressedByNolint(category, linenum):
"""Returns true if the specified error category is suppressed on this line.
Consults the global error_suppressions map populated by
- ParseNolintSuppressions/ResetNolintSuppressions.
+ ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.
Args:
category: str, the category of the error.
linenum: int, the current line number.
Returns:
- bool, True iff the error should be suppressed due to a NOLINT comment.
+ bool, True iff the error should be suppressed due to a NOLINT comment or
+ global suppression.
"""
- return (linenum in _error_suppressions.get(category, set()) or
+ return (_global_error_suppressions.get(category, False) or
+ linenum in _error_suppressions.get(category, set()) or
linenum in _error_suppressions.get(None, set()))
+
def Match(pattern, s):
"""Matches the string with the pattern, caching the compiled regexp."""
# The regexp compilation caching is inlined in both Match and Search for
# performance reasons; factoring it out into a separate function turns out
# to be noticeably expensive.
- if not pattern in _regexp_compile_cache:
+ if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].match(s)
+def ReplaceAll(pattern, rep, s):
+ """Replaces instances of pattern in a string with a replacement.
+
+ The compiled regex is kept in a cache shared by Match and Search.
+
+ Args:
+ pattern: regex pattern
+ rep: replacement text
+ s: search string
+
+ Returns:
+ string with replacements made (or original string if no replacements)
+ """
+ if pattern not in _regexp_compile_cache:
+ _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
+ return _regexp_compile_cache[pattern].sub(rep, s)
+
+
def Search(pattern, s):
"""Searches the string for the pattern, caching the compiled regexp."""
- if not pattern in _regexp_compile_cache:
+ if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].search(s)
-class _IncludeState(dict):
+def _IsSourceExtension(s):
+ """File extension (excluding dot) matches a source file extension."""
+ return s in ('c', 'cc', 'cpp', 'cxx')
+
+
+class _IncludeState(object):
"""Tracks line numbers for includes, and the order in which includes appear.
- As a dict, an _IncludeState object serves as a mapping between include
- filename and line number on which that file was included.
+ include_list contains list of lists of (header, line number) pairs.
+ It's a lists of lists rather than just one flat list to make it
+ easier to update across preprocessor boundaries.
Call CheckNextIncludeOrder() once for each header in the file, passing
in the type constants defined above. Calls in an illegal order will
@@ -458,12 +730,45 @@
}
def __init__(self):
- dict.__init__(self)
+ self.include_list = [[]]
+ self.ResetSection('')
+
+ def FindHeader(self, header):
+ """Check if a header has already been included.
+
+ Args:
+ header: header to check.
+ Returns:
+ Line number of previous occurrence, or -1 if the header has not
+ been seen before.
+ """
+ for section_list in self.include_list:
+ for f in section_list:
+ if f[0] == header:
+ return f[1]
+ return -1
+
+ def ResetSection(self, directive):
+ """Reset section checking for preprocessor directive.
+
+ Args:
+ directive: preprocessor directive (e.g. "if", "else").
+ """
# The name of the current section.
self._section = self._INITIAL_SECTION
# The path of last found header.
self._last_header = ''
+ # Update list of includes. Note that we never pop from the
+ # include list.
+ if directive in ('if', 'ifdef', 'ifndef'):
+ self.include_list.append([])
+ elif directive in ('else', 'elif'):
+ self.include_list[-1] = []
+
+ def SetLastHeader(self, header_path):
+ self._last_header = header_path
+
def CanonicalizeAlphabeticalOrder(self, header_path):
"""Returns a path canonicalized for alphabetical comparison.
@@ -479,19 +784,25 @@
"""
return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
- def IsInAlphabeticalOrder(self, header_path):
+ def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):
"""Check if a header is in alphabetical order with the previous header.
Args:
- header_path: Header to be checked.
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: The number of the line to check.
+ header_path: Canonicalized header to be checked.
Returns:
Returns true if the header is in alphabetical order.
"""
- canonical_header = self.CanonicalizeAlphabeticalOrder(header_path)
- if self._last_header > canonical_header:
+ # If previous section is different from current section, _last_header will
+ # be reset to empty string, so it's always less than current header.
+ #
+ # If previous line was a blank line, assume that the headers are
+ # intentionally sorted the way they are.
+ if (self._last_header > header_path and
+ Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])):
return False
- self._last_header = canonical_header
return True
def CheckNextIncludeOrder(self, header_type):
@@ -556,8 +867,11 @@
self.error_count = 0 # global count of reported errors
# filters to apply when emitting error messages
self.filters = _DEFAULT_FILTERS[:]
+ # backup of filter list. Used to restore the state after each file.
+ self._filters_backup = self.filters[:]
self.counting = 'total' # In what way are we counting errors?
self.errors_by_category = {} # string to int dict storing error counts
+ self.quiet = False # Suppress non-error messagess?
# output format:
# "emacs" - format that emacs can parse (default)
@@ -568,6 +882,12 @@
"""Sets the output format for errors."""
self.output_format = output_format
+ def SetQuiet(self, quiet):
+ """Sets the module's quiet settings, and returns the previous setting."""
+ last_quiet = self.quiet
+ self.quiet = quiet
+ return last_quiet
+
def SetVerboseLevel(self, level):
"""Sets the module's verbosity, and returns the previous setting."""
last_verbose_level = self.verbose_level
@@ -594,6 +914,10 @@
"""
# Default filters always have less priority than the flag ones.
self.filters = _DEFAULT_FILTERS[:]
+ self.AddFilters(filters)
+
+ def AddFilters(self, filters):
+ """ Adds more filters to the existing list of error-message filters. """
for filt in filters.split(','):
clean_filt = filt.strip()
if clean_filt:
@@ -603,6 +927,14 @@
raise ValueError('Every filter in --filters must start with + or -'
' (%s does not)' % filt)
+ def BackupFilters(self):
+ """ Saves the current filter list to backup storage."""
+ self._filters_backup = self.filters[:]
+
+ def RestoreFilters(self):
+ """ Restores filters previously backed up."""
+ self.filters = self._filters_backup[:]
+
def ResetErrorCounts(self):
"""Sets the module's error statistic back to zero."""
self.error_count = 0
@@ -623,7 +955,7 @@
for category, count in self.errors_by_category.iteritems():
sys.stderr.write('Category \'%s\' errors found: %d\n' %
(category, count))
- sys.stderr.write('Total errors found: %d\n' % self.error_count)
+ sys.stdout.write('Total errors found: %d\n' % self.error_count)
_cpplint_state = _CppLintState()
@@ -637,6 +969,14 @@
"""Sets the module's output format."""
_cpplint_state.SetOutputFormat(output_format)
+def _Quiet():
+ """Return's the module's quiet setting."""
+ return _cpplint_state.quiet
+
+def _SetQuiet(quiet):
+ """Set the module's quiet status, and return previous setting."""
+ return _cpplint_state.SetQuiet(quiet)
+
def _VerboseLevel():
"""Returns the module's verbosity setting."""
@@ -670,6 +1010,25 @@
"""
_cpplint_state.SetFilters(filters)
+def _AddFilters(filters):
+ """Adds more filter overrides.
+
+ Unlike _SetFilters, this function does not reset the current list of filters
+ available.
+
+ Args:
+ filters: A string of comma-separated filters (eg "whitespace/indent").
+ Each filter should start with + or -; else we die.
+ """
+ _cpplint_state.AddFilters(filters)
+
+def _BackupFilters():
+ """ Saves the current filter list to backup storage."""
+ _cpplint_state.BackupFilters()
+
+def _RestoreFilters():
+ """ Restores filters previously backed up."""
+ _cpplint_state.RestoreFilters()
class _FunctionState(object):
"""Tracks current function name and the number of lines in its body."""
@@ -705,6 +1064,9 @@
filename: The name of the current file.
linenum: The number of the line to check.
"""
+ if not self.in_a_function:
+ return
+
if Match(r'T(EST|est)', self.current_function):
base_trigger = self._TEST_TRIGGER
else:
@@ -732,7 +1094,7 @@
pass
-class FileInfo:
+class FileInfo(object):
"""Provides utility functions for filenames.
FileInfo provides easy access to the components of a file's path
@@ -775,12 +1137,13 @@
# Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by
# searching up from the current path.
- root_dir = os.path.dirname(fullname)
- while (root_dir != os.path.dirname(root_dir) and
- not os.path.exists(os.path.join(root_dir, ".git")) and
- not os.path.exists(os.path.join(root_dir, ".hg")) and
- not os.path.exists(os.path.join(root_dir, ".svn"))):
- root_dir = os.path.dirname(root_dir)
+ root_dir = current_dir = os.path.dirname(fullname)
+ while current_dir != os.path.dirname(current_dir):
+ if (os.path.exists(os.path.join(current_dir, ".git")) or
+ os.path.exists(os.path.join(current_dir, ".hg")) or
+ os.path.exists(os.path.join(current_dir, ".svn"))):
+ root_dir = current_dir
+ current_dir = os.path.dirname(current_dir)
if (os.path.exists(os.path.join(root_dir, ".git")) or
os.path.exists(os.path.join(root_dir, ".hg")) or
@@ -819,7 +1182,7 @@
def IsSource(self):
"""File has a source file extension."""
- return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx')
+ return _IsSourceExtension(self.Extension()[1:])
def _ShouldPrintError(category, confidence, linenum):
@@ -830,6 +1193,7 @@
# the verbosity level isn't high enough, or the filters filter it out.
if IsErrorSuppressedByNolint(category, linenum):
return False
+
if confidence < _cpplint_state.verbose_level:
return False
@@ -874,8 +1238,8 @@
if _ShouldPrintError(category, confidence, linenum):
_cpplint_state.IncrementErrorCount(category)
if _cpplint_state.output_format == 'vs7':
- sys.stderr.write('%s(%s): %s [%s] [%d]\n' % (
- filename, linenum, message, category, confidence))
+ sys.stderr.write('%s(%s): error cpplint: [%s] %s [%d]\n' % (
+ filename, linenum, category, message, confidence))
elif _cpplint_state.output_format == 'eclipse':
sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence))
@@ -884,14 +1248,12 @@
filename, linenum, message, category, confidence))
-# Matches standard C++ escape esequences per 2.13.2.3 of the C++ standard.
+# Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard.
_RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(
r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
-# Matches strings. Escape codes should already be removed by ESCAPES.
-_RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES = re.compile(r'"[^"]*"')
-# Matches characters. Escape codes should already be removed by ESCAPES.
-_RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES = re.compile(r"'.'")
-# Matches multi-line C++ comments.
+# Match a single C style comment on the same line.
+_RE_PATTERN_C_COMMENTS = r'/\*(?:[^*]|\*(?!/))*\*/'
+# Matches multi-line C style comments.
# This RE is a little bit more complicated than one might expect, because we
# have to take care of space removals tools so we can handle comments inside
# statements better.
@@ -900,10 +1262,10 @@
# if this doesn't work we try on left side but only if there's a non-character
# on the right.
_RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
- r"""(\s*/\*.*\*/\s*$|
- /\*.*\*/\s+|
- \s+/\*.*\*/(?=\W)|
- /\*.*\*/)""", re.VERBOSE)
+ r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' +
+ _RE_PATTERN_C_COMMENTS + r'\s+|' +
+ r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' +
+ _RE_PATTERN_C_COMMENTS + r')')
def IsCppString(line):
@@ -923,6 +1285,82 @@
return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
+def CleanseRawStrings(raw_lines):
+ """Removes C++11 raw strings from lines.
+
+ Before:
+ static const char kData[] = R"(
+ multi-line string
+ )";
+
+ After:
+ static const char kData[] = ""
+ (replaced by blank line)
+ "";
+
+ Args:
+ raw_lines: list of raw lines.
+
+ Returns:
+ list of lines with C++11 raw strings replaced by empty strings.
+ """
+
+ delimiter = None
+ lines_without_raw_strings = []
+ for line in raw_lines:
+ if delimiter:
+ # Inside a raw string, look for the end
+ end = line.find(delimiter)
+ if end >= 0:
+ # Found the end of the string, match leading space for this
+ # line and resume copying the original lines, and also insert
+ # a "" on the last line.
+ leading_space = Match(r'^(\s*)\S', line)
+ line = leading_space.group(1) + '""' + line[end + len(delimiter):]
+ delimiter = None
+ else:
+ # Haven't found the end yet, append a blank line.
+ line = '""'
+
+ # Look for beginning of a raw string, and replace them with
+ # empty strings. This is done in a loop to handle multiple raw
+ # strings on the same line.
+ while delimiter is None:
+ # Look for beginning of a raw string.
+ # See 2.14.15 [lex.string] for syntax.
+ #
+ # Once we have matched a raw string, we check the prefix of the
+ # line to make sure that the line is not part of a single line
+ # comment. It's done this way because we remove raw strings
+ # before removing comments as opposed to removing comments
+ # before removing raw strings. This is because there are some
+ # cpplint checks that requires the comments to be preserved, but
+ # we don't want to check comments that are inside raw strings.
+ matched = Match(r'^(.*?)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
+ if (matched and
+ not Match(r'^([^\'"]|\'(\\.|[^\'])*\'|"(\\.|[^"])*")*//',
+ matched.group(1))):
+ delimiter = ')' + matched.group(2) + '"'
+
+ end = matched.group(3).find(delimiter)
+ if end >= 0:
+ # Raw string ended on same line
+ line = (matched.group(1) + '""' +
+ matched.group(3)[end + len(delimiter):])
+ delimiter = None
+ else:
+ # Start of a multi-line raw string
+ line = matched.group(1) + '""'
+ else:
+ break
+
+ lines_without_raw_strings.append(line)
+
+ # TODO(unknown): if delimiter is not None here, we might want to
+ # emit a warning for unterminated string.
+ return lines_without_raw_strings
+
+
def FindNextMultiLineCommentStart(lines, lineix):
"""Find the beginning marker for a multiline comment."""
while lineix < len(lines):
@@ -948,7 +1386,7 @@
# Having // dummy comments makes the lines non-empty, so we will not get
# unnecessary blank line warnings later in the code.
for i in range(begin, end):
- lines[i] = '// dummy'
+ lines[i] = '/**/'
def RemoveMultiLineComments(filename, lines, error):
@@ -984,12 +1422,14 @@
class CleansedLines(object):
- """Holds 3 copies of all lines with different preprocessing applied to them.
+ """Holds 4 copies of all lines with different preprocessing applied to them.
- 1) elided member contains lines without strings and comments,
- 2) lines member contains lines without comments, and
+ 1) elided member contains lines without strings and comments.
+ 2) lines member contains lines without comments.
3) raw_lines member contains all the lines without processing.
- All these three members are of <type 'list'>, and of the same length.
+ 4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw
+ strings removed.
+ All these members are of <type 'list'>, and of the same length.
"""
def __init__(self, lines):
@@ -997,9 +1437,11 @@
self.lines = []
self.raw_lines = lines
self.num_lines = len(lines)
- for linenum in range(len(lines)):
- self.lines.append(CleanseComments(lines[linenum]))
- elided = self._CollapseStrings(lines[linenum])
+ self.lines_without_raw_strings = CleanseRawStrings(lines)
+ for linenum in range(len(self.lines_without_raw_strings)):
+ self.lines.append(CleanseComments(
+ self.lines_without_raw_strings[linenum]))
+ elided = self._CollapseStrings(self.lines_without_raw_strings[linenum])
self.elided.append(CleanseComments(elided))
def NumLines(self):
@@ -1018,45 +1460,151 @@
Returns:
The line with collapsed strings.
"""
- if not _RE_PATTERN_INCLUDE.match(elided):
- # Remove escaped characters first to make quote/single quote collapsing
- # basic. Things that look like escaped characters shouldn't occur
- # outside of strings and chars.
- elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
- elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided)
- elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided)
- return elided
+ if _RE_PATTERN_INCLUDE.match(elided):
+ return elided
+
+ # Remove escaped characters first to make quote/single quote collapsing
+ # basic. Things that look like escaped characters shouldn't occur
+ # outside of strings and chars.
+ elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
+
+ # Replace quoted strings and digit separators. Both single quotes
+ # and double quotes are processed in the same loop, otherwise
+ # nested quotes wouldn't work.
+ collapsed = ''
+ while True:
+ # Find the first quote character
+ match = Match(r'^([^\'"]*)([\'"])(.*)$', elided)
+ if not match:
+ collapsed += elided
+ break
+ head, quote, tail = match.groups()
+
+ if quote == '"':
+ # Collapse double quoted strings
+ second_quote = tail.find('"')
+ if second_quote >= 0:
+ collapsed += head + '""'
+ elided = tail[second_quote + 1:]
+ else:
+ # Unmatched double quote, don't bother processing the rest
+ # of the line since this is probably a multiline string.
+ collapsed += elided
+ break
+ else:
+ # Found single quote, check nearby text to eliminate digit separators.
+ #
+ # There is no special handling for floating point here, because
+ # the integer/fractional/exponent parts would all be parsed
+ # correctly as long as there are digits on both sides of the
+ # separator. So we are fine as long as we don't see something
+ # like "0.'3" (gcc 4.9.0 will not allow this literal).
+ if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):
+ match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail)
+ collapsed += head + match_literal.group(1).replace("'", '')
+ elided = match_literal.group(2)
+ else:
+ second_quote = tail.find('\'')
+ if second_quote >= 0:
+ collapsed += head + "''"
+ elided = tail[second_quote + 1:]
+ else:
+ # Unmatched single quote
+ collapsed += elided
+ break
+
+ return collapsed
-def FindEndOfExpressionInLine(line, startpos, depth, startchar, endchar):
- """Find the position just after the matching endchar.
+def FindEndOfExpressionInLine(line, startpos, stack):
+ """Find the position just after the end of current parenthesized expression.
Args:
line: a CleansedLines line.
startpos: start searching at this position.
- depth: nesting level at startpos.
- startchar: expression opening character.
- endchar: expression closing character.
+ stack: nesting stack at startpos.
Returns:
- Index just after endchar.
+ On finding matching end: (index just after matching end, None)
+ On finding an unclosed expression: (-1, None)
+ Otherwise: (-1, new stack at end of this line)
"""
for i in xrange(startpos, len(line)):
- if line[i] == startchar:
- depth += 1
- elif line[i] == endchar:
- depth -= 1
- if depth == 0:
- return i + 1
- return -1
+ char = line[i]
+ if char in '([{':
+ # Found start of parenthesized expression, push to expression stack
+ stack.append(char)
+ elif char == '<':
+ # Found potential start of template argument list
+ if i > 0 and line[i - 1] == '<':
+ # Left shift operator
+ if stack and stack[-1] == '<':
+ stack.pop()
+ if not stack:
+ return (-1, None)
+ elif i > 0 and Search(r'\boperator\s*$', line[0:i]):
+ # operator<, don't add to stack
+ continue
+ else:
+ # Tentative start of template argument list
+ stack.append('<')
+ elif char in ')]}':
+ # Found end of parenthesized expression.
+ #
+ # If we are currently expecting a matching '>', the pending '<'
+ # must have been an operator. Remove them from expression stack.
+ while stack and stack[-1] == '<':
+ stack.pop()
+ if not stack:
+ return (-1, None)
+ if ((stack[-1] == '(' and char == ')') or
+ (stack[-1] == '[' and char == ']') or
+ (stack[-1] == '{' and char == '}')):
+ stack.pop()
+ if not stack:
+ return (i + 1, None)
+ else:
+ # Mismatched parentheses
+ return (-1, None)
+ elif char == '>':
+ # Found potential end of template argument list.
+
+ # Ignore "->" and operator functions
+ if (i > 0 and
+ (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))):
+ continue
+
+ # Pop the stack if there is a matching '<'. Otherwise, ignore
+ # this '>' since it must be an operator.
+ if stack:
+ if stack[-1] == '<':
+ stack.pop()
+ if not stack:
+ return (i + 1, None)
+ elif char == ';':
+ # Found something that look like end of statements. If we are currently
+ # expecting a '>', the matching '<' must have been an operator, since
+ # template argument list should not contain statements.
+ while stack and stack[-1] == '<':
+ stack.pop()
+ if not stack:
+ return (-1, None)
+
+ # Did not find end of expression or unbalanced parentheses on this line
+ return (-1, stack)
def CloseExpression(clean_lines, linenum, pos):
- """If input points to ( or { or [, finds the position that closes it.
+ """If input points to ( or { or [ or <, finds the position that closes it.
- If lines[linenum][pos] points to a '(' or '{' or '[', finds the
+ If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
linenum/pos that correspond to the closing of the expression.
+ TODO(unknown): cpplint spends a fair bit of time matching parentheses.
+ Ideally we would want to index all opening and closing parentheses once
+ and have CloseExpression be just a simple lookup, but due to preprocessor
+ tricks, this is not so easy.
+
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
@@ -1070,31 +1618,141 @@
"""
line = clean_lines.elided[linenum]
- startchar = line[pos]
- if startchar not in '({[':
+ if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]):
return (line, clean_lines.NumLines(), -1)
- if startchar == '(': endchar = ')'
- if startchar == '[': endchar = ']'
- if startchar == '{': endchar = '}'
# Check first line
- end_pos = FindEndOfExpressionInLine(line, pos, 0, startchar, endchar)
+ (end_pos, stack) = FindEndOfExpressionInLine(line, pos, [])
if end_pos > -1:
return (line, linenum, end_pos)
- tail = line[pos:]
- num_open = tail.count(startchar) - tail.count(endchar)
- while linenum < clean_lines.NumLines() - 1:
+
+ # Continue scanning forward
+ while stack and linenum < clean_lines.NumLines() - 1:
linenum += 1
line = clean_lines.elided[linenum]
- delta = line.count(startchar) - line.count(endchar)
- if num_open + delta <= 0:
- return (line, linenum,
- FindEndOfExpressionInLine(line, 0, num_open, startchar, endchar))
- num_open += delta
+ (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack)
+ if end_pos > -1:
+ return (line, linenum, end_pos)
- # Did not find endchar before end of file, give up
+ # Did not find end of expression before end of file, give up
return (line, clean_lines.NumLines(), -1)
+
+def FindStartOfExpressionInLine(line, endpos, stack):
+ """Find position at the matching start of current expression.
+
+ This is almost the reverse of FindEndOfExpressionInLine, but note
+ that the input position and returned position differs by 1.
+
+ Args:
+ line: a CleansedLines line.
+ endpos: start searching at this position.
+ stack: nesting stack at endpos.
+
+ Returns:
+ On finding matching start: (index at matching start, None)
+ On finding an unclosed expression: (-1, None)
+ Otherwise: (-1, new stack at beginning of this line)
+ """
+ i = endpos
+ while i >= 0:
+ char = line[i]
+ if char in ')]}':
+ # Found end of expression, push to expression stack
+ stack.append(char)
+ elif char == '>':
+ # Found potential end of template argument list.
+ #
+ # Ignore it if it's a "->" or ">=" or "operator>"
+ if (i > 0 and
+ (line[i - 1] == '-' or
+ Match(r'\s>=\s', line[i - 1:]) or
+ Search(r'\boperator\s*$', line[0:i]))):
+ i -= 1
+ else:
+ stack.append('>')
+ elif char == '<':
+ # Found potential start of template argument list
+ if i > 0 and line[i - 1] == '<':
+ # Left shift operator
+ i -= 1
+ else:
+ # If there is a matching '>', we can pop the expression stack.
+ # Otherwise, ignore this '<' since it must be an operator.
+ if stack and stack[-1] == '>':
+ stack.pop()
+ if not stack:
+ return (i, None)
+ elif char in '([{':
+ # Found start of expression.
+ #
+ # If there are any unmatched '>' on the stack, they must be
+ # operators. Remove those.
+ while stack and stack[-1] == '>':
+ stack.pop()
+ if not stack:
+ return (-1, None)
+ if ((char == '(' and stack[-1] == ')') or
+ (char == '[' and stack[-1] == ']') or
+ (char == '{' and stack[-1] == '}')):
+ stack.pop()
+ if not stack:
+ return (i, None)
+ else:
+ # Mismatched parentheses
+ return (-1, None)
+ elif char == ';':
+ # Found something that look like end of statements. If we are currently
+ # expecting a '<', the matching '>' must have been an operator, since
+ # template argument list should not contain statements.
+ while stack and stack[-1] == '>':
+ stack.pop()
+ if not stack:
+ return (-1, None)
+
+ i -= 1
+
+ return (-1, stack)
+
+
+def ReverseCloseExpression(clean_lines, linenum, pos):
+ """If input points to ) or } or ] or >, finds the position that opens it.
+
+ If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
+ linenum/pos that correspond to the opening of the expression.
+
+ Args:
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: The number of the line to check.
+ pos: A position on the line.
+
+ Returns:
+ A tuple (line, linenum, pos) pointer *at* the opening brace, or
+ (line, 0, -1) if we never find the matching opening brace. Note
+ we ignore strings and comments when matching; and the line we
+ return is the 'cleansed' line at linenum.
+ """
+ line = clean_lines.elided[linenum]
+ if line[pos] not in ')}]>':
+ return (line, 0, -1)
+
+ # Check last line
+ (start_pos, stack) = FindStartOfExpressionInLine(line, pos, [])
+ if start_pos > -1:
+ return (line, linenum, start_pos)
+
+ # Continue scanning backward
+ while stack and linenum > 0:
+ linenum -= 1
+ line = clean_lines.elided[linenum]
+ (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)
+ if start_pos > -1:
+ return (line, linenum, start_pos)
+
+ # Did not find start of expression before beginning of file, give up
+ return (line, 0, -1)
+
+
def CheckForCopyright(filename, lines, error):
"""Logs an error if no Copyright message appears at the top of the file."""
@@ -1108,6 +1766,46 @@
'You should have a line: "Copyright [year] <Copyright Owner>"')
+def GetIndentLevel(line):
+ """Return the number of leading spaces in line.
+
+ Args:
+ line: A string to check.
+
+ Returns:
+ An integer count of leading spaces, possibly zero.
+ """
+ indent = Match(r'^( *)\S', line)
+ if indent:
+ return len(indent.group(1))
+ else:
+ return 0
+
+def PathSplitToList(path):
+ """Returns the path split into a list by the separator.
+
+ Args:
+ path: An absolute or relative path (e.g. '/a/b/c/' or '../a')
+
+ Returns:
+ A list of path components (e.g. ['a', 'b', 'c]).
+ """
+ lst = []
+ while True:
+ (head, tail) = os.path.split(path)
+ if head == path: # absolute paths end
+ lst.append(head)
+ break
+ if tail == path: # relative paths end
+ lst.append(tail)
+ break
+
+ path = head
+ lst.append(tail)
+
+ lst.reverse()
+ return lst
+
def GetHeaderGuardCPPVariable(filename):
"""Returns the CPP variable that should be used as a header guard.
@@ -1124,15 +1822,67 @@
# flymake.
filename = re.sub(r'_flymake\.h$', '.h', filename)
filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
+ # Replace 'c++' with 'cpp'.
+ filename = filename.replace('C++', 'cpp').replace('c++', 'cpp')
fileinfo = FileInfo(filename)
file_path_from_root = fileinfo.RepositoryName()
- if _root:
- file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root)
- return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_'
+
+ def FixupPathFromRoot():
+ if _root_debug:
+ sys.stderr.write("\n_root fixup, _root = '%s', repository name = '%s'\n"
+ %(_root, fileinfo.RepositoryName()))
+
+ # Process the file path with the --root flag if it was set.
+ if not _root:
+ if _root_debug:
+ sys.stderr.write("_root unspecified\n")
+ return file_path_from_root
+
+ def StripListPrefix(lst, prefix):
+ # f(['x', 'y'], ['w, z']) -> None (not a valid prefix)
+ if lst[:len(prefix)] != prefix:
+ return None
+ # f(['a, 'b', 'c', 'd'], ['a', 'b']) -> ['c', 'd']
+ return lst[(len(prefix)):]
+
+ # root behavior:
+ # --root=subdir , lstrips subdir from the header guard
+ maybe_path = StripListPrefix(PathSplitToList(file_path_from_root),
+ PathSplitToList(_root))
+
+ if _root_debug:
+ sys.stderr.write(("_root lstrip (maybe_path=%s, file_path_from_root=%s," +
+ " _root=%s)\n") %(maybe_path, file_path_from_root, _root))
+
+ if maybe_path:
+ return os.path.join(*maybe_path)
+
+ # --root=.. , will prepend the outer directory to the header guard
+ full_path = fileinfo.FullName()
+ root_abspath = os.path.abspath(_root)
+
+ maybe_path = StripListPrefix(PathSplitToList(full_path),
+ PathSplitToList(root_abspath))
+
+ if _root_debug:
+ sys.stderr.write(("_root prepend (maybe_path=%s, full_path=%s, " +
+ "root_abspath=%s)\n") %(maybe_path, full_path, root_abspath))
+
+ if maybe_path:
+ return os.path.join(*maybe_path)
+
+ if _root_debug:
+ sys.stderr.write("_root ignore, returning %s\n" %(file_path_from_root))
+
+ # --root=FAKE_DIR is ignored
+ return file_path_from_root
+
+ file_path_from_root = FixupPathFromRoot()
+ return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'
-def CheckForHeaderGuard(filename, lines, error):
+def CheckForHeaderGuard(filename, clean_lines, error):
"""Checks that the file contains a header guard.
Logs an error if no #ifndef header guard is present. For other
@@ -1140,18 +1890,29 @@
Args:
filename: The name of the C++ header file.
- lines: An array of strings, each representing a line of the file.
+ clean_lines: A CleansedLines instance containing the file.
error: The function to call with any errors found.
"""
+ # Don't check for header guards if there are error suppression
+ # comments somewhere in this file.
+ #
+ # Because this is silencing a warning for a nonexistent line, we
+ # only support the very specific NOLINT(build/header_guard) syntax,
+ # and not the general NOLINT or NOLINT(*) syntax.
+ raw_lines = clean_lines.lines_without_raw_strings
+ for i in raw_lines:
+ if Search(r'//\s*NOLINT\(build/header_guard\)', i):
+ return
+
cppvar = GetHeaderGuardCPPVariable(filename)
- ifndef = None
+ ifndef = ''
ifndef_linenum = 0
- define = None
- endif = None
+ define = ''
+ endif = ''
endif_linenum = 0
- for linenum, line in enumerate(lines):
+ for linenum, line in enumerate(raw_lines):
linesplit = line.split()
if len(linesplit) >= 2:
# find the first occurrence of #ifndef and #define, save arg
@@ -1166,18 +1927,12 @@
endif = line
endif_linenum = linenum
- if not ifndef:
+ if not ifndef or not define or ifndef != define:
error(filename, 0, 'build/header_guard', 5,
'No #ifndef header guard found, suggested CPP variable is: %s' %
cppvar)
return
- if not define:
- error(filename, 0, 'build/header_guard', 5,
- 'No #define header guard found, suggested CPP variable is: %s' %
- cppvar)
- return
-
# The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
# for backward compatibility.
if ifndef != cppvar:
@@ -1185,35 +1940,82 @@
if ifndef != cppvar + '_':
error_level = 5
- ParseNolintSuppressions(filename, lines[ifndef_linenum], ifndef_linenum,
+ ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum,
error)
error(filename, ifndef_linenum, 'build/header_guard', error_level,
'#ifndef header guard has wrong style, please use: %s' % cppvar)
- if define != ifndef:
- error(filename, 0, 'build/header_guard', 5,
- '#ifndef and #define don\'t match, suggested CPP variable is: %s' %
- cppvar)
+ # Check for "//" comments on endif line.
+ ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum,
+ error)
+ match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif)
+ if match:
+ if match.group(1) == '_':
+ # Issue low severity warning for deprecated double trailing underscore
+ error(filename, endif_linenum, 'build/header_guard', 0,
+ '#endif line should be "#endif // %s"' % cppvar)
return
- if endif != ('#endif // %s' % cppvar):
- error_level = 0
- if endif != ('#endif // %s' % (cppvar + '_')):
- error_level = 5
+ # Didn't find the corresponding "//" comment. If this file does not
+ # contain any "//" comments at all, it could be that the compiler
+ # only wants "/**/" comments, look for those instead.
+ no_single_line_comments = True
+ for i in xrange(1, len(raw_lines) - 1):
+ line = raw_lines[i]
+ if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line):
+ no_single_line_comments = False
+ break
- ParseNolintSuppressions(filename, lines[endif_linenum], endif_linenum,
- error)
- error(filename, endif_linenum, 'build/header_guard', error_level,
- '#endif line should be "#endif // %s"' % cppvar)
+ if no_single_line_comments:
+ match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif)
+ if match:
+ if match.group(1) == '_':
+ # Low severity warning for double trailing underscore
+ error(filename, endif_linenum, 'build/header_guard', 0,
+ '#endif line should be "#endif /* %s */"' % cppvar)
+ return
+
+ # Didn't find anything
+ error(filename, endif_linenum, 'build/header_guard', 5,
+ '#endif line should be "#endif // %s"' % cppvar)
-def CheckForUnicodeReplacementCharacters(filename, lines, error):
- """Logs an error for each line containing Unicode replacement characters.
+def CheckHeaderFileIncluded(filename, include_state, error):
+ """Logs an error if a .cc file does not include its header."""
- These indicate that either the file contained invalid UTF-8 (likely)
- or Unicode replacement characters (which it shouldn't). Note that
- it's possible for this to throw off line numbering if the invalid
- UTF-8 occurred adjacent to a newline.
+ # Do not check test files
+ fileinfo = FileInfo(filename)
+ if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()):
+ return
+
+ headerfile = filename[0:len(filename) - len(fileinfo.Extension())] + '.h'
+ if not os.path.exists(headerfile):
+ return
+ headername = FileInfo(headerfile).RepositoryName()
+ first_include = 0
+ for section_list in include_state.include_list:
+ for f in section_list:
+ if headername in f[0] or f[0] in headername:
+ return
+ if not first_include:
+ first_include = f[1]
+
+ error(filename, first_include, 'build/include', 5,
+ '%s should include its header file %s' % (fileinfo.RepositoryName(),
+ headername))
+
+
+def CheckForBadCharacters(filename, lines, error):
+ """Logs an error for each line containing bad characters.
+
+ Two kinds of bad characters:
+
+ 1. Unicode replacement characters: These indicate that either the file
+ contained invalid UTF-8 (likely) or Unicode replacement characters (which
+ it shouldn't). Note that it's possible for this to throw off line
+ numbering if the invalid UTF-8 occurred adjacent to a newline.
+
+ 2. NUL bytes. These are problematic for some tools.
Args:
filename: The name of the current file.
@@ -1224,6 +2026,8 @@
if u'\ufffd' in line:
error(filename, linenum, 'readability/utf8', 5,
'Line contains invalid UTF-8 (or Unicode replacement character).')
+ if '\0' in line:
+ error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')
def CheckForNewlineAtEOF(filename, lines, error):
@@ -1278,24 +2082,37 @@
if (line.count('"') - line.count('\\"')) % 2:
error(filename, linenum, 'readability/multiline_string', 5,
'Multi-line string ("...") found. This lint script doesn\'t '
- 'do well with such strings, and may give bogus warnings. They\'re '
- 'ugly and unnecessary, and you should use concatenation instead".')
+ 'do well with such strings, and may give bogus warnings. '
+ 'Use C++11 raw strings or concatenation instead.')
-threading_list = (
- ('asctime(', 'asctime_r('),
- ('ctime(', 'ctime_r('),
- ('getgrgid(', 'getgrgid_r('),
- ('getgrnam(', 'getgrnam_r('),
- ('getlogin(', 'getlogin_r('),
- ('getpwnam(', 'getpwnam_r('),
- ('getpwuid(', 'getpwuid_r('),
- ('gmtime(', 'gmtime_r('),
- ('localtime(', 'localtime_r('),
- ('rand(', 'rand_r('),
- ('readdir(', 'readdir_r('),
- ('strtok(', 'strtok_r('),
- ('ttyname(', 'ttyname_r('),
+# (non-threadsafe name, thread-safe alternative, validation pattern)
+#
+# The validation pattern is used to eliminate false positives such as:
+# _rand(); // false positive due to substring match.
+# ->rand(); // some member function rand().
+# ACMRandom rand(seed); // some variable named rand.
+# ISAACRandom rand(); // another variable named rand.
+#
+# Basically we require the return value of these functions to be used
+# in some expression context on the same line by matching on some
+# operator before the function name. This eliminates constructors and
+# member function calls.
+_UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)'
+_THREADING_LIST = (
+ ('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'),
+ ('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'),
+ ('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'),
+ ('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'),
+ ('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'),
+ ('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'),
+ ('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'),
+ ('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'),
+ ('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'),
+ ('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'),
+ ('strtok(', 'strtok_r(',
+ _UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'),
+ ('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'),
)
@@ -1315,17 +2132,34 @@
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
- for single_thread_function, multithread_safe_function in threading_list:
- ix = line.find(single_thread_function)
- # Comparisons made explicit for clarity -- pylint: disable-msg=C6403
- if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and
- line[ix - 1] not in ('_', '.', '>'))):
+ for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST:
+ # Additional pattern matching check to confirm that this is the
+ # function we are looking for
+ if Search(pattern, line):
error(filename, linenum, 'runtime/threadsafe_fn', 2,
- 'Consider using ' + multithread_safe_function +
- '...) instead of ' + single_thread_function +
+ 'Consider using ' + multithread_safe_func +
+ '...) instead of ' + single_thread_func +
'...) for improved thread safety.')
+def CheckVlogArguments(filename, clean_lines, linenum, error):
+ """Checks that VLOG() is only used for defining a logging level.
+
+ For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
+ VLOG(FATAL) are not.
+
+ Args:
+ filename: The name of the current file.
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: The number of the line to check.
+ error: The function to call with any errors found.
+ """
+ line = clean_lines.elided[linenum]
+ if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line):
+ error(filename, linenum, 'runtime/vlog', 5,
+ 'VLOG() should be used with numeric verbosity level. '
+ 'Use LOG() if you want symbolic severity levels.')
+
# Matches invalid increment: *count++, which moves pointer instead of
# incrementing a value.
_RE_PATTERN_INVALID_INCREMENT = re.compile(
@@ -1354,13 +2188,29 @@
'Changing pointer instead of value (or unused value of operator*).')
+def IsMacroDefinition(clean_lines, linenum):
+ if Search(r'^#define', clean_lines[linenum]):
+ return True
+
+ if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]):
+ return True
+
+ return False
+
+
+def IsForwardClassDeclaration(clean_lines, linenum):
+ return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum])
+
+
class _BlockInfo(object):
"""Stores information about a generic block of code."""
- def __init__(self, seen_open_brace):
+ def __init__(self, linenum, seen_open_brace):
+ self.starting_linenum = linenum
self.seen_open_brace = seen_open_brace
self.open_parentheses = 0
self.inline_asm = _NO_ASM
+ self.check_namespace_indentation = False
def CheckBegin(self, filename, clean_lines, linenum, error):
"""Run checks that applies to text up to the opening brace.
@@ -1390,19 +2240,43 @@
"""
pass
+ def IsBlockInfo(self):
+ """Returns true if this block is a _BlockInfo.
+
+ This is convenient for verifying that an object is an instance of
+ a _BlockInfo, but not an instance of any of the derived classes.
+
+ Returns:
+ True for this class, False for derived classes.
+ """
+ return self.__class__ == _BlockInfo
+
+
+class _ExternCInfo(_BlockInfo):
+ """Stores information about an 'extern "C"' block."""
+
+ def __init__(self, linenum):
+ _BlockInfo.__init__(self, linenum, True)
+
class _ClassInfo(_BlockInfo):
"""Stores information about a class."""
def __init__(self, name, class_or_struct, clean_lines, linenum):
- _BlockInfo.__init__(self, False)
+ _BlockInfo.__init__(self, linenum, False)
self.name = name
- self.starting_linenum = linenum
self.is_derived = False
+ self.check_namespace_indentation = True
if class_or_struct == 'struct':
self.access = 'public'
+ self.is_struct = True
else:
self.access = 'private'
+ self.is_struct = False
+
+ # Remember initial indentation level for this class. Using raw_lines here
+ # instead of elided to account for leading comments.
+ self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum])
# Try to find the end of the class. This will be confused by things like:
# class A {
@@ -1423,14 +2297,44 @@
if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]):
self.is_derived = True
+ def CheckEnd(self, filename, clean_lines, linenum, error):
+ # If there is a DISALLOW macro, it should appear near the end of
+ # the class.
+ seen_last_thing_in_class = False
+ for i in xrange(linenum - 1, self.starting_linenum, -1):
+ match = Search(
+ r'\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\(' +
+ self.name + r'\)',
+ clean_lines.elided[i])
+ if match:
+ if seen_last_thing_in_class:
+ error(filename, i, 'readability/constructors', 3,
+ match.group(1) + ' should be the last thing in the class')
+ break
+
+ if not Match(r'^\s*$', clean_lines.elided[i]):
+ seen_last_thing_in_class = True
+
+ # Check that closing brace is aligned with beginning of the class.
+ # Only do this if the closing brace is indented by only whitespaces.
+ # This means we will not check single-line class definitions.
+ indent = Match(r'^( *)\}', clean_lines.elided[linenum])
+ if indent and len(indent.group(1)) != self.class_indent:
+ if self.is_struct:
+ parent = 'struct ' + self.name
+ else:
+ parent = 'class ' + self.name
+ error(filename, linenum, 'whitespace/indent', 3,
+ 'Closing brace should be aligned with beginning of %s' % parent)
+
class _NamespaceInfo(_BlockInfo):
"""Stores information about a namespace."""
def __init__(self, name, linenum):
- _BlockInfo.__init__(self, False)
+ _BlockInfo.__init__(self, linenum, False)
self.name = name or ''
- self.starting_linenum = linenum
+ self.check_namespace_indentation = True
def CheckEnd(self, filename, clean_lines, linenum, error):
"""Check end of namespace comments."""
@@ -1448,34 +2352,41 @@
# deciding what these nontrivial things are, so this check is
# triggered by namespace size only, which works most of the time.
if (linenum - self.starting_linenum < 10
- and not Match(r'};*\s*(//|/\*).*\bnamespace\b', line)):
+ and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)):
return
# Look for matching comment at end of namespace.
#
# Note that we accept C style "/* */" comments for terminating
# namespaces, so that code that terminate namespaces inside
- # preprocessor macros can be cpplint clean. Example: http://go/nxpiz
+ # preprocessor macros can be cpplint clean.
#
# We also accept stuff like "// end of namespace <name>." with the
# period at the end.
#
# Besides these, we don't accept anything else, otherwise we might
# get false negatives when existing comment is a substring of the
- # expected namespace. Example: http://go/ldkdc, http://cl/23548205
+ # expected namespace.
if self.name:
# Named namespace
- if not Match((r'};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) +
- r'[\*/\.\\\s]*$'),
+ if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' +
+ re.escape(self.name) + r'[\*/\.\\\s]*$'),
line):
error(filename, linenum, 'readability/namespace', 5,
'Namespace should be terminated with "// namespace %s"' %
self.name)
else:
# Anonymous namespace
- if not Match(r'};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
- error(filename, linenum, 'readability/namespace', 5,
- 'Namespace should be terminated with "// namespace"')
+ if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
+ # If "// namespace anonymous" or "// anonymous namespace (more text)",
+ # mention "// anonymous namespace" as an acceptable form
+ if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line):
+ error(filename, linenum, 'readability/namespace', 5,
+ 'Anonymous namespace should be terminated with "// namespace"'
+ ' or "// anonymous namespace"')
+ else:
+ error(filename, linenum, 'readability/namespace', 5,
+ 'Anonymous namespace should be terminated with "// namespace"')
class _PreprocessorInfo(object):
@@ -1492,7 +2403,7 @@
self.seen_else = False
-class _NestingState(object):
+class NestingState(object):
"""Holds states related to parsing braces."""
def __init__(self):
@@ -1504,6 +2415,17 @@
# - _BlockInfo: some other type of block.
self.stack = []
+ # Top of the previous stack before each Update().
+ #
+ # Because the nesting_stack is updated at the end of each line, we
+ # had to do some convoluted checks to find out what is the current
+ # scope at the beginning of the line. This check is simplified by
+ # saving the previous top of nesting stack.
+ #
+ # We could save the full stack, but we only need the top. Copying
+ # the full nesting stack would slow down cpplint by ~10%.
+ self.previous_stack_top = []
+
# Stack of _PreprocessorInfo objects.
self.pp_stack = []
@@ -1524,6 +2446,82 @@
"""
return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
+ def InExternC(self):
+ """Check if we are currently one level inside an 'extern "C"' block.
+
+ Returns:
+ True if top of the stack is an extern block, False otherwise.
+ """
+ return self.stack and isinstance(self.stack[-1], _ExternCInfo)
+
+ def InClassDeclaration(self):
+ """Check if we are currently one level inside a class or struct declaration.
+
+ Returns:
+ True if top of the stack is a class/struct, False otherwise.
+ """
+ return self.stack and isinstance(self.stack[-1], _ClassInfo)
+
+ def InAsmBlock(self):
+ """Check if we are currently one level inside an inline ASM block.
+
+ Returns:
+ True if the top of the stack is a block containing inline ASM.
+ """
+ return self.stack and self.stack[-1].inline_asm != _NO_ASM
+
+ def InTemplateArgumentList(self, clean_lines, linenum, pos):
+ """Check if current position is inside template argument list.
+
+ Args:
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: The number of the line to check.
+ pos: position just after the suspected template argument.
+ Returns:
+ True if (linenum, pos) is inside template arguments.
+ """
+ while linenum < clean_lines.NumLines():
+ # Find the earliest character that might indicate a template argument
+ line = clean_lines.elided[linenum]
+ match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:])
+ if not match:
+ linenum += 1
+ pos = 0
+ continue
+ token = match.group(1)
+ pos += len(match.group(0))
+
+ # These things do not look like template argument list:
+ # class Suspect {
+ # class Suspect x; }
+ if token in ('{', '}', ';'): return False
+
+ # These things look like template argument list:
+ # template <class Suspect>
+ # template <class Suspect = default_value>
+ # template <class Suspect[]>
+ # template <class Suspect...>
+ if token in ('>', '=', '[', ']', '.'): return True
+
+ # Check if token is an unmatched '<'.
+ # If not, move on to the next character.
+ if token != '<':
+ pos += 1
+ if pos >= len(line):
+ linenum += 1
+ pos = 0
+ continue
+
+ # We can't be sure if we just find a single '<', and need to
+ # find the matching '>'.
+ (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)
+ if end_pos < 0:
+ # Not sure if template argument list or syntax error in file
+ return False
+ linenum = end_line
+ pos = end_pos
+ return False
+
def UpdatePreprocessor(self, line):
"""Update preprocessor stack.
@@ -1533,7 +2531,6 @@
#else
struct ResultDetailsPageElementExtensionPoint : public Extension {
#endif
- (see http://go/qwddn for original example)
We make the following assumptions (good enough for most files):
- Preprocessor condition evaluates to true from #if up to first
@@ -1581,6 +2578,7 @@
# TODO(unknown): unexpected #endif, issue warning?
pass
+ # TODO(unknown): Update() is too long, but we will refactor later.
def Update(self, filename, clean_lines, linenum, error):
"""Update nesting state with current line.
@@ -1592,7 +2590,17 @@
"""
line = clean_lines.elided[linenum]
- # Update pp_stack first
+ # Remember top of the previous nesting stack.
+ #
+ # The stack is always pushed/popped and not modified in place, so
+ # we can just do a shallow copy instead of copy.deepcopy. Using
+ # deepcopy would slow down cpplint by ~28%.
+ if self.stack:
+ self.previous_stack_top = self.stack[-1]
+ else:
+ self.previous_stack_top = None
+
+ # Update pp_stack
self.UpdatePreprocessor(line)
# Count parentheses. This is to avoid adding struct arguments to
@@ -1643,32 +2651,27 @@
# such as in:
# class LOCKABLE API Object {
# };
- #
- # Templates with class arguments may confuse the parser, for example:
- # template <class T
- # class Comparator = less<T>,
- # class Vector = vector<T> >
- # class HeapQueue {
- #
- # Because this parser has no nesting state about templates, by the
- # time it saw "class Comparator", it may think that it's a new class.
- # Nested templates have a similar problem:
- # template <
- # typename ExportedType,
- # typename TupleType,
- # template <typename, typename> class ImplTemplate>
- #
- # To avoid these cases, we ignore classes that are followed by '=' or '>'
class_decl_match = Match(
- r'\s*(template\s*<[\w\s<>,:]*>\s*)?'
- '(class|struct)\s+([A-Z_]+\s+)*(\w+(?:::\w+)*)'
- '(([^=>]|<[^<>]*>)*)$', line)
+ r'^(\s*(?:template\s*<[\w\s<>,:]*>\s*)?'
+ r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))'
+ r'(.*)$', line)
if (class_decl_match and
(not self.stack or self.stack[-1].open_parentheses == 0)):
- self.stack.append(_ClassInfo(
- class_decl_match.group(4), class_decl_match.group(2),
- clean_lines, linenum))
- line = class_decl_match.group(5)
+ # We do not want to accept classes that are actually template arguments:
+ # template <class Ignore1,
+ # class Ignore2 = Default<Args>,
+ # template <Args> class Ignore3>
+ # void Function() {};
+ #
+ # To avoid template argument cases, we scan forward and look for
+ # an unmatched '>'. If we see one, assume we are inside a
+ # template argument list.
+ end_declaration = len(class_decl_match.group(1))
+ if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration):
+ self.stack.append(_ClassInfo(
+ class_decl_match.group(3), class_decl_match.group(2),
+ clean_lines, linenum))
+ line = class_decl_match.group(4)
# If we have not yet seen the opening brace for the innermost block,
# run checks here.
@@ -1677,9 +2680,29 @@
# Update access control if we are inside a class/struct
if self.stack and isinstance(self.stack[-1], _ClassInfo):
- access_match = Match(r'\s*(public|private|protected)\s*:', line)
+ classinfo = self.stack[-1]
+ access_match = Match(
+ r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?'
+ r':(?:[^:]|$)',
+ line)
if access_match:
- self.stack[-1].access = access_match.group(1)
+ classinfo.access = access_match.group(2)
+
+ # Check that access keywords are indented +1 space. Skip this
+ # check if the keywords are not preceded by whitespaces.
+ indent = access_match.group(1)
+ if (len(indent) != classinfo.class_indent + 1 and
+ Match(r'^\s*$', indent)):
+ if classinfo.is_struct:
+ parent = 'struct ' + classinfo.name
+ else:
+ parent = 'class ' + classinfo.name
+ slots = ''
+ if access_match.group(3):
+ slots = access_match.group(3)
+ error(filename, linenum, 'whitespace/indent', 3,
+ '%s%s: should be indented +1 space inside %s' % (
+ access_match.group(2), slots, parent))
# Consume braces or semicolons from what's left of the line
while True:
@@ -1695,10 +2718,13 @@
# stack otherwise.
if not self.SeenOpenBrace():
self.stack[-1].seen_open_brace = True
+ elif Match(r'^extern\s*"[^"]*"\s*\{', line):
+ self.stack.append(_ExternCInfo(linenum))
else:
- self.stack.append(_BlockInfo(True))
+ self.stack.append(_BlockInfo(linenum, True))
if _MATCH_ASM.match(line):
self.stack[-1].inline_asm = _BLOCK_ASM
+
elif token == ';' or token == ')':
# If we haven't seen an opening brace yet, but we already saw
# a semicolon, this is probably a forward declaration. Pop
@@ -1729,8 +2755,8 @@
return classinfo
return None
- def CheckClassFinished(self, filename, error):
- """Checks that all classes have been completely parsed.
+ def CheckCompletedBlocks(self, filename, error):
+ """Checks that all classes and namespaces have been completely parsed.
Call this when all lines in a file have been processed.
Args:
@@ -1745,11 +2771,15 @@
error(filename, obj.starting_linenum, 'build/class', 5,
'Failed to find complete declaration of class %s' %
obj.name)
+ elif isinstance(obj, _NamespaceInfo):
+ error(filename, obj.starting_linenum, 'build/namespaces', 5,
+ 'Failed to find complete declaration of namespace %s' %
+ obj.name)
def CheckForNonStandardConstructs(filename, clean_lines, linenum,
nesting_state, error):
- """Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
+ r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
@@ -1770,7 +2800,7 @@
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
- nesting_state: A _NestingState instance which maintains information about
+ nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
@@ -1803,7 +2833,8 @@
r'\s+(register|static|extern|typedef)\b',
line):
error(filename, linenum, 'build/storage_class', 5,
- 'Storage class (static, extern, typedef, etc) should be first.')
+ 'Storage-class specifier (static, extern, typedef, etc) should be '
+ 'at the beginning of the declaration.')
if Match(r'\s*#\s*endif\s*[^/\s]+', line):
error(filename, linenum, 'build/endif_comment', 5,
@@ -1843,26 +2874,79 @@
# Look for single-argument constructors that aren't marked explicit.
# Technically a valid construct, but against style.
- args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)'
- % re.escape(base_classname),
- line)
- if (args and
- args.group(1) != 'void' and
- not Match(r'(const\s+)?%s\s*(?:<\w+>\s*)?&' % re.escape(base_classname),
- args.group(1).strip())):
- error(filename, linenum, 'runtime/explicit', 5,
- 'Single-argument constructors should be marked explicit.')
+ explicit_constructor_match = Match(
+ r'\s+(?:(?:inline|constexpr)\s+)*(explicit\s+)?'
+ r'(?:(?:inline|constexpr)\s+)*%s\s*'
+ r'\(((?:[^()]|\([^()]*\))*)\)'
+ % re.escape(base_classname),
+ line)
+
+ if explicit_constructor_match:
+ is_marked_explicit = explicit_constructor_match.group(1)
+
+ if not explicit_constructor_match.group(2):
+ constructor_args = []
+ else:
+ constructor_args = explicit_constructor_match.group(2).split(',')
+
+ # collapse arguments so that commas in template parameter lists and function
+ # argument parameter lists don't split arguments in two
+ i = 0
+ while i < len(constructor_args):
+ constructor_arg = constructor_args[i]
+ while (constructor_arg.count('<') > constructor_arg.count('>') or
+ constructor_arg.count('(') > constructor_arg.count(')')):
+ constructor_arg += ',' + constructor_args[i + 1]
+ del constructor_args[i + 1]
+ constructor_args[i] = constructor_arg
+ i += 1
+
+ defaulted_args = [arg for arg in constructor_args if '=' in arg]
+ noarg_constructor = (not constructor_args or # empty arg list
+ # 'void' arg specifier
+ (len(constructor_args) == 1 and
+ constructor_args[0].strip() == 'void'))
+ onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg
+ not noarg_constructor) or
+ # all but at most one arg defaulted
+ (len(constructor_args) >= 1 and
+ not noarg_constructor and
+ len(defaulted_args) >= len(constructor_args) - 1))
+ initializer_list_constructor = bool(
+ onearg_constructor and
+ Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0]))
+ copy_constructor = bool(
+ onearg_constructor and
+ Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&'
+ % re.escape(base_classname), constructor_args[0].strip()))
+
+ if (not is_marked_explicit and
+ onearg_constructor and
+ not initializer_list_constructor and
+ not copy_constructor):
+ if defaulted_args:
+ error(filename, linenum, 'runtime/explicit', 5,
+ 'Constructors callable with one argument '
+ 'should be marked explicit.')
+ else:
+ error(filename, linenum, 'runtime/explicit', 5,
+ 'Single-parameter constructors should be marked explicit.')
+ elif is_marked_explicit and not onearg_constructor:
+ if noarg_constructor:
+ error(filename, linenum, 'runtime/explicit', 5,
+ 'Zero-parameter constructors should not be marked explicit.')
-def CheckSpacingForFunctionCall(filename, line, linenum, error):
+def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error):
"""Checks for the correctness of various spacing around function calls.
Args:
filename: The name of the current file.
- line: The text of the line to check.
+ clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
+ line = clean_lines.elided[linenum]
# Since function calls often occur inside if/for/while/switch
# expressions - which have their own, more liberal conventions - we
@@ -1892,7 +2976,8 @@
# Note that we assume the contents of [] to be short enough that
# they'll never need to wrap.
if ( # Ignore control structures.
- not Search(r'\b(if|for|while|switch|return|delete)\b', fncall) and
+ not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
+ fncall) and
# Ignore pointers/references to functions.
not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
# Ignore pointers/references to arrays.
@@ -1904,10 +2989,18 @@
error(filename, linenum, 'whitespace/parens', 2,
'Extra space after (')
if (Search(r'\w\s+\(', fncall) and
- not Search(r'#\s*define|typedef', fncall) and
- not Search(r'\w\s+\((\w+::)?\*\w+\)\(', fncall)):
- error(filename, linenum, 'whitespace/parens', 4,
- 'Extra space before ( in function call')
+ not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and
+ not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and
+ not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and
+ not Search(r'\bcase\s+\(', fncall)):
+ # TODO(unknown): Space after an operator function seem to be a common
+ # error, silence those for now by restricting them to highest verbosity.
+ if Search(r'\boperator_*\b', line):
+ error(filename, linenum, 'whitespace/parens', 0,
+ 'Extra space before ( in function call')
+ else:
+ error(filename, linenum, 'whitespace/parens', 4,
+ 'Extra space before ( in function call')
# If the ) is followed only by a newline or a { + newline, assume it's
# part of a control statement (if/while/etc), and don't complain
if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
@@ -1936,12 +3029,26 @@
return not line or line.isspace()
+def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
+ error):
+ is_namespace_indent_item = (
+ len(nesting_state.stack) > 1 and
+ nesting_state.stack[-1].check_namespace_indentation and
+ isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and
+ nesting_state.previous_stack_top == nesting_state.stack[-2])
+
+ if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
+ clean_lines.elided, line):
+ CheckItemIndentationInNamespace(filename, clean_lines.elided,
+ line, error)
+
+
def CheckForFunctionLengths(filename, clean_lines, linenum,
function_state, error):
"""Reports for long function bodies.
For an overview why this is done, see:
- http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
+ https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
Uses a simplistic algorithm assuming other style guidelines
(especially spacing) are followed.
@@ -1961,8 +3068,6 @@
"""
lines = clean_lines.lines
line = lines[linenum]
- raw = clean_lines.raw_lines
- raw_line = raw[linenum]
joined_line = ''
starting_func = False
@@ -2009,191 +3114,58 @@
_RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')
-def CheckComment(comment, filename, linenum, error):
- """Checks for common mistakes in TODO comments.
+def CheckComment(line, filename, linenum, next_line_start, error):
+ """Checks for common mistakes in comments.
Args:
- comment: The text of the comment from the line in question.
+ line: The line in question.
filename: The name of the current file.
linenum: The number of the line to check.
+ next_line_start: The first non-whitespace column of the next line.
error: The function to call with any errors found.
"""
- match = _RE_PATTERN_TODO.match(comment)
- if match:
- # One whitespace is correct; zero whitespace is handled elsewhere.
- leading_whitespace = match.group(1)
- if len(leading_whitespace) > 1:
- error(filename, linenum, 'whitespace/todo', 2,
- 'Too many spaces before TODO')
+ commentpos = line.find('//')
+ if commentpos != -1:
+ # Check if the // may be in quotes. If so, ignore it
+ if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0:
+ # Allow one space for new scopes, two spaces otherwise:
+ if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and
+ ((commentpos >= 1 and
+ line[commentpos-1] not in string.whitespace) or
+ (commentpos >= 2 and
+ line[commentpos-2] not in string.whitespace))):
+ error(filename, linenum, 'whitespace/comments', 2,
+ 'At least two spaces is best between code and comments')
- username = match.group(2)
- if not username:
- error(filename, linenum, 'readability/todo', 2,
- 'Missing username in TODO; it should look like '
- '"// TODO(my_username): Stuff."')
+ # Checks for common mistakes in TODO comments.
+ comment = line[commentpos:]
+ match = _RE_PATTERN_TODO.match(comment)
+ if match:
+ # One whitespace is correct; zero whitespace is handled elsewhere.
+ leading_whitespace = match.group(1)
+ if len(leading_whitespace) > 1:
+ error(filename, linenum, 'whitespace/todo', 2,
+ 'Too many spaces before TODO')
- middle_whitespace = match.group(3)
- # Comparisons made explicit for correctness -- pylint: disable-msg=C6403
- if middle_whitespace != ' ' and middle_whitespace != '':
- error(filename, linenum, 'whitespace/todo', 2,
- 'TODO(my_username) should be followed by a space')
+ username = match.group(2)
+ if not username:
+ error(filename, linenum, 'readability/todo', 2,
+ 'Missing username in TODO; it should look like '
+ '"// TODO(my_username): Stuff."')
-def CheckAccess(filename, clean_lines, linenum, nesting_state, error):
- """Checks for improper use of DISALLOW* macros.
+ middle_whitespace = match.group(3)
+ # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
+ if middle_whitespace != ' ' and middle_whitespace != '':
+ error(filename, linenum, 'whitespace/todo', 2,
+ 'TODO(my_username) should be followed by a space')
- Args:
- filename: The name of the current file.
- clean_lines: A CleansedLines instance containing the file.
- linenum: The number of the line to check.
- nesting_state: A _NestingState instance which maintains information about
- the current stack of nested blocks being parsed.
- error: The function to call with any errors found.
- """
- line = clean_lines.elided[linenum] # get rid of comments and strings
-
- matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|'
- r'DISALLOW_EVIL_CONSTRUCTORS|'
- r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line)
- if not matched:
- return
- if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo):
- if nesting_state.stack[-1].access != 'private':
- error(filename, linenum, 'readability/constructors', 3,
- '%s must be in the private: section' % matched.group(1))
-
- else:
- # Found DISALLOW* macro outside a class declaration, or perhaps it
- # was used inside a function when it should have been part of the
- # class declaration. We could issue a warning here, but it
- # probably resulted in a compiler error already.
- pass
-
-
-def FindNextMatchingAngleBracket(clean_lines, linenum, init_suffix):
- """Find the corresponding > to close a template.
-
- Args:
- clean_lines: A CleansedLines instance containing the file.
- linenum: Current line number.
- init_suffix: Remainder of the current line after the initial <.
-
- Returns:
- True if a matching bracket exists.
- """
- line = init_suffix
- nesting_stack = ['<']
- while True:
- # Find the next operator that can tell us whether < is used as an
- # opening bracket or as a less-than operator. We only want to
- # warn on the latter case.
- #
- # We could also check all other operators and terminate the search
- # early, e.g. if we got something like this "a<b+c", the "<" is
- # most likely a less-than operator, but then we will get false
- # positives for default arguments (e.g. http://go/prccd) and
- # other template expressions (e.g. http://go/oxcjq).
- match = Search(r'^[^<>(),;\[\]]*([<>(),;\[\]])(.*)$', line)
- if match:
- # Found an operator, update nesting stack
- operator = match.group(1)
- line = match.group(2)
-
- if nesting_stack[-1] == '<':
- # Expecting closing angle bracket
- if operator in ('<', '(', '['):
- nesting_stack.append(operator)
- elif operator == '>':
- nesting_stack.pop()
- if not nesting_stack:
- # Found matching angle bracket
- return True
- elif operator == ',':
- # Got a comma after a bracket, this is most likely a template
- # argument. We have not seen a closing angle bracket yet, but
- # it's probably a few lines later if we look for it, so just
- # return early here.
- return True
- else:
- # Got some other operator.
- return False
-
- else:
- # Expecting closing parenthesis or closing bracket
- if operator in ('<', '(', '['):
- nesting_stack.append(operator)
- elif operator in (')', ']'):
- # We don't bother checking for matching () or []. If we got
- # something like (] or [), it would have been a syntax error.
- nesting_stack.pop()
-
- else:
- # Scan the next line
- linenum += 1
- if linenum >= len(clean_lines.elided):
- break
- line = clean_lines.elided[linenum]
-
- # Exhausted all remaining lines and still no matching angle bracket.
- # Most likely the input was incomplete, otherwise we should have
- # seen a semicolon and returned early.
- return True
-
-
-def FindPreviousMatchingAngleBracket(clean_lines, linenum, init_prefix):
- """Find the corresponding < that started a template.
-
- Args:
- clean_lines: A CleansedLines instance containing the file.
- linenum: Current line number.
- init_prefix: Part of the current line before the initial >.
-
- Returns:
- True if a matching bracket exists.
- """
- line = init_prefix
- nesting_stack = ['>']
- while True:
- # Find the previous operator
- match = Search(r'^(.*)([<>(),;\[\]])[^<>(),;\[\]]*$', line)
- if match:
- # Found an operator, update nesting stack
- operator = match.group(2)
- line = match.group(1)
-
- if nesting_stack[-1] == '>':
- # Expecting opening angle bracket
- if operator in ('>', ')', ']'):
- nesting_stack.append(operator)
- elif operator == '<':
- nesting_stack.pop()
- if not nesting_stack:
- # Found matching angle bracket
- return True
- elif operator == ',':
- # Got a comma before a bracket, this is most likely a
- # template argument. The opening angle bracket is probably
- # there if we look for it, so just return early here.
- return True
- else:
- # Got some other operator.
- return False
-
- else:
- # Expecting opening parenthesis or opening bracket
- if operator in ('>', ')', ']'):
- nesting_stack.append(operator)
- elif operator in ('(', '['):
- nesting_stack.pop()
-
- else:
- # Scan the previous line
- linenum -= 1
- if linenum < 0:
- break
- line = clean_lines.elided[linenum]
-
- # Exhausted all earlier lines and still no matching angle bracket.
- return False
+ # If the comment contains an alphanumeric character, there
+ # should be a space somewhere between it and the // unless
+ # it's a /// or //! Doxygen comment.
+ if (Match(r'//[^ ]*\w', comment) and
+ not Match(r'(///|//\!)(\s+|$)', comment)):
+ error(filename, linenum, 'whitespace/comments', 4,
+ 'Should have a space between // and comment')
def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
@@ -2209,12 +3181,15 @@
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
- nesting_state: A _NestingState instance which maintains information about
+ nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
- raw = clean_lines.raw_lines
+ # Don't use "elided" lines here, otherwise we can't check commented lines.
+ # Don't want to use "raw" either, because we don't want to check inside C++11
+ # raw strings,
+ raw = clean_lines.lines_without_raw_strings
line = raw[linenum]
# Before nixing comments, check if the line is blank for no good
@@ -2229,7 +3204,12 @@
# }
#
# A warning about missing end of namespace comments will be issued instead.
- if IsBlankLine(line) and not nesting_state.InNamespaceBody():
+ #
+ # Also skip blank line checks for 'extern "C"' blocks, which are formatted
+ # like namespaces.
+ if (IsBlankLine(line) and
+ not nesting_state.InNamespaceBody() and
+ not nesting_state.InExternC()):
elided = clean_lines.elided
prev_line = elided[linenum - 1]
prevbrace = prev_line.rfind('{')
@@ -2268,7 +3248,8 @@
if not exception:
error(filename, linenum, 'whitespace/blank_line', 2,
- 'Blank line at the start of a code block. Is this needed?')
+ 'Redundant blank line at the start of a code block '
+ 'should be deleted.')
# Ignore blank lines at the end of a block in a long if-else
# chain, like this:
# if (condition1) {
@@ -2283,56 +3264,72 @@
and Match(r'\s*}', next_line)
and next_line.find('} else ') == -1):
error(filename, linenum, 'whitespace/blank_line', 3,
- 'Blank line at the end of a code block. Is this needed?')
+ 'Redundant blank line at the end of a code block '
+ 'should be deleted.')
matched = Match(r'\s*(public|protected|private):', prev_line)
if matched:
error(filename, linenum, 'whitespace/blank_line', 3,
'Do not leave a blank line after "%s:"' % matched.group(1))
- # Next, we complain if there's a comment too near the text
- commentpos = line.find('//')
- if commentpos != -1:
- # Check if the // may be in quotes. If so, ignore it
- # Comparisons made explicit for clarity -- pylint: disable-msg=C6403
- if (line.count('"', 0, commentpos) -
- line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes
- # Allow one space for new scopes, two spaces otherwise:
- if (not Match(r'^\s*{ //', line) and
- ((commentpos >= 1 and
- line[commentpos-1] not in string.whitespace) or
- (commentpos >= 2 and
- line[commentpos-2] not in string.whitespace))):
- error(filename, linenum, 'whitespace/comments', 2,
- 'At least two spaces is best between code and comments')
- # There should always be a space between the // and the comment
- commentend = commentpos + 2
- if commentend < len(line) and not line[commentend] == ' ':
- # but some lines are exceptions -- e.g. if they're big
- # comment delimiters like:
- # //----------------------------------------------------------
- # or are an empty C++ style Doxygen comment, like:
- # ///
- # or they begin with multiple slashes followed by a space:
- # //////// Header comment
- match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or
- Search(r'^/$', line[commentend:]) or
- Search(r'^/+ ', line[commentend:]))
- if not match:
- error(filename, linenum, 'whitespace/comments', 4,
- 'Should have a space between // and comment')
- CheckComment(line[commentpos:], filename, linenum, error)
+ # Next, check comments
+ next_line_start = 0
+ if linenum + 1 < clean_lines.NumLines():
+ next_line = raw[linenum + 1]
+ next_line_start = len(next_line) - len(next_line.lstrip())
+ CheckComment(line, filename, linenum, next_line_start, error)
- line = clean_lines.elided[linenum] # get rid of comments and strings
+ # get rid of comments and strings
+ line = clean_lines.elided[linenum]
- # Don't try to do spacing checks for operator methods
- line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line)
+ # You shouldn't have spaces before your brackets, except maybe after
+ # 'delete []' or 'return []() {};'
+ if Search(r'\w\s+\[', line) and not Search(r'(?:delete|return)\s+\[', line):
+ error(filename, linenum, 'whitespace/braces', 5,
+ 'Extra space before [')
+
+ # In range-based for, we wanted spaces before and after the colon, but
+ # not around "::" tokens that might appear.
+ if (Search(r'for *\(.*[^:]:[^: ]', line) or
+ Search(r'for *\(.*[^: ]:[^:]', line)):
+ error(filename, linenum, 'whitespace/forcolon', 2,
+ 'Missing space around colon in range-based for loop')
+
+
+def CheckOperatorSpacing(filename, clean_lines, linenum, error):
+ """Checks for horizontal spacing around operators.
+
+ Args:
+ filename: The name of the current file.
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: The number of the line to check.
+ error: The function to call with any errors found.
+ """
+ line = clean_lines.elided[linenum]
+
+ # Don't try to do spacing checks for operator methods. Do this by
+ # replacing the troublesome characters with something else,
+ # preserving column position for all other characters.
+ #
+ # The replacement is done repeatedly to avoid false positives from
+ # operators that call operators.
+ while True:
+ match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line)
+ if match:
+ line = match.group(1) + ('_' * len(match.group(2))) + match.group(3)
+ else:
+ break
# We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
# Otherwise not. Note we only check for non-spaces on *both* sides;
# sometimes people put non-spaces on one side when aligning ='s among
# many lines (not that this is behavior that I approve of...)
- if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line):
+ if ((Search(r'[\w.]=', line) or
+ Search(r'=[\w.]', line))
+ and not Search(r'\b(if|while|for) ', line)
+ # Operators taken from [lex.operators] in C++11 standard.
+ and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line)
+ and not Search(r'operator=', line)):
error(filename, linenum, 'whitespace/operators', 4,
'Missing spaces around =')
@@ -2344,39 +3341,51 @@
#
# Check <= and >= first to avoid false positives with < and >, then
# check non-include lines for spacing around < and >.
- match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line)
+ #
+ # If the operator is followed by a comma, assume it's be used in a
+ # macro context and don't do any checks. This avoids false
+ # positives.
+ #
+ # Note that && is not included here. This is because there are too
+ # many false positives due to RValue references.
+ match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line)
if match:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around %s' % match.group(1))
- # We allow no-spaces around << when used like this: 10<<20, but
- # not otherwise (particularly, not when used as streams)
- match = Search(r'(\S)(?:L|UL|ULL|l|ul|ull)?<<(\S)', line)
- if match and not (match.group(1).isdigit() and match.group(2).isdigit()):
- error(filename, linenum, 'whitespace/operators', 3,
- 'Missing spaces around <<')
elif not Match(r'#.*include', line):
- # Avoid false positives on ->
- reduced_line = line.replace('->', '')
-
# Look for < that is not surrounded by spaces. This is only
# triggered if both sides are missing spaces, even though
# technically should should flag if at least one side is missing a
# space. This is done to avoid some false positives with shifts.
- match = Search(r'[^\s<]<([^\s=<].*)', reduced_line)
- if (match and
- not FindNextMatchingAngleBracket(clean_lines, linenum, match.group(1))):
- error(filename, linenum, 'whitespace/operators', 3,
- 'Missing spaces around <')
+ match = Match(r'^(.*[^\s<])<[^\s=<,]', line)
+ if match:
+ (_, _, end_pos) = CloseExpression(
+ clean_lines, linenum, len(match.group(1)))
+ if end_pos <= -1:
+ error(filename, linenum, 'whitespace/operators', 3,
+ 'Missing spaces around <')
# Look for > that is not surrounded by spaces. Similar to the
# above, we only trigger if both sides are missing spaces to avoid
# false positives with shifts.
- match = Search(r'^(.*[^\s>])>[^\s=>]', reduced_line)
- if (match and
- not FindPreviousMatchingAngleBracket(clean_lines, linenum,
- match.group(1))):
- error(filename, linenum, 'whitespace/operators', 3,
- 'Missing spaces around >')
+ match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)
+ if match:
+ (_, _, start_pos) = ReverseCloseExpression(
+ clean_lines, linenum, len(match.group(1)))
+ if start_pos <= -1:
+ error(filename, linenum, 'whitespace/operators', 3,
+ 'Missing spaces around >')
+
+ # We allow no-spaces around << when used like this: 10<<20, but
+ # not otherwise (particularly, not when used as streams)
+ #
+ # We also allow operators following an opening parenthesis, since
+ # those tend to be macros that deal with operators.
+ match = Search(r'(operator|[^\s(<])(?:L|UL|LL|ULL|l|ul|ll|ull)?<<([^\s,=<])', line)
+ if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and
+ not (match.group(1) == 'operator' and match.group(2) == ';')):
+ error(filename, linenum, 'whitespace/operators', 3,
+ 'Missing spaces around <<')
# We allow no-spaces around >> for almost anything. This is because
# C++11 allows ">>" to close nested templates, which accounts for
@@ -2401,7 +3410,19 @@
error(filename, linenum, 'whitespace/operators', 4,
'Extra space for operator %s' % match.group(1))
- # A pet peeve of mine: no spaces after an if, while, switch, or for
+
+def CheckParenthesisSpacing(filename, clean_lines, linenum, error):
+ """Checks for horizontal spacing around parentheses.
+
+ Args:
+ filename: The name of the current file.
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: The number of the line to check.
+ error: The function to call with any errors found.
+ """
+ line = clean_lines.elided[linenum]
+
+ # No spaces after an if, while, switch, or for
match = Search(r' (if\(|for\(|while\(|switch\()', line)
if match:
error(filename, linenum, 'whitespace/parens', 5,
@@ -2422,13 +3443,36 @@
not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
error(filename, linenum, 'whitespace/parens', 5,
'Mismatching spaces inside () in %s' % match.group(1))
- if not len(match.group(2)) in [0, 1]:
+ if len(match.group(2)) not in [0, 1]:
error(filename, linenum, 'whitespace/parens', 5,
'Should have zero or one spaces inside ( and ) in %s' %
match.group(1))
+
+def CheckCommaSpacing(filename, clean_lines, linenum, error):
+ """Checks for horizontal spacing near commas and semicolons.
+
+ Args:
+ filename: The name of the current file.
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: The number of the line to check.
+ error: The function to call with any errors found.
+ """
+ raw = clean_lines.lines_without_raw_strings
+ line = clean_lines.elided[linenum]
+
# You should always have a space after a comma (either as fn arg or operator)
- if Search(r',[^\s]', line):
+ #
+ # This does not apply when the non-space character following the
+ # comma is another comma, since the only time when that happens is
+ # for empty macro arguments.
+ #
+ # We run this check in two passes: first pass on elided lines to
+ # verify that lines contain missing whitespaces, second pass on raw
+ # lines to confirm that those missing whitespaces are not due to
+ # elided comments.
+ if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and
+ Search(r',[^,\s]', raw[linenum])):
error(filename, linenum, 'whitespace/comma', 3,
'Missing space after ,')
@@ -2440,28 +3484,142 @@
error(filename, linenum, 'whitespace/semicolon', 3,
'Missing space after ;')
- # Next we will look for issues with function calls.
- CheckSpacingForFunctionCall(filename, line, linenum, error)
+
+def _IsType(clean_lines, nesting_state, expr):
+ """Check if expression looks like a type name, returns true if so.
+
+ Args:
+ clean_lines: A CleansedLines instance containing the file.
+ nesting_state: A NestingState instance which maintains information about
+ the current stack of nested blocks being parsed.
+ expr: The expression to check.
+ Returns:
+ True, if token looks like a type.
+ """
+ # Keep only the last token in the expression
+ last_word = Match(r'^.*(\b\S+)$', expr)
+ if last_word:
+ token = last_word.group(1)
+ else:
+ token = expr
+
+ # Match native types and stdint types
+ if _TYPES.match(token):
+ return True
+
+ # Try a bit harder to match templated types. Walk up the nesting
+ # stack until we find something that resembles a typename
+ # declaration for what we are looking for.
+ typename_pattern = (r'\b(?:typename|class|struct)\s+' + re.escape(token) +
+ r'\b')
+ block_index = len(nesting_state.stack) - 1
+ while block_index >= 0:
+ if isinstance(nesting_state.stack[block_index], _NamespaceInfo):
+ return False
+
+ # Found where the opening brace is. We want to scan from this
+ # line up to the beginning of the function, minus a few lines.
+ # template <typename Type1, // stop scanning here
+ # ...>
+ # class C
+ # : public ... { // start scanning here
+ last_line = nesting_state.stack[block_index].starting_linenum
+
+ next_block_start = 0
+ if block_index > 0:
+ next_block_start = nesting_state.stack[block_index - 1].starting_linenum
+ first_line = last_line
+ while first_line >= next_block_start:
+ if clean_lines.elided[first_line].find('template') >= 0:
+ break
+ first_line -= 1
+ if first_line < next_block_start:
+ # Didn't find any "template" keyword before reaching the next block,
+ # there are probably no template things to check for this block
+ block_index -= 1
+ continue
+
+ # Look for typename in the specified range
+ for i in xrange(first_line, last_line + 1, 1):
+ if Search(typename_pattern, clean_lines.elided[i]):
+ return True
+ block_index -= 1
+
+ return False
+
+
+def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error):
+ """Checks for horizontal spacing near commas.
+
+ Args:
+ filename: The name of the current file.
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: The number of the line to check.
+ nesting_state: A NestingState instance which maintains information about
+ the current stack of nested blocks being parsed.
+ error: The function to call with any errors found.
+ """
+ line = clean_lines.elided[linenum]
# Except after an opening paren, or after another opening brace (in case of
# an initializer list, for instance), you should have spaces before your
- # braces. And since you should never have braces at the beginning of a line,
- # this is an easy test.
- if Search(r'[^ ({]{', line):
- error(filename, linenum, 'whitespace/braces', 5,
- 'Missing space before {')
+ # braces when they are delimiting blocks, classes, namespaces etc.
+ # And since you should never have braces at the beginning of a line,
+ # this is an easy test. Except that braces used for initialization don't
+ # follow the same rule; we often don't want spaces before those.
+ match = Match(r'^(.*[^ ({>]){', line)
+
+ if match:
+ # Try a bit harder to check for brace initialization. This
+ # happens in one of the following forms:
+ # Constructor() : initializer_list_{} { ... }
+ # Constructor{}.MemberFunction()
+ # Type variable{};
+ # FunctionCall(type{}, ...);
+ # LastArgument(..., type{});
+ # LOG(INFO) << type{} << " ...";
+ # map_of_type[{...}] = ...;
+ # ternary = expr ? new type{} : nullptr;
+ # OuterTemplate<InnerTemplateConstructor<Type>{}>
+ #
+ # We check for the character following the closing brace, and
+ # silence the warning if it's one of those listed above, i.e.
+ # "{.;,)<>]:".
+ #
+ # To account for nested initializer list, we allow any number of
+ # closing braces up to "{;,)<". We can't simply silence the
+ # warning on first sight of closing brace, because that would
+ # cause false negatives for things that are not initializer lists.
+ # Silence this: But not this:
+ # Outer{ if (...) {
+ # Inner{...} if (...){ // Missing space before {
+ # }; }
+ #
+ # There is a false negative with this approach if people inserted
+ # spurious semicolons, e.g. "if (cond){};", but we will catch the
+ # spurious semicolon with a separate check.
+ leading_text = match.group(1)
+ (endline, endlinenum, endpos) = CloseExpression(
+ clean_lines, linenum, len(match.group(1)))
+ trailing_text = ''
+ if endpos > -1:
+ trailing_text = endline[endpos:]
+ for offset in xrange(endlinenum + 1,
+ min(endlinenum + 3, clean_lines.NumLines() - 1)):
+ trailing_text += clean_lines.elided[offset]
+ # We also suppress warnings for `uint64_t{expression}` etc., as the style
+ # guide recommends brace initialization for integral types to avoid
+ # overflow/truncation.
+ if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text)
+ and not _IsType(clean_lines, nesting_state, leading_text)):
+ error(filename, linenum, 'whitespace/braces', 5,
+ 'Missing space before {')
# Make sure '} else {' has spaces.
if Search(r'}else', line):
error(filename, linenum, 'whitespace/braces', 5,
'Missing space before else')
- # You shouldn't have spaces before your brackets, except maybe after
- # 'delete []' or 'new char * []'.
- if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line):
- error(filename, linenum, 'whitespace/braces', 5,
- 'Extra space before [')
-
# You shouldn't have a space before a semicolon at the end of the line.
# There's a special case for "for" since the style guide allows space before
# the semicolon there.
@@ -2478,12 +3636,23 @@
'Extra space before last semicolon. If this should be an empty '
'statement, use {} instead.')
- # In range-based for, we wanted spaces before and after the colon, but
- # not around "::" tokens that might appear.
- if (Search('for *\(.*[^:]:[^: ]', line) or
- Search('for *\(.*[^: ]:[^:]', line)):
- error(filename, linenum, 'whitespace/forcolon', 2,
- 'Missing space around colon in range-based for loop')
+
+def IsDecltype(clean_lines, linenum, column):
+ """Check if the token ending on (linenum, column) is decltype().
+
+ Args:
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: the number of the line to check.
+ column: end column of the token to check.
+ Returns:
+ True if this token is decltype() expression, False otherwise.
+ """
+ (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column)
+ if start_col < 0:
+ return False
+ if Search(r'\bdecltype\s*$', text[0:start_col]):
+ return True
+ return False
def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
@@ -2577,21 +3746,24 @@
line = clean_lines.elided[linenum] # get rid of comments and strings
if Match(r'\s*{\s*$', line):
- # We allow an open brace to start a line in the case where someone
- # is using braces in a block to explicitly create a new scope,
- # which is commonly used to control the lifetime of
- # stack-allocated variables. We don't detect this perfectly: we
- # just don't complain if the last non-whitespace character on the
- # previous non-blank line is ';', ':', '{', or '}', or if the previous
- # line starts a preprocessor block.
+ # We allow an open brace to start a line in the case where someone is using
+ # braces in a block to explicitly create a new scope, which is commonly used
+ # to control the lifetime of stack-allocated variables. Braces are also
+ # used for brace initializers inside function calls. We don't detect this
+ # perfectly: we just don't complain if the last non-whitespace character on
+ # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
+ # previous line starts a preprocessor block. We also allow a brace on the
+ # following line if it is part of an array initialization and would not fit
+ # within the 80 character limit of the preceding line.
prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
- if (not Search(r'[;:}{]\s*$', prevline) and
- not Match(r'\s*#', prevline)):
+ if (not Search(r'[,;:}{(]\s*$', prevline) and
+ not Match(r'\s*#', prevline) and
+ not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)):
error(filename, linenum, 'whitespace/braces', 4,
'{ should almost always be at the end of the previous line')
# An else clause should be on the same line as the preceding closing brace.
- if Match(r'\s*else\s*', line):
+ if Match(r'\s*else\b\s*(?:if\b|\{|$)', line):
prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
if Match(r'\s*}\s*$', prevline):
error(filename, linenum, 'whitespace/newline', 4,
@@ -2599,19 +3771,20 @@
# If braces come on one side of an else, they should be on both.
# However, we have to worry about "else if" that spans multiple lines!
- if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
- if Search(r'}\s*else if([^{]*)$', line): # could be multi-line if
- # find the ( after the if
- pos = line.find('else if')
- pos = line.find('(', pos)
- if pos > 0:
- (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
- if endline[endpos:].find('{') == -1: # must be brace after if
- error(filename, linenum, 'readability/braces', 5,
- 'If an else has a brace on one side, it should have it on both')
- else: # common case: else not followed by a multi-line if
- error(filename, linenum, 'readability/braces', 5,
- 'If an else has a brace on one side, it should have it on both')
+ if Search(r'else if\s*\(', line): # could be multi-line if
+ brace_on_left = bool(Search(r'}\s*else if\s*\(', line))
+ # find the ( after the if
+ pos = line.find('else if')
+ pos = line.find('(', pos)
+ if pos > 0:
+ (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
+ brace_on_right = endline[endpos:].find('{') != -1
+ if brace_on_left != brace_on_right: # must be brace after if
+ error(filename, linenum, 'readability/braces', 5,
+ 'If an else has a brace on one side, it should have it on both')
+ elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
+ error(filename, linenum, 'readability/braces', 5,
+ 'If an else has a brace on one side, it should have it on both')
# Likewise, an else should never have the else clause on the same line
if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
@@ -2623,25 +3796,211 @@
error(filename, linenum, 'whitespace/newline', 4,
'do/while clauses should not be on a single line')
- # Braces shouldn't be followed by a ; unless they're defining a struct
- # or initializing an array.
- # We can't tell in general, but we can for some common cases.
- prevlinenum = linenum
- while True:
- (prevline, prevlinenum) = GetPreviousNonBlankLine(clean_lines, prevlinenum)
- if Match(r'\s+{.*}\s*;', line) and not prevline.count(';'):
- line = prevline + line
- else:
- break
- if (Search(r'{.*}\s*;', line) and
- line.count('{') == line.count('}') and
- not Search(r'struct|class|enum|\s*=\s*{', line)):
- error(filename, linenum, 'readability/braces', 4,
- "You don't need a ; after a }")
+ # Check single-line if/else bodies. The style guide says 'curly braces are not
+ # required for single-line statements'. We additionally allow multi-line,
+ # single statements, but we reject anything with more than one semicolon in
+ # it. This means that the first semicolon after the if should be at the end of
+ # its line, and the line after that should have an indent level equal to or
+ # lower than the if. We also check for ambiguous if/else nesting without
+ # braces.
+ if_else_match = Search(r'\b(if\s*\(|else\b)', line)
+ if if_else_match and not Match(r'\s*#', line):
+ if_indent = GetIndentLevel(line)
+ endline, endlinenum, endpos = line, linenum, if_else_match.end()
+ if_match = Search(r'\bif\s*\(', line)
+ if if_match:
+ # This could be a multiline if condition, so find the end first.
+ pos = if_match.end() - 1
+ (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos)
+ # Check for an opening brace, either directly after the if or on the next
+ # line. If found, this isn't a single-statement conditional.
+ if (not Match(r'\s*{', endline[endpos:])
+ and not (Match(r'\s*$', endline[endpos:])
+ and endlinenum < (len(clean_lines.elided) - 1)
+ and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))):
+ while (endlinenum < len(clean_lines.elided)
+ and ';' not in clean_lines.elided[endlinenum][endpos:]):
+ endlinenum += 1
+ endpos = 0
+ if endlinenum < len(clean_lines.elided):
+ endline = clean_lines.elided[endlinenum]
+ # We allow a mix of whitespace and closing braces (e.g. for one-liner
+ # methods) and a single \ after the semicolon (for macros)
+ endpos = endline.find(';')
+ if not Match(r';[\s}]*(\\?)$', endline[endpos:]):
+ # Semicolon isn't the last character, there's something trailing.
+ # Output a warning if the semicolon is not contained inside
+ # a lambda expression.
+ if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$',
+ endline):
+ error(filename, linenum, 'readability/braces', 4,
+ 'If/else bodies with multiple statements require braces')
+ elif endlinenum < len(clean_lines.elided) - 1:
+ # Make sure the next line is dedented
+ next_line = clean_lines.elided[endlinenum + 1]
+ next_indent = GetIndentLevel(next_line)
+ # With ambiguous nested if statements, this will error out on the
+ # if that *doesn't* match the else, regardless of whether it's the
+ # inner one or outer one.
+ if (if_match and Match(r'\s*else\b', next_line)
+ and next_indent != if_indent):
+ error(filename, linenum, 'readability/braces', 4,
+ 'Else clause should be indented at the same level as if. '
+ 'Ambiguous nested if/else chains require braces.')
+ elif next_indent > if_indent:
+ error(filename, linenum, 'readability/braces', 4,
+ 'If/else bodies with multiple statements require braces')
-def CheckEmptyLoopBody(filename, clean_lines, linenum, error):
- """Loop for empty loop body with only a single semicolon.
+def CheckTrailingSemicolon(filename, clean_lines, linenum, error):
+ """Looks for redundant trailing semicolon.
+
+ Args:
+ filename: The name of the current file.
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: The number of the line to check.
+ error: The function to call with any errors found.
+ """
+
+ line = clean_lines.elided[linenum]
+
+ # Block bodies should not be followed by a semicolon. Due to C++11
+ # brace initialization, there are more places where semicolons are
+ # required than not, so we use a whitelist approach to check these
+ # rather than a blacklist. These are the places where "};" should
+ # be replaced by just "}":
+ # 1. Some flavor of block following closing parenthesis:
+ # for (;;) {};
+ # while (...) {};
+ # switch (...) {};
+ # Function(...) {};
+ # if (...) {};
+ # if (...) else if (...) {};
+ #
+ # 2. else block:
+ # if (...) else {};
+ #
+ # 3. const member function:
+ # Function(...) const {};
+ #
+ # 4. Block following some statement:
+ # x = 42;
+ # {};
+ #
+ # 5. Block at the beginning of a function:
+ # Function(...) {
+ # {};
+ # }
+ #
+ # Note that naively checking for the preceding "{" will also match
+ # braces inside multi-dimensional arrays, but this is fine since
+ # that expression will not contain semicolons.
+ #
+ # 6. Block following another block:
+ # while (true) {}
+ # {};
+ #
+ # 7. End of namespaces:
+ # namespace {};
+ #
+ # These semicolons seems far more common than other kinds of
+ # redundant semicolons, possibly due to people converting classes
+ # to namespaces. For now we do not warn for this case.
+ #
+ # Try matching case 1 first.
+ match = Match(r'^(.*\)\s*)\{', line)
+ if match:
+ # Matched closing parenthesis (case 1). Check the token before the
+ # matching opening parenthesis, and don't warn if it looks like a
+ # macro. This avoids these false positives:
+ # - macro that defines a base class
+ # - multi-line macro that defines a base class
+ # - macro that defines the whole class-head
+ #
+ # But we still issue warnings for macros that we know are safe to
+ # warn, specifically:
+ # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
+ # - TYPED_TEST
+ # - INTERFACE_DEF
+ # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
+ #
+ # We implement a whitelist of safe macros instead of a blacklist of
+ # unsafe macros, even though the latter appears less frequently in
+ # google code and would have been easier to implement. This is because
+ # the downside for getting the whitelist wrong means some extra
+ # semicolons, while the downside for getting the blacklist wrong
+ # would result in compile errors.
+ #
+ # In addition to macros, we also don't want to warn on
+ # - Compound literals
+ # - Lambdas
+ # - alignas specifier with anonymous structs
+ # - decltype
+ closing_brace_pos = match.group(1).rfind(')')
+ opening_parenthesis = ReverseCloseExpression(
+ clean_lines, linenum, closing_brace_pos)
+ if opening_parenthesis[2] > -1:
+ line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]
+ macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix)
+ func = Match(r'^(.*\])\s*$', line_prefix)
+ if ((macro and
+ macro.group(1) not in (
+ 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',
+ 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',
+ 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or
+ (func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or
+ Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or
+ Search(r'\bdecltype$', line_prefix) or
+ Search(r'\s+=\s*$', line_prefix)):
+ match = None
+ if (match and
+ opening_parenthesis[1] > 1 and
+ Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):
+ # Multi-line lambda-expression
+ match = None
+
+ else:
+ # Try matching cases 2-3.
+ match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
+ if not match:
+ # Try matching cases 4-6. These are always matched on separate lines.
+ #
+ # Note that we can't simply concatenate the previous line to the
+ # current line and do a single match, otherwise we may output
+ # duplicate warnings for the blank line case:
+ # if (cond) {
+ # // blank line
+ # }
+ prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
+ if prevline and Search(r'[;{}]\s*$', prevline):
+ match = Match(r'^(\s*)\{', line)
+
+ # Check matching closing brace
+ if match:
+ (endline, endlinenum, endpos) = CloseExpression(
+ clean_lines, linenum, len(match.group(1)))
+ if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
+ # Current {} pair is eligible for semicolon check, and we have found
+ # the redundant semicolon, output warning here.
+ #
+ # Note: because we are scanning forward for opening braces, and
+ # outputting warnings for the matching closing brace, if there are
+ # nested blocks with trailing semicolons, we will get the error
+ # messages in reversed order.
+
+ # We need to check the line forward for NOLINT
+ raw_lines = clean_lines.raw_lines
+ ParseNolintSuppressions(filename, raw_lines[endlinenum-1], endlinenum-1,
+ error)
+ ParseNolintSuppressions(filename, raw_lines[endlinenum], endlinenum,
+ error)
+
+ error(filename, endlinenum, 'readability/braces', 4,
+ "You don't need a ; after a }")
+
+
+def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
+ """Look for empty loop/conditional body with only a single semicolon.
Args:
filename: The name of the current file.
@@ -2653,9 +4012,13 @@
# Search for loop keywords at the beginning of the line. Because only
# whitespaces are allowed before the keywords, this will also ignore most
# do-while-loops, since those lines should start with closing brace.
+ #
+ # We also check "if" blocks here, since an empty conditional block
+ # is likely an error.
line = clean_lines.elided[linenum]
- if Match(r'\s*(for|while)\s*\(', line):
- # Find the end of the conditional expression
+ matched = Match(r'\s*(for|while|if)\s*\(', line)
+ if matched:
+ # Find the end of the conditional expression.
(end_line, end_linenum, end_pos) = CloseExpression(
clean_lines, linenum, line.find('('))
@@ -2663,43 +4026,104 @@
# No warning for all other cases, including whitespace or newline, since we
# have a separate check for semicolons preceded by whitespace.
if end_pos >= 0 and Match(r';', end_line[end_pos:]):
- error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
- 'Empty loop bodies should use {} or continue')
+ if matched.group(1) == 'if':
+ error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
+ 'Empty conditional bodies should use {}')
+ else:
+ error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
+ 'Empty loop bodies should use {} or continue')
+
+ # Check for if statements that have completely empty bodies (no comments)
+ # and no else clauses.
+ if end_pos >= 0 and matched.group(1) == 'if':
+ # Find the position of the opening { for the if statement.
+ # Return without logging an error if it has no brackets.
+ opening_linenum = end_linenum
+ opening_line_fragment = end_line[end_pos:]
+ # Loop until EOF or find anything that's not whitespace or opening {.
+ while not Search(r'^\s*\{', opening_line_fragment):
+ if Search(r'^(?!\s*$)', opening_line_fragment):
+ # Conditional has no brackets.
+ return
+ opening_linenum += 1
+ if opening_linenum == len(clean_lines.elided):
+ # Couldn't find conditional's opening { or any code before EOF.
+ return
+ opening_line_fragment = clean_lines.elided[opening_linenum]
+ # Set opening_line (opening_line_fragment may not be entire opening line).
+ opening_line = clean_lines.elided[opening_linenum]
+
+ # Find the position of the closing }.
+ opening_pos = opening_line_fragment.find('{')
+ if opening_linenum == end_linenum:
+ # We need to make opening_pos relative to the start of the entire line.
+ opening_pos += end_pos
+ (closing_line, closing_linenum, closing_pos) = CloseExpression(
+ clean_lines, opening_linenum, opening_pos)
+ if closing_pos < 0:
+ return
+
+ # Now construct the body of the conditional. This consists of the portion
+ # of the opening line after the {, all lines until the closing line,
+ # and the portion of the closing line before the }.
+ if (clean_lines.raw_lines[opening_linenum] !=
+ CleanseComments(clean_lines.raw_lines[opening_linenum])):
+ # Opening line ends with a comment, so conditional isn't empty.
+ return
+ if closing_linenum > opening_linenum:
+ # Opening line after the {. Ignore comments here since we checked above.
+ body = list(opening_line[opening_pos+1:])
+ # All lines until closing line, excluding closing line, with comments.
+ body.extend(clean_lines.raw_lines[opening_linenum+1:closing_linenum])
+ # Closing line before the }. Won't (and can't) have comments.
+ body.append(clean_lines.elided[closing_linenum][:closing_pos-1])
+ body = '\n'.join(body)
+ else:
+ # If statement has brackets and fits on a single line.
+ body = opening_line[opening_pos+1:closing_pos-1]
+
+ # Check if the body is empty
+ if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body):
+ return
+ # The body is empty. Now make sure there's not an else clause.
+ current_linenum = closing_linenum
+ current_line_fragment = closing_line[closing_pos:]
+ # Loop until EOF or find anything that's not whitespace or else clause.
+ while Search(r'^\s*$|^(?=\s*else)', current_line_fragment):
+ if Search(r'^(?=\s*else)', current_line_fragment):
+ # Found an else clause, so don't log an error.
+ return
+ current_linenum += 1
+ if current_linenum == len(clean_lines.elided):
+ break
+ current_line_fragment = clean_lines.elided[current_linenum]
+
+ # The body is empty and there's no else clause until EOF or other code.
+ error(filename, end_linenum, 'whitespace/empty_if_body', 4,
+ ('If statement had no body and no else clause'))
-def ReplaceableCheck(operator, macro, line):
- """Determine whether a basic CHECK can be replaced with a more specific one.
-
- For example suggest using CHECK_EQ instead of CHECK(a == b) and
- similarly for CHECK_GE, CHECK_GT, CHECK_LE, CHECK_LT, CHECK_NE.
+def FindCheckMacro(line):
+ """Find a replaceable CHECK-like macro.
Args:
- operator: The C++ operator used in the CHECK.
- macro: The CHECK or EXPECT macro being called.
- line: The current source line.
-
+ line: line to search on.
Returns:
- True if the CHECK can be replaced with a more specific one.
+ (macro name, start position), or (None, -1) if no replaceable
+ macro is found.
"""
-
- # This matches decimal and hex integers, strings, and chars (in that order).
- match_constant = r'([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')'
-
- # Expression to match two sides of the operator with something that
- # looks like a literal, since CHECK(x == iterator) won't compile.
- # This means we can't catch all the cases where a more specific
- # CHECK is possible, but it's less annoying than dealing with
- # extraneous warnings.
- match_this = (r'\s*' + macro + r'\((\s*' +
- match_constant + r'\s*' + operator + r'[^<>].*|'
- r'.*[^<>]' + operator + r'\s*' + match_constant +
- r'\s*\))')
-
- # Don't complain about CHECK(x == NULL) or similar because
- # CHECK_EQ(x, NULL) won't compile (requires a cast).
- # Also, don't complain about more complex boolean expressions
- # involving && or || such as CHECK(a == b || c == d).
- return Match(match_this, line) and not Search(r'NULL|&&|\|\|', line)
+ for macro in _CHECK_MACROS:
+ i = line.find(macro)
+ if i >= 0:
+ # Find opening parenthesis. Do a regular expression match here
+ # to make sure that we are matching the expected CHECK macro, as
+ # opposed to some other macro that happens to contain the CHECK
+ # substring.
+ matched = Match(r'^(.*\b' + macro + r'\s*)\(', line)
+ if not matched:
+ continue
+ return (macro, len(matched.group(1)))
+ return (None, -1)
def CheckCheck(filename, clean_lines, linenum, error):
@@ -2713,26 +4137,111 @@
"""
# Decide the set of replacement macros that should be suggested
- raw_lines = clean_lines.raw_lines
- current_macro = ''
- for macro in _CHECK_MACROS:
- if raw_lines[linenum].find(macro) >= 0:
- current_macro = macro
- break
- if not current_macro:
- # Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT'
+ lines = clean_lines.elided
+ (check_macro, start_pos) = FindCheckMacro(lines[linenum])
+ if not check_macro:
return
- line = clean_lines.elided[linenum] # get rid of comments and strings
+ # Find end of the boolean expression by matching parentheses
+ (last_line, end_line, end_pos) = CloseExpression(
+ clean_lines, linenum, start_pos)
+ if end_pos < 0:
+ return
- # Encourage replacing plain CHECKs with CHECK_EQ/CHECK_NE/etc.
- for operator in ['==', '!=', '>=', '>', '<=', '<']:
- if ReplaceableCheck(operator, current_macro, line):
- error(filename, linenum, 'readability/check', 2,
- 'Consider using %s instead of %s(a %s b)' % (
- _CHECK_REPLACEMENT[current_macro][operator],
- current_macro, operator))
- break
+ # If the check macro is followed by something other than a
+ # semicolon, assume users will log their own custom error messages
+ # and don't suggest any replacements.
+ if not Match(r'\s*;', last_line[end_pos:]):
+ return
+
+ if linenum == end_line:
+ expression = lines[linenum][start_pos + 1:end_pos - 1]
+ else:
+ expression = lines[linenum][start_pos + 1:]
+ for i in xrange(linenum + 1, end_line):
+ expression += lines[i]
+ expression += last_line[0:end_pos - 1]
+
+ # Parse expression so that we can take parentheses into account.
+ # This avoids false positives for inputs like "CHECK((a < 4) == b)",
+ # which is not replaceable by CHECK_LE.
+ lhs = ''
+ rhs = ''
+ operator = None
+ while expression:
+ matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
+ r'==|!=|>=|>|<=|<|\()(.*)$', expression)
+ if matched:
+ token = matched.group(1)
+ if token == '(':
+ # Parenthesized operand
+ expression = matched.group(2)
+ (end, _) = FindEndOfExpressionInLine(expression, 0, ['('])
+ if end < 0:
+ return # Unmatched parenthesis
+ lhs += '(' + expression[0:end]
+ expression = expression[end:]
+ elif token in ('&&', '||'):
+ # Logical and/or operators. This means the expression
+ # contains more than one term, for example:
+ # CHECK(42 < a && a < b);
+ #
+ # These are not replaceable with CHECK_LE, so bail out early.
+ return
+ elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
+ # Non-relational operator
+ lhs += token
+ expression = matched.group(2)
+ else:
+ # Relational operator
+ operator = token
+ rhs = matched.group(2)
+ break
+ else:
+ # Unparenthesized operand. Instead of appending to lhs one character
+ # at a time, we do another regular expression match to consume several
+ # characters at once if possible. Trivial benchmark shows that this
+ # is more efficient when the operands are longer than a single
+ # character, which is generally the case.
+ matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
+ if not matched:
+ matched = Match(r'^(\s*\S)(.*)$', expression)
+ if not matched:
+ break
+ lhs += matched.group(1)
+ expression = matched.group(2)
+
+ # Only apply checks if we got all parts of the boolean expression
+ if not (lhs and operator and rhs):
+ return
+
+ # Check that rhs do not contain logical operators. We already know
+ # that lhs is fine since the loop above parses out && and ||.
+ if rhs.find('&&') > -1 or rhs.find('||') > -1:
+ return
+
+ # At least one of the operands must be a constant literal. This is
+ # to avoid suggesting replacements for unprintable things like
+ # CHECK(variable != iterator)
+ #
+ # The following pattern matches decimal, hex integers, strings, and
+ # characters (in that order).
+ lhs = lhs.strip()
+ rhs = rhs.strip()
+ match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
+ if Match(match_constant, lhs) or Match(match_constant, rhs):
+ # Note: since we know both lhs and rhs, we can provide a more
+ # descriptive error message like:
+ # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
+ # Instead of:
+ # Consider using CHECK_EQ instead of CHECK(a == b)
+ #
+ # We are still keeping the less descriptive message because if lhs
+ # or rhs gets long, the error message might become unreadable.
+ error(filename, linenum, 'readability/check', 2,
+ 'Consider using %s instead of %s(a %s b)' % (
+ _CHECK_REPLACEMENT[check_macro][operator],
+ check_macro, operator))
def CheckAltTokens(filename, clean_lines, linenum, error):
@@ -2783,6 +4292,16 @@
if unicodedata.east_asian_width(uc) in ('W', 'F'):
width += 2
elif not unicodedata.combining(uc):
+ # Issue 337
+ # https://mail.python.org/pipermail/python-list/2012-August/628809.html
+ if (sys.version_info.major, sys.version_info.minor) <= (3, 2):
+ # https://github.com/python/cpython/blob/2.7/Include/unicodeobject.h#L81
+ is_wide_build = sysconfig.get_config_var("Py_UNICODE_SIZE") >= 4
+ # https://github.com/python/cpython/blob/2.7/Objects/unicodeobject.c#L564
+ is_low_surrogate = 0xDC00 <= ord(uc) <= 0xDFFF
+ if not is_wide_build and is_low_surrogate:
+ width -= 1
+
width += 1
return width
else:
@@ -2802,13 +4321,17 @@
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
- nesting_state: A _NestingState instance which maintains information about
+ nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
- raw_lines = clean_lines.raw_lines
+ # Don't use "elided" lines here, otherwise we can't check commented lines.
+ # Don't want to use "raw" either, because we don't want to check inside C++11
+ # raw strings,
+ raw_lines = clean_lines.lines_without_raw_strings
line = raw_lines[linenum]
+ prev = raw_lines[linenum - 1] if linenum > 0 else ''
if line.find('\t') != -1:
error(filename, linenum, 'whitespace/tab', 1,
@@ -2826,32 +4349,33 @@
# if(match($0, " <<")) complain = 0;
# if(match(prev, " +for \\(")) complain = 0;
# if(prevodd && match(prevprev, " +for \\(")) complain = 0;
+ scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$'
+ classinfo = nesting_state.InnermostClass()
initial_spaces = 0
cleansed_line = clean_lines.elided[linenum]
while initial_spaces < len(line) and line[initial_spaces] == ' ':
initial_spaces += 1
- if line and line[-1].isspace():
- error(filename, linenum, 'whitespace/end_of_line', 4,
- 'Line ends in whitespace. Consider deleting these extra spaces.')
- # There are certain situations we allow one space, notably for labels
- elif ((initial_spaces == 1 or initial_spaces == 3) and
- not Match(r'\s*\w+\s*:\s*$', cleansed_line)):
+ # There are certain situations we allow one space, notably for
+ # section labels, and also lines containing multi-line raw strings.
+ # We also don't check for lines that look like continuation lines
+ # (of lines ending in double quotes, commas, equals, or angle brackets)
+ # because the rules for how to indent those are non-trivial.
+ if (not Search(r'[",=><] *$', prev) and
+ (initial_spaces == 1 or initial_spaces == 3) and
+ not Match(scope_or_label_pattern, cleansed_line) and
+ not (clean_lines.raw_lines[linenum] != line and
+ Match(r'^\s*""', line))):
error(filename, linenum, 'whitespace/indent', 3,
'Weird number of spaces at line-start. '
'Are you using a 2-space indent?')
- # Labels should always be indented at least one space.
- elif not initial_spaces and line[:2] != '//' and Search(r'[^:]:\s*$',
- line):
- error(filename, linenum, 'whitespace/labels', 4,
- 'Labels should always be indented at least one space. '
- 'If this is a member-initializer list in a constructor or '
- 'the base class list in a class definition, the colon should '
- 'be on the following line.')
+ if line and line[-1].isspace():
+ error(filename, linenum, 'whitespace/end_of_line', 4,
+ 'Line ends in whitespace. Consider deleting these extra spaces.')
# Check if the line is a header guard.
is_header_guard = False
- if file_extension == 'h':
+ if IsHeaderExtension(file_extension):
cppvar = GetHeaderGuardCPPVariable(filename)
if (line.startswith('#ifndef %s' % cppvar) or
line.startswith('#define %s' % cppvar) or
@@ -2867,14 +4391,12 @@
# developers fault.
if (not line.startswith('#include') and not is_header_guard and
not Match(r'^\s*//.*http(s?)://\S*$', line) and
+ not Match(r'^\s*//\s*[^\s]*$', line) and
not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
line_width = GetLineWidth(line)
- if line_width > 100:
- error(filename, linenum, 'whitespace/line_length', 4,
- 'Lines should very rarely be longer than 100 characters')
- elif line_width > 80:
+ if line_width > _line_length:
error(filename, linenum, 'whitespace/line_length', 2,
- 'Lines should be <= 80 characters long')
+ 'Lines should be <= %i characters long' % _line_length)
if (cleansed_line.count(';') > 1 and
# for loops are allowed two ;'s (and may run over two lines).
@@ -2890,9 +4412,14 @@
# Some more style checks
CheckBraces(filename, clean_lines, linenum, error)
- CheckEmptyLoopBody(filename, clean_lines, linenum, error)
- CheckAccess(filename, clean_lines, linenum, nesting_state, error)
+ CheckTrailingSemicolon(filename, clean_lines, linenum, error)
+ CheckEmptyBlockBody(filename, clean_lines, linenum, error)
CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
+ CheckOperatorSpacing(filename, clean_lines, linenum, error)
+ CheckParenthesisSpacing(filename, clean_lines, linenum, error)
+ CheckCommaSpacing(filename, clean_lines, linenum, error)
+ CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error)
+ CheckSpacingForFunctionCall(filename, clean_lines, linenum, error)
CheckCheck(filename, clean_lines, linenum, error)
CheckAltTokens(filename, clean_lines, linenum, error)
classinfo = nesting_state.InnermostClass()
@@ -2900,7 +4427,6 @@
CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
-_RE_PATTERN_INCLUDE_NEW_STYLE = re.compile(r'#include +"[^/]+\.h"')
_RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
# Matches the first component of a filename delimited by -s and _s. That is:
# _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
@@ -2937,23 +4463,6 @@
return os.path.splitext(filename)[0]
-def _IsTestFilename(filename):
- """Determines if the given filename has a suffix that identifies it as a test.
-
- Args:
- filename: The input filename.
-
- Returns:
- True if 'filename' looks like a test, False otherwise.
- """
- if (filename.endswith('_test.cc') or
- filename.endswith('_unittest.cc') or
- filename.endswith('_regtest.cc')):
- return True
- else:
- return False
-
-
def _ClassifyInclude(fileinfo, include, is_system):
"""Figures out what kind of header 'include' is.
@@ -2980,8 +4489,7 @@
"""
# This is a list of all standard c++ header files, except
# those already checked for above.
- is_stl_h = include in _STL_HEADERS
- is_cpp_h = is_stl_h or include in _CPP_HEADERS
+ is_cpp_h = include in _CPP_HEADERS
if is_system:
if is_cpp_h:
@@ -3030,11 +4538,17 @@
error: The function to call with any errors found.
"""
fileinfo = FileInfo(filename)
-
line = clean_lines.lines[linenum]
# "include" should use the new style "foo/bar.h" instead of just "bar.h"
- if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line):
+ # Only do this check if the included header follows google naming
+ # conventions. If not, assume that it's a 3rd party API that
+ # requires special include conventions.
+ #
+ # We also make an exception for Lua headers, which follow google
+ # naming convention but not the include convention.
+ match = Match(r'#include\s*"([^/]+\.h)"', line)
+ if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):
error(filename, linenum, 'build/include', 4,
'Include the directory when naming .h files')
@@ -3045,12 +4559,17 @@
if match:
include = match.group(2)
is_system = (match.group(1) == '<')
- if include in include_state:
+ duplicate_line = include_state.FindHeader(include)
+ if duplicate_line >= 0:
error(filename, linenum, 'build/include', 4,
'"%s" already included at %s:%s' %
- (include, filename, include_state[include]))
- else:
- include_state[include] = linenum
+ (include, filename, duplicate_line))
+ elif (include.endswith('.cc') and
+ os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)):
+ error(filename, linenum, 'build/include', 4,
+ 'Do not include .cc files from other packages')
+ elif not _THIRD_PARTY_HEADERS_PATTERN.match(include):
+ include_state.include_list[-1].append((include, linenum))
# We want to ensure that headers appear in the right order:
# 1) for foo.cc, foo.h (preferred location)
@@ -3069,23 +4588,17 @@
error(filename, linenum, 'build/include_order', 4,
'%s. Should be: %s.h, c system, c++ system, other.' %
(error_message, fileinfo.BaseName()))
- if not include_state.IsInAlphabeticalOrder(include):
+ canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
+ if not include_state.IsInAlphabeticalOrder(
+ clean_lines, linenum, canonical_include):
error(filename, linenum, 'build/include_alpha', 4,
'Include "%s" not in alphabetical order' % include)
+ include_state.SetLastHeader(canonical_include)
- # Look for any of the stream classes that are part of standard C++.
- match = _RE_PATTERN_INCLUDE.match(line)
- if match:
- include = match.group(2)
- if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include):
- # Many unit tests use cout, so we exempt them.
- if not _IsTestFilename(filename):
- error(filename, linenum, 'readability/streams', 3,
- 'Streams are highly discouraged.')
def _GetTextInside(text, start_pattern):
- """Retrieves all the text between matching open and close parentheses.
+ r"""Retrieves all the text between matching open and close parentheses.
Given a string of lines and a regular expression string, retrieve all the text
following the expression and between opening punctuation symbols like
@@ -3104,7 +4617,7 @@
The extracted text.
None if either the opening string or ending punctuation could not be found.
"""
- # TODO(sugawarayu): Audit cpplint.py to see what places could be profitably
+ # TODO(unknown): Audit cpplint.py to see what places could be profitably
# rewritten to use _GetTextInside (and use inferior regexp matching today).
# Give opening punctuations to get the matching close-punctuations.
@@ -3140,8 +4653,37 @@
return text[start_position:position - 1]
-def CheckLanguage(filename, clean_lines, linenum, file_extension, include_state,
- error):
+# Patterns for matching call-by-reference parameters.
+#
+# Supports nested templates up to 2 levels deep using this messy pattern:
+# < (?: < (?: < [^<>]*
+# >
+# | [^<>] )*
+# >
+# | [^<>] )*
+# >
+_RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*
+_RE_PATTERN_TYPE = (
+ r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?'
+ r'(?:\w|'
+ r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|'
+ r'::)+')
+# A call-by-reference parameter ends with '& identifier'.
+_RE_PATTERN_REF_PARAM = re.compile(
+ r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*'
+ r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]')
+# A call-by-const-reference parameter either ends with 'const& identifier'
+# or looks like 'const type& identifier' when 'type' is atomic.
+_RE_PATTERN_CONST_REF_PARAM = (
+ r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT +
+ r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')')
+# Stream types.
+_RE_PATTERN_REF_STREAM_PARAM = (
+ r'(?:.*stream\s*&\s*' + _RE_PATTERN_IDENT + r')')
+
+
+def CheckLanguage(filename, clean_lines, linenum, file_extension,
+ include_state, nesting_state, error):
"""Checks rules from the 'C++ language rules' section of cppguide.html.
Some of these rules are hard to test (function overloading, using
@@ -3153,6 +4695,8 @@
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
include_state: An _IncludeState instance in which the headers are inserted.
+ nesting_state: A NestingState instance which maintains information about
+ the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# If the line is empty or consists of entirely a comment, no need to
@@ -3166,132 +4710,25 @@
CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
return
- # Create an extended_line, which is the concatenation of the current and
- # next lines, for more effective checking of code that may span more than one
- # line.
- if linenum + 1 < clean_lines.NumLines():
- extended_line = line + clean_lines.elided[linenum + 1]
- else:
- extended_line = line
+ # Reset include state across preprocessor directives. This is meant
+ # to silence warnings for conditional includes.
+ match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line)
+ if match:
+ include_state.ResetSection(match.group(1))
# Make Windows paths like Unix.
fullname = os.path.abspath(filename).replace('\\', '/')
- # TODO(unknown): figure out if they're using default arguments in fn proto.
+ # Perform other checks now that we are sure that this is not an include line
+ CheckCasts(filename, clean_lines, linenum, error)
+ CheckGlobalStatic(filename, clean_lines, linenum, error)
+ CheckPrintf(filename, clean_lines, linenum, error)
- # Check for non-const references in functions. This is tricky because &
- # is also used to take the address of something. We allow <> for templates,
- # (ignoring whatever is between the braces) and : for classes.
- # These are complicated re's. They try to capture the following:
- # paren (for fn-prototype start), typename, &, varname. For the const
- # version, we're willing for const to be before typename or after
- # Don't check the implementation on same line.
- fnline = line.split('{', 1)[0]
- if (len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) >
- len(re.findall(r'\([^()]*\bconst\s+(?:typename\s+)?(?:struct\s+)?'
- r'(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) +
- len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+\s+const(\s?&|&\s?)[\w]+',
- fnline))):
-
- # We allow non-const references in a few standard places, like functions
- # called "swap()" or iostream operators like "<<" or ">>". We also filter
- # out for loops, which lint otherwise mistakenly thinks are functions.
- if not Search(
- r'(for|swap|Swap|operator[<>][<>])\s*\(\s*'
- r'(?:(?:typename\s*)?[\w:]|<.*>)+\s*&',
- fnline):
- error(filename, linenum, 'runtime/references', 2,
- 'Is this a non-const reference? '
- 'If so, make const or use a pointer.')
-
- # Check to see if they're using an conversion function cast.
- # I just try to capture the most common basic types, though there are more.
- # Parameterless conversion functions, such as bool(), are allowed as they are
- # probably a member operator declaration or default constructor.
- match = Search(
- r'(\bnew\s+)?\b' # Grab 'new' operator, if it's there
- r'(int|float|double|bool|char|int32|uint32|int64|uint64)\([^)]', line)
- if match:
- # gMock methods are defined using some variant of MOCK_METHODx(name, type)
- # where type may be float(), int(string), etc. Without context they are
- # virtually indistinguishable from int(x) casts. Likewise, gMock's
- # MockCallback takes a template parameter of the form return_type(arg_type),
- # which looks much like the cast we're trying to detect.
- if (match.group(1) is None and # If new operator, then this isn't a cast
- not (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
- Match(r'^\s*MockCallback<.*>', line))):
- # Try a bit harder to catch gmock lines: the only place where
- # something looks like an old-style cast is where we declare the
- # return type of the mocked method, and the only time when we
- # are missing context is if MOCK_METHOD was split across
- # multiple lines (for example http://go/hrfhr ), so we only need
- # to check the previous line for MOCK_METHOD.
- if (linenum == 0 or
- not Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(\S+,\s*$',
- clean_lines.elided[linenum - 1])):
- error(filename, linenum, 'readability/casting', 4,
- 'Using deprecated casting style. '
- 'Use static_cast<%s>(...) instead' %
- match.group(2))
-
- CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
- 'static_cast',
- r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
-
- # This doesn't catch all cases. Consider (const char * const)"hello".
- #
- # (char *) "foo" should always be a const_cast (reinterpret_cast won't
- # compile).
- if CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
- 'const_cast', r'\((char\s?\*+\s?)\)\s*"', error):
- pass
- else:
- # Check pointer casts for other than string constants
- CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
- 'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error)
-
- # In addition, we look for people taking the address of a cast. This
- # is dangerous -- casts can assign to temporaries, so the pointer doesn't
- # point where you think.
- if Search(
- r'(&\([^)]+\)[\w(])|(&(static|dynamic|reinterpret)_cast\b)', line):
- error(filename, linenum, 'runtime/casting', 4,
- ('Are you taking an address of a cast? '
- 'This is dangerous: could be a temp var. '
- 'Take the address before doing the cast, rather than after'))
-
- # Check for people declaring static/global STL strings at the top level.
- # This is dangerous because the C++ language does not guarantee that
- # globals with constructors are initialized before the first access.
- match = Match(
- r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)',
- line)
- # Make sure it's not a function.
- # Function template specialization looks like: "string foo<Type>(...".
- # Class template definitions look like: "string Foo<Type>::Method(...".
- if match and not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)?\s*\(([^"]|$)',
- match.group(3)):
- error(filename, linenum, 'runtime/string', 4,
- 'For a static/global string constant, use a C style string instead: '
- '"%schar %s[]".' %
- (match.group(1), match.group(2)))
-
- # Check that we're not using RTTI outside of testing code.
- if Search(r'\bdynamic_cast<', line) and not _IsTestFilename(filename):
- error(filename, linenum, 'runtime/rtti', 5,
- 'Do not use dynamic_cast<>. If you need to cast within a class '
- "hierarchy, use static_cast<> to upcast. Google doesn't support "
- 'RTTI.')
-
- if Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line):
- error(filename, linenum, 'runtime/init', 4,
- 'You seem to be initializing a member variable with itself.')
-
- if file_extension == 'h':
+ if IsHeaderExtension(file_extension):
# TODO(unknown): check that 1-arg constructors are explicit.
# How to tell it's a constructor?
# (handled in CheckForNonStandardConstructs for now)
- # TODO(unknown): check that classes have DISALLOW_EVIL_CONSTRUCTORS
+ # TODO(unknown): check that classes declare or disable copy/assign
# (level 1 error)
pass
@@ -3307,27 +4744,6 @@
error(filename, linenum, 'runtime/int', 4,
'Use int16/int64/etc, rather than the C type %s' % match.group(1))
- # When snprintf is used, the second argument shouldn't be a literal.
- match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
- if match and match.group(2) != '0':
- # If 2nd arg is zero, snprintf is used to calculate size.
- error(filename, linenum, 'runtime/printf', 3,
- 'If you can, use sizeof(%s) instead of %s as the 2nd arg '
- 'to snprintf.' % (match.group(1), match.group(2)))
-
- # Check if some verboten C functions are being used.
- if Search(r'\bsprintf\b', line):
- error(filename, linenum, 'runtime/printf', 5,
- 'Never use sprintf. Use snprintf instead.')
- match = Search(r'\b(strcpy|strcat)\b', line)
- if match:
- error(filename, linenum, 'runtime/printf', 4,
- 'Almost always, snprintf is better than %s' % match.group(1))
-
- if Search(r'\bsscanf\b', line):
- error(filename, linenum, 'runtime/printf', 1,
- 'sscanf can be ok, but is slow and can overflow buffers.')
-
# Check if some verboten operator overloading is going on
# TODO(unknown): catch out-of-line unary operator&:
# class X {};
@@ -3347,7 +4763,7 @@
# Check for potential format string bugs like printf(foo).
# We constrain the pattern not to pick things like DocidForPrintf(foo).
# Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
- # TODO(sugawarayu): Catch the following case. Need to change the calling
+ # TODO(unknown): Catch the following case. Need to change the calling
# convention of the whole function to process multiple line to handle it.
# printf(
# boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
@@ -3412,49 +4828,453 @@
'Do not use variable-length arrays. Use an appropriately named '
"('k' followed by CamelCase) compile-time constant for the size.")
- # If DISALLOW_EVIL_CONSTRUCTORS, DISALLOW_COPY_AND_ASSIGN, or
- # DISALLOW_IMPLICIT_CONSTRUCTORS is present, then it should be the last thing
- # in the class declaration.
- match = Match(
- (r'\s*'
- r'(DISALLOW_(EVIL_CONSTRUCTORS|COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))'
- r'\(.*\);$'),
- line)
- if match and linenum + 1 < clean_lines.NumLines():
- next_line = clean_lines.elided[linenum + 1]
- # We allow some, but not all, declarations of variables to be present
- # in the statement that defines the class. The [\w\*,\s]* fragment of
- # the regular expression below allows users to declare instances of
- # the class or pointers to instances, but not less common types such
- # as function pointers or arrays. It's a tradeoff between allowing
- # reasonable code and avoiding trying to parse more C++ using regexps.
- if not Search(r'^\s*}[\w\*,\s]*;', next_line):
- error(filename, linenum, 'readability/constructors', 3,
- match.group(1) + ' should be the last thing in the class')
-
# Check for use of unnamed namespaces in header files. Registration
# macros are typically OK, so we allow use of "namespace {" on lines
# that end with backslashes.
- if (file_extension == 'h'
+ if (IsHeaderExtension(file_extension)
and Search(r'\bnamespace\s*{', line)
and line[-1] != '\\'):
error(filename, linenum, 'build/namespaces', 4,
'Do not use unnamed namespaces in header files. See '
- 'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
+ 'https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
' for more information.')
-def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern,
- error):
- """Checks for a C-style cast by looking for the pattern.
-
- This also handles sizeof(type) warnings, due to similarity of content.
+def CheckGlobalStatic(filename, clean_lines, linenum, error):
+ """Check for unsafe global or static objects.
Args:
filename: The name of the current file.
+ clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
- line: The line of code to check.
- raw_line: The raw line of code to check, with comments.
+ error: The function to call with any errors found.
+ """
+ line = clean_lines.elided[linenum]
+
+ # Match two lines at a time to support multiline declarations
+ if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line):
+ line += clean_lines.elided[linenum + 1].strip()
+
+ # Check for people declaring static/global STL strings at the top level.
+ # This is dangerous because the C++ language does not guarantee that
+ # globals with constructors are initialized before the first access, and
+ # also because globals can be destroyed when some threads are still running.
+ # TODO(unknown): Generalize this to also find static unique_ptr instances.
+ # TODO(unknown): File bugs for clang-tidy to find these.
+ match = Match(
+ r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +'
+ r'([a-zA-Z0-9_:]+)\b(.*)',
+ line)
+
+ # Remove false positives:
+ # - String pointers (as opposed to values).
+ # string *pointer
+ # const string *pointer
+ # string const *pointer
+ # string *const pointer
+ #
+ # - Functions and template specializations.
+ # string Function<Type>(...
+ # string Class<Type>::Method(...
+ #
+ # - Operators. These are matched separately because operator names
+ # cross non-word boundaries, and trying to match both operators
+ # and functions at the same time would decrease accuracy of
+ # matching identifiers.
+ # string Class::operator*()
+ if (match and
+ not Search(r'\bstring\b(\s+const)?\s*[\*\&]\s*(const\s+)?\w', line) and
+ not Search(r'\boperator\W', line) and
+ not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))):
+ if Search(r'\bconst\b', line):
+ error(filename, linenum, 'runtime/string', 4,
+ 'For a static/global string constant, use a C style string '
+ 'instead: "%schar%s %s[]".' %
+ (match.group(1), match.group(2) or '', match.group(3)))
+ else:
+ error(filename, linenum, 'runtime/string', 4,
+ 'Static/global string variables are not permitted.')
+
+ if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or
+ Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)):
+ error(filename, linenum, 'runtime/init', 4,
+ 'You seem to be initializing a member variable with itself.')
+
+
+def CheckPrintf(filename, clean_lines, linenum, error):
+ """Check for printf related issues.
+
+ Args:
+ filename: The name of the current file.
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: The number of the line to check.
+ error: The function to call with any errors found.
+ """
+ line = clean_lines.elided[linenum]
+
+ # When snprintf is used, the second argument shouldn't be a literal.
+ match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
+ if match and match.group(2) != '0':
+ # If 2nd arg is zero, snprintf is used to calculate size.
+ error(filename, linenum, 'runtime/printf', 3,
+ 'If you can, use sizeof(%s) instead of %s as the 2nd arg '
+ 'to snprintf.' % (match.group(1), match.group(2)))
+
+ # Check if some verboten C functions are being used.
+ if Search(r'\bsprintf\s*\(', line):
+ error(filename, linenum, 'runtime/printf', 5,
+ 'Never use sprintf. Use snprintf instead.')
+ match = Search(r'\b(strcpy|strcat)\s*\(', line)
+ if match:
+ error(filename, linenum, 'runtime/printf', 4,
+ 'Almost always, snprintf is better than %s' % match.group(1))
+
+
+def IsDerivedFunction(clean_lines, linenum):
+ """Check if current line contains an inherited function.
+
+ Args:
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: The number of the line to check.
+ Returns:
+ True if current line contains a function with "override"
+ virt-specifier.
+ """
+ # Scan back a few lines for start of current function
+ for i in xrange(linenum, max(-1, linenum - 10), -1):
+ match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i])
+ if match:
+ # Look for "override" after the matching closing parenthesis
+ line, _, closing_paren = CloseExpression(
+ clean_lines, i, len(match.group(1)))
+ return (closing_paren >= 0 and
+ Search(r'\boverride\b', line[closing_paren:]))
+ return False
+
+
+def IsOutOfLineMethodDefinition(clean_lines, linenum):
+ """Check if current line contains an out-of-line method definition.
+
+ Args:
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: The number of the line to check.
+ Returns:
+ True if current line contains an out-of-line method definition.
+ """
+ # Scan back a few lines for start of current function
+ for i in xrange(linenum, max(-1, linenum - 10), -1):
+ if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):
+ return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None
+ return False
+
+
+def IsInitializerList(clean_lines, linenum):
+ """Check if current line is inside constructor initializer list.
+
+ Args:
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: The number of the line to check.
+ Returns:
+ True if current line appears to be inside constructor initializer
+ list, False otherwise.
+ """
+ for i in xrange(linenum, 1, -1):
+ line = clean_lines.elided[i]
+ if i == linenum:
+ remove_function_body = Match(r'^(.*)\{\s*$', line)
+ if remove_function_body:
+ line = remove_function_body.group(1)
+
+ if Search(r'\s:\s*\w+[({]', line):
+ # A lone colon tend to indicate the start of a constructor
+ # initializer list. It could also be a ternary operator, which
+ # also tend to appear in constructor initializer lists as
+ # opposed to parameter lists.
+ return True
+ if Search(r'\}\s*,\s*$', line):
+ # A closing brace followed by a comma is probably the end of a
+ # brace-initialized member in constructor initializer list.
+ return True
+ if Search(r'[{};]\s*$', line):
+ # Found one of the following:
+ # - A closing brace or semicolon, probably the end of the previous
+ # function.
+ # - An opening brace, probably the start of current class or namespace.
+ #
+ # Current line is probably not inside an initializer list since
+ # we saw one of those things without seeing the starting colon.
+ return False
+
+ # Got to the beginning of the file without seeing the start of
+ # constructor initializer list.
+ return False
+
+
+def CheckForNonConstReference(filename, clean_lines, linenum,
+ nesting_state, error):
+ """Check for non-const references.
+
+ Separate from CheckLanguage since it scans backwards from current
+ line, instead of scanning forward.
+
+ Args:
+ filename: The name of the current file.
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: The number of the line to check.
+ nesting_state: A NestingState instance which maintains information about
+ the current stack of nested blocks being parsed.
+ error: The function to call with any errors found.
+ """
+ # Do nothing if there is no '&' on current line.
+ line = clean_lines.elided[linenum]
+ if '&' not in line:
+ return
+
+ # If a function is inherited, current function doesn't have much of
+ # a choice, so any non-const references should not be blamed on
+ # derived function.
+ if IsDerivedFunction(clean_lines, linenum):
+ return
+
+ # Don't warn on out-of-line method definitions, as we would warn on the
+ # in-line declaration, if it isn't marked with 'override'.
+ if IsOutOfLineMethodDefinition(clean_lines, linenum):
+ return
+
+ # Long type names may be broken across multiple lines, usually in one
+ # of these forms:
+ # LongType
+ # ::LongTypeContinued &identifier
+ # LongType::
+ # LongTypeContinued &identifier
+ # LongType<
+ # ...>::LongTypeContinued &identifier
+ #
+ # If we detected a type split across two lines, join the previous
+ # line to current line so that we can match const references
+ # accordingly.
+ #
+ # Note that this only scans back one line, since scanning back
+ # arbitrary number of lines would be expensive. If you have a type
+ # that spans more than 2 lines, please use a typedef.
+ if linenum > 1:
+ previous = None
+ if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
+ # previous_line\n + ::current_line
+ previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',
+ clean_lines.elided[linenum - 1])
+ elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
+ # previous_line::\n + current_line
+ previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',
+ clean_lines.elided[linenum - 1])
+ if previous:
+ line = previous.group(1) + line.lstrip()
+ else:
+ # Check for templated parameter that is split across multiple lines
+ endpos = line.rfind('>')
+ if endpos > -1:
+ (_, startline, startpos) = ReverseCloseExpression(
+ clean_lines, linenum, endpos)
+ if startpos > -1 and startline < linenum:
+ # Found the matching < on an earlier line, collect all
+ # pieces up to current line.
+ line = ''
+ for i in xrange(startline, linenum + 1):
+ line += clean_lines.elided[i].strip()
+
+ # Check for non-const references in function parameters. A single '&' may
+ # found in the following places:
+ # inside expression: binary & for bitwise AND
+ # inside expression: unary & for taking the address of something
+ # inside declarators: reference parameter
+ # We will exclude the first two cases by checking that we are not inside a
+ # function body, including one that was just introduced by a trailing '{'.
+ # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].
+ if (nesting_state.previous_stack_top and
+ not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or
+ isinstance(nesting_state.previous_stack_top, _NamespaceInfo))):
+ # Not at toplevel, not within a class, and not within a namespace
+ return
+
+ # Avoid initializer lists. We only need to scan back from the
+ # current line for something that starts with ':'.
+ #
+ # We don't need to check the current line, since the '&' would
+ # appear inside the second set of parentheses on the current line as
+ # opposed to the first set.
+ if linenum > 0:
+ for i in xrange(linenum - 1, max(0, linenum - 10), -1):
+ previous_line = clean_lines.elided[i]
+ if not Search(r'[),]\s*$', previous_line):
+ break
+ if Match(r'^\s*:\s+\S', previous_line):
+ return
+
+ # Avoid preprocessors
+ if Search(r'\\\s*$', line):
+ return
+
+ # Avoid constructor initializer lists
+ if IsInitializerList(clean_lines, linenum):
+ return
+
+ # We allow non-const references in a few standard places, like functions
+ # called "swap()" or iostream operators like "<<" or ">>". Do not check
+ # those function parameters.
+ #
+ # We also accept & in static_assert, which looks like a function but
+ # it's actually a declaration expression.
+ whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'
+ r'operator\s*[<>][<>]|'
+ r'static_assert|COMPILE_ASSERT'
+ r')\s*\(')
+ if Search(whitelisted_functions, line):
+ return
+ elif not Search(r'\S+\([^)]*$', line):
+ # Don't see a whitelisted function on this line. Actually we
+ # didn't see any function name on this line, so this is likely a
+ # multi-line parameter list. Try a bit harder to catch this case.
+ for i in xrange(2):
+ if (linenum > i and
+ Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):
+ return
+
+ decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body
+ for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):
+ if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and
+ not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)):
+ error(filename, linenum, 'runtime/references', 2,
+ 'Is this a non-const reference? '
+ 'If so, make const or use a pointer: ' +
+ ReplaceAll(' *<', '<', parameter))
+
+
+def CheckCasts(filename, clean_lines, linenum, error):
+ """Various cast related checks.
+
+ Args:
+ filename: The name of the current file.
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: The number of the line to check.
+ error: The function to call with any errors found.
+ """
+ line = clean_lines.elided[linenum]
+
+ # Check to see if they're using an conversion function cast.
+ # I just try to capture the most common basic types, though there are more.
+ # Parameterless conversion functions, such as bool(), are allowed as they are
+ # probably a member operator declaration or default constructor.
+ match = Search(
+ r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b'
+ r'(int|float|double|bool|char|int32|uint32|int64|uint64)'
+ r'(\([^)].*)', line)
+ expecting_function = ExpectingFunctionArgs(clean_lines, linenum)
+ if match and not expecting_function:
+ matched_type = match.group(2)
+
+ # matched_new_or_template is used to silence two false positives:
+ # - New operators
+ # - Template arguments with function types
+ #
+ # For template arguments, we match on types immediately following
+ # an opening bracket without any spaces. This is a fast way to
+ # silence the common case where the function type is the first
+ # template argument. False negative with less-than comparison is
+ # avoided because those operators are usually followed by a space.
+ #
+ # function<double(double)> // bracket + no space = false positive
+ # value < double(42) // bracket + space = true positive
+ matched_new_or_template = match.group(1)
+
+ # Avoid arrays by looking for brackets that come after the closing
+ # parenthesis.
+ if Match(r'\([^()]+\)\s*\[', match.group(3)):
+ return
+
+ # Other things to ignore:
+ # - Function pointers
+ # - Casts to pointer types
+ # - Placement new
+ # - Alias declarations
+ matched_funcptr = match.group(3)
+ if (matched_new_or_template is None and
+ not (matched_funcptr and
+ (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',
+ matched_funcptr) or
+ matched_funcptr.startswith('(*)'))) and
+ not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and
+ not Search(r'new\(\S+\)\s*' + matched_type, line)):
+ error(filename, linenum, 'readability/casting', 4,
+ 'Using deprecated casting style. '
+ 'Use static_cast<%s>(...) instead' %
+ matched_type)
+
+ if not expecting_function:
+ CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',
+ r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
+
+ # This doesn't catch all cases. Consider (const char * const)"hello".
+ #
+ # (char *) "foo" should always be a const_cast (reinterpret_cast won't
+ # compile).
+ if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast',
+ r'\((char\s?\*+\s?)\)\s*"', error):
+ pass
+ else:
+ # Check pointer casts for other than string constants
+ CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',
+ r'\((\w+\s?\*+\s?)\)', error)
+
+ # In addition, we look for people taking the address of a cast. This
+ # is dangerous -- casts can assign to temporaries, so the pointer doesn't
+ # point where you think.
+ #
+ # Some non-identifier character is required before the '&' for the
+ # expression to be recognized as a cast. These are casts:
+ # expression = &static_cast<int*>(temporary());
+ # function(&(int*)(temporary()));
+ #
+ # This is not a cast:
+ # reference_type&(int* function_param);
+ match = Search(
+ r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|'
+ r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line)
+ if match:
+ # Try a better error message when the & is bound to something
+ # dereferenced by the casted pointer, as opposed to the casted
+ # pointer itself.
+ parenthesis_error = False
+ match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line)
+ if match:
+ _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1)))
+ if x1 >= 0 and clean_lines.elided[y1][x1] == '(':
+ _, y2, x2 = CloseExpression(clean_lines, y1, x1)
+ if x2 >= 0:
+ extended_line = clean_lines.elided[y2][x2:]
+ if y2 < clean_lines.NumLines() - 1:
+ extended_line += clean_lines.elided[y2 + 1]
+ if Match(r'\s*(?:->|\[)', extended_line):
+ parenthesis_error = True
+
+ if parenthesis_error:
+ error(filename, linenum, 'readability/casting', 4,
+ ('Are you taking an address of something dereferenced '
+ 'from a cast? Wrapping the dereferenced expression in '
+ 'parentheses will make the binding more obvious'))
+ else:
+ error(filename, linenum, 'runtime/casting', 4,
+ ('Are you taking an address of a cast? '
+ 'This is dangerous: could be a temp var. '
+ 'Take the address before doing the cast, rather than after'))
+
+
+def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
+ """Checks for a C-style cast by looking for the pattern.
+
+ Args:
+ filename: The name of the current file.
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: The number of the line to check.
cast_type: The string for the C++ cast to recommend. This is either
reinterpret_cast, static_cast, or const_cast, depending.
pattern: The regular expression used to find C-style casts.
@@ -3464,45 +5284,34 @@
True if an error was emitted.
False otherwise.
"""
+ line = clean_lines.elided[linenum]
match = Search(pattern, line)
if not match:
return False
- # e.g., sizeof(int)
- sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1])
- if sizeof_match:
- error(filename, linenum, 'runtime/sizeof', 1,
- 'Using sizeof(type). Use sizeof(varname) instead if possible')
- return True
-
- # operator++(int) and operator--(int)
- if (line[0:match.start(1) - 1].endswith(' operator++') or
- line[0:match.start(1) - 1].endswith(' operator--')):
+ # Exclude lines with keywords that tend to look like casts
+ context = line[0:match.start(1) - 1]
+ if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):
return False
- remainder = line[match.end(0):]
+ # Try expanding current context to see if we one level of
+ # parentheses inside a macro.
+ if linenum > 0:
+ for i in xrange(linenum - 1, max(0, linenum - 5), -1):
+ context = clean_lines.elided[i] + context
+ if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):
+ return False
- # The close paren is for function pointers as arguments to a function.
- # eg, void foo(void (*bar)(int));
- # The semicolon check is a more basic function check; also possibly a
- # function pointer typedef.
- # eg, void foo(int); or void foo(int) const;
- # The equals check is for function pointer assignment.
- # eg, void *(*foo)(int) = ...
- # The > is for MockCallback<...> ...
- #
- # Right now, this will only catch cases where there's a single argument, and
- # it's unnamed. It should probably be expanded to check for multiple
- # arguments with some unnamed.
- function_match = Match(r'\s*(\)|=|(const)?\s*(;|\{|throw\(\)|>))', remainder)
- if function_match:
- if (not function_match.group(3) or
- function_match.group(3) == ';' or
- ('MockCallback<' not in raw_line and
- '/*' not in raw_line)):
- error(filename, linenum, 'readability/function', 3,
- 'All parameters should be named in a function')
- return True
+ # operator++(int) and operator--(int)
+ if context.endswith(' operator++') or context.endswith(' operator--'):
+ return False
+
+ # A single unnamed argument for a function tends to look like old style cast.
+ # If we see those, don't issue warnings for deprecated casts.
+ remainder = line[match.end(0):]
+ if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',
+ remainder):
+ return False
# At this point, all that should be left is actual casts.
error(filename, linenum, 'readability/casting', 4,
@@ -3512,6 +5321,28 @@
return True
+def ExpectingFunctionArgs(clean_lines, linenum):
+ """Checks whether where function type arguments are expected.
+
+ Args:
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: The number of the line to check.
+
+ Returns:
+ True if the line at 'linenum' is inside something that expects arguments
+ of function types.
+ """
+ line = clean_lines.elided[linenum]
+ return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
+ (linenum >= 2 and
+ (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
+ clean_lines.elided[linenum - 1]) or
+ Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
+ clean_lines.elided[linenum - 2]) or
+ Search(r'\bstd::m?function\s*\<\s*$',
+ clean_lines.elided[linenum - 1]))))
+
+
_HEADERS_CONTAINING_TEMPLATES = (
('<deque>', ('deque',)),
('<functional>', ('unary_function', 'binary_function',
@@ -3534,11 +5365,15 @@
('<limits>', ('numeric_limits',)),
('<list>', ('list',)),
('<map>', ('map', 'multimap',)),
- ('<memory>', ('allocator',)),
+ ('<memory>', ('allocator', 'make_shared', 'make_unique', 'shared_ptr',
+ 'unique_ptr', 'weak_ptr')),
('<queue>', ('queue', 'priority_queue',)),
('<set>', ('set', 'multiset',)),
('<stack>', ('stack',)),
('<string>', ('char_traits', 'basic_string',)),
+ ('<tuple>', ('tuple',)),
+ ('<unordered_map>', ('unordered_map', 'unordered_multimap')),
+ ('<unordered_set>', ('unordered_set', 'unordered_multiset')),
('<utility>', ('pair',)),
('<vector>', ('vector',)),
@@ -3549,18 +5384,26 @@
('<slist>', ('slist',)),
)
+_HEADERS_MAYBE_TEMPLATES = (
+ ('<algorithm>', ('copy', 'max', 'min', 'min_element', 'sort',
+ 'transform',
+ )),
+ ('<utility>', ('forward', 'make_pair', 'move', 'swap')),
+ )
+
_RE_PATTERN_STRING = re.compile(r'\bstring\b')
-_re_pattern_algorithm_header = []
-for _template in ('copy', 'max', 'min', 'min_element', 'sort', 'swap',
- 'transform'):
- # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
- # type::max().
- _re_pattern_algorithm_header.append(
- (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
- _template,
- '<algorithm>'))
+_re_pattern_headers_maybe_templates = []
+for _header, _templates in _HEADERS_MAYBE_TEMPLATES:
+ for _template in _templates:
+ # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
+ # type::max().
+ _re_pattern_headers_maybe_templates.append(
+ (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
+ _template,
+ _header))
+# Other scripts may reach in and modify this pattern.
_re_pattern_templates = []
for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
for _template in _templates:
@@ -3600,13 +5443,13 @@
string: the additional prefix needed to open the header file.
"""
- if not filename_cc.endswith('.cc'):
+ fileinfo = FileInfo(filename_cc)
+ if not fileinfo.IsSource():
return (False, '')
- filename_cc = filename_cc[:-len('.cc')]
- if filename_cc.endswith('_unittest'):
- filename_cc = filename_cc[:-len('_unittest')]
- elif filename_cc.endswith('_test'):
- filename_cc = filename_cc[:-len('_test')]
+ filename_cc = filename_cc[:-len(fileinfo.Extension())]
+ matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo.BaseName())
+ if matched_test_suffix:
+ filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]
filename_cc = filename_cc.replace('/public/', '/')
filename_cc = filename_cc.replace('/internal/', '/')
@@ -3625,12 +5468,12 @@
return files_belong_to_same_module, common_path
-def UpdateIncludeState(filename, include_state, io=codecs):
- """Fill up the include_state with new includes found from the file.
+def UpdateIncludeState(filename, include_dict, io=codecs):
+ """Fill up the include_dict with new includes found from the file.
Args:
filename: the name of the header to read.
- include_state: an _IncludeState instance in which the headers are inserted.
+ include_dict: a dictionary in which the headers are inserted.
io: The io factory to use to read the file. Provided for testability.
Returns:
@@ -3648,9 +5491,7 @@
match = _RE_PATTERN_INCLUDE.search(clean_line)
if match:
include = match.group(2)
- # The value formatting is cute, but not really used right now.
- # What matters here is that the key is in include_state.
- include_state.setdefault(include, '%s:%d' % (filename, linenum))
+ include_dict.setdefault(include, linenum)
return True
@@ -3689,7 +5530,7 @@
if prefix.endswith('std::') or not prefix.endswith('::'):
required['<string>'] = (linenum, 'string')
- for pattern, template, header in _re_pattern_algorithm_header:
+ for pattern, template, header in _re_pattern_headers_maybe_templates:
if pattern.search(line):
required[header] = (linenum, template)
@@ -3698,13 +5539,19 @@
continue
for pattern, template, header in _re_pattern_templates:
- if pattern.search(line):
- required[header] = (linenum, template)
+ matched = pattern.search(line)
+ if matched:
+ # Don't warn about IWYU in non-STL namespaces:
+ # (We check only the first match per line; good enough.)
+ prefix = line[:matched.start()]
+ if prefix.endswith('std::') or not prefix.endswith('::'):
+ required[header] = (linenum, template)
# The policy is that if you #include something in foo.h you don't need to
# include it again in foo.cc. Here, we will look at possible includes.
- # Let's copy the include_state so it is only messed up within this function.
- include_state = include_state.copy()
+ # Let's flatten the include_state include_list and copy it into a dictionary.
+ include_dict = dict([item for sublist in include_state.include_list
+ for item in sublist])
# Did we find the header for this file (if any) and successfully load it?
header_found = False
@@ -3721,13 +5568,13 @@
# instead of 'foo_flymake.h'
abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
- # include_state is modified during iteration, so we iterate over a copy of
+ # include_dict is modified during iteration, so we iterate over a copy of
# the keys.
- header_keys = include_state.keys()
+ header_keys = include_dict.keys()
for header in header_keys:
(same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
fullpath = common_path + header
- if same_module and UpdateIncludeState(fullpath, include_state, io):
+ if same_module and UpdateIncludeState(fullpath, include_dict, io):
header_found = True
# If we can't find the header file for a .cc, assume it's because we don't
@@ -3741,7 +5588,7 @@
# All the lines have been processed, report the errors found.
for required_header_unstripped in required:
template = required[required_header_unstripped][1]
- if required_header_unstripped.strip('<>"') not in include_state:
+ if required_header_unstripped.strip('<>"') not in include_dict:
error(filename, required[required_header_unstripped][0],
'build/include_what_you_use', 4,
'Add #include ' + required_header_unstripped + ' for ' + template)
@@ -3753,7 +5600,7 @@
def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
"""Check that make_pair's template arguments are deduced.
- G++ 4.6 in C++0x mode fails badly if make_pair's template arguments are
+ G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are
specified explicitly, and such use isn't intended in any case.
Args:
@@ -3762,8 +5609,7 @@
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
- raw = clean_lines.raw_lines
- line = raw[linenum]
+ line = clean_lines.elided[linenum]
match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
if match:
error(filename, linenum, 'build/explicit_make_pair',
@@ -3772,6 +5618,165 @@
' OR use pair directly OR if appropriate, construct a pair directly')
+def CheckRedundantVirtual(filename, clean_lines, linenum, error):
+ """Check if line contains a redundant "virtual" function-specifier.
+
+ Args:
+ filename: The name of the current file.
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: The number of the line to check.
+ error: The function to call with any errors found.
+ """
+ # Look for "virtual" on current line.
+ line = clean_lines.elided[linenum]
+ virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line)
+ if not virtual: return
+
+ # Ignore "virtual" keywords that are near access-specifiers. These
+ # are only used in class base-specifier and do not apply to member
+ # functions.
+ if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or
+ Match(r'^\s+(public|protected|private)\b', virtual.group(3))):
+ return
+
+ # Ignore the "virtual" keyword from virtual base classes. Usually
+ # there is a column on the same line in these cases (virtual base
+ # classes are rare in google3 because multiple inheritance is rare).
+ if Match(r'^.*[^:]:[^:].*$', line): return
+
+ # Look for the next opening parenthesis. This is the start of the
+ # parameter list (possibly on the next line shortly after virtual).
+ # TODO(unknown): doesn't work if there are virtual functions with
+ # decltype() or other things that use parentheses, but csearch suggests
+ # that this is rare.
+ end_col = -1
+ end_line = -1
+ start_col = len(virtual.group(2))
+ for start_line in xrange(linenum, min(linenum + 3, clean_lines.NumLines())):
+ line = clean_lines.elided[start_line][start_col:]
+ parameter_list = Match(r'^([^(]*)\(', line)
+ if parameter_list:
+ # Match parentheses to find the end of the parameter list
+ (_, end_line, end_col) = CloseExpression(
+ clean_lines, start_line, start_col + len(parameter_list.group(1)))
+ break
+ start_col = 0
+
+ if end_col < 0:
+ return # Couldn't find end of parameter list, give up
+
+ # Look for "override" or "final" after the parameter list
+ # (possibly on the next few lines).
+ for i in xrange(end_line, min(end_line + 3, clean_lines.NumLines())):
+ line = clean_lines.elided[i][end_col:]
+ match = Search(r'\b(override|final)\b', line)
+ if match:
+ error(filename, linenum, 'readability/inheritance', 4,
+ ('"virtual" is redundant since function is '
+ 'already declared as "%s"' % match.group(1)))
+
+ # Set end_col to check whole lines after we are done with the
+ # first line.
+ end_col = 0
+ if Search(r'[^\w]\s*$', line):
+ break
+
+
+def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):
+ """Check if line contains a redundant "override" or "final" virt-specifier.
+
+ Args:
+ filename: The name of the current file.
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: The number of the line to check.
+ error: The function to call with any errors found.
+ """
+ # Look for closing parenthesis nearby. We need one to confirm where
+ # the declarator ends and where the virt-specifier starts to avoid
+ # false positives.
+ line = clean_lines.elided[linenum]
+ declarator_end = line.rfind(')')
+ if declarator_end >= 0:
+ fragment = line[declarator_end:]
+ else:
+ if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
+ fragment = line
+ else:
+ return
+
+ # Check that at most one of "override" or "final" is present, not both
+ if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment):
+ error(filename, linenum, 'readability/inheritance', 4,
+ ('"override" is redundant since function is '
+ 'already declared as "final"'))
+
+
+
+
+# Returns true if we are at a new block, and it is directly
+# inside of a namespace.
+def IsBlockInNameSpace(nesting_state, is_forward_declaration):
+ """Checks that the new block is directly in a namespace.
+
+ Args:
+ nesting_state: The _NestingState object that contains info about our state.
+ is_forward_declaration: If the class is a forward declared class.
+ Returns:
+ Whether or not the new block is directly in a namespace.
+ """
+ if is_forward_declaration:
+ if len(nesting_state.stack) >= 1 and (
+ isinstance(nesting_state.stack[-1], _NamespaceInfo)):
+ return True
+ else:
+ return False
+
+ return (len(nesting_state.stack) > 1 and
+ nesting_state.stack[-1].check_namespace_indentation and
+ isinstance(nesting_state.stack[-2], _NamespaceInfo))
+
+
+def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
+ raw_lines_no_comments, linenum):
+ """This method determines if we should apply our namespace indentation check.
+
+ Args:
+ nesting_state: The current nesting state.
+ is_namespace_indent_item: If we just put a new class on the stack, True.
+ If the top of the stack is not a class, or we did not recently
+ add the class, False.
+ raw_lines_no_comments: The lines without the comments.
+ linenum: The current line number we are processing.
+
+ Returns:
+ True if we should apply our namespace indentation check. Currently, it
+ only works for classes and namespaces inside of a namespace.
+ """
+
+ is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments,
+ linenum)
+
+ if not (is_namespace_indent_item or is_forward_declaration):
+ return False
+
+ # If we are in a macro, we do not want to check the namespace indentation.
+ if IsMacroDefinition(raw_lines_no_comments, linenum):
+ return False
+
+ return IsBlockInNameSpace(nesting_state, is_forward_declaration)
+
+
+# Call this method if the line is directly inside of a namespace.
+# If the line above is blank (excluding comments) or the start of
+# an inner namespace, it cannot be indented.
+def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum,
+ error):
+ line = raw_lines_no_comments[linenum]
+ if Match(r'^\s+', line):
+ error(filename, linenum, 'runtime/indentation_namespace', 4,
+ 'Do not indent within a namespace')
+
+
def ProcessLine(filename, file_extension, clean_lines, line,
include_state, function_state, nesting_state, error,
extra_check_functions=[]):
@@ -3785,7 +5790,7 @@
line: Number of line being processed.
include_state: An _IncludeState instance in which the headers are inserted.
function_state: A _FunctionState instance which counts function lines, etc.
- nesting_state: A _NestingState instance which maintains information about
+ nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
@@ -3796,21 +5801,97 @@
raw_lines = clean_lines.raw_lines
ParseNolintSuppressions(filename, raw_lines[line], line, error)
nesting_state.Update(filename, clean_lines, line, error)
- if nesting_state.stack and nesting_state.stack[-1].inline_asm != _NO_ASM:
- return
+ CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
+ error)
+ if nesting_state.InAsmBlock(): return
CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
CheckLanguage(filename, clean_lines, line, file_extension, include_state,
- error)
+ nesting_state, error)
+ CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
CheckForNonStandardConstructs(filename, clean_lines, line,
nesting_state, error)
+ CheckVlogArguments(filename, clean_lines, line, error)
CheckPosixThreading(filename, clean_lines, line, error)
CheckInvalidIncrement(filename, clean_lines, line, error)
CheckMakePairUsesDeduction(filename, clean_lines, line, error)
+ CheckRedundantVirtual(filename, clean_lines, line, error)
+ CheckRedundantOverrideOrFinal(filename, clean_lines, line, error)
for check_fn in extra_check_functions:
check_fn(filename, clean_lines, line, error)
+def FlagCxx11Features(filename, clean_lines, linenum, error):
+ """Flag those c++11 features that we only allow in certain places.
+
+ Args:
+ filename: The name of the current file.
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: The number of the line to check.
+ error: The function to call with any errors found.
+ """
+ line = clean_lines.elided[linenum]
+
+ include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
+
+ # Flag unapproved C++ TR1 headers.
+ if include and include.group(1).startswith('tr1/'):
+ error(filename, linenum, 'build/c++tr1', 5,
+ ('C++ TR1 headers such as <%s> are unapproved.') % include.group(1))
+
+ # Flag unapproved C++11 headers.
+ if include and include.group(1) in ('cfenv',
+ 'condition_variable',
+ 'fenv.h',
+ 'future',
+ 'mutex',
+ 'thread',
+ 'chrono',
+ 'ratio',
+ 'regex',
+ 'system_error',
+ ):
+ error(filename, linenum, 'build/c++11', 5,
+ ('<%s> is an unapproved C++11 header.') % include.group(1))
+
+ # The only place where we need to worry about C++11 keywords and library
+ # features in preprocessor directives is in macro definitions.
+ if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return
+
+ # These are classes and free functions. The classes are always
+ # mentioned as std::*, but we only catch the free functions if
+ # they're not found by ADL. They're alphabetical by header.
+ for top_name in (
+ # type_traits
+ 'alignment_of',
+ 'aligned_union',
+ ):
+ if Search(r'\bstd::%s\b' % top_name, line):
+ error(filename, linenum, 'build/c++11', 5,
+ ('std::%s is an unapproved C++11 class or function. Send c-style '
+ 'an example of where it would make your code more readable, and '
+ 'they may let you use it.') % top_name)
+
+
+def FlagCxx14Features(filename, clean_lines, linenum, error):
+ """Flag those C++14 features that we restrict.
+
+ Args:
+ filename: The name of the current file.
+ clean_lines: A CleansedLines instance containing the file.
+ linenum: The number of the line to check.
+ error: The function to call with any errors found.
+ """
+ line = clean_lines.elided[linenum]
+
+ include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
+
+ # Flag unapproved C++14 headers.
+ if include and include.group(1) in ('scoped_allocator', 'shared_mutex'):
+ error(filename, linenum, 'build/c++14', 5,
+ ('<%s> is an unapproved C++14 header.') % include.group(1))
+
+
def ProcessFileData(filename, file_extension, lines, error,
extra_check_functions=[]):
"""Performs lint checks and reports any errors to the given error function.
@@ -3831,31 +5912,122 @@
include_state = _IncludeState()
function_state = _FunctionState()
- nesting_state = _NestingState()
+ nesting_state = NestingState()
ResetNolintSuppressions()
CheckForCopyright(filename, lines, error)
-
- if file_extension == 'h':
- CheckForHeaderGuard(filename, lines, error)
-
+ ProcessGlobalSuppresions(lines)
RemoveMultiLineComments(filename, lines, error)
clean_lines = CleansedLines(lines)
+
+ if IsHeaderExtension(file_extension):
+ CheckForHeaderGuard(filename, clean_lines, error)
+
for line in xrange(clean_lines.NumLines()):
ProcessLine(filename, file_extension, clean_lines, line,
include_state, function_state, nesting_state, error,
extra_check_functions)
- nesting_state.CheckClassFinished(filename, error)
+ FlagCxx11Features(filename, clean_lines, line, error)
+ nesting_state.CheckCompletedBlocks(filename, error)
CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
+ # Check that the .cc file has included its header if it exists.
+ if _IsSourceExtension(file_extension):
+ CheckHeaderFileIncluded(filename, include_state, error)
+
# We check here rather than inside ProcessLine so that we see raw
# lines rather than "cleaned" lines.
- CheckForUnicodeReplacementCharacters(filename, lines, error)
+ CheckForBadCharacters(filename, lines, error)
CheckForNewlineAtEOF(filename, lines, error)
+def ProcessConfigOverrides(filename):
+ """ Loads the configuration files and processes the config overrides.
+
+ Args:
+ filename: The name of the file being processed by the linter.
+
+ Returns:
+ False if the current |filename| should not be processed further.
+ """
+
+ abs_filename = os.path.abspath(filename)
+ cfg_filters = []
+ keep_looking = True
+ while keep_looking:
+ abs_path, base_name = os.path.split(abs_filename)
+ if not base_name:
+ break # Reached the root directory.
+
+ cfg_file = os.path.join(abs_path, "CPPLINT.cfg")
+ abs_filename = abs_path
+ if not os.path.isfile(cfg_file):
+ continue
+
+ try:
+ with open(cfg_file) as file_handle:
+ for line in file_handle:
+ line, _, _ = line.partition('#') # Remove comments.
+ if not line.strip():
+ continue
+
+ name, _, val = line.partition('=')
+ name = name.strip()
+ val = val.strip()
+ if name == 'set noparent':
+ keep_looking = False
+ elif name == 'filter':
+ cfg_filters.append(val)
+ elif name == 'exclude_files':
+ # When matching exclude_files pattern, use the base_name of
+ # the current file name or the directory name we are processing.
+ # For example, if we are checking for lint errors in /foo/bar/baz.cc
+ # and we found the .cfg file at /foo/CPPLINT.cfg, then the config
+ # file's "exclude_files" filter is meant to be checked against "bar"
+ # and not "baz" nor "bar/baz.cc".
+ if base_name:
+ pattern = re.compile(val)
+ if pattern.match(base_name):
+ if _cpplint_state.quiet:
+ # Suppress "Ignoring file" warning when using --quiet.
+ return False
+ sys.stderr.write('Ignoring "%s": file excluded by "%s". '
+ 'File path component "%s" matches '
+ 'pattern "%s"\n' %
+ (filename, cfg_file, base_name, val))
+ return False
+ elif name == 'linelength':
+ global _line_length
+ try:
+ _line_length = int(val)
+ except ValueError:
+ sys.stderr.write('Line length must be numeric.')
+ elif name == 'root':
+ global _root
+ # root directories are specified relative to CPPLINT.cfg dir.
+ _root = os.path.join(os.path.dirname(cfg_file), val)
+ elif name == 'headers':
+ ProcessHppHeadersOption(val)
+ else:
+ sys.stderr.write(
+ 'Invalid configuration option (%s) in file %s\n' %
+ (name, cfg_file))
+
+ except IOError:
+ sys.stderr.write(
+ "Skipping config file '%s': Can't open for reading\n" % cfg_file)
+ keep_looking = False
+
+ # Apply all the accumulated filters in reverse order (top-level directory
+ # config options having the least priority).
+ for filter in reversed(cfg_filters):
+ _AddFilters(filter)
+
+ return True
+
+
def ProcessFile(filename, vlevel, extra_check_functions=[]):
"""Does google-lint on a single file.
@@ -3871,7 +6043,15 @@
"""
_SetVerboseLevel(vlevel)
+ _BackupFilters()
+ old_errors = _cpplint_state.error_count
+ if not ProcessConfigOverrides(filename):
+ _RestoreFilters()
+ return
+
+ lf_lines = []
+ crlf_lines = []
try:
# Support the UNIX convention of using "-" for stdin. Note that
# we are not opening the file with universal newline support
@@ -3879,10 +6059,7 @@
# contain trailing '\r' characters if we are reading a file that
# has CRLF endings.
# If after the split a trailing '\r' is present, it is removed
- # below. If it is not expected to be present (i.e. os.linesep !=
- # '\r\n' as in Windows), a warning is issued below if this file
- # is processed.
-
+ # below.
if filename == '-':
lines = codecs.StreamReaderWriter(sys.stdin,
codecs.getreader('utf8'),
@@ -3891,16 +6068,19 @@
else:
lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
- carriage_return_found = False
# Remove trailing '\r'.
- for linenum in range(len(lines)):
+ # The -1 accounts for the extra trailing blank line we get from split()
+ for linenum in range(len(lines) - 1):
if lines[linenum].endswith('\r'):
lines[linenum] = lines[linenum].rstrip('\r')
- carriage_return_found = True
+ crlf_lines.append(linenum + 1)
+ else:
+ lf_lines.append(linenum + 1)
except IOError:
sys.stderr.write(
"Skipping input '%s': Can't open for reading\n" % filename)
+ _RestoreFilters()
return
# Note, if no dot is found, this will give the entire filename as the ext.
@@ -3908,20 +6088,36 @@
# When reading from stdin, the extension is unknown, so no cpplint tests
# should rely on the extension.
- if (filename != '-' and file_extension != 'cc' and file_extension != 'h'
- and file_extension != 'cpp'):
- sys.stderr.write('Ignoring %s; not a .cc or .h file\n' % filename)
+ if filename != '-' and file_extension not in _valid_extensions:
+ sys.stderr.write('Ignoring %s; not a valid file name '
+ '(%s)\n' % (filename, ', '.join(_valid_extensions)))
else:
ProcessFileData(filename, file_extension, lines, Error,
extra_check_functions)
- if carriage_return_found and os.linesep != '\r\n':
- # Use 0 for linenum since outputting only one error for potentially
- # several lines.
- Error(filename, 0, 'whitespace/newline', 1,
- 'One or more unexpected \\r (^M) found;'
- 'better to use only a \\n')
- sys.stderr.write('Done processing %s\n' % filename)
+ # If end-of-line sequences are a mix of LF and CR-LF, issue
+ # warnings on the lines with CR.
+ #
+ # Don't issue any warnings if all lines are uniformly LF or CR-LF,
+ # since critique can handle these just fine, and the style guide
+ # doesn't dictate a particular end of line sequence.
+ #
+ # We can't depend on os.linesep to determine what the desired
+ # end-of-line sequence should be, since that will return the
+ # server-side end-of-line sequence.
+ if lf_lines and crlf_lines:
+ # Warn on every line with CR. An alternative approach might be to
+ # check whether the file is mostly CRLF or just LF, and warn on the
+ # minority, we bias toward LF here since most tools prefer LF.
+ for linenum in crlf_lines:
+ Error(filename, linenum, 'whitespace/newline', 1,
+ 'Unexpected \\r (^M) found; better to use only \\n')
+
+ # Suppress printing anything if --quiet was passed unless the error
+ # count has increased after processing this file.
+ if not _cpplint_state.quiet or old_errors != _cpplint_state.error_count:
+ sys.stdout.write('Done processing %s\n' % filename)
+ _RestoreFilters()
def PrintUsage(message):
@@ -3961,22 +6157,29 @@
(opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
'counting=',
'filter=',
- 'root='])
+ 'root=',
+ 'linelength=',
+ 'extensions=',
+ 'headers=',
+ 'quiet'])
except getopt.GetoptError:
PrintUsage('Invalid arguments.')
verbosity = _VerboseLevel()
output_format = _OutputFormat()
filters = ''
+ quiet = _Quiet()
counting_style = ''
for (opt, val) in opts:
if opt == '--help':
PrintUsage(None)
elif opt == '--output':
- if not val in ('emacs', 'vs7', 'eclipse'):
+ if val not in ('emacs', 'vs7', 'eclipse'):
PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
output_format = val
+ elif opt == '--quiet':
+ quiet = True
elif opt == '--verbose':
verbosity = int(val)
elif opt == '--filter':
@@ -3990,11 +6193,26 @@
elif opt == '--root':
global _root
_root = val
+ elif opt == '--linelength':
+ global _line_length
+ try:
+ _line_length = int(val)
+ except ValueError:
+ PrintUsage('Line length must be digits.')
+ elif opt == '--extensions':
+ global _valid_extensions
+ try:
+ _valid_extensions = set(val.split(','))
+ except ValueError:
+ PrintUsage('Extensions must be comma separated list.')
+ elif opt == '--headers':
+ ProcessHppHeadersOption(val)
if not filenames:
PrintUsage('No files were specified.')
_SetOutputFormat(output_format)
+ _SetQuiet(quiet)
_SetVerboseLevel(verbosity)
_SetFilters(filters)
_SetCountingStyle(counting_style)
@@ -4015,7 +6233,9 @@
_cpplint_state.ResetErrorCounts()
for filename in filenames:
ProcessFile(filename, _cpplint_state.verbose_level)
- _cpplint_state.PrintErrorCounts()
+ # If --quiet is passed, suppress printing error count unless there are errors.
+ if not _cpplint_state.quiet or _cpplint_state.error_count > 0:
+ _cpplint_state.PrintErrorCounts()
sys.exit(_cpplint_state.error_count > 0)
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/symbolizer/sanitizer_symbolize.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/symbolizer/sanitizer_symbolize.cpp
similarity index 97%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/symbolizer/sanitizer_symbolize.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/symbolizer/sanitizer_symbolize.cpp
index 8150b7a..ba285bc 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/symbolizer/sanitizer_symbolize.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/symbolizer/sanitizer_symbolize.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_symbolize.cc ----------------------------------*- C++ -*-===//
+//===-- sanitizer_symbolize.cpp ---------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -6,7 +6,7 @@
//
//===----------------------------------------------------------------------===//
//
-// Implementation of weak hooks from sanitizer_symbolizer_posix_libcdep.cc.
+// Implementation of weak hooks from sanitizer_symbolizer_posix_libcdep.cpp.
//
//===----------------------------------------------------------------------===//
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/symbolizer/sanitizer_wrappers.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/symbolizer/sanitizer_wrappers.cpp
similarity index 96%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/symbolizer/sanitizer_wrappers.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/symbolizer/sanitizer_wrappers.cpp
index c85ebe5..d3c59e3 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/symbolizer/sanitizer_wrappers.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/symbolizer/sanitizer_wrappers.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_wrappers.cc -----------------------------------*- C++ -*-===//
+//===-- sanitizer_wrappers.cpp ----------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -19,13 +19,6 @@
#include <tuple>
-// Need to match ../sanitizer_common/sanitizer_internal_defs.h
-#if defined(ARCH_PPC)
-#define OFF_T unsigned long
-#else
-#define OFF_T unsigned long long
-#endif
-
namespace __sanitizer {
unsigned long internal_open(const char *filename, int flags);
unsigned long internal_open(const char *filename, int flags, unsigned mode);
@@ -35,7 +28,7 @@
unsigned long internal_fstat(int fd, void *buf);
size_t internal_strlen(const char *s);
unsigned long internal_mmap(void *addr, unsigned long length, int prot,
- int flags, int fd, OFF_T offset);
+ int flags, int fd, unsigned long long offset);
void *internal_memcpy(void *dest, const void *src, unsigned long n);
// Used to propagate errno.
bool internal_iserror(unsigned long retval, int *rverrno = 0);
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/symbolizer/scripts/build_symbolizer.sh b/src/llvm-project/compiler-rt/lib/sanitizer_common/symbolizer/scripts/build_symbolizer.sh
index 0c3917c..be79f1d 100755
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/symbolizer/scripts/build_symbolizer.sh
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/symbolizer/scripts/build_symbolizer.sh
@@ -25,15 +25,25 @@
# object file with only our entry points exposed. However, this does not work at
# present, see PR30750.
-SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+set -x
+set -e
+set -u
+
+SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
SRC_DIR=$(readlink -f $SCRIPT_DIR/..)
TARGE_DIR=$(readlink -f $1)
-
-LLVM_SRC="${LLVM_SRC:-$SCRIPT_DIR/../../../../../..}"
+COMPILER_RT_SRC=$(readlink -f ${SCRIPT_DIR}/../../../..)
+LLVM_SRC=${LLVM_SRC:-${COMPILER_RT_SRC}/../llvm}
LLVM_SRC=$(readlink -f $LLVM_SRC)
+if [[ ! -d "${LLVM_SRC}/../llvm" ]] ; then
+ LLVM_SRC=$(readlink -f ${COMPILER_RT_SRC}/../../../llvm)
+fi
+LIBCXX_SRC=$(readlink -f ${COMPILER_RT_SRC}/../libcxx)
+LIBCXXABI_SRC=$(readlink -f ${COMPILER_RT_SRC}/../libcxxabi)
-if [[ ! -d "${LLVM_SRC}/projects/libcxxabi" ||
- ! -d "${LLVM_SRC}/projects/libcxx" ]]; then
+if [[ ! -d "${LLVM_SRC}/../llvm" ||
+ ! -d "${LIBCXX_SRC}" ||
+ ! -d "${LIBCXXABI_SRC}" ]]; then
echo "Missing or incomplete LLVM_SRC"
exit 1
fi
@@ -88,8 +98,13 @@
if [[ ! -d ${LIBCXX_BUILD} ]]; then
mkdir -p ${LIBCXX_BUILD}
cd ${LIBCXX_BUILD}
- LIBCXX_FLAGS="${FLAGS} -Wno-macro-redefined -I${LLVM_SRC}/projects/libcxxabi/include"
+ LIBCXX_FLAGS="${FLAGS} -Wno-macro-redefined -I${LIBCXX_SRC}/include"
+ PROJECTS=
+ if [[ ! -d $LLVM_SRC/projects/libcxxabi ]] ; then
+ PROJECTS="-DLLVM_ENABLE_PROJECTS='libcxx;libcxxabi'"
+ fi
cmake -GNinja \
+ ${PROJECTS} \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_C_COMPILER=$CC \
-DCMAKE_CXX_COMPILER=$CXX \
@@ -127,7 +142,7 @@
$LLVM_SRC
fi
cd ${LLVM_BUILD}
-ninja LLVMSymbolize LLVMObject LLVMBinaryFormat LLVMDebugInfoDWARF LLVMSupport LLVMDebugInfoPDB LLVMMC LLVMDemangle
+ninja LLVMSymbolize LLVMObject LLVMBinaryFormat LLVMDebugInfoDWARF LLVMSupport LLVMDebugInfoPDB LLVMMC LLVMDemangle LLVMTextAPI
cd ${BUILD_DIR}
rm -rf ${SYMBOLIZER_BUILD}
@@ -135,8 +150,8 @@
cd ${SYMBOLIZER_BUILD}
echo "Compiling..."
-SYMBOLIZER_FLAGS="$LLVM_FLAGS -I${LLVM_SRC}/include -I${LLVM_BUILD}/include -std=c++11"
-$CXX $SYMBOLIZER_FLAGS ${SRC_DIR}/sanitizer_symbolize.cc ${SRC_DIR}/sanitizer_wrappers.cc -c
+SYMBOLIZER_FLAGS="$LLVM_FLAGS -I${LLVM_SRC}/include -I${LLVM_BUILD}/include -std=c++14"
+$CXX $SYMBOLIZER_FLAGS ${SRC_DIR}/sanitizer_symbolize.cpp ${SRC_DIR}/sanitizer_wrappers.cpp -c
$AR rc symbolizer.a sanitizer_symbolize.o sanitizer_wrappers.o
SYMBOLIZER_API_LIST=__sanitizer_symbolize_code,__sanitizer_symbolize_data,__sanitizer_symbolize_flush,__sanitizer_symbolize_demangle
@@ -152,6 +167,7 @@
$LLVM_BUILD/lib/libLLVMDebugInfoPDB.a \
$LLVM_BUILD/lib/libLLVMDemangle.a \
$LLVM_BUILD/lib/libLLVMMC.a \
+ $LLVM_BUILD/lib/libLLVMTextAPI.a \
$ZLIB_BUILD/libz.a \
symbolizer.a \
all.bc
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/symbolizer/scripts/global_symbols.txt b/src/llvm-project/compiler-rt/lib/sanitizer_common/symbolizer/scripts/global_symbols.txt
index 2a0f76b..fa42e2a 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/symbolizer/scripts/global_symbols.txt
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/symbolizer/scripts/global_symbols.txt
@@ -19,8 +19,13 @@
__interceptor_pthread_cond_wait w
__interceptor_pthread_getspecific w
__interceptor_pthread_key_create w
+__interceptor_pthread_mutex_destroy w
+__interceptor_pthread_mutex_init w
__interceptor_pthread_mutex_lock w
__interceptor_pthread_mutex_unlock w
+__interceptor_pthread_mutexattr_destroy w
+__interceptor_pthread_mutexattr_init w
+__interceptor_pthread_mutexattr_settype w
__interceptor_pthread_once w
__interceptor_pthread_setspecific w
__interceptor_read w
@@ -70,9 +75,11 @@
getrlimit U
gettimeofday U
ioctl U
+isalnum U
isalpha U
isatty U
islower U
+isspace U
isprint U
isupper U
isxdigit U
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/CMakeLists.txt b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/CMakeLists.txt
index fd29d17..0726280 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/CMakeLists.txt
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/CMakeLists.txt
@@ -9,40 +9,42 @@
endif()
set(SANITIZER_UNITTESTS
- sanitizer_allocator_test.cc
- sanitizer_atomic_test.cc
- sanitizer_bitvector_test.cc
- sanitizer_bvgraph_test.cc
- sanitizer_common_test.cc
- sanitizer_deadlock_detector_test.cc
- sanitizer_flags_test.cc
- sanitizer_format_interceptor_test.cc
- sanitizer_ioctl_test.cc
- sanitizer_libc_test.cc
- sanitizer_linux_test.cc
- sanitizer_list_test.cc
- sanitizer_mutex_test.cc
- sanitizer_nolibc_test.cc
- sanitizer_posix_test.cc
- sanitizer_printf_test.cc
- sanitizer_procmaps_test.cc
- sanitizer_ring_buffer_test.cc
- sanitizer_quarantine_test.cc
- sanitizer_stackdepot_test.cc
- sanitizer_stacktrace_printer_test.cc
- sanitizer_stacktrace_test.cc
- sanitizer_stoptheworld_test.cc
- sanitizer_suppressions_test.cc
- sanitizer_symbolizer_test.cc
- sanitizer_test_main.cc
- sanitizer_thread_registry_test.cc
- sanitizer_type_traits_test.cc
- sanitizer_vector_test.cc)
+ sanitizer_allocator_test.cpp
+ sanitizer_atomic_test.cpp
+ sanitizer_bitvector_test.cpp
+ sanitizer_bvgraph_test.cpp
+ sanitizer_common_test.cpp
+ sanitizer_deadlock_detector_test.cpp
+ sanitizer_flags_test.cpp
+ sanitizer_format_interceptor_test.cpp
+ sanitizer_ioctl_test.cpp
+ sanitizer_libc_test.cpp
+ sanitizer_linux_test.cpp
+ sanitizer_list_test.cpp
+ sanitizer_mutex_test.cpp
+ sanitizer_nolibc_test.cpp
+ sanitizer_posix_test.cpp
+ sanitizer_printf_test.cpp
+ sanitizer_procmaps_test.cpp
+ sanitizer_ring_buffer_test.cpp
+ sanitizer_quarantine_test.cpp
+ sanitizer_stackdepot_test.cpp
+ sanitizer_stacktrace_printer_test.cpp
+ sanitizer_stacktrace_test.cpp
+ sanitizer_stoptheworld_test.cpp
+ sanitizer_suppressions_test.cpp
+ sanitizer_symbolizer_test.cpp
+ sanitizer_test_main.cpp
+ sanitizer_thread_registry_test.cpp
+ sanitizer_type_traits_test.cpp
+ sanitizer_vector_test.cpp
+ )
set(SANITIZER_TEST_HEADERS
sanitizer_pthread_wrappers.h
sanitizer_test_config.h
- sanitizer_test_utils.h)
+ sanitizer_test_utils.h
+ )
foreach(header ${SANITIZER_IMPL_HEADERS})
list(APPEND SANITIZER_TEST_HEADERS ${CMAKE_CURRENT_SOURCE_DIR}/../${header})
endforeach()
@@ -57,7 +59,8 @@
-O2
-Werror=sign-compare
-Wno-non-virtual-dtor
- -Wno-gnu-zero-variadic-macro-arguments)
+ -Wno-gnu-zero-variadic-macro-arguments
+ )
set(SANITIZER_TEST_LINK_FLAGS_COMMON ${COMPILER_RT_UNITTEST_LINK_FLAGS})
@@ -156,9 +159,9 @@
if("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux" AND "${arch}" STREQUAL "x86_64")
# Test that the libc-independent part of sanitizer_common is indeed
# independent of libc, by linking this binary without libc (here) and
- # executing it (unit test in sanitizer_nolibc_test.cc).
+ # executing it (unit test in sanitizer_nolibc_test.cpp).
clang_compile(sanitizer_nolibc_test_main.${arch}.o
- sanitizer_nolibc_test_main.cc
+ sanitizer_nolibc_test_main.cpp
CFLAGS ${SANITIZER_TEST_CFLAGS_COMMON} ${TARGET_FLAGS}
DEPS ${SANITIZER_TEST_COMPILE_DEPS})
add_compiler_rt_test(SanitizerUnitTests "Sanitizer-${arch}-Test-Nolibc" ${arch}
@@ -168,7 +171,7 @@
-Wl,-no-whole-archive
DEPS sanitizer_nolibc_test_main.${arch}.o
RTSanitizerCommon.test.nolibc.${arch}
- LINK_FLAGS -nostdlib ${TARGET_FLAGS})
+ LINK_FLAGS -static -nostdlib ${TARGET_FLAGS})
endif()
endmacro()
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/malloc_stress_transfer_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/malloc_stress_transfer_test.cpp
similarity index 87%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/malloc_stress_transfer_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/malloc_stress_transfer_test.cpp
index 3e03c4b..cf38798 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/malloc_stress_transfer_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/malloc_stress_transfer_test.cpp
@@ -1,5 +1,4 @@
#include <thread>
-#include <iostream>
const size_t kAllocSize = 16;
const size_t kInitialNumAllocs = 1 << 10;
@@ -8,8 +7,6 @@
const size_t kNumThreads = 16;
void Thread() {
- // int sp;
- // std::cerr << "Thread starting, sp = " << &sp << std::endl;
char *InitialAllocations[kInitialNumAllocs];
char *PeriodicaAllocations[kPeriodicNumAllocs];
for (auto &p : InitialAllocations) p = new char[kAllocSize];
@@ -26,8 +23,6 @@
}
int main() {
-// Thread();
-// return 0;
std::thread *Threads[kNumThreads];
for (auto &T : Threads) T = new std::thread(&Thread);
for (auto T : Threads) {
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_allocator_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_allocator_test.cpp
similarity index 97%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_allocator_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_allocator_test.cpp
index 5d99bf4..ff1f7f9 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_allocator_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_allocator_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_allocator_test.cc ---------------------------------------===//
+//===-- sanitizer_allocator_test.cpp --------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -868,10 +868,10 @@
const int kSize = 512;
{
InternalMmapVector<int> int_buf(kSize);
- EXPECT_EQ((uptr)kSize, int_buf.size()); // NOLINT
+ EXPECT_EQ((uptr)kSize, int_buf.size());
}
InternalMmapVector<char> char_buf(kSize);
- EXPECT_EQ((uptr)kSize, char_buf.size()); // NOLINT
+ EXPECT_EQ((uptr)kSize, char_buf.size());
internal_memset(char_buf.data(), 'c', kSize);
for (int i = 0; i < kSize; i++) {
EXPECT_EQ('c', char_buf[i]);
@@ -1404,4 +1404,15 @@
EXPECT_EQ((uptr)TestMapUnmapCallback::unmap_count, m.size1());
}
+TEST(SanitizerCommon, LowLevelAllocatorShouldRoundUpSizeOnAlloc) {
+ // When allocating a memory block slightly bigger than a memory page and
+ // LowLevelAllocator calls MmapOrDie for the internal buffer, it should round
+ // the size up to the page size, so that subsequent calls to the allocator
+ // can use the remaining space in the last allocated page.
+ static LowLevelAllocator allocator;
+ char *ptr1 = (char *)allocator.Allocate(GetPageSizeCached() + 16);
+ char *ptr2 = (char *)allocator.Allocate(16);
+ EXPECT_EQ(ptr2, ptr1 + GetPageSizeCached() + 16);
+}
+
#endif // #if !SANITIZER_DEBUG
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_allocator_testlib.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_allocator_testlib.cpp
similarity index 95%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_allocator_testlib.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_allocator_testlib.cpp
index e7d482f..93af8be 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_allocator_testlib.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_allocator_testlib.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_allocator_testlib.cc ------------------------------------===//
+//===-- sanitizer_allocator_testlib.cpp -----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -11,8 +11,8 @@
//===----------------------------------------------------------------------===//
/* Usage:
clang++ -std=c++11 -fno-exceptions -g -fPIC -I. -I../include -Isanitizer \
- sanitizer_common/tests/sanitizer_allocator_testlib.cc \
- $(\ls sanitizer_common/sanitizer_*.cc | grep -v sanitizer_common_nolibc.cc) \
+ sanitizer_common/tests/sanitizer_allocator_testlib.cpp \
+ $(\ls sanitizer_common/sanitizer_*.cpp | grep -v sanitizer_common_nolibc.cpp) \
sanitizer_common/sanitizer_linux_x86_64.S \
-shared -lpthread -o testmalloc.so
LD_PRELOAD=`pwd`/testmalloc.so /your/app
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_atomic_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_atomic_test.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_atomic_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_atomic_test.cpp
index 37ba0fa..9a3078b 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_atomic_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_atomic_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_atomic_test.cc ------------------------------------------===//
+//===-- sanitizer_atomic_test.cpp -----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_bitvector_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_bitvector_test.cpp
similarity index 96%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_bitvector_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_bitvector_test.cpp
index 9f60503..670e965 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_bitvector_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_bitvector_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_bitvector_test.cc ---------------------------------------===//
+//===-- sanitizer_bitvector_test.cpp --------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -68,7 +68,11 @@
void Print(const set<uptr> &s) {
for (set<uptr>::iterator it = s.begin(); it != s.end(); ++it) {
+#if defined(_WIN64)
+ fprintf(stderr, "%llu ", *it);
+#else
fprintf(stderr, "%lu ", *it);
+#endif
}
fprintf(stderr, "\n");
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_bvgraph_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_bvgraph_test.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_bvgraph_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_bvgraph_test.cpp
index 955b723..bb2f81f 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_bvgraph_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_bvgraph_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_bvgraph_test.cc -----------------------------------------===//
+//===-- sanitizer_bvgraph_test.cpp ----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_common_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_common_test.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_common_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_common_test.cpp
index 2350de9..212d2f5 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_common_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_common_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_common_test.cc ------------------------------------------===//
+//===-- sanitizer_common_test.cpp -----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -131,7 +131,7 @@
EXPECT_EQ((uptr)i, vector.size());
}
InternalMmapVector<uptr> empty_vector;
- CHECK_GT(empty_vector.capacity(), 0U);
+ CHECK_EQ(empty_vector.capacity(), 0U);
CHECK_EQ(0U, empty_vector.size());
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_deadlock_detector_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_deadlock_detector_test.cpp
similarity index 99%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_deadlock_detector_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_deadlock_detector_test.cpp
index f68bb70..b4ec339 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_deadlock_detector_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_deadlock_detector_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_deadlock_detector_test.cc -------------------------------===//
+//===-- sanitizer_deadlock_detector_test.cpp ------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_flags_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_flags_test.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_flags_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_flags_test.cpp
index cfe90ef..63a7da6 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_flags_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_flags_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_flags_test.cc -------------------------------------------===//
+//===-- sanitizer_flags_test.cpp ------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_format_interceptor_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_format_interceptor_test.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_format_interceptor_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_format_interceptor_test.cpp
index 9f70fbc..4ed8072 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_format_interceptor_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_format_interceptor_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_format_interceptor_test.cc ------------------------------===//
+//===-- sanitizer_format_interceptor_test.cpp -----------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_ioctl_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_ioctl_test.cpp
similarity index 97%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_ioctl_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_ioctl_test.cpp
index 738046a..8da09f6 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_ioctl_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_ioctl_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_ioctl_test.cc -------------------------------------------===//
+//===-- sanitizer_ioctl_test.cpp ------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_libc_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_libc_test.cpp
similarity index 96%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_libc_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_libc_test.cpp
index d8f4759..c3fddc5 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_libc_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_libc_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_libc_test.cc --------------------------------------------===//
+//===-- sanitizer_libc_test.cpp -------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -8,7 +8,8 @@
// Tests for sanitizer_libc.h.
//===----------------------------------------------------------------------===//
#include <algorithm>
-#include <fstream>
+#include <vector>
+#include <stdio.h>
#include "sanitizer_common/sanitizer_common.h"
#include "sanitizer_common/sanitizer_file.h"
@@ -166,16 +167,16 @@
class SanitizerCommonFileTest : public ::testing::TestWithParam<uptr> {
void SetUp() override {
data_.resize(GetParam());
- std::generate(data_.begin(), data_.end(), [] {
- return rand() % 256; // NOLINT
- });
+ std::generate(data_.begin(), data_.end(), [] { return rand() % 256; });
temp_file_name(file_name_, sizeof(file_name_),
"sanitizer_common.ReadFile.tmp.");
- std::ofstream f(file_name_, std::ios::out | std::ios::binary);
- if (!data_.empty())
- f.write(data_.data(), data_.size());
+ if (FILE *f = fopen(file_name_, "wb")) {
+ if (!data_.empty())
+ fwrite(data_.data(), data_.size(), 1, f);
+ fclose(f);
+ }
}
void TearDown() override { Unlink(file_name_); }
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_linux_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_linux_test.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_linux_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_linux_test.cpp
index a5ce5a2..1d8e7e8 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_linux_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_linux_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_linux_test.cc -------------------------------------------===//
+//===-- sanitizer_linux_test.cpp ------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_list_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_list_test.cpp
similarity index 97%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_list_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_list_test.cpp
index 7dd28ee..6344423 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_list_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_list_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_list_test.cc --------------------------------------------===//
+//===-- sanitizer_list_test.cpp -------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_mutex_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_mutex_test.cpp
similarity index 97%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_mutex_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_mutex_test.cpp
index ef1c5fa..2cfbaae 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_mutex_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_mutex_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_mutex_test.cc -------------------------------------------===//
+//===-- sanitizer_mutex_test.cpp ------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_nolibc_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_nolibc_test.cpp
similarity index 93%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_nolibc_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_nolibc_test.cpp
index fdab296..41376ee 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_nolibc_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_nolibc_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_nolibc_test.cc ------------------------------------------===//
+//===-- sanitizer_nolibc_test.cpp -----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_nolibc_test_main.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_nolibc_test_main.cpp
similarity index 90%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_nolibc_test_main.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_nolibc_test_main.cpp
index 70028506..5c02bfb 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_nolibc_test_main.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_nolibc_test_main.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_nolibc_test_main.cc -------------------------------------===//
+//===-- sanitizer_nolibc_test_main.cpp ------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_posix_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_posix_test.cpp
similarity index 91%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_posix_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_posix_test.cpp
index 6ceae7d..be577c3 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_posix_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_posix_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_posix_test.cc -------------------------------------------===//
+//===-- sanitizer_posix_test.cpp ------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -54,7 +54,12 @@
SpawnThread(GetPthreadDestructorIterations());
EXPECT_TRUE(destructor_executed);
SpawnThread(GetPthreadDestructorIterations() + 1);
+#if SANITIZER_SOLARIS
+ // Solaris continues calling destructors beyond PTHREAD_DESTRUCTOR_ITERATIONS.
+ EXPECT_TRUE(destructor_executed);
+#else
EXPECT_FALSE(destructor_executed);
+#endif
ASSERT_EQ(0, pthread_key_delete(key));
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_printf_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_printf_test.cpp
similarity index 83%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_printf_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_printf_test.cpp
index 4f86976..956ed65 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_printf_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_printf_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_printf_test.cc ------------------------------------------===//
+//===-- sanitizer_printf_test.cpp -----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -6,7 +6,7 @@
//
//===----------------------------------------------------------------------===//
//
-// Tests for sanitizer_printf.cc
+// Tests for sanitizer_printf.cpp
//
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_common.h"
@@ -20,12 +20,9 @@
TEST(Printf, Basic) {
char buf[1024];
- uptr len = internal_snprintf(buf, sizeof(buf),
- "a%db%zdc%ue%zuf%xh%zxq%pe%sr",
- (int)-1, (uptr)-2, // NOLINT
- (unsigned)-4, (uptr)5, // NOLINT
- (unsigned)10, (uptr)11, // NOLINT
- (void*)0x123, "_string_");
+ uptr len = internal_snprintf(
+ buf, sizeof(buf), "a%db%zdc%ue%zuf%xh%zxq%pe%sr", (int)-1, (uptr)-2,
+ (unsigned)-4, (uptr)5, (unsigned)10, (uptr)11, (void *)0x123, "_string_");
EXPECT_EQ(len, strlen(buf));
std::string expectedString = "a-1b-2c4294967292e5fahbq0x";
@@ -115,14 +112,14 @@
}
TEST(Printf, MinMax) {
- TestAgainstLibc<int>("%d-%d", INT_MIN, INT_MAX); // NOLINT
- TestAgainstLibc<unsigned>("%u-%u", 0, UINT_MAX); // NOLINT
- TestAgainstLibc<unsigned>("%x-%x", 0, UINT_MAX); // NOLINT
+ TestAgainstLibc<int>("%d-%d", INT_MIN, INT_MAX);
+ TestAgainstLibc<unsigned>("%u-%u", 0, UINT_MAX);
+ TestAgainstLibc<unsigned>("%x-%x", 0, UINT_MAX);
#if !defined(_WIN32)
// %z* format doesn't seem to be supported by MSVS.
- TestAgainstLibc<long>("%zd-%zd", LONG_MIN, LONG_MAX); // NOLINT
- TestAgainstLibc<unsigned long>("%zu-%zu", 0, ULONG_MAX); // NOLINT
- TestAgainstLibc<unsigned long>("%zx-%zx", 0, ULONG_MAX); // NOLINT
+ TestAgainstLibc<long>("%zd-%zd", LONG_MIN, LONG_MAX);
+ TestAgainstLibc<unsigned long>("%zu-%zu", 0, ULONG_MAX);
+ TestAgainstLibc<unsigned long>("%zx-%zx", 0, ULONG_MAX);
#endif
}
@@ -152,7 +149,7 @@
EXPECT_STREQ("12345 ", buf);
// Check that width does not overflow the smaller buffer, although
// 10 chars is requested, it stops at the buffer size, 8.
- len = internal_snprintf(buf, 8, "%-10s", "12345");
+ len = internal_snprintf(buf, 8, "%-10s", "12345"); // NOLINT
EXPECT_EQ(10U, len); // The required size reported.
EXPECT_STREQ("12345 ", buf);
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_procmaps_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_procmaps_test.cpp
similarity index 97%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_procmaps_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_procmaps_test.cpp
index 37ab3d9..08750c0 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_procmaps_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_procmaps_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_procmaps_test.cc ----------------------------------------===//
+//===-- sanitizer_procmaps_test.cpp ---------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_quarantine_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_quarantine_test.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_quarantine_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_quarantine_test.cpp
index 4088119..ee0ac6a 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_quarantine_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_quarantine_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_quarantine_test.cc --------------------------------------===//
+//===-- sanitizer_quarantine_test.cpp -------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_ring_buffer_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_ring_buffer_test.cpp
similarity index 97%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_ring_buffer_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_ring_buffer_test.cpp
index e10cd36..91ec2f9 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_ring_buffer_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_ring_buffer_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_vector_test.cc ------------------------------------------===//
+//===-- sanitizer_vector_test.cpp -----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stackdepot_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stackdepot_test.cpp
similarity index 97%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stackdepot_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stackdepot_test.cpp
index 24f6fcf..a06413c 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stackdepot_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stackdepot_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_stackdepot_test.cc --------------------------------------===//
+//===-- sanitizer_stackdepot_test.cpp -------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stacktrace_printer_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stacktrace_printer_test.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stacktrace_printer_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stacktrace_printer_test.cpp
index b6d1bd1..1ce89a3 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stacktrace_printer_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stacktrace_printer_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_common_printer_test.cc ----------------------------------===//
+//===-- sanitizer_common_printer_test.cpp ---------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stacktrace_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stacktrace_test.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stacktrace_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stacktrace_test.cpp
index 771a3e4..afd4a0e 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stacktrace_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stacktrace_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_stacktrace_test.cc --------------------------------------===//
+//===-- sanitizer_stacktrace_test.cpp -------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stoptheworld_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stoptheworld_test.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stoptheworld_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stoptheworld_test.cpp
index 98e64d8..beb56cf 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stoptheworld_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stoptheworld_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_stoptheworld_test.cc ------------------------------------===//
+//===-- sanitizer_stoptheworld_test.cpp -----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stoptheworld_testlib.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stoptheworld_testlib.cpp
similarity index 86%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stoptheworld_testlib.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stoptheworld_testlib.cpp
index 033170e..e333bf0 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stoptheworld_testlib.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_stoptheworld_testlib.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_stoptheworld_testlib.cc ---------------------------------===//
+//===-- sanitizer_stoptheworld_testlib.cpp --------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -10,8 +10,8 @@
//===----------------------------------------------------------------------===//
/* Usage:
clang++ -fno-exceptions -g -fPIC -I. \
- sanitizer_common/tests/sanitizer_stoptheworld_testlib.cc \
- sanitizer_common/sanitizer_*.cc -shared -lpthread -o teststoptheworld.so
+ sanitizer_common/tests/sanitizer_stoptheworld_testlib.cpp \
+ sanitizer_common/sanitizer_*.cpp -shared -lpthread -o teststoptheworld.so
LD_PRELOAD=`pwd`/teststoptheworld.so /your/app
*/
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_suppressions_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_suppressions_test.cpp
similarity index 86%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_suppressions_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_suppressions_test.cpp
index d64379a..50a6ce9 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_suppressions_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_suppressions_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_suppressions_test.cc ------------------------------------===//
+//===-- sanitizer_suppressions_test.cpp -----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -18,7 +18,7 @@
static bool MyMatch(const char *templ, const char *func) {
char tmp[1024];
- strcpy(tmp, templ); // NOLINT
+ snprintf(tmp, sizeof(tmp), "%s", templ);
return TemplateMatch(tmp, func);
}
@@ -80,43 +80,41 @@
};
TEST_F(SuppressionContextTest, Parse) {
- ctx_.Parse("race:foo\n"
- " race:bar\n" // NOLINT
- "race:baz \n" // NOLINT
- "# a comment\n"
- "race:quz\n"); // NOLINT
+ ctx_.Parse(
+ "race:foo\n"
+ " \trace:bar\n"
+ "race:baz\t \n"
+ "# a comment\n"
+ "race:quz\n");
CheckSuppressions(4, {"race", "race", "race", "race"},
{"foo", "bar", "baz", "quz"});
}
TEST_F(SuppressionContextTest, Parse2) {
ctx_.Parse(
- " # first line comment\n" // NOLINT
- " race:bar \n" // NOLINT
- "race:baz* *baz\n"
- "# a comment\n"
- "# last line comment\n"
- ); // NOLINT
+ " \t# first line comment\n"
+ " \trace:bar \t\n"
+ "race:baz* *baz\n"
+ "# a comment\n"
+ "# last line comment\n");
CheckSuppressions(2, {"race", "race"}, {"bar", "baz* *baz"});
}
TEST_F(SuppressionContextTest, Parse3) {
ctx_.Parse(
- "# last suppression w/o line-feed\n"
- "race:foo\n"
- "race:bar\r\n"
- "race:baz"
- ); // NOLINT
+ "# last suppression w/o line-feed\n"
+ "race:foo\n"
+ "race:bar\r\n"
+ "race:baz");
CheckSuppressions(3, {"race", "race", "race"}, {"foo", "bar", "baz"});
}
TEST_F(SuppressionContextTest, ParseType) {
ctx_.Parse(
- "race:foo\n"
- "thread:bar\n"
- "mutex:baz\n"
- "signal:quz\n"
- ); // NOLINT
+ "race:foo\n"
+ "thread:bar\n"
+ "mutex:baz\n"
+ "signal:quz\n");
CheckSuppressions(4, {"race", "thread", "mutex", "signal"},
{"foo", "bar", "baz", "quz"});
}
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_symbolizer_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_symbolizer_test.cpp
similarity index 96%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_symbolizer_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_symbolizer_test.cpp
index e6bdeaa..1e70c14 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_symbolizer_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_symbolizer_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_symbolizer_test.cc --------------------------------------===//
+//===-- sanitizer_symbolizer_test.cpp -------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_test_main.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_test_main.cpp
similarity index 91%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_test_main.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_test_main.cpp
index 8edee74..caab5ec 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_test_main.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_test_main.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_test_main.cc --------------------------------------------===//
+//===-- sanitizer_test_main.cpp -------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_thread_registry_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_thread_registry_test.cpp
similarity index 98%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_thread_registry_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_thread_registry_test.cpp
index 09c01d6..6c380f1 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_thread_registry_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_thread_registry_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_thread_registry_test.cc ---------------------------------===//
+//===-- sanitizer_thread_registry_test.cpp --------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_type_traits_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_type_traits_test.cpp
similarity index 94%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_type_traits_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_type_traits_test.cpp
index ccefeb6..40f6e47 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_type_traits_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_type_traits_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_type_traits_test.cc -------------------------------------===//
+//===-- sanitizer_type_traits_test.cpp ------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_vector_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_vector_test.cpp
similarity index 94%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_vector_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_vector_test.cpp
index 5d96e9b..771319c 100644
--- a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_vector_test.cc
+++ b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/sanitizer_vector_test.cpp
@@ -1,4 +1,4 @@
-//===-- sanitizer_vector_test.cc ------------------------------------------===//
+//===-- sanitizer_vector_test.cpp -----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
diff --git a/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/standalone_malloc_test.cc b/src/llvm-project/compiler-rt/lib/sanitizer_common/tests/standalone_malloc_test.cpp
similarity index 100%
rename from src/llvm-project/compiler-rt/lib/sanitizer_common/tests/standalone_malloc_test.cc
rename to src/llvm-project/compiler-rt/lib/sanitizer_common/tests/standalone_malloc_test.cpp