Merge "Use genrule instead of cc_genrule in Android.bp"
diff --git a/include/perfetto/base/weak_ptr.h b/include/perfetto/base/weak_ptr.h
index f004705..070a7f9 100644
--- a/include/perfetto/base/weak_ptr.h
+++ b/include/perfetto/base/weak_ptr.h
@@ -25,6 +25,8 @@
 namespace base {
 
 // A simple WeakPtr for single-threaded cases.
+// Generally keep the WeakPtrFactory as last fields in classes: it makes the
+// WeakPtr(s) invalidate as first thing in the class dtor.
 // Usage:
 // class MyClass {
 //  MyClass() : weak_factory_(this) {}
diff --git a/include/perfetto/ftrace_reader/ftrace_controller.h b/include/perfetto/ftrace_reader/ftrace_controller.h
index 848940e..cfdbc36 100644
--- a/include/perfetto/ftrace_reader/ftrace_controller.h
+++ b/include/perfetto/ftrace_reader/ftrace_controller.h
@@ -144,11 +144,11 @@
   std::unique_ptr<FtraceProcfs> ftrace_procfs_;
   bool listening_for_raw_trace_data_ = false;
   base::TaskRunner* task_runner_ = nullptr;
-  base::WeakPtrFactory<FtraceController> weak_factory_;
   std::vector<size_t> enabled_count_;
   std::unique_ptr<ProtoTranslationTable> table_;
   std::map<size_t, std::unique_ptr<CpuReader>> readers_;
   std::set<FtraceSink*> sinks_;
+  base::WeakPtrFactory<FtraceController> weak_factory_;
   PERFETTO_THREAD_CHECKER(thread_checker_)
 };
 
diff --git a/include/perfetto/ipc/service_proxy.h b/include/perfetto/ipc/service_proxy.h
index d94799f..8e961e1 100644
--- a/include/perfetto/ipc/service_proxy.h
+++ b/include/perfetto/ipc/service_proxy.h
@@ -90,8 +90,8 @@
   ServiceID service_id_ = 0;
   std::map<std::string, MethodID> remote_method_ids_;
   std::map<RequestID, DeferredBase> pending_callbacks_;
-  base::WeakPtrFactory<ServiceProxy> weak_ptr_factory_;
   EventListener* const event_listener_;
+  base::WeakPtrFactory<ServiceProxy> weak_ptr_factory_;
 };
 
 }  // namespace ipc
diff --git a/include/perfetto/protozero/protozero_message.h b/include/perfetto/protozero/protozero_message.h
index 7748f34..ba3e3a2 100644
--- a/include/perfetto/protozero/protozero_message.h
+++ b/include/perfetto/protozero/protozero_message.h
@@ -23,6 +23,7 @@
 
 #include <type_traits>
 
+#include "perfetto/base/logging.h"
 #include "perfetto/protozero/contiguous_memory_range.h"
 #include "perfetto/protozero/proto_utils.h"
 #include "perfetto/protozero/protozero_message_handle.h"
@@ -55,16 +56,24 @@
   // all nested messages) and seals the message. Returns the size of the message
   // (and all nested sub-messages), without taking into account any chunking.
   // Finalize is idempotent and can be called several times w/o side effects.
-  size_t Finalize();
+  uint32_t Finalize();
 
   // Optional. If is_valid() == true, the corresponding memory region (its
   // length == proto_utils::kMessageLengthFieldSize) is backfilled with the size
