summaryrefslogtreecommitdiffstats
path: root/xpcom/tests/gtest/TestThreadUtils.cpp
blob: 96b134288597154b9a1b39ce6da4bcb5b0ab6b5d (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
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
/* 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 <type_traits>

#include "nsComponentManagerUtils.h"
#include "nsIThread.h"
#include "nsThreadUtils.h"
#include "mozilla/IdleTaskRunner.h"
#include "mozilla/RefCounted.h"
#include "mozilla/SpinEventLoopUntil.h"
#include "mozilla/UniquePtr.h"

#include "gtest/gtest.h"

using namespace mozilla;

enum {
  TEST_CALL_VOID_ARG_VOID_RETURN,
  TEST_CALL_VOID_ARG_VOID_RETURN_CONST,
  TEST_CALL_VOID_ARG_NONVOID_RETURN,
  TEST_CALL_NONVOID_ARG_VOID_RETURN,
  TEST_CALL_NONVOID_ARG_NONVOID_RETURN,
  TEST_CALL_NONVOID_ARG_VOID_RETURN_EXPLICIT,
  TEST_CALL_NONVOID_ARG_NONVOID_RETURN_EXPLICIT,
#ifdef HAVE_STDCALL
  TEST_STDCALL_VOID_ARG_VOID_RETURN,
  TEST_STDCALL_VOID_ARG_NONVOID_RETURN,
  TEST_STDCALL_NONVOID_ARG_VOID_RETURN,
  TEST_STDCALL_NONVOID_ARG_NONVOID_RETURN,
  TEST_STDCALL_NONVOID_ARG_NONVOID_RETURN_EXPLICIT,
#endif
  TEST_CALL_NEWTHREAD_SUICIDAL,
  MAX_TESTS
};

bool gRunnableExecuted[MAX_TESTS];

class nsFoo : public nsISupports {
  NS_DECL_ISUPPORTS
  nsresult DoFoo(bool* aBool) {
    *aBool = true;
    return NS_OK;
  }

 private:
  virtual ~nsFoo() = default;
};

NS_IMPL_ISUPPORTS0(nsFoo)

class TestSuicide : public mozilla::Runnable {
 public:
  TestSuicide() : mozilla::Runnable("TestSuicide") {}
  NS_IMETHOD Run() override {
    // Runs first time on thread "Suicide", then dies on MainThread
    if (!NS_IsMainThread()) {
      mThread = do_GetCurrentThread();
      NS_DispatchToMainThread(this);
      return NS_OK;
    }
    MOZ_RELEASE_ASSERT(mThread);
    mThread->Shutdown();
    gRunnableExecuted[TEST_CALL_NEWTHREAD_SUICIDAL] = true;
    return NS_OK;
  }

 private:
  nsCOMPtr<nsIThread> mThread;
};

class nsBar : public nsISupports {
  virtual ~nsBar() = default;

 public:
  NS_DECL_ISUPPORTS
  void DoBar1(void) {
    gRunnableExecuted[TEST_CALL_VOID_ARG_VOID_RETURN] = true;
  }
  void DoBar1Const(void) const {
    gRunnableExecuted[TEST_CALL_VOID_ARG_VOID_RETURN_CONST] = true;
  }
  nsresult DoBar2(void) {
    gRunnableExecuted[TEST_CALL_VOID_ARG_NONVOID_RETURN] = true;
    return NS_OK;
  }
  void DoBar3(nsFoo* aFoo) {
    aFoo->DoFoo(&gRunnableExecuted[TEST_CALL_NONVOID_ARG_VOID_RETURN]);
  }
  nsresult DoBar4(nsFoo* aFoo) {
    return aFoo->DoFoo(
        &gRunnableExecuted[TEST_CALL_NONVOID_ARG_NONVOID_RETURN]);
  }
  void DoBar5(nsFoo* aFoo) {
    if (aFoo)
      gRunnableExecuted[TEST_CALL_NONVOID_ARG_VOID_RETURN_EXPLICIT] = true;
  }
  nsresult DoBar6(char* aFoo) {
    if (strlen(aFoo))
      gRunnableExecuted[TEST_CALL_NONVOID_ARG_NONVOID_RETURN_EXPLICIT] = true;
    return NS_OK;
  }
#ifdef HAVE_STDCALL
  void __stdcall DoBar1std(void) {
    gRunnableExecuted[TEST_STDCALL_VOID_ARG_VOID_RETURN] = true;
  }
  nsresult __stdcall DoBar2std(void) {
    gRunnableExecuted[TEST_STDCALL_VOID_ARG_NONVOID_RETURN] = true;
    return NS_OK;
  }
  void __stdcall DoBar3std(nsFoo* aFoo) {
    aFoo->DoFoo(&gRunnableExecuted[TEST_STDCALL_NONVOID_ARG_VOID_RETURN]);
  }
  nsresult __stdcall DoBar4std(nsFoo* aFoo) {
    return aFoo->DoFoo(
        &gRunnableExecuted[TEST_STDCALL_NONVOID_ARG_NONVOID_RETURN]);
  }
  void __stdcall DoBar5std(nsFoo* aFoo) {
    if (aFoo)
      gRunnableExecuted[TEST_STDCALL_NONVOID_ARG_VOID_RETURN_EXPLICIT] = true;
  }
  nsresult __stdcall DoBar6std(char* aFoo) {
    if (strlen(aFoo))
      gRunnableExecuted[TEST_CALL_NONVOID_ARG_VOID_RETURN_EXPLICIT] = true;
    return NS_OK;
  }
#endif
};

NS_IMPL_ISUPPORTS0(nsBar)

struct TestCopyWithNoMove {
  explicit TestCopyWithNoMove(int* aCopyCounter) : mCopyCounter(aCopyCounter) {}
  TestCopyWithNoMove(const TestCopyWithNoMove& a)
      : mCopyCounter(a.mCopyCounter) {
    *mCopyCounter += 1;
  };
  // No 'move' declaration, allows passing object by rvalue copy.
  // Destructor nulls member variable...
  ~TestCopyWithNoMove() { mCopyCounter = nullptr; }
  // ... so we can check that the object is called when still alive.
  void operator()() { MOZ_RELEASE_ASSERT(mCopyCounter); }
  int* mCopyCounter;
};
struct TestCopyWithDeletedMove {
  explicit TestCopyWithDeletedMove(int* aCopyCounter)
      : mCopyCounter(aCopyCounter) {}
  TestCopyWithDeletedMove(const TestCopyWithDeletedMove& a)
      : mCopyCounter(a.mCopyCounter) {
    *mCopyCounter += 1;
  };
  // Deleted move prevents passing by rvalue (even if copy would work)
  TestCopyWithDeletedMove(TestCopyWithDeletedMove&&) = delete;
  ~TestCopyWithDeletedMove() { mCopyCounter = nullptr; }
  void operator()() { MOZ_RELEASE_ASSERT(mCopyCounter); }
  int* mCopyCounter;
};
struct TestMove {
  explicit TestMove(int* aMoveCounter) : mMoveCounter(aMoveCounter) {}
  TestMove(const TestMove&) = delete;
  TestMove(TestMove&& a) : mMoveCounter(a.mMoveCounter) {
    a.mMoveCounter = nullptr;
    *mMoveCounter += 1;
  }
  ~TestMove() { mMoveCounter = nullptr; }
  void operator()() { MOZ_RELEASE_ASSERT(mMoveCounter); }
  int* mMoveCounter;
};
struct TestCopyMove {
  TestCopyMove(int* aCopyCounter, int* aMoveCounter)
      : mCopyCounter(aCopyCounter), mMoveCounter(aMoveCounter) {}
  TestCopyMove(const TestCopyMove& a)
      : mCopyCounter(a.mCopyCounter), mMoveCounter(a.mMoveCounter) {
    *mCopyCounter += 1;
  };
  TestCopyMove(TestCopyMove&& a)
      : mCopyCounter(a.mCopyCounter), mMoveCounter(a.mMoveCounter) {
    a.mMoveCounter = nullptr;
    *mMoveCounter += 1;
  }
  ~TestCopyMove() {
    mCopyCounter = nullptr;
    mMoveCounter = nullptr;
  }
  void operator()() {
    MOZ_RELEASE_ASSERT(mCopyCounter);
    MOZ_RELEASE_ASSERT(mMoveCounter);
  }
  int* mCopyCounter;
  int* mMoveCounter;
};

struct TestRefCounted : RefCounted<TestRefCounted> {
  MOZ_DECLARE_REFCOUNTED_TYPENAME(TestRefCounted);
};

static void Expect(const char* aContext, int aCounter, int aMaxExpected) {
  EXPECT_LE(aCounter, aMaxExpected) << aContext;
}

static void ExpectRunnableName(Runnable* aRunnable, const char* aExpectedName) {
#ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
  nsAutoCString name;
  EXPECT_TRUE(NS_SUCCEEDED(aRunnable->GetName(name))) << "Runnable::GetName()";
  EXPECT_TRUE(name.EqualsASCII(aExpectedName)) << "Verify Runnable name";
#endif
}

struct BasicRunnableFactory {
  static constexpr bool SupportsCopyWithDeletedMove = true;

  template <typename Function>
  static auto Create(const char* aName, Function&& aFunc) {
    return NS_NewRunnableFunction(aName, std::forward<Function>(aFunc));
  }
};

struct CancelableRunnableFactory {
  static constexpr bool SupportsCopyWithDeletedMove = false;

  template <typename Function>
  static auto Create(const char* aName, Function&& aFunc) {
    return NS_NewCancelableRunnableFunction(aName,
                                            std::forward<Function>(aFunc));
  }
};

template <typename RunnableFactory>
static void TestRunnableFactory(bool aNamed) {
  // Test RunnableFactory with copyable-only function object.
  {
    int copyCounter = 0;
    {
      nsCOMPtr<nsIRunnable> trackedRunnable;
      {
        TestCopyWithNoMove tracker(&copyCounter);
        trackedRunnable = aNamed ? RunnableFactory::Create("unused", tracker)
                                 : RunnableFactory::Create(
                                       "TestNewRunnableFunction", tracker);
        // Original 'tracker' is destroyed here.
      }
      // Verify that the runnable contains a non-destroyed function object.
      trackedRunnable->Run();
    }
    Expect(
        "RunnableFactory with copyable-only (and no move) function, "
        "copies",
        copyCounter, 1);
  }
  {
    int copyCounter = 0;
    {
      nsCOMPtr<nsIRunnable> trackedRunnable;
      {
        // Passing as rvalue, but using copy.
        // (TestCopyWithDeletedMove wouldn't allow this.)
        trackedRunnable =
            aNamed ? RunnableFactory::Create("unused",
                                             TestCopyWithNoMove(&copyCounter))
                   : RunnableFactory::Create("TestNewRunnableFunction",
                                             TestCopyWithNoMove(&copyCounter));
      }
      trackedRunnable->Run();
    }
    Expect(
        "RunnableFactory with copyable-only (and no move) function "
        "rvalue, copies",
        copyCounter, 1);
  }
  if constexpr (RunnableFactory::SupportsCopyWithDeletedMove) {
    int copyCounter = 0;
    {
      nsCOMPtr<nsIRunnable> trackedRunnable;
      {
        TestCopyWithDeletedMove tracker(&copyCounter);
        trackedRunnable = aNamed ? RunnableFactory::Create("unused", tracker)
                                 : RunnableFactory::Create(
                                       "TestNewRunnableFunction", tracker);
      }
      trackedRunnable->Run();
    }
    Expect(
        "RunnableFactory with copyable-only (and deleted move) "
        "function, copies",
        copyCounter, 1);
  }

  // Test RunnableFactory with movable-only function object.
  {
    int moveCounter = 0;
    {
      nsCOMPtr<nsIRunnable> trackedRunnable;
      {
        TestMove tracker(&moveCounter);
        trackedRunnable =
            aNamed ? RunnableFactory::Create("unused", std::move(tracker))
                   : RunnableFactory::Create("TestNewRunnableFunction",
                                             std::move(tracker));
      }
      trackedRunnable->Run();
    }
    Expect("RunnableFactory with movable-only function, moves", moveCounter, 1);
  }
  {
    int moveCounter = 0;
    {
      nsCOMPtr<nsIRunnable> trackedRunnable;
      {
        trackedRunnable =
            aNamed ? RunnableFactory::Create("unused", TestMove(&moveCounter))
                   : RunnableFactory::Create("TestNewRunnableFunction",
                                             TestMove(&moveCounter));
      }
      trackedRunnable->Run();
    }
    Expect("RunnableFactory with movable-only function rvalue, moves",
           moveCounter, 1);
  }

  // Test RunnableFactory with copyable&movable function object.
  {
    int copyCounter = 0;
    int moveCounter = 0;
    {
      nsCOMPtr<nsIRunnable> trackedRunnable;
      {
        TestCopyMove tracker(&copyCounter, &moveCounter);
        trackedRunnable =
            aNamed ? RunnableFactory::Create("unused", std::move(tracker))
                   : RunnableFactory::Create("TestNewRunnableFunction",
                                             std::move(tracker));
      }
      trackedRunnable->Run();
    }
    Expect("RunnableFactory with copyable&movable function, copies",
           copyCounter, 0);
    Expect("RunnableFactory with copyable&movable function, moves", moveCounter,
           1);
  }
  {
    int copyCounter = 0;
    int moveCounter = 0;
    {
      nsCOMPtr<nsIRunnable> trackedRunnable;
      {
        trackedRunnable =
            aNamed ? RunnableFactory::Create(
                         "unused", TestCopyMove(&copyCounter, &moveCounter))
                   : RunnableFactory::Create(
                         "TestNewRunnableFunction",
                         TestCopyMove(&copyCounter, &moveCounter));
      }
      trackedRunnable->Run();
    }
    Expect("RunnableFactory with copyable&movable function rvalue, copies",
           copyCounter, 0);
    Expect("RunnableFactory with copyable&movable function rvalue, moves",
           moveCounter, 1);
  }

  // Test RunnableFactory with copyable-only lambda capture.
  {
    int copyCounter = 0;
    {
      nsCOMPtr<nsIRunnable> trackedRunnable;
      {
        TestCopyWithNoMove tracker(&copyCounter);
        // Expect 2 copies (here -> local lambda -> runnable lambda).
        trackedRunnable =
            aNamed
                ? RunnableFactory::Create("unused",
                                          [tracker]() mutable { tracker(); })
                : RunnableFactory::Create("TestNewRunnableFunction",
                                          [tracker]() mutable { tracker(); });
      }
      trackedRunnable->Run();
    }
    Expect(
        "RunnableFactory with copyable-only (and no move) capture, "
        "copies",
        copyCounter, 2);
  }
  {
    int copyCounter = 0;
    {
      nsCOMPtr<nsIRunnable> trackedRunnable;
      {
        TestCopyWithDeletedMove tracker(&copyCounter);
        // Expect 2 copies (here -> local lambda -> runnable lambda).
        trackedRunnable =
            aNamed
                ? RunnableFactory::Create("unused",
                                          [tracker]() mutable { tracker(); })
                : RunnableFactory::Create("TestNewRunnableFunction",
                                          [tracker]() mutable { tracker(); });
      }
      trackedRunnable->Run();
    }
    Expect(
        "RunnableFactory with copyable-only (and deleted move) capture, "
        "copies",
        copyCounter, 2);
  }

  // Note: Not possible to use move-only captures.
  // (Until we can use C++14 generalized lambda captures)

  // Test RunnableFactory with copyable&movable lambda capture.
  {
    int copyCounter = 0;
    int moveCounter = 0;
    {
      nsCOMPtr<nsIRunnable> trackedRunnable;
      {
        TestCopyMove tracker(&copyCounter, &moveCounter);
        trackedRunnable =
            aNamed
                ? RunnableFactory::Create("unused",
                                          [tracker]() mutable { tracker(); })
                : RunnableFactory::Create("TestNewRunnableFunction",
                                          [tracker]() mutable { tracker(); });
        // Expect 1 copy (here -> local lambda) and 1 move (local -> runnable
        // lambda).
      }
      trackedRunnable->Run();
    }
    Expect("RunnableFactory with copyable&movable capture, copies", copyCounter,
           1);
    Expect("RunnableFactory with copyable&movable capture, moves", moveCounter,
           1);
  }
}

TEST(ThreadUtils, NewRunnableFunction)
{ TestRunnableFactory<BasicRunnableFactory>(/*aNamed*/ false); }

TEST(ThreadUtils, NewNamedRunnableFunction)
{
  // The named overload shall behave identical to the non-named counterpart.
  TestRunnableFactory<BasicRunnableFactory>(/*aNamed*/ true);

  // Test naming.
  {
    const char* expectedName = "NamedRunnable";
    RefPtr<Runnable> NamedRunnable =
        NS_NewRunnableFunction(expectedName, [] {});
    ExpectRunnableName(NamedRunnable, expectedName);
  }
}

TEST(ThreadUtils, NewCancelableRunnableFunction)
{ TestRunnableFactory<CancelableRunnableFactory>(/*aNamed*/ false); }

TEST(ThreadUtils, NewNamedCancelableRunnableFunction)
{
  // The named overload shall behave identical to the non-named counterpart.
  TestRunnableFactory<CancelableRunnableFactory>(/*aNamed*/ true);

  // Test naming.
  {
    const char* expectedName = "NamedRunnable";
    RefPtr<Runnable> NamedRunnable =
        NS_NewCancelableRunnableFunction(expectedName, [] {});
    ExpectRunnableName(NamedRunnable, expectedName);
  }

  // Test release on cancelation.
  {
    auto foo = MakeRefPtr<TestRefCounted>();
    bool ran = false;

    RefPtr<CancelableRunnable> func =
        NS_NewCancelableRunnableFunction("unused", [foo, &ran] { ran = true; });

    EXPECT_EQ(foo->refCount(), 2u);
    func->Cancel();

    EXPECT_EQ(foo->refCount(), 1u);
    EXPECT_FALSE(ran);
  }

  // Test no-op after cancelation.
  {
    auto foo = MakeRefPtr<TestRefCounted>();
    bool ran = false;

    RefPtr<CancelableRunnable> func =
        NS_NewCancelableRunnableFunction("unused", [foo, &ran] { ran = true; });

    EXPECT_EQ(foo->refCount(), 2u);
    func->Cancel();
    func->Run();

    EXPECT_FALSE(ran);
  }
}

static void TestNewRunnableMethod(bool aNamed) {
  memset(gRunnableExecuted, false, MAX_TESTS * sizeof(bool));
  // Scope the smart ptrs so that the runnables need to hold on to whatever they
  // need
  {
    RefPtr<nsFoo> foo = new nsFoo();
    RefPtr<nsBar> bar = new nsBar();
    RefPtr<const nsBar> constBar = bar;

    // This pointer will be freed at the end of the block
    // Do not dereference this pointer in the runnable method!
    RefPtr<nsFoo> rawFoo = new nsFoo();

    // Read only string. Dereferencing in runnable method to check this works.
    char* message = (char*)"Test message";

    {
      auto bar = MakeRefPtr<nsBar>();

      NS_DispatchToMainThread(
          aNamed ? NewRunnableMethod("unused", std::move(bar), &nsBar::DoBar1)
                 : NewRunnableMethod("nsBar::DoBar1", std::move(bar),
                                     &nsBar::DoBar1));
    }

    NS_DispatchToMainThread(
        aNamed ? NewRunnableMethod("unused", bar, &nsBar::DoBar1)
               : NewRunnableMethod("nsBar::DoBar1", bar, &nsBar::DoBar1));
    NS_DispatchToMainThread(
        aNamed ? NewRunnableMethod("unused", constBar, &nsBar::DoBar1Const)
               : NewRunnableMethod("nsBar::DoBar1Const", constBar,
                                   &nsBar::DoBar1Const));
    NS_DispatchToMainThread(
        aNamed ? NewRunnableMethod("unused", bar, &nsBar::DoBar2)
               : NewRunnableMethod("nsBar::DoBar2", bar, &nsBar::DoBar2));
    NS_DispatchToMainThread(
        aNamed ? NewRunnableMethod<RefPtr<nsFoo>>("unused", bar, &nsBar::DoBar3,
                                                  foo)
               : NewRunnableMethod<RefPtr<nsFoo>>("nsBar::DoBar3", bar,
                                                  &nsBar::DoBar3, foo));
    NS_DispatchToMainThread(
        aNamed ? NewRunnableMethod<RefPtr<nsFoo>>("unused", bar, &nsBar::DoBar4,
                                                  foo)
               : NewRunnableMethod<RefPtr<nsFoo>>("nsBar::DoBar4", bar,
                                                  &nsBar::DoBar4, foo));
    NS_DispatchToMainThread(
        aNamed
            ? NewRunnableMethod<nsFoo*>("unused", bar, &nsBar::DoBar5, rawFoo)
            : NewRunnableMethod<nsFoo*>("nsBar::DoBar5", bar, &nsBar::DoBar5,
                                        rawFoo));
    NS_DispatchToMainThread(
        aNamed
            ? NewRunnableMethod<char*>("unused", bar, &nsBar::DoBar6, message)
            : NewRunnableMethod<char*>("nsBar::DoBar6", bar, &nsBar::DoBar6,
                                       message));
#ifdef HAVE_STDCALL
    NS_DispatchToMainThread(
        aNamed ? NewRunnableMethod("unused", bar, &nsBar::DoBar1std)
               : NewRunnableMethod(bar, &nsBar::DoBar1std));
    NS_DispatchToMainThread(
        aNamed ? NewRunnableMethod("unused", bar, &nsBar::DoBar2std)
               : NewRunnableMethod(bar, &nsBar::DoBar2std));
    NS_DispatchToMainThread(
        aNamed ? NewRunnableMethod<RefPtr<nsFoo>>("unused", bar,
                                                  &nsBar::DoBar3std, foo)
               : NewRunnableMethod<RefPtr<nsFoo>>(bar, &nsBar::DoBar3std, foo));
    NS_DispatchToMainThread(
        aNamed ? NewRunnableMethod<RefPtr<nsFoo>>("unused", bar,
                                                  &nsBar::DoBar4std, foo)
               : NewRunnableMethod<RefPtr<nsFoo>>(bar, &nsBar::DoBar4std, foo));
    NS_DispatchToMainThread(
        aNamed ? NewRunnableMethod<nsFoo*>("unused", bar, &nsBar::DoBar5std,
                                           rawFoo)
               : NewRunnableMethod<nsFoo*>(bar, &nsBar::DoBar5std, rawFoo));
    NS_DispatchToMainThread(
        aNamed ? NewRunnableMethod<char*>("unused", bar, &nsBar::DoBar6std,
                                          message)
               : NewRunnableMethod<char*>(bar, &nsBar::DoBar6std, message));
#endif
  }

  // Spin the event loop
  NS_ProcessPendingEvents(nullptr);

  // Now test a suicidal event in NS_New(Named)Thread
  nsCOMPtr<nsIThread> thread;
  NS_NewNamedThread("SuicideThread", getter_AddRefs(thread), new TestSuicide());
  ASSERT_TRUE(thread);

  while (!gRunnableExecuted[TEST_CALL_NEWTHREAD_SUICIDAL]) {
    NS_ProcessPendingEvents(nullptr);
  }

  for (uint32_t i = 0; i < MAX_TESTS; i++) {
    EXPECT_TRUE(gRunnableExecuted[i]) << "Error in test " << i;
  }
}

