Skip to content

False-positive for lifetimebound functions returning a reference to a pointer/view #162834

@usx95

Description

@usx95

This came up while running the new lifetime analysis in Google. We have many false-positives involving absl::StatusOr accessor methods which mark the implicit this object parameter as lifetimebound. This gives false-positives in cases where the StatusOr doesn't own the underlying data (that is when the type is a pointer or view type).

Reproducer: https://godbolt.org/z/oMhdTTv78

#include <iostream>
#include <string>
#include <string_view>

template <class T>
struct StatusOr {
    ~StatusOr() {}
    const T& value() const& [[clang::lifetimebound]] { return data; }

   private:
    T data;
};

StatusOr<std::string_view> getViewOr();
StatusOr<std::string> getStringOr();
StatusOr<std::string*> getPointerOr();

void foo() {
    std::string_view view;
    {
        StatusOr<std::string_view> view_or = getViewOr();
        view = view_or.value();
    }
    std::cout << view;  // error: a use-after-free. Bad!
}

void bar() {
    std::string* pointer;
    {
        StatusOr<std::string*> pointer_or = getPointerOr();
        pointer = pointer_or.value();
    }
    std::cout << *pointer;  // error: a use-after-free. Bad!
}

void foobar() {
    std::string_view view;
    {
        StatusOr<std::string> string_or = getStringOr();
        view = string_or.value();
    }
    std::cout << view;  // error: a use-after-free. Good!
}

See https://godbolt.org/z/EvdTjoq38 for original issue with absl::StatusOr src.

Metadata

Metadata

Assignees

No one assigned

    Labels

    clang:temporal-safetyIssue/FR relating to the lifetime analysis in Clang (-Wdangling, -Wreturn-local-addr)false-positiveWarning fires when it should not

    Type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions