summaryrefslogtreecommitdiffstats
path: root/dom/asmjscache/AsmJSCache.cpp
blob: 4e1912f230b6fd574231ed4f3998d1051101ada0 (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
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
/* -*- 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 "AsmJSCache.h"

#include <stdio.h>

#include "js/RootingAPI.h"
#include "jsfriendapi.h"
#include "mozilla/Assertions.h"
#include "mozilla/CondVar.h"
#include "mozilla/CycleCollectedJSContext.h"
#include "mozilla/dom/asmjscache/PAsmJSCacheEntryChild.h"
#include "mozilla/dom/asmjscache/PAsmJSCacheEntryParent.h"
#include "mozilla/dom/ContentChild.h"
#include "mozilla/dom/PermissionMessageUtils.h"
#include "mozilla/dom/quota/Client.h"
#include "mozilla/dom/quota/QuotaManager.h"
#include "mozilla/dom/quota/QuotaObject.h"
#include "mozilla/dom/quota/UsageInfo.h"
#include "mozilla/HashFunctions.h"
#include "mozilla/ipc/BackgroundChild.h"
#include "mozilla/ipc/BackgroundParent.h"
#include "mozilla/ipc/BackgroundUtils.h"
#include "mozilla/ipc/PBackgroundChild.h"
#include "mozilla/Unused.h"
#include "nsAutoPtr.h"
#include "nsIAtom.h"
#include "nsIFile.h"
#include "nsIIPCBackgroundChildCreateCallback.h"
#include "nsIPermissionManager.h"
#include "nsIPrincipal.h"
#include "nsIRunnable.h"
#include "nsISimpleEnumerator.h"
#include "nsIThread.h"
#include "nsJSPrincipals.h"
#include "nsThreadUtils.h"
#include "nsXULAppAPI.h"
#include "prio.h"
#include "private/pprio.h"
#include "mozilla/Services.h"

#define ASMJSCACHE_METADATA_FILE_NAME "metadata"
#define ASMJSCACHE_ENTRY_FILE_NAME_BASE "module"

using mozilla::dom::quota::AssertIsOnIOThread;
using mozilla::dom::quota::DirectoryLock;
using mozilla::dom::quota::PersistenceType;
using mozilla::dom::quota::QuotaManager;
using mozilla::dom::quota::QuotaObject;
using mozilla::dom::quota::UsageInfo;
using mozilla::ipc::AssertIsOnBackgroundThread;
using mozilla::ipc::BackgroundChild;
using mozilla::ipc::IsOnBackgroundThread;
using mozilla::ipc::PBackgroundChild;
using mozilla::ipc::PrincipalInfo;
using mozilla::Unused;
using mozilla::HashString;

namespace mozilla {

MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE(ScopedPRFileDesc, PRFileDesc, PR_Close);

namespace dom {
namespace asmjscache {

namespace {

// Anything smaller should compile fast enough that caching will just add
// overhead.
static const size_t sMinCachedModuleLength = 10000;

// The number of characters to hash into the Metadata::Entry::mFastHash.
static const unsigned sNumFastHashChars = 4096;

nsresult
WriteMetadataFile(nsIFile* aMetadataFile, const Metadata& aMetadata)
{
  int32_t openFlags = PR_WRONLY | PR_TRUNCATE | PR_CREATE_FILE;

  JS::BuildIdCharVector buildId;
  bool ok = GetBuildId(&buildId);
  NS_ENSURE_TRUE(ok, NS_ERROR_OUT_OF_MEMORY);

  ScopedPRFileDesc fd;
  nsresult rv = aMetadataFile->OpenNSPRFileDesc(openFlags, 0644, &fd.rwget());
  NS_ENSURE_SUCCESS(rv, rv);

  uint32_t length = buildId.length();
  int32_t bytesWritten = PR_Write(fd, &length, sizeof(length));
  NS_ENSURE_TRUE(bytesWritten == sizeof(length), NS_ERROR_UNEXPECTED);

  bytesWritten = PR_Write(fd, buildId.begin(), length);
  NS_ENSURE_TRUE(bytesWritten == int32_t(length), NS_ERROR_UNEXPECTED);

  bytesWritten = PR_Write(fd, &aMetadata, sizeof(aMetadata));
  NS_ENSURE_TRUE(bytesWritten == sizeof(aMetadata), NS_ERROR_UNEXPECTED);

  return NS_OK;
}

nsresult
ReadMetadataFile(nsIFile* aMetadataFile, Metadata& aMetadata)
{
  int32_t openFlags = PR_RDONLY;

  ScopedPRFileDesc fd;
  nsresult rv = aMetadataFile->OpenNSPRFileDesc(openFlags, 0644, &fd.rwget());
  NS_ENSURE_SUCCESS(rv, rv);

  // Read the buildid and check that it matches the current buildid

  JS::BuildIdCharVector currentBuildId;
  bool ok = GetBuildId(&currentBuildId);
  NS_ENSURE_TRUE(ok, NS_ERROR_OUT_OF_MEMORY);

  uint32_t length;
  int32_t bytesRead = PR_Read(fd, &length, sizeof(length));
  NS_ENSURE_TRUE(bytesRead == sizeof(length), NS_ERROR_UNEXPECTED);

  NS_ENSURE_TRUE(currentBuildId.length() == length, NS_ERROR_UNEXPECTED);

  JS::BuildIdCharVector fileBuildId;
  ok = fileBuildId.resize(length);
  NS_ENSURE_TRUE(ok, NS_ERROR_OUT_OF_MEMORY);

  bytesRead = PR_Read(fd, fileBuildId.begin(), length);
  NS_ENSURE_TRUE(bytesRead == int32_t(length), NS_ERROR_UNEXPECTED);

  for (uint32_t i = 0; i < length; i++) {
    if (currentBuildId[i] != fileBuildId[i]) {
      return NS_ERROR_FAILURE;
    }
  }

  // Read the Metadata struct

  bytesRead = PR_Read(fd, &aMetadata, sizeof(aMetadata));
  NS_ENSURE_TRUE(bytesRead == sizeof(aMetadata), NS_ERROR_UNEXPECTED);

  return NS_OK;
}

nsresult
GetCacheFile(nsIFile* aDirectory, unsigned aModuleIndex, nsIFile** aCacheFile)
{
  nsCOMPtr<nsIFile> cacheFile;
  nsresult rv = aDirectory->Clone(getter_AddRefs(cacheFile));
  NS_ENSURE_SUCCESS(rv, rv);

  nsString cacheFileName = NS_LITERAL_STRING(ASMJSCACHE_ENTRY_FILE_NAME_BASE);
  cacheFileName.AppendInt(aModuleIndex);
  rv = cacheFile->Append(cacheFileName);
  NS_ENSURE_SUCCESS(rv, rv);

  cacheFile.forget(aCacheFile);
  return NS_OK;
}

class AutoDecreaseUsageForOrigin
{
  const nsACString& mGroup;
  const nsACString& mOrigin;

public:
  uint64_t mFreed;

  AutoDecreaseUsageForOrigin(const nsACString& aGroup,
                             const nsACString& aOrigin)

  : mGroup(aGroup),
    mOrigin(aOrigin),
    mFreed(0)
  { }

  ~AutoDecreaseUsageForOrigin()
  {
    AssertIsOnIOThread();

    if (!mFreed) {
      return;
    }

    QuotaManager* qm = QuotaManager::Get();
    MOZ_ASSERT(qm, "We are on the QuotaManager's IO thread");

    qm->DecreaseUsageForOrigin(quota::PERSISTENCE_TYPE_TEMPORARY,
                               mGroup, mOrigin, mFreed);
  }
};

static void
EvictEntries(nsIFile* aDirectory, const nsACString& aGroup,
             const nsACString& aOrigin, uint64_t aNumBytes,
             Metadata& aMetadata)
{
  AssertIsOnIOThread();

  AutoDecreaseUsageForOrigin usage(aGroup, aOrigin);

  for (int i = Metadata::kLastEntry; i >= 0 && usage.mFreed < aNumBytes; i--) {
    Metadata::Entry& entry = aMetadata.mEntries[i];
    unsigned moduleIndex = entry.mModuleIndex;

    nsCOMPtr<nsIFile> file;
    nsresult rv = GetCacheFile(aDirectory, moduleIndex, getter_AddRefs(file));
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return;
    }

    bool exists;
    rv = file->Exists(&exists);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return;
    }

    if (exists) {
      int64_t fileSize;
      rv = file->GetFileSize(&fileSize);
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return;
      }

      rv = file->Remove(false);
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return;
      }

      usage.mFreed += fileSize;
    }

    entry.clear();
  }
}

// FileDescriptorHolder owns a file descriptor and its memory mapping.
// FileDescriptorHolder is derived by two runnable classes (that is,
// (Parent|Child)Runnable.
class FileDescriptorHolder : public Runnable
{
public:
  FileDescriptorHolder()
  : mQuotaObject(nullptr),
    mFileSize(INT64_MIN),
    mFileDesc(nullptr),
    mFileMap(nullptr),
    mMappedMemory(nullptr)
  { }

  ~FileDescriptorHolder()
  {
    // These resources should have already been released by Finish().
    MOZ_ASSERT(!mQuotaObject);
    MOZ_ASSERT(!mMappedMemory);
    MOZ_ASSERT(!mFileMap);
    MOZ_ASSERT(!mFileDesc);
  }

  size_t
  FileSize() const
  {
    MOZ_ASSERT(mFileSize >= 0, "Accessing FileSize of unopened file");
    return mFileSize;
  }

  PRFileDesc*
  FileDesc() const
  {
    MOZ_ASSERT(mFileDesc, "Accessing FileDesc of unopened file");
    return mFileDesc;
  }

  bool
  MapMemory(OpenMode aOpenMode)
  {
    MOZ_ASSERT(!mFileMap, "Cannot call MapMemory twice");

    PRFileMapProtect mapFlags = aOpenMode == eOpenForRead ? PR_PROT_READONLY
                                                          : PR_PROT_READWRITE;

    mFileMap = PR_CreateFileMap(mFileDesc, mFileSize, mapFlags);
    NS_ENSURE_TRUE(mFileMap, false);

    mMappedMemory = PR_MemMap(mFileMap, 0, mFileSize);
    NS_ENSURE_TRUE(mMappedMemory, false);

    return true;
  }

  void*
  MappedMemory() const
  {
    MOZ_ASSERT(mMappedMemory, "Accessing MappedMemory of un-mapped file");
    return mMappedMemory;
  }

protected:
  // This method must be called before the directory lock is released (the lock
  // is protecting these resources). It is idempotent, so it is ok to call
  // multiple times (or before the file has been fully opened).
  void
  Finish()
  {
    if (mMappedMemory) {
      PR_MemUnmap(mMappedMemory, mFileSize);
      mMappedMemory = nullptr;
    }
    if (mFileMap) {
      PR_CloseFileMap(mFileMap);
      mFileMap = nullptr;
    }
    if (mFileDesc) {
      PR_Close(mFileDesc);
      mFileDesc = nullptr;
    }

    // Holding the QuotaObject alive until all the cache files are closed enables
    // assertions in QuotaManager that the cache entry isn't cleared while we
    // are working on it.
    mQuotaObject = nullptr;
  }

  RefPtr<QuotaObject> mQuotaObject;
  int64_t mFileSize;
  PRFileDesc* mFileDesc;
  PRFileMap* mFileMap;
  void* mMappedMemory;
};

// A runnable that implements a state machine required to open a cache entry.
// It executes in the parent for a cache access originating in the child.
// This runnable gets registered as an IPDL subprotocol actor so that it
// can communicate with the corresponding ChildRunnable.
class ParentRunnable final
  : public FileDescriptorHolder
  , public quota::OpenDirectoryListener
  , public PAsmJSCacheEntryParent
{
public:
  NS_DECL_ISUPPORTS_INHERITED
  NS_DECL_NSIRUNNABLE

  ParentRunnable(const PrincipalInfo& aPrincipalInfo,
                 OpenMode aOpenMode,
                 WriteParams aWriteParams)
  : mOwningThread(NS_GetCurrentThread()),
    mPrincipalInfo(aPrincipalInfo),
    mOpenMode(aOpenMode),
    mWriteParams(aWriteParams),
    mPersistence(quota::PERSISTENCE_TYPE_INVALID),
    mState(eInitial),
    mResult(JS::AsmJSCache_InternalError),
    mIsApp(false),
    mEnforcingQuota(true),
    mActorDestroyed(false),
    mOpened(false)
  {
    MOZ_ASSERT(XRE_IsParentProcess());
    AssertIsOnOwningThread();
    MOZ_COUNT_CTOR(ParentRunnable);
  }

private:
  ~ParentRunnable()
  {
    MOZ_ASSERT(mState == eFinished);
    MOZ_ASSERT(!mDirectoryLock);
    MOZ_ASSERT(mActorDestroyed);
    MOZ_COUNT_DTOR(ParentRunnable);
  }

  bool
  IsOnOwningThread() const
  {
    MOZ_ASSERT(mOwningThread);

    bool current;
    return NS_SUCCEEDED(mOwningThread->IsOnCurrentThread(&current)) && current;
  }

  void
  AssertIsOnOwningThread() const
  {
    MOZ_ASSERT(IsOnBackgroundThread());
    MOZ_ASSERT(IsOnOwningThread());
  }

  void
  AssertIsOnNonOwningThread() const
  {
    MOZ_ASSERT(!IsOnBackgroundThread());
    MOZ_ASSERT(!IsOnOwningThread());
  }

  // This method is called on the owning thread when no cache entry was found
  // to open. If we just tried a lookup in persistent storage then we might
  // still get a hit in temporary storage (for an asm.js module that wasn't
  // compiled at install-time).
  void
  CacheMiss()
  {
    AssertIsOnOwningThread();
    MOZ_ASSERT(mState == eFailedToReadMetadata ||
               mState == eWaitingToOpenCacheFileForRead);
    MOZ_ASSERT(mOpenMode == eOpenForRead);

    if (mPersistence == quota::PERSISTENCE_TYPE_TEMPORARY) {
      Fail();
      return;
    }

    // Try again with a clean slate. InitOnMainThread will see that mPersistence
    // is initialized and switch to temporary storage.
    MOZ_ASSERT(mPersistence == quota::PERSISTENCE_TYPE_PERSISTENT);
    FinishOnOwningThread();
    mState = eInitial;
    NS_DispatchToMainThread(this);
  }

  // This method is called on the owning thread when the JS engine is finished
  // reading/writing the cache entry.
  void
  Close()
  {
    AssertIsOnOwningThread();
    MOZ_ASSERT(mState == eOpened);

    mState = eFinished;

    MOZ_ASSERT(mOpened);

    FinishOnOwningThread();
  }

  // This method is called upon any failure that prevents the eventual opening
  // of the cache entry.
  void
  Fail()
  {
    AssertIsOnOwningThread();
    MOZ_ASSERT(mState != eFinished);

    mState = eFinished;

    MOZ_ASSERT(!mOpened);

    FinishOnOwningThread();

    if (!mActorDestroyed) {
      Unused << Send__delete__(this, mResult);
    }
  }

  // The same as method above but is intended to be called off the owning
  // thread.
  void
  FailOnNonOwningThread()
  {
    AssertIsOnNonOwningThread();
    MOZ_ASSERT(mState != eOpened &&
               mState != eFailing &&
               mState != eFinished);

    mState = eFailing;
    MOZ_ALWAYS_SUCCEEDS(mOwningThread->Dispatch(this, NS_DISPATCH_NORMAL));
  }

  void
  InitPersistenceType();

  nsresult
  InitOnMainThread();

  void
  OpenDirectory();

  nsresult
  ReadMetadata();

  nsresult
  OpenCacheFileForWrite();

  nsresult
  OpenCacheFileForRead();

  void
  FinishOnOwningThread();

  void
  DispatchToIOThread()
  {
    AssertIsOnOwningThread();

    // If shutdown just started, the QuotaManager may have been deleted.
    QuotaManager* qm = QuotaManager::Get();
    if (!qm) {
      FailOnNonOwningThread();
      return;
    }

    nsresult rv = qm->IOThread()->Dispatch(this, NS_DISPATCH_NORMAL);
    if (NS_FAILED(rv)) {
      FailOnNonOwningThread();
      return;
    }
  }

  // OpenDirectoryListener overrides.
  virtual void
  DirectoryLockAcquired(DirectoryLock* aLock) override;

  virtual void
  DirectoryLockFailed() override;

  // IPDL methods.
  bool
  Recv__delete__(const JS::AsmJSCacheResult& aResult) override
  {
    AssertIsOnOwningThread();
    MOZ_ASSERT(mState != eFinished);

    if (mOpened) {
      Close();
    } else {
      Fail();
    }

    MOZ_ASSERT(mState == eFinished);

    return true;
  }

  void
  ActorDestroy(ActorDestroyReason why) override
  {
    AssertIsOnOwningThread();
    MOZ_ASSERT(!mActorDestroyed);

    mActorDestroyed = true;

    // Assume ActorDestroy can happen at any time, so probe the current state to
    // determine what needs to happen.

    if (mState == eFinished) {
      return;
    }

    if (mOpened) {
      Close();
    } else {
      Fail();
    }

    MOZ_ASSERT(mState == eFinished);
  }

  bool
  RecvSelectCacheFileToRead(const uint32_t& aModuleIndex) override
  {
    AssertIsOnOwningThread();
    MOZ_ASSERT(mState == eWaitingToOpenCacheFileForRead);
    MOZ_ASSERT(mOpenMode == eOpenForRead);

    // A cache entry has been selected to open.

    mModuleIndex = aModuleIndex;
    mState = eReadyToOpenCacheFileForRead;
    DispatchToIOThread();

    return true;
  }

  bool
  RecvCacheMiss() override
  {
    AssertIsOnOwningThread();

    CacheMiss();

    return true;
  }

  nsCOMPtr<nsIEventTarget> mOwningThread;
  const PrincipalInfo mPrincipalInfo;
  const OpenMode mOpenMode;
  const WriteParams mWriteParams;

  // State initialized during eInitial:
  quota::PersistenceType mPersistence;
  nsCString mSuffix;
  nsCString mGroup;
  nsCString mOrigin;
  RefPtr<DirectoryLock> mDirectoryLock;

  // State initialized during eReadyToReadMetadata
  nsCOMPtr<nsIFile> mDirectory;
  nsCOMPtr<nsIFile> mMetadataFile;
  Metadata mMetadata;

  // State initialized during eWaitingToOpenCacheFileForRead
  unsigned mModuleIndex;

  enum State {
    eInitial, // Just created, waiting to be dispatched to main thread
    eWaitingToFinishInit, // Waiting to finish initialization
    eWaitingToOpenDirectory, // Waiting to open directory
    eWaitingToOpenMetadata, // Waiting to be called back from OpenDirectory
    eReadyToReadMetadata, // Waiting to read the metadata file on the IO thread
    eFailedToReadMetadata, // Waiting to be dispatched to owning thread after fail
    eSendingMetadataForRead, // Waiting to send OnOpenMetadataForRead
    eWaitingToOpenCacheFileForRead, // Waiting to hear back from child
    eReadyToOpenCacheFileForRead, // Waiting to open cache file for read
    eSendingCacheFile, // Waiting to send OnOpenCacheFile on the owning thread
    eOpened, // Finished calling OnOpenCacheFile, waiting to be closed
    eFailing, // Just failed, waiting to be dispatched to the owning thread
    eFinished, // Terminal state
  };
  State mState;
  JS::AsmJSCacheResult mResult;

  bool mIsApp;
  bool mEnforcingQuota;
  bool mActorDestroyed;
  bool mOpened;
};

void
ParentRunnable::InitPersistenceType()
{
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(mState == eInitial);

  if (mOpenMode == eOpenForWrite) {
    MOZ_ASSERT(mPersistence == quota::PERSISTENCE_TYPE_INVALID);

    // If we are performing install-time caching of an app, we'd like to store
    // the cache entry in persistent storage so the entry is never evicted,
    // but we need to check that quota is not enforced for the app.
    // That justifies us in skipping all quota checks when storing the cache
    // entry and avoids all the issues around the persistent quota prompt.
    // If quota is enforced for the app, then we can still cache in temporary
    // for a likely good first-run experience.

    MOZ_ASSERT_IF(mWriteParams.mInstalled, mIsApp);

    if (mWriteParams.mInstalled &&
        !QuotaManager::IsQuotaEnforced(quota::PERSISTENCE_TYPE_PERSISTENT,
                                       mOrigin, mIsApp)) {
      mPersistence = quota::PERSISTENCE_TYPE_PERSISTENT;
    } else {
      mPersistence = quota::PERSISTENCE_TYPE_TEMPORARY;
    }

    return;
  }

  // For the reasons described above, apps may have cache entries in both
  // persistent and temporary storage. At lookup time we don't know how and
  // where the given script was cached, so start the search in persistent
  // storage and, if that fails, search in temporary storage. (Non-apps can
  // only be stored in temporary storage.)

  MOZ_ASSERT_IF(mPersistence != quota::PERSISTENCE_TYPE_INVALID,
                mIsApp && mPersistence == quota::PERSISTENCE_TYPE_PERSISTENT);

  if (mPersistence == quota::PERSISTENCE_TYPE_INVALID && mIsApp) {
    mPersistence = quota::PERSISTENCE_TYPE_PERSISTENT;
  } else {
    mPersistence = quota::PERSISTENCE_TYPE_TEMPORARY;
  }
}

nsresult
ParentRunnable::InitOnMainThread()
{
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(mState == eInitial);
  MOZ_ASSERT(mPrincipalInfo.type() != PrincipalInfo::TNullPrincipalInfo);

  nsresult rv;
  nsCOMPtr<nsIPrincipal> principal =
    PrincipalInfoToPrincipal(mPrincipalInfo, &rv);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  rv = QuotaManager::GetInfoFromPrincipal(principal, &mSuffix, &mGroup,
                                          &mOrigin, &mIsApp);
  NS_ENSURE_SUCCESS(rv, rv);

  InitPersistenceType();

  mEnforcingQuota =
    QuotaManager::IsQuotaEnforced(mPersistence, mOrigin, mIsApp);

  return NS_OK;
}

void
ParentRunnable::OpenDirectory()
{
  AssertIsOnOwningThread();
  MOZ_ASSERT(mState == eWaitingToFinishInit ||
             mState == eWaitingToOpenDirectory);
  MOZ_ASSERT(QuotaManager::Get());

  mState = eWaitingToOpenMetadata;

  // XXX The exclusive lock shouldn't be needed for read operations.
  QuotaManager::Get()->OpenDirectory(mPersistence,
                                     mGroup,
                                     mOrigin,
                                     mIsApp,
                                     quota::Client::ASMJS,
                                     /* aExclusive */ true,
                                     this);
}