TEST(ThreadUtils, RunnableMethod)
{ TestNewRunnableMethod(/* aNamed */ false); }

TEST(ThreadUtils, NamedRunnableMethod)
{
  // The named overloads shall behave identical to the non-named counterparts.
  TestNewRunnableMethod(/* aNamed */ true);

  // Test naming.
  {
    RefPtr<nsFoo> foo = new nsFoo();
    const char* expectedName = "NamedRunnable";
    bool unused;
    RefPtr<Runnable> NamedRunnable =
        NewRunnableMethod<bool*>(expectedName, foo, &nsFoo::DoFoo, &unused);
    ExpectRunnableName(NamedRunnable, expectedName);
  }
}

class IdleObjectWithoutSetDeadline final {
 public:
  NS_INLINE_DECL_REFCOUNTING(IdleObjectWithoutSetDeadline)
  IdleObjectWithoutSetDeadline() : mRunnableExecuted(false) {}
  void Method() { mRunnableExecuted = true; }
  bool mRunnableExecuted;

 private:
  ~IdleObjectWithoutSetDeadline() = default;
};

class IdleObjectParentWithSetDeadline {
 public:
  IdleObjectParentWithSetDeadline() : mSetDeadlineCalled(false) {}
  void SetDeadline(TimeStamp aDeadline) { mSetDeadlineCalled = true; }
  bool mSetDeadlineCalled;
};

class IdleObjectInheritedSetDeadline final
    : public IdleObjectParentWithSetDeadline {
 public:
  NS_INLINE_DECL_REFCOUNTING(IdleObjectInheritedSetDeadline)
  IdleObjectInheritedSetDeadline() : mRunnableExecuted(false) {}
  void Method() { mRunnableExecuted = true; }
  bool mRunnableExecuted;

 private:
  ~IdleObjectInheritedSetDeadline() = default;
};

class IdleObject final {
 public:
  NS_INLINE_DECL_REFCOUNTING(IdleObject)
  IdleObject() {
    for (uint32_t index = 0; index < ArrayLength(mRunnableExecuted); ++index) {
      mRunnableExecuted[index] = false;
      mSetIdleDeadlineCalled = false;
    }
  }
  void SetDeadline(TimeStamp aTimeStamp) { mSetIdleDeadlineCalled = true; }

  void CheckExecutedMethods(const char* aKey, uint32_t aNumExecuted) {
    uint32_t index;
    for (index = 0; index < aNumExecuted; ++index) {
      ASSERT_TRUE(mRunnableExecuted[index])
      << aKey << ": Method" << index << " should've executed";
    }

    for (; index < ArrayLength(mRunnableExecuted); ++index) {
      ASSERT_FALSE(mRunnableExecuted[index])
      << aKey << ": Method" << index << " shouldn't have executed";
    }
  }

  void Method0() {
    CheckExecutedMethods("Method0", 0);
    mRunnableExecuted[0] = true;
    mSetIdleDeadlineCalled = false;
  }

  void Method1() {
    CheckExecutedMethods("Method1", 1);
    ASSERT_TRUE(mSetIdleDeadlineCalled);
    mRunnableExecuted[1] = true;
    mSetIdleDeadlineCalled = false;
  }

  void Method2() {
    CheckExecutedMethods("Method2", 2);
    ASSERT_TRUE(mSetIdleDeadlineCalled);
    mRunnableExecuted[2] = true;
    mSetIdleDeadlineCalled = false;
    NS_DispatchToCurrentThread(
        NewRunnableMethod("IdleObject::Method3", this, &IdleObject::Method3));
  }

  void Method3() {
    CheckExecutedMethods("Method3", 3);

    NS_NewTimerWithFuncCallback(getter_AddRefs(mTimer), Method4, this, 10,
                                nsITimer::TYPE_ONE_SHOT, "IdleObject::Method3");
    NS_DispatchToCurrentThreadQueue(
        NewIdleRunnableMethodWithTimer("IdleObject::Method5", this,
                                       &IdleObject::Method5),
        50, EventQueuePriority::Idle);
    NS_DispatchToCurrentThreadQueue(
        NewRunnableMethod("IdleObject::Method6", this, &IdleObject::Method6),
        100, EventQueuePriority::Idle);

    PR_Sleep(PR_MillisecondsToInterval(200));
    mRunnableExecuted[3] = true;
    mSetIdleDeadlineCalled = false;
  }

  static void Method4(nsITimer* aTimer, void* aClosure) {
    RefPtr<IdleObject> self = static_cast<IdleObject*>(aClosure);
    self->CheckExecutedMethods("Method4", 4);
    self->mRunnableExecuted[4] = true;
    self->mSetIdleDeadlineCalled = false;
  }

  void Method5() {
    CheckExecutedMethods("Method5", 5);
    ASSERT_TRUE(mSetIdleDeadlineCalled);
    mRunnableExecuted[5] = true;
    mSetIdleDeadlineCalled = false;
  }

  void Method6() {
    CheckExecutedMethods("Method6", 6);
    mRunnableExecuted[6] = true;
    mSetIdleDeadlineCalled = false;
  }

  void Method7() {
    CheckExecutedMethods("Method7", 7);
    ASSERT_TRUE(mSetIdleDeadlineCalled);
    mRunnableExecuted[7] = true;
    mSetIdleDeadlineCalled = false;
  }

 private:
  nsCOMPtr<nsITimer> mTimer;
  bool mRunnableExecuted[8];
  bool mSetIdleDeadlineCalled;
  ~IdleObject() = default;
};

// Disable test due to frequent failures
#if 0
// because test fails on multiple platforms
TEST(ThreadUtils, IdleRunnableMethod)
{
  {
    RefPtr<IdleObject> idle = new IdleObject();
    RefPtr<IdleObjectWithoutSetDeadline> idleNoSetDeadline =
        new IdleObjectWithoutSetDeadline();
    RefPtr<IdleObjectInheritedSetDeadline> idleInheritedSetDeadline =
        new IdleObjectInheritedSetDeadline();

    NS_DispatchToCurrentThread(
        NewRunnableMethod("IdleObject::Method0", idle, &IdleObject::Method0));
    NS_DispatchToCurrentThreadQueue(
        NewIdleRunnableMethod("IdleObject::Method1", idle,
                              &IdleObject::Method1),
        EventQueuePriority::Idle);
    NS_DispatchToCurrentThreadQueue(
        NewIdleRunnableMethodWithTimer("IdleObject::Method2", idle,
                                       &IdleObject::Method2),
        60000, EventQueuePriority::Idle);
    NS_DispatchToCurrentThreadQueue(
        NewIdleRunnableMethod("IdleObject::Method7", idle,
                              &IdleObject::Method7),
        EventQueuePriority::Idle);
    NS_DispatchToCurrentThreadQueue(
        NewIdleRunnableMethod<const char*, uint32_t>(
            "IdleObject::CheckExecutedMethods", idle,
            &IdleObject::CheckExecutedMethods, "final", 8),
        EventQueuePriority::Idle);
    NS_DispatchToCurrentThreadQueue(
        NewIdleRunnableMethod("IdleObjectWithoutSetDeadline::Method",
                              idleNoSetDeadline,
                              &IdleObjectWithoutSetDeadline::Method),
        EventQueuePriority::Idle);
    NS_DispatchToCurrentThreadQueue(
        NewIdleRunnableMethod("IdleObjectInheritedSetDeadline::Method",
                              idleInheritedSetDeadline,
                              &IdleObjectInheritedSetDeadline::Method),
        EventQueuePriority::Idle);

    NS_ProcessPendingEvents(nullptr);

    ASSERT_TRUE(idleNoSetDeadline->mRunnableExecuted);
    ASSERT_TRUE(idleInheritedSetDeadline->mRunnableExecuted);
    ASSERT_TRUE(idleInheritedSetDeadline->mSetDeadlineCalled);
  }
}
#endif

