• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef SRC_TRACING_CORE_TRACE_BUFFER_H_
18 #define SRC_TRACING_CORE_TRACE_BUFFER_H_
19 
20 #include <stdint.h>
21 #include <string.h>
22 
23 #include <array>
24 #include <limits>
25 #include <map>
26 #include <tuple>
27 
28 #include "perfetto/base/logging.h"
29 #include "perfetto/ext/base/paged_memory.h"
30 #include "perfetto/ext/base/thread_annotations.h"
31 #include "perfetto/ext/base/utils.h"
32 #include "perfetto/ext/tracing/core/basic_types.h"
33 #include "perfetto/ext/tracing/core/slice.h"
34 #include "perfetto/ext/tracing/core/trace_stats.h"
35 
36 namespace perfetto {
37 
38 class TracePacket;
39 
40 // The main buffer, owned by the tracing service, where all the trace data is
41 // ultimately stored into. The service will own several instances of this class,
42 // at least one per active consumer (as defined in the |buffers| section of
43 // trace_config.proto) and will copy chunks from the producer's shared memory
44 // buffers into here when a CommitData IPC is received.
45 //
46 // Writing into the buffer
47 // -----------------------
48 // Data is copied from the SMB(s) using CopyChunkUntrusted(). The buffer will
49 // hence contain data coming from different producers and different writer
50 // sequences, more specifically:
51 // - The service receives data by several producer(s), identified by their ID.
52 // - Each producer writes several sequences identified by the same WriterID.
53 //   (they correspond to TraceWriter instances in the producer).
54 // - Each Writer writes, in order, several chunks.
55 // - Each chunk contains zero, one, or more TracePacket(s), or even just
56 //   fragments of packets (when they span across several chunks).
57 //
58 // So at any point in time, the buffer will contain a variable number of logical
59 // sequences identified by the {ProducerID, WriterID} tuple. Any given chunk
60 // will only contain packets (or fragments) belonging to the same sequence.
61 //
62 // The buffer operates by default as a ring buffer.
63 // It has two overwrite policies:
64 //  1. kOverwrite (default): if the write pointer reaches the read pointer, old
65 //     unread chunks will be overwritten by new chunks.
66 //  2. kDiscard: if the write pointer reaches the read pointer, unread chunks
67 //     are preserved and the new chunks are discarded. Any future write becomes
68 //     a no-op, even if the reader manages to fully catch up. This is because
69 //     once a chunk is discarded, the sequence of packets is broken and trying
70 //     to recover would be too hard (also due to the fact that, at the same
71 //     time, we allow out-of-order commits and chunk re-writes).
72 //
73 // Chunks are (over)written in the same order of the CopyChunkUntrusted() calls.
74 // When overwriting old content, entire chunks are overwritten or clobbered.
75 // The buffer never leaves a partial chunk around. Chunks' payload is copied
76 // as-is, but their header is not and is repacked in order to keep the
77 // ProducerID around.
78 //
79 // Chunks are stored in the buffer next to each other. Each chunk is prefixed by
80 // an inline header (ChunkRecord), which contains most of the fields of the
81 // SharedMemoryABI ChunkHeader + the ProducerID + the size of the payload.
82 // It's a conventional binary object stream essentially, where each ChunkRecord
83 // tells where it ends and hence where to find the next one, like this:
84 //
85 //          .-------------------------. 16 byte boundary
86 //          | ChunkRecord:   16 bytes |
87 //          | - chunk id:     4 bytes |
88 //          | - producer id:  2 bytes |
89 //          | - writer id:    2 bytes |
90 //          | - #fragments:   2 bytes |
91 //    +-----+ - record size:  2 bytes |
92 //    |     | - flags+pad:    4 bytes |
93 //    |     +-------------------------+
94 //    |     |                         |
95 //    |     :     Chunk payload       :
96 //    |     |                         |
97 //    |     +-------------------------+
98 //    |     |    Optional padding     |
99 //    +---> +-------------------------+ 16 byte boundary
100 //          |      ChunkRecord        |
101 //          :                         :
102 // Chunks stored in the buffer are always rounded up to 16 bytes (that is
103 // sizeof(ChunkRecord)), in order to avoid further inner fragmentation.
104 // Special "padding" chunks can be put in the buffer, e.g. in the case when we
105 // try to write a chunk of size N while the write pointer is at the end of the
106 // buffer, but the write pointer is < N bytes from the end (and hence needs to
107 // wrap over).
108 // Because of this, the buffer is self-describing: the contents of the buffer
109 // can be reconstructed by just looking at the buffer content (this will be
110 // quite useful in future to recover the buffer from crash reports).
111 //
112 // However, in order to keep some operations (patching and reading) fast, a
113 // lookaside index is maintained (in |index_|), keeping each chunk in the buffer
114 // indexed by their {ProducerID, WriterID, ChunkID} tuple.
115 //
116 // Patching data out-of-band
117 // -------------------------
118 // This buffer also supports patching chunks' payload out-of-band, after they
119 // have been stored. This is to allow producers to backfill the "size" fields
120 // of the protos that spawn across several chunks, when the previous chunks are
121 // returned to the service. The MaybePatchChunkContents() deals with the fact
122 // that a chunk might have been lost (because of wrapping) by the time the OOB
123 // IPC comes.
124 //
125 // Reading from the buffer
126 // -----------------------
127 // This class supports one reader only (the consumer). Reads are NOT idempotent
128 // as they move the read cursors around. Reading back the buffer is the most
129 // conceptually complex part. The ReadNextTracePacket() method operates with
130 // whole packet granularity. Packets are returned only when all their fragments
131 // are available.
132 // This class takes care of:
133 // - Gluing packets within the same sequence, even if they are not stored
134 //   adjacently in the buffer.
135 // - Re-ordering chunks within a sequence (using the ChunkID, which wraps).
136 // - Detecting holes in packet fragments (because of loss of chunks).
137 // Reads guarantee that packets for the same sequence are read in FIFO order
138 // (according to their ChunkID), but don't give any guarantee about the read
139 // order of packets from different sequences, see comments in
140 // ReadNextTracePacket() below.
141 class TraceBuffer {
142  public:
143   static const size_t InlineChunkHeaderSize;  // For test/fake_packet.{cc,h}.
144 
145   // See comment in the header above.
146   enum OverwritePolicy { kOverwrite, kDiscard };
147 
148   // Argument for out-of-band patches applied through TryPatchChunkContents().
149   struct Patch {
150     // From SharedMemoryABI::kPacketHeaderSize.
151     static constexpr size_t kSize = 4;
152 
153     size_t offset_untrusted;
154     std::array<uint8_t, kSize> data;
155   };
156 
157   // Identifiers that are constant for a packet sequence.
158   struct PacketSequenceProperties {
159     ProducerID producer_id_trusted;
160     uid_t producer_uid_trusted;
161     pid_t producer_pid_trusted;
162     WriterID writer_id;
163   };
164 
165   // Can return nullptr if the memory allocation fails.
166   static std::unique_ptr<TraceBuffer> Create(size_t size_in_bytes,
167                                              OverwritePolicy = kOverwrite);
168 
169   ~TraceBuffer();
170 
171   // Copies a Chunk from a producer Shared Memory Buffer into the trace buffer.
172   // |src| points to the first packet in the SharedMemoryABI's chunk shared with
173   // an untrusted producer. "untrusted" here means: the producer might be
174   // malicious and might change |src| concurrently while we read it (internally
175   // this method memcpy()-s first the chunk before processing it). None of the
176   // arguments should be trusted, unless otherwise stated. We can trust that
177   // |src| points to a valid memory area, but not its contents.
178   //
179   // This method may be called multiple times for the same chunk. In this case,
180   // the original chunk's payload will be overridden and its number of fragments
181   // and flags adjusted to match |num_fragments| and |chunk_flags|. The service
182   // may use this to insert partial chunks (|chunk_complete = false|) before the
183   // producer has committed them.
184   //
185   // If |chunk_complete| is |false|, the TraceBuffer will only consider the
186   // first |num_fragments - 1| packets to be complete, since the producer may
187   // not have finished writing the latest packet. Reading from a sequence will
188   // also not progress past any incomplete chunks until they were rewritten with
189   // |chunk_complete = true|, e.g. after a producer's commit.
190   //
191   // TODO(eseckler): Pass in a PacketStreamProperties instead of individual IDs.
192   void CopyChunkUntrusted(ProducerID producer_id_trusted,
193                           uid_t producer_uid_trusted,
194                           pid_t producer_pid_trusted,
195                           WriterID writer_id,
196                           ChunkID chunk_id,
197                           uint16_t num_fragments,
198                           uint8_t chunk_flags,
199                           bool chunk_complete,
200                           const uint8_t* src,
201                           size_t size);
202   // Applies a batch of |patches| to the given chunk, if the given chunk is
203   // still in the buffer. Does nothing if the given ChunkID is gone.
204   // Returns true if the chunk has been found and patched, false otherwise.
205   // |other_patches_pending| is used to determine whether this is the only
206   // batch of patches for the chunk or there is more.
207   // If |other_patches_pending| == false, the chunk is marked as ready to be
208   // consumed. If true, the state of the chunk is not altered.
209   //
210   // Note: If the producer is batching commits (see shared_memory_arbiter.h), it
211   // will also attempt to do patching locally. Namely, if nested messages are
212   // completed while the chunk on which they started is being batched (i.e.
213   // before it has been committed to the service), the producer will apply the
214   // respective patches to the batched chunk. These patches will not be sent to
215   // the service - i.e. only the patches that the producer did not manage to
216   // apply before committing the chunk will be applied here.
217   bool TryPatchChunkContents(ProducerID,
218                              WriterID,
219                              ChunkID,
220                              const Patch* patches,
221                              size_t patches_size,
222                              bool other_patches_pending);
223 
224   // To read the contents of the buffer the caller needs to:
225   //   BeginRead()
226   //   while (ReadNextTracePacket(packet_fragments)) { ... }
227   // No other calls to any other method should be interleaved between
228   // BeginRead() and ReadNextTracePacket().
229   // Reads in the TraceBuffer are NOT idempotent.
230   void BeginRead();
231 
232   // Returns the next packet in the buffer, if any, and the producer_id,
233   // producer_uid, and writer_id of the producer/writer that wrote it (as passed
234   // in the CopyChunkUntrusted() call). Returns false if no packets can be read
235   // at this point. If a packet was read successfully,
236   // |previous_packet_on_sequence_dropped| is set to |true| if the previous
237   // packet on the sequence was dropped from the buffer before it could be read
238   // (e.g. because its chunk was overridden due to the ring buffer wrapping or
239   // due to an ABI violation), and to |false| otherwise.
240   //
241   // This function returns only complete packets. Specifically:
242   // When there is at least one complete packet in the buffer, this function
243   // returns true and populates the TracePacket argument with the boundaries of
244   // each fragment for one packet.
245   // TracePacket will have at least one slice when this function returns true.
246   // When there are no whole packets eligible to read (e.g. we are still missing
247   // fragments) this function returns false.
248   // This function guarantees also that packets for a given
249   // {ProducerID, WriterID} are read in FIFO order.
250   // This function does not guarantee any ordering w.r.t. packets belonging to
251   // different WriterID(s). For instance, given the following packets copied
252   // into the buffer:
253   //   {ProducerID: 1, WriterID: 1}: P1 P2 P3
254   //   {ProducerID: 1, WriterID: 2}: P4 P5 P6
255   //   {ProducerID: 2, WriterID: 1}: P7 P8 P9
256   // The following read sequence is possible:
257   //   P1, P4, P7, P2, P3, P5, P8, P9, P6
258   // But the following is guaranteed to NOT happen:
259   //   P1, P5, P7, P4 (P4 cannot come after P5)
260   bool ReadNextTracePacket(TracePacket*,
261                            PacketSequenceProperties* sequence_properties,
262                            bool* previous_packet_on_sequence_dropped);
263 
stats()264   const TraceStats::BufferStats& stats() const { return stats_; }
size()265   size_t size() const { return size_; }
266 
267  private:
268   friend class TraceBufferTest;
269 
270   // ChunkRecord is a Chunk header stored inline in the |data_| buffer, before
271   // the chunk payload (the packets' data). The |data_| buffer looks like this:
272   // +---------------+------------------++---------------+-----------------+
273   // | ChunkRecord 1 | Chunk payload 1  || ChunkRecord 2 | Chunk payload 2 | ...
274   // +---------------+------------------++---------------+-----------------+
275   // Most of the ChunkRecord fields are copied from SharedMemoryABI::ChunkHeader
276   // (the chunk header used in the shared memory buffers).
277   // A ChunkRecord can be a special "padding" record. In this case its payload
278   // should be ignored and the record should be just skipped.
279   //
280   // Full page move optimization:
281   // This struct has to be exactly (sizeof(PageHeader) + sizeof(ChunkHeader))
282   // (from shared_memory_abi.h) to allow full page move optimizations
283   // (TODO(primiano): not implemented yet). In the special case of moving a full
284   // 4k page that contains only one chunk, in fact, we can just ask the kernel
285   // to move the full SHM page (see SPLICE_F_{GIFT,MOVE}) and overlay the
286   // ChunkRecord on top of the moved SMB's header (page + chunk header).
287   // This special requirement is covered by static_assert(s) in the .cc file.
288   struct ChunkRecord {
ChunkRecordChunkRecord289     explicit ChunkRecord(size_t sz) : flags{0}, is_padding{0} {
290       PERFETTO_DCHECK(sz >= sizeof(ChunkRecord) &&
291                       sz % sizeof(ChunkRecord) == 0 && sz <= kMaxSize);
292       size = static_cast<decltype(size)>(sz);
293     }
294 
is_validChunkRecord295     bool is_valid() const { return size != 0; }
296 
297     // Keep this structure packed and exactly 16 bytes (128 bits) big.
298 
299     // [32 bits] Monotonic counter within the same writer_id.
300     ChunkID chunk_id = 0;
301 
302     // [16 bits] ID of the Producer from which the Chunk was copied from.
303     ProducerID producer_id = 0;
304 
305     // [16 bits] Unique per Producer (but not within the service).
306     // If writer_id == kWriterIdPadding the record should just be skipped.
307     WriterID writer_id = 0;
308 
309     // Number of fragments contained in the chunk.
310     uint16_t num_fragments = 0;
311 
312     // Size in bytes, including sizeof(ChunkRecord) itself.
313     uint16_t size;
314 
315     uint8_t flags : 6;  // See SharedMemoryABI::ChunkHeader::flags.
316     uint8_t is_padding : 1;
317     uint8_t unused_flag : 1;
318 
319     // Not strictly needed, can be reused for more fields in the future. But
320     // right now helps to spot chunks in hex dumps.
321     char unused[3] = {'C', 'H', 'U'};
322 
323     static constexpr size_t kMaxSize =
324         std::numeric_limits<decltype(size)>::max();
325   };
326 
327   // Lookaside index entry. This serves two purposes:
328   // 1) Allow a fast lookup of ChunkRecord by their ID (the tuple
329   //   {ProducerID, WriterID, ChunkID}). This is used when applying out-of-band
330   //   patches to the contents of the chunks after they have been copied into
331   //   the TraceBuffer.
332   // 2) keep the chunks ordered by their ID. This is used when reading back.
333   // 3) Keep metadata about the status of the chunk, e.g. whether the contents
334   //    have been read already and should be skipped in a future read pass.
335   // This struct should not have any field that is essential for reconstructing
336   // the contents of the buffer from a crash dump.
337   struct ChunkMeta {
338     // Key used for sorting in the map.
339     struct Key {
KeyChunkMeta::Key340       Key(ProducerID p, WriterID w, ChunkID c)
341           : producer_id{p}, writer_id{w}, chunk_id{c} {}
342 
KeyChunkMeta::Key343       explicit Key(const ChunkRecord& cr)
344           : Key(cr.producer_id, cr.writer_id, cr.chunk_id) {}
345 
346       // Note that this sorting doesn't keep into account the fact that ChunkID
347       // will wrap over at some point. The extra logic in SequenceIterator deals
348       // with that.
349       bool operator<(const Key& other) const {
350         return std::tie(producer_id, writer_id, chunk_id) <
351                std::tie(other.producer_id, other.writer_id, other.chunk_id);
352       }
353 
354       bool operator==(const Key& other) const {
355         return std::tie(producer_id, writer_id, chunk_id) ==
356                std::tie(other.producer_id, other.writer_id, other.chunk_id);
357       }
358 
359       bool operator!=(const Key& other) const { return !(*this == other); }
360 
361       // These fields should match at all times the corresponding fields in
362       // the |chunk_record|. They are copied here purely for efficiency to avoid
363       // dereferencing the buffer all the time.
364       ProducerID producer_id;
365       WriterID writer_id;
366       ChunkID chunk_id;
367     };
368 
369     enum IndexFlags : uint8_t {
370       // If set, the chunk state was kChunkComplete at the time it was copied.
371       // If unset, the chunk was still kChunkBeingWritten while copied. When
372       // reading from the chunk's sequence, the sequence will not advance past
373       // this chunk until this flag is set.
374       kComplete = 1 << 0,
375 
376       // If set, we skipped the last packet that we read from this chunk e.g.
377       // because we it was a continuation from a previous chunk that was dropped
378       // or due to an ABI violation.
379       kLastReadPacketSkipped = 1 << 1
380     };
381 
ChunkMetaChunkMeta382     ChunkMeta(ChunkRecord* r,
383               uint16_t p,
384               bool complete,
385               uint8_t f,
386               uid_t u,
387               pid_t pid)
388         : chunk_record{r},
389           trusted_uid{u},
390           trusted_pid(pid),
391           flags{f},
392           num_fragments{p} {
393       if (complete)
394         index_flags = kComplete;
395     }
396 
is_completeChunkMeta397     bool is_complete() const { return index_flags & kComplete; }
398 
set_completeChunkMeta399     void set_complete(bool complete) {
400       if (complete) {
401         index_flags |= kComplete;
402       } else {
403         index_flags &= ~kComplete;
404       }
405     }
406 
last_read_packet_skippedChunkMeta407     bool last_read_packet_skipped() const {
408       return index_flags & kLastReadPacketSkipped;
409     }
410 
set_last_read_packet_skippedChunkMeta411     void set_last_read_packet_skipped(bool skipped) {
412       if (skipped) {
413         index_flags |= kLastReadPacketSkipped;
414       } else {
415         index_flags &= ~kLastReadPacketSkipped;
416       }
417     }
418 
419     ChunkRecord* const chunk_record;  // Addr of ChunkRecord within |data_|.
420     const uid_t trusted_uid;          // uid of the producer.
421     const pid_t trusted_pid;          // pid of the producer.
422 
423     // Flags set by TraceBuffer to track the state of the chunk in the index.
424     uint8_t index_flags = 0;
425 
426     // Correspond to |chunk_record->flags| and |chunk_record->num_fragments|.
427     // Copied here for performance reasons (avoids having to dereference
428     // |chunk_record| while iterating over ChunkMeta) and to aid debugging in
429     // case the buffer gets corrupted.
430     uint8_t flags = 0;           // See SharedMemoryABI::ChunkHeader::flags.
431     uint16_t num_fragments = 0;  // Total number of packet fragments.
432 
433     uint16_t num_fragments_read = 0;  // Number of fragments already read.
434 
435     // The start offset of the next fragment (the |num_fragments_read|-th) to be
436     // read. This is the offset in bytes from the beginning of the ChunkRecord's
437     // payload (the 1st fragment starts at |chunk_record| +
438     // sizeof(ChunkRecord)).
439     uint16_t cur_fragment_offset = 0;
440   };
441 
442   using ChunkMap = std::map<ChunkMeta::Key, ChunkMeta>;
443 
444   // Allows to iterate over a sub-sequence of |index_| for all keys belonging to
445   // the same {ProducerID,WriterID}. Furthermore takes into account the wrapping
446   // of ChunkID. Instances are valid only as long as the |index_| is not altered
447   // (can be used safely only between adjacent ReadNextTracePacket() calls).
448   // The order of the iteration will proceed in the following order:
449   // |wrapping_id| + 1 -> |seq_end|, |seq_begin| -> |wrapping_id|.
450   // Practical example:
451   // - Assume that kMaxChunkID == 7
452   // - Assume that we have all 8 chunks in the range (0..7).
453   // - Hence, |seq_begin| == c0, |seq_end| == c7
454   // - Assume |wrapping_id| = 4 (c4 is the last chunk copied over
455   //   through a CopyChunkUntrusted()).
456   // The resulting iteration order will be: c5, c6, c7, c0, c1, c2, c3, c4.
457   struct SequenceIterator {
458     // Points to the 1st key (the one with the numerically min ChunkID).
459     ChunkMap::iterator seq_begin;
460 
461     // Points one past the last key (the one with the numerically max ChunkID).
462     ChunkMap::iterator seq_end;
463 
464     // Current iterator, always >= seq_begin && <= seq_end.
465     ChunkMap::iterator cur;
466 
467     // The latest ChunkID written. Determines the start/end of the sequence.
468     ChunkID wrapping_id;
469 
is_validSequenceIterator470     bool is_valid() const { return cur != seq_end; }
471 
producer_idSequenceIterator472     ProducerID producer_id() const {
473       PERFETTO_DCHECK(is_valid());
474       return cur->first.producer_id;
475     }
476 
writer_idSequenceIterator477     WriterID writer_id() const {
478       PERFETTO_DCHECK(is_valid());
479       return cur->first.writer_id;
480     }
481 
chunk_idSequenceIterator482     ChunkID chunk_id() const {
483       PERFETTO_DCHECK(is_valid());
484       return cur->first.chunk_id;
485     }
486 
487     ChunkMeta& operator*() {
488       PERFETTO_DCHECK(is_valid());
489       return cur->second;
490     }
491 
492     // Moves |cur| to the next chunk in the index.
493     // is_valid() will become false after calling this, if this was the last
494     // entry of the sequence.
495     void MoveNext();
496 
MoveToEndSequenceIterator497     void MoveToEnd() { cur = seq_end; }
498   };
499 
500   enum class ReadAheadResult {
501     kSucceededReturnSlices,
502     kFailedMoveToNextSequence,
503     kFailedStayOnSameSequence,
504   };
505 
506   enum class ReadPacketResult {
507     kSucceeded,
508     kFailedInvalidPacket,
509     kFailedEmptyPacket,
510   };
511 
512   explicit TraceBuffer(OverwritePolicy);
513   TraceBuffer(const TraceBuffer&) = delete;
514   TraceBuffer& operator=(const TraceBuffer&) = delete;
515 
516   bool Initialize(size_t size);
517 
518   // Returns an object that allows to iterate over chunks in the |index_| that
519   // have the same {ProducerID, WriterID} of
520   // |seq_begin.first.{producer,writer}_id|. |seq_begin| must be an iterator to
521   // the first entry in the |index_| that has a different {ProducerID, WriterID}
522   // from the previous one. It is valid for |seq_begin| to be == index_.end()
523   // (i.e. if the index is empty). The iteration takes care of ChunkID wrapping,
524   // by using |last_chunk_id_|.
525   SequenceIterator GetReadIterForSequence(ChunkMap::iterator seq_begin);
526 
527   // Used as a last resort when a buffer corruption is detected.
528   void ClearContentsAndResetRWCursors();
529 
530   // Adds a padding record of the given size (must be a multiple of
531   // sizeof(ChunkRecord)).
532   void AddPaddingRecord(size_t);
533 
534   // Look for contiguous fragment of the same packet starting from |read_iter_|.
535   // If a contiguous packet is found, all the fragments are pushed into
536   // TracePacket and the function returns kSucceededReturnSlices. If not, the
537   // function returns either kFailedMoveToNextSequence or
538   // kFailedStayOnSameSequence, telling the caller to continue looking for
539   // packets.
540   ReadAheadResult ReadAhead(TracePacket*);
541 
542   // Deletes (by marking the record invalid and removing form the index) all
543   // chunks from |wptr_| to |wptr_| + |bytes_to_clear|.
544   // Returns:
545   //   * The size of the gap left between the next valid Chunk and the end of
546   //     the deletion range.
547   //   * 0 if no next valid chunk exists (if the buffer is still zeroed).
548   //   * -1 if the buffer |overwrite_policy_| == kDiscard and the deletion would
549   //     cause unread chunks to be overwritten. In this case the buffer is left
550   //     untouched.
551   // Graphically, assume the initial situation is the following (|wptr_| = 10).
552   // |0        |10 (wptr_)       |30       |40                 |60
553   // +---------+-----------------+---------+-------------------+---------+
554   // | Chunk 1 | Chunk 2         | Chunk 3 | Chunk 4           | Chunk 5 |
555   // +---------+-----------------+---------+-------------------+---------+
556   //           |_________Deletion range_______|~~return value~~|
557   //
558   // A call to DeleteNextChunksFor(32) will remove chunks 2,3,4 and return 18
559   // (60 - 42), the distance between chunk 5 and the end of the deletion range.
560   ssize_t DeleteNextChunksFor(size_t bytes_to_clear);
561 
562   // Decodes the boundaries of the next packet (or a fragment) pointed by
563   // ChunkMeta and pushes that into |TracePacket|. It also increments the
564   // |num_fragments_read| counter.
565   // TracePacket can be nullptr, in which case the read state is still advanced.
566   // When TracePacket is not nullptr, ProducerID must also be not null and will
567   // be updated with the ProducerID that originally wrote the chunk.
568   ReadPacketResult ReadNextPacketInChunk(ChunkMeta*, TracePacket*);
569 
DcheckIsAlignedAndWithinBounds(const uint8_t * ptr)570   void DcheckIsAlignedAndWithinBounds(const uint8_t* ptr) const {
571     PERFETTO_DCHECK(ptr >= begin() && ptr <= end() - sizeof(ChunkRecord));
572     PERFETTO_DCHECK(
573         (reinterpret_cast<uintptr_t>(ptr) & (alignof(ChunkRecord) - 1)) == 0);
574   }
575 
GetChunkRecordAt(uint8_t * ptr)576   ChunkRecord* GetChunkRecordAt(uint8_t* ptr) {
577     DcheckIsAlignedAndWithinBounds(ptr);
578     // We may be accessing a new (empty) record.
579     data_.EnsureCommitted(
580         static_cast<size_t>(ptr + sizeof(ChunkRecord) - begin()));
581     return reinterpret_cast<ChunkRecord*>(ptr);
582   }
583 
584   void DiscardWrite();
585 
586   // |src| can be nullptr (in which case |size| must be ==
587   // record.size - sizeof(ChunkRecord)), for the case of writing a padding
588   // record. |wptr_| is NOT advanced by this function, the caller must do that.
WriteChunkRecord(uint8_t * wptr,const ChunkRecord & record,const uint8_t * src,size_t size)589   void WriteChunkRecord(uint8_t* wptr,
590                         const ChunkRecord& record,
591                         const uint8_t* src,
592                         size_t size) {
593     // Note: |record.size| will be slightly bigger than |size| because of the
594     // ChunkRecord header and rounding, to ensure that all ChunkRecord(s) are
595     // multiple of sizeof(ChunkRecord). The invariant is:
596     // record.size >= |size| + sizeof(ChunkRecord) (== if no rounding).
597     PERFETTO_DCHECK(size <= ChunkRecord::kMaxSize);
598     PERFETTO_DCHECK(record.size >= sizeof(record));
599     PERFETTO_DCHECK(record.size % sizeof(record) == 0);
600     PERFETTO_DCHECK(record.size >= size + sizeof(record));
601     PERFETTO_CHECK(record.size <= size_to_end());
602     DcheckIsAlignedAndWithinBounds(wptr);
603 
604     // We may be writing to this area for the first time.
605     data_.EnsureCommitted(static_cast<size_t>(wptr + record.size - begin()));
606 
607     // Deliberately not a *D*CHECK.
608     PERFETTO_CHECK(wptr + sizeof(record) + size <= end());
609     memcpy(wptr, &record, sizeof(record));
610     if (PERFETTO_LIKELY(src)) {
611       // If the producer modifies the data in the shared memory buffer while we
612       // are copying it to the central buffer, TSAN will (rightfully) flag that
613       // as a race. However the entire purpose of copying the data into the
614       // central buffer is that we can validate it without worrying that the
615       // producer changes it from under our feet, so this race is benign. The
616       // alternative would be to try computing which part of the buffer is safe
617       // to read (assuming a well-behaving client), but the risk of introducing
618       // a bug that way outweighs the benefit.
619       PERFETTO_ANNOTATE_BENIGN_RACE_SIZED(
620           src, size, "Benign race when copying chunk from shared memory.")
621       memcpy(wptr + sizeof(record), src, size);
622     } else {
623       PERFETTO_DCHECK(size == record.size - sizeof(record));
624     }
625     const size_t rounding_size = record.size - sizeof(record) - size;
626     memset(wptr + sizeof(record) + size, 0, rounding_size);
627   }
628 
begin()629   uint8_t* begin() const { return reinterpret_cast<uint8_t*>(data_.Get()); }
end()630   uint8_t* end() const { return begin() + size_; }
size_to_end()631   size_t size_to_end() const { return static_cast<size_t>(end() - wptr_); }
632 
633   base::PagedMemory data_;
634   size_t size_ = 0;            // Size in bytes of |data_|.
635   size_t max_chunk_size_ = 0;  // Max size in bytes allowed for a chunk.
636   uint8_t* wptr_ = nullptr;    // Write pointer.
637 
638   // An index that keeps track of the positions and metadata of each
639   // ChunkRecord.
640   ChunkMap index_;
641 
642   // Read iterator used for ReadNext(). It is reset by calling BeginRead().
643   // It becomes invalid after any call to methods that alters the |index_|.
644   SequenceIterator read_iter_;
645 
646   // See comments at the top of the file.
647   OverwritePolicy overwrite_policy_ = kOverwrite;
648 
649   // Only used when |overwrite_policy_ == kDiscard|. This is set the first time
650   // a write fails because it would overwrite unread chunks.
651   bool discard_writes_ = false;
652 
653   // Keeps track of the highest ChunkID written for a given sequence, taking
654   // into account a potential overflow of ChunkIDs. In the case of overflow,
655   // stores the highest ChunkID written since the overflow.
656   //
657   // TODO(primiano): should clean up keys from this map. Right now it grows
658   // without bounds (although realistically is not a problem unless we have too
659   // many producers/writers within the same trace session).
660   std::map<std::pair<ProducerID, WriterID>, ChunkID> last_chunk_id_written_;
661 
662   // Statistics about buffer usage.
663   TraceStats::BufferStats stats_;
664 
665 #if PERFETTO_DCHECK_IS_ON()
666   bool changed_since_last_read_ = false;
667 #endif
668 
669   // When true disable some DCHECKs that have been put in place to detect
670   // bugs in the producers. This is for tests that feed malicious inputs and
671   // hence mimic a buggy producer.
672   bool suppress_client_dchecks_for_testing_ = false;
673 };
674 
675 }  // namespace perfetto
676 
677 #endif  // SRC_TRACING_CORE_TRACE_BUFFER_H_
678