nsresult
ParentRunnable::ReadMetadata()
{
  AssertIsOnIOThread();
  MOZ_ASSERT(mState == eReadyToReadMetadata);

  QuotaManager* qm = QuotaManager::Get();
  MOZ_ASSERT(qm, "We are on the QuotaManager's IO thread");

  nsresult rv =
    qm->EnsureOriginIsInitialized(mPersistence, mSuffix, mGroup, mOrigin,
                                  mIsApp, getter_AddRefs(mDirectory));
  if (NS_WARN_IF(NS_FAILED(rv))) {
    mResult = JS::AsmJSCache_StorageInitFailure;
    return rv;
  }

  rv = mDirectory->Append(NS_LITERAL_STRING(ASMJSCACHE_DIRECTORY_NAME));
  NS_ENSURE_SUCCESS(rv, rv);

  bool exists;
  rv = mDirectory->Exists(&exists);
  NS_ENSURE_SUCCESS(rv, rv);

  if (!exists) {
    rv = mDirectory->Create(nsIFile::DIRECTORY_TYPE, 0755);
    NS_ENSURE_SUCCESS(rv, rv);
  } else {
    DebugOnly<bool> isDirectory;
    MOZ_ASSERT(NS_SUCCEEDED(mDirectory->IsDirectory(&isDirectory)));
    MOZ_ASSERT(isDirectory, "Should have caught this earlier!");
  }

  rv = mDirectory->Clone(getter_AddRefs(mMetadataFile));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = mMetadataFile->Append(NS_LITERAL_STRING(ASMJSCACHE_METADATA_FILE_NAME));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = mMetadataFile->Exists(&exists);
  NS_ENSURE_SUCCESS(rv, rv);

  if (exists && NS_FAILED(ReadMetadataFile(mMetadataFile, mMetadata))) {
    exists = false;
  }

  if (!exists) {
    // If we are reading, we can't possibly have a cache hit.
    if (mOpenMode == eOpenForRead) {
      return NS_ERROR_FILE_NOT_FOUND;
    }

    // Initialize Metadata with a valid empty state for the LRU cache.
    for (unsigned i = 0; i < Metadata::kNumEntries; i++) {
      Metadata::Entry& entry = mMetadata.mEntries[i];
      entry.mModuleIndex = i;
      entry.clear();
    }
  }

  return NS_OK;
}

