summaryrefslogtreecommitdiffstats
path: root/tools/profiler/gecko/ProfilerParent.cpp
blob: 403a4c2d6225e8d30f6c61557cc0cbf1c5ce8fec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "ProfilerParent.h"

#ifdef MOZ_GECKO_PROFILER
#  include "nsProfiler.h"
#  include "platform.h"
#endif

#include "GeckoProfiler.h"
#include "ProfilerControl.h"
#include "mozilla/BaseAndGeckoProfilerDetail.h"
#include "mozilla/BaseProfilerDetail.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/DataMutex.h"
#include "mozilla/IOInterposer.h"
#include "mozilla/ipc/Endpoint.h"
#include "mozilla/Maybe.h"
#include "mozilla/ProfileBufferControlledChunkManager.h"
#include "mozilla/ProfilerBufferSize.h"
#include "mozilla/RefPtr.h"
#include "mozilla/Unused.h"
#include "nsTArray.h"
#include "nsThreadUtils.h"

#include <utility>

namespace mozilla {

using namespace ipc;

/* static */
Endpoint<PProfilerChild> ProfilerParent::CreateForProcess(
    base::ProcessId aOtherPid) {
  MOZ_RELEASE_ASSERT(NS_IsMainThread());
  Endpoint<PProfilerChild> child;
#ifdef MOZ_GECKO_PROFILER
  Endpoint<PProfilerParent> parent;
  nsresult rv = PProfiler::CreateEndpoints(&parent, &child);

  if (NS_FAILED(rv)) {
    MOZ_CRASH("Failed to create top level actor for PProfiler!");
  }

  RefPtr<ProfilerParent> actor = new ProfilerParent(aOtherPid);
  if (!parent.Bind(actor)) {
    MOZ_CRASH("Failed to bind parent actor for PProfiler!");
  }

  actor->Init();
#endif

  return child;
}

#ifdef MOZ_GECKO_PROFILER

class ProfilerParentTracker;

// This class is responsible for gathering updates from chunk managers in
// different process, and request for the oldest chunks to be destroyed whenever
// the given memory limit is reached.
class ProfileBufferGlobalController final {
 public:
  explicit ProfileBufferGlobalController(size_t aMaximumBytes);

  ~ProfileBufferGlobalController();

  void HandleChildChunkManagerUpdate(
      base::ProcessId aProcessId,
      ProfileBufferControlledChunkManager::Update&& aUpdate);

  static bool IsLockedOnCurrentThread();

 private:
  // Calls aF(Json::Value&).
  template <typename F>
  void Log(F&& aF);

  static void LogUpdateChunks(Json::Value& updates, base::ProcessId aProcessId,
                              const TimeStamp& aTimeStamp, int aChunkDiff);
  void LogUpdate(base::ProcessId aProcessId,
                 const ProfileBufferControlledChunkManager::Update& aUpdate);
  void LogDeletion(base::ProcessId aProcessId, const TimeStamp& aTimeStamp);

  void HandleChunkManagerNonFinalUpdate(
      base::ProcessId aProcessId,
      ProfileBufferControlledChunkManager::Update&& aUpdate,
      ProfileBufferControlledChunkManager& aParentChunkManager);

  const size_t mMaximumBytes;

  const base::ProcessId mParentProcessId = base::GetCurrentProcId();

  struct ParentChunkManagerAndPendingUpdate {
    ProfileBufferControlledChunkManager* mChunkManager = nullptr;
    ProfileBufferControlledChunkManager::Update mPendingUpdate;
  };

  static DataMutexBase<ParentChunkManagerAndPendingUpdate,
                       baseprofiler::detail::BaseProfilerMutex>
      sParentChunkManagerAndPendingUpdate;

  size_t mUnreleasedTotalBytes = 0;

  struct PidAndBytes {
    base::ProcessId mProcessId;
    size_t mBytes;

    // For searching and sorting.
    bool operator==(base::ProcessId aSearchedProcessId) const {
      return mProcessId == aSearchedProcessId;
    }
    bool operator==(const PidAndBytes& aOther) const {
      return mProcessId == aOther.mProcessId;
    }
    bool operator<(base::ProcessId aSearchedProcessId) const {
      return mProcessId < aSearchedProcessId;
    }
    bool operator<(const PidAndBytes& aOther) const {
      return mProcessId < aOther.mProcessId;
    }
  };
  using PidAndBytesArray = nsTArray<PidAndBytes>;
  PidAndBytesArray mUnreleasedBytesByPid;

  size_t mReleasedTotalBytes = 0;

  struct TimeStampAndBytesAndPid {
    TimeStamp mTimeStamp;
    size_t mBytes;
    base::ProcessId mProcessId;

