summaryrefslogtreecommitdiff
path: root/open-vm-tools/lib/misc/msgfmt.c
blob: f3b7826bdfe343ebd8375af8ea41f5b8bda819e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
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
/* **********************************************************
 * Copyright 2007 VMware, Inc.  All rights reserved.
 * **********************************************************/

/*
 * Copyright (c) 1990, 1993
 *   The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Chris Torek.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * msgfmt.c --
 *
 *	MsgFmt: format messages for the Msg module
 */


#ifdef VMKERNEL
   #include "vmkernel.h"
   #include "vm_types.h"
   #include "vm_libc.h"
#else
   #include <stdlib.h>
   #include <stdio.h>
   #include <stdarg.h>
   #include <stddef.h>
   #include <string.h>
   #if defined(__FreeBSD__)
      #include <sys/param.h>
   #endif
   #if !defined(_WIN32) && !defined(SOL9) && \
       (!defined(__FreeBSD__) || __FreeBSD_version >= 500029)
      #include <stdint.h>
   #endif
   #if !defined(__FreeBSD__) || __FreeBSD_version >= 400017
      #include <wchar.h>
   #endif

   #include "vmware.h"
   #include "bsdfmt.h"
   #include "err.h"
#endif

#include "msgfmt.h"

#ifdef HAS_BSD_PRINTF
   #include <limits.h>
   #include <locale.h>
   #include "msgid.h"
#endif

/*
 * Older versions of FreeBSD don't have C99 support (stdint), and also
 * do not have wide character support. Re-implement the stuff we need
 * in those cases.
 */

#if defined(__FreeBSD__) && __FreeBSD_version <= 320001
static INLINE const wchar_t *
wmemchr(const wchar_t *s, wchar_t c, size_t n)
{
   size_t i;
   for (i = 0; i < n; i++) {
      if (s[i] == c) {
         return &s[i];
      }
   }

   return NULL;
}

static INLINE size_t
wcslen(const wchar_t *s)
{
   size_t i;

   for (i = 0; s[i]; i++);

   return i;
}
#endif

/*
 * The vmkernel doesn't have the Str module, malloc(), or
 * some of the standard C string functions.
 * The only ones we really need are Str_Vsnprintf() and memchr().
 */

#ifdef VMKERNEL // {

typedef int32 wchar_t;
typedef int32 wint_t;
typedef int64 intmax_t;
typedef size_t ptrdiff_t;

#define STUB(t, f, a) \
	static INLINE t f a { NOT_IMPLEMENTED(); return (t) 0;}
#define VSTUB(f, a) \
	static INLINE void f a { NOT_IMPLEMENTED(); }
STUB(char *, Str_Vasprintf, (char **b, const char *f, va_list a))
STUB(void *, malloc, (size_t s))
STUB(void *, realloc, (void *p, size_t s))
STUB(wchar_t *, wmemchr, (const wchar_t *s, wchar_t c, size_t n))
STUB(size_t, wcslen, (const wchar_t *s))
STUB(char *, strdup, (const char *s))
VSTUB(free, (void *p))
#undef STUB
#undef VSTUB

typedef int Err_Number;
#define ERR_INVALID (-1)
static INLINE Err_Number
Err_String2Errno(const char *string)
{
   return ERR_INVALID;
}

#ifdef VMX86_DEBUG
static INLINE Err_Number
Err_String2ErrnoDebug(const char *string)
{
   return ERR_INVALID;
}
#endif

static INLINE int
Str_Vsnprintf(char *str, size_t size, const char *format, va_list ap) {
   int n = vsnprintf(str, size, format, ap);
   ASSERT(n >= 0);
   if (n >= size) {
      str[size - 1] = '\0';
      n = -1;
   }
   return n;
}

static INLINE const void *
memchr(const void *s, int c, size_t n)
{
   const uint8 *p = s;
   const uint8 *e = p + n;
   while (p < e) {
      if (*p++ == c) {
	 return p;
      }
   }
   return NULL;
}

#endif // }

#if defined __ANDROID__
/*
 * Android doesn't support dtoa().
 */
#define NO_DTOA
#endif


/*
 * Local data
 */

typedef struct MsgFmtParseState {
   MsgFmt_Arg *args;
   int numArgs;
   int maxArgs;
   char *error;

   /*
    * Allocator state for caller-supplied buffer.
    */

   void *buf;
   char *bufp;
   char *bufe;
} MsgFmtParseState;

/* d, i, o, u, x, X, e, E, f, F, g, G, a, A, c, s, C, S, p, and n --hpreg */
static int const isSpecifier[] = {
   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
   0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
   0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1,
   1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};


/*
 * Local functions
 */

static MsgFmt_SpecFunc MsgFmtGetArg1;
static int MsgFmtAToI(char const **start, char const *end);
static void MsgFmtError(MsgFmtParseState *state, const char *fmt, ...);

static void MsgFmtAllocInit(MsgFmtParseState *state, void *buf, size_t size);
static void *MsgFmtAlloc(MsgFmtParseState *state, size_t size);
static Bool MsgFmtAllocArgs(MsgFmtParseState *state, int n);
static char *MsgFmtVasprintf(MsgFmtParseState *state,
                             const char *fmt, va_list args);
static void MsgFmtFreeAll(MsgFmtParseState *state);
static size_t MsgFmtBufUsed(MsgFmtParseState *state);
#ifdef HAS_BSD_PRINTF
static int MsgFmtSnprintfWork(char **outbuf, size_t bufSize, const char *fmt0,
                              const struct MsgFmt_Arg *args, int numArgs);
#endif


/*
 *-----------------------------------------------------------------------------
 *
 * MsgFmt_ParseWin32 --
 *
 *    Convert the Win32 representation of a format string into another
 *    representation --hpreg
 *
 *    XXX I haven't implemented %0 and %n, because they suck:
 *        . they mix content and presentation
 *        . they have nothing to do with parameters and hence have no
 *          equivalent in other systems
 *
 * Results:
 *     0 on success
 *    -1 on failure: out of memory
 *    -2 on failure: invalid 'in'
 *
 * Side effects:
 *    None
 *
 *-----------------------------------------------------------------------------
 */

int
MsgFmt_ParseWin32(MsgFmt_LitFunc *litFunc,    // IN
                  MsgFmt_SpecFunc *specFunc,  // IN
                  void *clientData,           // IN
                  char const *in)             // IN
{
   char const *startUnescaped;
   unsigned int sm;
   char const *pos = 0 /* Compiler warning --hpreg */;
   char const *type = 0 /* Compiler warning --hpreg */;
   int status;

   startUnescaped = in;
   sm = 0;

   for (; *in != '\0'; in++) {
      /* Unsigned does matter --hpreg */
      unsigned char ubyte;

      ubyte = *in;
      switch (sm) {
      case 2: /* Found %<1-9>...<byte> --hpreg */
         if (ubyte >= '0' && ubyte <= '9') {
            break;
         }
         if (ubyte == '!') {
            type = in + 1;
	    sm = 3;
            break;
         }
         if ((status = (*litFunc)(clientData, startUnescaped,
                                  pos - 1 - startUnescaped)) < 0 ||
             (status = (*specFunc)(clientData, pos, in - pos, "s", 1)) < 0) {
            return status;
         }
         startUnescaped = in;
         sm = 0;
         /* Fall through --hpreg */

      case 0: /* Found <byte> --hpreg */
         if (ubyte == '%') {
            pos = in + 1;
            sm = 1;
         }
         break;

      case 1: /* Found %<byte> --hpreg */
         if (ubyte >= '1' && ubyte <= '9') {
            sm = 2;
         } else {
            ASSERT_NOT_IMPLEMENTED(ubyte != '0' && ubyte != 'n');
            status = (*litFunc)(clientData, startUnescaped,
				in - 1 - startUnescaped);
            if (status < 0) {
               return status;
            }
            startUnescaped = in;
            sm = 0;
         }
         break;

      case 3: /* Found %<1-9>...!...<byte> --hpreg */
         if (ubyte == '!') {
            if (   (status = (*litFunc)(clientData, startUnescaped,
                                        pos - 1 - startUnescaped)) < 0
                || (status = (*specFunc)(clientData, pos, type - 1 - pos,
                		         type, in - type)) < 0) {
               return status;
            }
            startUnescaped = in + 1;
            sm = 0;
         }
         break;

      default:
         NOT_IMPLEMENTED();
         break;
      }
   }

   switch (sm) {
   case 0:
      status = (*litFunc)(clientData, startUnescaped, in - startUnescaped);
      if (status < 0) {
         return status;
      }
      break;

   case 2:
      if (   (status = (*litFunc)(clientData, startUnescaped,
                                  pos - 1 - startUnescaped)) < 0
          || (status = (*specFunc)(clientData, pos, in - pos, "s", 1)) < 0) {
         return status;
      }
      break;

   case 1:
   case 3:
      return -2;
      break;

   default:
      NOT_IMPLEMENTED();
      break;
   }

   return 0;
}


/*
 *-----------------------------------------------------------------------------
 *
 * MsgFmt_Parse --
 *
 *    Parse a message format.
 *
 * Results:
 *     0 on success
 *    -1 on failure: out of memory
 *    -2 on failure: invalid 'in'
 *
 * Side effects:
 *    None
 *
 *-----------------------------------------------------------------------------
 */