-  // of this message. This is the mechanism used by messages to backfill their
-  // corresponding size field in the parent message.
-  ContiguousMemoryRange size_field() const { return size_field_; }
-  void set_size_field(const ContiguousMemoryRange& reserved_range) {
-    size_field_ = reserved_range;
-  }
+  // of this message (minus |size_already_written| below). This is the mechanism
+  // used by messages to backfill their corresponding size field in the parent
+  // message.
+  uint8_t* size_field() const { return size_field_; }
+  void set_size_field(uint8_t* size_field) { size_field_ = size_field; }
+
+  // This is to deal with case of backfilling the size of a root (non-nested)
+  // message which is split into multiple chunks. Upon finalization only the
+  // partial size that lies in the last chunk has to be backfilled.
+  void inc_size_already_written(uint32_t sz) { size_already_written_ += sz; }
+
+  ProtoZeroMessage* nested_message() { return nested_message_; }
+
+  bool is_finalized() const { return finalized_; }
 
 #if PROTOZERO_ENABLE_HANDLE_DEBUGGING()
   void set_handle(ProtoZeroMessageHandleBase* handle) { handle_ = handle; }
@@ -94,7 +103,7 @@
   // Proto types: bool, enum (small).
   // Faster version of AppendVarInt for tiny numbers.
   void AppendTinyVarInt(uint32_t field_id, int32_t value) {
-    assert(0 <= value && value < 0x80);
+    PERFETTO_DCHECK(0 <= value && value < 0x80);
     if (nested_message_)
       EndNestedMessage();
 
@@ -154,11 +163,9 @@
   void EndNestedMessage();
 
   void WriteToStream(const uint8_t* src_begin, const uint8_t* src_end) {
-#if PROTOZERO_ENABLE_HANDLE_DEBUGGING()
-    assert(!sealed_);
-#endif
-    assert(src_begin < src_end);
-    const size_t size = static_cast<size_t>(src_end - src_begin);
+    PERFETTO_DCHECK(!finalized_);
+    PERFETTO_DCHECK(src_begin < src_end);
+    const uint32_t size = static_cast<uint32_t>(src_end - src_begin);
     stream_writer_->WriteBytes(src_begin, size);
     size_ += size;
   }
@@ -169,20 +176,23 @@
   // The stream writer interface used for the serialization.
   ScatteredStreamWriter* stream_writer_;
 
-  // Keeps track of the size of the current message.
-  size_t size_;
+  uint8_t* size_field_;
 
-  ContiguousMemoryRange size_field_;
+  // Keeps track of the size of the current message.
+  uint32_t size_;
+
+  // See comment for inc_size_already_written().
+  uint32_t size_already_written_;
+
+  // When true, no more changes to the message are allowed. This is to DCHECK
+  // attempts of writing to a message which has been Finalize()-d.
+  bool finalized_;
 
   // Used to detect attemps to create messages with a nesting level >
   // kMaxNestingDepth. |nesting_depth_| == 0 for root (non-nested) messages.
   uint8_t nesting_depth_;
 
 #if PROTOZERO_ENABLE_HANDLE_DEBUGGING()
-  // When true, no more changes to the message are allowed. This is to DCHECK
-  // attempts of writing to a message which has been Finalize()-d.
-  bool sealed_;
-
   ProtoZeroMessageHandleBase* handle_;
 #endif
 
@@ -193,6 +203,8 @@
   // nested messages are finalized and sealed when any other field is set in the
   // parent message (or the parent message itself is finalized) and cannot be
   // accessed anymore afterwards.
+  // TODO(primiano): optimization: I think that nested_message_, when non-null.
+  // will always be @ (this) + offsetof(nested_messages_arena_).
   ProtoZeroMessage* nested_message_;
 
   // The root message owns the storage for all its nested messages, up to a max
diff --git a/include/perfetto/protozero/protozero_message_handle.h b/include/perfetto/protozero/protozero_message_handle.h
index c7f737a..4179359 100644
--- a/include/perfetto/protozero/protozero_message_handle.h
+++ b/include/perfetto/protozero/protozero_message_handle.h
@@ -48,9 +48,6 @@
   ProtoZeroMessageHandleBase(ProtoZeroMessageHandleBase&&) noexcept;
   ProtoZeroMessageHandleBase& operator=(ProtoZeroMessageHandleBase&&);
 
-  void Finalize();
-  void set_on_finalize(std::function<void(size_t)> f) { on_finalize_ = f; }
-
  protected:
   explicit ProtoZeroMessageHandleBase(ProtoZeroMessage* = nullptr);
   ProtoZeroMessage& operator*() const { return *message_; }
@@ -66,7 +63,6 @@
   void Move(ProtoZeroMessageHandleBase&&);
 
   ProtoZeroMessage* message_;
-  std::function<void(size_t)> on_finalize_;
 };
 
 template <typename T>