    // For searching and sorting.
    bool operator==(const TimeStampAndBytesAndPid& aOther) const {
      // Sort first by timestamps, and then by pid in rare cases with the same
      // timestamps.
      return mTimeStamp == aOther.mTimeStamp && mProcessId == aOther.mProcessId;
    }
    bool operator<(const TimeStampAndBytesAndPid& aOther) const {
      // Sort first by timestamps, and then by pid in rare cases with the same
      // timestamps.
      return mTimeStamp < aOther.mTimeStamp ||
             (MOZ_UNLIKELY(mTimeStamp == aOther.mTimeStamp) &&
              mProcessId < aOther.mProcessId);
    }
  };
  using TimeStampAndBytesAndPidArray = nsTArray<TimeStampAndBytesAndPid>;
  TimeStampAndBytesAndPidArray mReleasedChunksByTime;
};

/* static */
DataMutexBase<ProfileBufferGlobalController::ParentChunkManagerAndPendingUpdate,
              baseprofiler::detail::BaseProfilerMutex>
    ProfileBufferGlobalController::sParentChunkManagerAndPendingUpdate{
        "ProfileBufferGlobalController::sParentChunkManagerAndPendingUpdate"};

// This singleton class tracks live ProfilerParent's (meaning there's a current
// connection with a child process).
// It also knows when the local profiler is running.
// And when both the profiler is running and at least one child is present, it
// creates a ProfileBufferGlobalController and forwards chunk updates to it.
class ProfilerParentTracker final {
 public:
  static void StartTracking(ProfilerParent* aParent);
  static void StopTracking(ProfilerParent* aParent);

  static void ProfilerStarted(uint32_t aEntries);
  static void ProfilerWillStopIfStarted();

  // Number of non-destroyed tracked ProfilerParents.
  static size_t ProfilerParentCount();

  template <typename FuncType>
  static void Enumerate(FuncType&& aIterFunc);

  template <typename FuncType>
  static void ForChild(base::ProcessId aChildPid, FuncType&& aIterFunc);

  static void ForwardChildChunkManagerUpdate(
      base::ProcessId aProcessId,
      ProfileBufferControlledChunkManager::Update&& aUpdate);

  ProfilerParentTracker();
  ~ProfilerParentTracker();

 private:
  // Get the singleton instance; Create one on the first request, unless we are
  // past XPCOMShutdownThreads, which is when it should get destroyed.
  static ProfilerParentTracker* GetInstance();

  // List of parents for currently-connected child processes.
  nsTArray<ProfilerParent*> mProfilerParents;

  // If non-0, the parent profiler is running, with this limit (in number of
  // entries.) This is needed here, because the parent profiler may start
  // running before child processes are known (e.g., startup profiling).
  uint32_t mEntries = 0;