nsresult
ParentRunnable::OpenCacheFileForWrite()
{
  AssertIsOnIOThread();
  MOZ_ASSERT(mState == eReadyToReadMetadata);
  MOZ_ASSERT(mOpenMode == eOpenForWrite);

  mFileSize = mWriteParams.mSize;

  // Kick out the oldest entry in the LRU queue in the metadata.
  mModuleIndex = mMetadata.mEntries[Metadata::kLastEntry].mModuleIndex;

  nsCOMPtr<nsIFile> file;
  nsresult rv = GetCacheFile(mDirectory, mModuleIndex, getter_AddRefs(file));
  NS_ENSURE_SUCCESS(rv, rv);

  QuotaManager* qm = QuotaManager::Get();
  MOZ_ASSERT(qm, "We are on the QuotaManager's IO thread");

  if (mEnforcingQuota) {
    // Create the QuotaObject before all file IO and keep it alive until caching
    // completes to get maximum assertion coverage in QuotaManager against
    // concurrent removal, etc.
    mQuotaObject = qm->GetQuotaObject(mPersistence, mGroup, mOrigin, file);
    NS_ENSURE_STATE(mQuotaObject);

    if (!mQuotaObject->MaybeUpdateSize(mWriteParams.mSize,
                                       /* aTruncate */ false)) {
      // If the request fails, it might be because mOrigin is using too much
      // space (MaybeUpdateSize will not evict our own origin since it is
      // active). Try to make some space by evicting LRU entries until there is
      // enough space.
      EvictEntries(mDirectory, mGroup, mOrigin, mWriteParams.mSize, mMetadata);
      if (!mQuotaObject->MaybeUpdateSize(mWriteParams.mSize,
                                         /* aTruncate */ false)) {
        mResult = JS::AsmJSCache_QuotaExceeded;
        return NS_ERROR_FAILURE;
      }
    }
  }

  int32_t openFlags = PR_RDWR | PR_TRUNCATE | PR_CREATE_FILE;
  rv = file->OpenNSPRFileDesc(openFlags, 0644, &mFileDesc);
  NS_ENSURE_SUCCESS(rv, rv);

  // Move the mModuleIndex's LRU entry to the recent end of the queue.
  PodMove(mMetadata.mEntries + 1, mMetadata.mEntries, Metadata::kLastEntry);
  Metadata::Entry& entry = mMetadata.mEntries[0];
  entry.mFastHash = mWriteParams.mFastHash;
  entry.mNumChars = mWriteParams.mNumChars;
  entry.mFullHash = mWriteParams.mFullHash;
  entry.mModuleIndex = mModuleIndex;

  rv = WriteMetadataFile(mMetadataFile, mMetadata);
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}

