summaryrefslogtreecommitdiffstats
blob: 597a6bb90effc170d7ebbb7ac1af9a3ecaf527c9 (plain) (blame)
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
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
/*
 * Copyright (C) 2013-2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <pthread.h>
#include <semaphore.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

#include <string>

#include <android-base/file.h>
#include <android-base/stringprintf.h>
#ifdef __ANDROID__  // includes sys/properties.h which does not exist outside
#include <cutils/properties.h>
#endif
#include <gtest/gtest.h>
#include <log/log_event_list.h>
#include <log/log_properties.h>
#include <log/log_transport.h>
#include <log/logprint.h>
#include <private/android_filesystem_config.h>
#include <private/android_logger.h>

#ifndef TEST_PREFIX
#ifdef TEST_LOGGER
#define TEST_PREFIX android_set_log_transport(TEST_LOGGER);
// make sure we always run code despite overrides if compiled for android
#elif defined(__ANDROID__)
#define TEST_PREFIX
#endif
#endif

#if (!defined(USING_LOGGER_DEFAULT) || !defined(USING_LOGGER_LOCAL) || \
     !defined(USING_LOGGER_STDERR))
#ifdef liblog  // a binary clue that we are overriding the test names
// Does not support log reading blocking feature yet
// Does not support LOG_ID_SECURITY (unless we set LOGGER_LOCAL | LOGGER_LOGD)
// Assume some common aspects are tested by USING_LOGGER_DEFAULT:
// Does not need to _retest_ pmsg functionality
// Does not need to _retest_ property handling as it is a higher function
// Does not need to _retest_ event mapping functionality
// Does not need to _retest_ ratelimit
// Does not need to _retest_ logprint
#define USING_LOGGER_LOCAL
#else
#define USING_LOGGER_DEFAULT
#endif
#endif
#ifdef USING_LOGGER_STDERR
#define SUPPORTS_END_TO_END 0
#else
#define SUPPORTS_END_TO_END 1
#endif

// enhanced version of LOG_FAILURE_RETRY to add support for EAGAIN and
// non-syscall libs. Since we are only using this in the emergency of
// a signal to stuff a terminating code into the logs, we will spin rather
// than try a usleep.
#define LOG_FAILURE_RETRY(exp)                                           \
  ({                                                                     \
    typeof(exp) _rc;                                                     \
    do {                                                                 \
      _rc = (exp);                                                       \
    } while (((_rc == -1) && ((errno == EINTR) || (errno == EAGAIN))) || \
             (_rc == -EINTR) || (_rc == -EAGAIN));                       \
    _rc;                                                                 \
  })

TEST(liblog, __android_log_btwrite) {
#ifdef TEST_PREFIX
  TEST_PREFIX
#endif
  int intBuf = 0xDEADBEEF;
  EXPECT_LT(0,
            __android_log_btwrite(0, EVENT_TYPE_INT, &intBuf, sizeof(intBuf)));
  long long longBuf = 0xDEADBEEFA55A5AA5;
  EXPECT_LT(
      0, __android_log_btwrite(0, EVENT_TYPE_LONG, &longBuf, sizeof(longBuf)));
  usleep(1000);
  char Buf[] = "\20\0\0\0DeAdBeEfA55a5aA5";
  EXPECT_LT(0,
            __android_log_btwrite(0, EVENT_TYPE_STRING, Buf, sizeof(Buf) - 1));
  usleep(1000);
}

#if (defined(__ANDROID__) && defined(USING_LOGGER_DEFAULT))
static std::string popenToString(const std::string& command) {
  std::string ret;

  FILE* fp = popen(command.c_str(), "r");
  if (fp) {
    if (!android::base::ReadFdToString(fileno(fp), &ret)) ret = "";
    pclose(fp);
  }
  return ret;
}

#ifndef NO_PSTORE
static bool isPmsgActive() {
  pid_t pid = getpid();

  std::string myPidFds =
      popenToString(android::base::StringPrintf("ls -l /proc/%d/fd", pid));
  if (myPidFds.length() == 0) return true;  // guess it is?

  return std::string::npos != myPidFds.find(" -> /dev/pmsg0");
}
#endif /* NO_PSTORE */

static bool isLogdwActive() {
  std::string logdwSignature =
      popenToString("grep /dev/socket/logdw /proc/net/unix");
  size_t beginning = logdwSignature.find(' ');
  if (beginning == std::string::npos) return true;
  beginning = logdwSignature.find(' ', beginning + 1);
  if (beginning == std::string::npos) return true;
  size_t end = logdwSignature.find(' ', beginning + 1);
  if (end == std::string::npos) return true;
  end = logdwSignature.find(' ', end + 1);
  if (end == std::string::npos) return true;
  end = logdwSignature.find(' ', end + 1);
  if (end == std::string::npos) return true;
  end = logdwSignature.find(' ', end + 1);
  if (end == std::string::npos) return true;
  std::string allLogdwEndpoints = popenToString(
      "grep ' 00000002" + logdwSignature.substr(beginning, end - beginning) +
      " ' /proc/net/unix | " +
      "sed -n 's/.* \\([0-9][0-9]*\\)$/ -> socket:[\\1]/p'");
  if (allLogdwEndpoints.length() == 0) return true;

  // NB: allLogdwEndpoints has some false positives in it, but those
  // strangers do not overlap with the simplistic activities inside this
  // test suite.

  pid_t pid = getpid();

  std::string myPidFds =
      popenToString(android::base::StringPrintf("ls -l /proc/%d/fd", pid));
  if (myPidFds.length() == 0) return true;

  // NB: fgrep with multiple strings is broken in Android
  for (beginning = 0;
       (end = allLogdwEndpoints.find('\n', beginning)) != std::string::npos;
       beginning = end + 1) {
    if (myPidFds.find(allLogdwEndpoints.substr(beginning, end - beginning)) !=
        std::string::npos)
      return true;
  }
  return false;
}

static bool tested__android_log_close;
#endif

TEST(liblog, __android_log_btwrite__android_logger_list_read) {
#if (defined(__ANDROID__) || defined(USING_LOGGER_LOCAL))
#ifdef TEST_PREFIX
  TEST_PREFIX
#endif
  struct logger_list* logger_list;

  pid_t pid = getpid();

  ASSERT_TRUE(NULL !=
              (logger_list = android_logger_list_open(
                   LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
                   1000, pid)));

  log_time ts(CLOCK_MONOTONIC);
  EXPECT_LT(0, __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)));
#ifdef USING_LOGGER_DEFAULT
  // Check that we can close and reopen the logger
  bool logdwActiveAfter__android_log_btwrite;
  if (getuid() == AID_ROOT) {
    tested__android_log_close = true;
#ifndef NO_PSTORE
    bool pmsgActiveAfter__android_log_btwrite = isPmsgActive();
    EXPECT_TRUE(pmsgActiveAfter__android_log_btwrite);
#endif /* NO_PSTORE */
    logdwActiveAfter__android_log_btwrite = isLogdwActive();
    EXPECT_TRUE(logdwActiveAfter__android_log_btwrite);
  } else if (!tested__android_log_close) {
    fprintf(stderr, "WARNING: can not test __android_log_close()\n");
  }
  __android_log_close();
  if (getuid() == AID_ROOT) {
#ifndef NO_PSTORE
    bool pmsgActiveAfter__android_log_close = isPmsgActive();
    EXPECT_FALSE(pmsgActiveAfter__android_log_close);
#endif /* NO_PSTORE */
    bool logdwActiveAfter__android_log_close = isLogdwActive();
    EXPECT_FALSE(logdwActiveAfter__android_log_close);
  }
#endif

  log_time ts1(CLOCK_MONOTONIC);
  EXPECT_LT(0, __android_log_btwrite(0, EVENT_TYPE_LONG, &ts1, sizeof(ts1)));
#ifdef USING_LOGGER_DEFAULT
  if (getuid() == AID_ROOT) {
#ifndef NO_PSTORE
    bool pmsgActiveAfter__android_log_btwrite = isPmsgActive();
    EXPECT_TRUE(pmsgActiveAfter__android_log_btwrite);
#endif /* NO_PSTORE */
    logdwActiveAfter__android_log_btwrite = isLogdwActive();
    EXPECT_TRUE(logdwActiveAfter__android_log_btwrite);
  }
#endif
  usleep(1000000);

  int count = 0;
  int second_count = 0;

  for (;;) {
    log_msg log_msg;
    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
      break;
    }

    EXPECT_EQ(log_msg.entry.pid, pid);

    if ((log_msg.entry.len != sizeof(android_log_event_long_t)) ||
        (log_msg.id() != LOG_ID_EVENTS)) {
      continue;
    }

    android_log_event_long_t* eventData;
    eventData = reinterpret_cast<android_log_event_long_t*>(log_msg.msg());

    if (!eventData || (eventData->payload.type != EVENT_TYPE_LONG)) {
      continue;
    }

    log_time tx(reinterpret_cast<char*>(&eventData->payload.data));
    if (ts == tx) {
      ++count;
    } else if (ts1 == tx) {
      ++second_count;
    }
  }

  EXPECT_EQ(SUPPORTS_END_TO_END, count);
  EXPECT_EQ(SUPPORTS_END_TO_END, second_count);

  android_logger_list_close(logger_list);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

#if (defined(__ANDROID__) || defined(USING_LOGGER_LOCAL))
static void print_transport(const char* prefix, int logger) {
  static const char orstr[] = " | ";

  if (!prefix) {
    prefix = "";
  }
  if (logger < 0) {
    fprintf(stderr, "%s%s\n", prefix, strerror(-logger));
    return;
  }

  if (logger == LOGGER_DEFAULT) {
    fprintf(stderr, "%sLOGGER_DEFAULT", prefix);
    prefix = orstr;
  }
  if (logger & LOGGER_LOGD) {
    fprintf(stderr, "%sLOGGER_LOGD", prefix);
    prefix = orstr;
  }
  if (logger & LOGGER_KERNEL) {
    fprintf(stderr, "%sLOGGER_KERNEL", prefix);
    prefix = orstr;
  }
  if (logger & LOGGER_NULL) {
    fprintf(stderr, "%sLOGGER_NULL", prefix);
    prefix = orstr;
  }
  if (logger & LOGGER_LOCAL) {
    fprintf(stderr, "%sLOGGER_LOCAL", prefix);
    prefix = orstr;
  }
  if (logger & LOGGER_STDERR) {
    fprintf(stderr, "%sLOGGER_STDERR", prefix);
    prefix = orstr;
  }
  logger &= ~(LOGGER_LOGD | LOGGER_KERNEL | LOGGER_NULL | LOGGER_LOCAL |
              LOGGER_STDERR);
  if (logger) {
    fprintf(stderr, "%s0x%x", prefix, logger);
    prefix = orstr;
  }
  if (prefix == orstr) {
    fprintf(stderr, "\n");
  }
}
#endif

// This test makes little sense standalone, and requires the tests ahead
// and behind us, to make us whole.  We could incorporate a prefix and
// suffix test to make this standalone, but opted to not complicate this.
TEST(liblog, android_set_log_transport) {
#if (defined(__ANDROID__) || defined(USING_LOGGER_LOCAL))
#ifdef TEST_PREFIX
  TEST_PREFIX
#endif

  int logger = android_get_log_transport();
  print_transport("android_get_log_transport = ", logger);
  EXPECT_NE(LOGGER_NULL, logger);

  int ret;
  EXPECT_EQ(LOGGER_NULL, ret = android_set_log_transport(LOGGER_NULL));
  print_transport("android_set_log_transport = ", ret);
  EXPECT_EQ(LOGGER_NULL, ret = android_get_log_transport());
  print_transport("android_get_log_transport = ", ret);

  pid_t pid = getpid();

  struct logger_list* logger_list;
  ASSERT_TRUE(NULL !=
              (logger_list = android_logger_list_open(
                   LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
                   1000, pid)));

  log_time ts(CLOCK_MONOTONIC);
  EXPECT_LT(0, __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)));

  usleep(1000000);

  int count = 0;

  for (;;) {
    log_msg log_msg;
    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
      break;
    }

    EXPECT_EQ(log_msg.entry.pid, pid);

    if ((log_msg.entry.len != sizeof(android_log_event_long_t)) ||
        (log_msg.id() != LOG_ID_EVENTS)) {
      continue;
    }

    android_log_event_long_t* eventData;
    eventData = reinterpret_cast<android_log_event_long_t*>(log_msg.msg());

    if (!eventData || (eventData->payload.type != EVENT_TYPE_LONG)) {
      continue;
    }

    log_time tx(reinterpret_cast<char*>(&eventData->payload.data));
    if (ts == tx) {
      ++count;
    }
  }

  android_logger_list_close(logger_list);

  EXPECT_EQ(logger, ret = android_set_log_transport(logger));
  print_transport("android_set_log_transport = ", ret);
  EXPECT_EQ(logger, ret = android_get_log_transport());
  print_transport("android_get_log_transport = ", ret);

  // False negative if liblog.__android_log_btwrite__android_logger_list_read
  // fails above, so we will likely succeed. But we will have so many
  // failures elsewhere that it is probably not worthwhile for us to
  // highlight yet another disappointment.
  //
  // We also expect failures in the following tests if the set does not
  // react in an appropriate manner internally, yet passes, so we depend
  // on this test being in the middle of a series of tests performed in
  // the same process.
  EXPECT_EQ(0, count);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

#ifdef TEST_PREFIX
static inline uint32_t get4LE(const uint8_t* src) {
  return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
}

static inline uint32_t get4LE(const char* src) {
  return get4LE(reinterpret_cast<const uint8_t*>(src));
}
#endif