int
MsgFmt_Parse(MsgFmt_LitFunc *litFunc,    // IN
             MsgFmt_SpecFunc *specFunc,  // IN
             void *clientData,           // IN
             char const *in)             // IN
{
   char const *startUnescaped;
   unsigned int sm;
   unsigned int counter;
   int status;
   char const *startEscaped = 0 /* Compiler warning --hpreg */;
   char const *type = 0 /* Compiler warning --hpreg */;
   Bool usePos = FALSE /* Compiler warning --hpreg */;

   startUnescaped = in;
   sm = 0;
   counter = 0;

   for (; *in != '\0'; in++) {
      /* Unsigned does matter --hpreg */
      unsigned char ubyte;

      ubyte = *in;
      switch (sm) {
      case 0: /* Found <byte> --hpreg */
         if (ubyte == '%') {
            sm = 1;
         }
         break;

      case 1: /* Found %<byte> --hpreg */
         if (ubyte == '%') {
	    if (litFunc != NULL &&
	        (status = (*litFunc)(clientData, startUnescaped,
				     in - 1 - startUnescaped)) < 0) {
	       return status;
	    }
            startUnescaped = in;
            sm = 0;
            break;
         }
         startEscaped = in;
         type = in;
         if (ubyte >= '1' && ubyte <= '9') {
            sm = 2;
            break;
         }
         sm = 3;
         /* Fall through --hpreg */

      case 3: /* Found %<1-9>...$...<byte> or %...<byte> --hpreg */
      variant3:
         if (isSpecifier[ubyte]) {
            char const *pos;
            char const *posEnd;
            char posBuf[10 /* 32 bits unsigned in decimal --hpreg */];

            if (counter) {
               if (usePos != (startEscaped != type)) {
                  return -2;
               }
            } else {
               usePos = (startEscaped != type);
            }
            counter++;

            if (usePos) {
               pos = startEscaped;
               posEnd = type - 1;
            } else {
               char *current;
               unsigned int value;

               current = posBuf + sizeof(posBuf);
               posEnd = current;
               value = counter;
               ASSERT(value);
               do {
                  current--;
                  ASSERT(current >= posBuf);
                  *current = '0' + value % 10;
                  value /= 10;
               } while (value);
               pos = current;
            }

            if (litFunc != NULL &&
		(status = (*litFunc)(clientData, startUnescaped,
				     startEscaped - 1 - startUnescaped)) < 0) {
	       return status;
	    }
            if ((status = (*specFunc)(clientData, pos, posEnd - pos, type,
                                      in + 1 - type)) < 0) {
               return status;
            }
            startUnescaped = in + 1;
            sm = 0;
            break;
         }
         /* Digits for field width & precision, zero for leading zeroes,
	    and dot for separator between width and precision. */
         if ((ubyte >= '0' && ubyte <= '9') || ubyte == '.') {
            break;
         }
	 /* Flags */
         if (ubyte == '#' || ubyte == '-' || ubyte == ' ' || ubyte == '+' ||
             ubyte == '\'') {
	    break;
	 }
	 /* Length modifiers */
	 if (ubyte == 'L' || ubyte == 'l' || ubyte == 'h' || ubyte == 'z' ||
	     ubyte == 'Z' || ubyte == 't' || ubyte == 'q' || ubyte == 'j' ||
	     ubyte == 'I') {
            break;
         }
         return -2;

      case 2: /* Found %<1-9>...<byte> --hpreg */
         if (ubyte >= '0' && ubyte <= '9') {
            break;
         }
         if (ubyte == '$') {
            type = in + 1;
            sm = 3;
            break;
         }
         sm = 3;
         goto variant3;

      default:
         NOT_IMPLEMENTED();
         break;
      }
   }

   if (sm) {
      return -2;
   }
   if (litFunc != NULL &&
       (status = (*litFunc)(clientData, startUnescaped,
			    in - startUnescaped)) < 0) {
      return status;
   }

   return 0;
}


/*
 *-----------------------------------------------------------------------------
 *
 * MsgFmt_ParseSpec --
 *
 *      Given a format specifier (the % stuff), return its contituent parts.
 *
 * Results:
 *      0 on success, -2 (bad format) on failure.
 *	Out parameters:
 *	   Width and precision are -1 if not specified.
 *	   Length modifier is '\0' if not specified.
 *	   Length modifier of "ll", "I64", or "q" is returned as 'L'.
 *	   (This means we freely allow %llf and %qf, which is not strictly
 *	   correct.  However, glibc printf allows them (as well as %Ld),
 *	   and they mean the same thing.)
 *	   Length modifier of "hh" is returned as 'H'.
 *	   Length modifier of "Z" is returned as 'z', for compatibility
 *	   with old glibc.
 *	On failure, some or all of the out parameters may be modified
 *	in an undefined manner.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

int
MsgFmt_ParseSpec(char const *pos,       // IN: n$ location
                 unsigned int posSize,  // IN: n$ length
                 char const *type,      // IN: specifier after position
                 unsigned int typeSize, // IN: size of above
		 int *position,         // OUT: argument position
		 int *flags,            // OUT: flags
		 int *width,            // OUT: width
		 int *precision,        // OUT: precision
		 char *lengthMod,       // OUT: length modifier
		 char *conversion)      // OUT: conversion specifier
{
   char const *p = type;
   char const *end = type + typeSize;

   /*
    * Convert argument position to int.
    * Fail if not a good decimal number greater than 0.
    */

   {
      char const *posEnd = pos + posSize;
      *position = MsgFmtAToI(&pos, posEnd);
      if (*position <= 0 || pos != posEnd) {
	 return -2;
      }
   }

   /*
    * The format specifier is, in this order,
    *    zero or more flags
    *    an optional width (a decimal number or *)
    *    an optional precision (. followed by optional decimal number or *)
    *    an optional length modifier (l, L, ll, z, etc.)
    *    conversion specifier (a character)
    *
    * The rest of this module does not recognize * as width or precision,
    * so we don't do it here either.
    *
    * glibc 2.2 supports the I flag, which we don't.  Instead, we
    * support the I, I32, and I64 length modifiers used by Microsoft.
    */

   /*
    * Flags
    */

   *flags = 0;
   for (; p < end; p++) {
      switch (*p) {
      case '#':
	 *flags |= MSGFMT_FLAG_ALT;
	 continue;
      case '0':
	 *flags |= MSGFMT_FLAG_ZERO;
	 continue;
      case '-':
	 *flags |= MSGFMT_FLAG_MINUS;
	 continue;
      case ' ':
	 *flags |= MSGFMT_FLAG_SPACE;
	 continue;
      case '+':
	 *flags |= MSGFMT_FLAG_PLUS;
	 continue;
      case '\'':
	 *flags |= MSGFMT_FLAG_QUOTE;
	 continue;

      default:
	 break;
      }
      break;
   }

   /*
    * Width
    */

   if (p >= end || *p < '1' || *p > '9') {
      *width = -1;
   } else {
      *width = MsgFmtAToI(&p, end);
      if (*width < 0) {
	 return -2;
      }
   }

   /*
    * Precision
    */

   if (p >= end || *p != '.') {
      *precision = -1;
   } else {
      p++;
      *precision = MsgFmtAToI(&p, end);
      if (*precision < 0) {
	 return -2;
      }
   }

   /*
    * Length modifier
    */

   if (p >= end) {
      return -2;
   }
   *lengthMod = '\0';
   switch (*p) {
   case 'h':
      p++;
      if (p >= end || *p != 'h') {
	 *lengthMod = 'h';
      } else {
	 p++;
	 *lengthMod = 'H';
      }
      break;
   case 'l':
      p++;
      if (p >= end || *p != 'l') {
	 *lengthMod = 'l';
      } else {
	 p++;
	 *lengthMod = 'L';
      }
      break;
   case 'I':
      /*
       * Microsoft:
       *    I64 is 64-bit number.  For us, the same as L.
       *    I32 is 32-bit number.  For us, nothing.
       *    I is size_t.
       */
      if (p + 2 < end && p[1] == '6' && p[2] == '4') {
	 p += 3;
	 *lengthMod = 'L';
      } else if (p + 2 < end && p[1] == '3' && p[2] == '2') {
	 p += 3;
      } else {
	 p++;
	 *lengthMod = 'z';
      }
      break;
   case 'q':
      p++;
      *lengthMod = 'L';
      break;
   case 'Z':
      p++;
      *lengthMod = 'z';
      break;
   case 'L':
   case 'j':
   case 'z':
   case 't':
      *lengthMod = *p++;
      break;
   }

   /*
    * Conversion specifier
    *
    * Return false if no conversion specifier or not the last character.
    */

   if (p + 1 == end && isSpecifier[(unsigned char) *p]) {
      *conversion = *p;
      return 0;
   }
   return -2;
}


/*
 *-----------------------------------------------------------------------------
 *
 * MsgFmtAToI --
 *
 *      Convert numeric string to integer.
 *	The range is 0 to MAX_INT32 (nonnegative 32-bit signed int).
 *	Empty string or a string that does not begin with
 *	a digit is treated as 0.
 *
 * Results:
 *      The number or -1 on overflow.
 *	Start pointer updated to point to first nonnumeric character.
 *	or first character before overflow.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static int
MsgFmtAToI(char const **start,	// IN/OUT: string pointer
           char const *end)	// IN: end of string
{
   char const *p;
   int n = 0;

   ASSERT_ON_COMPILE(sizeof (int) >= 4);
   for (p = *start; p < end && *p >= '0' && *p <= '9'; p++) {
      if (n > MAX_INT32 / 10) {
	 n = -1;
	 break;
      }
      n *= 10;
      n += *p - '0';
      if (n < 0) {
	 n = -1;
	 break;
      }
   }
   *start = p;
   return n;
}


/*
 *-----------------------------------------------------------------------------
 *
 * MsgFmt_GetArgs --
 *
 *      Parse a format string and return the arguments implied by it.
 *
 * Results:
 *	TRUE on sucess.
 *	Out parameters:
 *        The array of MsgFmt_Arg structures.
 *	  The number of arguments.
 *	  An error string on failure.
 *
 * Side effects:
 *      Memory is allocated.
 *
 *-----------------------------------------------------------------------------
 */

Bool
MsgFmt_GetArgs(const char *fmt,		// IN: format string
	       va_list va,		// IN: the argument list
	       MsgFmt_Arg **args,	// OUT: the returned arguments
	       int *numArgs,		// OUT: number of returned arguments
	       char **error)		// OUT: error string
{
   return MsgFmt_GetArgsWithBuf(fmt, va, args, numArgs, error, NULL, NULL);
}


