Skip to content

Commit

Permalink
feat core: make sure that labels are not used with integers, leading …
Browse files Browse the repository at this point in the history
…to memory corruption

Before this patch a code like `writer["metric"].ValueWithLabels(value, {{"label_name2", 2}, {"label_name3", "value3"}});` was attempting to create a `LabelView{std::string_view{"label_name2", 2}, std::string_view{"label_name3", "value3"}}`. The second string_view constructor was corrupting memory as it treated "label_name3" and "value3" as two iterators.

Tests: протестировано локально
commit_hash:e16d3d45a6d3f768611762a4b2fca596aba8d6c8
  • Loading branch information
apolukhin committed Nov 29, 2024
1 parent 296cbb9 commit 95bd775
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions core/include/userver/utils/statistics/labels.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,21 @@ class LabelView final {
LabelView() = default;
LabelView(Label&& label) = delete;
explicit LabelView(const Label& label) noexcept;
LabelView(std::string_view name, std::string_view value) noexcept : name_(name), value_(value) {}
constexpr LabelView(std::string_view name, std::string_view value) noexcept : name_(name), value_(value) {}

explicit operator bool() const { return !name_.empty(); }
template <class T, std::enable_if_t<std::is_arithmetic_v<T>>* = nullptr>
constexpr LabelView(std::string_view, T) {
static_assert(sizeof(T) && false, "Labels should not be arithmetic values, only strings!");
}

constexpr explicit operator bool() const { return !name_.empty(); }

std::string_view Name() const { return name_; }
std::string_view Value() const { return value_; }
constexpr std::string_view Name() const { return name_; }
constexpr std::string_view Value() const { return value_; }

private:
std::string_view name_;
std::string_view value_;
std::string_view name_{};
std::string_view value_{};
};

bool operator<(const LabelView& x, const LabelView& y) noexcept;
Expand All @@ -41,6 +46,11 @@ class Label final {
explicit Label(LabelView view);
Label(std::string name, std::string value);

template <class T, std::enable_if_t<std::is_arithmetic_v<T>>* = nullptr>
Label(std::string, T) {
static_assert(sizeof(T) && false, "Labels should not be arithmetic values, only strings!");
}

explicit operator bool() const { return !name_.empty(); }
explicit operator LabelView() const { return {name_, value_}; }

Expand Down

0 comments on commit 95bd775

Please sign in to comment.