static void bswrite_test(const char* message) {
#ifdef TEST_PREFIX
  TEST_PREFIX
  struct logger_list* logger_list;

  pid_t pid = getpid();

  ASSERT_TRUE(NULL !=
              (logger_list = android_logger_list_open(
                   LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
                   1000, pid)));

#ifdef __ANDROID__
  log_time ts(android_log_clockid());
#else
  log_time ts(CLOCK_REALTIME);
#endif

  EXPECT_LT(0, __android_log_bswrite(0, message));
  size_t num_lines = 1, size = 0, length = 0, total = 0;
  const char* cp = message;
  while (*cp) {
    if (*cp == '\n') {
      if (cp[1]) {
        ++num_lines;
      }
    } else {
      ++size;
    }
    ++cp;
    ++total;
    ++length;
    if ((LOGGER_ENTRY_MAX_PAYLOAD - 4 - 1 - 4) <= length) {
      break;
    }
  }
  while (*cp) {
    ++cp;
    ++total;
  }
  usleep(1000000);

  int count = 0;

  for (;;) {
    log_msg log_msg;
    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
      break;
    }

    EXPECT_EQ(log_msg.entry.pid, pid);

    if ((log_msg.entry.sec < (ts.tv_sec - 1)) ||
        ((ts.tv_sec + 1) < log_msg.entry.sec) ||
        ((size_t)log_msg.entry.len !=
         (sizeof(android_log_event_string_t) + length)) ||
        (log_msg.id() != LOG_ID_EVENTS)) {
      continue;
    }

    android_log_event_string_t* eventData;
    eventData = reinterpret_cast<android_log_event_string_t*>(log_msg.msg());

    if (!eventData || (eventData->type != EVENT_TYPE_STRING)) {
      continue;
    }

    size_t len = get4LE(reinterpret_cast<char*>(&eventData->length));
    if (len == total) {
      ++count;

      AndroidLogFormat* logformat = android_log_format_new();
      EXPECT_TRUE(NULL != logformat);
      AndroidLogEntry entry;
      char msgBuf[1024];
      if (length != total) {
        fprintf(stderr, "Expect \"Binary log entry conversion failed\"\n");
      }
      int processBinaryLogBuffer = android_log_processBinaryLogBuffer(
          &log_msg.entry_v1, &entry, NULL, msgBuf, sizeof(msgBuf));
      EXPECT_EQ((length == total) ? 0 : -1, processBinaryLogBuffer);
      if ((processBinaryLogBuffer == 0) || entry.message) {
        size_t line_overhead = 20;
        if (pid > 99999) ++line_overhead;
        if (pid > 999999) ++line_overhead;
        fflush(stderr);
        if (processBinaryLogBuffer) {
          EXPECT_GT((int)((line_overhead * num_lines) + size),
                    android_log_printLogLine(logformat, fileno(stderr), &entry));
        } else {
          EXPECT_EQ((int)((line_overhead * num_lines) + size),
                    android_log_printLogLine(logformat, fileno(stderr), &entry));
        }
      }
      android_log_format_free(logformat);
    }
  }

  EXPECT_EQ(SUPPORTS_END_TO_END, count);

  android_logger_list_close(logger_list);
#else
  message = NULL;
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

TEST(liblog, __android_log_bswrite_and_print) {
  bswrite_test("Hello World");
}

TEST(liblog, __android_log_bswrite_and_print__empty_string) {
  bswrite_test("");
}

TEST(liblog, __android_log_bswrite_and_print__newline_prefix) {
  bswrite_test("\nHello World\n");
}

TEST(liblog, __android_log_bswrite_and_print__newline_space_prefix) {
  bswrite_test("\n Hello World \n");
}

TEST(liblog, __android_log_bswrite_and_print__multiple_newline) {
  bswrite_test("one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten");
}

static void buf_write_test(const char* message) {
#ifdef TEST_PREFIX
  TEST_PREFIX
  struct logger_list* logger_list;

  pid_t pid = getpid();

  ASSERT_TRUE(
      NULL !=
      (logger_list = android_logger_list_open(
           LOG_ID_MAIN, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)));

  static const char tag[] = "TEST__android_log_buf_write";
#ifdef __ANDROID__
  log_time ts(android_log_clockid());
#else
  log_time ts(CLOCK_REALTIME);
#endif

  EXPECT_LT(
      0, __android_log_buf_write(LOG_ID_MAIN, ANDROID_LOG_INFO, tag, message));
  size_t num_lines = 1, size = 0, length = 0;
  const char* cp = message;
  while (*cp) {
    if (*cp == '\n') {
      if (cp[1]) {
        ++num_lines;
      }
    } else {
      ++size;
    }
    ++length;
    if ((LOGGER_ENTRY_MAX_PAYLOAD - 2 - sizeof(tag)) <= length) {
      break;
    }
    ++cp;
  }
  usleep(1000000);

  int count = 0;

  for (;;) {
    log_msg log_msg;
    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
      break;
    }

    ASSERT_EQ(log_msg.entry.pid, pid);

    if ((log_msg.entry.sec < (ts.tv_sec - 1)) ||
        ((ts.tv_sec + 1) < log_msg.entry.sec) ||
        ((size_t)log_msg.entry.len != (sizeof(tag) + length + 2)) ||
        (log_msg.id() != LOG_ID_MAIN)) {
      continue;
    }

    ++count;

    AndroidLogFormat* logformat = android_log_format_new();
    EXPECT_TRUE(NULL != logformat);
    AndroidLogEntry entry;
    int processLogBuffer =
        android_log_processLogBuffer(&log_msg.entry_v1, &entry);
    EXPECT_EQ(0, processLogBuffer);
    if (processLogBuffer == 0) {
      size_t line_overhead = 11;
      if (pid > 99999) ++line_overhead;
      if (pid > 999999) ++line_overhead;
      fflush(stderr);
      EXPECT_EQ((int)(((line_overhead + sizeof(tag)) * num_lines) + size),
                android_log_printLogLine(logformat, fileno(stderr), &entry));
    }
    android_log_format_free(logformat);
  }

  EXPECT_EQ(SUPPORTS_END_TO_END, count);

  android_logger_list_close(logger_list);
#else
  message = NULL;
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

TEST(liblog, __android_log_buf_write_and_print__empty) {
  buf_write_test("");
}

TEST(liblog, __android_log_buf_write_and_print__newline_prefix) {
  buf_write_test("\nHello World\n");
}

TEST(liblog, __android_log_buf_write_and_print__newline_space_prefix) {
  buf_write_test("\n Hello World \n");
}

#ifndef USING_LOGGER_LOCAL  // requires blocking reader functionality
#ifdef TEST_PREFIX
static unsigned signaled;
static log_time signal_time;

/*
 *  Strictly, we are not allowed to log messages in a signal context, but we
 * do make an effort to keep the failure surface minimized, and this in-effect
 * should catch any regressions in that effort. The odds of a logged message
 * in a signal handler causing a lockup problem should be _very_ small.
 */
static void caught_blocking_signal(int /*signum*/) {
  unsigned long long v = 0xDEADBEEFA55A0000ULL;

  v += getpid() & 0xFFFF;

  ++signaled;
  if ((signal_time.tv_sec == 0) && (signal_time.tv_nsec == 0)) {
    signal_time = log_time(CLOCK_MONOTONIC);
    signal_time.tv_sec += 2;
  }

  LOG_FAILURE_RETRY(__android_log_btwrite(0, EVENT_TYPE_LONG, &v, sizeof(v)));
}

// Fill in current process user and system time in 10ms increments
static void get_ticks(unsigned long long* uticks, unsigned long long* sticks) {
  *uticks = *sticks = 0;

  pid_t pid = getpid();

  char buffer[512];
  snprintf(buffer, sizeof(buffer), "/proc/%u/stat", pid);

  FILE* fp = fopen(buffer, "r");
  if (!fp) {
    return;
  }

  char* cp = fgets(buffer, sizeof(buffer), fp);
  fclose(fp);
  if (!cp) {
    return;
  }

  pid_t d;
  char s[sizeof(buffer)];
  char c;
  long long ll;
  unsigned long long ull;

  if (15 != sscanf(buffer,
                   "%d %s %c %lld %lld %lld %lld %lld %llu %llu %llu %llu %llu "
                   "%llu %llu ",
                   &d, s, &c, &ll, &ll, &ll, &ll, &ll, &ull, &ull, &ull, &ull,
                   &ull, uticks, sticks)) {
    *uticks = *sticks = 0;
  }
}
#endif

TEST(liblog, android_logger_list_read__cpu_signal) {
#ifdef TEST_PREFIX
  TEST_PREFIX
  struct logger_list* logger_list;
  unsigned long long v = 0xDEADBEEFA55A0000ULL;

  pid_t pid = getpid();

  v += pid & 0xFFFF;

  ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
                           LOG_ID_EVENTS, ANDROID_LOG_RDONLY, 1000, pid)));

  int count = 0;

  int signals = 0;

  unsigned long long uticks_start;
  unsigned long long sticks_start;
  get_ticks(&uticks_start, &sticks_start);

  const unsigned alarm_time = 10;

  memset(&signal_time, 0, sizeof(signal_time));

  signal(SIGALRM, caught_blocking_signal);
  alarm(alarm_time);

  signaled = 0;

  do {
    log_msg log_msg;
    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
      break;
    }

    alarm(alarm_time);

    ++count;

    ASSERT_EQ(log_msg.entry.pid, pid);

    if ((log_msg.entry.len != sizeof(android_log_event_long_t)) ||
        (log_msg.id() != LOG_ID_EVENTS)) {
      continue;
    }

    android_log_event_long_t* eventData;
    eventData = reinterpret_cast<android_log_event_long_t*>(log_msg.msg());

    if (!eventData || (eventData->payload.type != EVENT_TYPE_LONG)) {
      continue;
    }

    char* cp = reinterpret_cast<char*>(&eventData->payload.data);
    unsigned long long l = cp[0] & 0xFF;
    l |= (unsigned long long)(cp[1] & 0xFF) << 8;
    l |= (unsigned long long)(cp[2] & 0xFF) << 16;
    l |= (unsigned long long)(cp[3] & 0xFF) << 24;
    l |= (unsigned long long)(cp[4] & 0xFF) << 32;
    l |= (unsigned long long)(cp[5] & 0xFF) << 40;
    l |= (unsigned long long)(cp[6] & 0xFF) << 48;
    l |= (unsigned long long)(cp[7] & 0xFF) << 56;

    if (l == v) {
      ++signals;
      break;
    }
  } while (!signaled || (log_time(CLOCK_MONOTONIC) < signal_time));
  alarm(0);
  signal(SIGALRM, SIG_DFL);

  EXPECT_LE(1, count);

  EXPECT_EQ(1, signals);

  android_logger_list_close(logger_list);

  unsigned long long uticks_end;
  unsigned long long sticks_end;
  get_ticks(&uticks_end, &sticks_end);

  // Less than 1% in either user or system time, or both
  const unsigned long long one_percent_ticks = alarm_time;
  unsigned long long user_ticks = uticks_end - uticks_start;
  unsigned long long system_ticks = sticks_end - sticks_start;
  EXPECT_GT(one_percent_ticks, user_ticks);
  EXPECT_GT(one_percent_ticks, system_ticks);
  EXPECT_GT(one_percent_ticks, user_ticks + system_ticks);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

#ifdef TEST_PREFIX
/*
 *  Strictly, we are not allowed to log messages in a signal context, the
 * correct way to handle this is to ensure the messages are constructed in
 * a thread; the signal handler should only unblock the thread.
 */
static sem_t thread_trigger;

static void caught_blocking_thread(int /*signum*/) {
  sem_post(&thread_trigger);
}

static void* running_thread(void*) {
  unsigned long long v = 0xDEADBEAFA55A0000ULL;

  v += getpid() & 0xFFFF;

  struct timespec timeout;
  clock_gettime(CLOCK_REALTIME, &timeout);
  timeout.tv_sec += 55;
  sem_timedwait(&thread_trigger, &timeout);

  ++signaled;
  if ((signal_time.tv_sec == 0) && (signal_time.tv_nsec == 0)) {
    signal_time = log_time(CLOCK_MONOTONIC);
    signal_time.tv_sec += 2;
  }

  LOG_FAILURE_RETRY(__android_log_btwrite(0, EVENT_TYPE_LONG, &v, sizeof(v)));

  return NULL;
}

static int start_thread() {
  sem_init(&thread_trigger, 0, 0);

  pthread_attr_t attr;
  if (pthread_attr_init(&attr)) {
    return -1;
  }

  struct sched_param param;

  memset(&param, 0, sizeof(param));
  pthread_attr_setschedparam(&attr, &param);
  pthread_attr_setschedpolicy(&attr, SCHED_BATCH);

  if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) {
    pthread_attr_destroy(&attr);
    return -1;
  }

  pthread_t thread;
  if (pthread_create(&thread, &attr, running_thread, NULL)) {
    pthread_attr_destroy(&attr);
    return -1;
  }

  pthread_attr_destroy(&attr);
  return 0;
}
#endif

