llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

clang-tidy bugprone-unchecked-optional-access checker intermittently crashes on simple file using bitfields

Open virtuald opened this issue 3 years ago • 24 comments

Here's the file:


#include <optional>

extern "C" {

struct Dst {
    int max_cpus;
    int min_cpus;
    int default_cpus;

    unsigned int n1 : 1, n2 : 1, n3 : 1, n4 : 1, n5 : 1;
};
}

struct Src {
    std::optional<bool> n1;
    std::optional<bool> n2;
};

void do_something(Src *s, Dst *d)
{
#define STORE_ARG(n)                                                                               \
    {                                                                                              \
        const auto v = s->n;                                                                       \
        if (v.has_value()) {                                                                       \
            d->n = v.value();                                                                      \
        }                                                                                          \
    }

    // STORE_ARG(max_cpus)
    // STORE_ARG(min_cpus)
    // STORE_ARG(default_cpus)

    STORE_ARG(n1)
    STORE_ARG(n2)
}

Compiled Clang/etc from source tarball on Ubuntu 18.04:

$ clangd --version
clangd version 15.0.6
Features: linux
Platform: x86_64-unknown-linux-gnu

Here's the stack trace:

munmap_chunk(): invalid pointer
I[22:38:39.137] <-- textDocument/semanticTokens/full(5)
 #0 0x00005586f91e02cf PrintStackTraceSignalHandler(void*) Signals.cpp:0:0
 #1 0x00005586f91de29c SignalHandler(int) Signals.cpp:0:0
 #2 0x00007f58e4cb8980 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x12980)
 #3 0x00007f58e390ee87 raise /build/glibc-CVJwZb/glibc-2.27/signal/../sysdeps/unix/sysv/linux/raise.c:51:0
 #4 0x00007f58e39107f1 abort /build/glibc-CVJwZb/glibc-2.27/stdlib/abort.c:81:0
 #5 0x00007f58e3959837 __libc_message /build/glibc-CVJwZb/glibc-2.27/libio/../sysdeps/posix/libc_fatal.c:181:0
 #6 0x00007f58e39608ba /build/glibc-CVJwZb/glibc-2.27/malloc/malloc.c:5342:0
 #7 0x00007f58e3967e9c munmap_chunk /build/glibc-CVJwZb/glibc-2.27/malloc/malloc.c:2846:0
 #8 0x00007f58e3967e9c free /build/glibc-CVJwZb/glibc-2.27/malloc/malloc.c:3127:0
 #9 0x00005586fa617ea2 clang::dataflow::buildBooleanFormula(llvm::DenseSet<clang::dataflow::BoolValue*, llvm::DenseMapInfo<clang::dataflow::BoolValue*, void>> const&) (/disk2/dustin/llvm/prefix/bin/clangd+0x1acbea2)