  // When the profiler is running and there is at least one parent-child
  // connection, this is the controller that should receive chunk updates.
  Maybe<ProfileBufferGlobalController> mMaybeController;
};

static const Json::StaticString logRoot{"bufferGlobalController"};

template <typename F>
void ProfileBufferGlobalController::Log(F&& aF) {
  ProfilingLog::Access([&](Json::Value& aLog) {
    Json::Value& root = aLog[logRoot];
    if (!root.isObject()) {
      root = Json::Value(Json::objectValue);
      root[Json::StaticString{"logBegin" TIMESTAMP_JSON_SUFFIX}] =
          ProfilingLog::Timestamp();
    }
    std::forward<F>(aF)(root);
  });
}

/* static */
void ProfileBufferGlobalController::LogUpdateChunks(Json::Value& updates,
                                                    base::ProcessId aProcessId,
                                                    const TimeStamp& aTimeStamp,
                                                    int aChunkDiff) {
  MOZ_ASSERT(updates.isArray());
  Json::Value row{Json::arrayValue};
  row.append(Json::Value{Json::UInt64(aProcessId)});
  row.append(ProfilingLog::Timestamp(aTimeStamp));
  row.append(Json::Value{Json::Int(aChunkDiff)});
  updates.append(std::move(row));
}

void ProfileBufferGlobalController::LogUpdate(
    base::ProcessId aProcessId,
    const ProfileBufferControlledChunkManager::Update& aUpdate) {
  Log([&](Json::Value& aRoot) {
    Json::Value& updates = aRoot[Json::StaticString{"updates"}];
    if (!updates.isArray()) {
      aRoot[Json::StaticString{"updatesSchema"}] =
          Json::StaticString{"0: pid, 1: chunkRelease_TSms, 3: chunkDiff"};
      updates = Json::Value{Json::arrayValue};
    }
    if (aUpdate.IsFinal()) {
      LogUpdateChunks(updates, aProcessId, TimeStamp{}, 0);
    } else if (!aUpdate.IsNotUpdate()) {
      for (const auto& chunk : aUpdate.NewlyReleasedChunksRef()) {
        LogUpdateChunks(updates, aProcessId, chunk.mDoneTimeStamp, 1);
      }
    }
  });
}

void ProfileBufferGlobalController::LogDeletion(base::ProcessId aProcessId,
                                                const TimeStamp& aTimeStamp) {
  Log([&](Json::Value& aRoot) {
    Json::Value& updates = aRoot[Json::StaticString{"updates"}];
    if (!updates.isArray()) {
      updates = Json::Value{Json::arrayValue};
    }
    LogUpdateChunks(updates, aProcessId, aTimeStamp, -1);
  });
}

ProfileBufferGlobalController::ProfileBufferGlobalController(
    size_t aMaximumBytes)
    : mMaximumBytes(aMaximumBytes) {
  MOZ_RELEASE_ASSERT(NS_IsMainThread());

  Log([](Json::Value& aRoot) {
    aRoot[Json::StaticString{"controllerCreationTime" TIMESTAMP_JSON_SUFFIX}] =
        ProfilingLog::Timestamp();
  });

  // This is the local chunk manager for this parent process, so updates can be
  // handled here.
  ProfileBufferControlledChunkManager* parentChunkManager =
      profiler_get_controlled_chunk_manager();

  if (NS_WARN_IF(!parentChunkManager)) {
    Log([](Json::Value& aRoot) {
      aRoot[Json::StaticString{"controllerCreationFailureReason"}] =
          "No parent chunk manager";
    });
    return;
  }

  {
    auto lockedParentChunkManagerAndPendingUpdate =
        sParentChunkManagerAndPendingUpdate.Lock();
    lockedParentChunkManagerAndPendingUpdate->mChunkManager =
        parentChunkManager;
  }

  parentChunkManager->SetUpdateCallback(
      [this](ProfileBufferControlledChunkManager::Update&& aUpdate) {
        MOZ_ASSERT(!aUpdate.IsNotUpdate(),
                   "Update callback should never be given a non-update");
        auto lockedParentChunkManagerAndPendingUpdate =
            sParentChunkManagerAndPendingUpdate.Lock();
        if (aUpdate.IsFinal()) {
          // Final update of the parent.
          // We cannot keep the chunk manager, and there's no point handling
          // updates anymore. Do some cleanup now, to free resources before
          // we're destroyed.
          lockedParentChunkManagerAndPendingUpdate->mChunkManager = nullptr;
          lockedParentChunkManagerAndPendingUpdate->mPendingUpdate.Clear();
          mUnreleasedTotalBytes = 0;
          mUnreleasedBytesByPid.Clear();
          mReleasedTotalBytes = 0;
          mReleasedChunksByTime.Clear();
          return;
        }
        if (!lockedParentChunkManagerAndPendingUpdate->mChunkManager) {
          // No chunk manager, ignore updates.
          return;
        }
        // Special handling of parent non-final updates:
        // These updates are coming from *this* process, and may originate from
        // scopes in any thread where any lock is held, so using other locks (to
        // e.g., dispatch tasks or send IPCs) could trigger a deadlock. Instead,
        // parent updates are stored locally and handled when the next
        // non-parent update needs handling, see HandleChildChunkManagerUpdate.
        lockedParentChunkManagerAndPendingUpdate->mPendingUpdate.Fold(
            std::move(aUpdate));
      });
}

ProfileBufferGlobalController ::~ProfileBufferGlobalController() {
  MOZ_RELEASE_ASSERT(NS_IsMainThread());
  // Extract the parent chunk manager (if still set).
  // This means any update after this will be ignored.
  ProfileBufferControlledChunkManager* parentChunkManager = []() {
    auto lockedParentChunkManagerAndPendingUpdate =
        sParentChunkManagerAndPendingUpdate.Lock();
    lockedParentChunkManagerAndPendingUpdate->mPendingUpdate.Clear();
    return std::exchange(
        lockedParentChunkManagerAndPendingUpdate->mChunkManager, nullptr);
  }();
  if (parentChunkManager) {
    // We had not received a final update yet, so the chunk manager is still
    // valid. Reset the callback in the chunk manager, this will immediately
    // invoke the callback with the final empty update; see handling above.
    parentChunkManager->SetUpdateCallback({});
  }
}

void ProfileBufferGlobalController::HandleChildChunkManagerUpdate(
    base::ProcessId aProcessId,
    ProfileBufferControlledChunkManager::Update&& aUpdate) {
  MOZ_RELEASE_ASSERT(NS_IsMainThread());

  MOZ_ASSERT(aProcessId != mParentProcessId);

  MOZ_ASSERT(!aUpdate.IsNotUpdate(),
             "HandleChildChunkManagerUpdate should not be given a non-update");

  auto lockedParentChunkManagerAndPendingUpdate =
      sParentChunkManagerAndPendingUpdate.Lock();
  if (!lockedParentChunkManagerAndPendingUpdate->mChunkManager) {
    // No chunk manager, ignore updates.
    return;
  }

  if (aUpdate.IsFinal()) {
    // Final update in a child process, remove all traces of that process.
    LogUpdate(aProcessId, aUpdate);
    size_t index = mUnreleasedBytesByPid.BinaryIndexOf(aProcessId);
    if (index != PidAndBytesArray::NoIndex) {
      // We already have a value for this pid.
      PidAndBytes& pidAndBytes = mUnreleasedBytesByPid[index];
      mUnreleasedTotalBytes -= pidAndBytes.mBytes;
      mUnreleasedBytesByPid.RemoveElementAt(index);
    }

    size_t released = 0;
    mReleasedChunksByTime.RemoveElementsBy(
        [&released, aProcessId](const auto& chunk) {
          const bool match = chunk.mProcessId == aProcessId;
          if (match) {
            released += chunk.mBytes;
          }
          return match;
        });
    if (released != 0) {
      mReleasedTotalBytes -= released;
    }

    // Total can only have gone down, so there's no need to check the limit.
    return;
  }

  // Non-final update in child process.

  // Before handling the child update, we may have pending updates from the
  // parent, which can be processed now since we're in an IPC callback outside
  // of any profiler-related scope.
  if (!lockedParentChunkManagerAndPendingUpdate->mPendingUpdate.IsNotUpdate()) {
    MOZ_ASSERT(
        !lockedParentChunkManagerAndPendingUpdate->mPendingUpdate.IsFinal());
    HandleChunkManagerNonFinalUpdate(
        mParentProcessId,
        std::move(lockedParentChunkManagerAndPendingUpdate->mPendingUpdate),
        *lockedParentChunkManagerAndPendingUpdate->mChunkManager);
    lockedParentChunkManagerAndPendingUpdate->mPendingUpdate.Clear();
  }

  HandleChunkManagerNonFinalUpdate(
      aProcessId, std::move(aUpdate),
      *lockedParentChunkManagerAndPendingUpdate->mChunkManager);
}

/* static */
bool ProfileBufferGlobalController::IsLockedOnCurrentThread() {
  return sParentChunkManagerAndPendingUpdate.Mutex().IsLockedOnCurrentThread();
}

void ProfileBufferGlobalController::HandleChunkManagerNonFinalUpdate(
    base::ProcessId aProcessId,
    ProfileBufferControlledChunkManager::Update&& aUpdate,
    ProfileBufferControlledChunkManager& aParentChunkManager) {
  MOZ_ASSERT(!aUpdate.IsFinal());
  LogUpdate(aProcessId, aUpdate);

  size_t index = mUnreleasedBytesByPid.BinaryIndexOf(aProcessId);
  if (index != PidAndBytesArray::NoIndex) {
    // We already have a value for this pid.
    PidAndBytes& pidAndBytes = mUnreleasedBytesByPid[index];
    mUnreleasedTotalBytes =
        mUnreleasedTotalBytes - pidAndBytes.mBytes + aUpdate.UnreleasedBytes();
    pidAndBytes.mBytes = aUpdate.UnreleasedBytes();
  } else {
    // New pid.
    mUnreleasedBytesByPid.InsertElementSorted(
        PidAndBytes{aProcessId, aUpdate.UnreleasedBytes()});
    mUnreleasedTotalBytes += aUpdate.UnreleasedBytes();
  }

  size_t destroyedReleased = 0;
  if (!aUpdate.OldestDoneTimeStamp().IsNull()) {
    size_t i = 0;
    for (; i < mReleasedChunksByTime.Length(); ++i) {
      if (mReleasedChunksByTime[i].mTimeStamp >=
          aUpdate.OldestDoneTimeStamp()) {
        break;
      }
    }
    // Here, i is the index of the first item that's at or after
    // aUpdate.mOldestDoneTimeStamp, so chunks from aProcessId before that have
    // been destroyed.
    while (i != 0) {
      --i;
      const TimeStampAndBytesAndPid& item = mReleasedChunksByTime[i];
      if (item.mProcessId == aProcessId) {
        destroyedReleased += item.mBytes;
        mReleasedChunksByTime.RemoveElementAt(i);
      }
    }
  }

  size_t newlyReleased = 0;
  for (const ProfileBufferControlledChunkManager::ChunkMetadata& chunk :
       aUpdate.NewlyReleasedChunksRef()) {
    newlyReleased += chunk.mBufferBytes;
    mReleasedChunksByTime.InsertElementSorted(TimeStampAndBytesAndPid{
        chunk.mDoneTimeStamp, chunk.mBufferBytes, aProcessId});
  }

  mReleasedTotalBytes = mReleasedTotalBytes - destroyedReleased + newlyReleased;

#  ifdef DEBUG
  size_t totalReleased = 0;
  for (const TimeStampAndBytesAndPid& item : mReleasedChunksByTime) {
    totalReleased += item.mBytes;
  }
  MOZ_ASSERT(mReleasedTotalBytes == totalReleased);
#  endif  // DEBUG

  std::vector<ProfileBufferControlledChunkManager::ChunkMetadata> toDestroy;
  while (mUnreleasedTotalBytes + mReleasedTotalBytes > mMaximumBytes &&
         !mReleasedChunksByTime.IsEmpty()) {
    // We have reached the global memory limit, and there *are* released chunks
    // that can be destroyed. Start with the first one, which is the oldest.
    const TimeStampAndBytesAndPid& oldest = mReleasedChunksByTime[0];
    LogDeletion(oldest.mProcessId, oldest.mTimeStamp);
    mReleasedTotalBytes -= oldest.mBytes;
    if (oldest.mProcessId == mParentProcessId) {
      aParentChunkManager.DestroyChunksAtOrBefore(oldest.mTimeStamp);
    } else {
      ProfilerParentTracker::ForChild(
          oldest.mProcessId,
          [timestamp = oldest.mTimeStamp](ProfilerParent* profilerParent) {
            Unused << profilerParent->SendDestroyReleasedChunksAtOrBefore(
                timestamp);
          });
    }
    mReleasedChunksByTime.RemoveElementAt(0);
  }
}

/* static */
ProfilerParentTracker* ProfilerParentTracker::GetInstance() {
  MOZ_RELEASE_ASSERT(NS_IsMainThread());

  // The main instance pointer, it will be initialized at most once, before
  // XPCOMShutdownThreads.
  static UniquePtr<ProfilerParentTracker> instance = nullptr;
  if (MOZ_UNLIKELY(!instance)) {
    if (PastShutdownPhase(ShutdownPhase::XPCOMShutdownThreads)) {
      return nullptr;
    }

    instance = MakeUnique<ProfilerParentTracker>();

    // The tracker should get destroyed before threads are shutdown, because its
    // destruction closes extant channels, which could trigger promise
    // rejections that need to be dispatched to other threads.
    ClearOnShutdown(&instance, ShutdownPhase::XPCOMShutdownThreads);
  }

  return instance.get();
}

/* static */
void ProfilerParentTracker::StartTracking(ProfilerParent* aProfilerParent) {
  ProfilerParentTracker* tracker = GetInstance();
  if (!tracker) {
    return;
  }

  if (tracker->mMaybeController.isNothing() && tracker->mEntries != 0) {
    // There is no controller yet, but the profiler has started.
    // Since we're adding a ProfilerParent, it's a good time to start
    // controlling the global memory usage of the profiler.
    // (And this helps delay the Controller startup, because the parent profiler
    // can start *very* early in the process, when some resources like threads
    // are not ready yet.)
    tracker->mMaybeController.emplace(size_t(tracker->mEntries) *
                                      scBytesPerEntry);
  }

  tracker->mProfilerParents.AppendElement(aProfilerParent);
}

/* static */
void ProfilerParentTracker::StopTracking(ProfilerParent* aParent) {
  ProfilerParentTracker* tracker = GetInstance();
  if (!tracker) {
    return;
  }

  tracker->mProfilerParents.RemoveElement(aParent);
}

/* static */
void ProfilerParentTracker::ProfilerStarted(uint32_t aEntries) {
  ProfilerParentTracker* tracker = GetInstance();
  if (!tracker) {
    return;
  }

  tracker->mEntries = ClampToAllowedEntries(aEntries);

  if (tracker->mMaybeController.isNothing() &&
      !tracker->mProfilerParents.IsEmpty()) {
    // We are already tracking child processes, so it's a good time to start
    // controlling the global memory usage of the profiler.
    tracker->mMaybeController.emplace(size_t(tracker->mEntries) *
                                      scBytesPerEntry);
  }
}

/* static */
void ProfilerParentTracker::ProfilerWillStopIfStarted() {
  ProfilerParentTracker* tracker = GetInstance();
  if (!tracker) {
    return;
  }

  tracker->mEntries = 0;
  tracker->mMaybeController = Nothing{};
}

/* static */
size_t ProfilerParentTracker::ProfilerParentCount() {
  size_t count = 0;
  ProfilerParentTracker* tracker = GetInstance();
  if (tracker) {
    for (ProfilerParent* profilerParent : tracker->mProfilerParents) {
      if (!profilerParent->mDestroyed) {
        ++count;
      }
    }
  }
  return count;
}

template <typename FuncType>
/* static */
void ProfilerParentTracker::Enumerate(FuncType&& aIterFunc) {
  ProfilerParentTracker* tracker = GetInstance();
  if (!tracker) {
    return;
  }

  for (ProfilerParent* profilerParent : tracker->mProfilerParents) {
    if (!profilerParent->mDestroyed) {
      aIterFunc(profilerParent);
    }
  }
}

template <typename FuncType>
/* static */
void ProfilerParentTracker::ForChild(base::ProcessId aChildPid,
                                     FuncType&& aIterFunc) {
  ProfilerParentTracker* tracker = GetInstance();
  if (!tracker) {
    return;
  }

  for (ProfilerParent* profilerParent : tracker->mProfilerParents) {
    if (profilerParent->mChildPid == aChildPid) {
      if (!profilerParent->mDestroyed) {
        std::forward<FuncType>(aIterFunc)(profilerParent);
      }
      return;
    }
  }
}

/* static */
void ProfilerParentTracker::ForwardChildChunkManagerUpdate(
    base::ProcessId aProcessId,
    ProfileBufferControlledChunkManager::Update&& aUpdate) {
  ProfilerParentTracker* tracker = GetInstance();
  if (!tracker || tracker->mMaybeController.isNothing()) {
    return;
  }

  MOZ_ASSERT(!aUpdate.IsNotUpdate(),
             "No process should ever send a non-update");
  tracker->mMaybeController->HandleChildChunkManagerUpdate(aProcessId,
                                                           std::move(aUpdate));
}

ProfilerParentTracker::ProfilerParentTracker() {
  MOZ_RELEASE_ASSERT(NS_IsMainThread());
  MOZ_COUNT_CTOR(ProfilerParentTracker);
}

ProfilerParentTracker::~ProfilerParentTracker() {
  // This destructor should only be called on the main thread.
  MOZ_RELEASE_ASSERT(NS_IsMainThread() ||
                     // OR we're not on the main thread (including if we are
                     // past the end of `main()`), which is fine *if* there are
                     // no ProfilerParent's still registered, in which case
                     // nothing else will happen in this destructor anyway.
                     // See bug 1713971 for more information.
                     mProfilerParents.IsEmpty());
  MOZ_COUNT_DTOR(ProfilerParentTracker);

  // Close the channels of any profiler parents that haven't been destroyed.
  for (ProfilerParent* profilerParent : mProfilerParents.Clone()) {
    if (!profilerParent->mDestroyed) {
      // Keep the object alive until the call to Close() has completed.
      // Close() will trigger a call to DeallocPProfilerParent.
      RefPtr<ProfilerParent> actor = profilerParent;
      actor->Close();
    }
  }
}

ProfilerParent::ProfilerParent(base::ProcessId aChildPid)
    : mChildPid(aChildPid), mDestroyed(false) {
  MOZ_COUNT_CTOR(ProfilerParent);

  MOZ_RELEASE_ASSERT(NS_IsMainThread());
}

void ProfilerParent::Init() {
  MOZ_RELEASE_ASSERT(NS_IsMainThread());

  ProfilerParentTracker::StartTracking(this);

  // We propagated the profiler state from the parent process to the child
  // process through MOZ_PROFILER_STARTUP* environment variables.
  // However, the profiler state might have changed in this process since then,
  // and now that an active communication channel has been established with the
  // child process, it's a good time to sync up the two profilers again.

  int entries = 0;
  Maybe<double> duration = Nothing();
  double interval = 0;
  mozilla::Vector<const char*> filters;
  uint32_t features;
  uint64_t activeTabID;
  profiler_get_start_params(&entries, &duration, &interval, &features, &filters,
                            &activeTabID);

  if (entries != 0) {
    ProfilerInitParams ipcParams;
    ipcParams.enabled() = true;
    ipcParams.entries() = entries;
    ipcParams.duration() = duration;
    ipcParams.interval() = interval;
    ipcParams.features() = features;
    ipcParams.activeTabID() = activeTabID;

    // If the filters exclude our pid, make sure it's stopped, otherwise
    // continue with starting it.
    if (!profiler::detail::FiltersExcludePid(
            filters, ProfilerProcessId::FromNumber(mChildPid))) {
      ipcParams.filters().SetCapacity(filters.length());
      for (const char* filter : filters) {
        ipcParams.filters().AppendElement(filter);
      }

      Unused << SendEnsureStarted(ipcParams);
      RequestChunkManagerUpdate();
      return;
    }
  }

  Unused << SendStop();
}
#endif  // MOZ_GECKO_PROFILER

ProfilerParent::~ProfilerParent() {
  MOZ_COUNT_DTOR(ProfilerParent);

  MOZ_RELEASE_ASSERT(NS_IsMainThread());
#ifdef MOZ_GECKO_PROFILER
  ProfilerParentTracker::StopTracking(this);
#endif
}

#ifdef MOZ_GECKO_PROFILER
/* static */
nsTArray<ProfilerParent::SingleProcessProfilePromiseAndChildPid>
ProfilerParent::GatherProfiles() {
  nsTArray<SingleProcessProfilePromiseAndChildPid> results;
  if (!NS_IsMainThread()) {
    return results;
  }

  results.SetCapacity(ProfilerParentTracker::ProfilerParentCount());
  ProfilerParentTracker::Enumerate([&](ProfilerParent* profilerParent) {
    results.AppendElement(SingleProcessProfilePromiseAndChildPid{
        profilerParent->SendGatherProfile(), profilerParent->mChildPid});
  });
  return results;
}

/* static */
RefPtr<ProfilerParent::SingleProcessProgressPromise>
ProfilerParent::RequestGatherProfileProgress(base::ProcessId aChildPid) {
  RefPtr<SingleProcessProgressPromise> promise;
  ProfilerParentTracker::ForChild(
      aChildPid, [&promise](ProfilerParent* profilerParent) {
        promise = profilerParent->SendGetGatherProfileProgress();
      });
  return promise;
}

// Magic value for ProfileBufferChunkManagerUpdate::unreleasedBytes meaning
// that this is a final update from a child.
constexpr static uint64_t scUpdateUnreleasedBytesFINAL = uint64_t(-1);

/* static */
ProfileBufferChunkManagerUpdate ProfilerParent::MakeFinalUpdate() {
  return ProfileBufferChunkManagerUpdate{
      uint64_t(scUpdateUnreleasedBytesFINAL), 0, TimeStamp{},
      nsTArray<ProfileBufferChunkMetadata>{}};
}

/* static */
bool ProfilerParent::IsLockedOnCurrentThread() {
  return ProfileBufferGlobalController::IsLockedOnCurrentThread();
}

void ProfilerParent::RequestChunkManagerUpdate() {
  if (mDestroyed) {
    return;
  }

  RefPtr<AwaitNextChunkManagerUpdatePromise> updatePromise =
      SendAwaitNextChunkManagerUpdate();
  updatePromise->Then(
      GetMainThreadSerialEventTarget(), __func__,
      [self = RefPtr<ProfilerParent>(this)](
          const ProfileBufferChunkManagerUpdate& aUpdate) {
        if (aUpdate.unreleasedBytes() == scUpdateUnreleasedBytesFINAL) {
          // Special value meaning it's the final update from that child.
          ProfilerParentTracker::ForwardChildChunkManagerUpdate(
              self->mChildPid,
              ProfileBufferControlledChunkManager::Update(nullptr));
        } else {
          // Not the final update, translate it.
          std::vector<ProfileBufferControlledChunkManager::ChunkMetadata>
              chunks;
          if (!aUpdate.newlyReleasedChunks().IsEmpty()) {
            chunks.reserve(aUpdate.newlyReleasedChunks().Length());
            for (const ProfileBufferChunkMetadata& chunk :
                 aUpdate.newlyReleasedChunks()) {
              chunks.emplace_back(chunk.doneTimeStamp(), chunk.bufferBytes());
            }
          }
          // Let the tracker handle it.
          ProfilerParentTracker::ForwardChildChunkManagerUpdate(
              self->mChildPid,
              ProfileBufferControlledChunkManager::Update(
                  aUpdate.unreleasedBytes(), aUpdate.releasedBytes(),
                  aUpdate.oldestDoneTimeStamp(), std::move(chunks)));
          // This was not a final update, so start a new request.
          self->RequestChunkManagerUpdate();
        }
      },
      [self = RefPtr<ProfilerParent>(this)](
          mozilla::ipc::ResponseRejectReason aReason) {
        // Rejection could be for a number of reasons, assume the child will
        // not respond anymore, so we pretend we received a final update.
        ProfilerParentTracker::ForwardChildChunkManagerUpdate(
            self->mChildPid,
            ProfileBufferControlledChunkManager::Update(nullptr));
      });
}

// Ref-counted class that resolves a promise on destruction.
// Usage:
// RefPtr<GenericPromise> f() {
//   return PromiseResolverOnDestruction::RunTask(
//     [](RefPtr<PromiseResolverOnDestruction> aPromiseResolver){
//       // Give *copies* of aPromiseResolver to asynchronous sub-tasks, the
//       // last remaining RefPtr destruction will resolve the promise.
//     });
// }
class PromiseResolverOnDestruction {
 public:
  NS_INLINE_DECL_REFCOUNTING(PromiseResolverOnDestruction)