/*
 *-----------------------------------------------------------------------------
 *
 * MsgFmt_GetArgsWithBuf --
 *
 *      Parse a format string and return the arguments implied by it.
 *
 *	If buf is supplied, allocate memory there instead of with malloc().
 *
 * Results:
 *	TRUE on sucess.
 *	Out parameters:
 *        The array of MsgFmt_Arg structures.
 *	  The number of arguments.
 *	  An error string on failure.
 *	  The amount of buf used (if caller supplied buf)
 *
 * Side effects:
 *      Memory may be allocated.
 *
 *-----------------------------------------------------------------------------
 */

Bool
MsgFmt_GetArgsWithBuf(const char *fmt,	  // IN: format string
	              va_list va,	  // IN: the argument list
	              MsgFmt_Arg **args,  // OUT: the returned arguments
	              int *numArgs,	  // OUT: number of returned arguments
	              char **error,	  // OUT: error string
                      void *buf,	  // OUT: memory to store output
	              size_t *bufSize)	  // IN/OUT: size of buf /
                                          //         amount of buf used
{
   MsgFmtParseState state;
   int status;
   int i;

   memset(&state, 0, sizeof state);
   if (buf != NULL) {
      ASSERT(bufSize != NULL);
      MsgFmtAllocInit(&state, buf, *bufSize);
   }

   /*
    * First pass: parse format to get argument information
    */

   status = MsgFmt_Parse(NULL, MsgFmtGetArg1, &state, fmt);
   if (status < 0) {
      goto bad;
   }

   /*
    * Second pass: get argument values
    *
    * While we can store most values directly in the MsgFmt_Arg
    * structure, strings have to be copied into allocated space.
    * When precision is specified (see comment about it in
    * MsgFmtGetArg1()), we copy at most that many bytes because
    * that's how many printf() looks at, and we must not touch
    * memory beyond what printf() would.
    */

   for (i = 0; i < state.numArgs; i++) {
      MsgFmt_Arg *a = state.args + i;
      switch (a->type) {
      case MSGFMT_ARG_INVALID:
	 MsgFmtError(&state, "MsgFmt_GetArgs: gap in arguments at position %d",
		     i + 1);
	 goto bad;
	 break;

      case MSGFMT_ARG_INT32:
	 ASSERT_ON_COMPILE(sizeof (int) == sizeof (int32));
	 a->v.signed32 = va_arg(va, int);
	 break;
      case MSGFMT_ARG_INT64:
	 ASSERT_ON_COMPILE(sizeof (long long) == sizeof (int64));
	 a->v.signed64 = va_arg(va, long long);
	 break;

      case MSGFMT_ARG_PTR32:
	 // we can only handle this case if native pointer is 4 bytes
	 ASSERT(sizeof (void *) == sizeof (uint32));
	 a->v.unsigned32 = (uint32) (uintptr_t) va_arg(va, void *);
	 break;
      case MSGFMT_ARG_PTR64:
	 // we can only handle this case if native pointer is 8 bytes
	 ASSERT(sizeof (void *) == sizeof (uint64));
	 a->v.unsigned64 = (uint64) (uintptr_t) va_arg(va, void *);
	 break;

#ifndef NO_FLOATING_POINT
      case MSGFMT_ARG_FLOAT64:
         ASSERT_ON_COMPILE(sizeof (double) == 8);
         a->v.float64 = va_arg(va, double);
	 break;
#endif

      case MSGFMT_ARG_STRING8: {
	 const char *p = va_arg(va, char *);
	 size_t n;
	 Err_Number errorNumber;
	 ASSERT_ON_COMPILE(sizeof (char) == sizeof (int8));
	 ASSERT_ON_COMPILE(offsetof(MsgFmt_Arg, v.string8) ==
		           offsetof(MsgFmt_Arg, v.ptr));
	 if (p == NULL) {
	    a->v.string8 = NULL;
	 } else {
	    if (a->p.precision < 0) {
	       n = strlen(p);
	    } else {
	       const char *q;
	       n = a->p.precision;
	       q = memchr(p, '\0', n);
	       if (q != NULL) {
		  n = q - p;
	       }
	    }
	    // yes, sizeof (int8) is 1.
	    a->v.string8 = MsgFmtAlloc(&state, n + 1);
	    if (a->v.string8 == NULL) {
	       status = -1;
	       goto bad;
	    }
	    memcpy(a->v.string8, p, n);
	    a->v.string8[n] = '\0';
	 }
	 errorNumber = Err_String2Errno(p);
#ifdef VMX86_DEBUG
	 if (errorNumber == ERR_INVALID && p != NULL) {
	    // p may not be null terminated, so use string8
	    errorNumber = Err_String2ErrnoDebug(a->v.string8char);
	    if (errorNumber != ERR_INVALID) {
	       // Err_String2ErrnoDebug already logged its info
	       Log("%s: failed to look up copied error string at %p.\n",
		   __FUNCTION__, p);
	    }
	 }
#endif
	 if (errorNumber != ERR_INVALID) {
	    ASSERT_NOT_IMPLEMENTED(MSGFMT_CURRENT_PLATFORM !=
				   MSGFMT_PLATFORM_UNKNOWN);
	    ASSERT_ON_COMPILE(sizeof errorNumber == sizeof a->e.number);
	    a->type = MSGFMT_ARG_ERRNO;
	    a->e.platform = MSGFMT_CURRENT_PLATFORM;
	    a->e.number = errorNumber;
	    break;
	 }
	 break;
	 }
      case MSGFMT_ARG_STRING16:
      case MSGFMT_ARG_STRING32: {
	 // we can only handle the case when native wchar_t matches
	 // the string char size
	 const wchar_t *p = va_arg(va, wchar_t *);
	 size_t n;
	 ASSERT(a->type == MSGFMT_ARG_STRING16 ?
	        sizeof (wchar_t) == sizeof (int16) :
	        sizeof (wchar_t) == sizeof (int32));
	 ASSERT_ON_COMPILE(offsetof(MsgFmt_Arg, v.string16) ==
		           offsetof(MsgFmt_Arg, v.ptr));
	 ASSERT_ON_COMPILE(offsetof(MsgFmt_Arg, v.string32) ==
		           offsetof(MsgFmt_Arg, v.ptr));
	 if (p == NULL) {
	    a->v.ptr = NULL;
	 } else {
	    if (a->p.precision < 0) {
	       n = wcslen(p);
	    } else {
	       const wchar_t *q;
	       n = a->p.precision;
	       q = wmemchr(p, 0, n);
	       if (q != NULL) {
	          n = q - p;
	       }
	    }
	    a->v.ptr = MsgFmtAlloc(&state, sizeof (wchar_t) * (n + 1));
	    if (a->v.ptr == NULL) {
	       status = -1;
	       goto bad;
	    }
	    memcpy(a->v.ptr, p, sizeof (wchar_t) * n);
	    ((wchar_t *) a->v.ptr)[n] = 0;
	 }
	 break;
	 }

      case MSGFMT_ARG_ERRNO:	// there shouldn't be this case here
      default:
	 NOT_REACHED();
      }

      // clear private data
      memset(&a->p, 0, sizeof a->p);
   }

   /*
    * Pass results back
    */

   if (args == NULL) {
      MsgFmtFreeAll(&state);
   } else {
      *args = state.args;
   }
   if (numArgs != NULL) {
      *numArgs = state.numArgs;
   }
   if (bufSize != NULL) {
      *bufSize = MsgFmtBufUsed(&state);
   }
   ASSERT(state.error == NULL);
   *error = NULL;
   return TRUE;

bad:
   if (state.error == NULL) {
      switch (status) {
      case -1:
	 MsgFmtError(&state, "MsgFmt_GetArgs: out of memory");
	 break;
      case -2:
	 MsgFmtError(&state, "MsgFmt_GetArgs: error in format string");
	 break;
      default:
	 MsgFmtError(&state, "MsgFmt_GetArgs: error %d", status);
      }
   }
   ASSERT(state.args == NULL);	// MsgFmtError() frees args
   *error = state.error;
   return FALSE;
}


/*
 *-----------------------------------------------------------------------------
 *
 * MsgFmtGetArg1 --
 *
 *      Process one format specifier for MsgFmt_GetArgs().
 *	Called by MsgFmt_Parse().
 *
 * Results:
 *      0 on success,
 *	negative status on failure (see MsgFmt_Parse()).
 *	error string in state.error on failure.
 *
 * Side effects:
 *      Memory is allocated.
 *
 *-----------------------------------------------------------------------------
 */