diff --git a/include/perfetto/protozero/scattered_stream_writer.h b/include/perfetto/protozero/scattered_stream_writer.h
index 7def807..3f7c09c 100644
--- a/include/perfetto/protozero/scattered_stream_writer.h
+++ b/include/perfetto/protozero/scattered_stream_writer.h
@@ -80,7 +80,7 @@
   // Reserves a fixed amount of bytes to be backfilled later. The reserved range
   // is guaranteed to be contiguous and not span across chunks. |size| has to be
   // <= than the size of a new buffer returned by the Delegate::GetNewBuffer().
-  ContiguousMemoryRange ReserveBytes(size_t size);
+  uint8_t* ReserveBytes(size_t size);
 
   // Fast (but unsafe) version of the above. The caller must have previously
   // checked that there are at least |size| contiguous bytes available.
diff --git a/src/ftrace_reader/ftrace_controller.cc b/src/ftrace_reader/ftrace_controller.cc
index c548e53..08580c3 100644
--- a/src/ftrace_reader/ftrace_controller.cc
+++ b/src/ftrace_reader/ftrace_controller.cc
@@ -58,9 +58,9 @@
                                    std::unique_ptr<ProtoTranslationTable> table)
     : ftrace_procfs_(std::move(ftrace_procfs)),
       task_runner_(task_runner),
-      weak_factory_(this),
       enabled_count_(table->largest_id() + 1),
-      table_(std::move(table)) {}
+      table_(std::move(table)),
+      weak_factory_(this) {}
 
 FtraceController::~FtraceController() {
   for (size_t id = 1; id <= table_->largest_id(); id++) {
diff --git a/src/ipc/client_impl.h b/src/ipc/client_impl.h
index 71934ed..d8cceb1 100644
--- a/src/ipc/client_impl.h
+++ b/src/ipc/client_impl.h
@@ -86,10 +86,11 @@
   base::ScopedFile received_fd_;
   std::map<RequestID, QueuedRequest> queued_requests_;
   std::map<ServiceID, base::WeakPtr<ServiceProxy>> service_bindings_;
-  base::WeakPtrFactory<Client> weak_ptr_factory_;
 
   // Queue of calls to BindService() that happened before the socket connected.
   std::list<base::WeakPtr<ServiceProxy>> queued_bindings_;
+
+  base::WeakPtrFactory<Client> weak_ptr_factory_;
 };
 
 }  // namespace ipc
diff --git a/src/ipc/host_impl.h b/src/ipc/host_impl.h
index f09b32d..bf0c9eb 100644
--- a/src/ipc/host_impl.h
+++ b/src/ipc/host_impl.h
@@ -82,13 +82,13 @@
   static void SendFrame(ClientConnection*, const Frame&, int fd = -1);
 
   base::TaskRunner* const task_runner_;
-  base::WeakPtrFactory<HostImpl> weak_ptr_factory_;
   std::map<ServiceID, ExposedService> services_;
   std::unique_ptr<UnixSocket> sock_;  // The listening socket.
   std::map<ClientID, std::unique_ptr<ClientConnection>> clients_;
   std::map<UnixSocket*, ClientConnection*> clients_by_socket_;
   ServiceID last_service_id_ = 0;
   ClientID last_client_id_ = 0;
+  base::WeakPtrFactory<HostImpl> weak_ptr_factory_;
   PERFETTO_THREAD_CHECKER(thread_checker_)
 };
 