TEST(ThreadUtils, IdleTaskRunner)
{
  using namespace mozilla;

  // Repeating.
  int cnt1 = 0;
  RefPtr<IdleTaskRunner> runner1 = IdleTaskRunner::Create(
      [&cnt1](TimeStamp) {
        cnt1++;
        return true;
      },
      "runner1", 0, TimeDuration::FromMilliseconds(10),
      TimeDuration::FromMilliseconds(3), true, nullptr);

  // Non-repeating but callback always return false so it's still repeating.
  int cnt2 = 0;
  RefPtr<IdleTaskRunner> runner2 = IdleTaskRunner::Create(
      [&cnt2](TimeStamp) {
        cnt2++;
        return false;
      },
      "runner2", 0, TimeDuration::FromMilliseconds(10),
      TimeDuration::FromMilliseconds(3), false, nullptr);

  // Repeating until cnt3 >= 2 by returning 'true' in MayStopProcessing
  // callback. The strategy is to stop repeating as early as possible so that we
  // are more probable to catch the bug if it didn't stop as expected.
  int cnt3 = 0;
  RefPtr<IdleTaskRunner> runner3 = IdleTaskRunner::Create(
      [&cnt3](TimeStamp) {
        cnt3++;
        return true;
      },
      "runner3", 0, TimeDuration::FromMilliseconds(10),
      TimeDuration::FromMilliseconds(3), true, [&cnt3] { return cnt3 >= 2; });

  // Non-repeating can callback return true so the callback will
  // be only run once.
  int cnt4 = 0;
  RefPtr<IdleTaskRunner> runner4 = IdleTaskRunner::Create(
      [&cnt4](TimeStamp) {
        cnt4++;
        return true;
      },
      "runner4", 0, TimeDuration::FromMilliseconds(10),
      TimeDuration::FromMilliseconds(3), false, nullptr);

  // Firstly we wait until the two repeating tasks reach their limits.
  MOZ_ALWAYS_TRUE(
      SpinEventLoopUntil("xpcom:TEST(ThreadUtils, IdleTaskRunner) cnt1"_ns,
                         [&]() { return cnt1 >= 100; }));
  MOZ_ALWAYS_TRUE(
      SpinEventLoopUntil("xpcom:TEST(ThreadUtils, IdleTaskRunner) cnt2"_ns,
                         [&]() { return cnt2 >= 100; }));

  // At any point ==> 0 <= cnt3 <= 2 since MayStopProcessing() would return
  // true when cnt3 >= 2.
  MOZ_ALWAYS_TRUE(SpinEventLoopUntil(
      "xpcom:TEST(ThreadUtils, IdleTaskRunner) cnt3"_ns, [&]() {
        if (cnt3 > 2) {
          EXPECT_TRUE(false) << "MaybeContinueProcess() doesn't work.";
          return true;  // Stop on failure.
        }
        return cnt3 == 2;  // Stop finish if we have reached its max value.
      }));

  // At any point ==> 0 <= cnt4 <= 1 since this is a non-repeating
  // idle runner.
  MOZ_ALWAYS_TRUE(SpinEventLoopUntil(
      "xpcom:TEST(ThreadUtils, IdleTaskRunner) cnt4"_ns, [&]() {
        // At any point: 0 <= cnt4 <= 1
        if (cnt4 > 1) {
          EXPECT_TRUE(false) << "The 'mRepeating' flag doesn't work.";
          return true;  // Stop on failure.
        }
        return cnt4 == 1;
      }));

  // The repeating timers require an explicit Cancel() call.
  runner1->Cancel();
  runner2->Cancel();
}

// {9e70a320-be02-11d1-8031-006008159b5a}
#define NS_IFOO_IID                                  \
  {                                                  \
    0x9e70a320, 0xbe02, 0x11d1, {                    \
      0x80, 0x31, 0x00, 0x60, 0x08, 0x15, 0x9b, 0x5a \
    }                                                \
  }

TEST(ThreadUtils, TypeTraits)
{
  static_assert(std::is_same_v<int, mozilla::RemoveSmartPointer<int>>,
                "RemoveSmartPointer<int> should be int");
  static_assert(std::is_same_v<int*, mozilla::RemoveSmartPointer<int*>>,
                "RemoveSmartPointer<int*> should be int*");
  static_assert(std::is_same_v<UniquePtr<int>,
                               mozilla::RemoveSmartPointer<UniquePtr<int>>>,
                "RemoveSmartPointer<UniquePtr<int>> should be UniquePtr<int>");
  static_assert(std::is_same_v<int, mozilla::RemoveSmartPointer<RefPtr<int>>>,
                "RemoveSmartPointer<RefPtr<int>> should be int");
  static_assert(
      std::is_same_v<int, mozilla::RemoveSmartPointer<const RefPtr<int>>>,
      "RemoveSmartPointer<const RefPtr<int>> should be int");
  static_assert(
      std::is_same_v<int, mozilla::RemoveSmartPointer<volatile RefPtr<int>>>,
      "RemoveSmartPointer<volatile RefPtr<int>> should be int");
  static_assert(
      std::is_same_v<int,
                     mozilla::RemoveSmartPointer<const volatile RefPtr<int>>>,
      "RemoveSmartPointer<const volatile RefPtr<int>> should be int");
  static_assert(std::is_same_v<int, mozilla::RemoveSmartPointer<nsCOMPtr<int>>>,
                "RemoveSmartPointer<nsCOMPtr<int>> should be int");
  static_assert(
      std::is_same_v<int, mozilla::RemoveSmartPointer<const nsCOMPtr<int>>>,
      "RemoveSmartPointer<const nsCOMPtr<int>> should be int");
  static_assert(
      std::is_same_v<int, mozilla::RemoveSmartPointer<volatile nsCOMPtr<int>>>,
      "RemoveSmartPointer<volatile nsCOMPtr<int>> should be int");
  static_assert(
      std::is_same_v<int,
                     mozilla::RemoveSmartPointer<const volatile nsCOMPtr<int>>>,
      "RemoveSmartPointer<const volatile nsCOMPtr<int>> should be int");

  static_assert(std::is_same_v<int, mozilla::RemoveRawOrSmartPointer<int>>,
                "RemoveRawOrSmartPointer<int> should be int");
  static_assert(
      std::is_same_v<UniquePtr<int>,
                     mozilla::RemoveRawOrSmartPointer<UniquePtr<int>>>,
      "RemoveRawOrSmartPointer<UniquePtr<int>> should be UniquePtr<int>");
  static_assert(std::is_same_v<int, mozilla::RemoveRawOrSmartPointer<int*>>,
                "RemoveRawOrSmartPointer<int*> should be int");
  static_assert(
      std::is_same_v<const int, mozilla::RemoveRawOrSmartPointer<const int*>>,
      "RemoveRawOrSmartPointer<const int*> should be const int");
  static_assert(
      std::is_same_v<volatile int,
                     mozilla::RemoveRawOrSmartPointer<volatile int*>>,
      "RemoveRawOrSmartPointer<volatile int*> should be volatile int");
  static_assert(
      std::is_same_v<const volatile int,
                     mozilla::RemoveRawOrSmartPointer<const volatile int*>>,
      "RemoveRawOrSmartPointer<const volatile int*> should be const "
      "volatile int");
  static_assert(
      std::is_same_v<int, mozilla::RemoveRawOrSmartPointer<RefPtr<int>>>,
      "RemoveRawOrSmartPointer<RefPtr<int>> should be int");
  static_assert(
      std::is_same_v<int, mozilla::RemoveRawOrSmartPointer<const RefPtr<int>>>,
      "RemoveRawOrSmartPointer<const RefPtr<int>> should be int");
  static_assert(
      std::is_same_v<int,
                     mozilla::RemoveRawOrSmartPointer<volatile RefPtr<int>>>,
      "RemoveRawOrSmartPointer<volatile RefPtr<int>> should be int");
  static_assert(
      std::is_same_v<
          int, mozilla::RemoveRawOrSmartPointer<const volatile RefPtr<int>>>,
      "RemoveRawOrSmartPointer<const volatile RefPtr<int>> should be "
      "int");
  static_assert(
      std::is_same_v<int, mozilla::RemoveRawOrSmartPointer<nsCOMPtr<int>>>,
      "RemoveRawOrSmartPointer<nsCOMPtr<int>> should be int");
  static_assert(
      std::is_same_v<int,
                     mozilla::RemoveRawOrSmartPointer<const nsCOMPtr<int>>>,
      "RemoveRawOrSmartPointer<const nsCOMPtr<int>> should be int");
  static_assert(
      std::is_same_v<int,
                     mozilla::RemoveRawOrSmartPointer<volatile nsCOMPtr<int>>>,
      "RemoveRawOrSmartPointer<volatile nsCOMPtr<int>> should be int");
  static_assert(
      std::is_same_v<
          int, mozilla::RemoveRawOrSmartPointer<const volatile nsCOMPtr<int>>>,
      "RemoveRawOrSmartPointer<const volatile nsCOMPtr<int>> should be "
      "int");
}

namespace TestThreadUtils {

static bool gDebug = false;
static int gAlive, gZombies;
static int gAllConstructions, gConstructions, gCopyConstructions,
    gMoveConstructions, gDestructions, gAssignments, gMoves;
struct Spy {
  static void ClearActions() {
    gAllConstructions = gConstructions = gCopyConstructions =
        gMoveConstructions = gDestructions = gAssignments = gMoves = 0;
  }
  static void ClearAll() {
    ClearActions();
    gAlive = 0;
  }

  explicit Spy(int aID) : mID(aID) {
    ++gAlive;
    ++gAllConstructions;
    ++gConstructions;
    if (gDebug) {
      printf("Spy[%d@%p]()\n", mID, this);
    }
  }
  Spy(const Spy& o) : mID(o.mID) {
    ++gAlive;
    ++gAllConstructions;
    ++gCopyConstructions;
    if (gDebug) {
      printf("Spy[%d@%p](&[%d@%p])\n", mID, this, o.mID, &o);
    }
  }
  Spy(Spy&& o) : mID(o.mID) {
    o.mID = -o.mID;
    ++gZombies;
    ++gAllConstructions;
    ++gMoveConstructions;
    if (gDebug) {
      printf("Spy[%d@%p](&&[%d->%d@%p])\n", mID, this, -o.mID, o.mID, &o);
    }
  }
  ~Spy() {
    if (mID >= 0) {
      --gAlive;
    } else {
      --gZombies;
    }
    ++gDestructions;
    if (gDebug) {
      printf("~Spy[%d@%p]()\n", mID, this);
    }
    mID = 0;
  }
  Spy& operator=(const Spy& o) {
    ++gAssignments;
    if (gDebug) {
      printf("Spy[%d->%d@%p] = &[%d@%p]\n", mID, o.mID, this, o.mID, &o);
    }
    mID = o.mID;
    return *this;
  };
  Spy& operator=(Spy&& o) {
    --gAlive;
    ++gZombies;
    ++gMoves;
    if (gDebug) {
      printf("Spy[%d->%d@%p] = &&[%d->%d@%p]\n", mID, o.mID, this, o.mID,
             -o.mID, &o);
    }
    mID = o.mID;
    o.mID = -o.mID;
    return *this;
  };