static int
MsgFmtGetArg1(void *clientData,      // IN: state
              const char *pos,	     // IN: n$ location
              unsigned int posSize,  // IN: n$ length
              char const *type,      // IN: specifier after position
              unsigned int typeSize) // IN: size of above
{
   MsgFmtParseState *state = clientData;
   MsgFmt_Arg *a;
   int position;
   int flags;
   int width;
   int precision;
   char lengthMod;
   char conversion;
   MsgFmt_ArgType argType = MSGFMT_ARG_INVALID;
   int status;

   /*
    * Parse format specifier
    */

   status = MsgFmt_ParseSpec(pos, posSize, type, typeSize,
			     &position, &flags, &width, &precision,
			     &lengthMod, &conversion);
   if (status < 0) {
      MsgFmtError(state,
		  "MsgFmtGetArg1: bad specifier, "
	          "status %d, pos \"%.*s\", type \"%.*s\"",
	          status, posSize, pos, typeSize, type);
      return status;
   }

   /*
    * Make room in argument array if necessary.
    */

   if (position > state->numArgs) {
      if (!MsgFmtAllocArgs(state, position)) {
	 MsgFmtError(state, "MsgFmtGetArg1: out of memory at arg %d",
		     position);
	 return -1;
      }
      state->numArgs = position;
   }

   /*
    * Fill in argument structure based on the format specifier.
    *
    * For strings, the precision argument is the maximum length
    * to print.  We need to keep track of it so MsgFmt_GetArgs()
    * can know how many characters to squirrel away, in case
    * the string isn't null terminated, is very long, or falls off
    * the end of the world.
    *
    * In all other cases, the precision is unimportant to us
    * and we don't keep it around.
    */

   a = state->args + position - 1;

   switch (conversion) {
   case 'd':
   case 'i':
   case 'o':
   case 'u':
   case 'x':
   case 'X':
      switch (lengthMod) {
      // all of these take an int argument, they just print differently
      case '\0':
      case 'h':
      case 'H':
	 ASSERT_ON_COMPILE(sizeof (int) == sizeof (int32));
	 argType = MSGFMT_ARG_INT32;
	 break;

      case 'l':
	 ASSERT_ON_COMPILE(sizeof (long) == sizeof (int32) ||
			   sizeof (long) == sizeof (int64));
	 if (sizeof (long) == sizeof (int32)) {
	    argType = MSGFMT_ARG_INT32;
	 } else {
	    argType = MSGFMT_ARG_INT64;
	 }
	 break;

      case 'j':
#ifndef _WIN32 // no intmax_t, bsd_vsnprintf() uses 64 bits
	 ASSERT_ON_COMPILE(sizeof (intmax_t) == sizeof (int64));
#endif
      case 'L':
	 ASSERT_ON_COMPILE(sizeof (long long) == sizeof (int64));
	 argType = MSGFMT_ARG_INT64;
	 break;

      case 't':
	 ASSERT_ON_COMPILE(sizeof (ptrdiff_t) == sizeof (size_t));
      case 'z':
	 ASSERT_ON_COMPILE(sizeof (size_t) == sizeof (int32) ||
		           sizeof (size_t) == sizeof (int64));
	 if (sizeof (size_t) == sizeof (int32)) {
	    argType = MSGFMT_ARG_INT32;
	 } else {
	    argType = MSGFMT_ARG_INT64;
	 }
	 break;
      default:
	 NOT_REACHED();
      }
      break;

   case 'e':
   case 'E':
   case 'f':
   case 'F':
   case 'g':
   case 'G':
   case 'a':
   case 'A':
#ifndef NO_FLOATING_POINT
      switch (lengthMod) {
      // l h hh t z are not defined by man page, but allowed by glibc
      case '\0':
      case 'l':
      case 'h':
      case 'H':
      case 't':
      case 'z':
	 ASSERT_ON_COMPILE(sizeof (double) == 8);
	 argType = MSGFMT_ARG_FLOAT64;
	 break;
      // j is not defined by man page, but allowed by glibc
      case 'L':
      case 'j':
	 /*
	  * We don't do %Lf because it's not that useful to us, and
	  * long double has a number of implementations.  For example,
	  * on Win32 it's the same as double, and it would have a hard
	  * time dealing with a bigger one passed to it.
	  * We can just coerce it down to a double at the source,
	  * but then why bother?
	  */
	 MsgFmtError(state,
		     "MsgFmtGetArg1: %%%c%c not supported, "
	             "pos \"%.*s\", type \"%.*s\"",
	             lengthMod, conversion, posSize, pos, typeSize, type);
	 return -2;
      default:
	 NOT_REACHED();
      }
      break;
#else
      MsgFmtError(state,
                  "MsgFmtGetArg1: %%%c%c not supported, "
                  "pos \"%.*s\", type \"%.*s\"",
                  lengthMod, conversion, posSize, pos, typeSize, type);
      return -2;
#endif /*! NO_FLOATING_POINT */

   case 'c':
      switch (lengthMod) {
      // h hh t z not defined by man page, but allowed by glibc
      case '\0':
      case 'h':
      case 'H':
      case 't':
      case 'z':
	 ASSERT_ON_COMPILE(sizeof (int) == sizeof (int32));
	 argType = MSGFMT_ARG_INT32;
	 break;
      // j ll L not defined by man page nor actually supported
      case 'l':
      case 'j':
      case 'L':
	 goto caseC;
      default:
	 NOT_REACHED();
      }
      break;

   case 'C':
   caseC:
      // man page says it's a wint_t argument, but we assume promotion to int
      ASSERT_ON_COMPILE(sizeof (wint_t) <= sizeof (int) &&
	                sizeof (int) == sizeof (int32));
      argType = MSGFMT_ARG_INT32;
      break;

   case 's':
      // we interpret the length modifier like we do for %c
      switch (lengthMod) {
      case '\0':
      case 'h':
      case 'H':
      case 't':
      case 'z':
	 ASSERT_ON_COMPILE(sizeof (char) == sizeof (int8));
	 argType = MSGFMT_ARG_STRING8;
	 break;
      case 'l':
      case 'j':
      case 'L':
	 goto caseS;
      default:
	 NOT_REACHED();
      }
      // keep track of maximum string length, see block comment above
      a->p.precision = precision;
      ASSERT(a->v.ptr == NULL);
      break;

   case 'S':
   caseS:

#if defined __ANDROID__
      ASSERT_ON_COMPILE(sizeof (wchar_t) == sizeof (int16) ||
	                sizeof (wchar_t) == sizeof (int32) ||
                        sizeof (wchar_t) == sizeof (int8));
#else
      ASSERT_ON_COMPILE(sizeof (wchar_t) == sizeof (int16) ||
                        sizeof (wchar_t) == sizeof (int32));
#endif

      if (sizeof (wchar_t) == sizeof (int16)) {
	 argType = MSGFMT_ARG_STRING16;
#if defined __ANDROID__
      } else if (sizeof (wchar_t) == sizeof (int8)) {
         argType = MSGFMT_ARG_STRING8;
#endif
      } else {
	 argType = MSGFMT_ARG_STRING32;
      }
      // keep track of maximum string length, see block comment above
      a->p.precision = precision;
      ASSERT(a->v.ptr == NULL);
      break;

   case 'p':
      ASSERT_ON_COMPILE(sizeof (void *) == sizeof (int32) ||
	                sizeof (void *) == sizeof (int64));
      if (sizeof (void *) == sizeof (int32)) {
	 argType = MSGFMT_ARG_PTR32;
      } else {
	 argType = MSGFMT_ARG_PTR64;
      }
      break;

   case 'n':
      MsgFmtError(state,
		  "MsgFmtGetArg1: %%n not supported, "
		  "pos \"%.*s\", type \"%.*s\"",
		  posSize, pos, typeSize, type);
      return -2;

   // MsgFmt_ParseSpec() doesn't do %m, and we don't see %%
   default:
      MsgFmtError(state,
		  "MsgFmtGetArg1: %%%c not understood, "
		  "pos \"%.*s\", type \"%.*s\"",
		  conversion, posSize, pos, typeSize, type);
      NOT_REACHED();
   }

   ASSERT(argType != MSGFMT_ARG_INVALID);
   if (a->type != MSGFMT_ARG_INVALID && a->type != argType) {
      MsgFmtError(state,
		  "MsgFmtGetArg1: incompatible specifiers for argument %d, "
	          "old type %d, new type %d, pos \"%.*s\", type \"%.*s\"",
	          position, a->type, argType, posSize, pos, typeSize, type);
      return -2;
   }
   a->type = argType;

   return 0;
}


/*
 *-----------------------------------------------------------------------------
 *
 * MsgFmtError --
 *
 *      Format an error string and squirrel it away.
 *
 * Results:
 *      Error string returned in state variable.
 *
 * Side effects:
 *      Memory may be allocated.
 *
 *-----------------------------------------------------------------------------
 */

static void
MsgFmtError(MsgFmtParseState *state,	// IN/OUT: state structure
            const char *fmt,		// IN: error format
	    ...)			// IN: error args
{
   va_list args;

   ASSERT(state->error == NULL);
   // free up space (in call-supplied buffer) for error string
   MsgFmtFreeAll(state);
   va_start(args, fmt);
   state->error = MsgFmtVasprintf(state, fmt, args);
   va_end(args);
}


/*
 *-----------------------------------------------------------------------------
 *
 * MsgFmt_FreeArgs --
 *
 *      Free an array of MsgFmt_Arg structures.
 *	Do not call this on an array in a caller-supplied
 *	buffer from MsgFmt_GetArgsWithBuf().
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Memory is freed.
 *
 *-----------------------------------------------------------------------------
 */

void
MsgFmt_FreeArgs(MsgFmt_Arg *args,	// IN/OUT: arguments to free
                int numArgs)		// IN: number of arguments
{
   int i;

   for (i = 0; i < numArgs; i++) {
      switch (args[i].type) {
      case MSGFMT_ARG_STRING8:
      case MSGFMT_ARG_STRING16:
      case MSGFMT_ARG_STRING32:
      case MSGFMT_ARG_ERRNO:
	 free(args[i].v.ptr);
	 break;
      default:
	 ;
      }
   }
   free(args);
}


/*
 *-----------------------------------------------------------------------------
 *
 * MsgFmtAllocInit --
 *
 *	Initialize allocator for caller-supplied buffer.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	As described.
 *
 *-----------------------------------------------------------------------------
 */

static void
MsgFmtAllocInit(MsgFmtParseState *state, // IN/OUT: state structure
	        void *buf,		 // IN: buffer
                size_t size)		 // IN: size to allocate
{
   state->bufp = state->buf = buf;
   state->bufe = state->bufp + size;
}


/*
 *-----------------------------------------------------------------------------
 *
 * MsgFmtAlloc --
 *
 *	Allocate memory from malloc() or from supplied buffer.
 *
 * Results:
 *	Pointer or NULL on failure.
 *
 * Side effects:
 *	Memory allocated or state updated.
 *
 *-----------------------------------------------------------------------------
 */