#10 0x00005586fa618458 clang::dataflow::WatchedLiteralsSolver::solve(llvm::DenseSet<clang::dataflow::BoolValue*, llvm::DenseMapInfo<clang::dataflow::BoolValue*, void>>) (/disk2/dustin/llvm/prefix/bin/clangd+0x1acc458)
#11 0x00005586fa6024cd clang::dataflow::DataflowAnalysisContext::flowConditionImplies(clang::dataflow::AtomicBoolValue&, clang::dataflow::BoolValue&) (/disk2/dustin/llvm/prefix/bin/clangd+0x1ab64cd)
#12 0x00005586fa5eab15 std::_Function_handler<std::vector<clang::SourceLocation, std::allocator<clang::SourceLocation>> (clang::CXXMemberCallExpr const*, clang::ast_matchers::MatchFinder::MatchResult const&, clang::dataflow::Environment const&), clang::dataflow::(anonymous namespace)::buildDiagnoseMatchSwitch(clang::dataflow::UncheckedOptionalAccessModelOptions const&)::'lambda'(clang::CXXMemberCallExpr const*, clang::ast_matchers::MatchFinder::MatchResult const&, clang::dataflow::Environment const&)>::_M_invoke(std::_Any_data const&, clang::CXXMemberCallExpr const*&&, clang::ast_matchers::MatchFinder::MatchResult const&, clang::dataflow::Environment const&) UncheckedOptionalAccessModel.cpp:0:0
#13 0x00005586fa5e9473 std::_Function_handler<std::vector<clang::SourceLocation, std::allocator<clang::SourceLocation>> (clang::Stmt const*, clang::ast_matchers::MatchFinder::MatchResult const&, clang::dataflow::Environment const&), clang::dataflow::MatchSwitchBuilder<clang::dataflow::Environment const, std::vector<clang::SourceLocation, std::allocator<clang::SourceLocation>>>&& clang::dataflow::MatchSwitchBuilder<clang::dataflow::Environment const, std::vector<clang::SourceLocation, std::allocator<clang::SourceLocation>>>::CaseOf<clang::CXXMemberCallExpr>(clang::ast_matchers::internal::Matcher<clang::Stmt>, std::function<std::vector<clang::SourceLocation, std::allocator<clang::SourceLocation>> (clang::CXXMemberCallExpr const*, clang::ast_matchers::MatchFinder::MatchResult const&, clang::dataflow::Environment const&)>) &&::'lambda'(clang::Stmt const*, clang::ast_matchers::MatchFinder::MatchResult const&, clang::dataflow::Environment const&)>::_M_invoke(std::_Any_data const&, clang::Stmt const*&&, clang::ast_matchers::MatchFinder::MatchResult const&, clang::dataflow::Environment const&) (/disk2/dustin/llvm/prefix/bin/clangd+0x1a9d473)
#14 0x00005586fa5ed853 std::_Function_handler<std::vector<clang::SourceLocation, std::allocator<clang::SourceLocation>> (clang::Stmt const&, clang::ASTContext&, clang::dataflow::Environment const&), clang::dataflow::MatchSwitchBuilder<clang::dataflow::Environment const, std::vector<clang::SourceLocation, std::allocator<clang::SourceLocation>>>::Build() &&::'lambda'(clang::Stmt const&, clang::ASTContext&, clang::dataflow::Environment const&)>::_M_invoke(std::_Any_data const&, clang::Stmt const&, clang::ASTContext&, clang::dataflow::Environment const&) (/disk2/dustin/llvm/prefix/bin/clangd+0x1aa1853)
#15 0x00005586fa5ea4cb clang::dataflow::UncheckedOptionalAccessDiagnoser::diagnose(clang::ASTContext&, clang::Stmt const*, clang::dataflow::Environment const&) (/disk2/dustin/llvm/prefix/bin/clangd+0x1a9e4cb)
#16 0x00005586fa5b43d9 std::_Function_handler<void (clang::Stmt const*, clang::dataflow::DataflowAnalysisState<clang::dataflow::NoopLattice> const&), clang::tidy::bugprone::analyzeFunction(clang::FunctionDecl const&, clang::ASTContext&)::'lambda'(clang::Stmt const*, clang::dataflow::DataflowAnalysisState<clang::dataflow::NoopLattice> const&)>::_M_invoke(std::_Any_data const&, clang::Stmt const*&&, clang::dataflow::DataflowAnalysisState<clang::dataflow::NoopLattice> const&) UncheckedOptionalAccessCheck.cpp:0:0
#17 0x00005586fa5b4886 std::_Function_handler<void (clang::Stmt const*, clang::dataflow::TypeErasedDataflowAnalysisState const&), llvm::Expected<std::vector<llvm::Optional<clang::dataflow::DataflowAnalysisState<clang::dataflow::UncheckedOptionalAccessModel::Lattice>>, std::allocator<llvm::Optional<clang::dataflow::DataflowAnalysisState<clang::dataflow::UncheckedOptionalAccessModel::Lattice>>>>> clang::dataflow::runDataflowAnalysis<clang::dataflow::UncheckedOptionalAccessModel>(clang::dataflow::ControlFlowContext const&, clang::dataflow::UncheckedOptionalAccessModel&, clang::dataflow::Environment const&, std::function<void (clang::Stmt const*, clang::dataflow::DataflowAnalysisState<clang::dataflow::UncheckedOptionalAccessModel::Lattice> const&)>)::'lambda'(clang::Stmt const*, clang::dataflow::TypeErasedDataflowAnalysisState const&)>::_M_invoke(std::_Any_data const&, clang::Stmt const*&&, clang::dataflow::TypeErasedDataflowAnalysisState const&) (/disk2/dustin/llvm/prefix/bin/clangd+0x1a68886)
#18 0x00005586fa60f622 std::_Function_handler<void (clang::CFGStmt const&, clang::dataflow::TypeErasedDataflowAnalysisState const&), clang::dataflow::runTypeErasedDataflowAnalysis(clang::dataflow::ControlFlowContext const&, clang::dataflow::TypeErasedDataflowAnalysis&, clang::dataflow::Environment const&, std::function<void (clang::Stmt const*, clang::dataflow::TypeErasedDataflowAnalysisState const&)>)::'lambda'(clang::CFGStmt const&, clang::dataflow::TypeErasedDataflowAnalysisState const&)>::_M_invoke(std::_Any_data const&, clang::CFGStmt const&, clang::dataflow::TypeErasedDataflowAnalysisState const&) TypeErasedDataflowAnalysis.cpp:0:0
#19 0x00005586fa6110bb clang::dataflow::transferBlock(clang::dataflow::ControlFlowContext const&, std::vector<llvm::Optional<clang::dataflow::TypeErasedDataflowAnalysisState>, std::allocator<llvm::Optional<clang::dataflow::TypeErasedDataflowAnalysisState>>>&, clang::CFGBlock const&, clang::dataflow::Environment const&, clang::dataflow::TypeErasedDataflowAnalysis&, std::function<void (clang::CFGStmt const&, clang::dataflow::TypeErasedDataflowAnalysisState const&)>) (/disk2/dustin/llvm/prefix/bin/clangd+0x1ac50bb)
#20 0x00005586fa613653 clang::dataflow::runTypeErasedDataflowAnalysis(clang::dataflow::ControlFlowContext const&, clang::dataflow::TypeErasedDataflowAnalysis&, clang::dataflow::Environment const&, std::function<void (clang::Stmt const*, clang::dataflow::TypeErasedDataflowAnalysisState const&)>) (/disk2/dustin/llvm/prefix/bin/clangd+0x1ac7653)
#21 0x00005586fa5b5ff1 llvm::Expected<std::vector<llvm::Optional<clang::dataflow::DataflowAnalysisState<clang::dataflow::UncheckedOptionalAccessModel::Lattice>>, std::allocator<llvm::Optional<clang::dataflow::DataflowAnalysisState<clang::dataflow::UncheckedOptionalAccessModel::Lattice>>>>> clang::dataflow::runDataflowAnalysis<clang::dataflow::UncheckedOptionalAccessModel>(clang::dataflow::ControlFlowContext const&, clang::dataflow::UncheckedOptionalAccessModel&, clang::dataflow::Environment const&, std::function<void (clang::Stmt const*, clang::dataflow::DataflowAnalysisState<clang::dataflow::UncheckedOptionalAccessModel::Lattice> const&)>) (/disk2/dustin/llvm/prefix/bin/clangd+0x1a69ff1)
#22 0x00005586fa5b6e0d clang::tidy::bugprone::analyzeFunction(clang::FunctionDecl const&, clang::ASTContext&) UncheckedOptionalAccessCheck.cpp:0:0
#23 0x00005586fa5b7502 clang::tidy::bugprone::UncheckedOptionalAccessCheck::check(clang::ast_matchers::MatchFinder::MatchResult const&) (/disk2/dustin/llvm/prefix/bin/clangd+0x1a6b502)
#24 0x00005586fb0038f9 clang::ast_matchers::internal::(anonymous namespace)::MatchASTVisitor::MatchVisitor::visitMatch(clang::ast_matchers::BoundNodes const&) ASTMatchFinder.cpp:0:0
#25 0x00005586fb048118 clang::ast_matchers::internal::BoundNodesTreeBuilder::visitMatches(clang::ast_matchers::internal::BoundNodesTreeBuilder::Visitor*) (/disk2/dustin/llvm/prefix/bin/clangd+0x24fc118)
#26 0x00005586fb006034 clang::ast_matchers::internal::(anonymous namespace)::MatchASTVisitor::matchWithFilter(clang::DynTypedNode const&) ASTMatchFinder.cpp:0:0
#27 0x00005586fb027bd8 clang::ast_matchers::internal::(anonymous namespace)::MatchASTVisitor::TraverseDecl(clang::Decl*) ASTMatchFinder.cpp:0:0
#28 0x00005586fb042633 clang::RecursiveASTVisitor<clang::ast_matchers::internal::(anonymous namespace)::MatchASTVisitor>::TraverseTranslationUnitDecl(clang::TranslationUnitDecl*) ASTMatchFinder.cpp:0:0
#29 0x00005586fb027c19 clang::ast_matchers::internal::(anonymous namespace)::MatchASTVisitor::TraverseDecl(clang::Decl*) ASTMatchFinder.cpp:0:0
#30 0x00005586fb029db9 clang::ast_matchers::MatchFinder::matchAST(clang::ASTContext&) (/disk2/dustin/llvm/prefix/bin/clangd+0x24dddb9)
#31 0x00005586fa1c3e48 clang::clangd::ParsedAST::build(llvm::StringRef, clang::clangd::ParseInputs const&, std::unique_ptr<clang::CompilerInvocation, std::default_delete<clang::CompilerInvocation>>, llvm::ArrayRef<clang::clangd::Diag>, std::shared_ptr<clang::clangd::PreambleData const>) (/disk2/dustin/llvm/prefix/bin/clangd+0x1677e48)
#32 0x00005586fa23858a clang::clangd::(anonymous namespace)::ASTWorker::updatePreamble(std::unique_ptr<clang::CompilerInvocation, std::default_delete<clang::CompilerInvocation>>, clang::clangd::ParseInputs, std::shared_ptr<clang::clangd::PreambleData const>, std::vector<clang::clangd::Diag, std::allocator<clang::clangd::Diag>>, clang::clangd::WantDiagnostics)::'lambda'()::operator()() (.part.746) TUScheduler.cpp:0:0
#33 0x00005586fa239999 clang::clangd::(anonymous namespace)::ASTWorker::updatePreamble(std::unique_ptr<clang::CompilerInvocation, std::default_delete<clang::CompilerInvocation>>, clang::clangd::ParseInputs, std::shared_ptr<clang::clangd::PreambleData const>, std::vector<clang::clangd::Diag, std::allocator<clang::clangd::Diag>>, clang::clangd::WantDiagnostics)::'lambda'()::operator()() TUScheduler.cpp:0:0
#34 0x00005586fa22fda9 clang::clangd::(anonymous namespace)::ASTWorker::runTask(llvm::StringRef, llvm::function_ref<void ()>) (.constprop.758) TUScheduler.cpp:0:0
#35 0x00005586fa2372ec clang::clangd::(anonymous namespace)::ASTWorker::run() TUScheduler.cpp:0:0
#36 0x00005586fa3ed382 void* llvm::thread::ThreadProxy<std::tuple<clang::clangd::AsyncTaskRunner::runAsync(llvm::Twine const&, llvm::unique_function<void ()>)::'lambda0'()>>(void*) Threading.cpp:0:0
#37 0x00007f58e4cad6db start_thread /build/glibc-CVJwZb/glibc-2.27/nptl/pthread_create.c:463:0
#38 0x00007f58e39f161f __clone /build/glibc-CVJwZb/glibc-2.27/misc/../sysdeps/unix/sysv/linux/x86_64/clone.S:97:0
Signalled during AST worker action: Build AST