  int mID;  // ID given at construction, or negation if was moved from; 0 when
            // destroyed.
};

struct ISpyWithISupports : public nsISupports {
  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IFOO_IID)
  NS_IMETHOD_(nsrefcnt) RefCnt() = 0;
  NS_IMETHOD_(int32_t) ID() = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(ISpyWithISupports, NS_IFOO_IID)
struct SpyWithISupports : public ISpyWithISupports, public Spy {
 private:
  virtual ~SpyWithISupports() = default;

 public:
  explicit SpyWithISupports(int aID) : Spy(aID){};
  NS_DECL_ISUPPORTS
  NS_IMETHOD_(nsrefcnt) RefCnt() override { return mRefCnt; }
  NS_IMETHOD_(int32_t) ID() override { return mID; }
};
NS_IMPL_ISUPPORTS(SpyWithISupports, ISpyWithISupports)

class IThreadUtilsObject : public nsISupports {
 public:
  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IFOO_IID)

  NS_IMETHOD_(nsrefcnt) RefCnt() = 0;
  NS_IMETHOD_(int32_t) ID() = 0;
};

NS_DEFINE_STATIC_IID_ACCESSOR(IThreadUtilsObject, NS_IFOO_IID)

struct ThreadUtilsObjectNonRefCountedBase {
  virtual void MethodFromNonRefCountedBase() {}
};

struct ThreadUtilsObject : public IThreadUtilsObject,
                           public ThreadUtilsObjectNonRefCountedBase {
  // nsISupports implementation
  NS_DECL_ISUPPORTS

  // IThreadUtilsObject implementation
  NS_IMETHOD_(nsrefcnt) RefCnt() override { return mRefCnt; }
  NS_IMETHOD_(int32_t) ID() override { return 0; }

  int mCount;  // Number of calls + arguments processed.
  int mA0, mA1, mA2, mA3;
  Spy mSpy;
  const Spy* mSpyPtr;
  ThreadUtilsObject()
      : mCount(0), mA0(0), mA1(0), mA2(0), mA3(0), mSpy(1), mSpyPtr(nullptr) {}

 private:
  virtual ~ThreadUtilsObject() = default;

 public:
  void Test0() { mCount += 1; }
  void Test1i(int a0) {
    mCount += 2;
    mA0 = a0;
  }
  void Test2i(int a0, int a1) {
    mCount += 3;
    mA0 = a0;
    mA1 = a1;
  }
  void Test3i(int a0, int a1, int a2) {
    mCount += 4;
    mA0 = a0;
    mA1 = a1;
    mA2 = a2;
  }
  void Test4i(int a0, int a1, int a2, int a3) {
    mCount += 5;
    mA0 = a0;
    mA1 = a1;
    mA2 = a2;
    mA3 = a3;
  }
  void Test1pi(int* ap) {
    mCount += 2;
    mA0 = ap ? *ap : -1;
  }
  void Test1pci(const int* ap) {
    mCount += 2;
    mA0 = ap ? *ap : -1;
  }
  void Test1ri(int& ar) {
    mCount += 2;
    mA0 = ar;
  }
  void Test1rri(int&& arr) {
    mCount += 2;
    mA0 = arr;
  }
  void Test1upi(mozilla::UniquePtr<int> aup) {
    mCount += 2;
    mA0 = aup ? *aup : -1;
  }
  void Test1rupi(mozilla::UniquePtr<int>& aup) {
    mCount += 2;
    mA0 = aup ? *aup : -1;
  }
  void Test1rrupi(mozilla::UniquePtr<int>&& aup) {
    mCount += 2;
    mA0 = aup ? *aup : -1;
  }

  void Test1s(Spy) { mCount += 2; }
  void Test1ps(Spy*) { mCount += 2; }
  void Test1rs(Spy&) { mCount += 2; }
  void Test1rrs(Spy&&) { mCount += 2; }
  void Test1ups(mozilla::UniquePtr<Spy>) { mCount += 2; }
  void Test1rups(mozilla::UniquePtr<Spy>&) { mCount += 2; }
  void Test1rrups(mozilla::UniquePtr<Spy>&&) { mCount += 2; }

  // Possible parameter passing styles:
  void TestByValue(Spy s) {
    if (gDebug) {
      printf("TestByValue(Spy[%d@%p])\n", s.mID, &s);
    }
    mSpy = s;
  };
  void TestByConstLRef(const Spy& s) {
    if (gDebug) {
      printf("TestByConstLRef(Spy[%d@%p]&)\n", s.mID, &s);
    }
    mSpy = s;
  };
  void TestByRRef(Spy&& s) {
    if (gDebug) {
      printf("TestByRRef(Spy[%d@%p]&&)\n", s.mID, &s);
    }
    mSpy = std::move(s);
  };
  void TestByLRef(Spy& s) {
    if (gDebug) {
      printf("TestByLRef(Spy[%d@%p]&)\n", s.mID, &s);
    }
    mSpy = s;
    mSpyPtr = &s;
  };
  void TestByPointer(Spy* p) {
    if (p) {
      if (gDebug) {
        printf("TestByPointer(&Spy[%d@%p])\n", p->mID, p);
      }
      mSpy = *p;
    } else {
      if (gDebug) {
        printf("TestByPointer(nullptr)\n");
      }
    }
    mSpyPtr = p;
  };
  void TestByPointerToConst(const Spy* p) {
    if (p) {
      if (gDebug) {
        printf("TestByPointerToConst(&Spy[%d@%p])\n", p->mID, p);
      }
      mSpy = *p;
    } else {
      if (gDebug) {
        printf("TestByPointerToConst(nullptr)\n");
      }
    }
    mSpyPtr = p;
  };
};

NS_IMPL_ISUPPORTS(ThreadUtilsObject, IThreadUtilsObject)

class ThreadUtilsRefCountedFinal final {
 public:
  ThreadUtilsRefCountedFinal() : m_refCount(0) {}
  ~ThreadUtilsRefCountedFinal() = default;
  // 'AddRef' and 'Release' methods with different return types, to verify
  // that the return type doesn't influence storage selection.
  long AddRef(void) { return ++m_refCount; }
  void Release(void) { --m_refCount; }

 private:
  long m_refCount;
};

class ThreadUtilsRefCountedBase {
 public:
  ThreadUtilsRefCountedBase() : m_refCount(0) {}
  virtual ~ThreadUtilsRefCountedBase() = default;
  // 'AddRef' and 'Release' methods with different return types, to verify
  // that the return type doesn't influence storage selection.
  virtual void AddRef(void) { ++m_refCount; }
  virtual MozExternalRefCountType Release(void) { return --m_refCount; }

 private:
  MozExternalRefCountType m_refCount;
};

class ThreadUtilsRefCountedDerived : public ThreadUtilsRefCountedBase {};

class ThreadUtilsNonRefCounted {};

}  // namespace TestThreadUtils