static void *
MsgFmtAlloc(MsgFmtParseState *state,	// IN/OUT: state structure
            size_t size)		// IN: size to allocate
{
   void *p;

   if (state->buf == NULL) {
      p = malloc(size);
   } else {
      if (state->bufe - state->bufp < size) {
	 return NULL;
      }
      p = state->bufp;
      state->bufp += size;
   }
   return p;
}


/*
 *-----------------------------------------------------------------------------
 *
 * MsgFmtAllocArgs --
 *
 *	Grow MsgFmt_Arg array to accomodate new entry.
 *
 * Results:
 *	TRUE on success.
 *	State updated.
 *
 * Side effects:
 *	Memory may be allocated.
 *
 *-----------------------------------------------------------------------------
 */

static Bool
MsgFmtAllocArgs(MsgFmtParseState *state, // IN/OUT: state structure
                int n)			 // IN: 1-based argument number
{
   if (n <= state->maxArgs) {
      return TRUE;
   }

   /*
    * If using malloc, then reallocate() the array with some slack.
    * If using our own buffer, just grow it exactly.
    */

   if (state->buf == NULL) {
      void *p;
      n = MAX(4, n + state->maxArgs);
      p = realloc(state->args, n * sizeof *state->args);
      if (p == NULL) {
	 return FALSE;
      }
      state->args = p;
   } else {
      if (state->args == NULL) {
	 // first time
	 state->args = (void *) state->bufp;
      } else {
	 // growing: there must be nothing after the args array
	 ASSERT((void *) state->bufp == state->args + state->maxArgs);
      }
      if ((char *) (state->args + n) > state->bufe) {
	 return FALSE;
      }
      state->bufp = (char *) (state->args + n);
   }
   memset(state->args + state->maxArgs, 0,
	  sizeof *state->args * (n - state->maxArgs));
   state->maxArgs = n;
   return TRUE;
}


/*
 *-----------------------------------------------------------------------------
 *
 * MsgFmtVasprintf --
 *
 *      Format a string in allocated space.
 *
 * Results:
 *      String.
 *
 * Side effects:
 *	Memory allocated or state updated.
 *	Panic if can't allocate.
 *
 *-----------------------------------------------------------------------------
 */

static char *
MsgFmtVasprintf(MsgFmtParseState *state,	// IN/OUT: state structure
                const char *fmt,		// IN: error format
	        va_list args)		// IN: error args
{
   char *p;

   ASSERT(state->error == NULL);
   if (state->buf == NULL) {
      p = Str_Vasprintf(NULL, fmt, args);
      ASSERT_MEM_ALLOC(p != NULL);
   } else {
      int n;
      p = state->bufp;
      // Str_Vsnprintf() may truncate
      n = Str_Vsnprintf(p, (char *)state->bufe - p, fmt, args);
      state->bufp = (n < 0) ? state->bufe : state->bufp + n + 1;
   }
   return p;
}


/*
 *-----------------------------------------------------------------------------
 *
 * MsgFmtFreeAll --
 *
 *	Free all memory associated with current MsgFmt_Arg array.
 *
 * Results:
 *	State updated.
 *
 * Side effects:
 *	Memory may be freed.
 *
 *-----------------------------------------------------------------------------
 */

static void
MsgFmtFreeAll(MsgFmtParseState *state) // IN/OUT: state structure
{
   if (state->args == NULL)
      return;

   if (state->buf == NULL) {
      MsgFmt_FreeArgs(state->args, state->numArgs);
   } else {
      state->bufp = state->buf;
   }
   state->numArgs = state->maxArgs = 0;
   state->args = NULL;
}


/*
 *-----------------------------------------------------------------------------
 *
 * MsgFmtBufUsed --
 *
 *      Return the amount of space used in the caller supplied buffer.
 *
 * Results:
 *      size_t	
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static size_t
MsgFmtBufUsed(MsgFmtParseState *state) // IN: state structure
{
   if (state->buf == NULL) {
      return 0;
   } else {
      return state->bufp - (char *)state->buf;
   }
}


/*
 *-----------------------------------------------------------------------------
 *
 * MsgFmt_SwizzleArgs --
 *
 *      Pointer swizzling. Flattens pointers in the MsgFmt_Arg array by
 *      converting them to offsets relative to the start of the args array.
 *      This should only be invoked if the MsgFmt_Arg array was allocated 
 *      from a caller-supplied buffer from MsgFmt_GetArgsWithBuf.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      For all i such that args[i] is a string parameter,
 *      args[i].v.offset is set to the offset from args to the start
 *      of the string, or to 0 if the string was NULL.
 *
 *-----------------------------------------------------------------------------
 */

void
MsgFmt_SwizzleArgs(MsgFmt_Arg *args,
                   int numArgs)
{
   int i;
   int8* bufStart = (int8*)args;

   for (i = 0; i < numArgs; i++) {
      
      switch (args[i].type) {
         case MSGFMT_ARG_STRING8:
         case MSGFMT_ARG_STRING16:
         case MSGFMT_ARG_STRING32:
	    if (args[i].v.ptr == NULL) {
	       // offset is never 0 otherwise
	       args[i].v.offset = 0;
	    } else {
	       args[i].v.offset = (int8*)args[i].v.ptr - bufStart;
	    }
            break;
         default:
            break;
      }
   }
}


/*
 *-----------------------------------------------------------------------------
 *
 * MsgFmt_GetSwizzledString --
 *
 *      Helper for pointer un-swizzling.  Obtains the pointer encoded
 *      by a swizzled argument, if it is a string and the pointer is
 *      within the proper bounds.
 *
 * Results:
 *      NULL and a non-zero return value if the given argument is not
 *      a string, or the pointer is out of bounds (below the end of
 *      the args array or above the end of the buffer), or the string
 *      is not null-terminated within the buffer.
 *
 *      Exception to the above: an offset of 0 is used to encode the
 *      NULL pointer.  In this case, yields NULL and returns zero.
 *
 *      Otherwise, yields a pointer to the string and returns zero.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

int
MsgFmt_GetSwizzledString(const MsgFmt_Arg *args,    // IN: argument array
                         int               numArgs, // IN: size of the array
                         int               i,       // IN: index into the array
                         const void       *bufEnd,  // IN: string space bound
                         const int8      **str)     // OUT: the string
{
   const int8 *bufStart = (const int8*)args;
   const int8 *strStart = (const int8*)(args + numArgs);
   const int8 *strEnd = bufEnd;
   
   switch(args[i].type) {
      case MSGFMT_ARG_STRING8:
      case MSGFMT_ARG_STRING16:
      case MSGFMT_ARG_STRING32:
         if (args[i].v.offset == 0) {
            // offset is never 0 otherwise
            *str = NULL;
            return 0;
         } else {
            const int8 *ptr = args[i].v.offset + bufStart;
            
            if (ptr < strStart || ptr >= strEnd
                || memchr(ptr, '\0', strEnd - ptr) == NULL) {
               *str = NULL;
               return -1;
            } else {
               *str = ptr;
               return 0;
            }
         }
         break;
      default:
         *str = NULL;
         return -1;
   }
   NOT_REACHED();
}


/*
 *-----------------------------------------------------------------------------
 *
 * MsgFmt_UnswizzleArgs --
 *
 *      Pointer un-swizzling. Re-instates the pointers in the arg array.
 *      This should only be invoked if the MsgFmt_Arg array was previously
 *      swizzled using MsgFmt_SwizzleArgs.
 *
 *      If a reconstituted pointer would be out of range -- i.e.,
 *      before the end of the args array or after the provided
 *      end-of-buffer pointer -- it is replaced with NULL and an error
 *      is returned.  This is also done if the resulting string is not
 *      null-terminated within the provided bound.
 *
 * Results:
 *      0 on success; -1 in case of bad pointer.
 *
 * Side effects:
 *      For all i such that args[i] is a string parameter, sets
 *      args[i].v.ptr to the string previously encoded as an offset,
 *      or to NULL if the offset was 0, or to NULL in case of error.
 *
 *-----------------------------------------------------------------------------
 */

int
MsgFmt_UnswizzleArgs(MsgFmt_Arg *args,    // IN/OUT: the arguments (+ strings)
                     int         numArgs, // IN: number of arguments
                     void       *bufEnd)  // IN: string space bound
{
   int i;
   int failures = 0;

   for (i = 0; i < numArgs; i++) {
      switch (args[i].type) {
         case MSGFMT_ARG_STRING8:
         case MSGFMT_ARG_STRING16:
         case MSGFMT_ARG_STRING32:
            if (MsgFmt_GetSwizzledString(args, numArgs, i, bufEnd,
                                         (const int8**)&args[i].v.ptr) != 0) {
               ++failures;
            }
            break;
         default:
            break;
      }
   }
   return failures > 0 ? -1 : 0;
}


/*
 *-----------------------------------------------------------------------------
 *
 * MsgFmt_CopyArgs --
 *      
 *      Copy all args from the given 'copyArgs' array. 
 *
 * Results:
 *      Pointer to copied args array.
 *
 * Side effects:
 *      Allocates memory for new args array.
 *
 *-----------------------------------------------------------------------------
 */

MsgFmt_Arg*
MsgFmt_CopyArgs(MsgFmt_Arg* copyArgs,      // IN: Args to be copied
                int numArgs)               // IN: number of args
{
   MsgFmt_Arg *args;
   int i;

   args = malloc(numArgs * sizeof(MsgFmt_Arg));
   if (args == NULL) {
      return NULL;
   }

   memcpy(args, copyArgs, numArgs * sizeof(MsgFmt_Arg));
   
   for (i = 0; i < numArgs; i++) {
      switch (args[i].type) {
         case MSGFMT_ARG_STRING8:
         case MSGFMT_ARG_ERRNO:
	    if (args[i].v.string8 != NULL) {
	       args[i].v.string8char = strdup(copyArgs[i].v.string8char);
	       if (args[i].v.string8 == NULL) {
		  MsgFmt_FreeArgs(args, i);
		  return NULL;
	       }
	    }
            break;
         case MSGFMT_ARG_STRING16:
         case MSGFMT_ARG_STRING32:
            /*
             * We don't care about these types.
             */
            NOT_IMPLEMENTED();
            break;
         default:
            break;
      }
   }

   return args;
}