nsresult
ParentRunnable::OpenCacheFileForRead()
{
  AssertIsOnIOThread();
  MOZ_ASSERT(mState == eReadyToOpenCacheFileForRead);
  MOZ_ASSERT(mOpenMode == eOpenForRead);

  nsCOMPtr<nsIFile> file;
  nsresult rv = GetCacheFile(mDirectory, mModuleIndex, getter_AddRefs(file));
  NS_ENSURE_SUCCESS(rv, rv);

  QuotaManager* qm = QuotaManager::Get();
  MOZ_ASSERT(qm, "We are on the QuotaManager's IO thread");

  if (mEnforcingQuota) {
    // Even though it's not strictly necessary, create the QuotaObject before
    // all file IO and keep it alive until caching completes to get maximum
    // assertion coverage in QuotaManager against concurrent removal, etc.
    mQuotaObject = qm->GetQuotaObject(mPersistence, mGroup, mOrigin, file);
    NS_ENSURE_STATE(mQuotaObject);
  }

  rv = file->GetFileSize(&mFileSize);
  NS_ENSURE_SUCCESS(rv, rv);

  int32_t openFlags = PR_RDONLY | nsIFile::OS_READAHEAD;
  rv = file->OpenNSPRFileDesc(openFlags, 0644, &mFileDesc);
  NS_ENSURE_SUCCESS(rv, rv);

  // Move the mModuleIndex's LRU entry to the recent end of the queue.
  unsigned lruIndex = 0;
  while (mMetadata.mEntries[lruIndex].mModuleIndex != mModuleIndex) {
    if (++lruIndex == Metadata::kNumEntries) {
      return NS_ERROR_UNEXPECTED;
    }
  }
  Metadata::Entry entry = mMetadata.mEntries[lruIndex];
  PodMove(mMetadata.mEntries + 1, mMetadata.mEntries, lruIndex);
  mMetadata.mEntries[0] = entry;

  rv = WriteMetadataFile(mMetadataFile, mMetadata);
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}

void
ParentRunnable::FinishOnOwningThread()
{
  AssertIsOnOwningThread();

  // Per FileDescriptorHolder::Finish()'s comment, call before
  // releasing the directory lock.
  FileDescriptorHolder::Finish();

  mDirectoryLock = nullptr;
}