TEST(liblog, android_logger_list_read__cpu_thread) {
#ifdef TEST_PREFIX
  TEST_PREFIX
  struct logger_list* logger_list;
  unsigned long long v = 0xDEADBEAFA55A0000ULL;

  pid_t pid = getpid();

  v += pid & 0xFFFF;

  ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
                           LOG_ID_EVENTS, ANDROID_LOG_RDONLY, 1000, pid)));

  int count = 0;

  int signals = 0;

  unsigned long long uticks_start;
  unsigned long long sticks_start;
  get_ticks(&uticks_start, &sticks_start);

  const unsigned alarm_time = 10;

  memset(&signal_time, 0, sizeof(signal_time));

  signaled = 0;
  EXPECT_EQ(0, start_thread());

  signal(SIGALRM, caught_blocking_thread);
  alarm(alarm_time);

  do {
    log_msg log_msg;
    if (LOG_FAILURE_RETRY(android_logger_list_read(logger_list, &log_msg)) <= 0) {
      break;
    }

    alarm(alarm_time);

    ++count;

    ASSERT_EQ(log_msg.entry.pid, pid);

    if ((log_msg.entry.len != sizeof(android_log_event_long_t)) ||
        (log_msg.id() != LOG_ID_EVENTS)) {
      continue;
    }

    android_log_event_long_t* eventData;
    eventData = reinterpret_cast<android_log_event_long_t*>(log_msg.msg());

    if (!eventData || (eventData->payload.type != EVENT_TYPE_LONG)) {
      continue;
    }

    char* cp = reinterpret_cast<char*>(&eventData->payload.data);
    unsigned long long l = cp[0] & 0xFF;
    l |= (unsigned long long)(cp[1] & 0xFF) << 8;
    l |= (unsigned long long)(cp[2] & 0xFF) << 16;
    l |= (unsigned long long)(cp[3] & 0xFF) << 24;
    l |= (unsigned long long)(cp[4] & 0xFF) << 32;
    l |= (unsigned long long)(cp[5] & 0xFF) << 40;
    l |= (unsigned long long)(cp[6] & 0xFF) << 48;
    l |= (unsigned long long)(cp[7] & 0xFF) << 56;

    if (l == v) {
      ++signals;
      break;
    }
  } while (!signaled || (log_time(CLOCK_MONOTONIC) < signal_time));
  alarm(0);
  signal(SIGALRM, SIG_DFL);

  EXPECT_LE(1, count);

  EXPECT_EQ(1, signals);

  android_logger_list_close(logger_list);

  unsigned long long uticks_end;
  unsigned long long sticks_end;
  get_ticks(&uticks_end, &sticks_end);

  // Less than 1% in either user or system time, or both
  const unsigned long long one_percent_ticks = alarm_time;
  unsigned long long user_ticks = uticks_end - uticks_start;
  unsigned long long system_ticks = sticks_end - sticks_start;
  EXPECT_GT(one_percent_ticks, user_ticks);
  EXPECT_GT(one_percent_ticks, system_ticks);
  EXPECT_GT(one_percent_ticks, user_ticks + system_ticks);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}
#endif  // !USING_LOGGER_LOCAL

#ifdef TEST_PREFIX
static const char max_payload_tag[] = "TEST_max_payload_and_longish_tag_XXXX";
#define SIZEOF_MAX_PAYLOAD_BUF \
  (LOGGER_ENTRY_MAX_PAYLOAD - sizeof(max_payload_tag) - 1)
#endif
static const char max_payload_buf[] =
    "LEONATO\n\
I learn in this letter that Don Peter of Arragon\n\
comes this night to Messina\n\
MESSENGER\n\
He is very near by this: he was not three leagues off\n\
when I left him\n\
LEONATO\n\
How many gentlemen have you lost in this action?\n\
MESSENGER\n\
But few of any sort, and none of name\n\
LEONATO\n\
A victory is twice itself when the achiever brings\n\
home full numbers. I find here that Don Peter hath\n\
bestowed much honour on a young Florentine called Claudio\n\
MESSENGER\n\
Much deserved on his part and equally remembered by\n\
Don Pedro: he hath borne himself beyond the\n\
promise of his age, doing, in the figure of a lamb,\n\
the feats of a lion: he hath indeed better\n\
bettered expectation than you must expect of me to\n\
tell you how\n\
LEONATO\n\
He hath an uncle here in Messina will be very much\n\
glad of it.\n\
MESSENGER\n\
I have already delivered him letters, and there\n\
appears much joy in him; even so much that joy could\n\
not show itself modest enough without a badge of\n\
bitterness.\n\
LEONATO\n\
Did he break out into tears?\n\
MESSENGER\n\
In great measure.\n\
LEONATO\n\
A kind overflow of kindness: there are no faces\n\
truer than those that are so washed. How much\n\
better is it to weep at joy than to joy at weeping!\n\
BEATRICE\n\
I pray you, is Signior Mountanto returned from the\n\
wars or no?\n\
MESSENGER\n\
I know none of that name, lady: there was none such\n\
in the army of any sort.\n\
LEONATO\n\
What is he that you ask for, niece?\n\
HERO\n\
My cousin means Signior Benedick of Padua.\n\
MESSENGER\n\
O, he's returned; and as pleasant as ever he was.\n\
BEATRICE\n\
He set up his bills here in Messina and challenged\n\
Cupid at the flight; and my uncle's fool, reading\n\
the challenge, subscribed for Cupid, and challenged\n\
him at the bird-bolt. I pray you, how many hath he\n\
killed and eaten in these wars? But how many hath\n\
he killed? for indeed I promised to eat all of his killing.\n\
LEONATO\n\
Faith, niece, you tax Signior Benedick too much;\n\
but he'll be meet with you, I doubt it not.\n\
MESSENGER\n\
He hath done good service, lady, in these wars.\n\
BEATRICE\n\
You had musty victual, and he hath holp to eat it:\n\
he is a very valiant trencherman; he hath an\n\
excellent stomach.\n\
MESSENGER\n\
And a good soldier too, lady.\n\
BEATRICE\n\
And a good soldier to a lady: but what is he to a lord?\n\
MESSENGER\n\
A lord to a lord, a man to a man; stuffed with all\n\
honourable virtues.\n\
BEATRICE\n\
It is so, indeed; he is no less than a stuffed man:\n\
but for the stuffing,--well, we are all mortal.\n\
LEONATO\n\
You must not, sir, mistake my niece. There is a\n\
kind of merry war betwixt Signior Benedick and her:\n\
they never meet but there's a skirmish of wit\n\
between them.\n\
BEATRICE\n\
Alas! he gets nothing by that. In our last\n\
conflict four of his five wits went halting off, and\n\
now is the whole man governed with one: so that if\n\
he have wit enough to keep himself warm, let him\n\
bear it for a difference between himself and his\n\
horse; for it is all the wealth that he hath left,\n\
to be known a reasonable creature. Who is his\n\
companion now? He hath every month a new sworn brother.\n\
MESSENGER\n\
Is't possible?\n\
BEATRICE\n\
Very easily possible: he wears his faith but as\n\
the fashion of his hat; it ever changes with the\n\
next block.\n\
MESSENGER\n\
I see, lady, the gentleman is not in your books.\n\
BEATRICE\n\
No; an he were, I would burn my study. But, I pray\n\
you, who is his companion? Is there no young\n\
squarer now that will make a voyage with him to the devil?\n\
MESSENGER\n\
He is most in the company of the right noble Claudio.\n\
BEATRICE\n\
O Lord, he will hang upon him like a disease: he\n\
is sooner caught than the pestilence, and the taker\n\
runs presently mad. God help the noble Claudio! if\n\
he have caught the Benedick, it will cost him a\n\
thousand pound ere a' be cured.\n\
MESSENGER\n\
I will hold friends with you, lady.\n\
BEATRICE\n\
Do, good friend.\n\
LEONATO\n\
You will never run mad, niece.\n\
BEATRICE\n\
No, not till a hot January.\n\
MESSENGER\n\
Don Pedro is approached.\n\
Enter DON PEDRO, DON JOHN, CLAUDIO, BENEDICK, and BALTHASAR\n\
\n\
DON PEDRO\n\
Good Signior Leonato, you are come to meet your\n\
trouble: the fashion of the world is to avoid\n\
cost, and you encounter it\n\
LEONATO\n\
Never came trouble to my house in the likeness of your grace,\n\
for trouble being gone, comfort should remain, but\n\
when you depart from me, sorrow abides and happiness\n\
takes his leave.";

TEST(liblog, max_payload) {
#ifdef TEST_PREFIX
  TEST_PREFIX
  pid_t pid = getpid();
  char tag[sizeof(max_payload_tag)];
  memcpy(tag, max_payload_tag, sizeof(tag));
  snprintf(tag + sizeof(tag) - 5, 5, "%04X", pid & 0xFFFF);

  LOG_FAILURE_RETRY(__android_log_buf_write(LOG_ID_SYSTEM, ANDROID_LOG_INFO,
                                            tag, max_payload_buf));
  sleep(2);

  struct logger_list* logger_list;

  ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
                           LOG_ID_SYSTEM, ANDROID_LOG_RDONLY, 100, 0)));

  bool matches = false;
  ssize_t max_len = 0;

  for (;;) {
    log_msg log_msg;
    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
      break;
    }

    if ((log_msg.entry.pid != pid) || (log_msg.id() != LOG_ID_SYSTEM)) {
      continue;
    }

    char* data = log_msg.msg();

    if (!data || strcmp(++data, tag)) {
      continue;
    }

    data += strlen(data) + 1;

    const char* left = data;
    const char* right = max_payload_buf;
    while (*left && *right && (*left == *right)) {
      ++left;
      ++right;
    }

    if (max_len <= (left - data)) {
      max_len = left - data + 1;
    }

    if (max_len > 512) {
      matches = true;
      break;
    }
  }

  android_logger_list_close(logger_list);

#if SUPPORTS_END_TO_END
  EXPECT_EQ(true, matches);

  EXPECT_LE(SIZEOF_MAX_PAYLOAD_BUF, static_cast<size_t>(max_len));
#else
  EXPECT_EQ(false, matches);
#endif
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

TEST(liblog, __android_log_buf_print__maxtag) {
#ifdef TEST_PREFIX
  TEST_PREFIX
  struct logger_list* logger_list;

  pid_t pid = getpid();

  ASSERT_TRUE(
      NULL !=
      (logger_list = android_logger_list_open(
           LOG_ID_MAIN, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)));

#ifdef __ANDROID__
  log_time ts(android_log_clockid());
#else
  log_time ts(CLOCK_REALTIME);
#endif

  EXPECT_LT(0, __android_log_buf_print(LOG_ID_MAIN, ANDROID_LOG_INFO,
                                       max_payload_buf, max_payload_buf));
  usleep(1000000);

  int count = 0;

  for (;;) {
    log_msg log_msg;
    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
      break;
    }

    ASSERT_EQ(log_msg.entry.pid, pid);

    if ((log_msg.entry.sec < (ts.tv_sec - 1)) ||
        ((ts.tv_sec + 1) < log_msg.entry.sec) ||
        ((size_t)log_msg.entry.len < LOGGER_ENTRY_MAX_PAYLOAD) ||
        (log_msg.id() != LOG_ID_MAIN)) {
      continue;
    }

    ++count;

    AndroidLogFormat* logformat = android_log_format_new();
    EXPECT_TRUE(NULL != logformat);
    AndroidLogEntry entry;
    int processLogBuffer =
        android_log_processLogBuffer(&log_msg.entry_v1, &entry);
    EXPECT_EQ(0, processLogBuffer);
    if (processLogBuffer == 0) {
      fflush(stderr);
      int printLogLine =
          android_log_printLogLine(logformat, fileno(stderr), &entry);
      // Legacy tag truncation
      EXPECT_LE(128, printLogLine);
      // Measured maximum if we try to print part of the tag as message
      EXPECT_GT(LOGGER_ENTRY_MAX_PAYLOAD * 13 / 8, printLogLine);
    }
    android_log_format_free(logformat);
  }

  EXPECT_EQ(SUPPORTS_END_TO_END, count);

  android_logger_list_close(logger_list);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

TEST(liblog, too_big_payload) {
#ifdef TEST_PREFIX
  TEST_PREFIX
  pid_t pid = getpid();
  static const char big_payload_tag[] = "TEST_big_payload_XXXX";
  char tag[sizeof(big_payload_tag)];
  memcpy(tag, big_payload_tag, sizeof(tag));
  snprintf(tag + sizeof(tag) - 5, 5, "%04X", pid & 0xFFFF);

  std::string longString(3266519, 'x');

  ssize_t ret = LOG_FAILURE_RETRY(__android_log_buf_write(
      LOG_ID_SYSTEM, ANDROID_LOG_INFO, tag, longString.c_str()));

  struct logger_list* logger_list;

  ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
                           LOG_ID_SYSTEM,
                           ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 100, 0)));

  ssize_t max_len = 0;

  for (;;) {
    log_msg log_msg;
    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
      break;
    }

    if ((log_msg.entry.pid != pid) || (log_msg.id() != LOG_ID_SYSTEM)) {
      continue;
    }

    char* data = log_msg.msg();

    if (!data || strcmp(++data, tag)) {
      continue;
    }

    data += strlen(data) + 1;

    const char* left = data;
    const char* right = longString.c_str();
    while (*left && *right && (*left == *right)) {
      ++left;
      ++right;
    }

    if (max_len <= (left - data)) {
      max_len = left - data + 1;
    }
  }

  android_logger_list_close(logger_list);

#if !SUPPORTS_END_TO_END
  max_len =
      max_len ? max_len : LOGGER_ENTRY_MAX_PAYLOAD - sizeof(big_payload_tag);
#endif
  EXPECT_LE(LOGGER_ENTRY_MAX_PAYLOAD - sizeof(big_payload_tag),
            static_cast<size_t>(max_len));

  // SLOP: Allow the underlying interface to optionally place a
  // terminating nul at the LOGGER_ENTRY_MAX_PAYLOAD's last byte
  // or not.
  if (ret == (max_len + static_cast<ssize_t>(sizeof(big_payload_tag)) - 1)) {
    --max_len;
  }
  EXPECT_EQ(ret, max_len + static_cast<ssize_t>(sizeof(big_payload_tag)));
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