#ifdef HAS_BSD_PRINTF // {

/*
 *-----------------------------------------------------------------------------
 *
 * MsgFmt_Snprintf --
 *
 *      MsgFmt_Arg version of Str_Vsnprintf().
 *
 * Results:
 *      Number of character written, not including null termination,
 *	or number of characters would have been written on overflow.
 *	(This is exactly the same as vsnprintf(), but different
 *	from Str_Vsnprintf().)
 *	String is always null terminated, even on overflow.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

int
MsgFmt_Snprintf(char *buf,		 // OUT: formatted string
                size_t size,		 // IN: size of buffer
                const char *format,	 // IN: format
                const MsgFmt_Arg *args,	 // IN: message arguments
                int numArgs)		 // IN: number of arguments
{
   return MsgFmtSnprintfWork(&buf, size, format, args, numArgs);
}


/*
 *-----------------------------------------------------------------------------
 *
 * MsgFmt_Asprintf --
 *
 *      MsgFmt_Arg version of Str_Vasprintf().
 *
 * Results:
 *	Allocated string on success.
 *	NULL on failure.
 *	Length of returned string (not including null termination)
 *	in *length (if length != NULL).
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

char *
MsgFmt_Asprintf(size_t *length,		 // OUT: length of returned string
                const char *format,	 // IN: format
                const MsgFmt_Arg *args,	 // IN: message arguments
                int numArgs)		 // IN: number of arguments
{
   char *p = NULL;
   int n = MsgFmtSnprintfWork(&p, 0, format, args, numArgs);

   if (n < 0) {
      return NULL;
   }
   if (length != NULL) {
      *length = n;
   }
   return p;
}

static int
MsgFmtSnprintfWork(char **outbuf, size_t bufSize, const char *fmt0,
                   const MsgFmt_Arg *args, int numArgs)
{
   char *fmt;      /* format string */
   int ch;         /* character from fmt */
   int n;          /* handy integer (short term usage) */
   char *cp;      /* handy char pointer (short term usage) */
   BSDFmt_IOV *iovp;   /* for PRINT macro */
   int flags;      /* flags as above */
   int ret;      /* return value accumulator */
   int width;      /* width from format (%8d), or 0 */
   int prec;      /* precision from format; <0 for N/A */
   char sign;      /* sign prefix (' ', '+', '-', or \0) */
   char thousands_sep;   /* locale specific thousands separator */
   const char *grouping;   /* locale specific numeric grouping rules */

#ifndef NO_FLOATING_POINT
   /*
    * We can decompose the printed representation of floating
    * point numbers into several parts, some of which may be empty:
    *
    * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
    *    A       B     ---C---      D       E   F
    *
    * A:   'sign' holds this value if present; '\0' otherwise
    * B:   ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
    * C:   cp points to the string MMMNNN.  Leading and trailing
    *   zeros are not in the string and must be added.
    * D:   expchar holds this character; '\0' if no exponent, e.g. %f
    * F:   at least two digits for decimal, at least one digit for hex
    */
   char *decimal_point;   /* locale specific decimal point */
#if defined __ANDROID__
   static char dp = '.';
#endif
   int signflag;      /* true if float is negative */
   union {         /* floating point arguments %[aAeEfFgG] */
      double dbl;
      long double ldbl;
   } fparg;
   int expt;      /* integer value of exponent */
   char expchar;      /* exponent character: [eEpP\0] */
   char *dtoaend;      /* pointer to end of converted digits */
   int expsize;      /* character count for expstr */
   int lead;      /* sig figs before decimal or group sep */
   int ndig;      /* actual number of digits returned by dtoa */
   char expstr[MAXEXPDIG+2];   /* buffer for exponent string: e+ZZZ */
   char *dtoaresult;   /* buffer allocated by dtoa */
   int nseps;      /* number of group separators with ' */
   int nrepeats;      /* number of repeats of the last group */
#endif
   uintmax_t ujval;   /* %j, %ll, %q, %t, %z integers */
   int base;      /* base for [diouxX] conversion */
   int dprec;      /* a copy of prec if [diouxX], 0 otherwise */
   int realsz;      /* field size expanded by dprec, sign, etc */
   int size;      /* size of converted field or string */
   int prsize;             /* max size of printed field */
   const char *xdigs;        /* digits for %[xX] conversion */
   BSDFmt_UIO uio;   /* output information: summary */
   BSDFmt_IOV iov[BSDFMT_NIOV]; /* ... and individual io vectors */
   char buf[INT_CONV_BUF];/* buffer with space for digits of uintmax_t */
   char ox[2];      /* space for 0x; ox[1] is either x, X, or \0 */
   int nextarg;            /* 1-based argument index */
   const MsgFmt_Arg *a;
   char *convbuf;      /* wide to multibyte conversion result */
   BSDFmt_StrBuf sbuf;

   /*
    * BEWARE, these `goto error' on error, and PAD uses `n'.
    */
#define   PRINT(ptr, len) {                             \
      iovp->iov_base = (ptr);                           \
      iovp->iov_len = (len);                            \
      uio.uio_resid += (len);                           \
      iovp++;                                           \
      if (++uio.uio_iovcnt >= BSDFMT_NIOV) {            \
         if (BSDFmt_SPrint(&sbuf, &uio))                \
            goto error;                                 \
         iovp = iov;                                    \
      }                                                 \
   }
#define   PAD(howmany, with) {                  \
      if ((n = (howmany)) > 0) {                \
         while (n > PADSIZE) {                  \
            PRINT(with, PADSIZE);               \
            n -= PADSIZE;                       \
         }                                      \
         PRINT(with, n);                        \
      }                                         \
   }
#define   PRINTANDPAD(p, ep, len, with) do {    \
      int n2 = (ep) - (p);                      \
      if (n2 > (len))                           \
         n2 = (len);                            \
      if (n2 > 0)                               \
         PRINT((p), n2);                        \
      PAD((len) - (n2 > 0 ? n2 : 0), (with));   \
   } while(0)
#define   FLUSH() {                                                     \
      if (uio.uio_resid && BSDFmt_SPrint(&sbuf, &uio))                  \
         goto error;                                                    \
      uio.uio_iovcnt = 0;                                               \
      iovp = iov;                                                       \
   }

#define FETCHARG(a, i) do { \
   int ii = (i) - 1; \
   if (ii >= numArgs) { \
      sbuf.error = TRUE; \
      goto error; \
   } \
   (a) = args + ii; \
} while (FALSE)

   /*
    * Get * arguments, including the form *nn$.
    */
#define GETASTER(val) do { \
   int n2 = 0; \
   char *cp = fmt; \
   const MsgFmt_Arg *a; \
   while (is_digit(*cp)) { \
      n2 = 10 * n2 + to_digit(*cp); \
      cp++; \
   } \
   if (*cp == '$') { \
      FETCHARG(a, n2); \
      fmt = cp + 1; \
   } else { \
      FETCHARG(a, nextarg++); \
   } \
   if (a->type != MSGFMT_ARG_INT32) { \
      sbuf.error = TRUE; \
      goto error; \
   } \
   val = a->v.signed32; \
} while (FALSE)

   xdigs = xdigs_lower;
   thousands_sep = '\0';
   grouping = NULL;
   convbuf = NULL;
#ifndef NO_FLOATING_POINT
   dtoaresult = NULL;
#if defined __ANDROID__
   /*
    * Struct lconv is not working! For decimal_point,
    * using '.' instead is a workaround.
    */
   NOT_TESTED();
   decimal_point = &dp;
#else
   decimal_point = localeconv()->decimal_point;
#endif
#endif

   fmt = (char *)fmt0;
   nextarg = 1;
   uio.uio_iov = iovp = iov;
   uio.uio_resid = 0;
   uio.uio_iovcnt = 0;
   ret = 0;

   /*
    * Set up output string buffer structure.
    */

   sbuf.alloc = *outbuf == NULL;
   sbuf.error = FALSE;
   sbuf.buf = *outbuf;
   sbuf.size = bufSize;
   sbuf.index = 0;

   /*
    * If asprintf(), allocate initial buffer based on format length.
    * Empty format only needs one byte.
    * Otherwise, round up to multiple of 64.
    */

   if (sbuf.alloc) {
      size_t n = strlen(fmt0) + 1;	// +1 for \0
      if (n > 1) {
	 n = ROUNDUP(n, 64);
      }
      if ((sbuf.buf = malloc(n * sizeof (char))) == NULL) {
	 sbuf.error = TRUE;
	 goto error;
      }
      sbuf.size = n;
   }

   // shut compile up
#ifndef NO_FLOATING_POINT
   expt = 0;
   expchar = 0;
   dtoaend = NULL;
   expsize = 0;
   lead = 0;
   ndig = 0;
   nseps = 0;
   nrepeats = 0;