NS_IMETHODIMP
ParentRunnable::Run()
{
  nsresult rv;

  // All success/failure paths must eventually call Finish() to avoid leaving
  // the parser hanging.
  switch (mState) {
    case eInitial: {
      MOZ_ASSERT(NS_IsMainThread());

      rv = InitOnMainThread();
      if (NS_FAILED(rv)) {
        FailOnNonOwningThread();
        return NS_OK;
      }

      mState = eWaitingToFinishInit;
      MOZ_ALWAYS_SUCCEEDS(mOwningThread->Dispatch(this, NS_DISPATCH_NORMAL));

      return NS_OK;
    }

    case eWaitingToFinishInit: {
      AssertIsOnOwningThread();

      if (QuotaManager::IsShuttingDown()) {
        Fail();
        return NS_OK;
      }

      if (QuotaManager::Get()) {
        OpenDirectory();
        return NS_OK;
      }

      mState = eWaitingToOpenDirectory;
      QuotaManager::GetOrCreate(this);

      return NS_OK;
    }

    case eWaitingToOpenDirectory: {
      AssertIsOnOwningThread();

      if (NS_WARN_IF(!QuotaManager::Get())) {
        Fail();
        return NS_OK;
      }

      OpenDirectory();
      return NS_OK;
    }

    case eReadyToReadMetadata: {
      AssertIsOnIOThread();

      rv = ReadMetadata();
      if (NS_FAILED(rv)) {
        mState = eFailedToReadMetadata;
        MOZ_ALWAYS_SUCCEEDS(mOwningThread->Dispatch(this, NS_DISPATCH_NORMAL));
        return NS_OK;
      }

      if (mOpenMode == eOpenForRead) {
        mState = eSendingMetadataForRead;
        MOZ_ALWAYS_SUCCEEDS(mOwningThread->Dispatch(this, NS_DISPATCH_NORMAL));

        return NS_OK;
      }

      rv = OpenCacheFileForWrite();
      if (NS_FAILED(rv)) {
        FailOnNonOwningThread();
        return NS_OK;
      }

      mState = eSendingCacheFile;
      MOZ_ALWAYS_SUCCEEDS(mOwningThread->Dispatch(this, NS_DISPATCH_NORMAL));
      return NS_OK;
    }

    case eFailedToReadMetadata: {
      AssertIsOnOwningThread();

      if (mOpenMode == eOpenForRead) {
        CacheMiss();
        return NS_OK;
      }

      Fail();
      return NS_OK;
    }

    case eSendingMetadataForRead: {
      AssertIsOnOwningThread();
      MOZ_ASSERT(mOpenMode == eOpenForRead);

      mState = eWaitingToOpenCacheFileForRead;

      // Metadata is now open.
      if (!SendOnOpenMetadataForRead(mMetadata)) {
        Fail();
        return NS_OK;
      }

      return NS_OK;
    }

    case eReadyToOpenCacheFileForRead: {
      AssertIsOnIOThread();
      MOZ_ASSERT(mOpenMode == eOpenForRead);

      rv = OpenCacheFileForRead();
      if (NS_FAILED(rv)) {
        FailOnNonOwningThread();
        return NS_OK;
      }

      mState = eSendingCacheFile;
      MOZ_ALWAYS_SUCCEEDS(mOwningThread->Dispatch(this, NS_DISPATCH_NORMAL));
      return NS_OK;
    }

    case eSendingCacheFile: {
      AssertIsOnOwningThread();

      mState = eOpened;

      // The entry is now open.
      MOZ_ASSERT(!mOpened);
      mOpened = true;

      FileDescriptor::PlatformHandleType handle =
        FileDescriptor::PlatformHandleType(PR_FileDesc2NativeHandle(mFileDesc));
      if (!SendOnOpenCacheFile(mFileSize, FileDescriptor(handle))) {
        Fail();
        return NS_OK;
      }

      return NS_OK;
    }

    case eFailing: {
      AssertIsOnOwningThread();

      Fail();

      return NS_OK;
    }

    case eWaitingToOpenMetadata:
    case eWaitingToOpenCacheFileForRead:
    case eOpened:
    case eFinished: {
      MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Shouldn't Run() in this state");
    }
  }

  MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Corrupt state");
  return NS_OK;
}

void
ParentRunnable::DirectoryLockAcquired(DirectoryLock* aLock)
{
  AssertIsOnOwningThread();
  MOZ_ASSERT(mState == eWaitingToOpenMetadata);
  MOZ_ASSERT(!mDirectoryLock);

  mDirectoryLock = aLock;

  mState = eReadyToReadMetadata;
  DispatchToIOThread();
}

void
ParentRunnable::DirectoryLockFailed()
{
  AssertIsOnOwningThread();
  MOZ_ASSERT(mState == eWaitingToOpenMetadata);
  MOZ_ASSERT(!mDirectoryLock);

  Fail();
}

NS_IMPL_ISUPPORTS_INHERITED0(ParentRunnable, FileDescriptorHolder)

bool
FindHashMatch(const Metadata& aMetadata, const ReadParams& aReadParams,
              unsigned* aModuleIndex)
{
  // Perform a fast hash of the first sNumFastHashChars chars. Each cache entry
  // also stores an mFastHash of its first sNumFastHashChars so this gives us a
  // fast way to probabilistically determine whether we have a cache hit. We
  // still do a full hash of all the chars before returning the cache file to
  // the engine to avoid penalizing the case where there are multiple cached
  // asm.js modules where the first sNumFastHashChars are the same. The
  // mFullHash of each cache entry can have a different mNumChars so the fast
  // hash allows us to avoid performing up to Metadata::kNumEntries separate
  // full hashes.
  uint32_t numChars = aReadParams.mLimit - aReadParams.mBegin;
  MOZ_ASSERT(numChars > sNumFastHashChars);
  uint32_t fastHash = HashString(aReadParams.mBegin, sNumFastHashChars);

  for (unsigned i = 0; i < Metadata::kNumEntries ; i++) {
    // Compare the "fast hash" first to see whether it is worthwhile to
    // hash all the chars.
    Metadata::Entry entry = aMetadata.mEntries[i];
    if (entry.mFastHash != fastHash) {
      continue;
    }

    // Assuming we have enough characters, hash all the chars it would take
    // to match this cache entry and compare to the cache entry. If we get a
    // hit we'll still do a full source match later (in the JS engine), but
    // the full hash match means this is probably the cache entry we want.
    if (numChars < entry.mNumChars) {
      continue;
    }
    uint32_t fullHash = HashString(aReadParams.mBegin, entry.mNumChars);
    if (entry.mFullHash != fullHash) {
      continue;
    }

    *aModuleIndex = entry.mModuleIndex;
    return true;
  }

  return false;
}

} // unnamed namespace

PAsmJSCacheEntryParent*
AllocEntryParent(OpenMode aOpenMode,
                 WriteParams aWriteParams,
                 const PrincipalInfo& aPrincipalInfo)
{
  AssertIsOnBackgroundThread();

  if (NS_WARN_IF(aPrincipalInfo.type() == PrincipalInfo::TNullPrincipalInfo)) {
    MOZ_ASSERT(false);
    return nullptr;
  }

  RefPtr<ParentRunnable> runnable =
    new ParentRunnable(aPrincipalInfo, aOpenMode, aWriteParams);

  nsresult rv = NS_DispatchToMainThread(runnable);
  NS_ENSURE_SUCCESS(rv, nullptr);

  // Transfer ownership to IPDL.
  return runnable.forget().take();
}

void
DeallocEntryParent(PAsmJSCacheEntryParent* aActor)
{
  // Transfer ownership back from IPDL.
  RefPtr<ParentRunnable> op =
    dont_AddRef(static_cast<ParentRunnable*>(aActor));
}