TEST(liblog, dual_reader) {
#ifdef TEST_PREFIX
  TEST_PREFIX

  static const int num = 25;

  for (int i = 25; i > 0; --i) {
    static const char fmt[] = "dual_reader %02d";
    char buffer[sizeof(fmt) + 8];
    snprintf(buffer, sizeof(buffer), fmt, i);
    LOG_FAILURE_RETRY(__android_log_buf_write(LOG_ID_MAIN, ANDROID_LOG_INFO,
                                              "liblog", buffer));
  }
  usleep(1000000);

  struct logger_list* logger_list1;
  ASSERT_TRUE(NULL != (logger_list1 = android_logger_list_open(
                           LOG_ID_MAIN,
                           ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, num, 0)));

  struct logger_list* logger_list2;

  if (NULL == (logger_list2 = android_logger_list_open(
                   LOG_ID_MAIN, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
                   num - 10, 0))) {
    android_logger_list_close(logger_list1);
    ASSERT_TRUE(NULL != logger_list2);
  }

  int count1 = 0;
  bool done1 = false;
  int count2 = 0;
  bool done2 = false;

  do {
    log_msg log_msg;

    if (!done1) {
      if (android_logger_list_read(logger_list1, &log_msg) <= 0) {
        done1 = true;
      } else {
        ++count1;
      }
    }

    if (!done2) {
      if (android_logger_list_read(logger_list2, &log_msg) <= 0) {
        done2 = true;
      } else {
        ++count2;
      }
    }
  } while ((!done1) || (!done2));

  android_logger_list_close(logger_list1);
  android_logger_list_close(logger_list2);

  EXPECT_EQ(num * SUPPORTS_END_TO_END, count1);
  EXPECT_EQ((num - 10) * SUPPORTS_END_TO_END, count2);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

#ifdef USING_LOGGER_DEFAULT  // Do not retest logprint
static bool checkPriForTag(AndroidLogFormat* p_format, const char* tag,
                           android_LogPriority pri) {
  return android_log_shouldPrintLine(p_format, tag, pri) &&
         !android_log_shouldPrintLine(p_format, tag,
                                      (android_LogPriority)(pri - 1));
}

TEST(liblog, filterRule) {
  static const char tag[] = "random";

  AndroidLogFormat* p_format = android_log_format_new();

  android_log_addFilterRule(p_format, "*:i");

  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_INFO));
  EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) ==
              0);
  android_log_addFilterRule(p_format, "*");
  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_DEBUG));
  EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
  android_log_addFilterRule(p_format, "*:v");
  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_VERBOSE));
  EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
  android_log_addFilterRule(p_format, "*:i");
  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_INFO));
  EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) ==
              0);

  android_log_addFilterRule(p_format, tag);
  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_VERBOSE));
  EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
  android_log_addFilterRule(p_format, "random:v");
  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_VERBOSE));
  EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
  android_log_addFilterRule(p_format, "random:d");
  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_DEBUG));
  EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) > 0);
  android_log_addFilterRule(p_format, "random:w");
  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_WARN));
  EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) ==
              0);

  android_log_addFilterRule(p_format, "crap:*");
  EXPECT_TRUE(checkPriForTag(p_format, "crap", ANDROID_LOG_VERBOSE));
  EXPECT_TRUE(
      android_log_shouldPrintLine(p_format, "crap", ANDROID_LOG_VERBOSE) > 0);

  // invalid expression
  EXPECT_TRUE(android_log_addFilterRule(p_format, "random:z") < 0);
  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_WARN));
  EXPECT_TRUE(android_log_shouldPrintLine(p_format, tag, ANDROID_LOG_DEBUG) ==
              0);

  // Issue #550946
  EXPECT_TRUE(android_log_addFilterString(p_format, " ") == 0);
  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_WARN));

  // note trailing space
  EXPECT_TRUE(android_log_addFilterString(p_format, "*:s random:d ") == 0);
  EXPECT_TRUE(checkPriForTag(p_format, tag, ANDROID_LOG_DEBUG));

  EXPECT_TRUE(android_log_addFilterString(p_format, "*:s random:z") < 0);

#if 0  // bitrot, seek update
    char defaultBuffer[512];

    android_log_formatLogLine(p_format,
        defaultBuffer, sizeof(defaultBuffer), 0, ANDROID_LOG_ERROR, 123,
        123, 123, tag, "nofile", strlen("Hello"), "Hello", NULL);

    fprintf(stderr, "%s\n", defaultBuffer);
#endif

  android_log_format_free(p_format);
}
#endif  // USING_LOGGER_DEFAULT