#endif
   ujval = 0;

   /*
    * Scan the format for conversions (`%' character).
    */
   for (;;) {
      for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
         /* void */;
      if ((n = fmt - cp) != 0) {
         if ((unsigned)ret + n > INT_MAX) {
            ret = EOF;
            goto error;
         }
         PRINT(cp, n);
         ret += n;
      }
      if (ch == '\0')
         goto done;
      fmt++;      /* skip over '%' */

      flags = 0;
      dprec = 0;
      width = 0;
      prec = -1;
      sign = '\0';
      ox[1] = '\0';

     rflag:      ch = *fmt++;
     reswitch:   switch (ch) {
      case ' ':
         /*-
          * ``If the space and + flags both appear, the space
          * flag will be ignored.''
          *   -- ANSI X3J11
          */
         if (!sign)
            sign = ' ';
         goto rflag;
      case '#':
         flags |= ALT;
         goto rflag;
      case '*':
         /*-
          * ``A negative field width argument is taken as a
          * - flag followed by a positive field width.''
          *   -- ANSI X3J11
          * They don't exclude field widths read from args.
          */
         GETASTER (width);
         if (width >= 0)
            goto rflag;
         width = -width;
         /* FALLTHROUGH */
      case '-':
         flags |= LADJUST;
         goto rflag;
      case '+':
         sign = '+';
         goto rflag;
      case '\'':
         flags |= GROUPING;
#if defined __ANDROID__
         /*
          * Struct lconv is not working! The code below is a workaround.
          */
         NOT_TESTED();
         thousands_sep = ',';
#else
         thousands_sep = *(localeconv()->thousands_sep);
         grouping = localeconv()->grouping;
#endif
         goto rflag;
      case '.':
         if ((ch = *fmt++) == '*') {
            GETASTER (prec);
            goto rflag;
         }
         prec = 0;
         while (is_digit(ch)) {
            prec = 10 * prec + to_digit(ch);
            ch = *fmt++;
         }
         goto reswitch;
      case '0':
         /*-
          * ``Note that 0 is taken as a flag, not as the
          * beginning of a field width.''
          *   -- ANSI X3J11
          */
         flags |= ZEROPAD;
         goto rflag;
      case '1': case '2': case '3': case '4':
      case '5': case '6': case '7': case '8': case '9':
         n = 0;
         do {
            n = 10 * n + to_digit(ch);
            ch = *fmt++;
         } while (is_digit(ch));
         if (ch == '$') {
            nextarg = n;
            goto rflag;
         }
         width = n;
         goto reswitch;
      case 'h':
         if (flags & SHORTINT) {
            flags &= ~SHORTINT;
            flags |= CHARINT;
         } else
            flags |= SHORTINT;
         goto rflag;
      case 'j':
         flags |= INTMAXT;
         goto rflag;
      case 'I':
         /* could be I64 - long long int is 64bit */
         if (fmt[0] == '6' && fmt[1] == '4') {
            fmt += 2;
            flags |= LLONGINT;
            goto rflag;
         }
         /* could be I32 - normal int is 32bit */
         if (fmt[0] == '3' && fmt[1] == '2') {
            fmt += 2;
            /* flags |= normal integer - it is 32bit for all our targets */
            goto rflag;
         }
         /*
          * I alone - use Microsoft's semantic as size_t modifier.  We do
          * not support glibc's semantic to use alternative digits.
          */
         flags |= SIZET;
         goto rflag;
      case 'l':
         if (flags & LONGINT) {
            flags &= ~LONGINT;
            flags |= LLONGINT;
         } else
            flags |= LONGINT;
         goto rflag;
      case 'L':
      case 'q':
         flags |= LLONGINT;   /* not necessarily */
         goto rflag;
      case 't':
         flags |= PTRDIFFT;
         goto rflag;
      case 'Z':
      case 'z':
         flags |= SIZET;
         goto rflag;
      case 'C':
         flags |= LONGINT;
         /*FALLTHROUGH*/
      case 'c':
	 FETCHARG(a, nextarg++);
	 if (a->type != MSGFMT_ARG_INT32) {
	    sbuf.error = TRUE;
	    goto error;
	 }
         if (flags & LONGINT) {
            static const mbstate_t initial;
            mbstate_t mbs;
            size_t mbseqlen;

	    mbs = initial;
	    // XXX must deal with mismatch between wchar_t size
            mbseqlen = wcrtomb(cp = buf, (wchar_t)a->v.signed32, &mbs);
            if (mbseqlen == (size_t)-1) {
               sbuf.error = TRUE;
               goto error;
            }
            size = (int)mbseqlen;
         } else {
            *(cp = buf) = a->v.signed32;
            size = 1;
         }
         sign = '\0';
         break;
      case 'D':
         flags |= LONGINT;
         /*FALLTHROUGH*/
      case 'd':
      case 'i':
	 FETCHARG(a, nextarg++);
	 if ((flags & (INTMAXT|LLONGINT)) != 0) {
	    if (a->type == MSGFMT_ARG_INT64) {
	       ujval = a->v.signed64;
	    } else {
	       sbuf.error = TRUE;
	       goto error;
	    }
	 } else if ((flags & (SIZET|PTRDIFFT|LONGINT)) != 0) {
	    if (a->type == MSGFMT_ARG_INT64) {
	       ujval = a->v.signed64;
	    } else if (a->type == MSGFMT_ARG_INT32) {
	       ujval = (intmax_t) a->v.signed32;
	    } else {
	       sbuf.error = TRUE;
	       goto error;
	    }
	 } else if ((flags & SHORTINT) != 0) {
	    if (a->type == MSGFMT_ARG_INT32) {
	       ujval = (intmax_t) (short) a->v.signed32;
	    } else {
	       sbuf.error = TRUE;
	       goto error;
	    }
	 } else if ((flags & CHARINT) != 0) {
	    if (a->type == MSGFMT_ARG_INT32) {
	       ujval = (intmax_t) (signed char) a->v.signed32;
	    } else {
	       sbuf.error = TRUE;
	       goto error;
	    }
	 } else {
	    if (a->type == MSGFMT_ARG_INT32) {
	       ujval = (intmax_t) a->v.signed32;
	    } else {
	       sbuf.error = TRUE;
	       goto error;
	    }
	 }
	 if ((intmax_t)ujval < 0) {
	    ujval = -ujval;
	    sign = '-';
	 }
         base = 10;
         goto number;
#ifndef NO_FLOATING_POINT
      case 'e':
      case 'E':
         expchar = ch;
         if (prec < 0)   /* account for digit before decpt */
            prec = DEFPREC + 1;
         else
            prec++;
         goto fp_begin;
      case 'f':
      case 'F':
         expchar = '\0';
         goto fp_begin;
      case 'g':
      case 'G':
         expchar = ch - ('g' - 'e');
         if (prec == 0)
            prec = 1;
      fp_begin:
         if (flags & LLONGINT) {
	    sbuf.error = TRUE;
	    goto error;
	 }
         if (prec < 0)
            prec = DEFPREC;
         if (dtoaresult != NULL)
            freedtoa(dtoaresult);
	 FETCHARG(a, nextarg++);
	 if (a->type != MSGFMT_ARG_FLOAT64) {
	    sbuf.error = TRUE;
	    goto error;
	 }
	 fparg.dbl = a->v.float64;
#if defined NO_DTOA
         NOT_TESTED();
         dtoaresult = NULL;
         sbuf.error = TRUE;

         goto error;
#else
	 dtoaresult = cp =
	    dtoa(fparg.dbl, expchar ? 2 : 3, prec,
		 &expt, &signflag, &dtoaend);
#endif
	 if (expt == 9999)
	    expt = INT_MAX;
         if (signflag)
            sign = '-';
         if (expt == INT_MAX) {   /* inf or nan */
            if (*cp == 'N') {
               cp = (ch >= 'a') ? "nan" : "NAN";
               sign = '\0';
            } else
               cp = (ch >= 'a') ? "inf" : "INF";
            size = 3;
            break;
         }
         flags |= FPT;
         ndig = dtoaend - cp;
         if (ch == 'g' || ch == 'G') {
            if (expt > -4 && expt <= prec) {
               /* Make %[gG] smell like %[fF] */
               expchar = '\0';
               if (flags & ALT)
                  prec -= expt;
               else
                  prec = ndig - expt;
               if (prec < 0)
                  prec = 0;
            } else {
               /*
                * Make %[gG] smell like %[eE], but
                * trim trailing zeroes if no # flag.
                */
               if (!(flags & ALT))
                  prec = ndig;
            }
         }
         if (expchar) {
            expsize = BSDFmt_Exponent(expstr, expt - 1, expchar);
            size = expsize + prec;
            if (prec > 1 || flags & ALT)
               ++size;
         } else {
            /* space for digits before decimal point */
            if (expt > 0)
               size = expt;
            else   /* "0" */
               size = 1;
            /* space for decimal pt and following digits */
            if (prec || flags & ALT)
               size += prec + 1;
            if (grouping && expt > 0) {
               /* space for thousands' grouping */
               nseps = nrepeats = 0;
               lead = expt;
               while (*grouping != CHAR_MAX) {
                  if (lead <= *grouping)
                     break;
                  lead -= *grouping;
                  if (*(grouping+1)) {
                     nseps++;
                     grouping++;
                  } else
                     nrepeats++;
               }
               size += nseps + nrepeats;
            } else
               lead = expt;
         }
         break;
#endif /* !NO_FLOATING_POINT */
      case 'n':
	 sbuf.error = TRUE;
	 goto error;
      case 'O':
         flags |= LONGINT;
         /*FALLTHROUGH*/
      case 'o':
         base = 8;
         goto get_unsigned;
      case 'p':
         /*-
          * ``The argument shall be a pointer to void.  The
          * value of the pointer is converted to a sequence
          * of printable characters, in an implementation-
          * defined manner.''
          *   -- ANSI X3J11
          */
	 FETCHARG(a, nextarg++);
	 if (a->type == MSGFMT_ARG_PTR32) {
	    ujval = a->v.unsigned32;
	 } else if (a->type == MSGFMT_ARG_PTR64) {
	    ujval = a->v.unsigned64;
	 } else {
	    sbuf.error = TRUE;
	    goto error;
	 }
         base = 16;
         xdigs = xdigs_upper;
         flags = flags | INTMAXT;
         /*
          * PR 103201
          * VisualC sscanf doesn't grok '0x', so prefix zeroes.
          */
//         ox[1] = 'x';
         goto nosign;
      case 'S':
         flags |= LONGINT;
         /*FALLTHROUGH*/
      case 's':
	 FETCHARG(a, nextarg++);
	 if (flags & LONGINT) {
            wchar_t *wcp;
#if defined __ANDROID__
            ASSERT_ON_COMPILE(sizeof (wchar_t) == sizeof (int16) ||
                              sizeof (wchar_t) == sizeof (int32) ||
                              sizeof (wchar_t) == sizeof (int8));
            if ((sizeof (wchar_t) == sizeof (int16) &&
                 a->type != MSGFMT_ARG_STRING16) ||
                (sizeof (wchar_t) == sizeof (int32) &&
                 a->type != MSGFMT_ARG_STRING32) ||
                (sizeof (wchar_t) == sizeof (int8) &&
                 a->type != MSGFMT_ARG_STRING8)) {
#else
            ASSERT_ON_COMPILE(sizeof (wchar_t) == 2 || sizeof (wchar_t) == 4);
	    if (sizeof (wchar_t) == 2 ?
		a->type != MSGFMT_ARG_STRING16 :
		a->type != MSGFMT_ARG_STRING32) {
#endif
	       sbuf.error = TRUE;
	       goto error;
	    }
            if ((wcp = (wchar_t *) a->v.ptr) == NULL)
               cp = "(null)";
            else {
	       if (convbuf != NULL)
		  free(convbuf);
               convbuf = BSDFmt_WCharToUTF8(wcp, prec);
               if (convbuf == NULL) {
                  sbuf.error = TRUE;
                  goto error;
               }
               cp = convbuf;
            }
	 } else {
	    if (a->type != MSGFMT_ARG_STRING8 &&
		a->type != MSGFMT_ARG_ERRNO) {
	       sbuf.error = TRUE;
	       goto error;
	    }

	    /*
	     * Use localized string (in localString) if available.
	     * Strip off Msg ID if unlocalized string has one.
	     * Use (null) for null pointer.
	     */

	    if (a->p.localString != NULL) {
	       cp = a->p.localString;
	    } else if (a->v.string8 != NULL) {
	       cp = (char *) Msg_StripMSGID(a->v.string8char);
	    } else {
	       cp = "(null)";
	    }
	 }
         if (prec >= 0) {
            /*
             * We can use strlen here because the string is always
	     * terminated, unlike the string passed to MsgFmt_GetArgs.
	     * However, it's somewhat faster to use memchr.
	     */
            char *p = memchr(cp, 0, prec);

            if (p != NULL) {
               size = p - cp;
               if (size > prec)
                  size = prec;
            } else
               size = prec;
         } else
            size = strlen(cp);
         sign = '\0';
         break;
      case 'U':
         flags |= LONGINT;
         /*FALLTHROUGH*/
      case 'u':
         base = 10;
         goto get_unsigned;
      case 'X':
         xdigs = xdigs_upper;
         goto hex;
      case 'x':
         xdigs = xdigs_lower;
      hex:
         base = 16;
         if (flags & ALT)
            ox[1] = ch;
         flags &= ~GROUPING;

      get_unsigned:
	 FETCHARG(a, nextarg++);
	 if ((flags & (INTMAXT|LLONGINT)) != 0) {
	    if (a->type == MSGFMT_ARG_INT64) {
	       ujval = a->v.unsigned64;
	    } else {
	       sbuf.error = TRUE;
	       goto error;
	    }
	 } else if ((flags & (SIZET|PTRDIFFT|LONGINT)) != 0) {
	    if (a->type == MSGFMT_ARG_INT64) {
	       ujval = a->v.unsigned64;
	    } else if (a->type == MSGFMT_ARG_INT32) {
	       ujval = (uintmax_t) a->v.unsigned32;
	    } else {
	       sbuf.error = TRUE;
	       goto error;
	    }
	 } else if ((flags & SHORTINT) != 0) {
	    if (a->type == MSGFMT_ARG_INT32) {
	       ujval = (intmax_t) (unsigned short) a->v.unsigned32;
	    } else {
	       sbuf.error = TRUE;
	       goto error;
	    }
	 } else if ((flags & CHARINT) != 0) {
	    if (a->type == MSGFMT_ARG_INT32) {
	       ujval = (intmax_t) (unsigned char) a->v.unsigned32;
	    } else {
	       sbuf.error = TRUE;
	       goto error;
	    }
	 } else {
	    if (a->type == MSGFMT_ARG_INT32) {
	       ujval = (intmax_t) a->v.unsigned32;
	    } else {
	       sbuf.error = TRUE;
	       goto error;
	    }
	 }
         if (ujval == 0) /* squash 0x/X if zero */
            ox[1] = '\0';

         /* unsigned conversions */
      nosign:
	 sign = '\0';
         /*-
          * ``... diouXx conversions ... if a precision is
          * specified, the 0 flag will be ignored.''
          *   -- ANSI X3J11
          */
      number:
	 if ((dprec = prec) >= 0)
            flags &= ~ZEROPAD;

         /*-
          * ``The result of converting a zero value with an
          * explicit precision of zero is no characters.''
          *   -- ANSI X3J11
          *
          * ``The C Standard is clear enough as is.  The call
          * printf("%#.0o", 0) should print 0.''
          *   -- Defect Report #151
          */
         cp = buf + INT_CONV_BUF;
	 if (ujval != 0 || prec != 0 ||
	     (flags & ALT && base == 8))
	    cp = BSDFmt_UJToA(ujval, cp, base,
			      flags & ALT, xdigs,
			      flags & GROUPING, thousands_sep,
			      grouping);
         size = buf + INT_CONV_BUF - cp;
         if (size > INT_CONV_BUF)   /* should never happen */
            abort();
         break;
      default:   /* "%?" prints ?, unless ? is NUL */
         if (ch == '\0')
            goto done;
         /* pretend it was %c with argument ch */
         cp = buf;
         *cp = ch;
         size = 1;
         sign = '\0';
         break;
      }

      /*
       * All reasonable formats wind up here.  At this point, `cp'
       * points to a string which (if not flags&LADJUST) should be
       * padded out to `width' places.  If flags&ZEROPAD, it should
       * first be prefixed by any sign or other prefix; otherwise,
       * it should be blank padded before the prefix is emitted.
       * After any left-hand padding and prefixing, emit zeroes
       * required by a decimal [diouxX] precision, then print the
       * string proper, then emit zeroes required by any leftover
       * floating precision; finally, if LADJUST, pad with blanks.
       *
       * Compute actual size, so we know how much to pad.
       * size excludes decimal prec; realsz includes it.
       */
      realsz = dprec > size ? dprec : size;
      if (sign)
         realsz++;
      if (ox[1])
         realsz += 2;

      prsize = width > realsz ? width : realsz;
      if ((unsigned)ret + prsize > INT_MAX) {
         ret = EOF;
         goto error;
      }

      /* right-adjusting blank padding */
      if ((flags & (LADJUST|ZEROPAD)) == 0)
         PAD(width - realsz, blanks);

      /* prefix */
      if (sign)
         PRINT(&sign, 1);

      if (ox[1]) {   /* ox[1] is either x, X, or \0 */
         ox[0] = '0';
         PRINT(ox, 2);
      }

      /* right-adjusting zero padding */
      if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
         PAD(width - realsz, zeroes);

      /* leading zeroes from decimal precision */
      PAD(dprec - size, zeroes);

      /* the string or number proper */
#ifndef NO_FLOATING_POINT
      if ((flags & FPT) == 0) {
         PRINT(cp, size);
      } else {   /* glue together f_p fragments */
         if (!expchar) {   /* %[fF] or sufficiently short %[gG] */
            if (expt <= 0) {
               PRINT(zeroes, 1);
               if (prec || flags & ALT)
                  PRINT(decimal_point, 1);
               PAD(-expt, zeroes);
               /* already handled initial 0's */
               prec += expt;
            } else {
               PRINTANDPAD(cp, dtoaend, lead, zeroes);
               cp += lead;
               if (grouping) {
                  while (nseps>0 || nrepeats>0) {
                     if (nrepeats > 0)
                        nrepeats--;
                     else {
                        grouping--;
                        nseps--;
                     }
                     PRINT(&thousands_sep,
                           1);
                     PRINTANDPAD(cp,dtoaend,
                                 *grouping, zeroes);
                     cp += *grouping;
                  }
                  if (cp > dtoaend)
                     cp = dtoaend;
               }
               if (prec || flags & ALT)
                  PRINT(decimal_point,1);
            }
            PRINTANDPAD(cp, dtoaend, prec, zeroes);
         } else {   /* %[eE] or sufficiently long %[gG] */
            if (prec > 1 || flags & ALT) {
               buf[0] = *cp++;
               buf[1] = *decimal_point;
               PRINT(buf, 2);
               PRINT(cp, ndig-1);
               PAD(prec - ndig, zeroes);
            } else   /* XeYYY */
               PRINT(cp, 1);
            PRINT(expstr, expsize);
         }
      }
#else
      PRINT(cp, size);
#endif
      /* left-adjusting padding (always blank) */
      if (flags & LADJUST)
         PAD(width - realsz, blanks);

      /* finally, adjust ret */
      ret += prsize;

      FLUSH();   /* copy out the I/O vectors */
   }
done:
   FLUSH();

   /*
    * Always null terminate, unless buffer is size 0.
    */

   ASSERT(!sbuf.error && ret >= 0);
   if (sbuf.size <= 0) {
      ASSERT(!sbuf.alloc);
   } else {
      ASSERT(sbuf.index < sbuf.size);
      sbuf.buf[sbuf.index] = '\0';
   }

error:
#ifndef NO_FLOATING_POINT
   if (dtoaresult != NULL)
      freedtoa(dtoaresult);
#endif
   if (convbuf != NULL)
      free(convbuf);
   if (sbuf.error) {
      ret = EOF;
   }

   // return allocated buffer on success, free it on failure
   if (sbuf.alloc) {
      if (ret < 0) {
	 free(sbuf.buf);
      } else {
	 *outbuf = sbuf.buf;
      }
   }

   return (ret);
   /* NOTREACHED */

#undef PRINT
#undef PAD
#undef PRINTANDPAD
#undef FLUSH
#undef FETCHARG
#undef GETASTER
}

#endif // }