namespace {

// A runnable that presents a single interface to the AsmJSCache ops which need
// to wait until the file is open.
class ChildRunnable final
  : public FileDescriptorHolder
  , public PAsmJSCacheEntryChild
  , public nsIIPCBackgroundChildCreateCallback
{
  typedef mozilla::ipc::PBackgroundChild PBackgroundChild;

public:
  class AutoClose
  {
    ChildRunnable* mChildRunnable;

  public:
    explicit AutoClose(ChildRunnable* aChildRunnable = nullptr)
    : mChildRunnable(aChildRunnable)
    { }

    void
    Init(ChildRunnable* aChildRunnable)
    {
      MOZ_ASSERT(!mChildRunnable);
      mChildRunnable = aChildRunnable;
    }

    ChildRunnable*
    operator->() const MOZ_NO_ADDREF_RELEASE_ON_RETURN
    {
      MOZ_ASSERT(mChildRunnable);
      return mChildRunnable;
    }

    void
    Forget(ChildRunnable** aChildRunnable)
    {
      *aChildRunnable = mChildRunnable;
      mChildRunnable = nullptr;
    }

    ~AutoClose()
    {
      if (mChildRunnable) {
        mChildRunnable->Close();
      }
    }
  };

  NS_DECL_ISUPPORTS_INHERITED
  NS_DECL_NSIRUNNABLE
  NS_DECL_NSIIPCBACKGROUNDCHILDCREATECALLBACK

  ChildRunnable(nsIPrincipal* aPrincipal,
                OpenMode aOpenMode,
                WriteParams aWriteParams,
                ReadParams aReadParams)
  : mPrincipal(aPrincipal),
    mWriteParams(aWriteParams),
    mReadParams(aReadParams),
    mMutex("ChildRunnable::mMutex"),
    mCondVar(mMutex, "ChildRunnable::mCondVar"),
    mOpenMode(aOpenMode),
    mState(eInitial),
    mResult(JS::AsmJSCache_InternalError),
    mActorDestroyed(false),
    mWaiting(false),
    mOpened(false)
  {
    MOZ_ASSERT(!NS_IsMainThread());
    MOZ_COUNT_CTOR(ChildRunnable);
  }

  JS::AsmJSCacheResult
  BlockUntilOpen(AutoClose* aCloser)
  {
    MOZ_ASSERT(!mWaiting, "Can only call BlockUntilOpen once");
    MOZ_ASSERT(!mOpened, "Can only call BlockUntilOpen once");

    mWaiting = true;

    nsresult rv = NS_DispatchToMainThread(this);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return JS::AsmJSCache_InternalError;
    }

    {
      MutexAutoLock lock(mMutex);
      while (mWaiting) {
        mCondVar.Wait();
      }
    }

    if (!mOpened) {
      return mResult;
    }

    // Now that we're open, we're guaranteed a Close() call. However, we are
    // not guaranteed someone is holding an outstanding reference until the File
    // is closed, so we do that ourselves and Release() in OnClose().
    aCloser->Init(this);
    AddRef();
    return JS::AsmJSCache_Success;
  }

  void Cleanup()
  {
#ifdef DEBUG
    NoteActorDestroyed();
#endif
  }

private:
  ~ChildRunnable()
  {
    MOZ_ASSERT(!mWaiting, "Shouldn't be destroyed while thread is waiting");
    MOZ_ASSERT(!mOpened);
    MOZ_ASSERT(mState == eFinished);
    MOZ_ASSERT(mActorDestroyed);
    MOZ_COUNT_DTOR(ChildRunnable);
  }

  // IPDL methods.
  bool
  RecvOnOpenMetadataForRead(const Metadata& aMetadata) override
  {
    MOZ_ASSERT(NS_IsMainThread());
    MOZ_ASSERT(mState == eOpening);

    uint32_t moduleIndex;
    if (FindHashMatch(aMetadata, mReadParams, &moduleIndex)) {
      return SendSelectCacheFileToRead(moduleIndex);
    }

    return SendCacheMiss();
  }

  bool
  RecvOnOpenCacheFile(const int64_t& aFileSize,
                      const FileDescriptor& aFileDesc) override
  {
    MOZ_ASSERT(NS_IsMainThread());
    MOZ_ASSERT(mState == eOpening);

    mFileSize = aFileSize;

    auto rawFD = aFileDesc.ClonePlatformHandle();
    mFileDesc = PR_ImportFile(PROsfd(rawFD.release()));
    if (!mFileDesc) {
      return false;
    }

    mState = eOpened;
    Notify(JS::AsmJSCache_Success);
    return true;
  }

  bool
  Recv__delete__(const JS::AsmJSCacheResult& aResult) override
  {
    MOZ_ASSERT(NS_IsMainThread());
    MOZ_ASSERT(mState == eOpening);

    Fail(aResult);
    return true;
  }

  void
  ActorDestroy(ActorDestroyReason why) override
  {
    MOZ_ASSERT(NS_IsMainThread());
    NoteActorDestroyed();
  }

  void
  Close()
  {
    MOZ_ASSERT(mState == eOpened);

    mState = eClosing;
    NS_DispatchToMainThread(this);
  }

  void
  Fail(JS::AsmJSCacheResult aResult)
  {
    MOZ_ASSERT(NS_IsMainThread());
    MOZ_ASSERT(mState == eInitial || mState == eOpening);
    MOZ_ASSERT(aResult != JS::AsmJSCache_Success);

    mState = eFinished;

    FileDescriptorHolder::Finish();
    Notify(aResult);
  }

  void
  Notify(JS::AsmJSCacheResult aResult)
  {
    MOZ_ASSERT(NS_IsMainThread());

    MutexAutoLock lock(mMutex);
    MOZ_ASSERT(mWaiting);

    mWaiting = false;
    mOpened = aResult == JS::AsmJSCache_Success;
    mResult = aResult;
    mCondVar.Notify();
  }

  void NoteActorDestroyed()
  {
    mActorDestroyed = true;
  }

  nsIPrincipal* const mPrincipal;
  nsAutoPtr<PrincipalInfo> mPrincipalInfo;
  WriteParams mWriteParams;
  ReadParams mReadParams;
  Mutex mMutex;
  CondVar mCondVar;

  // Couple enums and bools together
  const OpenMode mOpenMode;
  enum State {
    eInitial, // Just created, waiting to be dispatched to the main thread
    eBackgroundChildPending, // Waiting for the background child to be created
    eOpening, // Waiting for the parent process to respond
    eOpened, // Parent process opened the entry and sent it back
    eClosing, // Waiting to be dispatched to the main thread to Send__delete__
    eFinished // Terminal state
  };
  State mState;
  JS::AsmJSCacheResult mResult;

  bool mActorDestroyed;
  bool mWaiting;
  bool mOpened;
};

NS_IMETHODIMP
ChildRunnable::Run()
{
  switch (mState) {
    case eInitial: {
      MOZ_ASSERT(NS_IsMainThread());

      if (mPrincipal->GetIsNullPrincipal()) {
        NS_WARNING("AsmsJSCache not supported on null principal.");
        Fail(JS::AsmJSCache_InternalError);
        return NS_OK;
      }

      nsAutoPtr<PrincipalInfo> principalInfo(new PrincipalInfo());
      nsresult rv = PrincipalToPrincipalInfo(mPrincipal, principalInfo);
      if (NS_WARN_IF(NS_FAILED(rv))) {
        Fail(JS::AsmJSCache_InternalError);
        return NS_OK;
      }

      mPrincipalInfo = Move(principalInfo);

      PBackgroundChild* actor = BackgroundChild::GetForCurrentThread();
      if (actor) {
        ActorCreated(actor);
        return NS_OK;
      }

      if (NS_WARN_IF(!BackgroundChild::GetOrCreateForCurrentThread(this))) {
        Fail(JS::AsmJSCache_InternalError);
        return NS_OK;
      }

      mState = eBackgroundChildPending;
      return NS_OK;
    }

    case eClosing: {
      MOZ_ASSERT(NS_IsMainThread());

      // Per FileDescriptorHolder::Finish()'s comment, call before
      // releasing the directory lock (which happens in the parent upon receipt
      // of the Send__delete__ message).
      FileDescriptorHolder::Finish();

      MOZ_ASSERT(mOpened);
      mOpened = false;

      // Match the AddRef in BlockUntilOpen(). The main thread event loop still
      // holds an outstanding ref which will keep 'this' alive until returning to
      // the event loop.
      Release();

      if (!mActorDestroyed) {
        Unused << Send__delete__(this, JS::AsmJSCache_Success);
      }

      mState = eFinished;
      return NS_OK;
    }

    case eBackgroundChildPending:
    case eOpening:
    case eOpened:
    case eFinished: {
      MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Shouldn't Run() in this state");
    }
  }

  MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Corrupt state");
  return NS_OK;
}