diff --git a/src/ipc/service_proxy.cc b/src/ipc/service_proxy.cc
index 8cdb545..a817764 100644
--- a/src/ipc/service_proxy.cc
+++ b/src/ipc/service_proxy.cc
@@ -28,7 +28,7 @@
 namespace ipc {
 
 ServiceProxy::ServiceProxy(EventListener* event_listener)
-    : weak_ptr_factory_(this), event_listener_(event_listener) {}
+    : event_listener_(event_listener), weak_ptr_factory_(this) {}
 
 ServiceProxy::~ServiceProxy() {
   if (client_ && connected())
diff --git a/src/protozero/protozero_message.cc b/src/protozero/protozero_message.cc
index 195b5c2..b60f366 100644
--- a/src/protozero/protozero_message.cc
+++ b/src/protozero/protozero_message.cc
@@ -53,11 +53,12 @@
 
   stream_writer_ = stream_writer;
   size_ = 0;
-  size_field_.reset();
+  size_field_ = nullptr;
+  size_already_written_ = 0;
   nested_message_ = nullptr;
   nesting_depth_ = 0;
+  finalized_ = false;
 #if PROTOZERO_ENABLE_HANDLE_DEBUGGING()
-  sealed_ = false;
   handle_ = nullptr;
 #endif
 }
@@ -85,25 +86,23 @@
   WriteToStream(src_u8, src_u8 + size);
 }
 