If it's not obvious or reproducible, I'm happy to rebuild using debug symbols or whatever to help out. When I was trying to get it down to a more minimal reproducer it seems to be something about the bitfields that it doesn't like.

virtuald avatar Dec 28 '22 03:12 virtuald

@llvm/issue-subscribers-clangd

llvmbot avatar Dec 28 '22 04:12 llvmbot

The crash happens inside the implementation of the clang-tidy check bugprone-unchecked-optional-access, so as a workaround until the bug is fixed, you can disable the check by adding the following to a .clangd config file in your project root:

Diagnostics:
  ClangTidy:
    Remove: bugprone-unchecked-optional-access

HighCommander4 avatar Dec 28 '22 07:12 HighCommander4

I haven't been able to reproduce the crash so far. It may depend on the code inside <optional>, can you specify which standard library (libstdc++ or libc++) and version you're using?

HighCommander4 avatar Dec 28 '22 07:12 HighCommander4

@llvm/issue-subscribers-clang-tidy

llvmbot avatar Dec 28 '22 14:12 llvmbot

I'm using a compile_commands.json that is using the system g++/libc. I have:

$ g++ --version
g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
$ dpkg -S /usr/include/c++/7/optional
libstdc++-7-dev:amd64: /usr/include/c++/7/optional
$ dpkg -l libstdc++-7-dev
// snipped
libstdc++-7-dev:amd64                                     7.5.0-3ubuntu1~18.04