  template <typename TaskFunction>
  static RefPtr<GenericPromise> RunTask(TaskFunction&& aTaskFunction) {
    RefPtr<PromiseResolverOnDestruction> promiseResolver =
        new PromiseResolverOnDestruction();
    RefPtr<GenericPromise> promise =
        promiseResolver->mPromiseHolder.Ensure(__func__);
    std::forward<TaskFunction>(aTaskFunction)(std::move(promiseResolver));
    return promise;
  }

 private:
  PromiseResolverOnDestruction() = default;

  ~PromiseResolverOnDestruction() {
    mPromiseHolder.ResolveIfExists(/* unused */ true, __func__);
  }

  MozPromiseHolder<GenericPromise> mPromiseHolder;
};

// Given a ProfilerParentSendFunction: (ProfilerParent*) -> some MozPromise,
// run the function on all live ProfilerParents and return a GenericPromise, and
// when their promise gets resolve, resolve our Generic promise.
template <typename ProfilerParentSendFunction>
static RefPtr<GenericPromise> SendAndConvertPromise(
    ProfilerParentSendFunction&& aProfilerParentSendFunction) {
  if (!NS_IsMainThread()) {
    return GenericPromise::CreateAndResolve(/* unused */ true, __func__);
  }

  return PromiseResolverOnDestruction::RunTask(
      [&](RefPtr<PromiseResolverOnDestruction> aPromiseResolver) {
        ProfilerParentTracker::Enumerate([&](ProfilerParent* profilerParent) {
          std::forward<ProfilerParentSendFunction>(aProfilerParentSendFunction)(
              profilerParent)
              ->Then(GetMainThreadSerialEventTarget(), __func__,
                     [aPromiseResolver](
                         typename std::remove_reference_t<
                             decltype(*std::forward<ProfilerParentSendFunction>(
                                 aProfilerParentSendFunction)(
                                 profilerParent))>::ResolveOrRejectValue&&) {
                       // Whatever the resolution/rejection is, do nothing.
                       // The lambda aPromiseResolver ref-count will decrease.
                     });
        });
      });
}

/* static */
RefPtr<GenericPromise> ProfilerParent::ProfilerStarted(
    nsIProfilerStartParams* aParams) {
  if (!NS_IsMainThread()) {
    return GenericPromise::CreateAndResolve(/* unused */ true, __func__);
  }

  ProfilerInitParams ipcParams;
  double duration;
  ipcParams.enabled() = true;
  aParams->GetEntries(&ipcParams.entries());
  aParams->GetDuration(&duration);
  if (duration > 0.0) {
    ipcParams.duration() = Some(duration);
  } else {
    ipcParams.duration() = Nothing();
  }
  aParams->GetInterval(&ipcParams.interval());
  aParams->GetFeatures(&ipcParams.features());
  ipcParams.filters() = aParams->GetFilters().Clone();
  // We need filters as a Span<const char*> to test pids in the lambda below.
  auto filtersCStrings = nsTArray<const char*>{aParams->GetFilters().Length()};
  for (const auto& filter : aParams->GetFilters()) {
    filtersCStrings.AppendElement(filter.Data());
  }
  aParams->GetActiveTabID(&ipcParams.activeTabID());

  ProfilerParentTracker::ProfilerStarted(ipcParams.entries());

  return SendAndConvertPromise([&](ProfilerParent* profilerParent) {
    if (profiler::detail::FiltersExcludePid(
            filtersCStrings,
            ProfilerProcessId::FromNumber(profilerParent->mChildPid))) {
      // This pid is excluded, don't start the profiler at all.
      return PProfilerParent::StartPromise::CreateAndResolve(/* unused */ true,
                                                             __func__);
    }
    auto promise = profilerParent->SendStart(ipcParams);
    profilerParent->RequestChunkManagerUpdate();
    return promise;
  });
}

/* static */
void ProfilerParent::ProfilerWillStopIfStarted() {
  if (!NS_IsMainThread()) {
    return;
  }

  ProfilerParentTracker::ProfilerWillStopIfStarted();
}

/* static */
RefPtr<GenericPromise> ProfilerParent::ProfilerStopped() {
  return SendAndConvertPromise([](ProfilerParent* profilerParent) {
    return profilerParent->SendStop();
  });
}

/* static */
RefPtr<GenericPromise> ProfilerParent::ProfilerPaused() {
  return SendAndConvertPromise([](ProfilerParent* profilerParent) {
    return profilerParent->SendPause();
  });
}

/* static */
RefPtr<GenericPromise> ProfilerParent::ProfilerResumed() {
  return SendAndConvertPromise([](ProfilerParent* profilerParent) {
    return profilerParent->SendResume();
  });
}

/* static */
RefPtr<GenericPromise> ProfilerParent::ProfilerPausedSampling() {
  return SendAndConvertPromise([](ProfilerParent* profilerParent) {
    return profilerParent->SendPauseSampling();
  });
}

/* static */
RefPtr<GenericPromise> ProfilerParent::ProfilerResumedSampling() {
  return SendAndConvertPromise([](ProfilerParent* profilerParent) {
    return profilerParent->SendResumeSampling();
  });
}

/* static */
void ProfilerParent::ClearAllPages() {
  if (!NS_IsMainThread()) {
    return;
  }

  ProfilerParentTracker::Enumerate([](ProfilerParent* profilerParent) {
    Unused << profilerParent->SendClearAllPages();
  });
}

/* static */
RefPtr<GenericPromise> ProfilerParent::WaitOnePeriodicSampling() {
  return SendAndConvertPromise([](ProfilerParent* profilerParent) {
    return profilerParent->SendWaitOnePeriodicSampling();
  });
}

void ProfilerParent::ActorDestroy(ActorDestroyReason aActorDestroyReason) {
  MOZ_RELEASE_ASSERT(NS_IsMainThread());
  mDestroyed = true;
}

#endif

}  // namespace mozilla