summaryrefslogtreecommitdiffstats
path: root/dom/system/PathUtils.cpp
blob: d43171c4e93f12b7d9454a5ffd2f74913bb33083 (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
/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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 "PathUtils.h"

#include "mozilla/ClearOnShutdown.h"
#include "mozilla/DataMutex.h"
#include "mozilla/ErrorNames.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/Maybe.h"
#include "mozilla/MozPromise.h"
#include "mozilla/RefPtr.h"
#include "mozilla/Result.h"
#include "mozilla/ResultExtensions.h"
#include "mozilla/Span.h"
#include "mozilla/dom/DOMParser.h"
#include "mozilla/dom/PathUtilsBinding.h"
#include "mozilla/dom/Promise.h"
#include "nsAppDirectoryServiceDefs.h"
#include "nsCOMPtr.h"
#include "nsDirectoryServiceDefs.h"
#include "nsDirectoryServiceUtils.h"
#include "nsIFile.h"
#include "nsIGlobalObject.h"
#include "nsLocalFile.h"
#include "nsNetUtil.h"
#include "nsString.h"
#include "xpcpublic.h"

namespace mozilla::dom {

static constexpr auto ERROR_EMPTY_PATH =
    "PathUtils does not support empty paths"_ns;
static constexpr auto ERROR_INITIALIZE_PATH = "Could not initialize path"_ns;
static constexpr auto ERROR_GET_PARENT = "Could not get parent path"_ns;
static constexpr auto ERROR_JOIN = "Could not append to path"_ns;

static constexpr auto COLON = ": "_ns;

static void ThrowError(ErrorResult& aErr, const nsresult aResult,
                       const nsCString& aMessage) {
  nsAutoCStringN<32> errName;
  GetErrorName(aResult, errName);

  nsAutoCStringN<256> formattedMsg;
  formattedMsg.Append(aMessage);
  formattedMsg.Append(COLON);
  formattedMsg.Append(errName);

  switch (aResult) {
    case NS_ERROR_FILE_UNRECOGNIZED_PATH:
      aErr.ThrowOperationError(formattedMsg);
      break;

    case NS_ERROR_FILE_ACCESS_DENIED:
      aErr.ThrowInvalidAccessError(formattedMsg);
      break;

    case NS_ERROR_FAILURE:
    default:
      aErr.ThrowUnknownError(formattedMsg);
      break;
  }
}

static bool DoWindowsPathCheck() {
#ifdef XP_WIN
#  ifdef DEBUG
  return true;
#  else   // DEBUG
  return xpc::IsInAutomation();
#  endif  // DEBUG
#else     // XP_WIN
  return false;
#endif    // XP_WIN
}

/* static */
nsresult PathUtils::InitFileWithPath(nsIFile* aFile, const nsAString& aPath) {
  if (DoWindowsPathCheck()) {
    MOZ_RELEASE_ASSERT(!aPath.Contains(u'/'),
                       "Windows paths cannot include forward slashes");
  }

  MOZ_ASSERT(aFile);
  return aFile->InitWithPath(aPath);
}

StaticDataMutex<Maybe<PathUtils::DirectoryCache>> PathUtils::sDirCache{
    "sDirCache"};

/**
 * Return the leaf name, including leading path separators in the case of
 * Windows UNC drive paths.
 *
 * @param aFile The file whose leaf name is to be returned.
 * @param aResult The string to hold the resulting leaf name.
 * @param aParent The pre-computed parent of |aFile|. If not provided, it will
 *                be computed.
 */
static nsresult GetLeafNamePreservingRoot(nsIFile* aFile, nsString& aResult,
                                          nsIFile* aParent = nullptr) {
  MOZ_ASSERT(aFile);

  nsCOMPtr<nsIFile> parent = aParent;
  if (!parent) {
    MOZ_TRY(aFile->GetParent(getter_AddRefs(parent)));
  }

  if (parent) {
    return aFile->GetLeafName(aResult);
  }

  // We have reached the root path. On Windows, the leafname for a UNC path
  // will not have the leading backslashes, so we need to use the entire path
  // here:
  //
  // * for a UNIX root path (/) this will be /;
  // * for a Windows drive path (e.g., C:), this will be the drive path (C:);
  //   and
  // * for a Windows UNC server path (e.g., \\\\server), this will be the full
  //   server path (\\\\server).
  return aFile->GetPath(aResult);
}

void PathUtils::Filename(const GlobalObject&, const nsAString& aPath,
                         nsString& aResult, ErrorResult& aErr) {
  if (aPath.IsEmpty()) {
    aErr.ThrowNotAllowedError(ERROR_EMPTY_PATH);
    return;
  }

  nsCOMPtr<nsIFile> path = new nsLocalFile();
  if (nsresult rv = InitFileWithPath(path, aPath); NS_FAILED(rv)) {
    ThrowError(aErr, rv, ERROR_INITIALIZE_PATH);
    return;
  }

  if (nsresult rv = GetLeafNamePreservingRoot(path, aResult); NS_FAILED(rv)) {
    ThrowError(aErr, rv, "Could not get leaf name of path"_ns);
    return;
  }
}

void PathUtils::Parent(const GlobalObject&, const nsAString& aPath,
                       const int32_t aDepth, nsString& aResult,
                       ErrorResult& aErr) {
  if (aPath.IsEmpty()) {
    aErr.ThrowNotAllowedError(ERROR_EMPTY_PATH);
    return;
  }

  nsCOMPtr<nsIFile> path = new nsLocalFile();
  if (nsresult rv = InitFileWithPath(path, aPath); NS_FAILED(rv)) {
    ThrowError(aErr, rv, ERROR_INITIALIZE_PATH);
    return;
  }

  if (aDepth <= 0) {
    aErr.ThrowNotSupportedError("A depth of at least 1 is required");
    return;
  }

  nsCOMPtr<nsIFile> parent;
  for (int32_t i = 0; path && i < aDepth; i++) {
    if (nsresult rv = path->GetParent(getter_AddRefs(parent)); NS_FAILED(rv)) {
      ThrowError(aErr, rv, ERROR_GET_PARENT);
      return;
    }
    path = parent;
  }

  if (parent) {
    MOZ_ALWAYS_SUCCEEDS(parent->GetPath(aResult));
  } else {
    aResult = VoidString();
  }
}

void PathUtils::Join(const GlobalObject&, const Sequence<nsString>& aComponents,
                     nsString& aResult, ErrorResult& aErr) {
  nsCOMPtr<nsIFile> path = Join(Span(aComponents), aErr);
  if (aErr.Failed()) {
    return;
  }

  MOZ_ALWAYS_SUCCEEDS(path->GetPath(aResult));
}

already_AddRefed<nsIFile> PathUtils::Join(
    const Span<const nsString>& aComponents, ErrorResult& aErr) {
  if (aComponents.IsEmpty() || aComponents[0].IsEmpty()) {
    aErr.ThrowNotAllowedError(ERROR_EMPTY_PATH);
    return nullptr;
  }

  nsCOMPtr<nsIFile> path = new nsLocalFile();
  if (nsresult rv = InitFileWithPath(path, aComponents[0]); NS_FAILED(rv)) {
    ThrowError(aErr, rv, ERROR_INITIALIZE_PATH);
    return nullptr;
  }

  const auto components = Span<const nsString>(aComponents).Subspan(1);
  for (const auto& component : components) {
    if (nsresult rv = path->Append(component); NS_FAILED(rv)) {
      ThrowError(aErr, rv, ERROR_JOIN);
      return nullptr;
    }
  }

  return path.forget();
}

void PathUtils::JoinRelative(const GlobalObject&, const nsAString& aBasePath,
                             const nsAString& aRelativePath, nsString& aResult,
                             ErrorResult& aErr) {
  if (aRelativePath.IsEmpty()) {
    aResult = aBasePath;
    return;
  }

  nsCOMPtr<nsIFile> path = new nsLocalFile();
  if (nsresult rv = InitFileWithPath(path, aBasePath); NS_FAILED(rv)) {
    ThrowError(aErr, rv, ERROR_INITIALIZE_PATH);
    return;
  }

  if (nsresult rv = path->AppendRelativePath(aRelativePath); NS_FAILED(rv)) {
    ThrowError(aErr, rv, ERROR_JOIN);
    return;
  }

  MOZ_ALWAYS_SUCCEEDS(path->GetPath(aResult));
}

void PathUtils::ToExtendedWindowsPath(const GlobalObject&,
                                      const nsAString& aPath, nsString& aResult,
                                      ErrorResult& aErr) {
#ifndef XP_WIN
  aErr.ThrowNotAllowedError("Operation is windows specific"_ns);
  return;
#else
  if (aPath.IsEmpty()) {
    aErr.ThrowNotAllowedError(ERROR_EMPTY_PATH);
    return;
  }

  const nsAString& str1 = Substring(aPath, 1, 1);
  const nsAString& str2 = Substring(aPath, 2, aPath.Length() - 2);

  bool isUNC = aPath.Length() >= 2 &&
               (aPath.First() == '\\' || aPath.First() == '/') &&
               (str1.EqualsLiteral("\\") || str1.EqualsLiteral("/"));

  constexpr auto pathPrefix = u"\\\\?\\"_ns;
  const nsAString& uncPath = pathPrefix + u"UNC\\"_ns + str2;
  const nsAString& normalPath = pathPrefix + aPath;

  nsCOMPtr<nsIFile> path = new nsLocalFile();
  if (nsresult rv = InitFileWithPath(path, isUNC ? uncPath : normalPath);
      NS_FAILED(rv)) {
    ThrowError(aErr, rv, ERROR_INITIALIZE_PATH);
    return;
  }

  MOZ_ALWAYS_SUCCEEDS(path->GetPath(aResult));
#endif
}

void PathUtils::Normalize(const GlobalObject&, const nsAString& aPath,
                          nsString& aResult, ErrorResult& aErr) {
  if (aPath.IsEmpty()) {
    aErr.ThrowNotAllowedError(ERROR_EMPTY_PATH);
    return;
  }

  nsCOMPtr<nsIFile> path = new nsLocalFile();
  if (nsresult rv = InitFileWithPath(path, aPath); NS_FAILED(rv)) {
    ThrowError(aErr, rv, ERROR_INITIALIZE_PATH);
    return;
  }

  if (nsresult rv = path->Normalize(); NS_FAILED(rv)) {
    ThrowError(aErr, rv, "Could not normalize path"_ns);
    return;
  }

  MOZ_ALWAYS_SUCCEEDS(path->GetPath(aResult));
}

void PathUtils::Split(const GlobalObject&, const nsAString& aPath,
                      nsTArray<nsString>& aResult, ErrorResult& aErr) {
  if (aPath.IsEmpty()) {
    aErr.ThrowNotAllowedError(ERROR_EMPTY_PATH);
    return;
  }

  nsCOMPtr<nsIFile> path = new nsLocalFile();
  if (nsresult rv = InitFileWithPath(path, aPath); NS_FAILED(rv)) {
    ThrowError(aErr, rv, ERROR_INITIALIZE_PATH);
    return;
  }

  while (path) {
    auto* component = aResult.EmplaceBack(fallible);
    if (!component) {
      aErr.Throw(NS_ERROR_OUT_OF_MEMORY);
      return;
    }

    nsCOMPtr<nsIFile> parent;
    if (nsresult rv = path->GetParent(getter_AddRefs(parent)); NS_FAILED(rv)) {
      ThrowError(aErr, rv, ERROR_GET_PARENT);
      return;
    }

    // GetLeafPreservingRoot cannot fail if we pass it a parent path.
    MOZ_ALWAYS_SUCCEEDS(GetLeafNamePreservingRoot(path, *component, parent));

    path = parent;
  }

  aResult.Reverse();
}

void PathUtils::SplitRelative(const GlobalObject& aGlobal,
                              const nsAString& aPath,
                              const SplitRelativeOptions& aOptions,
                              nsTArray<nsString>& aResult, ErrorResult& aErr) {
  if (aPath.IsEmpty()) {
    aErr.ThrowNotAllowedError(ERROR_EMPTY_PATH);
    return;
  }

  if (DoWindowsPathCheck()) {
    MOZ_RELEASE_ASSERT(!aPath.Contains(u'/'),
                       "Windows paths cannot include forward slashes");
  }

  if (IsAbsolute(aGlobal, aPath)) {
    aErr.ThrowNotAllowedError(
        "PathUtils.splitRelative requires a relative path"_ns);
    return;
  }

#ifdef XP_WIN
  constexpr auto SEPARATOR = u'\\';
#else
  constexpr auto SEPARATOR = u'/';
#endif

  constexpr auto PARENT = u".."_ns;
  constexpr auto CURRENT = u"."_ns;

  for (const nsAString& pathComponent :
       nsCharSeparatedTokenizerTemplate<NS_TokenizerIgnoreNothing>{aPath,
                                                                   SEPARATOR}
           .ToRange()) {
    if (!aOptions.mAllowEmpty && pathComponent.IsEmpty()) {
      aErr.ThrowNotAllowedError(
          "PathUtils.splitRelative: Empty directory components (\"\") not "
          "allowed by options");
      return;
    }

    if (!aOptions.mAllowParentDir && pathComponent == PARENT) {
      aErr.ThrowNotAllowedError(
          "PathUtils.splitRelative: Parent directory components (\"..\") not "
          "allowed by options");
      return;
    }

    if (!aOptions.mAllowCurrentDir && pathComponent == CURRENT) {
      aErr.ThrowNotAllowedError(
          "PathUtils.splitRelative: Current directory components (\".\") not "
          "allowed by options");
      return;
    }

    aResult.AppendElement(pathComponent);
  }
}

void PathUtils::ToFileURI(const GlobalObject&, const nsAString& aPath,
                          nsCString& aResult, ErrorResult& aErr) {
  if (aPath.IsEmpty()) {
    aErr.ThrowNotAllowedError(ERROR_EMPTY_PATH);
    return;
  }

  nsCOMPtr<nsIFile> path = new nsLocalFile();
  if (nsresult rv = InitFileWithPath(path, aPath); NS_FAILED(rv)) {
    ThrowError(aErr, rv, ERROR_INITIALIZE_PATH);
    return;
  }

  nsCOMPtr<nsIURI> uri;
  if (nsresult rv = NS_NewFileURI(getter_AddRefs(uri), path); NS_FAILED(rv)) {
    ThrowError(aErr, rv, "Could not initialize File URI"_ns);
    return;
  }

  if (nsresult rv = uri->GetSpec(aResult); NS_FAILED(rv)) {
    ThrowError(aErr, rv, "Could not retrieve URI spec"_ns);
    return;
  }
}

bool PathUtils::IsAbsolute(const GlobalObject&, const nsAString& aPath) {
  nsCOMPtr<nsIFile> path = new nsLocalFile();
  nsresult rv = InitFileWithPath(path, aPath);
  return NS_SUCCEEDED(rv);
}

void PathUtils::GetProfileDirSync(const GlobalObject&, nsString& aResult,
                                  ErrorResult& aErr) {
  MOZ_ASSERT(NS_IsMainThread());

  auto guard = sDirCache.Lock();
  DirectoryCache::Ensure(guard.ref())
      .GetDirectorySync(aResult, aErr, DirectoryCache::Directory::Profile);
}
void PathUtils::GetLocalProfileDirSync(const GlobalObject&, nsString& aResult,
                                       ErrorResult& aErr) {
  MOZ_ASSERT(NS_IsMainThread());

  auto guard = sDirCache.Lock();
  DirectoryCache::Ensure(guard.ref())
      .GetDirectorySync(aResult, aErr, DirectoryCache::Directory::LocalProfile);
}
void PathUtils::GetTempDirSync(const GlobalObject&, nsString& aResult,
                               ErrorResult& aErr) {
  MOZ_ASSERT(NS_IsMainThread());

  auto guard = sDirCache.Lock();
  DirectoryCache::Ensure(guard.ref())
      .GetDirectorySync(aResult, aErr, DirectoryCache::Directory::Temp);
}

void PathUtils::GetXulLibraryPathSync(const GlobalObject&, nsString& aResult,
                                      ErrorResult& aErr) {
  MOZ_ASSERT(NS_IsMainThread());

  auto guard = sDirCache.Lock();
  DirectoryCache::Ensure(guard.ref())
      .GetDirectorySync(aResult, aErr, DirectoryCache::Directory::XulLibrary);
}

already_AddRefed<Promise> PathUtils::GetProfileDirAsync(
    const GlobalObject& aGlobal, ErrorResult& aErr) {
  MOZ_ASSERT(!NS_IsMainThread());

  auto guard = sDirCache.Lock();
  return DirectoryCache::Ensure(guard.ref())
      .GetDirectoryAsync(aGlobal, aErr, DirectoryCache::Directory::Profile);
}

already_AddRefed<Promise> PathUtils::GetLocalProfileDirAsync(
    const GlobalObject& aGlobal, ErrorResult& aErr) {
  MOZ_ASSERT(!NS_IsMainThread());

  auto guard = sDirCache.Lock();
  return DirectoryCache::Ensure(guard.ref())
      .GetDirectoryAsync(aGlobal, aErr,
                         DirectoryCache::Directory::LocalProfile);
}

already_AddRefed<Promise> PathUtils::GetTempDirAsync(
    const GlobalObject& aGlobal, ErrorResult& aErr) {
  MOZ_ASSERT(!NS_IsMainThread());

  auto guard = sDirCache.Lock();
  return DirectoryCache::Ensure(guard.ref())
      .GetDirectoryAsync(aGlobal, aErr, DirectoryCache::Directory::Temp);
}

already_AddRefed<Promise> PathUtils::GetXulLibraryPathAsync(
    const GlobalObject& aGlobal, ErrorResult& aErr) {
  MOZ_ASSERT(!NS_IsMainThread());

  auto guard = sDirCache.Lock();
  return DirectoryCache::Ensure(guard.ref())
      .GetDirectoryAsync(aGlobal, aErr, DirectoryCache::Directory::XulLibrary);
}

PathUtils::DirectoryCache::DirectoryCache() {
  for (auto& dir : mDirectories) {
    dir.SetIsVoid(true);
  }
}

PathUtils::DirectoryCache& PathUtils::DirectoryCache::Ensure(
    Maybe<PathUtils::DirectoryCache>& aCache) {
  if (aCache.isNothing()) {
    aCache.emplace();

    auto clearAtShutdown = []() {
      RunOnShutdown([]() {
        auto cache = PathUtils::sDirCache.Lock();
        cache->reset();
      });
    };

    if (NS_IsMainThread()) {
      clearAtShutdown();
    } else {
      NS_DispatchToMainThread(
          NS_NewRunnableFunction(__func__, std::move(clearAtShutdown)));
    }
  }

  return aCache.ref();
}

void PathUtils::DirectoryCache::GetDirectorySync(
    nsString& aResult, ErrorResult& aErr, const Directory aRequestedDir) {
  MOZ_RELEASE_ASSERT(aRequestedDir < Directory::Count);

  if (nsresult rv = PopulateDirectoriesImpl(aRequestedDir); NS_FAILED(rv)) {
    nsAutoCStringN<32> errorName;
    GetErrorName(rv, errorName);

    nsAutoCStringN<256> msg;
    msg.Append("Could not retrieve directory "_ns);
    msg.Append(kDirectoryNames[aRequestedDir]);
    msg.Append(COLON);
    msg.Append(errorName);

    aErr.ThrowUnknownError(msg);
    return;
  }

  aResult = mDirectories[aRequestedDir];
}

already_AddRefed<Promise> PathUtils::DirectoryCache::GetDirectoryAsync(
    const GlobalObject& aGlobal, ErrorResult& aErr,
    const Directory aRequestedDir) {
  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());
  RefPtr<Promise> promise = Promise::Create(global, aErr);
  if (aErr.Failed()) {
    return nullptr;
  }

  if (RefPtr<PopulateDirectoriesPromise> p =
          PopulateDirectories(aRequestedDir)) {
    p->Then(
        GetCurrentSerialEventTarget(), __func__,
        [promise, aRequestedDir](const Ok&) {
          auto cache = PathUtils::sDirCache.Lock();
          cache.ref()->ResolveWithDirectory(promise, aRequestedDir);
        },
        [promise](const nsresult& aRv) { promise->MaybeReject(aRv); });
  } else {
    ResolveWithDirectory(promise, aRequestedDir);
  }

  return promise.forget();
}

void PathUtils::DirectoryCache::ResolveWithDirectory(
    Promise* aPromise, const Directory aRequestedDir) {
  MOZ_RELEASE_ASSERT(aRequestedDir < Directory::Count);
  MOZ_RELEASE_ASSERT(!mDirectories[aRequestedDir].IsVoid());
  aPromise->MaybeResolve(mDirectories[aRequestedDir]);
}

already_AddRefed<PathUtils::DirectoryCache::PopulateDirectoriesPromise>
PathUtils::DirectoryCache::PopulateDirectories(
    const PathUtils::DirectoryCache::Directory aRequestedDir) {
  MOZ_RELEASE_ASSERT(aRequestedDir < Directory::Count);

  // If we have already resolved the requested directory, we can return
  // immediately.
  // Otherwise, if we have already fired off a request to populate the entry,
  // so we can return the corresponding promise immediately. caller will queue
  // a Thenable onto that promise to resolve/reject the request.
  if (!mDirectories[aRequestedDir].IsVoid()) {
    return nullptr;
  }
  if (!mPromises[aRequestedDir].IsEmpty()) {
    return mPromises[aRequestedDir].Ensure(__func__);
  }

  RefPtr<PopulateDirectoriesPromise> promise =
      mPromises[aRequestedDir].Ensure(__func__);

  if (NS_IsMainThread()) {
    nsresult rv = PopulateDirectoriesImpl(aRequestedDir);
    ResolvePopulateDirectoriesPromise(rv, aRequestedDir);
  } else {
    nsCOMPtr<nsIRunnable> runnable =
        NS_NewRunnableFunction(__func__, [aRequestedDir]() {
          auto cache = PathUtils::sDirCache.Lock();
          nsresult rv = cache.ref()->PopulateDirectoriesImpl(aRequestedDir);
          cache.ref()->ResolvePopulateDirectoriesPromise(rv, aRequestedDir);
        });
    NS_DispatchToMainThread(runnable.forget());
  }

  return promise.forget();
}

void PathUtils::DirectoryCache::ResolvePopulateDirectoriesPromise(
    nsresult aRv, const PathUtils::DirectoryCache::Directory aRequestedDir) {
  MOZ_RELEASE_ASSERT(aRequestedDir < Directory::Count);

  if (NS_SUCCEEDED(aRv)) {
    mPromises[aRequestedDir].Resolve(Ok{}, __func__);
  } else {
    mPromises[aRequestedDir].Reject(aRv, __func__);
  }
}

nsresult PathUtils::DirectoryCache::PopulateDirectoriesImpl(
    const PathUtils::DirectoryCache::Directory aRequestedDir) {
  MOZ_RELEASE_ASSERT(NS_IsMainThread());
  MOZ_RELEASE_ASSERT(aRequestedDir < Directory::Count);

  if (!mDirectories[aRequestedDir].IsVoid()) {
    // In between when this promise was dispatched to the main thread and now,
    // the directory cache has had this entry populated (via the
    // on-main-thread sync method).
    return NS_OK;
  }

  nsCOMPtr<nsIFile> path;

  MOZ_TRY(NS_GetSpecialDirectory(kDirectoryNames[aRequestedDir],
                                 getter_AddRefs(path)));
  MOZ_TRY(path->GetPath(mDirectories[aRequestedDir]));

  return NS_OK;
}

}  // namespace mozilla::dom