Debian Codegraph @

mozglue/baseprofiler/public/ProfileChunkedBuffer.h

raw
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #ifndef ProfileChunkedBuffer_h
8 #define ProfileChunkedBuffer_h
9
10 #include "mozilla/Attributes.h"
11 #include "mozilla/BaseProfilerDetail.h"
12 #include "mozilla/NotNull.h"
13 #include "mozilla/ProfileBufferChunkManager.h"
14 #include "mozilla/ProfileBufferChunkManagerSingle.h"
15 #include "mozilla/ProfileBufferEntrySerialization.h"
16 #include "mozilla/ProfileChunkedBufferDetail.h"
17 #include "mozilla/RefPtr.h"
18 #include "mozilla/ScopeExit.h"
19 #include "mozilla/Unused.h"
20
21 #include <utility>
22
23 #ifdef DEBUG
24 # include <cstdio>
25 #endif
26
27 namespace mozilla {
28
29 // Thread-safe buffer that can store blocks of different sizes during defined
30 // sessions, using Chunks (from a ChunkManager) as storage.
31 //
32 // Each *block* contains an *entry* and the entry size:
33 // [ entry_size | entry ] [ entry_size | entry ] ...
34 //
35 // *In-session* is a period of time during which `ProfileChunkedBuffer` allows
36 // reading and writing.
37 // *Out-of-session*, the `ProfileChunkedBuffer` object is still valid, but
38 // contains no data, and gracefully denies accesses.
39 //
40 // To write an entry, the buffer reserves a block of sufficient size (to contain
41 // user data of predetermined size), writes the entry size, and lets the caller
42 // fill the entry contents using a ProfileBufferEntryWriter. E.g.:
43 // ```
44 // ProfileChunkedBuffer cb(...);
45 // cb.ReserveAndPut([]() { return sizeof(123); },
46 // [&](Maybe<ProfileBufferEntryWriter>& aEW) {
47 // if (aEW) { aEW->WriteObject(123); }
48 // });
49 // ```
50 // Other `Put...` functions may be used as shortcuts for simple entries.
51 // The objects given to the caller's callbacks should only be used inside the
52 // callbacks and not stored elsewhere, because they keep their own references to
53 // chunk memory and therefore should not live longer.
54 // Different type of objects may be serialized into an entry, see
55 // `ProfileBufferEntryWriter::Serializer` for more information.
56 //
57 // When reading data, the buffer iterates over blocks (it knows how to read the
58 // entry size, and therefore move to the next block), and lets the caller read
59 // the entry inside of each block. E.g.:
60 // ```
61 // cb.ReadEach([](ProfileBufferEntryReader& aER) {
62 // /* Use ProfileBufferEntryReader functions to read serialized objects. */
63 // int n = aER.ReadObject<int>();
64 // });
65 // ```
66 // Different type of objects may be deserialized from an entry, see
67 // `ProfileBufferEntryReader::Deserializer` for more information.
68 //
69 // Writers may retrieve the block index corresponding to an entry
70 // (`ProfileBufferBlockIndex` is an opaque type preventing the user from easily
71 // modifying it). That index may later be used with `ReadAt` to get back to the
72 // entry in that particular block -- if it still exists.
73 class ProfileChunkedBuffer {
74 public:
75 using Byte = ProfileBufferChunk::Byte;
76 using Length = ProfileBufferChunk::Length;
77
78 enum class ThreadSafety { WithoutMutex, WithMutex };
79
80 // Default constructor starts out-of-session (nothing to read or write).
81 explicit ProfileChunkedBuffer(ThreadSafety aThreadSafety)
82 : mMutex(aThreadSafety != ThreadSafety::WithoutMutex) {}
83
84 // Start in-session with external chunk manager.
85 ProfileChunkedBuffer(ThreadSafety aThreadSafety,
86 ProfileBufferChunkManager& aChunkManager)
87 : mMutex(aThreadSafety != ThreadSafety::WithoutMutex) {
88 SetChunkManager(aChunkManager);
89 }
90
91 // Start in-session with owned chunk manager.
92 ProfileChunkedBuffer(ThreadSafety aThreadSafety,
93 UniquePtr<ProfileBufferChunkManager>&& aChunkManager)
94 : mMutex(aThreadSafety != ThreadSafety::WithoutMutex) {
95 SetChunkManager(std::move(aChunkManager));
96 }
97
98 ~ProfileChunkedBuffer() {
99 // Do proper clean-up by resetting the chunk manager.
100 ResetChunkManager();
101 }
102
103 // This cannot change during the lifetime of this buffer, so there's no need
104 // to lock.
105 [[nodiscard]] bool IsThreadSafe() const { return mMutex.IsActivated(); }
106
107 [[nodiscard]] bool IsInSession() const {
108 baseprofiler::detail::BaseProfilerMaybeAutoLock lock(mMutex);
109 return !!mChunkManager;
110 }
111
112 // Stop using the current chunk manager.
113 // If we own the current chunk manager, it will be destroyed.
114 // This will always clear currently-held chunks, if any.
115 void ResetChunkManager() {
116 baseprofiler::detail::BaseProfilerMaybeAutoLock lock(mMutex);
117 Unused << ResetChunkManager(lock);
118 }
119
120 // Set the current chunk manager.
121 // The caller is responsible for keeping the chunk manager alive as along as
122 // it's used here (until the next (Re)SetChunkManager, or
123 // ~ProfileChunkedBuffer).
124 void SetChunkManager(ProfileBufferChunkManager& aChunkManager) {
125 baseprofiler::detail::BaseProfilerMaybeAutoLock lock(mMutex);
126 Unused << ResetChunkManager(lock);
127 SetChunkManager(aChunkManager, lock);
128 }
129
130 // Set the current chunk manager, and keep ownership of it.
131 void SetChunkManager(UniquePtr<ProfileBufferChunkManager>&& aChunkManager) {
132 baseprofiler::detail::BaseProfilerMaybeAutoLock lock(mMutex);
133 Unused << ResetChunkManager(lock);
134 mOwnedChunkManager = std::move(aChunkManager);
135 if (mOwnedChunkManager) {
136 SetChunkManager(*mOwnedChunkManager, lock);
137 }
138 }
139
140 // Set the current chunk manager, except if it's already the one provided.
141 // The caller is responsible for keeping the chunk manager alive as along as
142 // it's used here (until the next (Re)SetChunkManager, or
143 // ~ProfileChunkedBuffer).
144 void SetChunkManagerIfDifferent(ProfileBufferChunkManager& aChunkManager) {
145 baseprofiler::detail::BaseProfilerMaybeAutoLock lock(mMutex);
146 if (!mChunkManager || mChunkManager != &aChunkManager) {
147 Unused << ResetChunkManager(lock);
148 SetChunkManager(aChunkManager, lock);
149 }
150 }
151
152 // Clear the contents of this buffer, ready to receive new chunks.
153 // Note that memory is not freed: No chunks are destroyed, they are all
154 // receycled.
155 // Also the range doesn't reset, instead it continues at some point after the
156 // previous range. This may be useful if the caller may be keeping indexes
157 // into old chunks that have now been cleared, using these indexes will fail
158 // gracefully (instead of potentially pointing into new data).
159 void Clear() {
160 baseprofiler::detail::BaseProfilerMaybeAutoLock lock(mMutex);
161 if (MOZ_UNLIKELY(!mChunkManager)) {
162 // Out-of-session.
163 return;
164 }
165
166 mRangeStart = mRangeEnd = mNextChunkRangeStart;
167 mPushedBlockCount = 0;
168 mClearedBlockCount = 0;
169 mFailedPutBytes = 0;
170
171 // Recycle all released chunks as "next" chunks. This will reduce the number
172 // of future allocations. Also, when using ProfileBufferChunkManagerSingle,
173 // this retrieves the one chunk if it was released.
174 UniquePtr<ProfileBufferChunk> releasedChunks =
175 mChunkManager->GetExtantReleasedChunks();
176 if (releasedChunks) {
177 // Released chunks should be in the "Done" state, they need to be marked
178 // "recycled" before they can be reused.
179 for (ProfileBufferChunk* chunk = releasedChunks.get(); chunk;
180 chunk = chunk->GetNext()) {
181 chunk->MarkRecycled();
182 }
183 mNextChunks = ProfileBufferChunk::Join(std::move(mNextChunks),
184 std::move(releasedChunks));
185 }
186
187 if (mCurrentChunk) {
188 // We already have a current chunk (empty or in-use), mark it "done" and
189 // then "recycled", ready to be reused.
190 mCurrentChunk->MarkDone();
191 mCurrentChunk->MarkRecycled();
192 } else {
193 if (!mNextChunks) {
194 // No current chunk, and no next chunks to recycle, nothing more to do.
195 // The next "Put" operation will try to allocate a chunk as needed.
196 return;
197 }
198
199 // No current chunk, take a next chunk.
200 mCurrentChunk = std::exchange(mNextChunks, mNextChunks->ReleaseNext());
201 }
202
203 // Here, there was already a current chunk, or one has just been taken.
204 // Make sure it's ready to receive new entries.
205 InitializeCurrentChunk(lock);
206 }
207
208 // Buffer maximum length in bytes.
209 Maybe<size_t> BufferLength() const {
210 baseprofiler::detail::BaseProfilerMaybeAutoLock lock(mMutex);
211 if (!mChunkManager) {
212 return Nothing{};
213 }
214 return Some(mChunkManager->MaxTotalSize());
215 }
216
217 [[nodiscard]] size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
218 baseprofiler::detail::BaseProfilerMaybeAutoLock lock(mMutex);
219 return SizeOfExcludingThis(aMallocSizeOf, lock);
220 }
221
222 [[nodiscard]] size_t SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
223 baseprofiler::detail::BaseProfilerMaybeAutoLock lock(mMutex);
224 return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf, lock);
225 }
226
227 // Snapshot of the buffer state.
228 struct State {
229 // Index to/before the first block.
230 ProfileBufferIndex mRangeStart = 1;
231
232 // Index past the last block. Equals mRangeStart if empty.
233 ProfileBufferIndex mRangeEnd = 1;
234
235 // Number of blocks that have been pushed into this buffer.
236 uint64_t mPushedBlockCount = 0;
237
238 // Number of blocks that have been removed from this buffer.
239 // Note: Live entries = pushed - cleared.
240 uint64_t mClearedBlockCount = 0;
241
242 // Number of bytes that could not be put into this buffer.
243 uint64_t mFailedPutBytes = 0;
244 };
245
246 // Get a snapshot of the current state.
247 // When out-of-session, mFirstReadIndex==mNextWriteIndex, and
248 // mPushedBlockCount==mClearedBlockCount==0.
249 // Note that these may change right after this thread-safe call, so they
250 // should only be used for statistical purposes.
251 [[nodiscard]] State GetState() const {
252 baseprofiler::detail::BaseProfilerMaybeAutoLock lock(mMutex);
253 return {mRangeStart, mRangeEnd, mPushedBlockCount, mClearedBlockCount,
254 mFailedPutBytes};
255 }
256
257 // In in-session, return the start TimeStamp of the earliest chunk.
258 // If out-of-session, return a null TimeStamp.
259 [[nodiscard]] TimeStamp GetEarliestChunkStartTimeStamp() const {
260 baseprofiler::detail::BaseProfilerMaybeAutoLock lock(mMutex);
261 if (MOZ_UNLIKELY(!mChunkManager)) {
262 // Out-of-session.
263 return {};
264 }
265 return mChunkManager->PeekExtantReleasedChunks(
266 [&](const ProfileBufferChunk* aOldestChunk) -> TimeStamp {
267 if (aOldestChunk) {
268 return aOldestChunk->ChunkHeader().mStartTimeStamp;
269 }
270 if (mCurrentChunk) {
271 return mCurrentChunk->ChunkHeader().mStartTimeStamp;
272 }
273 return {};
274 });
275 }
276
277 [[nodiscard]] bool IsEmpty() const {
278 baseprofiler::detail::BaseProfilerMaybeAutoLock lock(mMutex);
279 return mRangeStart == mRangeEnd;
280 }
281
282 // True if this buffer is already locked on this thread.
283 // This should be used if some functions may call an already-locked buffer,
284 // e.g.: Put -> memory hook -> profiler_add_native_allocation_marker -> Put.
285 [[nodiscard]] bool IsThreadSafeAndLockedOnCurrentThread() const {
286 return mMutex.IsActivatedAndLockedOnCurrentThread();
287 }
288
289 // Lock the buffer mutex and run the provided callback.
290 // This can be useful when the caller needs to explicitly lock down this
291 // buffer, but not do anything else with it.
292 template <typename Callback>
293 auto LockAndRun(Callback&& aCallback) const {
294 baseprofiler::detail::BaseProfilerMaybeAutoLock lock(mMutex);
295 return std::forward<Callback>(aCallback)();
296 }
297
298 // Reserve a block that can hold an entry of the given `aCallbackEntryBytes()`
299 // size, write the entry size (ULEB128-encoded), and invoke and return
300 // `aCallback(Maybe<ProfileBufferEntryWriter>&)`.
301 // Note: `aCallbackEntryBytes` is a callback instead of a simple value, to
302 // delay this potentially-expensive computation until after we're checked that
303 // we're in-session; use `Put(Length, Callback)` below if you know the size
304 // already.
305 template <typename CallbackEntryBytes, typename Callback>
306 auto ReserveAndPut(CallbackEntryBytes&& aCallbackEntryBytes,
307 Callback&& aCallback)
308 -> decltype(std::forward<Callback>(aCallback)(
309 std::declval<Maybe<ProfileBufferEntryWriter>&>())) {
310 baseprofiler::detail::BaseProfilerMaybeAutoLock lock(mMutex);
311
312 // This can only be read in the 2nd lambda below after it has been written
313 // by the first lambda.
314 Length entryBytes;
315
316 return ReserveAndPutRaw(
317 [&]() {
318 entryBytes = std::forward<CallbackEntryBytes>(aCallbackEntryBytes)();
319 MOZ_ASSERT(entryBytes != 0, "Empty entries are not allowed");
320 return ULEB128Size(entryBytes) + entryBytes;
321 },
322 [&](Maybe<ProfileBufferEntryWriter>& aMaybeEntryWriter) {
323 if (aMaybeEntryWriter.isSome()) {
324 aMaybeEntryWriter->WriteULEB128(entryBytes);
325 MOZ_ASSERT(aMaybeEntryWriter->RemainingBytes() == entryBytes);
326 }
327 return std::forward<Callback>(aCallback)(aMaybeEntryWriter);
328 },
329 lock);
330 }
331
332 template <typename Callback>
333 auto Put(Length aEntryBytes, Callback&& aCallback) {
334 return ReserveAndPut([aEntryBytes]() { return aEntryBytes; },
335 std::forward<Callback>(aCallback));
336 }
337
338 // Add a new entry copied from the given buffer, return block index.
339 ProfileBufferBlockIndex PutFrom(const void* aSrc, Length aBytes) {
340 return ReserveAndPut(
341 [aBytes]() { return aBytes; },
342 [aSrc, aBytes](Maybe<ProfileBufferEntryWriter>& aMaybeEntryWriter) {
343 if (aMaybeEntryWriter.isNothing()) {
344 return ProfileBufferBlockIndex{};
345 }
346 aMaybeEntryWriter->WriteBytes(aSrc, aBytes);
347 return aMaybeEntryWriter->CurrentBlockIndex();
348 });
349 }
350
351 // Add a new single entry with *all* given object (using a Serializer for
352 // each), return block index.
353 template <typename... Ts>
354 ProfileBufferBlockIndex PutObjects(const Ts&... aTs) {
355 static_assert(sizeof...(Ts) > 0,
356 "PutObjects must be given at least one object.");
357 return ReserveAndPut(
358 [&]() { return ProfileBufferEntryWriter::SumBytes(aTs...); },
359 [&](Maybe<ProfileBufferEntryWriter>& aMaybeEntryWriter) {
360 if (aMaybeEntryWriter.isNothing()) {
361 return ProfileBufferBlockIndex{};
362 }
363 aMaybeEntryWriter->WriteObjects(aTs...);
364 return aMaybeEntryWriter->CurrentBlockIndex();
365 });
366 }
367
368 // Add a new entry copied from the given object, return block index.
369 template <typename T>
370 ProfileBufferBlockIndex PutObject(const T& aOb) {
371 return PutObjects(aOb);
372 }
373
374 // Get *all* chunks related to this buffer, including extant chunks in its
375 // ChunkManager, and yet-unused new/recycled chunks.
376 // We don't expect this buffer to be used again, though it's still possible
377 // and will allocate the first buffer when needed.
378 [[nodiscard]] UniquePtr<ProfileBufferChunk> GetAllChunks() {
379 baseprofiler::detail::BaseProfilerMaybeAutoLock lock(mMutex);
380 if (MOZ_UNLIKELY(!mChunkManager)) {
381 // Out-of-session.
382 return nullptr;
383 }
384 UniquePtr<ProfileBufferChunk> chunks =
385 mChunkManager->GetExtantReleasedChunks();
386 Unused << HandleRequestedChunk_IsPending(lock);
387 if (MOZ_LIKELY(!!mCurrentChunk)) {
388 mCurrentChunk->MarkDone();
389 chunks =
390 ProfileBufferChunk::Join(std::move(chunks), std::move(mCurrentChunk));
391 }
392 chunks =
393 ProfileBufferChunk::Join(std::move(chunks), std::move(mNextChunks));
394 mChunkManager->ForgetUnreleasedChunks();
395 mRangeStart = mRangeEnd = mNextChunkRangeStart;
396 return chunks;
397 }
398
399 // True if the given index points inside the current chunk (up to the last
400 // written byte).
401 // This could be used to check if an index written now would have a good
402 // chance of referring to a previous block that has not been destroyed yet.
403 // But use with extreme care: This information may become incorrect right
404 // after this function returns, because new writes could start a new chunk.
405 [[nodiscard]] bool IsIndexInCurrentChunk(ProfileBufferIndex aIndex) const {
406 baseprofiler::detail::BaseProfilerMaybeAutoLock lock(mMutex);
407 if (MOZ_UNLIKELY(!mChunkManager || !mCurrentChunk)) {
408 // Out-of-session, or no current chunk.
409 return false;
410 }
411 return (mCurrentChunk->RangeStart() <= aIndex) &&
412 (aIndex < (mCurrentChunk->RangeStart() +
413 mCurrentChunk->OffsetPastLastBlock()));
414 }
415
416 class Reader;
417
418 // Class that can iterate through blocks and provide
419 // `ProfileBufferEntryReader`s.
420 // Created through `Reader`, lives within a lock guard lifetime.
421 class BlockIterator {
422 public:
423 #ifdef DEBUG
424 ~BlockIterator() {
425 // No BlockIterator should live outside of a mutexed call.
426 mBuffer->mMutex.AssertCurrentThreadOwns();
427 }
428 #endif // DEBUG
429
430 // Comparison with other iterator, mostly used in range-for loops.
431 [[nodiscard]] bool operator==(const BlockIterator& aRhs) const {
432 MOZ_ASSERT(mBuffer == aRhs.mBuffer);
433 return mCurrentBlockIndex == aRhs.mCurrentBlockIndex;
434 }
435 [[nodiscard]] bool operator!=(const BlockIterator& aRhs) const {
436 MOZ_ASSERT(mBuffer == aRhs.mBuffer);
437 return mCurrentBlockIndex != aRhs.mCurrentBlockIndex;
438 }
439
440 // Advance to next BlockIterator.
441 BlockIterator& operator++() {
442 mBuffer->mMutex.AssertCurrentThreadOwns();
443 mCurrentBlockIndex =
444 ProfileBufferBlockIndex::CreateFromProfileBufferIndex(
445 mNextBlockPointer.GlobalRangePosition());
446 mCurrentEntry =
447 mNextBlockPointer.EntryReader(mNextBlockPointer.ReadEntrySize());
448 return *this;
449 }
450
451 // Dereferencing creates a `ProfileBufferEntryReader` object for the entry
452 // inside this block.
453 // (Note: It would be possible to return a `const
454 // ProfileBufferEntryReader&`, but not useful in practice, because in most
455 // case the user will want to read, which is non-const.)
456 [[nodiscard]] ProfileBufferEntryReader operator*() const {
457 return mCurrentEntry;
458 }
459
460 // True if this iterator is just past the last entry.
461 [[nodiscard]] bool IsAtEnd() const {
462 return mCurrentEntry.RemainingBytes() == 0;
463 }
464
465 // Can be used as reference to come back to this entry with `GetEntryAt()`.
466 [[nodiscard]] ProfileBufferBlockIndex CurrentBlockIndex() const {
467 return mCurrentBlockIndex;
468 }
469
470 // Index past the end of this block, which is the start of the next block.
471 [[nodiscard]] ProfileBufferBlockIndex NextBlockIndex() const {
472 MOZ_ASSERT(!IsAtEnd());
473 return ProfileBufferBlockIndex::CreateFromProfileBufferIndex(
474 mNextBlockPointer.GlobalRangePosition());
475 }
476
477 // Index of the first block in the whole buffer.
478 [[nodiscard]] ProfileBufferBlockIndex BufferRangeStart() const {
479 mBuffer->mMutex.AssertCurrentThreadOwns();
480 return ProfileBufferBlockIndex::CreateFromProfileBufferIndex(
481 mBuffer->mRangeStart);
482 }
483
484 // Index past the last block in the whole buffer.
485 [[nodiscard]] ProfileBufferBlockIndex BufferRangeEnd() const {
486 mBuffer->mMutex.AssertCurrentThreadOwns();
487 return ProfileBufferBlockIndex::CreateFromProfileBufferIndex(
488 mBuffer->mRangeEnd);
489 }
490
491 private:
492 // Only a Reader can instantiate a BlockIterator.
493 friend class Reader;
494
495 BlockIterator(const ProfileChunkedBuffer& aBuffer,
496 const ProfileBufferChunk* aChunks0,
497 const ProfileBufferChunk* aChunks1,
498 ProfileBufferBlockIndex aBlockIndex)
499 : mNextBlockPointer(aChunks0, aChunks1, aBlockIndex),
500 mCurrentBlockIndex(
501 ProfileBufferBlockIndex::CreateFromProfileBufferIndex(
502 mNextBlockPointer.GlobalRangePosition())),
503 mCurrentEntry(
504 mNextBlockPointer.EntryReader(mNextBlockPointer.ReadEntrySize())),
505 mBuffer(WrapNotNull(&aBuffer)) {
506 // No BlockIterator should live outside of a mutexed call.
507 mBuffer->mMutex.AssertCurrentThreadOwns();
508 }
509
510 profiler::detail::InChunkPointer mNextBlockPointer;
511
512 ProfileBufferBlockIndex mCurrentBlockIndex;
513
514 ProfileBufferEntryReader mCurrentEntry;
515
516 // Using a non-null pointer instead of a reference, to allow copying.
517 // This BlockIterator should only live inside one of the thread-safe
518 // ProfileChunkedBuffer functions, for this reference to stay valid.
519 NotNull<const ProfileChunkedBuffer*> mBuffer;
520 };
521
522 // Class that can create `BlockIterator`s (e.g., for range-for), or just
523 // iterate through entries; lives within a lock guard lifetime.
524 class MOZ_RAII Reader {
525 public:
526 Reader(const Reader&) = delete;
527 Reader& operator=(const Reader&) = delete;
528 Reader(Reader&&) = delete;
529 Reader& operator=(Reader&&) = delete;
530
531 #ifdef DEBUG
532 ~Reader() {
533 // No Reader should live outside of a mutexed call.
534 mBuffer.mMutex.AssertCurrentThreadOwns();
535 }
536 #endif // DEBUG
537
538 // Index of the first block in the whole buffer.
539 [[nodiscard]] ProfileBufferBlockIndex BufferRangeStart() const {
540 mBuffer.mMutex.AssertCurrentThreadOwns();
541 return ProfileBufferBlockIndex::CreateFromProfileBufferIndex(
542 mBuffer.mRangeStart);
543 }
544
545 // Index past the last block in the whole buffer.
546 [[nodiscard]] ProfileBufferBlockIndex BufferRangeEnd() const {
547 mBuffer.mMutex.AssertCurrentThreadOwns();
548 return ProfileBufferBlockIndex::CreateFromProfileBufferIndex(
549 mBuffer.mRangeEnd);
550 }
551
552 // Iterators to the first and past-the-last blocks.
553 // Compatible with range-for (see `ForEach` below as example).
554 [[nodiscard]] BlockIterator begin() const {
555 return BlockIterator(mBuffer, mChunks0, mChunks1, nullptr);
556 }
557 // Note that a `BlockIterator` at the `end()` should not be dereferenced, as
558 // there is no actual block there!
559 [[nodiscard]] BlockIterator end() const {
560 return BlockIterator(mBuffer, nullptr, nullptr, nullptr);
561 }
562
563 // Get a `BlockIterator` at the given `ProfileBufferBlockIndex`, clamped to
564 // the stored range. Note that a `BlockIterator` at the `end()` should not
565 // be dereferenced, as there is no actual block there!
566 [[nodiscard]] BlockIterator At(ProfileBufferBlockIndex aBlockIndex) const {
567 if (aBlockIndex < BufferRangeStart()) {
568 // Anything before the range (including null ProfileBufferBlockIndex) is
569 // clamped at the beginning.
570 return begin();
571 }
572 // Otherwise we at least expect the index to be valid (pointing exactly at
573 // a live block, or just past the end.)
574 return BlockIterator(mBuffer, mChunks0, mChunks1, aBlockIndex);
575 }
576
577 // Run `aCallback(ProfileBufferEntryReader&)` on each entry from first to
578 // last. Callback should not store `ProfileBufferEntryReader`, as it may
579 // become invalid after this thread-safe call.
580 template <typename Callback>
581 void ForEach(Callback&& aCallback) const {
582 for (ProfileBufferEntryReader reader : *this) {
583 aCallback(reader);
584 }
585 }
586
587 // If this reader only points at one chunk with some data, this data will be
588 // exposed as a single entry.
589 [[nodiscard]] ProfileBufferEntryReader SingleChunkDataAsEntry() {
590 const ProfileBufferChunk* onlyNonEmptyChunk = nullptr;
591 for (const ProfileBufferChunk* chunkList : {mChunks0, mChunks1}) {
592 for (const ProfileBufferChunk* chunk = chunkList; chunk;
593 chunk = chunk->GetNext()) {
594 if (chunk->OffsetFirstBlock() != chunk->OffsetPastLastBlock()) {
595 if (onlyNonEmptyChunk) {
596 // More than one non-empty chunk.
597 return ProfileBufferEntryReader();
598 }
599 onlyNonEmptyChunk = chunk;
600 }
601 }
602 }
603 if (!onlyNonEmptyChunk) {
604 // No non-empty chunks.
605 return ProfileBufferEntryReader();
606 }
607 // Here, we have found one chunk that had some data.
608 return ProfileBufferEntryReader(
609 onlyNonEmptyChunk->BufferSpan().FromTo(
610 onlyNonEmptyChunk->OffsetFirstBlock(),
611 onlyNonEmptyChunk->OffsetPastLastBlock()),
612 ProfileBufferBlockIndex::CreateFromProfileBufferIndex(
613 onlyNonEmptyChunk->RangeStart()),
614 ProfileBufferBlockIndex::CreateFromProfileBufferIndex(
615 onlyNonEmptyChunk->RangeStart() +
616 (onlyNonEmptyChunk->OffsetPastLastBlock() -
617 onlyNonEmptyChunk->OffsetFirstBlock())));
618 }
619
620 private:
621 friend class ProfileChunkedBuffer;
622
623 explicit Reader(const ProfileChunkedBuffer& aBuffer,
624 const ProfileBufferChunk* aChunks0,
625 const ProfileBufferChunk* aChunks1)
626 : mBuffer(aBuffer), mChunks0(aChunks0), mChunks1(aChunks1) {
627 // No Reader should live outside of a mutexed call.
628 mBuffer.mMutex.AssertCurrentThreadOwns();
629 }
630
631 // This Reader should only live inside one of the thread-safe
632 // ProfileChunkedBuffer functions, for this reference to stay valid.
633 const ProfileChunkedBuffer& mBuffer;
634 const ProfileBufferChunk* mChunks0;
635 const ProfileBufferChunk* mChunks1;
636 };
637
638 // In in-session, call `aCallback(ProfileChunkedBuffer::Reader&)` and return
639 // true. Callback should not store `Reader`, because it may become invalid
640 // after this call.
641 // If out-of-session, return false (callback is not invoked).
642 template <typename Callback>
643 [[nodiscard]] auto Read(Callback&& aCallback) const {
644 baseprofiler::detail::BaseProfilerMaybeAutoLock lock(mMutex);
645 if (MOZ_UNLIKELY(!mChunkManager)) {
646 // Out-of-session.
647 return std::forward<Callback>(aCallback)(static_cast<Reader*>(nullptr));
648 }
649 return mChunkManager->PeekExtantReleasedChunks(
650 [&](const ProfileBufferChunk* aOldestChunk) {
651 Reader reader(*this, aOldestChunk, mCurrentChunk.get());
652 return std::forward<Callback>(aCallback)(&reader);
653 });
654 }
655
656 // Invoke `aCallback(ProfileBufferEntryReader& [, ProfileBufferBlockIndex])`
657 // on each entry, it must read or at least skip everything. Either/both chunk
658 // pointers may be null.
659 template <typename Callback>
660 static void ReadEach(const ProfileBufferChunk* aChunks0,
661 const ProfileBufferChunk* aChunks1,
662 Callback&& aCallback) {
663 static_assert(std::is_invocable_v<Callback, ProfileBufferEntryReader&> ||
664 std::is_invocable_v<Callback, ProfileBufferEntryReader&,
665 ProfileBufferBlockIndex>,
666 "ReadEach callback must take ProfileBufferEntryReader& and "
667 "optionally a ProfileBufferBlockIndex");
668 profiler::detail::InChunkPointer p{aChunks0, aChunks1};
669 while (!p.IsNull()) {
670 // The position right before an entry size *is* a block index.
671 const ProfileBufferBlockIndex blockIndex =
672 ProfileBufferBlockIndex::CreateFromProfileBufferIndex(
673 p.GlobalRangePosition());
674 Length entrySize = p.ReadEntrySize();
675 if (entrySize == 0) {
676 return;
677 }
678 ProfileBufferEntryReader entryReader = p.EntryReader(entrySize);
679 if (entryReader.RemainingBytes() == 0) {
680 return;
681 }
682 MOZ_ASSERT(entryReader.RemainingBytes() == entrySize);
683 if constexpr (std::is_invocable_v<Callback, ProfileBufferEntryReader&,
684 ProfileBufferBlockIndex>) {
685 aCallback(entryReader, blockIndex);
686 } else {
687 Unused << blockIndex;
688 aCallback(entryReader);
689 }
690 MOZ_ASSERT(entryReader.RemainingBytes() == 0);
691 }
692 }
693
694 // Invoke `aCallback(ProfileBufferEntryReader& [, ProfileBufferBlockIndex])`
695 // on each entry, it must read or at least skip everything.
696 template <typename Callback>
697 void ReadEach(Callback&& aCallback) const {
698 baseprofiler::detail::BaseProfilerMaybeAutoLock lock(mMutex);
699 if (MOZ_UNLIKELY(!mChunkManager)) {
700 // Out-of-session.
701 return;
702 }
703 mChunkManager->PeekExtantReleasedChunks(
704 [&](const ProfileBufferChunk* aOldestChunk) {
705 ReadEach(aOldestChunk, mCurrentChunk.get(),
706 std::forward<Callback>(aCallback));
707 });
708 }
709
710 // Call `aCallback(Maybe<ProfileBufferEntryReader>&&)` on the entry at
711 // the given ProfileBufferBlockIndex; The `Maybe` will be `Nothing` if
712 // out-of-session, or if that entry doesn't exist anymore, or if we've reached
713 // just past the last entry. Return whatever `aCallback` returns. Callback
714 // should not store `ProfileBufferEntryReader`, because it may become invalid
715 // after this call.
716 // Either/both chunk pointers may be null.
717 template <typename Callback>
718 [[nodiscard]] static auto ReadAt(ProfileBufferBlockIndex aMinimumBlockIndex,
719 const ProfileBufferChunk* aChunks0,
720 const ProfileBufferChunk* aChunks1,
721 Callback&& aCallback) {
722 static_assert(
723 std::is_invocable_v<Callback, Maybe<ProfileBufferEntryReader>&&>,
724 "ReadAt callback must take a Maybe<ProfileBufferEntryReader>&&");
725 Maybe<ProfileBufferEntryReader> maybeEntryReader;
726 if (profiler::detail::InChunkPointer p{aChunks0, aChunks1}; !p.IsNull()) {
727 // If the pointer position is before the given position, try to advance.
728 if (p.GlobalRangePosition() >=
729 aMinimumBlockIndex.ConvertToProfileBufferIndex() ||
730 p.AdvanceToGlobalRangePosition(
731 aMinimumBlockIndex.ConvertToProfileBufferIndex())) {
732 MOZ_ASSERT(p.GlobalRangePosition() >=
733 aMinimumBlockIndex.ConvertToProfileBufferIndex());
734 // Here we're pointing at the start of a block, try to read the entry
735 // size. (Entries cannot be empty, so 0 means failure.)
736 if (Length entrySize = p.ReadEntrySize(); entrySize != 0) {
737 maybeEntryReader.emplace(p.EntryReader(entrySize));
738 if (maybeEntryReader->RemainingBytes() == 0) {
739 // An empty entry reader means there was no complete block at the
740 // given index.
741 maybeEntryReader.reset();
742 } else {
743 MOZ_ASSERT(maybeEntryReader->RemainingBytes() == entrySize);
744 }
745 }
746 }
747 }
748 #ifdef DEBUG
749 auto assertAllRead = MakeScopeExit([&]() {
750 MOZ_ASSERT(!maybeEntryReader || maybeEntryReader->RemainingBytes() == 0);
751 });
752 #endif // DEBUG
753 return std::forward<Callback>(aCallback)(std::move(maybeEntryReader));
754 }
755
756 // Call `aCallback(Maybe<ProfileBufferEntryReader>&&)` on the entry at
757 // the given ProfileBufferBlockIndex; The `Maybe` will be `Nothing` if
758 // out-of-session, or if that entry doesn't exist anymore, or if we've reached
759 // just past the last entry. Return whatever `aCallback` returns. Callback
760 // should not store `ProfileBufferEntryReader`, because it may become invalid
761 // after this call.
762 template <typename Callback>
763 [[nodiscard]] auto ReadAt(ProfileBufferBlockIndex aBlockIndex,
764 Callback&& aCallback) const {
765 baseprofiler::detail::BaseProfilerMaybeAutoLock lock(mMutex);
766 if (MOZ_UNLIKELY(!mChunkManager)) {
767 // Out-of-session.
768 return std::forward<Callback>(aCallback)(Nothing{});
769 }
770 return mChunkManager->PeekExtantReleasedChunks(
771 [&](const ProfileBufferChunk* aOldestChunk) {
772 return ReadAt(aBlockIndex, aOldestChunk, mCurrentChunk.get(),
773 std::forward<Callback>(aCallback));
774 });
775 }
776
777 // Append the contents of another ProfileChunkedBuffer to this one.
778 ProfileBufferBlockIndex AppendContents(const ProfileChunkedBuffer& aSrc) {
779 ProfileBufferBlockIndex firstBlockIndex;
780 // If we start failing, we'll stop writing.
781 bool failed = false;
782 aSrc.ReadEach([&](ProfileBufferEntryReader& aER) {
783 if (failed) {
784 return;
785 }
786 failed =
787 !Put(aER.RemainingBytes(), [&](Maybe<ProfileBufferEntryWriter>& aEW) {
788 if (aEW.isNothing()) {
789 return false;
790 }
791 if (!firstBlockIndex) {
792 firstBlockIndex = aEW->CurrentBlockIndex();
793 }
794 aEW->WriteFromReader(aER, aER.RemainingBytes());
795 return true;
796 });
797 });
798 return failed ? nullptr : firstBlockIndex;
799 }
800
801 #ifdef DEBUG
802 void Dump(std::FILE* aFile = stdout) const {
803 baseprofiler::detail::BaseProfilerMaybeAutoLock lock(mMutex);
804 fprintf(aFile,
805 "ProfileChunkedBuffer[%p] State: range %u-%u pushed=%u cleared=%u "
806 "(live=%u) failed-puts=%u bytes",
807 this, unsigned(mRangeStart), unsigned(mRangeEnd),
808 unsigned(mPushedBlockCount), unsigned(mClearedBlockCount),
809 unsigned(mPushedBlockCount) - unsigned(mClearedBlockCount),
810 unsigned(mFailedPutBytes));
811 if (MOZ_UNLIKELY(!mChunkManager)) {
812 fprintf(aFile, " - Out-of-session\n");
813 return;
814 }
815 fprintf(aFile, " - chunks:\n");
816 bool hasChunks = false;
817 mChunkManager->PeekExtantReleasedChunks(
818 [&](const ProfileBufferChunk* aOldestChunk) {
819 for (const ProfileBufferChunk* chunk = aOldestChunk; chunk;
820 chunk = chunk->GetNext()) {
821 fprintf(aFile, "R ");
822 chunk->Dump(aFile);
823 hasChunks = true;
824 }
825 });
826 if (mCurrentChunk) {
827 fprintf(aFile, "C ");
828 mCurrentChunk->Dump(aFile);
829 hasChunks = true;
830 }
831 for (const ProfileBufferChunk* chunk = mNextChunks.get(); chunk;
832 chunk = chunk->GetNext()) {
833 fprintf(aFile, "N ");
834 chunk->Dump(aFile);
835 hasChunks = true;
836 }
837 switch (mRequestedChunkHolder->GetState()) {
838 case RequestedChunkRefCountedHolder::State::Unused:
839 fprintf(aFile, " - No request pending.\n");
840 break;
841 case RequestedChunkRefCountedHolder::State::Requested:
842 fprintf(aFile, " - Request pending.\n");
843 break;
844 case RequestedChunkRefCountedHolder::State::Fulfilled:
845 fprintf(aFile, " - Request fulfilled.\n");
846 break;
847 }
848 if (!hasChunks) {
849 fprintf(aFile, " No chunks.\n");
850 }
851 }
852 #endif // DEBUG
853
854 private:
855 // Used to de/serialize a ProfileChunkedBuffer (e.g., containing a backtrace).
856 friend ProfileBufferEntryWriter::Serializer<ProfileChunkedBuffer>;
857 friend ProfileBufferEntryReader::Deserializer<ProfileChunkedBuffer>;
858 friend ProfileBufferEntryWriter::Serializer<UniquePtr<ProfileChunkedBuffer>>;
859 friend ProfileBufferEntryReader::Deserializer<
860 UniquePtr<ProfileChunkedBuffer>>;
861
862 [[nodiscard]] UniquePtr<ProfileBufferChunkManager> ResetChunkManager(
863 const baseprofiler::detail::BaseProfilerMaybeAutoLock&) {
864 UniquePtr<ProfileBufferChunkManager> chunkManager;
865 if (mChunkManager) {
866 mRequestedChunkHolder = nullptr;
867 mChunkManager->ForgetUnreleasedChunks();
868 #ifdef DEBUG
869 mChunkManager->DeregisteredFrom(this);
870 #endif
871 mChunkManager = nullptr;
872 chunkManager = std::move(mOwnedChunkManager);
873 if (mCurrentChunk) {
874 mCurrentChunk->MarkDone();
875 mCurrentChunk = nullptr;
876 }
877 mNextChunks = nullptr;
878 mNextChunkRangeStart = mRangeEnd;
879 mRangeStart = mRangeEnd;
880 mPushedBlockCount = 0;
881 mClearedBlockCount = 0;
882 mFailedPutBytes = 0;
883 }
884 return chunkManager;
885 }
886
887 void SetChunkManager(
888 ProfileBufferChunkManager& aChunkManager,
889 const baseprofiler::detail::BaseProfilerMaybeAutoLock& aLock) {
890 MOZ_ASSERT(!mChunkManager);
891 mChunkManager = &aChunkManager;
892 #ifdef DEBUG
893 mChunkManager->RegisteredWith(this);
894 #endif
895
896 mChunkManager->SetChunkDestroyedCallback(
897 [this](const ProfileBufferChunk& aChunk) {
898 for (;;) {
899 ProfileBufferIndex rangeStart = mRangeStart;
900 if (MOZ_LIKELY(rangeStart <= aChunk.RangeStart())) {
901 if (MOZ_LIKELY(mRangeStart.compareExchange(
902 rangeStart,
903 aChunk.RangeStart() + aChunk.BufferBytes()))) {
904 break;
905 }
906 }
907 }
908 mClearedBlockCount += aChunk.BlockCount();
909 });
910
911 // We start with one chunk right away, and request a following one now
912 // so it should be available before the current chunk is full.
913 SetAndInitializeCurrentChunk(mChunkManager->GetChunk(), aLock);
914 mRequestedChunkHolder = MakeRefPtr<RequestedChunkRefCountedHolder>();
915 RequestChunk(aLock);
916 }
917
918 [[nodiscard]] size_t SizeOfExcludingThis(
919 MallocSizeOf aMallocSizeOf,
920 const baseprofiler::detail::BaseProfilerMaybeAutoLock&) const {
921 if (MOZ_UNLIKELY(!mChunkManager)) {
922 // Out-of-session.
923 return 0;
924 }
925 size_t size = mChunkManager->SizeOfIncludingThis(aMallocSizeOf);
926 if (mCurrentChunk) {
927 size += mCurrentChunk->SizeOfIncludingThis(aMallocSizeOf);
928 }
929 if (mNextChunks) {
930 size += mNextChunks->SizeOfIncludingThis(aMallocSizeOf);
931 }
932 return size;
933 }
934
935 void InitializeCurrentChunk(
936 const baseprofiler::detail::BaseProfilerMaybeAutoLock&) {
937 MOZ_ASSERT(!!mCurrentChunk);
938 mCurrentChunk->SetRangeStart(mNextChunkRangeStart);
939 mNextChunkRangeStart += mCurrentChunk->BufferBytes();
940 Unused << mCurrentChunk->ReserveInitialBlockAsTail(0);
941 }
942
943 void SetAndInitializeCurrentChunk(
944 UniquePtr<ProfileBufferChunk>&& aChunk,
945 const baseprofiler::detail::BaseProfilerMaybeAutoLock& aLock) {
946 mCurrentChunk = std::move(aChunk);
947 if (mCurrentChunk) {
948 InitializeCurrentChunk(aLock);
949 }
950 }
951
952 void RequestChunk(
953 const baseprofiler::detail::BaseProfilerMaybeAutoLock& aLock) {
954 if (HandleRequestedChunk_IsPending(aLock)) {
955 // There is already a pending request, don't start a new one.
956 return;
957 }
958
959 // Ensure the `RequestedChunkHolder` knows we're starting a request.
960 mRequestedChunkHolder->StartRequest();
961
962 // Request a chunk, the callback carries a `RefPtr` of the
963 // `RequestedChunkHolder`, so it's guaranteed to live until it's invoked,
964 // even if this `ProfileChunkedBuffer` changes its `ChunkManager` or is
965 // destroyed.
966 mChunkManager->RequestChunk(
967 [requestedChunkHolder = RefPtr<RequestedChunkRefCountedHolder>(
968 mRequestedChunkHolder)](UniquePtr<ProfileBufferChunk> aChunk) {
969 requestedChunkHolder->AddRequestedChunk(std::move(aChunk));
970 });
971 }
972
973 [[nodiscard]] bool HandleRequestedChunk_IsPending(
974 const baseprofiler::detail::BaseProfilerMaybeAutoLock& aLock) {
975 MOZ_ASSERT(!!mChunkManager);
976 MOZ_ASSERT(!!mRequestedChunkHolder);
977
978 if (mRequestedChunkHolder->GetState() ==
979 RequestedChunkRefCountedHolder::State::Unused) {
980 return false;
981 }
982
983 // A request is either in-flight or fulfilled.
984 Maybe<UniquePtr<ProfileBufferChunk>> maybeChunk =
985 mRequestedChunkHolder->GetChunkIfFulfilled();
986 if (maybeChunk.isNothing()) {
987 // Request is still pending.
988 return true;
989 }
990
991 // Since we extracted the provided chunk, the holder should now be unused.
992 MOZ_ASSERT(mRequestedChunkHolder->GetState() ==
993 RequestedChunkRefCountedHolder::State::Unused);
994
995 // Request has been fulfilled.
996 UniquePtr<ProfileBufferChunk>& chunk = *maybeChunk;
997 if (chunk) {
998 // Try to use as current chunk if needed.
999 if (!mCurrentChunk) {
1000 SetAndInitializeCurrentChunk(std::move(chunk), aLock);
1001 // We've just received a chunk and made it current, request a next chunk
1002 // for later.
1003 MOZ_ASSERT(!mNextChunks);
1004 RequestChunk(aLock);
1005 return true;
1006 }
1007
1008 if (!mNextChunks) {
1009 mNextChunks = std::move(chunk);
1010 } else {
1011 mNextChunks->InsertNext(std::move(chunk));
1012 }
1013 }
1014
1015 return false;
1016 }
1017
1018 // Get a pointer to the next chunk available
1019 [[nodiscard]] ProfileBufferChunk* GetOrCreateCurrentChunk(
1020 const baseprofiler::detail::BaseProfilerMaybeAutoLock& aLock) {
1021 ProfileBufferChunk* current = mCurrentChunk.get();
1022 if (MOZ_UNLIKELY(!current)) {
1023 // No current chunk ready.
1024 MOZ_ASSERT(!mNextChunks,
1025 "There shouldn't be next chunks when there is no current one");
1026 // See if a request has recently been fulfilled, ignore pending status.
1027 Unused << HandleRequestedChunk_IsPending(aLock);
1028 current = mCurrentChunk.get();
1029 if (MOZ_UNLIKELY(!current)) {
1030 // There was no pending chunk, try to get one right now.
1031 // This may still fail, but we can't do anything else about it, the
1032 // caller must handle the nullptr case.
1033 // Attempt a request for later.
1034 SetAndInitializeCurrentChunk(mChunkManager->GetChunk(), aLock);
1035 current = mCurrentChunk.get();
1036 }
1037 }
1038 return current;
1039 }
1040
1041 // Get a pointer to the next chunk available
1042 [[nodiscard]] ProfileBufferChunk* GetOrCreateNextChunk(
1043 const baseprofiler::detail::BaseProfilerMaybeAutoLock& aLock) {
1044 MOZ_ASSERT(!!mCurrentChunk,
1045 "Why ask for a next chunk when there isn't even a current one?");
1046 ProfileBufferChunk* next = mNextChunks.get();
1047 if (MOZ_UNLIKELY(!next)) {
1048 // No next chunk ready, see if a request has recently been fulfilled,
1049 // ignore pending status.
1050 Unused << HandleRequestedChunk_IsPending(aLock);
1051 next = mNextChunks.get();
1052 if (MOZ_UNLIKELY(!next)) {
1053 // There was no pending chunk, try to get one right now.
1054 mNextChunks = mChunkManager->GetChunk();
1055 next = mNextChunks.get();
1056 // This may still fail, but we can't do anything else about it, the
1057 // caller must handle the nullptr case.
1058 if (MOZ_UNLIKELY(!next)) {
1059 // Attempt a request for later.
1060 RequestChunk(aLock);
1061 }
1062 }
1063 }
1064 return next;
1065 }
1066
1067 // Reserve a block of `aCallbackBlockBytes()` size, and invoke and return
1068 // `aCallback(Maybe<ProfileBufferEntryWriter>&)`. Note that this is the "raw"
1069 // version that doesn't write the entry size at the beginning of the block.
1070 // Note: `aCallbackBlockBytes` is a callback instead of a simple value, to
1071 // delay this potentially-expensive computation until after we're checked that
1072 // we're in-session; use `Put(Length, Callback)` below if you know the size
1073 // already.
1074 template <typename CallbackBlockBytes, typename Callback>
1075 auto ReserveAndPutRaw(CallbackBlockBytes&& aCallbackBlockBytes,
1076 Callback&& aCallback,
1077 baseprofiler::detail::BaseProfilerMaybeAutoLock& aLock,
1078 uint64_t aBlockCount = 1) {
1079 // The entry writer that will point into one or two chunks to write
1080 // into, empty by default (failure).
1081 Maybe<ProfileBufferEntryWriter> maybeEntryWriter;
1082
1083 // The current chunk will be filled if we need to write more than its
1084 // remaining space.
1085 bool currentChunkFilled = false;
1086
1087 // If the current chunk gets filled, we may or may not initialize the next
1088 // chunk!
1089 bool nextChunkInitialized = false;
1090
1091 if (MOZ_LIKELY(mChunkManager)) {
1092 // In-session.
1093
1094 const Length blockBytes =
1095 std::forward<CallbackBlockBytes>(aCallbackBlockBytes)();
1096
1097 if (ProfileBufferChunk* current = GetOrCreateCurrentChunk(aLock);
1098 MOZ_LIKELY(current)) {
1099 if (blockBytes <= current->RemainingBytes()) {
1100 // Block fits in current chunk with only one span.
1101 currentChunkFilled = blockBytes == current->RemainingBytes();
1102 const auto [mem0, blockIndex] = current->ReserveBlock(blockBytes);
1103 MOZ_ASSERT(mem0.LengthBytes() == blockBytes);
1104 maybeEntryWriter.emplace(
1105 mem0, blockIndex,
1106 ProfileBufferBlockIndex::CreateFromProfileBufferIndex(
1107 blockIndex.ConvertToProfileBufferIndex() + blockBytes));
1108 MOZ_ASSERT(maybeEntryWriter->RemainingBytes() == blockBytes);
1109 mRangeEnd += blockBytes;
1110 mPushedBlockCount += aBlockCount;
1111 } else if (blockBytes >= current->BufferBytes()) {
1112 // Currently only two buffer chunks are held at a time and it is not
1113 // possible to write an object that takes up more space than this. In
1114 // this scenario, silently discard this block of data if it is unable
1115 // to fit into the two reserved profiler chunks.
1116 mFailedPutBytes += blockBytes;
1117 } else {
1118 // Block doesn't fit fully in current chunk, it needs to overflow into
1119 // the next one.
1120 // Whether or not we can write this entry, the current chunk is now
1121 // considered full, so it will be released. (Otherwise we could refuse
1122 // this entry, but later accept a smaller entry into this chunk, which
1123 // would be somewhat inconsistent.)
1124 currentChunkFilled = true;
1125 // Make sure the next chunk is available (from a previous request),
1126 // otherwise create one on the spot.
1127 if (ProfileBufferChunk* next = GetOrCreateNextChunk(aLock);
1128 MOZ_LIKELY(next)) {
1129 // Here, we know we have a current and a next chunk.
1130 // Reserve head of block at the end of the current chunk.
1131 const auto [mem0, blockIndex] =
1132 current->ReserveBlock(current->RemainingBytes());
1133 MOZ_ASSERT(mem0.LengthBytes() < blockBytes);
1134 MOZ_ASSERT(current->RemainingBytes() == 0);
1135 // Set the next chunk range, and reserve the needed space for the
1136 // tail of the block.
1137 next->SetRangeStart(mNextChunkRangeStart);
1138 mNextChunkRangeStart += next->BufferBytes();
1139 const auto mem1 = next->ReserveInitialBlockAsTail(
1140 blockBytes - mem0.LengthBytes());
1141 MOZ_ASSERT(next->RemainingBytes() != 0);
1142 nextChunkInitialized = true;
1143 // Block is split in two spans.
1144 maybeEntryWriter.emplace(
1145 mem0, mem1, blockIndex,
1146 ProfileBufferBlockIndex::CreateFromProfileBufferIndex(
1147 blockIndex.ConvertToProfileBufferIndex() + blockBytes));
1148 MOZ_ASSERT(maybeEntryWriter->RemainingBytes() == blockBytes);
1149 mRangeEnd += blockBytes;
1150 mPushedBlockCount += aBlockCount;
1151 } else {
1152 // Cannot get a new chunk. Record put failure.
1153 mFailedPutBytes += blockBytes;
1154 }
1155 }
1156 } else {
1157 // Cannot get a current chunk. Record put failure.
1158 mFailedPutBytes += blockBytes;
1159 }
1160 } // end of `if (MOZ_LIKELY(mChunkManager))`
1161
1162 // Here, we either have a `Nothing` (failure), or a non-empty entry writer
1163 // pointing at the start of the block.
1164
1165 // After we invoke the callback and return, we may need to handle the
1166 // current chunk being filled.
1167 auto handleFilledChunk = MakeScopeExit([&]() {
1168 // If the entry writer was not already empty, the callback *must* have
1169 // filled the full entry.
1170 MOZ_ASSERT(!maybeEntryWriter || maybeEntryWriter->RemainingBytes() == 0);
1171
1172 if (currentChunkFilled) {
1173 // Extract current (now filled) chunk.
1174 UniquePtr<ProfileBufferChunk> filled = std::move(mCurrentChunk);
1175
1176 if (mNextChunks) {
1177 // Cycle to the next chunk.
1178 mCurrentChunk =
1179 std::exchange(mNextChunks, mNextChunks->ReleaseNext());
1180
1181 // Make sure it is initialized (it is now the current chunk).
1182 if (!nextChunkInitialized) {
1183 InitializeCurrentChunk(aLock);
1184 }
1185 }
1186
1187 // And finally mark filled chunk done and release it.
1188 filled->MarkDone();
1189 mChunkManager->ReleaseChunk(std::move(filled));
1190
1191 // Request another chunk if needed.
1192 // In most cases, here we should have one current chunk and no next
1193 // chunk, so we want to do a request so there hopefully will be a next
1194 // chunk available when the current one gets filled.
1195 // But we also for a request if we don't even have a current chunk (if
1196 // it's too late, it's ok because the next `ReserveAndPutRaw` wil just
1197 // allocate one on the spot.)
1198 // And if we already have a next chunk, there's no need for more now.
1199 if (!mCurrentChunk || !mNextChunks) {
1200 RequestChunk(aLock);
1201 }
1202 }
1203 });
1204
1205 return std::forward<Callback>(aCallback)(maybeEntryWriter);
1206 }
1207
1208 // Reserve a block of `aBlockBytes` size, and invoke and return
1209 // `aCallback(Maybe<ProfileBufferEntryWriter>&)`. Note that this is the "raw"
1210 // version that doesn't write the entry size at the beginning of the block.
1211 template <typename Callback>
1212 auto ReserveAndPutRaw(Length aBlockBytes, Callback&& aCallback,
1213 uint64_t aBlockCount) {
1214 baseprofiler::detail::BaseProfilerMaybeAutoLock lock(mMutex);
1215 return ReserveAndPutRaw([aBlockBytes]() { return aBlockBytes; },
1216 std::forward<Callback>(aCallback), lock,
1217 aBlockCount);
1218 }
1219
1220 // Mutex guarding the following members.
1221 mutable baseprofiler::detail::BaseProfilerMaybeMutex mMutex;
1222
1223 // Pointer to the current Chunk Manager (or null when out-of-session.)
1224 // It may be owned locally (see below) or externally.
1225 ProfileBufferChunkManager* mChunkManager = nullptr;
1226
1227 // Only non-null when we own the current Chunk Manager.
1228 UniquePtr<ProfileBufferChunkManager> mOwnedChunkManager;
1229
1230 UniquePtr<ProfileBufferChunk> mCurrentChunk;
1231
1232 UniquePtr<ProfileBufferChunk> mNextChunks;
1233
1234 // Class used to transfer requested chunks from a `ChunkManager` to a
1235 // `ProfileChunkedBuffer`.
1236 // It needs to be ref-counted because the request may be fulfilled
1237 // asynchronously, and either side may be destroyed during the request.
1238 // It cannot use the `ProfileChunkedBuffer` mutex, because that buffer and its
1239 // mutex could be destroyed during the request.
1240 class RequestedChunkRefCountedHolder {
1241 public:
1242 enum class State { Unused, Requested, Fulfilled };
1243
1244 // Get the current state. Note that it may change after the function
1245 // returns, so it should be used carefully, e.g., `ProfileChunkedBuffer` can
1246 // see if a request is pending or fulfilled, to avoid starting another
1247 // request.
1248 [[nodiscard]] State GetState() const {
1249 baseprofiler::detail::BaseProfilerAutoLock lock(mRequestMutex);
1250 return mState;
1251 }
1252
1253 // Must be called by `ProfileChunkedBuffer` when it requests a chunk.
1254 // There cannot be more than one request in-flight.
1255 void StartRequest() {
1256 baseprofiler::detail::BaseProfilerAutoLock lock(mRequestMutex);
1257 MOZ_ASSERT(mState == State::Unused, "Already requested or fulfilled");
1258 mState = State::Requested;
1259 }
1260
1261 // Must be called by the `ChunkManager` with a chunk.
1262 // If the `ChunkManager` cannot provide a chunk (because of memory limits,
1263 // or it gets destroyed), it must call this anyway with a nullptr.
1264 void AddRequestedChunk(UniquePtr<ProfileBufferChunk>&& aChunk) {
1265 baseprofiler::detail::BaseProfilerAutoLock lock(mRequestMutex);
1266 MOZ_ASSERT(mState == State::Requested);
1267 mState = State::Fulfilled;
1268 mRequestedChunk = std::move(aChunk);
1269 }
1270
1271 // The `ProfileChunkedBuffer` can try to extract the provided chunk after a
1272 // request:
1273 // - Nothing -> Request is not fulfilled yet.
1274 // - Some(nullptr) -> The `ChunkManager` was not able to provide a chunk.
1275 // - Some(chunk) -> Requested chunk.
1276 [[nodiscard]] Maybe<UniquePtr<ProfileBufferChunk>> GetChunkIfFulfilled() {
1277 Maybe<UniquePtr<ProfileBufferChunk>> maybeChunk;
1278 baseprofiler::detail::BaseProfilerAutoLock lock(mRequestMutex);
1279 MOZ_ASSERT(mState == State::Requested || mState == State::Fulfilled);
1280 if (mState == State::Fulfilled) {
1281 mState = State::Unused;
1282 maybeChunk.emplace(std::move(mRequestedChunk));
1283 }
1284 return maybeChunk;
1285 }
1286
1287 // Ref-counting implementation. Hand-rolled, because mozilla::RefCounted
1288 // logs AddRefs and Releases in xpcom, but this object could be AddRef'd
1289 // by the Base Profiler before xpcom starts, then Release'd by the Gecko
1290 // Profiler in xpcom, leading to apparent negative leaks.
1291
1292 void AddRef() {
1293 baseprofiler::detail::BaseProfilerAutoLock lock(mRequestMutex);
1294 ++mRefCount;
1295 }
1296
1297 void Release() {
1298 {
1299 baseprofiler::detail::BaseProfilerAutoLock lock(mRequestMutex);
1300 if (--mRefCount > 0) {
1301 return;
1302 }
1303 }
1304 delete this;
1305 }
1306
1307 private:
1308 ~RequestedChunkRefCountedHolder() = default;
1309
1310 // Mutex guarding the following members.
1311 mutable baseprofiler::detail::BaseProfilerMutex mRequestMutex;
1312 int mRefCount = 0;
1313 State mState = State::Unused;
1314 UniquePtr<ProfileBufferChunk> mRequestedChunk;
1315 };
1316
1317 // Requested-chunk holder, kept alive when in-session, but may also live
1318 // longer if a request is in-flight.
1319 RefPtr<RequestedChunkRefCountedHolder> mRequestedChunkHolder;
1320
1321 // Range start of the next chunk to become current. Starting at 1 because
1322 // 0 is a reserved index similar to nullptr.
1323 ProfileBufferIndex mNextChunkRangeStart = 1;
1324
1325 // Index to the first block.
1326 // Atomic because it may be increased when a Chunk is destroyed, and the
1327 // callback may be invoked from anywhere, including from inside one of our
1328 // locked section, so we cannot protect it with a mutex.
1329 Atomic<ProfileBufferIndex, MemoryOrdering::ReleaseAcquire> mRangeStart{1};
1330
1331 // Index past the last block. Equals mRangeStart if empty.
1332 ProfileBufferIndex mRangeEnd = 1;
1333
1334 // Number of blocks that have been pushed into this buffer.
1335 uint64_t mPushedBlockCount = 0;
1336
1337 // Number of blocks that have been removed from this buffer.
1338 // Note: Live entries = pushed - cleared.
1339 // Atomic because it may be updated when a Chunk is destroyed, and the
1340 // callback may be invoked from anywhere, including from inside one of our
1341 // locked section, so we cannot protect it with a mutex.
1342 Atomic<uint64_t, MemoryOrdering::ReleaseAcquire> mClearedBlockCount{0};
1343
1344 // Number of bytes that could not be put into this buffer.
1345 uint64_t mFailedPutBytes = 0;
1346 };
1347
1348 // ----------------------------------------------------------------------------
1349 // ProfileChunkedBuffer serialization
1350
1351 // A ProfileChunkedBuffer can hide another one!
1352 // This will be used to store marker backtraces; They can be read back into a
1353 // UniquePtr<ProfileChunkedBuffer>.
1354 // Format: len (ULEB128) | start | end | buffer (len bytes) | pushed | cleared
1355 // len==0 marks an out-of-session buffer, or empty buffer.
1356 template <>
1357 struct ProfileBufferEntryWriter::Serializer<ProfileChunkedBuffer> {
1358 static Length Bytes(const ProfileChunkedBuffer& aBuffer) {
1359 return aBuffer.Read([&](ProfileChunkedBuffer::Reader* aReader) {
1360 if (!aReader) {
1361 // Out-of-session, we only need 1 byte to store a length of 0.
1362 return ULEB128Size<Length>(0);
1363 }
1364 ProfileBufferEntryReader reader = aReader->SingleChunkDataAsEntry();
1365 const ProfileBufferIndex start =
1366 reader.CurrentBlockIndex().ConvertToProfileBufferIndex();
1367 const ProfileBufferIndex end =
1368 reader.NextBlockIndex().ConvertToProfileBufferIndex();
1369 MOZ_ASSERT(end - start <= std::numeric_limits<Length>::max());
1370 const Length len = static_cast<Length>(end - start);
1371 if (len == 0) {
1372 // In-session but empty, also store a length of 0.
1373 return ULEB128Size<Length>(0);
1374 }
1375 // In-session.
1376 return static_cast<Length>(ULEB128Size(len) + sizeof(start) + len +
1377 sizeof(aBuffer.mPushedBlockCount) +
1378 sizeof(aBuffer.mClearedBlockCount));
1379 });
1380 }
1381
1382 static void Write(ProfileBufferEntryWriter& aEW,
1383 const ProfileChunkedBuffer& aBuffer) {
1384 aBuffer.Read([&](ProfileChunkedBuffer::Reader* aReader) {
1385 if (!aReader) {
1386 // Out-of-session, only store a length of 0.
1387 aEW.WriteULEB128<Length>(0);
1388 return;
1389 }
1390 ProfileBufferEntryReader reader = aReader->SingleChunkDataAsEntry();
1391 const ProfileBufferIndex start =
1392 reader.CurrentBlockIndex().ConvertToProfileBufferIndex();
1393 const ProfileBufferIndex end =
1394 reader.NextBlockIndex().ConvertToProfileBufferIndex();
1395 MOZ_ASSERT(end - start <= std::numeric_limits<Length>::max());
1396 const Length len = static_cast<Length>(end - start);
1397 MOZ_ASSERT(len <= aEW.RemainingBytes());
1398 if (len == 0) {
1399 // In-session but empty, only store a length of 0.
1400 aEW.WriteULEB128<Length>(0);
1401 return;
1402 }
1403 // In-session.
1404 // Store buffer length, and start index.
1405 aEW.WriteULEB128(len);
1406 aEW.WriteObject(start);
1407 // Write all the bytes.
1408 aEW.WriteFromReader(reader, reader.RemainingBytes());
1409 // And write stats.
1410 aEW.WriteObject(static_cast<uint64_t>(aBuffer.mPushedBlockCount));
1411 aEW.WriteObject(static_cast<uint64_t>(aBuffer.mClearedBlockCount));
1412 // Note: Failed pushes are not important to serialize.
1413 });
1414 }
1415 };
1416
1417 // A serialized ProfileChunkedBuffer can be read into an empty buffer (either
1418 // out-of-session, or in-session with enough room).
1419 template <>
1420 struct ProfileBufferEntryReader::Deserializer<ProfileChunkedBuffer> {
1421 static void ReadInto(ProfileBufferEntryReader& aER,
1422 ProfileChunkedBuffer& aBuffer) {
1423 // Expect an empty buffer, as we're going to overwrite it.
1424 MOZ_ASSERT(aBuffer.GetState().mRangeStart == aBuffer.GetState().mRangeEnd);
1425 // Read the stored buffer length.
1426 const auto len = aER.ReadULEB128<ProfileChunkedBuffer::Length>();
1427 if (len == 0) {
1428 // 0-length means an "uninteresting" buffer, just return now.
1429 return;
1430 }
1431 // We have a non-empty buffer to read.
1432
1433 // Read start and end indices.
1434 const auto start = aER.ReadObject<ProfileBufferIndex>();
1435 aBuffer.mRangeStart = start;
1436 // For now, set the end to be the start (the buffer is still empty). It will
1437 // be updated in `ReserveAndPutRaw()` below.
1438 aBuffer.mRangeEnd = start;
1439
1440 if (aBuffer.IsInSession()) {
1441 // Output buffer is in-session (i.e., it already has a memory buffer
1442 // attached). Make sure the caller allocated enough space.
1443 MOZ_RELEASE_ASSERT(aBuffer.BufferLength().value() >= len);
1444 } else {
1445 // Output buffer is out-of-session, set a new chunk manager that will
1446 // provide a single chunk of just the right size.
1447 aBuffer.SetChunkManager(MakeUnique<ProfileBufferChunkManagerSingle>(len));
1448 MOZ_ASSERT(aBuffer.BufferLength().value() >= len);
1449 }
1450
1451 // Copy bytes into the buffer.
1452 aBuffer.ReserveAndPutRaw(
1453 len,
1454 [&](Maybe<ProfileBufferEntryWriter>& aEW) {
1455 MOZ_RELEASE_ASSERT(aEW.isSome());
1456 aEW->WriteFromReader(aER, len);
1457 },
1458 0);
1459 // Finally copy stats.
1460 aBuffer.mPushedBlockCount = aER.ReadObject<uint64_t>();
1461 aBuffer.mClearedBlockCount = aER.ReadObject<uint64_t>();
1462 // Failed puts are not important to keep.
1463 aBuffer.mFailedPutBytes = 0;
1464 }
1465
1466 // We cannot output a ProfileChunkedBuffer object (not copyable), use
1467 // `ReadInto()` or `aER.ReadObject<UniquePtr<BlocksRinbBuffer>>()` instead.
1468 static ProfileChunkedBuffer Read(ProfileBufferEntryReader& aER) = delete;
1469 };
1470
1471 // A ProfileChunkedBuffer is usually refererenced through a UniquePtr, for
1472 // convenience we support (de)serializing that UniquePtr directly.
1473 // This is compatible with the non-UniquePtr serialization above, with a null
1474 // pointer being treated like an out-of-session or empty buffer; and any of
1475 // these would be deserialized into a null pointer.
1476 template <>
1477 struct ProfileBufferEntryWriter::Serializer<UniquePtr<ProfileChunkedBuffer>> {
1478 static Length Bytes(const UniquePtr<ProfileChunkedBuffer>& aBufferUPtr) {
1479 if (!aBufferUPtr) {
1480 // Null pointer, treat it like an empty buffer, i.e., write length of 0.
1481 return ULEB128Size<Length>(0);
1482 }
1483 // Otherwise write the pointed-at ProfileChunkedBuffer (which could be
1484 // out-of-session or empty.)
1485 return SumBytes(*aBufferUPtr);
1486 }
1487
1488 static void Write(ProfileBufferEntryWriter& aEW,
1489 const UniquePtr<ProfileChunkedBuffer>& aBufferUPtr) {
1490 if (!aBufferUPtr) {
1491 // Null pointer, treat it like an empty buffer, i.e., write length of 0.
1492 aEW.WriteULEB128<Length>(0);
1493 return;
1494 }
1495 // Otherwise write the pointed-at ProfileChunkedBuffer (which could be
1496 // out-of-session or empty.)
1497 aEW.WriteObject(*aBufferUPtr);
1498 }
1499 };
1500
1501 // Serialization of a raw pointer to ProfileChunkedBuffer.
1502 // Use Deserializer<UniquePtr<ProfileChunkedBuffer>> to read it back.
1503 template <>
1504 struct ProfileBufferEntryWriter::Serializer<ProfileChunkedBuffer*> {
1505 static Length Bytes(ProfileChunkedBuffer* aBufferUPtr) {
1506 if (!aBufferUPtr) {
1507 // Null pointer, treat it like an empty buffer, i.e., write length of 0.
1508 return ULEB128Size<Length>(0);
1509 }
1510 // Otherwise write the pointed-at ProfileChunkedBuffer (which could be
1511 // out-of-session or empty.)
1512 return SumBytes(*aBufferUPtr);
1513 }
1514
1515 static void Write(ProfileBufferEntryWriter& aEW,
1516 ProfileChunkedBuffer* aBufferUPtr) {
1517 if (!aBufferUPtr) {
1518 // Null pointer, treat it like an empty buffer, i.e., write length of 0.
1519 aEW.WriteULEB128<Length>(0);
1520 return;
1521 }
1522 // Otherwise write the pointed-at ProfileChunkedBuffer (which could be
1523 // out-of-session or empty.)
1524 aEW.WriteObject(*aBufferUPtr);
1525 }
1526 };
1527
1528 template <>
1529 struct ProfileBufferEntryReader::Deserializer<UniquePtr<ProfileChunkedBuffer>> {
1530 static void ReadInto(ProfileBufferEntryReader& aER,
1531 UniquePtr<ProfileChunkedBuffer>& aBuffer) {
1532 aBuffer = Read(aER);
1533 }
1534
1535 static UniquePtr<ProfileChunkedBuffer> Read(ProfileBufferEntryReader& aER) {
1536 UniquePtr<ProfileChunkedBuffer> bufferUPtr;
1537 // Keep a copy of the reader before reading the length, so we can restart
1538 // from here below.
1539 ProfileBufferEntryReader readerBeforeLen = aER;
1540 // Read the stored buffer length.
1541 const auto len = aER.ReadULEB128<ProfileChunkedBuffer::Length>();
1542 if (len == 0) {
1543 // 0-length means an "uninteresting" buffer, just return nullptr.
1544 return bufferUPtr;
1545 }
1546 // We have a non-empty buffer.
1547 // allocate an empty ProfileChunkedBuffer without mutex.
1548 bufferUPtr = MakeUnique<ProfileChunkedBuffer>(
1549 ProfileChunkedBuffer::ThreadSafety::WithoutMutex);
1550 // Rewind the reader before the length and deserialize the contents, using
1551 // the non-UniquePtr Deserializer.
1552 aER = readerBeforeLen;
1553 aER.ReadIntoObject(*bufferUPtr);
1554 return bufferUPtr;
1555 }
1556 };
1557
1558 } // namespace mozilla
1559
1560 #endif // ProfileChunkedBuffer_h