#ifdef USING_LOGGER_DEFAULT  // Do not retest property handling
TEST(liblog, is_loggable) {
#ifdef __ANDROID__
  static const char tag[] = "is_loggable";
  static const char log_namespace[] = "persist.log.tag.";
  static const size_t base_offset = 8; /* skip "persist." */
  // sizeof("string") = strlen("string") + 1
  char key[sizeof(log_namespace) + sizeof(tag) - 1];
  char hold[4][PROP_VALUE_MAX];
  static const struct {
    int level;
    char type;
  } levels[] = {
    { ANDROID_LOG_VERBOSE, 'v' },
    { ANDROID_LOG_DEBUG, 'd' },
    { ANDROID_LOG_INFO, 'i' },
    { ANDROID_LOG_WARN, 'w' },
    { ANDROID_LOG_ERROR, 'e' },
    { ANDROID_LOG_FATAL, 'a' },
    { -1, 's' },
    { -2, 'g' },  // Illegal value, resort to default
  };

  // Set up initial test condition
  memset(hold, 0, sizeof(hold));
  snprintf(key, sizeof(key), "%s%s", log_namespace, tag);
  property_get(key, hold[0], "");
  property_set(key, "");
  property_get(key + base_offset, hold[1], "");
  property_set(key + base_offset, "");
  strcpy(key, log_namespace);
  key[sizeof(log_namespace) - 2] = '\0';
  property_get(key, hold[2], "");
  property_set(key, "");
  property_get(key, hold[3], "");
  property_set(key + base_offset, "");

  // All combinations of level and defaults
  for (size_t i = 0; i < (sizeof(levels) / sizeof(levels[0])); ++i) {
    if (levels[i].level == -2) {
      continue;
    }
    for (size_t j = 0; j < (sizeof(levels) / sizeof(levels[0])); ++j) {
      if (levels[j].level == -2) {
        continue;
      }
      fprintf(stderr, "i=%zu j=%zu\r", i, j);
      bool android_log_is_loggable = __android_log_is_loggable_len(
          levels[i].level, tag, strlen(tag), levels[j].level);
      if ((levels[i].level < levels[j].level) || (levels[j].level == -1)) {
        if (android_log_is_loggable) {
          fprintf(stderr, "\n");
        }
        EXPECT_FALSE(android_log_is_loggable);
        for (size_t k = 10; k; --k) {
          EXPECT_FALSE(__android_log_is_loggable_len(
              levels[i].level, tag, strlen(tag), levels[j].level));
        }
      } else {
        if (!android_log_is_loggable) {
          fprintf(stderr, "\n");
        }
        EXPECT_TRUE(android_log_is_loggable);
        for (size_t k = 10; k; --k) {
          EXPECT_TRUE(__android_log_is_loggable_len(
              levels[i].level, tag, strlen(tag), levels[j].level));
        }
      }
    }
  }

  // All combinations of level and tag and global properties
  for (size_t i = 0; i < (sizeof(levels) / sizeof(levels[0])); ++i) {
    if (levels[i].level == -2) {
      continue;
    }
    for (size_t j = 0; j < (sizeof(levels) / sizeof(levels[0])); ++j) {
      char buf[2];
      buf[0] = levels[j].type;
      buf[1] = '\0';

      snprintf(key, sizeof(key), "%s%s", log_namespace, tag);
      fprintf(stderr, "i=%zu j=%zu property_set(\"%s\",\"%s\")\r", i, j, key,
              buf);
      usleep(20000);
      property_set(key, buf);
      bool android_log_is_loggable = __android_log_is_loggable_len(
          levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG);
      if ((levels[i].level < levels[j].level) || (levels[j].level == -1) ||
          ((levels[i].level < ANDROID_LOG_DEBUG) && (levels[j].level == -2))) {
        if (android_log_is_loggable) {
          fprintf(stderr, "\n");
        }
        EXPECT_FALSE(android_log_is_loggable);
        for (size_t k = 10; k; --k) {
          EXPECT_FALSE(__android_log_is_loggable_len(
              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
        }
      } else {
        if (!android_log_is_loggable) {
          fprintf(stderr, "\n");
        }
        EXPECT_TRUE(android_log_is_loggable);
        for (size_t k = 10; k; --k) {
          EXPECT_TRUE(__android_log_is_loggable_len(
              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
        }
      }
      usleep(20000);
      property_set(key, "");

      fprintf(stderr, "i=%zu j=%zu property_set(\"%s\",\"%s\")\r", i, j,
              key + base_offset, buf);
      property_set(key + base_offset, buf);
      android_log_is_loggable = __android_log_is_loggable_len(
          levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG);
      if ((levels[i].level < levels[j].level) || (levels[j].level == -1) ||
          ((levels[i].level < ANDROID_LOG_DEBUG) && (levels[j].level == -2))) {
        if (android_log_is_loggable) {
          fprintf(stderr, "\n");
        }
        EXPECT_FALSE(android_log_is_loggable);
        for (size_t k = 10; k; --k) {
          EXPECT_FALSE(__android_log_is_loggable_len(
              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
        }
      } else {
        if (!android_log_is_loggable) {
          fprintf(stderr, "\n");
        }
        EXPECT_TRUE(android_log_is_loggable);
        for (size_t k = 10; k; --k) {
          EXPECT_TRUE(__android_log_is_loggable_len(
              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
        }
      }
      usleep(20000);
      property_set(key + base_offset, "");

      strcpy(key, log_namespace);
      key[sizeof(log_namespace) - 2] = '\0';
      fprintf(stderr, "i=%zu j=%zu property_set(\"%s\",\"%s\")\r", i, j, key,
              buf);
      property_set(key, buf);
      android_log_is_loggable = __android_log_is_loggable_len(
          levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG);
      if ((levels[i].level < levels[j].level) || (levels[j].level == -1) ||
          ((levels[i].level < ANDROID_LOG_DEBUG) && (levels[j].level == -2))) {
        if (android_log_is_loggable) {
          fprintf(stderr, "\n");
        }
        EXPECT_FALSE(android_log_is_loggable);
        for (size_t k = 10; k; --k) {
          EXPECT_FALSE(__android_log_is_loggable_len(
              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
        }
      } else {
        if (!android_log_is_loggable) {
          fprintf(stderr, "\n");
        }
        EXPECT_TRUE(android_log_is_loggable);
        for (size_t k = 10; k; --k) {
          EXPECT_TRUE(__android_log_is_loggable_len(
              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
        }
      }
      usleep(20000);
      property_set(key, "");

      fprintf(stderr, "i=%zu j=%zu property_set(\"%s\",\"%s\")\r", i, j,
              key + base_offset, buf);
      property_set(key + base_offset, buf);
      android_log_is_loggable = __android_log_is_loggable_len(
          levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG);
      if ((levels[i].level < levels[j].level) || (levels[j].level == -1) ||
          ((levels[i].level < ANDROID_LOG_DEBUG) && (levels[j].level == -2))) {
        if (android_log_is_loggable) {
          fprintf(stderr, "\n");
        }
        EXPECT_FALSE(android_log_is_loggable);
        for (size_t k = 10; k; --k) {
          EXPECT_FALSE(__android_log_is_loggable_len(
              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
        }
      } else {
        if (!android_log_is_loggable) {
          fprintf(stderr, "\n");
        }
        EXPECT_TRUE(android_log_is_loggable);
        for (size_t k = 10; k; --k) {
          EXPECT_TRUE(__android_log_is_loggable_len(
              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
        }
      }
      usleep(20000);
      property_set(key + base_offset, "");
    }
  }

  // All combinations of level and tag properties, but with global set to INFO
  strcpy(key, log_namespace);
  key[sizeof(log_namespace) - 2] = '\0';
  usleep(20000);
  property_set(key, "I");
  snprintf(key, sizeof(key), "%s%s", log_namespace, tag);
  for (size_t i = 0; i < (sizeof(levels) / sizeof(levels[0])); ++i) {
    if (levels[i].level == -2) {
      continue;
    }
    for (size_t j = 0; j < (sizeof(levels) / sizeof(levels[0])); ++j) {
      char buf[2];
      buf[0] = levels[j].type;
      buf[1] = '\0';

      fprintf(stderr, "i=%zu j=%zu property_set(\"%s\",\"%s\")\r", i, j, key,
              buf);
      usleep(20000);
      property_set(key, buf);
      bool android_log_is_loggable = __android_log_is_loggable_len(
          levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG);
      if ((levels[i].level < levels[j].level) || (levels[j].level == -1) ||
          ((levels[i].level < ANDROID_LOG_INFO)  // Yes INFO
           && (levels[j].level == -2))) {
        if (android_log_is_loggable) {
          fprintf(stderr, "\n");
        }
        EXPECT_FALSE(android_log_is_loggable);
        for (size_t k = 10; k; --k) {
          EXPECT_FALSE(__android_log_is_loggable_len(
              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
        }
      } else {
        if (!android_log_is_loggable) {
          fprintf(stderr, "\n");
        }
        EXPECT_TRUE(android_log_is_loggable);
        for (size_t k = 10; k; --k) {
          EXPECT_TRUE(__android_log_is_loggable_len(
              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
        }
      }
      usleep(20000);
      property_set(key, "");

      fprintf(stderr, "i=%zu j=%zu property_set(\"%s\",\"%s\")\r", i, j,
              key + base_offset, buf);
      property_set(key + base_offset, buf);
      android_log_is_loggable = __android_log_is_loggable_len(
          levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG);
      if ((levels[i].level < levels[j].level) || (levels[j].level == -1) ||
          ((levels[i].level < ANDROID_LOG_INFO)  // Yes INFO
           && (levels[j].level == -2))) {
        if (android_log_is_loggable) {
          fprintf(stderr, "\n");
        }
        EXPECT_FALSE(android_log_is_loggable);
        for (size_t k = 10; k; --k) {
          EXPECT_FALSE(__android_log_is_loggable_len(
              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
        }
      } else {
        if (!android_log_is_loggable) {
          fprintf(stderr, "\n");
        }
        EXPECT_TRUE(android_log_is_loggable);
        for (size_t k = 10; k; --k) {
          EXPECT_TRUE(__android_log_is_loggable_len(
              levels[i].level, tag, strlen(tag), ANDROID_LOG_DEBUG));
        }
      }
      usleep(20000);
      property_set(key + base_offset, "");
    }
  }

  // reset parms
  snprintf(key, sizeof(key), "%s%s", log_namespace, tag);
  usleep(20000);
  property_set(key, hold[0]);
  property_set(key + base_offset, hold[1]);
  strcpy(key, log_namespace);
  key[sizeof(log_namespace) - 2] = '\0';
  property_set(key, hold[2]);
  property_set(key + base_offset, hold[3]);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}
#endif  // USING_LOGGER_DEFAULT

// Following tests the specific issues surrounding error handling wrt logd.
// Kills logd and toss all collected data, equivalent to logcat -b all -c,
// except we also return errors to the logging callers.
#ifdef USING_LOGGER_DEFAULT
#ifdef __ANDROID__
#ifdef TEST_PREFIX
// helper to liblog.enoent to count end-to-end matching logging messages.
static int count_matching_ts(log_time ts) {
  usleep(1000000);

  pid_t pid = getpid();

  struct logger_list* logger_list = android_logger_list_open(
      LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid);

  int count = 0;
  if (logger_list == NULL) return count;

  for (;;) {
    log_msg log_msg;
    if (android_logger_list_read(logger_list, &log_msg) <= 0) break;

    if (log_msg.entry.len != sizeof(android_log_event_long_t)) continue;
    if (log_msg.id() != LOG_ID_EVENTS) continue;

    android_log_event_long_t* eventData;
    eventData = reinterpret_cast<android_log_event_long_t*>(log_msg.msg());
    if (!eventData) continue;
    if (eventData->payload.type != EVENT_TYPE_LONG) continue;

    log_time tx(reinterpret_cast<char*>(&eventData->payload.data));
    if (ts != tx) continue;

    // found event message with matching timestamp signature in payload
    ++count;
  }
  android_logger_list_close(logger_list);

  return count;
}

// meant to be handed to ASSERT_TRUE / EXPECT_TRUE only to expand the message
static testing::AssertionResult IsOk(bool ok, std::string& message) {
  return ok ? testing::AssertionSuccess()
            : (testing::AssertionFailure() << message);
}
#endif  // TEST_PREFIX

TEST(liblog, enoent) {
#ifdef TEST_PREFIX
  TEST_PREFIX
  log_time ts(CLOCK_MONOTONIC);
  EXPECT_LT(0, __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)));
  EXPECT_EQ(SUPPORTS_END_TO_END, count_matching_ts(ts));

  // This call will fail if we are setuid(AID_SYSTEM), beware of any
  // test prior to this one playing with setuid and causing interference.
  // We need to run before these tests so that they do not interfere with
  // this test.
  //
  // Stopping the logger can affect some other test's expectations as they
  // count on the log buffers filled with existing content, and this
  // effectively does a logcat -c emptying it.  So we want this test to be
  // as near as possible to the bottom of the file.  For example
  // liblog.android_logger_get_ is one of those tests that has no recourse
  // and that would be adversely affected by emptying the log if it was run
  // right after this test.
  if (getuid() != AID_ROOT) {
    fprintf(
        stderr,
        "WARNING: test conditions request being run as root and not AID=%d\n",
        getuid());
    if (!__android_log_is_debuggable()) {
      fprintf(
          stderr,
          "WARNING: can not run test on a \"user\" build, bypassing test\n");
      return;
    }
  }

  system((getuid() == AID_ROOT) ? "stop logd" : "su 0 stop logd");
  usleep(1000000);

  // A clean stop like we are testing returns -ENOENT, but in the _real_
  // world we could get -ENOTCONN or -ECONNREFUSED depending on timing.
  // Alas we can not test these other return values; accept that they
  // are treated equally within the open-retry logic in liblog.
  ts = log_time(CLOCK_MONOTONIC);
  int ret = __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts));
  std::string content = android::base::StringPrintf(
      "__android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)) = %d %s\n",
      ret, (ret <= 0) ? strerror(-ret) : "(content sent)");
  EXPECT_TRUE(
      IsOk((ret == -ENOENT) || (ret == -ENOTCONN) || (ret == -ECONNREFUSED),
           content));
  ret = __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts));
  content = android::base::StringPrintf(
      "__android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)) = %d %s\n",
      ret, (ret <= 0) ? strerror(-ret) : "(content sent)");
  EXPECT_TRUE(
      IsOk((ret == -ENOENT) || (ret == -ENOTCONN) || (ret == -ECONNREFUSED),
           content));
  EXPECT_EQ(0, count_matching_ts(ts));

  system((getuid() == AID_ROOT) ? "start logd" : "su 0 start logd");
  usleep(1000000);

  EXPECT_EQ(0, count_matching_ts(ts));

  ts = log_time(CLOCK_MONOTONIC);
  EXPECT_LT(0, __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)));
  EXPECT_EQ(SUPPORTS_END_TO_END, count_matching_ts(ts));

#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}
#endif  // __ANDROID__
#endif  // USING_LOGGER_DEFAULT

// Below this point we run risks of setuid(AID_SYSTEM) which may affect others.

// Do not retest properties, and cannot log into LOG_ID_SECURITY
#ifdef USING_LOGGER_DEFAULT
TEST(liblog, __security) {
#ifdef __ANDROID__
  static const char persist_key[] = "persist.logd.security";
  static const char readonly_key[] = "ro.device_owner";
  // A silly default value that can never be in readonly_key so
  // that it can be determined the property is not set.
  static const char nothing_val[] = "_NOTHING_TO_SEE_HERE_";
  char persist[PROP_VALUE_MAX];
  char persist_hold[PROP_VALUE_MAX];
  char readonly[PROP_VALUE_MAX];

  // First part of this test requires the test itself to have the appropriate
  // permissions. If we do not have them, we can not override them, so we
  // bail rather than give a failing grade.
  property_get(persist_key, persist, "");
  fprintf(stderr, "INFO: getprop %s -> %s\n", persist_key, persist);
  strncpy(persist_hold, persist, PROP_VALUE_MAX);
  property_get(readonly_key, readonly, nothing_val);
  fprintf(stderr, "INFO: getprop %s -> %s\n", readonly_key, readonly);

  if (!strcmp(readonly, nothing_val)) {
    // Lets check if we can set the value (we should not be allowed to do so)
    EXPECT_FALSE(__android_log_security());
    fprintf(stderr, "WARNING: setting ro.device_owner to a domain\n");
    static const char domain[] = "com.google.android.SecOps.DeviceOwner";
    EXPECT_NE(0, property_set(readonly_key, domain));
    useconds_t total_time = 0;
    static const useconds_t seconds = 1000000;
    static const useconds_t max_time = 5 * seconds;  // not going to happen
    static const useconds_t rest = 20 * 1000;
    for (; total_time < max_time; total_time += rest) {
      usleep(rest);  // property system does not guarantee performance.
      property_get(readonly_key, readonly, nothing_val);
      if (!strcmp(readonly, domain)) {
        if (total_time > rest) {
          fprintf(stderr, "INFO: took %u.%06u seconds to set property\n",
                  (unsigned)(total_time / seconds),
                  (unsigned)(total_time % seconds));
        }
        break;
      }
    }
    EXPECT_STRNE(domain, readonly);
  }

  if (!strcasecmp(readonly, "false") || !readonly[0] ||
      !strcmp(readonly, nothing_val)) {
    // not enough permissions to run tests surrounding persist.logd.security
    EXPECT_FALSE(__android_log_security());
    return;
  }

  if (!strcasecmp(persist, "true")) {
    EXPECT_TRUE(__android_log_security());
  } else {
    EXPECT_FALSE(__android_log_security());
  }
  property_set(persist_key, "TRUE");
  property_get(persist_key, persist, "");
  uid_t uid = getuid();
  gid_t gid = getgid();
  bool perm = (gid == AID_ROOT) || (uid == AID_ROOT);
  EXPECT_STREQ(perm ? "TRUE" : persist_hold, persist);
  if (!strcasecmp(persist, "true")) {
    EXPECT_TRUE(__android_log_security());
  } else {
    EXPECT_FALSE(__android_log_security());
  }
  property_set(persist_key, "FALSE");
  property_get(persist_key, persist, "");
  EXPECT_STREQ(perm ? "FALSE" : persist_hold, persist);
  if (!strcasecmp(persist, "true")) {
    EXPECT_TRUE(__android_log_security());
  } else {
    EXPECT_FALSE(__android_log_security());
  }
  property_set(persist_key, "true");
  property_get(persist_key, persist, "");
  EXPECT_STREQ(perm ? "true" : persist_hold, persist);
  if (!strcasecmp(persist, "true")) {
    EXPECT_TRUE(__android_log_security());
  } else {
    EXPECT_FALSE(__android_log_security());
  }
  property_set(persist_key, "false");
  property_get(persist_key, persist, "");
  EXPECT_STREQ(perm ? "false" : persist_hold, persist);
  if (!strcasecmp(persist, "true")) {
    EXPECT_TRUE(__android_log_security());
  } else {
    EXPECT_FALSE(__android_log_security());
  }
  property_set(persist_key, "");
  property_get(persist_key, persist, "");
  EXPECT_STREQ(perm ? "" : persist_hold, persist);
  if (!strcasecmp(persist, "true")) {
    EXPECT_TRUE(__android_log_security());
  } else {
    EXPECT_FALSE(__android_log_security());
  }
  property_set(persist_key, persist_hold);
  property_get(persist_key, persist, "");
  EXPECT_STREQ(persist_hold, persist);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

TEST(liblog, __security_buffer) {
#ifdef __ANDROID__
  struct logger_list* logger_list;
  android_event_long_t buffer;

  static const char persist_key[] = "persist.logd.security";
  char persist[PROP_VALUE_MAX];
  bool set_persist = false;
  bool allow_security = false;

  if (__android_log_security()) {
    allow_security = true;
  } else {
    property_get(persist_key, persist, "");
    if (strcasecmp(persist, "true")) {
      property_set(persist_key, "TRUE");
      if (__android_log_security()) {
        allow_security = true;
        set_persist = true;
      } else {
        property_set(persist_key, persist);
      }
    }
  }

  if (!allow_security) {
    fprintf(stderr,
            "WARNING: "
            "security buffer disabled, bypassing end-to-end test\n");

    log_time ts(CLOCK_MONOTONIC);

    buffer.type = EVENT_TYPE_LONG;
    buffer.data = *(static_cast<uint64_t*>((void*)&ts));

    // expect failure!
    ASSERT_GE(0, __android_log_security_bwrite(0, &buffer, sizeof(buffer)));

    return;
  }

  /* Matches clientHasLogCredentials() in logd */
  uid_t uid = getuid();
  gid_t gid = getgid();
  bool clientHasLogCredentials = true;
  if ((uid != AID_SYSTEM) && (uid != AID_ROOT) && (uid != AID_LOG) &&
      (gid != AID_SYSTEM) && (gid != AID_ROOT) && (gid != AID_LOG)) {
    uid_t euid = geteuid();
    if ((euid != AID_SYSTEM) && (euid != AID_ROOT) && (euid != AID_LOG)) {
      gid_t egid = getegid();
      if ((egid != AID_SYSTEM) && (egid != AID_ROOT) && (egid != AID_LOG)) {
        int num_groups = getgroups(0, NULL);
        if (num_groups > 0) {
          gid_t groups[num_groups];
          num_groups = getgroups(num_groups, groups);
          while (num_groups > 0) {
            if (groups[num_groups - 1] == AID_LOG) {
              break;
            }
            --num_groups;
          }
        }
        if (num_groups <= 0) {
          clientHasLogCredentials = false;
        }
      }
    }
  }
  if (!clientHasLogCredentials) {
    fprintf(stderr,
            "WARNING: "
            "not in system context, bypassing end-to-end test\n");

    log_time ts(CLOCK_MONOTONIC);

    buffer.type = EVENT_TYPE_LONG;
    buffer.data = *(static_cast<uint64_t*>((void*)&ts));

    // expect failure!
    ASSERT_GE(0, __android_log_security_bwrite(0, &buffer, sizeof(buffer)));

    return;
  }

  EXPECT_EQ(0, setuid(AID_SYSTEM));  // only one that can read security buffer

  uid = getuid();
  gid = getgid();
  pid_t pid = getpid();

  ASSERT_TRUE(NULL !=
              (logger_list = android_logger_list_open(
                   LOG_ID_SECURITY, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
                   1000, pid)));

  log_time ts(CLOCK_MONOTONIC);

  buffer.type = EVENT_TYPE_LONG;
  buffer.data = *(static_cast<uint64_t*>((void*)&ts));

  ASSERT_LT(0, __android_log_security_bwrite(0, &buffer, sizeof(buffer)));
  usleep(1000000);

  int count = 0;

  for (;;) {
    log_msg log_msg;
    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
      break;
    }

    ASSERT_EQ(log_msg.entry.pid, pid);

    if ((log_msg.entry.len != sizeof(android_log_event_long_t)) ||
        (log_msg.id() != LOG_ID_SECURITY)) {
      continue;
    }

    android_log_event_long_t* eventData;
    eventData = reinterpret_cast<android_log_event_long_t*>(log_msg.msg());

    if (!eventData || (eventData->payload.type != EVENT_TYPE_LONG)) {
      continue;
    }

    log_time tx(reinterpret_cast<char*>(&eventData->payload.data));
    if (ts == tx) {
      ++count;
    }
  }

  if (set_persist) {
    property_set(persist_key, persist);
  }

  android_logger_list_close(logger_list);

  bool clientHasSecurityCredentials = (uid == AID_SYSTEM) || (gid == AID_SYSTEM);
  if (!clientHasSecurityCredentials) {
    fprintf(stderr,
            "WARNING: "
            "not system, content submitted but can not check end-to-end\n");
  }
  EXPECT_EQ(clientHasSecurityCredentials ? 1 : 0, count);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}
#endif  // USING_LOGGER_DEFAULT

#ifdef TEST_PREFIX
static void android_errorWriteWithInfoLog_helper(int TAG, const char* SUBTAG,
                                                 int UID, const char* payload,
                                                 int DATA_LEN, int& count) {
  TEST_PREFIX
  struct logger_list* logger_list;

  pid_t pid = getpid();

  count = 0;

  ASSERT_TRUE(NULL !=
              (logger_list = android_logger_list_open(
                   LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
                   1000, pid)));

  int retval_android_errorWriteWithinInfoLog =
      android_errorWriteWithInfoLog(TAG, SUBTAG, UID, payload, DATA_LEN);
  if (payload) {
    ASSERT_LT(0, retval_android_errorWriteWithinInfoLog);
  } else {
    ASSERT_GT(0, retval_android_errorWriteWithinInfoLog);
  }

  sleep(2);

  for (;;) {
    log_msg log_msg;
    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
      break;
    }

    char* eventData = log_msg.msg();
    if (!eventData) {
      continue;
    }

    char* original = eventData;

    // Tag
    int tag = get4LE(eventData);
    eventData += 4;

    if (tag != TAG) {
      continue;
    }

    if (!payload) {
      // This tag should not have been written because the data was null
      ++count;
      break;
    }

    // List type
    ASSERT_EQ(EVENT_TYPE_LIST, eventData[0]);
    eventData++;

    // Number of elements in list
    ASSERT_EQ(3, eventData[0]);
    eventData++;

    // Element #1: string type for subtag
    ASSERT_EQ(EVENT_TYPE_STRING, eventData[0]);
    eventData++;

    unsigned subtag_len = strlen(SUBTAG);
    if (subtag_len > 32) subtag_len = 32;
    ASSERT_EQ(subtag_len, get4LE(eventData));
    eventData += 4;

    if (memcmp(SUBTAG, eventData, subtag_len)) {
      continue;
    }
    eventData += subtag_len;

    // Element #2: int type for uid
    ASSERT_EQ(EVENT_TYPE_INT, eventData[0]);
    eventData++;

    ASSERT_EQ(UID, (int)get4LE(eventData));
    eventData += 4;

    // Element #3: string type for data
    ASSERT_EQ(EVENT_TYPE_STRING, eventData[0]);
    eventData++;

    size_t dataLen = get4LE(eventData);
    eventData += 4;
    if (DATA_LEN < 512) ASSERT_EQ(DATA_LEN, (int)dataLen);

    if (memcmp(payload, eventData, dataLen)) {
      continue;
    }

    if (DATA_LEN >= 512) {
      eventData += dataLen;
      // 4 bytes for the tag, and max_payload_buf should be truncated.
      ASSERT_LE(4 + 512, eventData - original);       // worst expectations
      ASSERT_GT(4 + DATA_LEN, eventData - original);  // must be truncated
    }

    ++count;
  }

  android_logger_list_close(logger_list);
}
#endif

// Make multiple tests and re-tests orthogonal to prevent falsing.
#ifdef TEST_LOGGER
#define UNIQUE_TAG(X) \
  (0x12340000 + (((X) + sizeof(int) + sizeof(void*)) << 8) + TEST_LOGGER)
#else
#define UNIQUE_TAG(X) \
  (0x12340000 + (((X) + sizeof(int) + sizeof(void*)) << 8) + 0xBA)
#endif

TEST(liblog, android_errorWriteWithInfoLog__android_logger_list_read__typical) {
#ifdef TEST_PREFIX
  int count;
  android_errorWriteWithInfoLog_helper(UNIQUE_TAG(1), "test-subtag", -1,
                                       max_payload_buf, 200, count);
  EXPECT_EQ(SUPPORTS_END_TO_END, count);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

TEST(liblog,
     android_errorWriteWithInfoLog__android_logger_list_read__data_too_large) {
#ifdef TEST_PREFIX
  int count;
  android_errorWriteWithInfoLog_helper(UNIQUE_TAG(2), "test-subtag", -1,
                                       max_payload_buf, sizeof(max_payload_buf),
                                       count);
  EXPECT_EQ(SUPPORTS_END_TO_END, count);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

TEST(liblog,
     android_errorWriteWithInfoLog__android_logger_list_read__null_data) {
#ifdef TEST_PREFIX
  int count;
  android_errorWriteWithInfoLog_helper(UNIQUE_TAG(3), "test-subtag", -1, NULL,
                                       200, count);
  EXPECT_EQ(0, count);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

TEST(liblog,
     android_errorWriteWithInfoLog__android_logger_list_read__subtag_too_long) {
#ifdef TEST_PREFIX
  int count;
  android_errorWriteWithInfoLog_helper(
      UNIQUE_TAG(4), "abcdefghijklmnopqrstuvwxyz now i know my abc", -1,
      max_payload_buf, 200, count);
  EXPECT_EQ(SUPPORTS_END_TO_END, count);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

TEST(liblog, __android_log_bswrite_and_print___max) {
  bswrite_test(max_payload_buf);
}

TEST(liblog, __android_log_buf_write_and_print__max) {
  buf_write_test(max_payload_buf);
}

#ifdef TEST_PREFIX
static void android_errorWriteLog_helper(int TAG, const char* SUBTAG,
                                         int& count) {
  TEST_PREFIX
  struct logger_list* logger_list;

  pid_t pid = getpid();

  count = 0;

  // Do a Before and After on the count to measure the effect. Decrement
  // what we find in Before to set the stage.
  ASSERT_TRUE(NULL !=
              (logger_list = android_logger_list_open(
                   LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
                   1000, pid)));

  for (;;) {
    log_msg log_msg;
    if (android_logger_list_read(logger_list, &log_msg) <= 0) break;

    char* eventData = log_msg.msg();
    if (!eventData) continue;

    // Tag
    int tag = get4LE(eventData);
    eventData += 4;

    if (tag != TAG) continue;

    if (!SUBTAG) {
      // This tag should not have been written because the data was null
      --count;
      break;
    }

    // List type
    eventData++;
    // Number of elements in list
    eventData++;
    // Element #1: string type for subtag
    eventData++;

    eventData += 4;

    if (memcmp(SUBTAG, eventData, strlen(SUBTAG))) continue;
    --count;
  }

  android_logger_list_close(logger_list);

  // Do an After on the count to measure the effect.
  ASSERT_TRUE(NULL !=
              (logger_list = android_logger_list_open(
                   LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
                   1000, pid)));

  int retval_android_errorWriteLog = android_errorWriteLog(TAG, SUBTAG);
  if (SUBTAG) {
    ASSERT_LT(0, retval_android_errorWriteLog);
  } else {
    ASSERT_GT(0, retval_android_errorWriteLog);
  }

  sleep(2);

  for (;;) {
    log_msg log_msg;
    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
      break;
    }

    char* eventData = log_msg.msg();
    if (!eventData) {
      continue;
    }

    // Tag
    int tag = get4LE(eventData);
    eventData += 4;

    if (tag != TAG) {
      continue;
    }

    if (!SUBTAG) {
      // This tag should not have been written because the data was null
      ++count;
      break;
    }

    // List type
    ASSERT_EQ(EVENT_TYPE_LIST, eventData[0]);
    eventData++;

    // Number of elements in list
    ASSERT_EQ(3, eventData[0]);
    eventData++;

    // Element #1: string type for subtag
    ASSERT_EQ(EVENT_TYPE_STRING, eventData[0]);
    eventData++;

    ASSERT_EQ(strlen(SUBTAG), get4LE(eventData));
    eventData += 4;

    if (memcmp(SUBTAG, eventData, strlen(SUBTAG))) {
      continue;
    }
    ++count;
  }

  android_logger_list_close(logger_list);
}
#endif

TEST(liblog, android_errorWriteLog__android_logger_list_read__success) {
#ifdef TEST_PREFIX
  int count;
  android_errorWriteLog_helper(UNIQUE_TAG(5), "test-subtag", count);
  EXPECT_EQ(SUPPORTS_END_TO_END, count);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

TEST(liblog, android_errorWriteLog__android_logger_list_read__null_subtag) {
#ifdef TEST_PREFIX
  int count;
  android_errorWriteLog_helper(UNIQUE_TAG(6), NULL, count);
  EXPECT_EQ(0, count);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

// Do not retest logger list handling
#if (defined(TEST_PREFIX) || !defined(USING_LOGGER_LOCAL))
static int is_real_element(int type) {
  return ((type == EVENT_TYPE_INT) || (type == EVENT_TYPE_LONG) ||
          (type == EVENT_TYPE_STRING) || (type == EVENT_TYPE_FLOAT));
}

static int android_log_buffer_to_string(const char* msg, size_t len,
                                        char* strOut, size_t strOutLen) {
  android_log_context context = create_android_log_parser(msg, len);
  android_log_list_element elem;
  bool overflow = false;
  /* Reserve 1 byte for null terminator. */
  size_t origStrOutLen = strOutLen--;

  if (!context) {
    return -EBADF;
  }

  memset(&elem, 0, sizeof(elem));

  size_t outCount;

  do {
    elem = android_log_read_next(context);
    switch ((int)elem.type) {
      case EVENT_TYPE_LIST:
        if (strOutLen == 0) {
          overflow = true;
        } else {
          *strOut++ = '[';
          strOutLen--;
        }
        break;

      case EVENT_TYPE_LIST_STOP:
        if (strOutLen == 0) {
          overflow = true;
        } else {
          *strOut++ = ']';
          strOutLen--;
        }
        break;

      case EVENT_TYPE_INT:
        /*
         * snprintf also requires room for the null terminator, which
         * we don't care about  but we have allocated enough room for
         * that
         */
        outCount = snprintf(strOut, strOutLen + 1, "%" PRId32, elem.data.int32);
        if (outCount <= strOutLen) {
          strOut += outCount;
          strOutLen -= outCount;
        } else {
          overflow = true;
        }
        break;

      case EVENT_TYPE_LONG:
        /*
         * snprintf also requires room for the null terminator, which
         * we don't care about but we have allocated enough room for
         * that
         */
        outCount = snprintf(strOut, strOutLen + 1, "%" PRId64, elem.data.int64);
        if (outCount <= strOutLen) {
          strOut += outCount;
          strOutLen -= outCount;
        } else {
          overflow = true;
        }
        break;

      case EVENT_TYPE_FLOAT:
        /*
         * snprintf also requires room for the null terminator, which
         * we don't care about but we have allocated enough room for
         * that
         */
        outCount = snprintf(strOut, strOutLen + 1, "%f", elem.data.float32);
        if (outCount <= strOutLen) {
          strOut += outCount;
          strOutLen -= outCount;
        } else {
          overflow = true;
        }
        break;

      default:
        elem.complete = true;
        break;

      case EVENT_TYPE_UNKNOWN:
#if 0  // Ideal purity in the test, we want to complain about UNKNOWN showing up
            if (elem.complete) {
                break;
            }
#endif
        elem.data.string = const_cast<char*>("<unknown>");
        elem.len = strlen(elem.data.string);
      /* FALLTHRU */
      case EVENT_TYPE_STRING:
        if (elem.len <= strOutLen) {
          memcpy(strOut, elem.data.string, elem.len);
          strOut += elem.len;
          strOutLen -= elem.len;
        } else if (strOutLen > 0) {
          /* copy what we can */
          memcpy(strOut, elem.data.string, strOutLen);
          strOut += strOutLen;
          strOutLen = 0;
          overflow = true;
        }
        break;
    }

    if (elem.complete) {
      break;
    }
    /* Determine whether to put a comma or not. */
    if (!overflow &&
        (is_real_element(elem.type) || (elem.type == EVENT_TYPE_LIST_STOP))) {
      android_log_list_element next = android_log_peek_next(context);
      if (!next.complete &&
          (is_real_element(next.type) || (next.type == EVENT_TYPE_LIST))) {
        if (strOutLen == 0) {
          overflow = true;
        } else {
          *strOut++ = ',';
          strOutLen--;
        }
      }
    }
  } while ((elem.type != EVENT_TYPE_UNKNOWN) && !overflow && !elem.complete);

  android_log_destroy(&context);

  if (overflow) {
    if (strOutLen < origStrOutLen) {
      /* leave an indicator */
      *(strOut - 1) = '!';
    } else {
      /* nothing was written at all */
      *strOut++ = '!';
    }
  }
  *strOut++ = '\0';

  if ((elem.type == EVENT_TYPE_UNKNOWN) && !elem.complete) {
    fprintf(stderr, "Binary log entry conversion failed\n");
    return -EINVAL;
  }

  return 0;
}
#endif  // TEST_PREFIX || !USING_LOGGER_LOCAL

#ifdef TEST_PREFIX
static const char* event_test_int32(uint32_t tag, size_t& expected_len) {
  android_log_context ctx;

  EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
  if (!ctx) {
    return NULL;
  }
  EXPECT_LE(0, android_log_write_int32(ctx, 0x40302010));
  EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
  EXPECT_LE(0, android_log_destroy(&ctx));
  EXPECT_TRUE(NULL == ctx);

  expected_len = sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint32_t);

  return "1076895760";
}

static const char* event_test_int64(uint32_t tag, size_t& expected_len) {
  android_log_context ctx;

  EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
  if (!ctx) {
    return NULL;
  }
  EXPECT_LE(0, android_log_write_int64(ctx, 0x8070605040302010));
  EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
  EXPECT_LE(0, android_log_destroy(&ctx));
  EXPECT_TRUE(NULL == ctx);

  expected_len = sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint64_t);

  return "-9191740941672636400";
}

static const char* event_test_list_int64(uint32_t tag, size_t& expected_len) {
  android_log_context ctx;

  EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
  if (!ctx) {
    return NULL;
  }
  EXPECT_LE(0, android_log_write_list_begin(ctx));
  EXPECT_LE(0, android_log_write_int64(ctx, 0x8070605040302010));
  EXPECT_LE(0, android_log_write_list_end(ctx));
  EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
  EXPECT_LE(0, android_log_destroy(&ctx));
  EXPECT_TRUE(NULL == ctx);

  expected_len = sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint8_t) +
                 sizeof(uint8_t) + sizeof(uint64_t);

  return "[-9191740941672636400]";
}

static const char* event_test_simple_automagic_list(uint32_t tag,
                                                    size_t& expected_len) {
  android_log_context ctx;

  EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
  if (!ctx) {
    return NULL;
  }
  // The convenience API where we allow a simple list to be
  // created without explicit begin or end calls.
  EXPECT_LE(0, android_log_write_int32(ctx, 0x40302010));
  EXPECT_LE(0, android_log_write_int64(ctx, 0x8070605040302010));
  EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
  EXPECT_LE(0, android_log_destroy(&ctx));
  EXPECT_TRUE(NULL == ctx);

  expected_len = sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint8_t) +
                 sizeof(uint8_t) + sizeof(uint32_t) + sizeof(uint8_t) +
                 sizeof(uint64_t);

  return "[1076895760,-9191740941672636400]";
}

static const char* event_test_list_empty(uint32_t tag, size_t& expected_len) {
  android_log_context ctx;

  EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
  if (!ctx) {
    return NULL;
  }
  EXPECT_LE(0, android_log_write_list_begin(ctx));
  EXPECT_LE(0, android_log_write_list_end(ctx));
  EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
  EXPECT_LE(0, android_log_destroy(&ctx));
  EXPECT_TRUE(NULL == ctx);

  expected_len = sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint8_t);

  return "[]";
}

static const char* event_test_complex_nested_list(uint32_t tag,
                                                  size_t& expected_len) {
  android_log_context ctx;

  EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
  if (!ctx) {
    return NULL;
  }

  EXPECT_LE(0, android_log_write_list_begin(ctx));  // [
  EXPECT_LE(0, android_log_write_int32(ctx, 0x01020304));
  EXPECT_LE(0, android_log_write_int64(ctx, 0x0102030405060708));
  EXPECT_LE(0, android_log_write_string8(ctx, "Hello World"));
  EXPECT_LE(0, android_log_write_list_begin(ctx));  // [
  EXPECT_LE(0, android_log_write_int32(ctx, 1));
  EXPECT_LE(0, android_log_write_int32(ctx, 2));
  EXPECT_LE(0, android_log_write_int32(ctx, 3));
  EXPECT_LE(0, android_log_write_int32(ctx, 4));
  EXPECT_LE(0, android_log_write_list_end(ctx));  // ]
  EXPECT_LE(0, android_log_write_float32(ctx, 1.0102030405060708));
  EXPECT_LE(0, android_log_write_list_end(ctx));  // ]

  //
  // This one checks for the automagic list creation because a list
  // begin and end was missing for it! This is actually an <oops> corner
  // case, and not the behavior we morally support. The automagic API is to
  // allow for a simple case of a series of objects in a single list. e.g.
  //   int32,int32,int32,string -> [int32,int32,int32,string]
  //
  EXPECT_LE(0, android_log_write_string8(ctx, "dlroW olleH"));

  EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
  EXPECT_LE(0, android_log_destroy(&ctx));
  EXPECT_TRUE(NULL == ctx);

  expected_len = sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint8_t) +
                 sizeof(uint8_t) + sizeof(uint8_t) + sizeof(uint8_t) +
                 sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint64_t) +
                 sizeof(uint8_t) + sizeof(uint32_t) + sizeof("Hello World") -
                 1 + sizeof(uint8_t) + sizeof(uint8_t) +
                 4 * (sizeof(uint8_t) + sizeof(uint32_t)) + sizeof(uint8_t) +
                 sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint32_t) +
                 sizeof("dlroW olleH") - 1;

  return "[[16909060,72623859790382856,Hello World,[1,2,3,4],1.010203],dlroW "
         "olleH]";
}

static const char* event_test_7_level_prefix(uint32_t tag,
                                             size_t& expected_len) {
  android_log_context ctx;

  EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
  if (!ctx) {
    return NULL;
  }
  EXPECT_LE(0, android_log_write_list_begin(ctx));
  EXPECT_LE(0, android_log_write_list_begin(ctx));
  EXPECT_LE(0, android_log_write_list_begin(ctx));
  EXPECT_LE(0, android_log_write_list_begin(ctx));
  EXPECT_LE(0, android_log_write_list_begin(ctx));
  EXPECT_LE(0, android_log_write_list_begin(ctx));
  EXPECT_LE(0, android_log_write_list_begin(ctx));
  EXPECT_LE(0, android_log_write_int32(ctx, 1));
  EXPECT_LE(0, android_log_write_list_end(ctx));
  EXPECT_LE(0, android_log_write_int32(ctx, 2));
  EXPECT_LE(0, android_log_write_list_end(ctx));
  EXPECT_LE(0, android_log_write_int32(ctx, 3));
  EXPECT_LE(0, android_log_write_list_end(ctx));
  EXPECT_LE(0, android_log_write_int32(ctx, 4));
  EXPECT_LE(0, android_log_write_list_end(ctx));
  EXPECT_LE(0, android_log_write_int32(ctx, 5));
  EXPECT_LE(0, android_log_write_list_end(ctx));
  EXPECT_LE(0, android_log_write_int32(ctx, 6));
  EXPECT_LE(0, android_log_write_list_end(ctx));
  EXPECT_LE(0, android_log_write_int32(ctx, 7));
  EXPECT_LE(0, android_log_write_list_end(ctx));
  EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
  EXPECT_LE(0, android_log_destroy(&ctx));
  EXPECT_TRUE(NULL == ctx);

  expected_len = sizeof(uint32_t) + 7 * (sizeof(uint8_t) + sizeof(uint8_t) +
                                         sizeof(uint8_t) + sizeof(uint32_t));

  return "[[[[[[[1],2],3],4],5],6],7]";
}

static const char* event_test_7_level_suffix(uint32_t tag,
                                             size_t& expected_len) {
  android_log_context ctx;

  EXPECT_TRUE(NULL != (ctx = create_android_logger(tag)));
  if (!ctx) {
    return NULL;
  }
  EXPECT_LE(0, android_log_write_list_begin(ctx));
  EXPECT_LE(0, android_log_write_int32(ctx, 1));
  EXPECT_LE(0, android_log_write_list_begin(ctx));
  EXPECT_LE(0, android_log_write_int32(ctx, 2));
  EXPECT_LE(0, android_log_write_list_begin(ctx));
  EXPECT_LE(0, android_log_write_int32(ctx, 3));
  EXPECT_LE(0, android_log_write_list_begin(ctx));
  EXPECT_LE(0, android_log_write_int32(ctx, 4));
  EXPECT_LE(0, android_log_write_list_begin(ctx));
  EXPECT_LE(0, android_log_write_int32(ctx, 5));
  EXPECT_LE(0, android_log_write_list_begin(ctx));
  EXPECT_LE(0, android_log_write_int32(ctx, 6));
  EXPECT_LE(0, android_log_write_list_end(ctx));
  EXPECT_LE(0, android_log_write_list_end(ctx));
  EXPECT_LE(0, android_log_write_list_end(ctx));
  EXPECT_LE(0, android_log_write_list_end(ctx));
  EXPECT_LE(0, android_log_write_list_end(ctx));
  EXPECT_LE(0, android_log_write_list_end(ctx));
  EXPECT_LE(0, android_log_write_list(ctx, LOG_ID_EVENTS));
  EXPECT_LE(0, android_log_destroy(&ctx));
  EXPECT_TRUE(NULL == ctx);

  expected_len = sizeof(uint32_t) + 6 * (sizeof(uint8_t) + sizeof(uint8_t) +
                                         sizeof(uint8_t) + sizeof(uint32_t));

  return "[1,[2,[3,[4,[5,[6]]]]]]";
}

static const char* event_test_android_log_error_write(uint32_t tag,
                                                      size_t& expected_len) {
  EXPECT_LE(
      0, __android_log_error_write(tag, "Hello World", 42, "dlroW olleH", 11));

  expected_len = sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint8_t) +
                 sizeof(uint8_t) + sizeof(uint32_t) + sizeof("Hello World") -
                 1 + sizeof(uint8_t) + sizeof(uint32_t) + sizeof(uint8_t) +
                 sizeof(uint32_t) + sizeof("dlroW olleH") - 1;

  return "[Hello World,42,dlroW olleH]";
}

static const char* event_test_android_log_error_write_null(uint32_t tag,
                                                           size_t& expected_len) {
  EXPECT_LE(0, __android_log_error_write(tag, "Hello World", 42, NULL, 0));

  expected_len = sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint8_t) +
                 sizeof(uint8_t) + sizeof(uint32_t) + sizeof("Hello World") -
                 1 + sizeof(uint8_t) + sizeof(uint32_t) + sizeof(uint8_t) +
                 sizeof(uint32_t) + sizeof("") - 1;

  return "[Hello World,42,]";
}

// make sure all user buffers are flushed
static void print_barrier() {
  std::cout.flush();
  fflush(stdout);
  std::cerr.flush();
  fflush(stderr);  // everything else is paranoia ...
}

static void create_android_logger(const char* (*fn)(uint32_t tag,
                                                    size_t& expected_len)) {
  TEST_PREFIX
  struct logger_list* logger_list;

  pid_t pid = getpid();

  ASSERT_TRUE(NULL !=
              (logger_list = android_logger_list_open(
                   LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
                   1000, pid)));

#ifdef __ANDROID__
  log_time ts(android_log_clockid());
#else
  log_time ts(CLOCK_REALTIME);
#endif

  size_t expected_len;
  const char* expected_string = (*fn)(1005, expected_len);

  if (!expected_string) {
    android_logger_list_close(logger_list);
    return;
  }

  usleep(1000000);

  int count = 0;

  for (;;) {
    log_msg log_msg;
    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
      break;
    }

    ASSERT_EQ(log_msg.entry.pid, pid);

    if ((log_msg.entry.sec < (ts.tv_sec - 1)) ||
        ((ts.tv_sec + 1) < log_msg.entry.sec) ||
        ((size_t)log_msg.entry.len != expected_len) ||
        (log_msg.id() != LOG_ID_EVENTS)) {
      continue;
    }

    char* eventData = log_msg.msg();

    ++count;

    AndroidLogFormat* logformat = android_log_format_new();
    EXPECT_TRUE(NULL != logformat);
    AndroidLogEntry entry;
    char msgBuf[1024];
    int processBinaryLogBuffer = android_log_processBinaryLogBuffer(
        &log_msg.entry_v1, &entry, NULL, msgBuf, sizeof(msgBuf));
    EXPECT_EQ(0, processBinaryLogBuffer);
    if (processBinaryLogBuffer == 0) {
      int line_overhead = 20;
      if (pid > 99999) ++line_overhead;
      if (pid > 999999) ++line_overhead;
      print_barrier();
      int printLogLine =
          android_log_printLogLine(logformat, fileno(stderr), &entry);
      print_barrier();
      EXPECT_EQ(line_overhead + (int)strlen(expected_string), printLogLine);
    }
    android_log_format_free(logformat);

    // test buffer reading API
    int buffer_to_string = -1;
    if (eventData) {
      snprintf(msgBuf, sizeof(msgBuf), "I/[%" PRIu32 "]", get4LE(eventData));
      print_barrier();
      fprintf(stderr, "%-10s(%5u): ", msgBuf, pid);
      memset(msgBuf, 0, sizeof(msgBuf));
      buffer_to_string = android_log_buffer_to_string(
          eventData + sizeof(uint32_t), log_msg.entry.len - sizeof(uint32_t),
          msgBuf, sizeof(msgBuf));
      fprintf(stderr, "%s\n", msgBuf);
      print_barrier();
    }
    EXPECT_EQ(0, buffer_to_string);
    EXPECT_EQ(strlen(expected_string), strlen(msgBuf));
    EXPECT_EQ(0, strcmp(expected_string, msgBuf));
  }

  EXPECT_EQ(SUPPORTS_END_TO_END, count);

  android_logger_list_close(logger_list);
}
#endif

TEST(liblog, create_android_logger_int32) {
#ifdef TEST_PREFIX
  create_android_logger(event_test_int32);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

TEST(liblog, create_android_logger_int64) {
#ifdef TEST_PREFIX
  create_android_logger(event_test_int64);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

TEST(liblog, create_android_logger_list_int64) {
#ifdef TEST_PREFIX
  create_android_logger(event_test_list_int64);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

TEST(liblog, create_android_logger_simple_automagic_list) {
#ifdef TEST_PREFIX
  create_android_logger(event_test_simple_automagic_list);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

TEST(liblog, create_android_logger_list_empty) {
#ifdef TEST_PREFIX
  create_android_logger(event_test_list_empty);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

TEST(liblog, create_android_logger_complex_nested_list) {
#ifdef TEST_PREFIX
  create_android_logger(event_test_complex_nested_list);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

TEST(liblog, create_android_logger_7_level_prefix) {
#ifdef TEST_PREFIX
  create_android_logger(event_test_7_level_prefix);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

TEST(liblog, create_android_logger_7_level_suffix) {
#ifdef TEST_PREFIX
  create_android_logger(event_test_7_level_suffix);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

TEST(liblog, create_android_logger_android_log_error_write) {
#ifdef TEST_PREFIX
  create_android_logger(event_test_android_log_error_write);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

TEST(liblog, create_android_logger_android_log_error_write_null) {
#ifdef TEST_PREFIX
  create_android_logger(event_test_android_log_error_write_null);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

#ifdef USING_LOGGER_DEFAULT  // Do not retest logger list handling
TEST(liblog, create_android_logger_overflow) {
  android_log_context ctx;

  EXPECT_TRUE(NULL != (ctx = create_android_logger(1005)));
  if (ctx) {
    for (size_t i = 0; i < ANDROID_MAX_LIST_NEST_DEPTH; ++i) {
      EXPECT_LE(0, android_log_write_list_begin(ctx));
    }
    EXPECT_GT(0, android_log_write_list_begin(ctx));
    /* One more for good measure, must be permanently unhappy */
    EXPECT_GT(0, android_log_write_list_begin(ctx));
    EXPECT_LE(0, android_log_destroy(&ctx));
    EXPECT_TRUE(NULL == ctx);
  }

  ASSERT_TRUE(NULL != (ctx = create_android_logger(1005)));
  for (size_t i = 0; i < ANDROID_MAX_LIST_NEST_DEPTH; ++i) {
    EXPECT_LE(0, android_log_write_list_begin(ctx));
    EXPECT_LE(0, android_log_write_int32(ctx, i));
  }
  EXPECT_GT(0, android_log_write_list_begin(ctx));
  /* One more for good measure, must be permanently unhappy */
  EXPECT_GT(0, android_log_write_list_begin(ctx));
  EXPECT_LE(0, android_log_destroy(&ctx));
  ASSERT_TRUE(NULL == ctx);
}

TEST(liblog, android_log_write_list_buffer) {
  __android_log_event_list ctx(1005);
  ctx << 1005 << "tag_def"
      << "(tag|1),(name|3),(format|3)";
  std::string buffer(ctx);
  ctx.close();

  char msgBuf[1024];
  memset(msgBuf, 0, sizeof(msgBuf));
  EXPECT_EQ(android_log_buffer_to_string(buffer.data(), buffer.length(), msgBuf,
                                         sizeof(msgBuf)),
            0);
  EXPECT_STREQ(msgBuf, "[1005,tag_def,(tag|1),(name|3),(format|3)]");
}
#endif  // USING_LOGGER_DEFAULT

#ifdef USING_LOGGER_DEFAULT  // Do not retest pmsg functionality
#ifdef __ANDROID__
#ifndef NO_PSTORE
static const char __pmsg_file[] =
    "/data/william-shakespeare/MuchAdoAboutNothing.txt";
#endif /* NO_PSTORE */
#endif

TEST(liblog, __android_log_pmsg_file_write) {
#ifdef __ANDROID__
#ifndef NO_PSTORE
  __android_log_close();
  if (getuid() == AID_ROOT) {
    tested__android_log_close = true;
    bool pmsgActiveAfter__android_log_close = isPmsgActive();
    bool logdwActiveAfter__android_log_close = isLogdwActive();
    EXPECT_FALSE(pmsgActiveAfter__android_log_close);
    EXPECT_FALSE(logdwActiveAfter__android_log_close);
  } else if (!tested__android_log_close) {
    fprintf(stderr, "WARNING: can not test __android_log_close()\n");
  }
  int return__android_log_pmsg_file_write = __android_log_pmsg_file_write(
      LOG_ID_CRASH, ANDROID_LOG_VERBOSE, __pmsg_file, max_payload_buf,
      sizeof(max_payload_buf));
  EXPECT_LT(0, return__android_log_pmsg_file_write);
  if (return__android_log_pmsg_file_write == -ENOMEM) {
    fprintf(stderr,
            "Kernel does not have space allocated to pmsg pstore driver "
            "configured\n");
  } else if (!return__android_log_pmsg_file_write) {
    fprintf(stderr,
            "Reboot, ensure file %s matches\n"
            "with liblog.__android_log_msg_file_read test\n",
            __pmsg_file);
  }
  bool pmsgActiveAfter__android_pmsg_file_write;
  bool logdwActiveAfter__android_pmsg_file_write;
  if (getuid() == AID_ROOT) {
    pmsgActiveAfter__android_pmsg_file_write = isPmsgActive();
    logdwActiveAfter__android_pmsg_file_write = isLogdwActive();
    EXPECT_FALSE(pmsgActiveAfter__android_pmsg_file_write);
    EXPECT_FALSE(logdwActiveAfter__android_pmsg_file_write);
  }
  EXPECT_LT(
      0, __android_log_buf_print(LOG_ID_MAIN, ANDROID_LOG_INFO,
                                 "TEST__android_log_pmsg_file_write", "main"));
  if (getuid() == AID_ROOT) {
    bool pmsgActiveAfter__android_log_buf_print = isPmsgActive();
    bool logdwActiveAfter__android_log_buf_print = isLogdwActive();
    EXPECT_TRUE(pmsgActiveAfter__android_log_buf_print);
    EXPECT_TRUE(logdwActiveAfter__android_log_buf_print);
  }
  EXPECT_LT(0, __android_log_pmsg_file_write(LOG_ID_CRASH, ANDROID_LOG_VERBOSE,
                                             __pmsg_file, max_payload_buf,
                                             sizeof(max_payload_buf)));
  if (getuid() == AID_ROOT) {
    pmsgActiveAfter__android_pmsg_file_write = isPmsgActive();
    logdwActiveAfter__android_pmsg_file_write = isLogdwActive();
    EXPECT_TRUE(pmsgActiveAfter__android_pmsg_file_write);
    EXPECT_TRUE(logdwActiveAfter__android_pmsg_file_write);
  }
#else  /* NO_PSTORE */
  GTEST_LOG_(INFO) << "This test does nothing because of NO_PSTORE.\n";
#endif /* NO_PSTORE */
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}

#ifdef __ANDROID__
#ifndef NO_PSTORE
static ssize_t __pmsg_fn(log_id_t logId, char prio, const char* filename,
                         const char* buf, size_t len, void* arg) {
  EXPECT_TRUE(NULL == arg);
  EXPECT_EQ(LOG_ID_CRASH, logId);
  EXPECT_EQ(ANDROID_LOG_VERBOSE, prio);
  EXPECT_FALSE(NULL == strstr(__pmsg_file, filename));
  EXPECT_EQ(len, sizeof(max_payload_buf));
  EXPECT_EQ(0, strcmp(max_payload_buf, buf));

  ++signaled;
  if ((len != sizeof(max_payload_buf)) || strcmp(max_payload_buf, buf)) {
    fprintf(stderr, "comparison fails on content \"%s\"\n", buf);
  }
  return arg || (LOG_ID_CRASH != logId) || (ANDROID_LOG_VERBOSE != prio) ||
                 !strstr(__pmsg_file, filename) ||
                 (len != sizeof(max_payload_buf)) ||
                 !!strcmp(max_payload_buf, buf)
             ? -ENOEXEC
             : 1;
}
#endif /* NO_PSTORE */
#endif

TEST(liblog, __android_log_pmsg_file_read) {
#ifdef __ANDROID__
#ifndef NO_PSTORE
  signaled = 0;

  __android_log_close();
  if (getuid() == AID_ROOT) {
    tested__android_log_close = true;
    bool pmsgActiveAfter__android_log_close = isPmsgActive();
    bool logdwActiveAfter__android_log_close = isLogdwActive();
    EXPECT_FALSE(pmsgActiveAfter__android_log_close);
    EXPECT_FALSE(logdwActiveAfter__android_log_close);
  } else if (!tested__android_log_close) {
    fprintf(stderr, "WARNING: can not test __android_log_close()\n");
  }

  ssize_t ret = __android_log_pmsg_file_read(LOG_ID_CRASH, ANDROID_LOG_VERBOSE,
                                             __pmsg_file, __pmsg_fn, NULL);

  if (getuid() == AID_ROOT) {
    bool pmsgActiveAfter__android_log_pmsg_file_read = isPmsgActive();
    bool logdwActiveAfter__android_log_pmsg_file_read = isLogdwActive();
    EXPECT_FALSE(pmsgActiveAfter__android_log_pmsg_file_read);
    EXPECT_FALSE(logdwActiveAfter__android_log_pmsg_file_read);
  }

  if (ret == -ENOENT) {
    fprintf(stderr,
            "No pre-boot results of liblog.__android_log_mesg_file_write to "
            "compare with,\n"
            "false positive test result.\n");
    return;
  }

  EXPECT_LT(0, ret);
  EXPECT_EQ(1U, signaled);
#else  /* NO_PSTORE */
  GTEST_LOG_(INFO) << "This test does nothing because of NO_PSTORE.\n";
#endif /* NO_PSTORE */
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}
#endif  // USING_LOGGER_DEFAULT

#ifdef USING_LOGGER_DEFAULT  // Do not retest event mapping functionality
#ifdef __ANDROID__
// must be: '<needle:> 0 kB'
static bool isZero(const std::string& content, std::string::size_type pos,
                   const char* needle) {
  std::string::size_type offset = content.find(needle, pos);
  return (offset != std::string::npos) &&
         ((offset = content.find_first_not_of(" \t", offset + strlen(needle))) !=
          std::string::npos) &&
         (content.find_first_not_of('0', offset) != offset);
}

// must not be: '<needle:> 0 kB'
static bool isNotZero(const std::string& content, std::string::size_type pos,
                      const char* needle) {
  std::string::size_type offset = content.find(needle, pos);
  return (offset != std::string::npos) &&
         ((offset = content.find_first_not_of(" \t", offset + strlen(needle))) !=
          std::string::npos) &&
         (content.find_first_not_of("123456789", offset) != offset);
}

static void event_log_tags_test_smap(pid_t pid) {
  std::string filename = android::base::StringPrintf("/proc/%d/smaps", pid);

  std::string content;
  if (!android::base::ReadFileToString(filename, &content)) return;

  bool shared_ok = false;
  bool private_ok = false;
  bool anonymous_ok = false;
  bool pass_ok = false;

  static const char event_log_tags[] = "event-log-tags";
  std::string::size_type pos = 0;
  while ((pos = content.find(event_log_tags, pos)) != std::string::npos) {
    pos += strlen(event_log_tags);

    // must not be: 'Shared_Clean: 0 kB'
    bool ok =
        isNotZero(content, pos, "Shared_Clean:") ||
        // If not /etc/event-log-tags, thus r/w, then half points
        // back for not 'Shared_Dirty: 0 kB'
        ((content.substr(pos - 5 - strlen(event_log_tags), 5) != "/etc/") &&
         isNotZero(content, pos, "Shared_Dirty:"));
    if (ok && !pass_ok) {
      shared_ok = true;
    } else if (!ok) {
      shared_ok = false;
    }

    // must be: 'Private_Dirty: 0 kB' and 'Private_Clean: 0 kB'
    ok = isZero(content, pos, "Private_Dirty:") ||
         isZero(content, pos, "Private_Clean:");
    if (ok && !pass_ok) {
      private_ok = true;
    } else if (!ok) {
      private_ok = false;
    }

    // must be: 'Anonymous: 0 kB'
    ok = isZero(content, pos, "Anonymous:");
    if (ok && !pass_ok) {
      anonymous_ok = true;
    } else if (!ok) {
      anonymous_ok = false;
    }

    pass_ok = true;
  }
  content = "";

  if (!pass_ok) return;
  if (shared_ok && anonymous_ok && private_ok) return;

  filename = android::base::StringPrintf("/proc/%d/comm", pid);
  android::base::ReadFileToString(filename, &content);
  content = android::base::StringPrintf(
      "%d:%s", pid, content.substr(0, content.find('\n')).c_str());

  EXPECT_TRUE(IsOk(shared_ok, content));
  EXPECT_TRUE(IsOk(private_ok, content));
  EXPECT_TRUE(IsOk(anonymous_ok, content));
}
#endif  // __ANDROID__

TEST(liblog, event_log_tags) {
#ifdef __ANDROID__
  std::unique_ptr<DIR, int (*)(DIR*)> proc_dir(opendir("/proc"), closedir);
  ASSERT_FALSE(!proc_dir);

  dirent* e;
  while ((e = readdir(proc_dir.get()))) {
    if (e->d_type != DT_DIR) continue;
    if (!isdigit(e->d_name[0])) continue;
    long long id = atoll(e->d_name);
    if (id <= 0) continue;
    pid_t pid = id;
    if (id != pid) continue;
    event_log_tags_test_smap(pid);
  }
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}
#endif  // USING_LOGGER_DEFAULT

#ifdef USING_LOGGER_DEFAULT  // Do not retest ratelimit
TEST(liblog, __android_log_ratelimit) {
  time_t state = 0;

  errno = 42;
  // Prime
  __android_log_ratelimit(3, &state);
  EXPECT_EQ(errno, 42);
  // Check
  EXPECT_FALSE(__android_log_ratelimit(3, &state));
  sleep(1);
  EXPECT_FALSE(__android_log_ratelimit(3, &state));
  sleep(4);
  EXPECT_TRUE(__android_log_ratelimit(3, &state));
  sleep(5);
  EXPECT_TRUE(__android_log_ratelimit(3, &state));

  // API checks
  IF_ALOG_RATELIMIT_LOCAL(3, &state) {
    EXPECT_FALSE(0 != "IF_ALOG_RATELIMIT_LOCAL(3, &state)");
  }

  IF_ALOG_RATELIMIT() {
    ;
  }
  else {
    EXPECT_TRUE(0 == "IF_ALOG_RATELIMIT()");
  }
  IF_ALOG_RATELIMIT() {
    EXPECT_FALSE(0 != "IF_ALOG_RATELIMIT()");
  }
  // Do not test default seconds, to allow liblog to tune freely
}
#endif  // USING_LOGGER_DEFAULT

#ifdef USING_LOGGER_DEFAULT  // Do not retest event mapping functionality
TEST(liblog, android_lookupEventTagNum) {
#ifdef __ANDROID__
  EventTagMap* map = android_openEventTagMap(NULL);
  EXPECT_TRUE(NULL != map);
  std::string Name = android::base::StringPrintf("a%d", getpid());
  int tag = android_lookupEventTagNum(map, Name.c_str(), "(new|1)",
                                      ANDROID_LOG_UNKNOWN);
  android_closeEventTagMap(map);
  if (tag == -1) system("tail -3 /dev/event-log-tags >&2");
  EXPECT_NE(-1, tag);
  EXPECT_NE(0, tag);
  EXPECT_GT(UINT32_MAX, (unsigned)tag);
#else
  GTEST_LOG_(INFO) << "This test does nothing.\n";
#endif
}
#endif  // USING_LOGGER_DEFAULT