Fix UB when WriteBytesUnsafe writes zero bytes
memcpy is not safe to call with NULL, 0 due to a C language bug that was
inherited into C++. The STL functions from <algorithm> (which bottom out
to the right functions anyway) avoid this. See discussion in
https://crrev.com/c/4968444.
Bug: crbug/1394755
Change-Id: Ib2a22bf4b9ea624c238e0c5eec8715f99781da0d
diff --git a/include/perfetto/protozero/scattered_stream_writer.h b/include/perfetto/protozero/scattered_stream_writer.h
index 96329e9..719c490 100644
--- a/include/perfetto/protozero/scattered_stream_writer.h
+++ b/include/perfetto/protozero/scattered_stream_writer.h
@@ -22,6 +22,8 @@
#include <stdint.h>
#include <string.h>
+#include <algorithm>
+
#include "perfetto/base/compiler.h"
#include "perfetto/base/export.h"
#include "perfetto/base/logging.h"
@@ -76,13 +78,13 @@
// Assumes that the caller checked that there is enough headroom.
// TODO(primiano): perf optimization, this is a tracing hot path. The
- // compiler can make strong optimization on memcpy if the size arg is a
+ // compiler can make strong optimization on std::copy if the size arg is a
// constexpr. Make a templated variant of this for fixed-size writes.
// TODO(primiano): restrict / noalias might also help.
inline void WriteBytesUnsafe(const uint8_t* src, size_t size) {
uint8_t* const end = write_ptr_ + size;
assert(end <= cur_range_.end);
- memcpy(write_ptr_, src, size);
+ std::copy(src, src + size, write_ptr_);
write_ptr_ = end;
}