TEST(ThreadUtils, main)
{
  using namespace TestThreadUtils;

  static_assert(!IsParameterStorageClass<int>::value,
                "'int' should not be recognized as Storage Class");
  static_assert(
      IsParameterStorageClass<StoreCopyPassByConstLRef<int>>::value,
      "StoreCopyPassByConstLRef<int> should be recognized as Storage Class");
  static_assert(
      IsParameterStorageClass<StoreCopyPassByRRef<int>>::value,
      "StoreCopyPassByRRef<int> should be recognized as Storage Class");
  static_assert(
      IsParameterStorageClass<StoreRefPassByLRef<int>>::value,
      "StoreRefPassByLRef<int> should be recognized as Storage Class");
  static_assert(
      IsParameterStorageClass<StoreConstRefPassByConstLRef<int>>::value,
      "StoreConstRefPassByConstLRef<int> should be recognized as Storage "
      "Class");
  static_assert(
      IsParameterStorageClass<StoreRefPtrPassByPtr<int>>::value,
      "StoreRefPtrPassByPtr<int> should be recognized as Storage Class");
  static_assert(IsParameterStorageClass<StorePtrPassByPtr<int>>::value,
                "StorePtrPassByPtr<int> should be recognized as Storage Class");
  static_assert(
      IsParameterStorageClass<StoreConstPtrPassByConstPtr<int>>::value,
      "StoreConstPtrPassByConstPtr<int> should be recognized as Storage Class");

  RefPtr<ThreadUtilsObject> rpt(new ThreadUtilsObject);
  int count = 0;

  // Test legacy functions.

  nsCOMPtr<nsIRunnable> r1 =
      NewRunnableMethod("TestThreadUtils::ThreadUtilsObject::Test0", rpt,
                        &ThreadUtilsObject::Test0);
  r1->Run();
  EXPECT_EQ(count += 1, rpt->mCount);

  r1 = NewRunnableMethod<int>("TestThreadUtils::ThreadUtilsObject::Test1i", rpt,
                              &ThreadUtilsObject::Test1i, 11);
  r1->Run();
  EXPECT_EQ(count += 2, rpt->mCount);
  EXPECT_EQ(11, rpt->mA0);

  // Test calling a method from a non-ref-counted base.

  r1 = NewRunnableMethod(
      "TestThreadUtils::ThreadUtilsObjectNonRefCountedBase::"
      "MethodFromNonRefCountedBase",
      rpt, &ThreadUtilsObject::MethodFromNonRefCountedBase);
  r1->Run();
  EXPECT_EQ(count, rpt->mCount);

  // Test variadic function with simple POD arguments.

  r1 = NewRunnableMethod("TestThreadUtils::ThreadUtilsObject::Test0", rpt,
                         &ThreadUtilsObject::Test0);
  r1->Run();
  EXPECT_EQ(count += 1, rpt->mCount);

  static_assert(std::is_same_v<::detail::ParameterStorage<int>::Type,
                               StoreCopyPassByConstLRef<int>>,
                "detail::ParameterStorage<int>::Type should be "
                "StoreCopyPassByConstLRef<int>");

  r1 = NewRunnableMethod<int>("TestThreadUtils::ThreadUtilsObject::Test1i", rpt,
                              &ThreadUtilsObject::Test1i, 12);
  r1->Run();
  EXPECT_EQ(count += 2, rpt->mCount);
  EXPECT_EQ(12, rpt->mA0);

  r1 = NewRunnableMethod<int, int>("TestThreadUtils::ThreadUtilsObject::Test2i",
                                   rpt, &ThreadUtilsObject::Test2i, 21, 22);
  r1->Run();
  EXPECT_EQ(count += 3, rpt->mCount);
  EXPECT_EQ(21, rpt->mA0);
  EXPECT_EQ(22, rpt->mA1);

  r1 = NewRunnableMethod<int, int, int>(
      "TestThreadUtils::ThreadUtilsObject::Test3i", rpt,
      &ThreadUtilsObject::Test3i, 31, 32, 33);
  r1->Run();
  EXPECT_EQ(count += 4, rpt->mCount);
  EXPECT_EQ(31, rpt->mA0);
  EXPECT_EQ(32, rpt->mA1);
  EXPECT_EQ(33, rpt->mA2);

  r1 = NewRunnableMethod<int, int, int, int>(
      "TestThreadUtils::ThreadUtilsObject::Test4i", rpt,
      &ThreadUtilsObject::Test4i, 41, 42, 43, 44);
  r1->Run();
  EXPECT_EQ(count += 5, rpt->mCount);
  EXPECT_EQ(41, rpt->mA0);
  EXPECT_EQ(42, rpt->mA1);
  EXPECT_EQ(43, rpt->mA2);
  EXPECT_EQ(44, rpt->mA3);

  // More interesting types of arguments.

  // Passing a short to make sure forwarding works with an inexact type match.
  short int si = 11;
  r1 = NewRunnableMethod<int>("TestThreadUtils::ThreadUtilsObject::Test1i", rpt,
                              &ThreadUtilsObject::Test1i, si);
  r1->Run();
  EXPECT_EQ(count += 2, rpt->mCount);
  EXPECT_EQ(si, rpt->mA0);

  // Raw pointer, possible cv-qualified.
  static_assert(
      std::is_same_v<::detail::ParameterStorage<int*>::Type,
                     StorePtrPassByPtr<int>>,
      "detail::ParameterStorage<int*>::Type should be StorePtrPassByPtr<int>");
  static_assert(std::is_same_v<::detail::ParameterStorage<int* const>::Type,
                               StorePtrPassByPtr<int>>,
                "detail::ParameterStorage<int* const>::Type should be "
                "StorePtrPassByPtr<int>");
  static_assert(std::is_same_v<::detail::ParameterStorage<int* volatile>::Type,
                               StorePtrPassByPtr<int>>,
                "detail::ParameterStorage<int* volatile>::Type should be "
                "StorePtrPassByPtr<int>");
  static_assert(
      std::is_same_v<::detail::ParameterStorage<int* const volatile>::Type,
                     StorePtrPassByPtr<int>>,
      "detail::ParameterStorage<int* const volatile>::Type should be "
      "StorePtrPassByPtr<int>");
  static_assert(
      std::is_same_v<::detail::ParameterStorage<int*>::Type::stored_type, int*>,
      "detail::ParameterStorage<int*>::Type::stored_type should be int*");
  static_assert(
      std::is_same_v<::detail::ParameterStorage<int*>::Type::passed_type, int*>,
      "detail::ParameterStorage<int*>::Type::passed_type should be int*");
  {
    int i = 12;
    r1 = NewRunnableMethod<int*>("TestThreadUtils::ThreadUtilsObject::Test1pi",
                                 rpt, &ThreadUtilsObject::Test1pi, &i);
    r1->Run();
    EXPECT_EQ(count += 2, rpt->mCount);
    EXPECT_EQ(i, rpt->mA0);
  }

  // Raw pointer to const.
  static_assert(std::is_same_v<::detail::ParameterStorage<const int*>::Type,
                               StoreConstPtrPassByConstPtr<int>>,
                "detail::ParameterStorage<const int*>::Type should be "
                "StoreConstPtrPassByConstPtr<int>");
  static_assert(
      std::is_same_v<::detail::ParameterStorage<const int* const>::Type,
                     StoreConstPtrPassByConstPtr<int>>,
      "detail::ParameterStorage<const int* const>::Type should be "
      "StoreConstPtrPassByConstPtr<int>");
  static_assert(
      std::is_same_v<::detail::ParameterStorage<const int* volatile>::Type,
                     StoreConstPtrPassByConstPtr<int>>,
      "detail::ParameterStorage<const int* volatile>::Type should be "
      "StoreConstPtrPassByConstPtr<int>");
  static_assert(std::is_same_v<
                    ::detail::ParameterStorage<const int* const volatile>::Type,
                    StoreConstPtrPassByConstPtr<int>>,
                "detail::ParameterStorage<const int* const volatile>::Type "
                "should be StoreConstPtrPassByConstPtr<int>");
  static_assert(
      std::is_same_v<::detail::ParameterStorage<const int*>::Type::stored_type,
                     const int*>,
      "detail::ParameterStorage<const int*>::Type::stored_type should be const "
      "int*");
  static_assert(
      std::is_same_v<::detail::ParameterStorage<const int*>::Type::passed_type,
                     const int*>,
      "detail::ParameterStorage<const int*>::Type::passed_type should be const "
      "int*");
  {
    int i = 1201;
    r1 = NewRunnableMethod<const int*>(
        "TestThreadUtils::ThreadUtilsObject::Test1pci", rpt,
        &ThreadUtilsObject::Test1pci, &i);
    r1->Run();
    EXPECT_EQ(count += 2, rpt->mCount);
    EXPECT_EQ(i, rpt->mA0);
  }

  // nsRefPtr to pointer.
  static_assert(
      std::is_same_v<::detail::ParameterStorage<
                         StoreRefPtrPassByPtr<SpyWithISupports>>::Type,
                     StoreRefPtrPassByPtr<SpyWithISupports>>,
      "ParameterStorage<StoreRefPtrPassByPtr<SpyWithISupports>>::Type should "
      "be StoreRefPtrPassByPtr<SpyWithISupports>");
  static_assert(
      std::is_same_v<::detail::ParameterStorage<SpyWithISupports*>::Type,
                     StoreRefPtrPassByPtr<SpyWithISupports>>,
      "ParameterStorage<SpyWithISupports*>::Type should be "
      "StoreRefPtrPassByPtr<SpyWithISupports>");
  static_assert(
      std::is_same_v<StoreRefPtrPassByPtr<SpyWithISupports>::stored_type,
                     RefPtr<SpyWithISupports>>,
      "StoreRefPtrPassByPtr<SpyWithISupports>::stored_type should be "
      "RefPtr<SpyWithISupports>");
  static_assert(
      std::is_same_v<StoreRefPtrPassByPtr<SpyWithISupports>::passed_type,
                     SpyWithISupports*>,
      "StoreRefPtrPassByPtr<SpyWithISupports>::passed_type should be "
      "SpyWithISupports*");
  // (more nsRefPtr tests below)

  // nsRefPtr for ref-countable classes that do not derive from ISupports.
  static_assert(::detail::HasRefCountMethods<ThreadUtilsRefCountedFinal>,
                "ThreadUtilsRefCountedFinal has AddRef() and Release()");
  static_assert(
      std::is_same_v<
          ::detail::ParameterStorage<ThreadUtilsRefCountedFinal*>::Type,
          StoreRefPtrPassByPtr<ThreadUtilsRefCountedFinal>>,
      "ParameterStorage<ThreadUtilsRefCountedFinal*>::Type should be "
      "StoreRefPtrPassByPtr<ThreadUtilsRefCountedFinal>");
  static_assert(::detail::HasRefCountMethods<ThreadUtilsRefCountedBase>,
                "ThreadUtilsRefCountedBase has AddRef() and Release()");
  static_assert(
      std::is_same_v<
          ::detail::ParameterStorage<ThreadUtilsRefCountedBase*>::Type,
          StoreRefPtrPassByPtr<ThreadUtilsRefCountedBase>>,
      "ParameterStorage<ThreadUtilsRefCountedBase*>::Type should be "
      "StoreRefPtrPassByPtr<ThreadUtilsRefCountedBase>");
  static_assert(::detail::HasRefCountMethods<ThreadUtilsRefCountedDerived>,
                "ThreadUtilsRefCountedDerived has AddRef() and Release()");
  static_assert(
      std::is_same_v<
          ::detail::ParameterStorage<ThreadUtilsRefCountedDerived*>::Type,
          StoreRefPtrPassByPtr<ThreadUtilsRefCountedDerived>>,
      "ParameterStorage<ThreadUtilsRefCountedDerived*>::Type should be "
      "StoreRefPtrPassByPtr<ThreadUtilsRefCountedDerived>");

  static_assert(!::detail::HasRefCountMethods<ThreadUtilsNonRefCounted>,
                "ThreadUtilsNonRefCounted doesn't have AddRef() and Release()");
  static_assert(!std::is_same_v<
                    ::detail::ParameterStorage<ThreadUtilsNonRefCounted*>::Type,
                    StoreRefPtrPassByPtr<ThreadUtilsNonRefCounted>>,
                "ParameterStorage<ThreadUtilsNonRefCounted*>::Type should NOT "
                "be StoreRefPtrPassByPtr<ThreadUtilsNonRefCounted>");

  // Lvalue reference.
  static_assert(
      std::is_same_v<::detail::ParameterStorage<int&>::Type,
                     StoreRefPassByLRef<int>>,
      "ParameterStorage<int&>::Type should be StoreRefPassByLRef<int>");
  static_assert(
      std::is_same_v<::detail::ParameterStorage<int&>::Type::stored_type,
                     StoreRefPassByLRef<int>::stored_type>,
      "ParameterStorage<int&>::Type::stored_type should be "
      "StoreRefPassByLRef<int>::stored_type");
  static_assert(
      std::is_same_v<::detail::ParameterStorage<int&>::Type::stored_type, int&>,
      "ParameterStorage<int&>::Type::stored_type should be int&");
  static_assert(
      std::is_same_v<::detail::ParameterStorage<int&>::Type::passed_type, int&>,
      "ParameterStorage<int&>::Type::passed_type should be int&");
  {
    int i = 13;
    r1 = NewRunnableMethod<int&>("TestThreadUtils::ThreadUtilsObject::Test1ri",
                                 rpt, &ThreadUtilsObject::Test1ri, i);
    r1->Run();
    EXPECT_EQ(count += 2, rpt->mCount);
    EXPECT_EQ(i, rpt->mA0);
  }

  // Rvalue reference -- Actually storing a copy and then moving it.
  static_assert(
      std::is_same_v<::detail::ParameterStorage<int&&>::Type,
                     StoreCopyPassByRRef<int>>,
      "ParameterStorage<int&&>::Type should be StoreCopyPassByRRef<int>");
  static_assert(
      std::is_same_v<::detail::ParameterStorage<int&&>::Type::stored_type,
                     StoreCopyPassByRRef<int>::stored_type>,
      "ParameterStorage<int&&>::Type::stored_type should be "
      "StoreCopyPassByRRef<int>::stored_type");
  static_assert(
      std::is_same_v<::detail::ParameterStorage<int&&>::Type::stored_type, int>,
      "ParameterStorage<int&&>::Type::stored_type should be int");
  static_assert(
      std::is_same_v<::detail::ParameterStorage<int&&>::Type::passed_type,
                     int&&>,
      "ParameterStorage<int&&>::Type::passed_type should be int&&");
  {
    int i = 14;
    r1 = NewRunnableMethod<int&&>(
        "TestThreadUtils::ThreadUtilsObject::Test1rri", rpt,
        &ThreadUtilsObject::Test1rri, std::move(i));
  }
  r1->Run();
  EXPECT_EQ(count += 2, rpt->mCount);
  EXPECT_EQ(14, rpt->mA0);

  // Null unique pointer, by semi-implicit store&move with "T&&" syntax.
  static_assert(std::is_same_v<
                    ::detail::ParameterStorage<mozilla::UniquePtr<int>&&>::Type,
                    StoreCopyPassByRRef<mozilla::UniquePtr<int>>>,
                "ParameterStorage<UniquePtr<int>&&>::Type should be "
                "StoreCopyPassByRRef<UniquePtr<int>>");
  static_assert(
      std::is_same_v<::detail::ParameterStorage<
                         mozilla::UniquePtr<int>&&>::Type::stored_type,
                     StoreCopyPassByRRef<mozilla::UniquePtr<int>>::stored_type>,
      "ParameterStorage<UniquePtr<int>&&>::Type::stored_type should be "
      "StoreCopyPassByRRef<UniquePtr<int>>::stored_type");
  static_assert(
      std::is_same_v<::detail::ParameterStorage<
                         mozilla::UniquePtr<int>&&>::Type::stored_type,
                     mozilla::UniquePtr<int>>,
      "ParameterStorage<UniquePtr<int>&&>::Type::stored_type should be "
      "UniquePtr<int>");
  static_assert(
      std::is_same_v<::detail::ParameterStorage<
                         mozilla::UniquePtr<int>&&>::Type::passed_type,
                     mozilla::UniquePtr<int>&&>,
      "ParameterStorage<UniquePtr<int>&&>::Type::passed_type should be "
      "UniquePtr<int>&&");
  {
    mozilla::UniquePtr<int> upi;
    r1 = NewRunnableMethod<mozilla::UniquePtr<int>&&>(
        "TestThreadUtils::ThreadUtilsObject::Test1upi", rpt,
        &ThreadUtilsObject::Test1upi, std::move(upi));
  }
  r1->Run();
  EXPECT_EQ(count += 2, rpt->mCount);
  EXPECT_EQ(-1, rpt->mA0);
  rpt->mA0 = 0;

  // Null unique pointer, by explicit store&move with "StoreCopyPassByRRef<T>"
  // syntax.
  static_assert(
      std::is_same_v<::detail::ParameterStorage<StoreCopyPassByRRef<
                         mozilla::UniquePtr<int>>>::Type::stored_type,
                     StoreCopyPassByRRef<mozilla::UniquePtr<int>>::stored_type>,
      "ParameterStorage<StoreCopyPassByRRef<UniquePtr<int>>>::Type::stored_"
      "type should be StoreCopyPassByRRef<UniquePtr<int>>::stored_type");
  static_assert(
      std::is_same_v<::detail::ParameterStorage<StoreCopyPassByRRef<
                         mozilla::UniquePtr<int>>>::Type::stored_type,
                     StoreCopyPassByRRef<mozilla::UniquePtr<int>>::stored_type>,
      "ParameterStorage<StoreCopyPassByRRef<UniquePtr<int>>>::Type::stored_"
      "type should be StoreCopyPassByRRef<UniquePtr<int>>::stored_type");
  static_assert(
      std::is_same_v<::detail::ParameterStorage<StoreCopyPassByRRef<
                         mozilla::UniquePtr<int>>>::Type::stored_type,
                     mozilla::UniquePtr<int>>,
      "ParameterStorage<StoreCopyPassByRRef<UniquePtr<int>>>::Type::stored_"
      "type should be UniquePtr<int>");
  static_assert(
      std::is_same_v<::detail::ParameterStorage<StoreCopyPassByRRef<
                         mozilla::UniquePtr<int>>>::Type::passed_type,
                     mozilla::UniquePtr<int>&&>,
      "ParameterStorage<StoreCopyPassByRRef<UniquePtr<int>>>::Type::passed_"
      "type should be UniquePtr<int>&&");
  {
    mozilla::UniquePtr<int> upi;
    r1 = NewRunnableMethod<StoreCopyPassByRRef<mozilla::UniquePtr<int>>>(
        "TestThreadUtils::ThreadUtilsObject::Test1upi", rpt,
        &ThreadUtilsObject::Test1upi, std::move(upi));
  }
  r1->Run();
  EXPECT_EQ(count += 2, rpt->mCount);
  EXPECT_EQ(-1, rpt->mA0);

  // Unique pointer as xvalue.
  {
    mozilla::UniquePtr<int> upi = mozilla::MakeUnique<int>(1);
    r1 = NewRunnableMethod<mozilla::UniquePtr<int>&&>(
        "TestThreadUtils::ThreadUtilsObject::Test1upi", rpt,
        &ThreadUtilsObject::Test1upi, std::move(upi));
  }
  r1->Run();
  EXPECT_EQ(count += 2, rpt->mCount);
  EXPECT_EQ(1, rpt->mA0);

  {
    mozilla::UniquePtr<int> upi = mozilla::MakeUnique<int>(1);
    r1 = NewRunnableMethod<StoreCopyPassByRRef<mozilla::UniquePtr<int>>>(
        "TestThreadUtils::ThreadUtilsObject::Test1upi", rpt,
        &ThreadUtilsObject::Test1upi, std::move(upi));
  }
  r1->Run();
  EXPECT_EQ(count += 2, rpt->mCount);
  EXPECT_EQ(1, rpt->mA0);

  // Unique pointer as prvalue.
  r1 = NewRunnableMethod<mozilla::UniquePtr<int>&&>(
      "TestThreadUtils::ThreadUtilsObject::Test1upi", rpt,
      &ThreadUtilsObject::Test1upi, mozilla::MakeUnique<int>(2));
  r1->Run();
  EXPECT_EQ(count += 2, rpt->mCount);
  EXPECT_EQ(2, rpt->mA0);

  // Unique pointer as lvalue to lref.
  {
    mozilla::UniquePtr<int> upi;
    r1 = NewRunnableMethod<mozilla::UniquePtr<int>&>(
        "TestThreadUtils::ThreadUtilsObject::Test1rupi", rpt,
        &ThreadUtilsObject::Test1rupi, upi);
    // Passed as lref, so Run() must be called while local upi is still alive!
    r1->Run();
  }
  EXPECT_EQ(count += 2, rpt->mCount);
  EXPECT_EQ(-1, rpt->mA0);

  // Verify copy/move assumptions.

  Spy::ClearAll();
  if (gDebug) {
    printf("%d - Test: Store copy from lvalue, pass by const lvalue ref\n",
           __LINE__);
  }
  {  // Block around nsCOMPtr lifetime.
    nsCOMPtr<nsIRunnable> r5;
    {  // Block around Spy lifetime.
      if (gDebug) {
        printf("%d - Spy s(20)\n", __LINE__);
      }
      Spy s(20);
      EXPECT_EQ(1, gConstructions);
      EXPECT_EQ(1, gAlive);
      if (gDebug) {
        printf(
            "%d - r5 = "
            "NewRunnableMethod<StoreCopyPassByConstLRef<Spy>>(&TestByConstLRef,"
            " s)\n",
            __LINE__);
      }
      r5 = NewRunnableMethod<StoreCopyPassByConstLRef<Spy>>(
          "TestThreadUtils::ThreadUtilsObject::TestByConstLRef", rpt,
          &ThreadUtilsObject::TestByConstLRef, s);
      EXPECT_EQ(2, gAlive);
      EXPECT_LE(1, gCopyConstructions);  // At least 1 copy-construction.
      Spy::ClearActions();
      if (gDebug) {
        printf("%d - End block with Spy s(20)\n", __LINE__);
      }
    }
    EXPECT_EQ(1, gDestructions);
    EXPECT_EQ(1, gAlive);
    Spy::ClearActions();
    if (gDebug) {
      printf("%d - Run()\n", __LINE__);
    }
    r5->Run();
    EXPECT_EQ(0, gCopyConstructions);  // No copies in call.
    EXPECT_EQ(20, rpt->mSpy.mID);
    EXPECT_EQ(0, gDestructions);
    EXPECT_EQ(1, gAlive);
    Spy::ClearActions();
    if (gDebug) {
      printf("%d - End block with r\n", __LINE__);
    }
  }
  if (gDebug) {
    printf("%d - After end block with r\n", __LINE__);
  }
  EXPECT_EQ(1, gDestructions);
  EXPECT_EQ(0, gAlive);

  Spy::ClearAll();
  if (gDebug) {
    printf("%d - Test: Store copy from prvalue, pass by const lvalue ref\n",
           __LINE__);
  }
  {
    if (gDebug) {
      printf(
          "%d - r6 = "
          "NewRunnableMethod<StoreCopyPassByConstLRef<Spy>>(&TestByConstLRef, "
          "Spy(21))\n",
          __LINE__);
    }
    nsCOMPtr<nsIRunnable> r6 = NewRunnableMethod<StoreCopyPassByConstLRef<Spy>>(
        "TestThreadUtils::ThreadUtilsObject::TestByConstLRef", rpt,
        &ThreadUtilsObject::TestByConstLRef, Spy(21));
    EXPECT_EQ(1, gAlive);
    EXPECT_EQ(1, gConstructions);
    EXPECT_LE(1, gMoveConstructions);
    Spy::ClearActions();
    if (gDebug) {
      printf("%d - Run()\n", __LINE__);
    }
    r6->Run();
    EXPECT_EQ(0, gCopyConstructions);  // No copies in call.
    EXPECT_EQ(21, rpt->mSpy.mID);
    EXPECT_EQ(0, gDestructions);
    EXPECT_EQ(1, gAlive);
    Spy::ClearActions();
    if (gDebug) {
      printf("%d - End block with r\n", __LINE__);
    }
  }
  if (gDebug) {
    printf("%d - After end block with r\n", __LINE__);
  }
  EXPECT_EQ(1, gDestructions);
  EXPECT_EQ(0, gAlive);

  Spy::ClearAll();
  if (gDebug) {
    printf("%d - Test: Store copy from lvalue, pass by rvalue ref\n", __LINE__);
  }
  {  // Block around nsCOMPtr lifetime.
    nsCOMPtr<nsIRunnable> r7;
    {  // Block around Spy lifetime.
      if (gDebug) {
        printf("%d - Spy s(30)\n", __LINE__);
      }
      Spy s(30);
      EXPECT_EQ(1, gConstructions);
      EXPECT_EQ(1, gAlive);
      if (gDebug) {
        printf(
            "%d - r7 = "
            "NewRunnableMethod<StoreCopyPassByRRef<Spy>>(&TestByRRef, s)\n",
            __LINE__);
      }
      r7 = NewRunnableMethod<StoreCopyPassByRRef<Spy>>(
          "TestThreadUtils::ThreadUtilsObject::TestByRRef", rpt,
          &ThreadUtilsObject::TestByRRef, s);
      EXPECT_EQ(2, gAlive);
      EXPECT_LE(1, gCopyConstructions);  // At least 1 copy-construction.
      Spy::ClearActions();
      if (gDebug) {
        printf("%d - End block with Spy s(30)\n", __LINE__);
      }
    }
    EXPECT_EQ(1, gDestructions);
    EXPECT_EQ(1, gAlive);
    Spy::ClearActions();
    if (gDebug) {
      printf("%d - Run()\n", __LINE__);
    }
    r7->Run();
    EXPECT_LE(1, gMoves);  // Move in call.
    EXPECT_EQ(30, rpt->mSpy.mID);
    EXPECT_EQ(0, gDestructions);
    EXPECT_EQ(0, gAlive);    // Spy inside Test is not counted.
    EXPECT_EQ(1, gZombies);  // Our local spy should now be a zombie.
    Spy::ClearActions();
    if (gDebug) {
      printf("%d - End block with r\n", __LINE__);
    }
  }
  if (gDebug) {
    printf("%d - After end block with r\n", __LINE__);
  }
  EXPECT_EQ(1, gDestructions);
  EXPECT_EQ(0, gAlive);

  Spy::ClearAll();
  if (gDebug) {
    printf("%d - Test: Store copy from prvalue, pass by rvalue ref\n",
           __LINE__);
  }
  {
    if (gDebug) {
      printf(
          "%d - r8 = NewRunnableMethod<StoreCopyPassByRRef<Spy>>(&TestByRRef, "
          "Spy(31))\n",
          __LINE__);
    }
    nsCOMPtr<nsIRunnable> r8 = NewRunnableMethod<StoreCopyPassByRRef<Spy>>(
        "TestThreadUtils::ThreadUtilsObject::TestByRRef", rpt,
        &ThreadUtilsObject::TestByRRef, Spy(31));
    EXPECT_EQ(1, gAlive);
    EXPECT_EQ(1, gConstructions);
    EXPECT_LE(1, gMoveConstructions);
    Spy::ClearActions();
    if (gDebug) {
      printf("%d - Run()\n", __LINE__);
    }
    r8->Run();
    EXPECT_LE(1, gMoves);  // Move in call.
    EXPECT_EQ(31, rpt->mSpy.mID);
    EXPECT_EQ(0, gDestructions);
    EXPECT_EQ(0, gAlive);    // Spy inside Test is not counted.
    EXPECT_EQ(1, gZombies);  // Our local spy should now be a zombie.
    Spy::ClearActions();
    if (gDebug) {
      printf("%d - End block with r\n", __LINE__);
    }
  }
  if (gDebug) {
    printf("%d - After end block with r\n", __LINE__);
  }
  EXPECT_EQ(1, gDestructions);
  EXPECT_EQ(0, gAlive);

  Spy::ClearAll();
  if (gDebug) {
    printf("%d - Test: Store lvalue ref, pass lvalue ref\n", __LINE__);
  }
  {
    if (gDebug) {
      printf("%d - Spy s(40)\n", __LINE__);
    }
    Spy s(40);
    EXPECT_EQ(1, gConstructions);
    EXPECT_EQ(1, gAlive);
    Spy::ClearActions();
    if (gDebug) {
      printf("%d - r9 = NewRunnableMethod<Spy&>(&TestByLRef, s)\n", __LINE__);
    }
    nsCOMPtr<nsIRunnable> r9 = NewRunnableMethod<Spy&>(
        "TestThreadUtils::ThreadUtilsObject::TestByLRef", rpt,
        &ThreadUtilsObject::TestByLRef, s);
    EXPECT_EQ(0, gAllConstructions);
    EXPECT_EQ(0, gDestructions);
    EXPECT_EQ(1, gAlive);
    Spy::ClearActions();
    if (gDebug) {
      printf("%d - Run()\n", __LINE__);
    }
    r9->Run();
    EXPECT_LE(1, gAssignments);  // Assignment from reference in call.
    EXPECT_EQ(40, rpt->mSpy.mID);
    EXPECT_EQ(&s, rpt->mSpyPtr);
    EXPECT_EQ(0, gDestructions);
    EXPECT_EQ(1, gAlive);  // Spy inside Test is not counted.
    Spy::ClearActions();
    if (gDebug) {
      printf("%d - End block with r\n", __LINE__);
    }
  }
  if (gDebug) {
    printf("%d - After end block with r\n", __LINE__);
  }
  EXPECT_EQ(1, gDestructions);
  EXPECT_EQ(0, gAlive);

  Spy::ClearAll();
  if (gDebug) {
    printf("%d - Test: Store nsRefPtr, pass by pointer\n", __LINE__);
  }
  {  // Block around nsCOMPtr lifetime.
    nsCOMPtr<nsIRunnable> r10;
    SpyWithISupports* ptr = 0;
    {  // Block around RefPtr<Spy> lifetime.
      if (gDebug) {
        printf("%d - RefPtr<SpyWithISupports> s(new SpyWithISupports(45))\n",
               __LINE__);
      }
      RefPtr<SpyWithISupports> s(new SpyWithISupports(45));
      ptr = s.get();
      EXPECT_EQ(1, gConstructions);
      EXPECT_EQ(1, gAlive);
      if (gDebug) {
        printf(
            "%d - r10 = "
            "NewRunnableMethod<StoreRefPtrPassByPtr<Spy>>(&TestByRRef, "
            "s.get())\n",
            __LINE__);
      }
      r10 = NewRunnableMethod<StoreRefPtrPassByPtr<SpyWithISupports>>(
          "TestThreadUtils::ThreadUtilsObject::TestByPointer", rpt,
          &ThreadUtilsObject::TestByPointer, s.get());
      EXPECT_LE(0, gAllConstructions);
      EXPECT_EQ(1, gAlive);
      Spy::ClearActions();
      if (gDebug) {
        printf("%d - End block with RefPtr<Spy> s\n", __LINE__);
      }
    }
    EXPECT_EQ(0, gDestructions);
    EXPECT_EQ(1, gAlive);
    Spy::ClearActions();
    if (gDebug) {
      printf("%d - Run()\n", __LINE__);
    }
    r10->Run();
    EXPECT_LE(1, gAssignments);  // Assignment from pointee in call.
    EXPECT_EQ(45, rpt->mSpy.mID);
    EXPECT_EQ(ptr, rpt->mSpyPtr);
    EXPECT_EQ(0, gDestructions);
    EXPECT_EQ(1, gAlive);  // Spy inside Test is not counted.
    Spy::ClearActions();
    if (gDebug) {
      printf("%d - End block with r\n", __LINE__);
    }
  }
  if (gDebug) {
    printf("%d - After end block with r\n", __LINE__);
  }
  EXPECT_EQ(1, gDestructions);
  EXPECT_EQ(0, gAlive);

  Spy::ClearAll();
  if (gDebug) {
    printf("%d - Test: Store pointer to lvalue, pass by pointer\n", __LINE__);
  }
  {
    if (gDebug) {
      printf("%d - Spy s(55)\n", __LINE__);
    }
    Spy s(55);
    EXPECT_EQ(1, gConstructions);
    EXPECT_EQ(1, gAlive);
    Spy::ClearActions();
    if (gDebug) {
      printf("%d - r11 = NewRunnableMethod<Spy*>(&TestByPointer, s)\n",
             __LINE__);
    }
    nsCOMPtr<nsIRunnable> r11 = NewRunnableMethod<Spy*>(
        "TestThreadUtils::ThreadUtilsObject::TestByPointer", rpt,
        &ThreadUtilsObject::TestByPointer, &s);
    EXPECT_EQ(0, gAllConstructions);
    EXPECT_EQ(0, gDestructions);
    EXPECT_EQ(1, gAlive);
    Spy::ClearActions();
    if (gDebug) {
      printf("%d - Run()\n", __LINE__);
    }
    r11->Run();
    EXPECT_LE(1, gAssignments);  // Assignment from pointee in call.
    EXPECT_EQ(55, rpt->mSpy.mID);
    EXPECT_EQ(&s, rpt->mSpyPtr);
    EXPECT_EQ(0, gDestructions);
    EXPECT_EQ(1, gAlive);  // Spy inside Test is not counted.
    Spy::ClearActions();
    if (gDebug) {
      printf("%d - End block with r\n", __LINE__);
    }
  }
  if (gDebug) {
    printf("%d - After end block with r\n", __LINE__);
  }
  EXPECT_EQ(1, gDestructions);
  EXPECT_EQ(0, gAlive);

  Spy::ClearAll();
  if (gDebug) {
    printf("%d - Test: Store pointer to const lvalue, pass by pointer\n",
           __LINE__);
  }
  {
    if (gDebug) {
      printf("%d - Spy s(60)\n", __LINE__);
    }
    Spy s(60);
    EXPECT_EQ(1, gConstructions);
    EXPECT_EQ(1, gAlive);
    Spy::ClearActions();
    if (gDebug) {
      printf("%d - r12 = NewRunnableMethod<Spy*>(&TestByPointer, s)\n",
             __LINE__);
    }
    nsCOMPtr<nsIRunnable> r12 = NewRunnableMethod<const Spy*>(
        "TestThreadUtils::ThreadUtilsObject::TestByPointerToConst", rpt,
        &ThreadUtilsObject::TestByPointerToConst, &s);
    EXPECT_EQ(0, gAllConstructions);
    EXPECT_EQ(0, gDestructions);
    EXPECT_EQ(1, gAlive);
    Spy::ClearActions();
    if (gDebug) {
      printf("%d - Run()\n", __LINE__);
    }
    r12->Run();
    EXPECT_LE(1, gAssignments);  // Assignment from pointee in call.
    EXPECT_EQ(60, rpt->mSpy.mID);
    EXPECT_EQ(&s, rpt->mSpyPtr);
    EXPECT_EQ(0, gDestructions);
    EXPECT_EQ(1, gAlive);  // Spy inside Test is not counted.
    Spy::ClearActions();
    if (gDebug) {
      printf("%d - End block with r\n", __LINE__);
    }
  }
  if (gDebug) {
    printf("%d - After end block with r\n", __LINE__);
  }
  EXPECT_EQ(1, gDestructions);
  EXPECT_EQ(0, gAlive);
}