I'll see if I can make a standalone project that reproduces on my system.

Edit: in case the header does matter, here's it's md5sum:

$ md5sum /usr/include/c++/7/optional
59d8fe05fa6ea813a41acc1da762c915  /usr/include/c++/7/optional

virtuald avatar Dec 28 '22 15:12 virtuald

By itself, it didn't crash. I had to add a compile commands generated by meson. It also doesn't seem to crash the first time in my standalone version, but if I restart clangd from vscode several times it would crash. Here's a command line from clangd after the crash:

Signalled during AST worker action: Build AST
  Filename: ../crash.cpp
  Directory: /disk2/dustin/llvm-crash/build
  Command Line: /disk2/dustin/llvm/prefix/bin/clang --driver-mode=g++ -Ilibcrash.so.p -I. -I.. -fdiagnostics-color=auto -D_FILE_OFFSET_BITS=64 -Wall -Winvalid-pch -Wnon-virtual-dtor -std=gnu++17 -O2 -g -fPIC -MD -MQ libcrash.so.p/crash.cpp.o -MF libcrash.so.p/crash.cpp.o.d -o libcrash.so.p/crash.cpp.o -c -resource-dir=/disk2/dustin/llvm/prefix/lib/clang/15.0.6 -- /disk2/dustin/llvm-crash/crash.cpp
  Version: 2

Also, it does seem to be something about my .clang-tidy and the check that you mentioned. Here's my .clang-tidy:

---
Checks: >
  -*,
  bugprone-unchecked-optional-access
WarningsAsErrors: >
  bugprone-*,
  performance-*
CheckOptions:
- key:             cppcoreguidelines-special-member-functions.AllowMissingMoveFunctionsWhenCopyIsDeleted
  value:           '1'
- key:             readability-implicit-bool-conversion.AllowIntegerConditions
  value:           '1'
- key:             readability-implicit-bool-conversion.AllowPointerConditions
  value:           '1'
- key:             readability-implicit-bool-cast.AllowIntegerConditions
  value:           '1'
- key:             readability-implicit-bool-cast.AllowPointerConditions
  value:           '1'
...

Attached the standalone project in case that's useful: llvm-crash.tar.gz

virtuald avatar Dec 28 '22 16:12 virtuald

Thanks, I can reproduce the crash on your example project. It's intermittent, and it occurs with clangd trunk as well.

HighCommander4 avatar Dec 29 '22 02:12 HighCommander4

Here's the stack trace that I get with trunk:

