microsoft / microsoft/STL

Investigate adding `lifetimebound` attributes to important functions

Open
#3,754 2 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement
Dominant language
C++
Stars
11.1k
Forks
1.7k
Avg merge
4d 15h
Merged PRs (30d)
22

Description

The [[clang::lifetimebound]] and [[msvc::lifetimebound]] attributes can detect dangerous usage:

C:\Temp>type woof.cpp
struct X {
    int a;
};

#ifdef __clang__
#define ATTR [[clang::lifetimebound]]
#else
#define ATTR [[msvc::lifetimebound]] // should use _HAS_MSVC_ATTRIBUTE
#endif

const int& f(const X& x ATTR) noexcept {
    return x.a;
}

int main() {
    const int& r = f(X{1729}); // dangerous, emits warning
    (void) r;
}
C:\Temp>clang-cl /EHsc /nologo /W4 /MTd /Od /c woof.cpp
woof.cpp(16,22): warning: temporary bound to local reference 'r' will be destroyed at the end of the full-expression
      [-Wdangling]
    const int& r = f(X{1729}); // dangerous, emits warning
                     ^~~~~~~
1 warning generated.

C:\Temp>set esp.extensions=cppcorecheck.dll

C:\Temp>cl /EHsc /nologo /W4 /MTd /Od /c /analyze:autolog- /analyze:plugin espxengine.dll woof.cpp
woof.cpp
C:\Temp\woof.cpp(16) : warning C26815: The pointer is dangling because it points at a temporary instance which was destroyed.

We should investigate adding these attributes to important functions in the STL.

To avoid regressions, we should:

  • Have an escape hatch
  • Do this gradually
  • Have test coverage (similar to our "include all headers" tests) that verifies that the STL itself is clean with respect this these dangling-reference warnings
  • For each added attribute, manually verify that it detects bogus usage

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked Clang and MSVC lifetimebound attribute documentation and the proposed safeguards in this issue. Identify important STL functions suitable for gradual annotation, add an escape hatch, and provide coverage similar to the existing include-all-headers tests. Done means the STL remains clean under dangling-reference warnings and each attribute is manually verified against bogus usage.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
32/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.