Skip to content

Commit

Permalink
byte_view: avoid UB when determining buffer address from iterator
Browse files Browse the repository at this point in the history
  • Loading branch information
riebl committed Dec 4, 2024
1 parent 08ec1b7 commit 8c70334
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
26 changes: 21 additions & 5 deletions vanetza/common/byte_view.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,26 @@
namespace vanetza
{

byte_view_range::byte_view_range(
const ByteBuffer::const_iterator& begin,
const ByteBuffer::const_iterator& end) :
iterator_range(begin, end)
namespace
{

boost::iterator_range<byte_view_iterator>
make_safe_range(const ByteBuffer::const_iterator& begin, const ByteBuffer::const_iterator& end)
{
if (begin < end) {
byte_view_iterator vbegin { begin };
byte_view_iterator vend { std::next(vbegin, std::distance(begin, end)) };
return boost::iterator_range<byte_view_iterator> { vbegin, vend };
} else {
byte_view_iterator empty;
return boost::iterator_range<byte_view_iterator> { empty, empty };
}
}

}

byte_view_range::byte_view_range(const ByteBuffer::const_iterator& begin, const ByteBuffer::const_iterator& end) :
iterator_range(make_safe_range(begin, end))
{
}

Expand All @@ -19,7 +35,7 @@ byte_view_range::byte_view_range(const byte_view_iterator& begin, const byte_vie
}

byte_view_range::byte_view_range(ByteBuffer&& _buffer) :
iterator_range(_buffer.begin(), _buffer.end()), buffer(std::move(_buffer))
iterator_range(make_safe_range(_buffer.begin(), _buffer.end())), buffer(std::move(_buffer))
{
}

Expand Down
5 changes: 3 additions & 2 deletions vanetza/common/byte_view.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#define BYTE_VIEW_HPP_TXN2ISMB

#include <vanetza/common/byte_buffer.hpp>
#include <boost/core/pointer_traits.hpp>
#include <boost/range/iterator_range.hpp>
#include <iterator>
#include <memory>
Expand All @@ -23,7 +24,7 @@ class byte_view_iterator

byte_view_iterator() = default;
explicit byte_view_iterator(pointer p) : m_iterator(p) {}
explicit byte_view_iterator(const ByteBuffer::const_iterator& it) : m_iterator(&*it) {}
explicit byte_view_iterator(const ByteBuffer::const_iterator& it) : m_iterator(boost::to_address(it)) {}

constexpr value_type operator*() const
{
Expand Down Expand Up @@ -153,7 +154,7 @@ class byte_view_range : private boost::iterator_range<byte_view_iterator>
* \param buffer pass buffer via rvalue
* \note View is valid without limitation
*/
byte_view_range(ByteBuffer&&);
explicit byte_view_range(ByteBuffer&&);

/**
* Get pointer to start of contiguous buffer memory
Expand Down

0 comments on commit 8c70334

Please sign in to comment.