llvm/src/llvm/include/llvm/Support/Casting.h:578: decltype(auto) llvm::cast(From *) [To = clang::dataflow::BoolValue, From = clang::dataflow::Value]: Assertion `isa<To>(Val) && "cast<Ty>() argument of incompatible type!"' failed.
 #0 0x00007faff93a4f8a llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) llvm/src/llvm/lib/Support/Unix/Signals.inc:567:11
 #1 0x00007faff93a513b PrintStackTraceSignalHandler(void*) llvm/src/llvm/lib/Support/Unix/Signals.inc:641:1
 #2 0x00007faff93a3796 llvm::sys::RunSignalHandlers() llvm/src/llvm/lib/Support/Signals.cpp:104:5
 #3 0x00007faff93a5865 SignalHandler(int) llvm/src/llvm/lib/Support/Unix/Signals.inc:412:1
 #4 0x00007fafffe0a730 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x12730)
 #5 0x00007faff87328eb raise /build/glibc-6iIyft/glibc-2.28/signal/../sysdeps/unix/sysv/linux/raise.c:51:1
 #6 0x00007faff871d535 abort /build/glibc-6iIyft/glibc-2.28/stdlib/abort.c:81:7
 #7 0x00007faff871d40f _nl_load_domain /build/glibc-6iIyft/glibc-2.28/intl/loadmsgcat.c:1177:9
 #8 0x00007faff872b1a2 (/lib/x86_64-linux-gnu/libc.so.6+0x301a2)
 #9 0x00007fafede5c0c8 decltype(auto) llvm::cast<clang::dataflow::BoolValue, clang::dataflow::Value>(clang::dataflow::Value*) llvm/src/llvm/include/llvm/Support/Casting.h:579:10
#10 0x00007fafede531b8 clang::dataflow::mergeDistinctValues(clang::QualType, clang::dataflow::Value&, clang::dataflow::Environment const&, clang::dataflow::Value&, clang::dataflow::Environment const&, clang::dataflow::Environment&, clang::dataflow::Environment::ValueModel&) llvm/src/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp:97:11
#11 0x00007fafede5306d clang::dataflow::Environment::join(clang::dataflow::Environment const&, clang::dataflow::Environment::ValueModel&) llvm/src/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp:477:16
#12 0x00007fafede7b102 clang::dataflow::computeBlockInputState(clang::CFGBlock const&, clang::dataflow::AnalysisContext&) llvm/src/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp:285:5
#13 0x00007fafede7ab3a clang::dataflow::transferCFGBlock(clang::CFGBlock const&, clang::dataflow::AnalysisContext&, std::function<void (clang::CFGElement const&, clang::dataflow::TypeErasedDataflowAnalysisState const&)>) llvm/src/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp:374:30
#14 0x00007fafede7b5a6 clang::dataflow::runTypeErasedDataflowAnalysis(clang::dataflow::ControlFlowContext const&, clang::dataflow::TypeErasedDataflowAnalysis&, clang::dataflow::Environment const&, std::function<void (clang::CFGElement const&, clang::dataflow::TypeErasedDataflowAnalysisState const&)>) llvm/src/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp:448:9
#15 0x00007faff6e693d7 llvm::Expected<std::vector<llvm::Optional<clang::dataflow::DataflowAnalysisState<clang::dataflow::UncheckedOptionalAccessModel::Lattice>>, std::allocator<llvm::Optional<clang::dataflow::DataflowAnalysisState<clang::dataflow::UncheckedOptionalAccessModel::Lattice>>>>> clang::dataflow::runDataflowAnalysis<clang::dataflow::UncheckedOptionalAccessModel>(clang::dataflow::ControlFlowContext const&, clang::dataflow::UncheckedOptionalAccessModel&, clang::dataflow::Environment const&, std::function<void (clang::CFGElement const&, clang::dataflow::DataflowAnalysisState<clang::dataflow::UncheckedOptionalAccessModel::Lattice> const&)>) llvm/src/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h:211:32
#16 0x00007faff6e68521 clang::tidy::bugprone::analyzeFunction(clang::FunctionDecl const&, clang::ASTContext&) llvm/src/clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp:59:28
#17 0x00007faff6e68270 clang::tidy::bugprone::UncheckedOptionalAccessCheck::check(clang::ast_matchers::MatchFinder::MatchResult const&) llvm/src/clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp:100:45
#18 0x00007faffe6282ae clang::tidy::ClangTidyCheck::run(clang::ast_matchers::MatchFinder::MatchResult const&) llvm/src/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp:46:1
#19 0x00007faff3c82308 clang::ast_matchers::internal::(anonymous namespace)::MatchASTVisitor::MatchVisitor::visitMatch(clang::ast_matchers::BoundNodes const&) llvm/src/clang/lib/ASTMatchers/ASTMatchFinder.cpp:1260:7
#20 0x00007faff3dc556a clang::ast_matchers::internal::BoundNodesTreeBuilder::visitMatches(clang::ast_matchers::internal::BoundNodesTreeBuilder::Visitor*) llvm/src/clang/lib/ASTMatchers/ASTMatchersInternal.cpp:104:5
#21 0x00007faff3c81e25 clang::ast_matchers::internal::(anonymous namespace)::MatchASTVisitor::matchWithFilter(clang::DynTypedNode const&) llvm/src/clang/lib/ASTMatchers/ASTMatchFinder.cpp:1056:7
#22 0x00007faff3c81af2 clang::ast_matchers::internal::(anonymous namespace)::MatchASTVisitor::matchDispatch(clang::Decl const*) llvm/src/clang/lib/ASTMatchers/ASTMatchFinder.cpp:1075:5
#23 0x00007faff3c818fd void clang::ast_matchers::internal::(anonymous namespace)::MatchASTVisitor::match<clang::Decl>(clang::Decl const&) llvm/src/clang/lib/ASTMatchers/ASTMatchFinder.cpp:720:3
#24 0x00007faff3c84afd clang::ast_matchers::internal::(anonymous namespace)::MatchASTVisitor::TraverseDecl(clang::Decl*) llvm/src/clang/lib/ASTMatchers/ASTMatchFinder.cpp:1448:3
#25 0x00007faff3c92619 clang::RecursiveASTVisitor<clang::ast_matchers::internal::(anonymous namespace)::MatchASTVisitor>::TraverseTranslationUnitDecl(clang::TranslationUnitDecl*) llvm/src/clang/include/clang/AST/RecursiveASTVisitor.h:1599:1
#26 0x00007faff3c85a76 clang::RecursiveASTVisitor<clang::ast_matchers::internal::(anonymous namespace)::MatchASTVisitor>::TraverseDecl(clang::Decl*) llvm/build/tools/clang/include/clang/AST/DeclNodes.inc:645:1
#27 0x00007faff3c84b0a clang::ast_matchers::internal::(anonymous namespace)::MatchASTVisitor::TraverseDecl(clang::Decl*) llvm/src/clang/lib/ASTMatchers/ASTMatchFinder.cpp:1449:3
#28 0x00007faff3bfb3e2 clang::RecursiveASTVisitor<clang::ast_matchers::internal::(anonymous namespace)::MatchASTVisitor>::TraverseAST(clang::ASTContext&) llvm/src/clang/include/clang/AST/RecursiveASTVisitor.h:188:5
#29 0x00007faff3bfb23c clang::ast_matchers::MatchFinder::matchAST(clang::ASTContext&) llvm/src/clang/lib/ASTMatchers/ASTMatchFinder.cpp:1678:11
#30 0x00007fafff2587d0 clang::clangd::ParsedAST::build(llvm::StringRef, clang::clangd::ParseInputs const&, std::unique_ptr<clang::CompilerInvocation, std::default_delete<clang::CompilerInvocation>>, llvm::ArrayRef<clang::clangd::Diag>, std::shared_ptr<clang::clangd::PreambleData const>) llvm/src/clang-tools-extra/clangd/ParsedAST.cpp:643:3
#31 0x00007fafff3ff686 clang::clangd::(anonymous namespace)::ASTWorker::generateDiagnostics(std::unique_ptr<clang::CompilerInvocation, std::default_delete<clang::CompilerInvocation>>, clang::clangd::ParseInputs, std::vector<clang::clangd::Diag, std::allocator<clang::clangd::Diag>>) llvm/src/clang-tools-extra/clangd/TUScheduler.cpp:1190:40
#32 0x00007fafff3ff340 clang::clangd::(anonymous namespace)::ASTWorker::updatePreamble(std::unique_ptr<clang::CompilerInvocation, std::default_delete<clang::CompilerInvocation>>, clang::clangd::ParseInputs, std::shared_ptr<clang::clangd::PreambleData const>, std::vector<clang::clangd::Diag, std::allocator<clang::clangd::Diag>>, clang::clangd::WantDiagnostics)::$_2::operator()() llvm/src/clang-tools-extra/clangd/TUScheduler.cpp:1124:5
#33 0x00007fafff40127d void llvm::detail::UniqueFunctionBase<void>::CallImpl<clang::clangd::(anonymous namespace)::ASTWorker::updatePreamble(std::unique_ptr<clang::CompilerInvocation, std::default_delete<clang::CompilerInvocation>>, clang::clangd::ParseInputs, std::shared_ptr<clang::clangd::PreambleData const>, std::vector<clang::clangd::Diag, std::allocator<clang::clangd::Diag>>, clang::clangd::WantDiagnostics)::$_2>(void*) llvm/src/llvm/include/llvm/ADT/FunctionExtras.h:221:5
#34 0x00007faffeed10af llvm::unique_function<void ()>::operator()() llvm/src/llvm/include/llvm/ADT/FunctionExtras.h:383:5
#35 0x00007fafff408535 void llvm::function_ref<void ()>::callback_fn<llvm::unique_function<void ()>>(long) llvm/src/llvm/include/llvm/ADT/STLFunctionalExtras.h:45:5
#36 0x00007fafff408519 llvm::function_ref<void ()>::operator()() const llvm/src/llvm/include/llvm/ADT/STLFunctionalExtras.h:68:5
#37 0x00007fafff3fa344 clang::clangd::(anonymous namespace)::ASTWorker::runTask(llvm::StringRef, llvm::function_ref<void ()>) llvm/src/clang-tools-extra/clangd/TUScheduler.cpp:1305:1
#38 0x00007fafff3f9a3a clang::clangd::(anonymous namespace)::ASTWorker::run() llvm/src/clang-tools-extra/clangd/TUScheduler.cpp:1438:5
#39 0x00007fafff3f92cd clang::clangd::(anonymous namespace)::ASTWorker::create(llvm::StringRef, clang::clangd::GlobalCompilationDatabase const&, clang::clangd::TUScheduler::ASTCache&, clang::clangd::TUScheduler::HeaderIncluderCache&, clang::clangd::AsyncTaskRunner*, clang::clangd::Semaphore&, clang::clangd::TUScheduler::Options const&, clang::clangd::ParsingCallbacks&)::$_7::operator()() const llvm/src/clang-tools-extra/clangd/TUScheduler.cpp:820:49
#40 0x00007fafff3f923d void llvm::detail::UniqueFunctionBase<void>::CallImpl<clang::clangd::(anonymous namespace)::ASTWorker::create(llvm::StringRef, clang::clangd::GlobalCompilationDatabase const&, clang::clangd::TUScheduler::ASTCache&, clang::clangd::TUScheduler::HeaderIncluderCache&, clang::clangd::AsyncTaskRunner*, clang::clangd::Semaphore&, clang::clangd::TUScheduler::Options const&, clang::clangd::ParsingCallbacks&)::$_7>(void*) llvm/src/llvm/include/llvm/ADT/FunctionExtras.h:221:5
#41 0x00007faff96e5d8f llvm::unique_function<void ()>::operator()() llvm/src/llvm/include/llvm/ADT/FunctionExtras.h:383:5
#42 0x00007faff96e7f73 clang::clangd::AsyncTaskRunner::runAsync(llvm::Twine const&, llvm::unique_function<void ()>)::$_1::operator()() llvm/src/clang-tools-extra/clangd/support/Threading.cpp:102:14
#43 0x00007faff96e7f15 void llvm::thread::Apply<clang::clangd::AsyncTaskRunner::runAsync(llvm::Twine const&, llvm::unique_function<void ()>)::$_1>(std::tuple<clang::clangd::AsyncTaskRunner::runAsync(llvm::Twine const&, llvm::unique_function<void ()>)::$_1>&, std::integer_sequence<unsigned long>) llvm/src/llvm/include/llvm/Support/thread.h:43:3
#44 0x00007faff96e7ed3 void llvm::thread::GenericThreadProxy<std::tuple<clang::clangd::AsyncTaskRunner::runAsync(llvm::Twine const&, llvm::unique_function<void ()>)::$_1>>(void*) llvm/src/llvm/include/llvm/Support/thread.h:51:3
#45 0x00007faff96e7b85 void* llvm::thread::ThreadProxy<std::tuple<clang::clangd::AsyncTaskRunner::runAsync(llvm::Twine const&, llvm::unique_function<void ()>)::$_1>>(void*) llvm/src/llvm/include/llvm/Support/thread.h:61:5
#46 0x00007fafffdfffa3 start_thread /build/glibc-6iIyft/glibc-2.28/nptl/pthread_create.c:487:7
#47 0x00007faff87f406f __clone /build/glibc-6iIyft/glibc-2.28/misc/../sysdeps/unix/sysv/linux/x86_64/clone.S:97:0
Signalled during AST worker action: Build AST

HighCommander4 avatar Dec 29 '22 02:12 HighCommander4

The crash does occur when running this check with clang-tidy on the command line, it's not specific to clangd.

HighCommander4 avatar Dec 29 '22 02:12 HighCommander4

Reduced testcase:

namespace std {

template <typename T> class optional {
public:
  bool has_value() const noexcept;

  const T &value() const &;
};

}

struct Dst {
  unsigned int n1 : 1;
};

void do_something(Dst *d) {
  const std::optional<bool> v;
  if (v.has_value()) {
    d->n1 = v.value();
  }
}

HighCommander4 avatar Dec 29 '22 02:12 HighCommander4

cc @ymand as the author of the affected checker

HighCommander4 avatar Dec 29 '22 02:12 HighCommander4

Thanks so much!

virtuald avatar Dec 29 '22 03:12 virtuald

Reduced testcase:

namespace std {

template <typename T> class optional {
public:
  bool has_value() const noexcept;

  const T &value() const &;
};

}

struct Dst {
  unsigned int n1 : 1;
};

void do_something(Dst *d) {
  const std::optional<bool> v;
  if (v.has_value()) {
    d->n1 = v.value();
  }
}

I attached GDB and found something interesting.

So IIUC the issue happens in https://github.com/llvm/llvm-project/blob/main/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp#L96

static Value *mergeDistinctValues(QualType Type, Value &Val1,
                                  const Environment &Env1, Value &Val2,
                                  const Environment &Env2,
                                  Environment &MergedEnv,
                                  Environment::ValueModel &Model) {
  // Join distinct boolean values preserving information about the constraints
  // in the respective path conditions.
  if (auto *Expr1 = dyn_cast<BoolValue>(&Val1)) {
    auto *Expr2 = cast<BoolValue>(&Val2);
    // ...
  }

If I add debugString(Val1.getKind()) and debugString(Val2.getKind()) before the if condition and try:

../Debug/bin/clang-tidy --checks="-*, bugprone-unchecked-optional-access" bitfield-crashes-clang-tidy.cc

I got:

❯ ../Debug/bin/clang-tidy --checks="-*, bugprone-unchecked-optional-access" bitfield-crashes-clang-tidy.cc
Val1: Integer
Val2: AtomicBool
Val1: Integer
Val2: AtomicBool
❯ ../Debug/bin/clang-tidy --checks="-*, bugprone-unchecked-optional-access" bitfield-crashes-clang-tidy.cc
Val1: Integer
Val2: AtomicBool
Val1: Integer
Val2: AtomicBool
❯ ../Debug/bin/clang-tidy --checks="-*, bugprone-unchecked-optional-access" bitfield-crashes-clang-tidy.cc
Val1: AtomicBool
Val2: Integer
// crashes!!!                                                                                                                                                                                            

That's quite interesting because the crash is not always reproducible as it depends on some ordering. If Val1 is a AtomicBoolValue (BoolValue) and Val2 is not, then the crash happens.

So I believe this should be a logic error in the code? However, I'm indeed confused about why this will happen (Not an expert in data flow analysis... Is this normal? Or do we have deeper problems?)

junaire avatar Dec 29 '22 06:12 junaire

Submitted https://reviews.llvm.org/D140753

junaire avatar Dec 29 '22 09:12 junaire

Update: It doesn't matter if we have a bitfield or not, the code below is enough to cause a crash, though it's intermittent.

namespace std {

template <typename T> class optional {
public:
  bool has_value() const noexcept;

  const T &value() const &;
};

}

struct Dst {
  unsigned int n1 /*: 1*/;
};

void do_something(Dst *d) {
  const std::optional<bool> v;
  if (v.has_value()) {
    d->n1 = v.value();
  }
}

junaire avatar Dec 29 '22 13:12 junaire

I'm surprised by it being intermittent. But, if I had to guess, I think this makes sense (to cause a crash at that point): on the "then" branch, n1 leaves with a bool value. On the (implicit) else branch, n1 is still an integer. So, (if this is the case), we'll either need to accept the patch your proposed, or change our handling of bool-to-int casts.

ymand avatar Dec 29 '22 14:12 ymand

Confirmed: https://github.com/llvm/llvm-project/blob/af5dd2706c845b8bea6ba9fd3e68c1ee982b01fa/clang/lib/Analysis/FlowSensitive/Transfer.cpp#L331-L352

ymand avatar Dec 29 '22 14:12 ymand

When the underlying type is bool, we should create a fresh integer value.

ymand avatar Dec 29 '22 14:12 ymand

I'm surprised by it being intermittent. But, if I had to guess, I think this makes sense (to cause a crash at that point): on the "then" branch, n1 leaves with a bool value. On the (implicit) else branch, n1 is still an integer. So, (if this is the case), we'll either need to accept the patch your proposed, or change our handling of bool-to-int casts.

Hi, thanks for your explanation, it really helps me to understand the root problem. (At least to some extent! :D )

Though I'm not super familiar with dataflow analysis, I guess you mean we're lacking some necessary logic to handle boolean-to-integral casts. I'm curious about how difficult is it to implement that? I would really like to contribute to this if it's within my ability, but sure it's also OK with me if you think this is a high priority and I can abandon my previous patch. :)

junaire avatar Dec 29 '22 14:12 junaire

Though I'm not super familiar with dataflow analysis, I guess you mean we're lacking some necessary logic to handle boolean-to-integral casts. Right. We essentially ignore all (implicit) integral casts, treating the resulting value as the same as the underlying value:

Env.setStorageLocation(*S, *SubExprLoc)

That line sets S to be identical to SubExpr as far as the analysis is concerned. That is, we don't even allocate a fresh storage location and point to the same value, we just map both expressions to the same storage location.

I'm curious about how difficult is it to implement that? I would really like to contribute to this if it's within my ability, but sure it's also OK with me if you think this is a high priority and I can abandon my previous patch. :) I don't know about the priority of the original poster, but we don't have pressure on our end. This should be fairly easy and local: in the code I pointed to, check whether the underlying value (SubExpr) is of boolean type while the cast is to non-boolean type (or vice versa), and in those circumstances, create a fresh element: fresh storage location, fresh value. You should leave a FIXME of some sort, though, for us to translate between the values once we start modelling booleans.

Thanks for helping out!

ymand avatar Dec 29 '22 15:12 ymand