-size_t ProtoZeroMessage::Finalize() {
+uint32_t ProtoZeroMessage::Finalize() {
   if (nested_message_)
     EndNestedMessage();
 
   // Write the length of the nested message a posteriori, using a leading-zero
   // redundant varint encoding.
-  if (size_field_.is_valid()) {
-#if PROTOZERO_ENABLE_HANDLE_DEBUGGING()
-    PERFETTO_DCHECK(!sealed_);
-#endif
+  if (size_field_) {
+    PERFETTO_DCHECK(!finalized_);
     PERFETTO_DCHECK(size_ < proto_utils::kMaxMessageLength);
-    PERFETTO_DCHECK(proto_utils::kMessageLengthFieldSize == size_field_.size());
-    proto_utils::WriteRedundantVarInt(static_cast<uint32_t>(size_),
-                                      size_field_.begin);
-    size_field_.reset();
+    PERFETTO_DCHECK(size_ >= size_already_written_);
+    proto_utils::WriteRedundantVarInt(size_ - size_already_written_,
+                                      size_field_);
+    size_field_ = nullptr;
   }
 
+  finalized_ = true;
 #if PROTOZERO_ENABLE_HANDLE_DEBUGGING()
-  sealed_ = true;
   if (handle_)
     handle_->reset_message();
 #endif
diff --git a/src/protozero/protozero_message_handle.cc b/src/protozero/protozero_message_handle.cc
index 3e2b4e7..79452e7 100644
--- a/src/protozero/protozero_message_handle.cc
+++ b/src/protozero/protozero_message_handle.cc
@@ -18,7 +18,6 @@
 
 #include <utility>
 
-#include "perfetto/base/logging.h"
 #include "perfetto/protozero/protozero_message.h"
 
 namespace protozero {
@@ -33,7 +32,8 @@
 }
 
 ProtoZeroMessageHandleBase::~ProtoZeroMessageHandleBase() {
-  Finalize();
+  if (message_)
+    message_->Finalize();
 }
 
 ProtoZeroMessageHandleBase::ProtoZeroMessageHandleBase(
@@ -45,21 +45,12 @@
     ProtoZeroMessageHandleBase&& other) {
   // If the current handle was pointing to a message and is being reset to a new
   // one, finalize the old message.
-  Finalize();
+  if (message_)
+    message_->Finalize();
   Move(std::move(other));
   return *this;
 }
 
-void ProtoZeroMessageHandleBase::Finalize() {
-  if (!message_)
-    return;
-  const size_t size = message_->Finalize();
-  if (on_finalize_) {
-    on_finalize_(size);
-    on_finalize_ = nullptr;
-  }
-}
-
 void ProtoZeroMessageHandleBase::Move(ProtoZeroMessageHandleBase&& other) {
   // In theory other->message_ could be nullptr, if |other| is a handle that has
   // been std::move-d (and hence empty). There isn't a legitimate use case for
@@ -68,8 +59,6 @@
   // useless null-check.
   message_ = other.message_;
   other.message_ = nullptr;
-  on_finalize_ = std::move(other.on_finalize_);
-  other.on_finalize_ = nullptr;
 #if PROTOZERO_ENABLE_HANDLE_DEBUGGING()
   message_->set_handle(this);
 #endif
diff --git a/src/protozero/protozero_message_unittest.cc b/src/protozero/protozero_message_unittest.cc
index 076612b..4bf66c0 100644
--- a/src/protozero/protozero_message_unittest.cc
+++ b/src/protozero/protozero_message_unittest.cc
@@ -194,9 +194,7 @@
 TEST_F(ProtoZeroMessageTest, BackfillSizeOnFinalization) {
   ProtoZeroMessage* root_msg = NewMessage();
   uint8_t root_msg_size[proto_utils::kMessageLengthFieldSize] = {};
-  root_msg->set_size_field(
-      {&root_msg_size[0],
-       &root_msg_size[proto_utils::kMessageLengthFieldSize]});
+  root_msg->set_size_field(&root_msg_size[0]);
   root_msg->AppendVarInt(1, 0x42);
 
   FakeChildMessage* nested_msg_1 =
@@ -209,6 +207,8 @@
   memset(buf200, 0x42, sizeof(buf200));
   nested_msg_2->AppendBytes(5, buf200, sizeof(buf200));
 
+  root_msg->inc_size_already_written(6);
+
   // The value returned by Finalize() should be == the full size of |root_msg|.
   EXPECT_EQ(217u, root_msg->Finalize());
   EXPECT_EQ(217u, GetNumSerializedBytes());
@@ -216,7 +216,7 @@
   // However the size written in the size field should take into account the
   // inc_size_already_written() call and be equal to 118 - 6 = 112, encoded
   // in a rendundant varint encoding of kMessageLengthFieldSize bytes.
-  EXPECT_STREQ("\xD9\x81\x80\x00", reinterpret_cast<char*>(root_msg_size));
+  EXPECT_STREQ("\xD3\x81\x80\x00", reinterpret_cast<char*>(root_msg_size));
 
   // Skip 2 bytes for the 0x42 varint + 1 byte for the |nested_msg_1| preamble.
   GetNextSerializedBytes(3);
@@ -258,24 +258,18 @@
   uint8_t msg1_size[proto_utils::kMessageLengthFieldSize] = {};
   uint8_t msg2_size[proto_utils::kMessageLengthFieldSize] = {};
   uint8_t msg3_size[proto_utils::kMessageLengthFieldSize] = {};
-  msg1->set_size_field(
-      {&msg1_size[0], &msg1_size[proto_utils::kMessageLengthFieldSize]});
-  msg2->set_size_field(
-      {&msg2_size[0], &msg2_size[proto_utils::kMessageLengthFieldSize]});
-  msg3->set_size_field(
-      {&msg3_size[0], &msg3_size[proto_utils::kMessageLengthFieldSize]});
+  msg1->set_size_field(&msg1_size[0]);
+  msg2->set_size_field(&msg2_size[0]);
+  msg3->set_size_field(&msg3_size[0]);
 
   // Test that the handle going out of scope causes the finalization of the
   // target message and triggers the optional callback.
-  size_t callback_arg = 0;
   {
     ProtoZeroMessageHandle<FakeRootMessage> handle1(msg1);
-    handle1.set_on_finalize([&callback_arg](size_t sz) { callback_arg = sz; });
     handle1->AppendBytes(1 /* field_id */, kTestBytes, 1 /* size */);
     ASSERT_EQ(0u, msg1_size[0]);
   }
   ASSERT_EQ(0x83u, msg1_size[0]);
-  ASSERT_EQ(3u, callback_arg);
 
   // Test that the handle can be late initialized.
   ProtoZeroMessageHandle<FakeRootMessage> handle2(ignored_msg);
@@ -293,8 +287,6 @@
   ProtoZeroMessageHandle<FakeRootMessage> handle3(msg3);
   handle3->AppendBytes(1 /* field_id */, kTestBytes, 4 /* size */);
   ASSERT_EQ(0u, msg3_size[0]);  // msg2 should be NOT finalized yet.
-  callback_arg = 0;
-  handle3.set_on_finalize([&callback_arg](size_t sz) { callback_arg = sz; });
 
   // Both |handle3| and |handle_swp| point to a valid message (respectively,
   // |msg3| and |msg2|). Now move |handle3| into |handle_swp|.
@@ -305,10 +297,8 @@
   ASSERT_EQ(msg3, &*handle_swp);
   handle_swp->AppendBytes(2 /* field_id */, kTestBytes, 8 /* size */);
   ProtoZeroMessageHandle<FakeRootMessage> another_handle(ignored_msg);
-  ASSERT_EQ(0u, callback_arg);
   handle_swp = std::move(another_handle);
   ASSERT_EQ(0x90u, msg3_size[0]);  // |msg3| should be finalized at this point.
-  ASSERT_EQ(0x10u, callback_arg);
 
 #if PROTOZERO_ENABLE_HANDLE_DEBUGGING()
   // In developer builds w/ PERFETTO_DCHECK on a finalized message should
@@ -322,37 +312,36 @@
 
   // Test also the behavior of handle with non-root (nested) messages.
 
-  ContiguousMemoryRange size_msg_2;
+  uint8_t* size_msg_2;
   {
     auto* nested_msg_1 = NewMessage()->BeginNestedMessage<FakeChildMessage>(3);
     ProtoZeroMessageHandle<FakeChildMessage> child_handle_1(nested_msg_1);
-    ContiguousMemoryRange size_msg_1 = nested_msg_1->size_field();
-    memset(size_msg_1.begin, 0, size_msg_1.size());
+    uint8_t* size_msg_1 = nested_msg_1->size_field();
+    memset(size_msg_1, 0, proto_utils::kMessageLengthFieldSize);
     child_handle_1->AppendVarInt(1, 0x11);
 
     auto* nested_msg_2 = NewMessage()->BeginNestedMessage<FakeChildMessage>(2);
     size_msg_2 = nested_msg_2->size_field();
-    memset(size_msg_2.begin, 0, size_msg_2.size());
+    memset(size_msg_2, 0, proto_utils::kMessageLengthFieldSize);
     ProtoZeroMessageHandle<FakeChildMessage> child_handle_2(nested_msg_2);
     child_handle_2->AppendVarInt(2, 0xFF);
 
     // |nested_msg_1| should not be finalized yet.
-    ASSERT_EQ(0u, size_msg_1.begin[0]);
+    ASSERT_EQ(0u, size_msg_1[0]);
 
     // This move should cause |nested_msg_1| to be finalized, but not
     // |nested_msg_2|, which will be finalized only after the current scope.
     child_handle_1 = std::move(child_handle_2);
-    ASSERT_EQ(0x82u, size_msg_1.begin[0]);
-    ASSERT_EQ(0u, size_msg_2.begin[0]);
+    ASSERT_EQ(0x82u, size_msg_1[0]);
+    ASSERT_EQ(0u, size_msg_2[0]);
   }
-  ASSERT_EQ(0x83u, size_msg_2.begin[0]);
+  ASSERT_EQ(0x83u, size_msg_2[0]);
 }
 
 TEST_F(ProtoZeroMessageTest, MoveMessageHandle) {
   FakeRootMessage* msg = NewMessage();
   uint8_t msg_size[proto_utils::kMessageLengthFieldSize] = {};
-  msg->set_size_field(
-      {&msg_size[0], &msg_size[proto_utils::kMessageLengthFieldSize]});
+  msg->set_size_field(&msg_size[0]);
 
   // Test that the handle going out of scope causes the finalization of the
   // target message.
diff --git a/src/protozero/scattered_stream_writer.cc b/src/protozero/scattered_stream_writer.cc
index 23fb12c..e128b5f 100644
--- a/src/protozero/scattered_stream_writer.cc
+++ b/src/protozero/scattered_stream_writer.cc
@@ -56,7 +56,7 @@
 
 // TODO(primiano): perf optimization: I suspect that at the end this will always
 // be called with |size| == 4, in which case we might just hardcode it.
-ContiguousMemoryRange ScatteredStreamWriter::ReserveBytes(size_t size) {
+uint8_t* ScatteredStreamWriter::ReserveBytes(size_t size) {
   if (write_ptr_ + size > cur_range_.end) {
     // Assume the reservations are always < Delegate::GetNewBuffer().size(),
     // so that one single call to Extend() will definitely give enough headroom.
@@ -68,7 +68,7 @@
 #ifndef NDEBUG
   memset(begin, '\xFF', size);
 #endif
-  return {begin, begin + size};
+  return begin;
 }
 
 }  // namespace protozero
diff --git a/src/protozero/scattered_stream_writer_unittest.cc b/src/protozero/scattered_stream_writer_unittest.cc
index 3dc38fb..3b83b4c 100644
--- a/src/protozero/scattered_stream_writer_unittest.cc
+++ b/src/protozero/scattered_stream_writer_unittest.cc
@@ -55,7 +55,7 @@
 
   // This starts at offset 1, to make sure we don't hardcode any assumption
   // about alignment.
-  ContiguousMemoryRange reserved_range_1 = ssw.ReserveBytes(4);
+  uint8_t* reserved_range_1 = ssw.ReserveBytes(4);
   EXPECT_EQ(2u, delegate.chunks().size());
   EXPECT_EQ(3u, ssw.bytes_available());
 
@@ -64,14 +64,14 @@
   EXPECT_EQ(3u, delegate.chunks().size());
   EXPECT_EQ(7u, ssw.bytes_available());
 
-  ContiguousMemoryRange reserved_range_2 = ssw.ReserveBytes(4);
+  uint8_t* reserved_range_2 = ssw.ReserveBytes(4);
   ssw.WriteBytes(kTwentyByteBuf, sizeof(kTwentyByteBuf));
   EXPECT_EQ(6u, delegate.chunks().size());
   EXPECT_EQ(7u, ssw.bytes_available());
 
   // Writing reserved bytes should not change the bytes_available().
-  memcpy(reserved_range_1.begin, kFourByteBuf, sizeof(kFourByteBuf));
-  memcpy(reserved_range_2.begin, kFourByteBuf, sizeof(kFourByteBuf));
+  memcpy(reserved_range_1, kFourByteBuf, sizeof(kFourByteBuf));
+  memcpy(reserved_range_2, kFourByteBuf, sizeof(kFourByteBuf));
   EXPECT_EQ(6u, delegate.chunks().size());
   EXPECT_EQ(7u, ssw.bytes_available());
 
@@ -79,11 +79,11 @@
   // even if the previous one is not exhausted
   for (uint8_t i = 0; i < 5; ++i)
     ssw.WriteByte(0xFF);
-  memcpy(ssw.ReserveBytes(4).begin, kFourByteBuf, sizeof(kFourByteBuf));
+  memcpy(ssw.ReserveBytes(4), kFourByteBuf, sizeof(kFourByteBuf));
   memcpy(ssw.ReserveBytesUnsafe(3), kThreeByteBuf, sizeof(kThreeByteBuf));
-  memcpy(ssw.ReserveBytes(3).begin, kThreeByteBuf, sizeof(kThreeByteBuf));
+  memcpy(ssw.ReserveBytes(3), kThreeByteBuf, sizeof(kThreeByteBuf));
   memcpy(ssw.ReserveBytesUnsafe(1), kOneByteBuf, sizeof(kOneByteBuf));
-  memcpy(ssw.ReserveBytes(1).begin, kOneByteBuf, sizeof(kOneByteBuf));
+  memcpy(ssw.ReserveBytes(1), kOneByteBuf, sizeof(kOneByteBuf));
 
   EXPECT_EQ(8u, delegate.chunks().size());
   EXPECT_EQ(3u, ssw.bytes_available());
diff --git a/src/tracing/ipc/consumer/consumer_ipc_client_impl.h b/src/tracing/ipc/consumer/consumer_ipc_client_impl.h
index 7c93913..b7d4b41 100644
--- a/src/tracing/ipc/consumer/consumer_ipc_client_impl.h
+++ b/src/tracing/ipc/consumer/consumer_ipc_client_impl.h
@@ -81,9 +81,9 @@
   // to |ipc_channel_| and (de)serializes method invocations over the wire.
   ConsumerPortProxy consumer_port_;
 
-  base::WeakPtrFactory<ConsumerIPCClientImpl> weak_ptr_factory_;
-
   bool connected_ = false;
+
+  base::WeakPtrFactory<ConsumerIPCClientImpl> weak_ptr_factory_;
 };
 
 }  // namespace perfetto
diff --git a/src/tracing/ipc/service/producer_ipc_service.h b/src/tracing/ipc/service/producer_ipc_service.h
index ebe7d21..094f8b3 100644
--- a/src/tracing/ipc/service/producer_ipc_service.h
+++ b/src/tracing/ipc/service/producer_ipc_service.h
@@ -101,11 +101,12 @@
   void OnDataSourceRegistered(ipc::ClientID, std::string, DataSourceID);
 
   Service* const core_service_;
-  base::WeakPtrFactory<ProducerIPCService> weak_ptr_factory_;
 
   // Maps IPC clients to ProducerEndpoint instances registered on the
   // |core_service_| business logic.
   std::map<ipc::ClientID, std::unique_ptr<RemoteProducer>> producers_;
+
+  base::WeakPtrFactory<ProducerIPCService> weak_ptr_factory_;
 };
 
 }  // namespace perfetto
diff --git a/src/tracing/test/test_shared_memory.cc b/src/tracing/test/test_shared_memory.cc
index dc5756b..6c1db1f 100644
--- a/src/tracing/test/test_shared_memory.cc
+++ b/src/tracing/test/test_shared_memory.cc
@@ -16,6 +16,7 @@
 
 #include "src/tracing/test/test_shared_memory.h"
 
+#include <stdlib.h>
 #include <string.h>
 
 #include "perfetto/base/logging.h"
@@ -23,8 +24,11 @@
 namespace perfetto {
 
 TestSharedMemory::TestSharedMemory(size_t size) {
-  mem_.reset(new char[size]);
-  memset(mem_.get(), 0, size);
+  void* ptr = nullptr;
+  int res = posix_memalign(&ptr, 4096, size);
+  PERFETTO_CHECK(res == 0 && ptr);
+  mem_.reset(ptr);
+  memset(ptr, 0, size);
   size_ = size;
 }
 
diff --git a/src/tracing/test/test_shared_memory.h b/src/tracing/test/test_shared_memory.h
index 7abfb3e..e074e85 100644
--- a/src/tracing/test/test_shared_memory.h
+++ b/src/tracing/test/test_shared_memory.h
@@ -21,6 +21,7 @@
 
 #include <memory>
 
+#include "perfetto/base/utils.h"
 #include "perfetto/tracing/core/shared_memory.h"
 
 namespace perfetto {
@@ -41,7 +42,7 @@
   void* start() const override { return mem_.get(); }
   size_t size() const override { return size_; }
 
-  std::unique_ptr<char[]> mem_;
+  std::unique_ptr<void, base::FreeDeleter> mem_;
   size_t size_;
 };