summaryrefslogtreecommitdiffstats
path: root/toolkit/components/telemetry/other/UntrustedModules.cpp
blob: db77ad8e9615d58fde5f3cd80a1e750066c8943b (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
/* -*- 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 "UntrustedModules.h"

#include "mozilla/dom/ContentParent.h"
#include "mozilla/MozPromise.h"
#include "mozilla/RDDChild.h"
#include "mozilla/RDDProcessManager.h"
#include "mozilla/WinDllServices.h"
#include "nsISupportsImpl.h"
#include "nsProxyRelease.h"
#include "nsXULAppAPI.h"
#include "UntrustedModulesDataSerializer.h"

namespace mozilla {
namespace Telemetry {

static const uint32_t kMaxModulesArrayLen = 100;

using UntrustedModulesIpcPromise =
    MozPromise<Maybe<UntrustedModulesData>, ipc::ResponseRejectReason, true>;

using MultiGetUntrustedModulesPromise =
    MozPromise<bool /*aIgnored*/, nsresult, true>;

class MOZ_HEAP_CLASS MultiGetUntrustedModulesData final {
  using BackupType = UntrustedModulesBackupService::BackupType;

 public:
  /**
   * @param aFlags [in] Combinations of the flags defined under nsITelemetry.
   *               (See "Flags for getUntrustedModuleLoadEvents"
   *                in nsITelemetry.idl)
   */
  explicit MultiGetUntrustedModulesData(uint32_t aFlags)
      : mFlags(aFlags),
        mBackupSvc(UntrustedModulesBackupService::Get()),
        mPromise(new MultiGetUntrustedModulesPromise::Private(__func__)),
        mNumPending(0) {}

  NS_INLINE_DECL_THREADSAFE_REFCOUNTING(MultiGetUntrustedModulesData)

  RefPtr<MultiGetUntrustedModulesPromise> GetUntrustedModuleLoadEvents();
  void Serialize(RefPtr<dom::Promise>&& aPromise);

  MultiGetUntrustedModulesData(const MultiGetUntrustedModulesData&) = delete;
  MultiGetUntrustedModulesData(MultiGetUntrustedModulesData&&) = delete;
  MultiGetUntrustedModulesData& operator=(const MultiGetUntrustedModulesData&) =
      delete;
  MultiGetUntrustedModulesData& operator=(MultiGetUntrustedModulesData&&) =
      delete;

 private:
  ~MultiGetUntrustedModulesData() = default;

  void AddPending(RefPtr<UntrustedModulesPromise>&& aNewPending) {
    MOZ_ASSERT(NS_IsMainThread());

    ++mNumPending;

    RefPtr<MultiGetUntrustedModulesData> self(this);
    aNewPending->Then(
        GetMainThreadSerialEventTarget(), __func__,
        [self](Maybe<UntrustedModulesData>&& aResult) {
          self->OnCompletion(std::move(aResult));
        },
        [self](nsresult aReason) { self->OnCompletion(); });
  }

  void AddPending(RefPtr<UntrustedModulesIpcPromise>&& aNewPending) {
    MOZ_ASSERT(NS_IsMainThread());

    ++mNumPending;

    RefPtr<MultiGetUntrustedModulesData> self(this);
    aNewPending->Then(
        GetMainThreadSerialEventTarget(), __func__,
        [self](Maybe<UntrustedModulesData>&& aResult) {
          self->OnCompletion(std::move(aResult));
        },
        [self](ipc::ResponseRejectReason&& aReason) { self->OnCompletion(); });
  }

  void OnCompletion() {
    MOZ_ASSERT(NS_IsMainThread() && mNumPending > 0);

    --mNumPending;
    if (mNumPending) {
      return;
    }

    mPromise->Resolve(true, __func__);
  }

  void OnCompletion(Maybe<UntrustedModulesData>&& aResult) {
    MOZ_ASSERT(NS_IsMainThread());

    if (aResult.isSome()) {
      mBackupSvc->Backup(BackupType::Staging, std::move(aResult.ref()));
    }

    OnCompletion();
  }

 private:
  // Combinations of the flags defined under nsITelemetry.
  // (See "Flags for getUntrustedModuleLoadEvents" in nsITelemetry.idl)
  uint32_t mFlags;

  RefPtr<UntrustedModulesBackupService> mBackupSvc;
  RefPtr<MultiGetUntrustedModulesPromise::Private> mPromise;
  size_t mNumPending;
};

RefPtr<MultiGetUntrustedModulesPromise>
MultiGetUntrustedModulesData::GetUntrustedModuleLoadEvents() {
  MOZ_ASSERT(XRE_IsParentProcess() && NS_IsMainThread());

  // Parent process
  RefPtr<DllServices> dllSvc(DllServices::Get());
  AddPending(dllSvc->GetUntrustedModulesData());

  // Child processes
  nsTArray<dom::ContentParent*> contentParents;
  dom::ContentParent::GetAll(contentParents);
  for (auto&& contentParent : contentParents) {
    AddPending(contentParent->SendGetUntrustedModulesData());
  }

  if (RDDProcessManager* rddMgr = RDDProcessManager::Get()) {
    if (RDDChild* rddChild = rddMgr->GetRDDChild()) {
      AddPending(rddChild->SendGetUntrustedModulesData());
    }
  }

  return mPromise;
}

void MultiGetUntrustedModulesData::Serialize(RefPtr<dom::Promise>&& aPromise) {
  MOZ_ASSERT(NS_IsMainThread());

  dom::AutoJSAPI jsapi;
  if (NS_WARN_IF(!jsapi.Init(aPromise->GetGlobalObject()))) {
    aPromise->MaybeReject(NS_ERROR_FAILURE);
    return;
  }

  JSContext* cx = jsapi.cx();
  UntrustedModulesDataSerializer serializer(cx, kMaxModulesArrayLen, mFlags);
  if (!serializer) {
    aPromise->MaybeReject(NS_ERROR_FAILURE);
    return;
  }

  nsresult rv;
  if (mFlags & nsITelemetry::INCLUDE_OLD_LOADEVENTS) {
    // When INCLUDE_OLD_LOADEVENTS is set, we need to return instances
    // from both "Staging" and "Settled" backup.
    if (mFlags & nsITelemetry::KEEP_LOADEVENTS_NEW) {
      // When INCLUDE_OLD_LOADEVENTS and KEEP_LOADEVENTS_NEW are set, we need to
      // return a JS object consisting of all instances from both "Staging" and
      // "Settled" backups, keeping instances in those backups as is.
      if (mFlags & nsITelemetry::EXCLUDE_STACKINFO_FROM_LOADEVENTS) {
        // Without the stack info, we can add multiple UntrustedModulesData to
        // the serializer directly.
        rv = serializer.Add(mBackupSvc->Ref(BackupType::Staging));
        if (NS_WARN_IF(NS_FAILED(rv))) {
          aPromise->MaybeReject(rv);
          return;
        }
        rv = serializer.Add(mBackupSvc->Ref(BackupType::Settled));
        if (NS_WARN_IF(NS_FAILED(rv))) {
          aPromise->MaybeReject(rv);
          return;
        }
      } else {
        // Currently we don't have a method to merge UntrustedModulesData into
        // a serialized JS object because merging CombinedStack will be tricky.
        // Thus we return an error on this flag combination.
        aPromise->MaybeReject(NS_ERROR_INVALID_ARG);
        return;
      }
    } else {
      // When KEEP_LOADEVENTS_NEW is not set, we can move data from "Staging"
      // to "Settled" first, then add "Settled" to the serializer.
      mBackupSvc->SettleAllStagingData();

      const UntrustedModulesBackupData& settledRef =
          mBackupSvc->Ref(BackupType::Settled);
      if (settledRef.IsEmpty()) {
        aPromise->MaybeReject(NS_ERROR_NOT_AVAILABLE);
        return;
      }

      rv = serializer.Add(settledRef);
      if (NS_WARN_IF(NS_FAILED(rv))) {
        aPromise->MaybeReject(rv);
        return;
      }
    }
  } else {
    // When INCLUDE_OLD_LOADEVENTS is not set, we serialize only the "Staging"
    // into a JS object.
    const UntrustedModulesBackupData& stagingRef =
        mBackupSvc->Ref(BackupType::Staging);

    if (stagingRef.IsEmpty()) {
      aPromise->MaybeReject(NS_ERROR_NOT_AVAILABLE);
      return;
    }

    rv = serializer.Add(stagingRef);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      aPromise->MaybeReject(rv);
      return;
    }

    // When KEEP_LOADEVENTS_NEW is not set, we move all "Staging" instances
    // to the "Settled".
    if (!(mFlags & nsITelemetry::KEEP_LOADEVENTS_NEW)) {
      mBackupSvc->SettleAllStagingData();
    }
  }

  JS::RootedValue jsval(cx);
  serializer.GetObject(&jsval);
  aPromise->MaybeResolve(jsval);
}

nsresult GetUntrustedModuleLoadEvents(uint32_t aFlags, JSContext* cx,
                                      dom::Promise** aPromise) {
  // Create a promise using global context.
  nsIGlobalObject* global = xpc::CurrentNativeGlobal(cx);
  if (NS_WARN_IF(!global)) {
    return NS_ERROR_FAILURE;
  }

  ErrorResult result;
  RefPtr<dom::Promise> promise(dom::Promise::Create(global, result));
  if (NS_WARN_IF(result.Failed())) {
    return result.StealNSResult();
  }

  auto multi = MakeRefPtr<MultiGetUntrustedModulesData>(aFlags);
  multi->GetUntrustedModuleLoadEvents()->Then(
      GetMainThreadSerialEventTarget(), __func__,
      [promise, multi](bool) mutable { multi->Serialize(std::move(promise)); },
      [promise](nsresult aRv) { promise->MaybeReject(aRv); });

  promise.forget(aPromise);
  return NS_OK;
}

}  // namespace Telemetry
}  // namespace mozilla