void
ChildRunnable::ActorCreated(PBackgroundChild* aActor)
{
  MOZ_ASSERT(NS_IsMainThread());

  if (!aActor->SendPAsmJSCacheEntryConstructor(this, mOpenMode, mWriteParams,
                                               *mPrincipalInfo)) {
    // Unblock the parsing thread with a failure.

    Fail(JS::AsmJSCache_InternalError);

    return;
  }

  // AddRef to keep this runnable alive until IPDL deallocates the
  // subprotocol (DeallocEntryChild).
  AddRef();

  mState = eOpening;
}

void
ChildRunnable::ActorFailed()
{
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(mState == eBackgroundChildPending);

  Fail(JS::AsmJSCache_InternalError);
}

NS_IMPL_ISUPPORTS_INHERITED(ChildRunnable,
                            FileDescriptorHolder,
                            nsIIPCBackgroundChildCreateCallback)

} // unnamed namespace

void
DeallocEntryChild(PAsmJSCacheEntryChild* aActor)
{
  // Match the AddRef before SendPAsmJSCacheEntryConstructor.
  static_cast<ChildRunnable*>(aActor)->Release();
}

namespace {

JS::AsmJSCacheResult
OpenFile(nsIPrincipal* aPrincipal,
         OpenMode aOpenMode,
         WriteParams aWriteParams,
         ReadParams aReadParams,
         ChildRunnable::AutoClose* aChildRunnable)
{
  MOZ_ASSERT_IF(aOpenMode == eOpenForRead, aWriteParams.mSize == 0);
  MOZ_ASSERT_IF(aOpenMode == eOpenForWrite, aReadParams.mBegin == nullptr);

  // There are three reasons we don't attempt caching from the main thread:
  //  1. In the parent process: QuotaManager::WaitForOpenAllowed prevents
  //     synchronous waiting on the main thread requiring a runnable to be
  //     dispatched to the main thread.
  //  2. In the child process: the IPDL PContent messages we need to
  //     synchronously wait on are dispatched to the main thread.
  //  3. While a cache lookup *should* be much faster than compilation, IO
  //     operations can be unpredictably slow and we'd like to avoid the
  //     occasional janks on the main thread.
  // We could use a nested event loop to address 1 and 2, but we're potentially
  // in the middle of running JS (eval()) and nested event loops can be
  // semantically observable.
  if (NS_IsMainThread()) {
    return JS::AsmJSCache_SynchronousScript;
  }

  // Check to see whether the principal reflects a private browsing session.
  // Since AsmJSCache requires disk access at the moment, caching should be
  // disabled in private browsing situations. Failing here will cause later
  // read/write requests to also fail.
  uint32_t pbId;
  if (NS_WARN_IF(NS_FAILED(aPrincipal->GetPrivateBrowsingId(&pbId)))) {
    return JS::AsmJSCache_InternalError;
  }

  if (pbId > 0) {
    return JS::AsmJSCache_Disabled_PrivateBrowsing;
  }

  // We need to synchronously call into the parent to open the file and
  // interact with the QuotaManager. The child can then map the file into its
  // address space to perform I/O.
  RefPtr<ChildRunnable> childRunnable =
    new ChildRunnable(aPrincipal, aOpenMode, aWriteParams, aReadParams);

  JS::AsmJSCacheResult openResult =
    childRunnable->BlockUntilOpen(aChildRunnable);
  if (openResult != JS::AsmJSCache_Success) {
    childRunnable->Cleanup();
    return openResult;
  }

  if (!childRunnable->MapMemory(aOpenMode)) {
    return JS::AsmJSCache_InternalError;
  }

  return JS::AsmJSCache_Success;
}

} // namespace

typedef uint32_t AsmJSCookieType;
static const uint32_t sAsmJSCookie = 0x600d600d;

bool
OpenEntryForRead(nsIPrincipal* aPrincipal,
                 const char16_t* aBegin,
                 const char16_t* aLimit,
                 size_t* aSize,
                 const uint8_t** aMemory,
                 intptr_t* aHandle)
{
  if (size_t(aLimit - aBegin) < sMinCachedModuleLength) {
    return false;
  }

  ReadParams readParams;
  readParams.mBegin = aBegin;
  readParams.mLimit = aLimit;

  ChildRunnable::AutoClose childRunnable;
  WriteParams notAWrite;
  JS::AsmJSCacheResult openResult =
    OpenFile(aPrincipal, eOpenForRead, notAWrite, readParams, &childRunnable);
  if (openResult != JS::AsmJSCache_Success) {
    return false;
  }

  // Although we trust that the stored cache files have not been arbitrarily
  // corrupted, it is possible that a previous execution aborted in the middle
  // of writing a cache file (crash, OOM-killer, etc). To protect against
  // partially-written cache files, we use the following scheme:
  //  - Allocate an extra word at the beginning of every cache file which
  //    starts out 0 (OpenFile opens with PR_TRUNCATE).
  //  - After the asm.js serialization is complete, PR_SyncMemMap to write
  //    everything to disk and then store a non-zero value (sAsmJSCookie)
  //    in the first word.
  //  - When attempting to read a cache file, check whether the first word is
  //    sAsmJSCookie.
  if (childRunnable->FileSize() < sizeof(AsmJSCookieType) ||
      *(AsmJSCookieType*)childRunnable->MappedMemory() != sAsmJSCookie) {
    return false;
  }

  *aSize = childRunnable->FileSize() - sizeof(AsmJSCookieType);
  *aMemory = (uint8_t*) childRunnable->MappedMemory() + sizeof(AsmJSCookieType);

  // The caller guarnatees a call to CloseEntryForRead (on success or
  // failure) at which point the file will be closed.
  childRunnable.Forget(reinterpret_cast<ChildRunnable**>(aHandle));
  return true;
}

void
CloseEntryForRead(size_t aSize,
                  const uint8_t* aMemory,
                  intptr_t aHandle)
{
  ChildRunnable::AutoClose childRunnable(
    reinterpret_cast<ChildRunnable*>(aHandle));

  MOZ_ASSERT(aSize + sizeof(AsmJSCookieType) == childRunnable->FileSize());
  MOZ_ASSERT(aMemory - sizeof(AsmJSCookieType) ==
               childRunnable->MappedMemory());
}

JS::AsmJSCacheResult
OpenEntryForWrite(nsIPrincipal* aPrincipal,
                  bool aInstalled,
                  const char16_t* aBegin,
                  const char16_t* aEnd,
                  size_t aSize,
                  uint8_t** aMemory,
                  intptr_t* aHandle)
{
  if (size_t(aEnd - aBegin) < sMinCachedModuleLength) {
    return JS::AsmJSCache_ModuleTooSmall;
  }

  // Add extra space for the AsmJSCookieType (see OpenEntryForRead).
  aSize += sizeof(AsmJSCookieType);

  static_assert(sNumFastHashChars < sMinCachedModuleLength, "HashString safe");

  WriteParams writeParams;
  writeParams.mInstalled = aInstalled;
  writeParams.mSize = aSize;
  writeParams.mFastHash = HashString(aBegin, sNumFastHashChars);
  writeParams.mNumChars = aEnd - aBegin;
  writeParams.mFullHash = HashString(aBegin, writeParams.mNumChars);

  ChildRunnable::AutoClose childRunnable;
  ReadParams notARead;
  JS::AsmJSCacheResult openResult =
    OpenFile(aPrincipal, eOpenForWrite, writeParams, notARead, &childRunnable);
  if (openResult != JS::AsmJSCache_Success) {
    return openResult;
  }

  // Strip off the AsmJSCookieType from the buffer returned to the caller,
  // which expects a buffer of aSize, not a buffer of sizeWithCookie starting
  // with a cookie.
  *aMemory = (uint8_t*) childRunnable->MappedMemory() + sizeof(AsmJSCookieType);

  // The caller guarnatees a call to CloseEntryForWrite (on success or
  // failure) at which point the file will be closed
  childRunnable.Forget(reinterpret_cast<ChildRunnable**>(aHandle));
  return JS::AsmJSCache_Success;
}

void
CloseEntryForWrite(size_t aSize,
                   uint8_t* aMemory,
                   intptr_t aHandle)
{
  ChildRunnable::AutoClose childRunnable(
    reinterpret_cast<ChildRunnable*>(aHandle));

  MOZ_ASSERT(aSize + sizeof(AsmJSCookieType) == childRunnable->FileSize());
  MOZ_ASSERT(aMemory - sizeof(AsmJSCookieType) ==
               childRunnable->MappedMemory());

  // Flush to disk before writing the cookie (see OpenEntryForRead).
  if (PR_SyncMemMap(childRunnable->FileDesc(),
                    childRunnable->MappedMemory(),
                    childRunnable->FileSize()) == PR_SUCCESS) {
    *(AsmJSCookieType*)childRunnable->MappedMemory() = sAsmJSCookie;
  }
}

class Client : public quota::Client
{
  ~Client() {}

public:
  NS_IMETHOD_(MozExternalRefCountType)
  AddRef() override;

  NS_IMETHOD_(MozExternalRefCountType)
  Release() override;

  virtual Type
  GetType() override
  {
    return ASMJS;
  }

  virtual nsresult
  InitOrigin(PersistenceType aPersistenceType,
             const nsACString& aGroup,
             const nsACString& aOrigin,
             const AtomicBool& aCanceled,
             UsageInfo* aUsageInfo) override
  {
    if (!aUsageInfo) {
      return NS_OK;
    }
    return GetUsageForOrigin(aPersistenceType,
                             aGroup,
                             aOrigin,
                             aCanceled,
                             aUsageInfo);
  }

  virtual nsresult
  GetUsageForOrigin(PersistenceType aPersistenceType,
                    const nsACString& aGroup,
                    const nsACString& aOrigin,
                    const AtomicBool& aCanceled,
                    UsageInfo* aUsageInfo) override
  {
    QuotaManager* qm = QuotaManager::Get();
    MOZ_ASSERT(qm, "We were being called by the QuotaManager");

    nsCOMPtr<nsIFile> directory;
    nsresult rv = qm->GetDirectoryForOrigin(aPersistenceType, aOrigin,
                                            getter_AddRefs(directory));
    NS_ENSURE_SUCCESS(rv, rv);
    MOZ_ASSERT(directory, "We're here because the origin directory exists");

    rv = directory->Append(NS_LITERAL_STRING(ASMJSCACHE_DIRECTORY_NAME));
    NS_ENSURE_SUCCESS(rv, rv);

    DebugOnly<bool> exists;
    MOZ_ASSERT(NS_SUCCEEDED(directory->Exists(&exists)) && exists);

    nsCOMPtr<nsISimpleEnumerator> entries;
    rv = directory->GetDirectoryEntries(getter_AddRefs(entries));
    NS_ENSURE_SUCCESS(rv, rv);

    bool hasMore;
    while (NS_SUCCEEDED((rv = entries->HasMoreElements(&hasMore))) &&
           hasMore && !aCanceled) {
      nsCOMPtr<nsISupports> entry;
      rv = entries->GetNext(getter_AddRefs(entry));
      NS_ENSURE_SUCCESS(rv, rv);

      nsCOMPtr<nsIFile> file = do_QueryInterface(entry);
      NS_ENSURE_TRUE(file, NS_NOINTERFACE);

      int64_t fileSize;
      rv = file->GetFileSize(&fileSize);
      NS_ENSURE_SUCCESS(rv, rv);

      MOZ_ASSERT(fileSize >= 0, "Negative size?!");

      // Since the client is not explicitly storing files, append to database
      // usage which represents implicit storage allocation.
      aUsageInfo->AppendToDatabaseUsage(uint64_t(fileSize));
    }
    NS_ENSURE_SUCCESS(rv, rv);

    return NS_OK;
  }

  virtual void
  OnOriginClearCompleted(PersistenceType aPersistenceType,
                         const nsACString& aOrigin)
                         override
  { }

  virtual void
  ReleaseIOThreadObjects() override
  { }

  virtual void
  AbortOperations(const nsACString& aOrigin) override
  { }

  virtual void
  AbortOperationsForProcess(ContentParentId aContentParentId) override
  { }

  virtual void
  StartIdleMaintenance() override
  { }

  virtual void
  StopIdleMaintenance() override
  { }

  virtual void
  ShutdownWorkThreads() override
  { }

private:
  nsAutoRefCnt mRefCnt;
  NS_DECL_OWNINGTHREAD
};

NS_IMPL_ADDREF(asmjscache::Client)
NS_IMPL_RELEASE(asmjscache::Client)

quota::Client*
CreateClient()
{
  return new Client();
}

} // namespace asmjscache
} // namespace dom
} // namespace mozilla

namespace IPC {

using mozilla::dom::asmjscache::Metadata;
using mozilla::dom::asmjscache::WriteParams;

void
ParamTraits<Metadata>::Write(Message* aMsg, const paramType& aParam)
{
  for (unsigned i = 0; i < Metadata::kNumEntries; i++) {
    const Metadata::Entry& entry = aParam.mEntries[i];
    WriteParam(aMsg, entry.mFastHash);
    WriteParam(aMsg, entry.mNumChars);
    WriteParam(aMsg, entry.mFullHash);
    WriteParam(aMsg, entry.mModuleIndex);
  }
}

bool
ParamTraits<Metadata>::Read(const Message* aMsg, PickleIterator* aIter,
                            paramType* aResult)
{
  for (unsigned i = 0; i < Metadata::kNumEntries; i++) {
    Metadata::Entry& entry = aResult->mEntries[i];
    if (!ReadParam(aMsg, aIter, &entry.mFastHash) ||
        !ReadParam(aMsg, aIter, &entry.mNumChars) ||
        !ReadParam(aMsg, aIter, &entry.mFullHash) ||
        !ReadParam(aMsg, aIter, &entry.mModuleIndex))
    {
      return false;
    }
  }
  return true;
}

void
ParamTraits<Metadata>::Log(const paramType& aParam, std::wstring* aLog)
{
  for (unsigned i = 0; i < Metadata::kNumEntries; i++) {
    const Metadata::Entry& entry = aParam.mEntries[i];
    LogParam(entry.mFastHash, aLog);
    LogParam(entry.mNumChars, aLog);
    LogParam(entry.mFullHash, aLog);
    LogParam(entry.mModuleIndex, aLog);
  }
}

void
ParamTraits<WriteParams>::Write(Message* aMsg, const paramType& aParam)
{
  WriteParam(aMsg, aParam.mSize);
  WriteParam(aMsg, aParam.mFastHash);
  WriteParam(aMsg, aParam.mNumChars);
  WriteParam(aMsg, aParam.mFullHash);
  WriteParam(aMsg, aParam.mInstalled);
}

bool
ParamTraits<WriteParams>::Read(const Message* aMsg, PickleIterator* aIter,
                               paramType* aResult)
{
  return ReadParam(aMsg, aIter, &aResult->mSize) &&
         ReadParam(aMsg, aIter, &aResult->mFastHash) &&
         ReadParam(aMsg, aIter, &aResult->mNumChars) &&
         ReadParam(aMsg, aIter, &aResult->mFullHash) &&
         ReadParam(aMsg, aIter, &aResult->mInstalled);
}

void
ParamTraits<WriteParams>::Log(const paramType& aParam, std::wstring* aLog)
{
  LogParam(aParam.mSize, aLog);
  LogParam(aParam.mFastHash, aLog);
  LogParam(aParam.mNumChars, aLog);
  LogParam(aParam.mFullHash, aLog);
  LogParam(aParam.mInstalled, aLog);
}

} // namespace IPC