summaryrefslogtreecommitdiff
path: root/src/gtm/common/gtm_opt_handler.c
blob: 533d38ec7ef71cc51438ac27a330f7c523cbb31c (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
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
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
/* -*-pgsql-c-*- */
/*
 * Scanner for the configuration file
 *
 * Copyright (c) 2000-2011, PostgreSQL Global Development Group
 *
 * src/backend/utils/misc/guc-file.l
 */

#include "gtm/gtm.h"

#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>

#include "postgres.h"
#include "mb/pg_wchar.h"
#include "gtm/path.h"
#include "gtm/assert.h"
#include "gtm/gtm_opt.h"
#include "gtm/gtm_opt_tables.h"
#include "gtm/elog.h"
#include "gtm_opt_scanner.c"

/* Avoid exit() on fatal scanner errors (a bit ugly -- see yy_fatal_error) */
#undef fprintf
#define fprintf(file, fmt, msg)  ereport(ERROR, (errmsg_internal("%s", msg)))

static unsigned int ConfigFileLineno;

/* flex fails to supply a prototype for GTMOPT_yylex, so provide one */
int GTMOPT_GTMOPT_yylex(void);

/* Functions defined in this file */
static char *GTMOPT_scanstr(const char *s);
static struct config_generic *find_option(const char *name, bool create_placeholders, int elevel);
static char *gtm_opt_strdup(int elevel, const char *src);
static int gtm_opt_name_compare(const char *namea, const char *nameb);
struct config_generic **get_gtm_opt_variables(void);
void build_gtm_opt_variables(void);
static bool gtm_opt_parse_bool(const char *value, bool *result);
static bool gtm_opt_parse_bool_with_len(const char *value, size_t len, bool *result);
static void set_config_sourcefile(const char *name, char *sourcefile, int sourceline);
static int gtm_opt_var_compare(const void *a, const void *b);
static void InitializeOneGTMOption(struct config_generic * gconf);
static void ReportGTMOption(struct config_generic * record);
static char *_ShowOption(struct config_generic * record, bool use_units);

/*
 * Variables to bel fed by specific option definition: gtm_opt.c and gtm_proxy_opt.c
 */
extern char *GTMConfigFileName;
extern char	   *data_directory;
extern struct config_generic **gtm_opt_variables;
extern int num_gtm_opt_variables;
extern int	size_gtm_opt_variables;
extern bool reporting_enabled;	/* TRUE to enable GTMOPT_REPORT */
extern char *config_filename;   /* Default configuration file name */
extern int	GTMOptUpdateCount; /* Indicates when specific option is updated */
extern bool isStartUp;

/*
 * Tables of options: to be defined in gtm_opt.c and gtm_proxy_opt.c
 */
extern struct config_bool ConfigureNamesBool[];
extern struct config_int ConfigureNamesInt[];
extern struct config_real ConfigureNamesReal[];
extern struct config_string ConfigureNamesString[];
extern struct config_enum ConfigureNamesEnum[];

/*
 * Note: MAX_BACKENDS is limited to 2^23-1 because inval.c stores the
 * backend ID as a 3-byte signed integer.  Even if that limitation were
 * removed, we still could not exceed INT_MAX/4 because some places compute
 * 4*MaxBackends without any overflow check.  This is rechecked in
 * check_maxconnections, since MaxBackends is computed as MaxConnections
 * plus autovacuum_max_workers plus one (for the autovacuum launcher).
 */
#define MAX_BACKENDS	0x7fffff

#define KB_PER_MB (1024)
#define KB_PER_GB (1024*1024)

#define MS_PER_S 1000
#define S_PER_MIN 60
#define MS_PER_MIN (1000 * 60)
#define MIN_PER_H 60
#define S_PER_H (60 * 60)
#define MS_PER_H (1000 * 60 * 60)
#define MIN_PER_D (60 * 24)
#define S_PER_D (60 * 60 * 24)
#define MS_PER_D (1000 * 60 * 60 * 24)

/*
 * Exported function to read and process the configuration file. The
 * parameter indicates in what context the file is being read --- either
 * postmaster startup (including standalone-backend startup) or SIGHUP.
 * All options mentioned in the configuration file are set to new values.
 * If an error occurs, no values will be changed.
 */
void
ProcessConfigFile(GtmOptContext context)
{
	int			elevel;
	ConfigVariable *item,
				   *head,
				   *tail;
	char	   *cvc = NULL;
	int			i;

	Assert((context == GTMC_STARTUP || context == GTMC_SIGHUP));

	if (context == GTMC_SIGHUP)
		elevel = DEBUG2;
	else
		elevel = ERROR;

	/* Parse the file into a list of option names and values */
	head = tail = NULL;

	if (!ParseConfigFile(GTMConfigFileName, NULL, 0, elevel, &head, &tail))
		goto cleanup_list;

#if 0
	/* No custom_variable_classes now */
	/*
	 * This part of the code remained the same as original guc.c because
	 * we might want to have custom variable class for gtm.conf.
	 */
	/*
	 * We need the proposed new value of custom_variable_classes to check
	 * custom variables with.  ParseConfigFile ensured that if it's in
	 * the file, it's first in the list.  But first check to see if we
	 * have an active value from the command line, which should override
	 * the file in any case.  (Since there's no relevant env var, the
	 * only possible nondefault sources are the file and ARGV.)
	 */
	cvc_struct = (struct config_string *)
		find_option("custom_variable_classes", false, elevel);
	Assert(cvc_struct);
	if (cvc_struct->gen.reset_source > GTMC_S_FILE)
	{
		cvc = gtm_opt_strdup(elevel, cvc_struct->reset_val);
		if (cvc == NULL)
			goto cleanup_list;
	}
	else if (head != NULL &&
			 gtm_opt_name_compare(head->name, "custom_variable_classes") == 0)
	{
		/*
		 * Need to canonicalize the value by calling the check hook.
		 */
		void   *extra = NULL;

		cvc = gtm_opt_strdup(elevel, head->value);
		if (cvc == NULL)
			goto cleanup_list;
		if (extra)
			free(extra);
	}
#endif

	/*
	 * Mark all extant GUC variables as not present in the config file.
	 * We need this so that we can tell below which ones have been removed
	 * from the file since we last processed it.
	 */
	for (i = 0; i < num_gtm_opt_variables; i++)
	{
		struct config_generic *gconf = gtm_opt_variables[i];

		gconf->status &= ~GTMOPT_IS_IN_FILE;
	}

	/*
	 * Check if all options are valid.  As a side-effect, the GTMOPT_IS_IN_FILE
	 * flag is set on each GUC variable mentioned in the list.
	 */
	for (item = head; item; item = item->next)
	{
		char *sep = strchr(item->name, GTMOPT_QUALIFIER_SEPARATOR);

		if (sep)
		{
			/*
			 * There is no GUC entry.  If we called set_config_option then
			 * it would make a placeholder, which we don't want to do yet,
			 * since we could still fail further down the list.  Do nothing
			 * (assuming that making the placeholder will succeed later).
			 */
			if (find_option(item->name, false, elevel) == NULL)
				continue;
			/*
			 * 3. There is already a GUC entry (either real or placeholder) for
			 * the variable.  In this case we should let set_config_option
			 * check it, since the assignment could well fail if it's a real
			 * entry.
			 */
		}

		if (!set_config_option(item->name, item->value, context,
							   GTMC_S_FILE, false))
			goto cleanup_list;
	}

	/*
	 * Check for variables having been removed from the config file, and
	 * revert their reset values (and perhaps also effective values) to the
	 * boot-time defaults.  If such a variable can't be changed after startup,
	 * just throw a warning and continue.  (This is analogous to the fact that
	 * set_config_option only throws a warning for a new but different value.
	 * If we wanted to make it a hard error, we'd need an extra pass over the
	 * list so that we could throw the error before starting to apply
	 * changes.)
	 */
	for (i = 0; i < num_gtm_opt_variables; i++)
	{
		struct config_generic *gconf = gtm_opt_variables[i];
		GtmOptStack   *stack;

		if (gconf->reset_source != GTMC_S_FILE ||
			(gconf->status & GTMOPT_IS_IN_FILE))
			continue;
		if (gconf->context < GTMC_SIGHUP)
		{
			/*
			 * In the original code, errcode() stores specified error code to sqlerrcode, which does not
			 * exist in GTM.
			 */
			if (isStartUp)
			{
				write_stderr("parameter \"%s\" cannot be changed without restarting the server",
							 gconf->name);
			}
			else
			{
				ereport(elevel,
						(0,
						 errmsg("parameter \"%s\" cannot be changed without restarting the server",
								gconf->name)));
			}
			continue;
		}

		/*
		 * Reset any "file" sources to "default", else set_config_option
		 * will not override those settings.
		 */
		if (gconf->reset_source == GTMC_S_FILE)
			gconf->reset_source = GTMC_S_DEFAULT;
		if (gconf->source == GTMC_S_FILE)
			gconf->source = GTMC_S_DEFAULT;
		for (stack = gconf->stack; stack; stack = stack->prev)
		{
			if (stack->source == GTMC_S_FILE)
				stack->source = GTMC_S_DEFAULT;
		}

		/* Now we can re-apply the wired-in default (i.e., the boot_val) */
		set_config_option(gconf->name, NULL, context, GTMC_S_DEFAULT,
						  true);
		if (context == GTMC_SIGHUP)
		{
			if (isStartUp)
			{
				write_stderr("parameter \"%s\" removed from configuration file, reset to default\n",
							 gconf->name);
			}
			else
			{
				ereport(elevel,
						(errmsg("parameter \"%s\" removed from configuration file, reset to default",
								gconf->name)));
			}
		}
	}

	/*
	 * Restore any variables determined by environment variables or
	 * dynamically-computed defaults.  This is a no-op except in the case
	 * where one of these had been in the config file and is now removed.
	 *
	 * In particular, we *must not* do this during the postmaster's
	 * initial loading of the file, since the timezone functions in
	 * particular should be run only after initialization is complete.
	 *
	 * XXX this is an unmaintainable crock, because we have to know how
	 * to set (or at least what to call to set) every variable that could
	 * potentially have GTMC_S_DYNAMIC_DEFAULT or GTMC_S_ENV_VAR source.
	 * However, there's no time to redesign it for 9.1.
	 */

	/* If we got here all the options checked out okay, so apply them. */
	for (item = head; item; item = item->next)
	{
		char   *pre_value = NULL;

		if (set_config_option(item->name, item->value, context,
			   					 GTMC_S_FILE, true))
		{
			set_config_sourcefile(item->name, item->filename,
								  item->sourceline);

			if (pre_value)
			{
				const char *post_value = GetConfigOption(item->name, false);

				if (!post_value)
					post_value = "";
				if (strcmp(pre_value, post_value) != 0)
				{
					if (isStartUp)
					{
						write_stderr("parameter \"%s\" changed to \"%s\"\n",
									 item->name, item->value);
					}
					else
					{
						ereport(elevel,
								(errmsg("parameter \"%s\" changed to \"%s\"",
										item->name, item->value)));
					}
				}
			}
		}

		if (pre_value)
			free(pre_value);
	}

	/* PGXCTODO: configuration file reload time update */

cleanup_list:
	FreeConfigVariables(head);
	if (cvc)
		free(cvc);
}

/*
 * See next function for details. This one will just work with a config_file
 * name rather than an already opened File Descriptor
 */
bool
ParseConfigFile(const char *config_file, const char *calling_file,
				int depth, int elevel,
				ConfigVariable **head_p,
				ConfigVariable **tail_p)
{
	bool		OK = true;
	FILE	   *fp;
	char		abs_path[MAXPGPATH];

	/*
	 * Reject too-deep include nesting depth.  This is just a safety check
	 * to avoid dumping core due to stack overflow if an include file loops
	 * back to itself.  The maximum nesting depth is pretty arbitrary.
	 */
	if (depth > 10)
	{
		if (isStartUp)
		{
			write_stderr("could not open configuration file \"%s\": maximum nesting depth exceeded\n",
						 config_file);
		}
		else
		{
			ereport(elevel,
					(0,
					 errmsg("could not open configuration file \"%s\": maximum nesting depth exceeded",
							config_file)));
		}
		return false;
	}

	/*
	 * If config_file is a relative path, convert to absolute.  We consider
	 * it to be relative to the directory holding the calling file.
	 */
	if (!is_absolute_path(config_file))
	{
		if (calling_file != NULL)
		{
			strlcpy(abs_path, calling_file, sizeof(abs_path));
			get_parent_directory(abs_path);
			join_path_components(abs_path, abs_path, config_file);
			canonicalize_path(abs_path);
			config_file = abs_path;
		}
		else
		{
			/*
			 * calling_file is NULL, we make an absolute path from $PGDATA
			 */
			join_path_components(abs_path, data_directory, config_file);
			canonicalize_path(abs_path);
			config_file = abs_path;
		}
	}

	fp = fopen(config_file, "r");
	if (!fp)
	{
		if (isStartUp)
		{
			write_stderr("could not open configuration file \"%s\": %m\n",
						 config_file);
		}
		else
		{
			ereport(elevel,
					(0,
					 errmsg("could not open configuration file \"%s\": %m",
							config_file)));
		}
		return false;
	}

	OK = ParseConfigFp(fp, config_file, depth, elevel, head_p, tail_p);

	fclose(fp);

	return OK;
}

/*
 * Read and parse a single configuration file.  This function recurses
 * to handle "include" directives.
 *
 * Input parameters:
 *	fp: file pointer from AllocateFile for the configuration file to parse
 *	config_file: absolute or relative path of file to read
 *	depth: recursion depth (used only to prevent infinite recursion)
 *	elevel: error logging level determined by ProcessConfigFile()
 * Output parameters:
 *	head_p, tail_p: head and tail of linked list of name/value pairs
 *
 * *head_p and *tail_p must be initialized to NULL before calling the outer
 * recursion level.  On exit, they contain a list of name-value pairs read
 * from the input file(s).
 *
 * Returns TRUE if successful, FALSE if an error occurred.  The error has
 * already been ereport'd, it is only necessary for the caller to clean up
 * its own state and release the name/value pairs list.
 *
 * Note: if elevel >= ERROR then an error will not return control to the
 * caller, and internal state such as open files will not be cleaned up.
 * This case occurs only during postmaster or standalone-backend startup,
 * where an error will lead to immediate process exit anyway; so there is
 * no point in contorting the code so it can clean up nicely.
 */
bool
ParseConfigFp(FILE *fp, const char *config_file, int depth, int elevel,
			  ConfigVariable **head_p, ConfigVariable **tail_p)
{
	bool		OK = true;
	YY_BUFFER_STATE lex_buffer;
	int			token;

	/*
	 * Parse
	 */
	lex_buffer = GTMOPT_yy_create_buffer(fp, YY_BUF_SIZE);
	GTMOPT_yy_switch_to_buffer(lex_buffer);

	ConfigFileLineno = 1;

	/* This loop iterates once per logical line */
	while ((token = GTMOPT_yylex()))
	{
		char	   *opt_name, *opt_value;
		ConfigVariable *item;

		if (token == GTMOPT_EOL)	/* empty or comment line */
			continue;

		/* first token on line is option name */
		if (token != GTMOPT_ID && token != GTMOPT_QUALIFIED_ID)
			goto parse_error;
		opt_name = strdup(GTMOPT_yytext);

		/* next we have an optional equal sign; discard if present */
		token = GTMOPT_yylex();
		if (token == GTMOPT_EQUALS)
			token = GTMOPT_yylex();

		/* now we must have the option value */
		if (token != GTMOPT_ID &&
			token != GTMOPT_STRING &&
			token != GTMOPT_INTEGER &&
			token != GTMOPT_REAL &&
			token != GTMOPT_UNQUOTED_STRING)
			goto parse_error;
		if (token == GTMOPT_STRING)	/* strip quotes and escapes */
			opt_value = GTMOPT_scanstr(GTMOPT_yytext);
		else
			opt_value = strdup(GTMOPT_yytext);

		/* now we'd like an end of line, or possibly EOF */
		token = GTMOPT_yylex();
		if (token != GTMOPT_EOL)
		{
			if (token != 0)
				goto parse_error;
			/* treat EOF like \n for line numbering purposes, cf bug 4752 */
			ConfigFileLineno++;
		}

		/* OK, process the option name and value */
		if (gtm_opt_name_compare(opt_name, "include") == 0)
		{
			/*
			 * An include directive isn't a variable and should be processed
			 * immediately.
			 */
			unsigned int save_ConfigFileLineno = ConfigFileLineno;

			if (!ParseConfigFile(opt_value, config_file,
								 depth + 1, elevel,
								 head_p, tail_p))
			{
				free(opt_name);
				free(opt_value);
				OK = false;
				goto cleanup_exit;
			}
			GTMOPT_yy_switch_to_buffer(lex_buffer);
			ConfigFileLineno = save_ConfigFileLineno;
			free(opt_name);
			free(opt_value);
		}
		else if (gtm_opt_name_compare(opt_name, "custom_variable_classes") == 0)
		{
			/*
			 * This variable must be processed first as it controls
			 * the validity of other variables; so it goes at the head
			 * of the result list.  If we already found a value for it,
			 * replace with this one.
			 */
			item = *head_p;
			if (item != NULL &&
				gtm_opt_name_compare(item->name, "custom_variable_classes") == 0)
			{
				/* replace existing head item */
				free(item->name);
				free(item->value);
				item->name = opt_name;
				item->value = opt_value;
				item->filename = strdup(config_file);
				item->sourceline = ConfigFileLineno-1;
			}
			else
			{
				/* prepend to list */
				item = malloc(sizeof *item);
				item->name = opt_name;
				item->value = opt_value;
				item->filename = strdup(config_file);
				item->sourceline = ConfigFileLineno-1;
				item->next = *head_p;
				*head_p = item;
				if (*tail_p == NULL)
					*tail_p = item;
			}
		}
		else
		{
			/* ordinary variable, append to list */
			item = malloc(sizeof *item);
			item->name = opt_name;
			item->value = opt_value;
			item->filename = strdup(config_file);
			item->sourceline = ConfigFileLineno-1;
			item->next = NULL;
			if (*head_p == NULL)
				*head_p = item;
			else
				(*tail_p)->next = item;
			*tail_p = item;
		}

		/* break out of loop if read EOF, else loop for next line */
		if (token == 0)
			break;
	}

	/* successful completion of parsing */
	goto cleanup_exit;

 parse_error:
	if (token == GTMOPT_EOL || token == 0)
	{
		if (isStartUp)
		{
			write_stderr("syntax error in file \"%s\" line %u, near end of line\n",
						 config_file, ConfigFileLineno - 1);
		}
		else
		{
			ereport(elevel,
					(0,
					 errmsg("syntax error in file \"%s\" line %u, near end of line",
							config_file, ConfigFileLineno - 1)));
		}
	}
	else
	{
		if (isStartUp)
		{
			write_stderr("syntax error in file \"%s\" line %u, near token \"%s\"\n",
						 config_file, ConfigFileLineno, GTMOPT_yytext);
		}
		else
		{
			ereport(elevel,
					(0,
					 errmsg("syntax error in file \"%s\" line %u, near token \"%s\"",
							config_file, ConfigFileLineno, GTMOPT_yytext)));
		}
	}
	OK = false;

cleanup_exit:
	GTMOPT_yy_delete_buffer(lex_buffer);
	return OK;
}


/*
 * Free a list of ConfigVariables, including the names and the values
 */
void
FreeConfigVariables(ConfigVariable *list)
{
	ConfigVariable *item;

	item = list;
	while (item)
	{
		ConfigVariable *next = item->next;

		free(item->name);
		free(item->value);
		free(item->filename);
		free(item);
		item = next;
	}
}


/*
 *		scanstr
 *
 * Strip the quotes surrounding the given string, and collapse any embedded
 * '' sequences and backslash escapes.
 *
 * the string returned is malloc'd and should eventually be free'd by the
 * caller.
 */
static char *
GTMOPT_scanstr(const char *s)
{
	char	   *newStr;
	int			len,
				i,
				j;

	Assert(s != NULL && s[0] == '\'');
	len = strlen(s);
	Assert(len >= 2);
	Assert(s[len-1] == '\'');

	/* Skip the leading quote; we'll handle the trailing quote below */
	s++, len--;

	/* Since len still includes trailing quote, this is enough space */
	newStr = malloc(len);

	for (i = 0, j = 0; i < len; i++)
	{
		if (s[i] == '\\')
		{
			i++;
			switch (s[i])
			{
				case 'b':
					newStr[j] = '\b';
					break;
				case 'f':
					newStr[j] = '\f';
					break;
				case 'n':
					newStr[j] = '\n';
					break;
				case 'r':
					newStr[j] = '\r';
					break;
				case 't':
					newStr[j] = '\t';
					break;
				case '0':
				case '1':
				case '2':
				case '3':
				case '4':
				case '5':
				case '6':
				case '7':
					{
						int			k;
						long		octVal = 0;

						for (k = 0;
							 s[i + k] >= '0' && s[i + k] <= '7' && k < 3;
							 k++)
							octVal = (octVal << 3) + (s[i + k] - '0');
						i += k - 1;
						newStr[j] = ((char) octVal);
					}
					break;
				default:
					newStr[j] = s[i];
					break;
			}					/* switch */
		}
		else if (s[i] == '\'' && s[i+1] == '\'')
		{
			/* doubled quote becomes just one quote */
			newStr[j] = s[++i];
		}
		else
			newStr[j] = s[i];
		j++;
	}

	/* We copied the ending quote to newStr, so replace with \0 */
	Assert(j > 0 && j <= len);
	newStr[--j] = '\0';

	return newStr;
}

/*
 * The following code includes most of the code ported from guc.c.
 * Because they should be shared by gtm_opt.c and gtm_proxy_opt.c, they are placed here.
 */

/*
 * Some infrastructure for checking malloc/strdup/realloc calls
 */
static void *
gtm_opt_malloc(int elevel, size_t size)
{
	void	   *data;

	data = malloc(size);
	if (data == NULL)
	{
		if (isStartUp)
		{
			write_stderr("out of memory\n");
		}
		else
		{
			ereport(elevel,
					(0,
					 errmsg("out of memory")));
		}
	}
	return data;
}

#if 0
/* PGXCTODO: this will be used for future extensions */
static void *
gtm_opt_realloc(int elevel, void *old, size_t size)
{
	void	   *data;

	data = realloc(old, size);
	if (data == NULL)
	{
		if (isStartUp)
		{
			write_stderr("out of memory\n");
		}
		else
		{
			ereport(elevel,
					(0,
					 errmsg("out of memory")));
		}
	}
	return data;
}
#endif

static char *
gtm_opt_strdup(int elevel, const char *src)
{
	char	   *data;

	data = strdup(src);
	if (data == NULL)
	{
		if (isStartUp)
		{
			write_stderr("out of memory\n");
		}
		else
		{
			ereport(elevel,
					(0,
					 errmsg("out of memory")));
		}
	}
	return data;
}

/*
 * Detect whether strval is referenced anywhere in a GTM string item
 */
static bool
string_field_used(struct config_string * conf, char *strval)
{
	GtmOptStack   *stack;

	if (strval == *(conf->variable) ||
		strval == conf->reset_val ||
		strval == conf->boot_val)
		return true;
	for (stack = conf->gen.stack; stack; stack = stack->prev)
	{
		if (strval == stack->prior.val.stringval ||
			strval == stack->masked.val.stringval)
			return true;
	}
	return false;
}


/*
 * Support for assigning to a field of a string GTM item.  Free the prior
 * value if it's not referenced anywhere else in the item (including stacked
 * states).
 */
static void
set_string_field(struct config_string * conf, char **field, char *newval)
{
	char	   *oldval = *field;

	/* Do the assignment */
	*field = newval;

	/* Free old value if it's not NULL and isn't referenced anymore */
	if (oldval && !string_field_used(conf, oldval))
		free(oldval);
}


/*
 * Detect whether an "extra" struct is referenced anywhere in a GTM item
 */
static bool
extra_field_used(struct config_generic * gconf, void *extra)
{
	GtmOptStack   *stack;

	if (extra == gconf->extra)
		return true;
	switch (gconf->vartype)
	{
		case GTMC_BOOL:
			if (extra == ((struct config_bool *) gconf)->reset_extra)
				return true;
			break;
		case GTMC_INT:
			if (extra == ((struct config_int *) gconf)->reset_extra)
				return true;
			break;
		case GTMC_REAL:
			if (extra == ((struct config_real *) gconf)->reset_extra)
				return true;
			break;
		case GTMC_STRING:
			if (extra == ((struct config_string *) gconf)->reset_extra)
				return true;
			break;
		case GTMC_ENUM:
			if (extra == ((struct config_enum *) gconf)->reset_extra)
				return true;
			break;
	}
	for (stack = gconf->stack; stack; stack = stack->prev)
	{
		if (extra == stack->prior.extra ||
			extra == stack->masked.extra)
			return true;
	}

	return false;
}


/*
 * Support for assigning to an "extra" field of a GTM item.  Free the prior
 * value if it's not referenced anywhere else in the item (including stacked
 * states).
 */
static void
set_extra_field(struct config_generic * gconf, void **field, void *newval)
{
	void	   *oldval = *field;

	/* Do the assignment */
	*field = newval;

	/* Free old value if it's not NULL and isn't referenced anymore */
	if (oldval && !extra_field_used(gconf, oldval))
		free(oldval);
}


/*
 * Support for copying a variable's active value into a stack entry.
 * The "extra" field associated with the active value is copied, too.
 *
 * NB: be sure stringval and extra fields of a new stack entry are
 * initialized to NULL before this is used, else we'll try to free() them.
 */
static void
set_stack_value(struct config_generic * gconf, config_var_value *val)
{
	switch (gconf->vartype)
	{
		case GTMC_BOOL:
			val->val.boolval =
				*((struct config_bool *) gconf)->variable;
			break;
		case GTMC_INT:
			val->val.intval =
				*((struct config_int *) gconf)->variable;
			break;
		case GTMC_REAL:
			val->val.realval =
				*((struct config_real *) gconf)->variable;
			break;
		case GTMC_STRING:
			set_string_field((struct config_string *) gconf,
							 &(val->val.stringval),
							 *((struct config_string *) gconf)->variable);
			break;
		case GTMC_ENUM:
			val->val.enumval =
				*((struct config_enum *) gconf)->variable;
			break;
	}
	set_extra_field(gconf, &(val->extra), gconf->extra);
}

#if 0
/* PGXCTODO: This is let for future extension support */
/*
 * Support for discarding a no-longer-needed value in a stack entry.
 * The "extra" field associated with the stack entry is cleared, too.
 */
static void
discard_stack_value(struct config_generic * gconf, config_var_value *val)
{
	switch (gconf->vartype)
	{
		case GTMC_BOOL:
		case GTMC_INT:
		case GTMC_REAL:
		case GTMC_ENUM:
			/* no need to do anything */
			break;
		case GTMC_STRING:
			set_string_field((struct config_string *) gconf,
							 &(val->val.stringval),
							 NULL);
			break;
	}
	set_extra_field(gconf, &(val->extra), NULL);
}
#endif

/*
 * Fetch the sorted array pointer (exported for help_config.c's use ONLY)
 */
struct config_generic **
get_gtm_opt_variables(void)
{
	return gtm_opt_variables;
}

/*
 * Build the sorted array.	This is split out so that it could be
 * re-executed after startup (eg, we could allow loadable modules to
 * add vars, and then we'd need to re-sort).
 */
void
build_gtm_opt_variables(void)
{
	int			size_vars;
	int			num_vars = 0;
	struct config_generic **gtm_opt_vars;
	int			i;

	for (i = 0; ConfigureNamesBool[i].gen.name; i++)
	{
		struct config_bool *conf = &ConfigureNamesBool[i];

		/* Rather than requiring vartype to be filled in by hand, do this: */
		conf->gen.vartype = GTMC_BOOL;
		num_vars++;
	}

	for (i = 0; ConfigureNamesInt[i].gen.name; i++)
	{
		struct config_int *conf = &ConfigureNamesInt[i];

		conf->gen.vartype = GTMC_INT;
		num_vars++;
	}

	for (i = 0; ConfigureNamesReal[i].gen.name; i++)
	{
		struct config_real *conf = &ConfigureNamesReal[i];

		conf->gen.vartype = GTMC_REAL;
		num_vars++;
	}

	for (i = 0; ConfigureNamesString[i].gen.name; i++)
	{
		struct config_string *conf = &ConfigureNamesString[i];

		conf->gen.vartype = GTMC_STRING;
		num_vars++;
	}

	for (i = 0; ConfigureNamesEnum[i].gen.name; i++)
	{
		struct config_enum *conf = &ConfigureNamesEnum[i];

		conf->gen.vartype = GTMC_ENUM;
		num_vars++;
	}

	/*
	 * Create table with 20% slack
	 */
	size_vars = num_vars + num_vars / 4;

	gtm_opt_vars = (struct config_generic **)
		gtm_opt_malloc(FATAL, size_vars * sizeof(struct config_generic *));

	num_vars = 0;

	for (i = 0; ConfigureNamesBool[i].gen.name; i++)
		gtm_opt_vars[num_vars++] = &ConfigureNamesBool[i].gen;

	for (i = 0; ConfigureNamesInt[i].gen.name; i++)
		gtm_opt_vars[num_vars++] = &ConfigureNamesInt[i].gen;

	for (i = 0; ConfigureNamesReal[i].gen.name; i++)
		gtm_opt_vars[num_vars++] = &ConfigureNamesReal[i].gen;

	for (i = 0; ConfigureNamesString[i].gen.name; i++)
		gtm_opt_vars[num_vars++] = &ConfigureNamesString[i].gen;

	for (i = 0; ConfigureNamesEnum[i].gen.name; i++)
		gtm_opt_vars[num_vars++] = &ConfigureNamesEnum[i].gen;

	if (gtm_opt_variables)
		free(gtm_opt_variables);
	gtm_opt_variables = gtm_opt_vars;
	num_gtm_opt_variables = num_vars;
	size_gtm_opt_variables = size_vars;
	qsort((void *) gtm_opt_variables, num_gtm_opt_variables,
		  sizeof(struct config_generic *), gtm_opt_var_compare);
}


#if 0
/* PGXCTODO: This is let for future extension support */
/*
 * Add a new GTM variable to the list of known variables. The
 * list is expanded if needed.
 */
static bool
add_gtm_opt_variable(struct config_generic * var, int elevel)
{
	if (num_gtm_opt_variables + 1 >= size_gtm_opt_variables)
	{
		/*
		 * Increase the vector by 25%
		 */
		int			size_vars = size_gtm_opt_variables + size_gtm_opt_variables / 4;
		struct config_generic **gtm_opt_vars;

		if (size_vars == 0)
		{
			size_vars = 100;
			gtm_opt_vars = (struct config_generic **)
				gtm_opt_malloc(elevel, size_vars * sizeof(struct config_generic *));
		}
		else
		{
			gtm_opt_vars = (struct config_generic **)
				gtm_opt_realloc(elevel, gtm_opt_variables, size_vars * sizeof(struct config_generic *));
		}

		if (gtm_opt_vars == NULL)
			return false;		/* out of memory */

		gtm_opt_variables = gtm_opt_vars;
		size_gtm_opt_variables = size_vars;
	}
	gtm_opt_variables[num_gtm_opt_variables++] = var;
	qsort((void *) gtm_opt_variables, num_gtm_opt_variables,
		  sizeof(struct config_generic *), gtm_opt_var_compare);
	return true;
}


/*
 * Create and add a placeholder variable. It's presumed to belong
 * to a valid custom variable class at this point.
 */
static struct config_generic *
add_placeholder_variable(const char *name, int elevel)
{
	size_t		sz = sizeof(struct config_string) + sizeof(char *);
	struct config_string *var;
	struct config_generic *gen;

	var = (struct config_string *) gtm_opt_malloc(elevel, sz);
	if (var == NULL)
		return NULL;
	memset(var, 0, sz);
	gen = &var->gen;

	gen->name = gtm_opt_strdup(elevel, name);
	if (gen->name == NULL)
	{
		free(var);
		return NULL;
	}

	gen->context = GTMC_USERSET;
	gen->short_desc = "GTM placeholder variable";
	gen->flags = GTMOPT_NO_SHOW_ALL | GTMOPT_NOT_IN_SAMPLE | GTMOPT_CUSTOM_PLACEHOLDER;
	gen->vartype = GTMC_STRING;

	/*
	 * The char* is allocated at the end of the struct since we have no
	 * 'static' place to point to.	Note that the current value, as well as
	 * the boot and reset values, start out NULL.
	 */
	var->variable = (char **) (var + 1);

	if (!add_gtm_opt_variable((struct config_generic *) var, elevel))
	{
		free((void *) gen->name);
		free(var);
		return NULL;
	}

	return gen;
}
#endif

/*
 * Look up option NAME.  If it exists, return a pointer to its record,
 * else return NULL.  If create_placeholders is TRUE, we'll create a
 * placeholder record for a valid-looking custom variable name.
 */
static struct config_generic *
find_option(const char *name, bool create_placeholders, int elevel)
{
	const char **key = &name;
	struct config_generic **res;

	Assert(name);

	/*
	 * By equating const char ** with struct config_generic *, we are assuming
	 * the name field is first in config_generic.
	 */
	res = (struct config_generic **) bsearch((void *) &key,
											 (void *) gtm_opt_variables,
											 num_gtm_opt_variables,
											 sizeof(struct config_generic *),
											 gtm_opt_var_compare);
	if (res)
		return *res;

	/* Unknown name */
	return NULL;
}


/*
 * comparator for qsorting and bsearching gtm_opt_variables array
 */
static int
gtm_opt_var_compare(const void *a, const void *b)
{
	struct config_generic *confa = *(struct config_generic **) a;
	struct config_generic *confb = *(struct config_generic **) b;

	return gtm_opt_name_compare(confa->name, confb->name);
}


/*
 * the bare comparison function for GTM names
 */
static int
gtm_opt_name_compare(const char *namea, const char *nameb)
{
	/*
	 * The temptation to use strcasecmp() here must be resisted, because the
	 * array ordering has to remain stable across setlocale() calls. So, build
	 * our own with a simple ASCII-only downcasing.
	 */
	while (*namea && *nameb)
	{
		char		cha = *namea++;
		char		chb = *nameb++;

		if (cha >= 'A' && cha <= 'Z')
			cha += 'a' - 'A';
		if (chb >= 'A' && chb <= 'Z')
			chb += 'a' - 'A';
		if (cha != chb)
			return cha - chb;
	}
	if (*namea)
		return 1;				/* a is longer */
	if (*nameb)
		return -1;				/* b is longer */
	return 0;
}


/*
 * Initialize GTM options during program startup.
 *
 * Note that we cannot read the config file yet, since we have not yet
 * processed command-line switches.
 */
void
InitializeGTMOptions(void)
{
	int			i;

	/*
	 * Build sorted array of all GTM variables.
	 */
	build_gtm_opt_variables();

	/*
	 * Load all variables with their compiled-in defaults, and initialize
	 * status fields as needed.
	 */
	for (i = 0; i < num_gtm_opt_variables; i++)
	{
		InitializeOneGTMOption(gtm_opt_variables[i]);
	}

	reporting_enabled = false;

}


/*
 * Initialize one GTM option variable to its compiled-in default.
 *
 * Note: the reason for calling check_hooks is not that we think the boot_val
 * might fail, but that the hooks might wish to compute an "extra" struct.
 */
static void
InitializeOneGTMOption(struct config_generic * gconf)
{
	gconf->status = 0;
	gconf->reset_source = GTMC_S_DEFAULT;
	gconf->source = GTMC_S_DEFAULT;
	gconf->stack = NULL;
	gconf->extra = NULL;
	gconf->sourcefile = NULL;
	gconf->sourceline = 0;
	gconf->context = GTMC_DEFAULT;

	switch (gconf->vartype)
	{
		case GTMC_BOOL:
			{
				struct config_bool *conf = (struct config_bool *) gconf;
				bool		newval = conf->boot_val;
				void	   *extra = NULL;

				*conf->variable = conf->reset_val = newval;
				conf->gen.extra = conf->reset_extra = extra;
				break;
			}
		case GTMC_INT:
			{
				struct config_int *conf = (struct config_int *) gconf;
				int			newval = conf->boot_val;
				void	   *extra = NULL;

				Assert(newval >= conf->min);
				Assert(newval <= conf->max);
				*conf->variable = conf->reset_val = newval;
				conf->gen.extra = conf->reset_extra = extra;
				break;
			}
		case GTMC_REAL:
			{
				struct config_real *conf = (struct config_real *) gconf;
				double		newval = conf->boot_val;
				void	   *extra = NULL;

				Assert(newval >= conf->min);
				Assert(newval <= conf->max);
				*conf->variable = conf->reset_val = newval;
				conf->gen.extra = conf->reset_extra = extra;
				break;
			}
		case GTMC_STRING:
			{
				struct config_string *conf = (struct config_string *) gconf;
				char	   *newval;
				void	   *extra = NULL;

				/* non-NULL boot_val must always get strdup'd */
				if (conf->boot_val != NULL)
					newval = gtm_opt_strdup(FATAL, conf->boot_val);
				else
					newval = NULL;

				*conf->variable = conf->reset_val = newval;
				conf->gen.extra = conf->reset_extra = extra;
				break;
			}
		case GTMC_ENUM:
			{
				struct config_enum *conf = (struct config_enum *) gconf;
				int			newval = conf->boot_val;
				void	   *extra = NULL;

				*conf->variable = conf->reset_val = newval;
				conf->gen.extra = conf->reset_extra = extra;
				break;
			}
	}
}


/*
 * Select the configuration files and data directory to be used, and
 * do the initial read of postgresql.conf.
 *
 * This is called after processing command-line switches.
 *		userDoption is the -D switch value if any (NULL if unspecified).
 *		progname is just for use in error messages.
 *
 * Returns true on success; on failure, prints a suitable error message
 * to stderr and returns false.
 */
bool
SelectConfigFiles(const char *userDoption, const char *progname)
{
	char	   *configdir;
	char	   *fname;
	struct stat stat_buf;

	/* configdir is -D option, or $PGDATA if no -D */
	if (userDoption)
		configdir = make_absolute_path(userDoption);
	else
		configdir = NULL;

	/*
	 * Find the configuration file: if config_file was specified on the
	 * command line, use it, else use configdir/postgresql.conf.  In any case
	 * ensure the result is an absolute path, so that it will be interpreted
	 * the same way by future backends.
	 */
	if (GTMConfigFileName)
	{
		if (GTMConfigFileName[0] == '/')
			fname = make_absolute_path(GTMConfigFileName);
		else
		{
			if (configdir)
			{
				fname = gtm_opt_malloc(FATAL,
									   strlen(configdir) + strlen(GTMConfigFileName) + 2);
				sprintf(fname, "%s/%s", configdir, GTMConfigFileName);
			}
			else
				fname = make_absolute_path(GTMConfigFileName);
		}
	}
	else if (configdir)
	{
		fname = gtm_opt_malloc(FATAL,
						   strlen(configdir) + strlen(config_filename) + 2);
		sprintf(fname, "%s/%s", configdir, config_filename);
	}
	else
	{
		write_stderr("%s does not know where to find the server configuration file.\n"
					 "You must specify the --config-file or -D invocation "
					 "option or set the PGDATA environment variable.\n",
					 progname);
		return false;
	}

	/*
	 * Set the GTMConfigFileName GTM variable to its final value, ensuring that
	 * it can't be overridden later.
	 */
	SetConfigOption("config_file", fname, GTMC_STARTUP, GTMC_S_OVERRIDE);
	free(fname);

	/*
	 * Now read the config file for the first time.
	 */
	if (stat(GTMConfigFileName, &stat_buf) != 0)
	{
		write_stderr("%s cannot access the server configuration file \"%s\": %s\n",
					 progname, GTMConfigFileName, strerror(errno));
		return false;
	}

	ProcessConfigFile(GTMC_STARTUP);

	free(configdir);

	return true;
}

/*
 * Reset all options to their saved default values (implements RESET ALL)
 */
void
ResetAllOptions(void)
{
	int			i;

	for (i = 0; i < num_gtm_opt_variables; i++)
	{
		struct config_generic *gconf = gtm_opt_variables[i];

		/* Don't reset if special exclusion from RESET ALL */
		if (gconf->flags & GTMOPT_NO_RESET_ALL)
			continue;
		/* No need to reset if wasn't SET */
		if (gconf->source <= GTMC_S_OVERRIDE)
			continue;

		switch (gconf->vartype)
		{
			case GTMC_BOOL:
				{
					struct config_bool *conf = (struct config_bool *) gconf;

					*conf->variable = conf->reset_val;
					set_extra_field(&conf->gen, &conf->gen.extra,
									conf->reset_extra);
					break;
				}
			case GTMC_INT:
				{
					struct config_int *conf = (struct config_int *) gconf;

					*conf->variable = conf->reset_val;
					set_extra_field(&conf->gen, &conf->gen.extra,
									conf->reset_extra);
					break;
				}
			case GTMC_REAL:
				{
					struct config_real *conf = (struct config_real *) gconf;

					*conf->variable = conf->reset_val;
					set_extra_field(&conf->gen, &conf->gen.extra,
									conf->reset_extra);
					break;
				}
			case GTMC_STRING:
				{
					struct config_string *conf = (struct config_string *) gconf;

					set_string_field(conf, conf->variable, conf->reset_val);
					set_extra_field(&conf->gen, &conf->gen.extra,
									conf->reset_extra);
					break;
				}
			case GTMC_ENUM:
				{
					struct config_enum *conf = (struct config_enum *) gconf;

					*conf->variable = conf->reset_val;
					set_extra_field(&conf->gen, &conf->gen.extra,
									conf->reset_extra);
					break;
				}
		}

		gconf->source = gconf->reset_source;

		if (gconf->flags & GTMOPT_REPORT)
			ReportGTMOption(gconf);
	}
}



/*
 * push_old_value
 *		Push previous state during transactional assignment to a GTM variable.
 */
static void
push_old_value(struct config_generic * gconf)
{
	GtmOptStack   *stack;

	/* If we're not inside a nest level, do nothing */
	if (GTMOptUpdateCount == 0)
		return;

	/* Do we already have a stack entry of the current nest level? */
	stack = gconf->stack;
	if (stack && stack->nest_level >= GTMOptUpdateCount)
		return;

	/*
	 * Push a new stack entry
	 *
	 * We keep all the stack entries in TopTransactionContext for simplicity.
	 */
	stack = (GtmOptStack *) MemoryContextAllocZero(TopMemoryContext,
												sizeof(GtmOptStack));

	stack->prev = gconf->stack;
	stack->nest_level = GTMOptUpdateCount;
	stack->source = gconf->source;
	set_stack_value(gconf, &stack->prior);

	gconf->stack = stack;
}



/*
 * Enter a new nesting level for GTM values.  This is called at subtransaction
 * start and when entering a function that has proconfig settings.	NOTE that
 * we must not risk error here, else subtransaction start will be unhappy.
 */
int
NewGTMNestLevel(void)
{
	return ++GTMOptUpdateCount;
}

/*
 * Try to parse value as an integer.  The accepted formats are the
 * usual decimal, octal, or hexadecimal formats, optionally followed by
 * a unit name if "flags" indicates a unit is allowed.
 *
 * If the string parses okay, return true, else false.
 * If okay and result is not NULL, return the value in *result.
 * If not okay and hintmsg is not NULL, *hintmsg is set to a suitable
 *	HINT message, or NULL if no hint provided.
 */
bool
parse_int(const char *value, int *result, int flags, const char **hintmsg)
{
	int64		val;
	char	   *endptr;

	/* To suppress compiler warnings, always set output params */
	if (result)
		*result = 0;
	if (hintmsg)
		*hintmsg = NULL;

	/* We assume here that int64 is at least as wide as long */
	errno = 0;
	val = strtol(value, &endptr, 0);

	if (endptr == value)
		return false;			/* no HINT for integer syntax error */

	if (errno == ERANGE || val != (int64) ((int32) val))
	{
		if (hintmsg)
			*hintmsg = gettext_noop("Value exceeds integer range.");
		return false;
	}

	/* allow whitespace between integer and unit */
	while (isspace((unsigned char) *endptr))
		endptr++;

	/* Handle possible unit */
	if (*endptr != '\0')
	{
		/*
		 * Note: the multiple-switch coding technique here is a bit tedious,
		 * but seems necessary to avoid intermediate-value overflows.
		 */
		if (flags & GTMOPT_UNIT_MEMORY)
		{
			/* Set hint for use if no match or trailing garbage */
			if (hintmsg)
				*hintmsg = gettext_noop("Valid units for this parameter are \"kB\", \"MB\", and \"GB\".");

#if BLCKSZ < 1024 || BLCKSZ > (1024*1024)
#error BLCKSZ must be between 1KB and 1MB
#endif
#if XLOG_BLCKSZ < 1024 || XLOG_BLCKSZ > (1024*1024)
#error XLOG_BLCKSZ must be between 1KB and 1MB
#endif

			if (strncmp(endptr, "kB", 2) == 0)
			{
				endptr += 2;
				switch (flags & GTMOPT_UNIT_MEMORY)
				{
					case GTMOPT_UNIT_BLOCKS:
						val /= (BLCKSZ / 1024);
						break;
					case GTMOPT_UNIT_XBLOCKS:
						val /= (XLOG_BLCKSZ / 1024);
						break;
				}
			}
			else if (strncmp(endptr, "MB", 2) == 0)
			{
				endptr += 2;
				switch (flags & GTMOPT_UNIT_MEMORY)
				{
					case GTMOPT_UNIT_KB:
						val *= KB_PER_MB;
						break;
					case GTMOPT_UNIT_BLOCKS:
						val *= KB_PER_MB / (BLCKSZ / 1024);
						break;
					case GTMOPT_UNIT_XBLOCKS:
						val *= KB_PER_MB / (XLOG_BLCKSZ / 1024);
						break;
				}
			}
			else if (strncmp(endptr, "GB", 2) == 0)
			{
				endptr += 2;
				switch (flags & GTMOPT_UNIT_MEMORY)
				{
					case GTMOPT_UNIT_KB:
						val *= KB_PER_GB;
						break;
					case GTMOPT_UNIT_BLOCKS:
						val *= KB_PER_GB / (BLCKSZ / 1024);
						break;
					case GTMOPT_UNIT_XBLOCKS:
						val *= KB_PER_GB / (XLOG_BLCKSZ / 1024);
						break;
				}
			}
		}
		else if (flags & GTMOPT_UNIT_TIME)
		{
			/* Set hint for use if no match or trailing garbage */
			if (hintmsg)
				*hintmsg = gettext_noop("Valid units for this parameter are \"ms\", \"s\", \"min\", \"h\", and \"d\".");

			if (strncmp(endptr, "ms", 2) == 0)
			{
				endptr += 2;
				switch (flags & GTMOPT_UNIT_TIME)
				{
					case GTMOPT_UNIT_S:
						val /= MS_PER_S;
						break;
					case GTMOPT_UNIT_MIN:
						val /= MS_PER_MIN;
						break;
				}
			}
			else if (strncmp(endptr, "s", 1) == 0)
			{
				endptr += 1;
				switch (flags & GTMOPT_UNIT_TIME)
				{
					case GTMOPT_UNIT_MS:
						val *= MS_PER_S;
						break;
					case GTMOPT_UNIT_MIN:
						val /= S_PER_MIN;
						break;
				}
			}
			else if (strncmp(endptr, "min", 3) == 0)
			{
				endptr += 3;
				switch (flags & GTMOPT_UNIT_TIME)
				{
					case GTMOPT_UNIT_MS:
						val *= MS_PER_MIN;
						break;
					case GTMOPT_UNIT_S:
						val *= S_PER_MIN;
						break;
				}
			}
			else if (strncmp(endptr, "h", 1) == 0)
			{
				endptr += 1;
				switch (flags & GTMOPT_UNIT_TIME)
				{
					case GTMOPT_UNIT_MS:
						val *= MS_PER_H;
						break;
					case GTMOPT_UNIT_S:
						val *= S_PER_H;
						break;
					case GTMOPT_UNIT_MIN:
						val *= MIN_PER_H;
						break;
				}
			}
			else if (strncmp(endptr, "d", 1) == 0)
			{
				endptr += 1;
				switch (flags & GTMOPT_UNIT_TIME)
				{
					case GTMOPT_UNIT_MS:
						val *= MS_PER_D;
						break;
					case GTMOPT_UNIT_S:
						val *= S_PER_D;
						break;
					case GTMOPT_UNIT_MIN:
						val *= MIN_PER_D;
						break;
				}
			}
		}

		/* allow whitespace after unit */
		while (isspace((unsigned char) *endptr))
			endptr++;

		if (*endptr != '\0')
			return false;		/* appropriate hint, if any, already set */

		/* Check for overflow due to units conversion */
		if (val != (int64) ((int32) val))
		{
			if (hintmsg)
				*hintmsg = gettext_noop("Value exceeds integer range.");
			return false;
		}
	}

	if (result)
		*result = (int) val;
	return true;
}



/*
 * Try to parse value as a floating point number in the usual format.
 * If the string parses okay, return true, else false.
 * If okay and result is not NULL, return the value in *result.
 */
bool
parse_real(const char *value, double *result)
{
	double		val;
	char	   *endptr;

	if (result)
		*result = 0;			/* suppress compiler warning */

	errno = 0;
	val = strtod(value, &endptr);
	if (endptr == value || errno == ERANGE)
		return false;

	/* allow whitespace after number */
	while (isspace((unsigned char) *endptr))
		endptr++;
	if (*endptr != '\0')
		return false;

	if (result)
		*result = val;
	return true;
}



/*
 * Lookup the value for an enum option with the selected name
 * (case-insensitive).
 * If the enum option is found, sets the retval value and returns
 * true. If it's not found, return FALSE and retval is set to 0.
 */
bool
config_enum_lookup_by_name(struct config_enum * record, const char *value,
						   int *retval)
{
	const struct config_enum_entry *entry;

	for (entry = record->options; entry && entry->name; entry++)
	{
		if (pg_strcasecmp(value, entry->name) == 0)
		{
			*retval = entry->val;
			return TRUE;
		}
	}

	*retval = 0;
	return FALSE;
}



/*
 * Return a list of all available options for an enum, excluding
 * hidden ones, separated by the given separator.
 * If prefix is non-NULL, it is added before the first enum value.
 * If suffix is non-NULL, it is added to the end of the string.
 */
static char *
config_enum_get_options(struct config_enum * record, const char *prefix,
						const char *suffix, const char *separator)
{
	const struct config_enum_entry *entry;
	StringInfoData retstr;
	int			seplen;

	initStringInfo(&retstr);
	appendStringInfoString(&retstr, prefix);

	seplen = strlen(separator);
	for (entry = record->options; entry && entry->name; entry++)
	{
		if (!entry->hidden)
		{
			appendStringInfoString(&retstr, entry->name);
			appendBinaryStringInfo(&retstr, separator, seplen);
		}
	}

	/*
	 * All the entries may have been hidden, leaving the string empty if no
	 * prefix was given. This indicates a broken GTM setup, since there is no
	 * use for an enum without any values, so we just check to make sure we
	 * don't write to invalid memory instead of actually trying to do
	 * something smart with it.
	 */
	if (retstr.len >= seplen)
	{
		/* Replace final separator */
		retstr.data[retstr.len - seplen] = '\0';
		retstr.len -= seplen;
	}

	appendStringInfoString(&retstr, suffix);

	return retstr.data;
}


/*
 * Sets option `name' to given value. The value should be a string
 * which is going to be parsed and converted to the appropriate data
 * type.  The context and source parameters indicate in which context this
 * function is being called so it can apply the access restrictions
 * properly.
 *
 * If value is NULL, set the option to its default value (normally the
 * reset_val, but if source == GTMC_S_DEFAULT we instead use the boot_val).
 *
 * action indicates whether to set the value globally in the session, locally
 * to the current top transaction, or just for the duration of a function call.
 *
 * If changeVal is false then don't really set the option but do all
 * the checks to see if it would work.
 *
 * If there is an error (non-existing option, invalid value) then an
 * ereport(ERROR) is thrown *unless* this is called in a context where we
 * don't want to ereport (currently, startup or SIGHUP config file reread).
 * In that case we write a suitable error message via ereport(LOG) and
 * return false. This is working around the deficiencies in the ereport
 * mechanism, so don't blame me.  In all other cases, the function
 * returns true, including cases where the input is valid but we chose
 * not to apply it because of context or source-priority considerations.
 *
 * See also SetConfigOption for an external interface.
 */
bool
set_config_option(const char *name, const char *value,
				  GtmOptContext context, GtmOptSource source,
				  bool changeVal)
{
	struct config_generic *record;
	int			elevel;
	bool		prohibitValueChange = false;
	bool		makeDefault;

	if (context == GTMC_SIGHUP || source == GTMC_S_DEFAULT)
	{
		/*
		 * To avoid cluttering the log, only the postmaster bleats loudly
		 * about problems with the config file.
		 */
		elevel = DEBUG3;
	}
	else if (source == GTMC_S_DATABASE || source == GTMC_S_USER ||
			 source == GTMC_S_DATABASE_USER)
		elevel = WARNING;
	else
		elevel = ERROR;

	record = find_option(name, true, elevel);
	if (record == NULL)
	{
		if (isStartUp)
		{
			write_stderr("unrecognized configuration parameter \"%s\"\n", name);
		}
		else
		{
			ereport(elevel,
					(0,
					 errmsg("unrecognized configuration parameter \"%s\"", name)));
		}
		return false;
	}

	/*
	 * If source is postgresql.conf, mark the found record with
	 * GTMOPT_IS_IN_FILE. This is for the convenience of ProcessConfigFile.  Note
	 * that we do it even if changeVal is false, since ProcessConfigFile wants
	 * the marking to occur during its testing pass.
	 */
	if (source == GTMC_S_FILE)
		record->status |= GTMOPT_IS_IN_FILE;

	/*
	 * Check if the option can be set at this time. See guc.h for the precise
	 * rules.
	 */
	switch (record->context)
	{
		case GTMC_DEFAULT:
		case GTMC_STARTUP:
			if (context == GTMC_SIGHUP)
			{
				/*
				 * We are re-reading a GTMC_POSTMASTER variable from
				 * postgresql.conf.  We can't change the setting, so we should
				 * give a warning if the DBA tries to change it.  However,
				 * because of variant formats, canonicalization by check
				 * hooks, etc, we can't just compare the given string directly
				 * to what's stored.  Set a flag to check below after we have
				 * the final storable value.
				 *
				 * During the "checking" pass we just do nothing, to avoid
				 * printing the warning twice.
				 */
				if (!changeVal)
					return true;

				prohibitValueChange = true;
			}
			else if (context != GTMC_STARTUP)
			{
				if (isStartUp)
				{
					write_stderr("parameter \"%s\" cannot be changed without restarting the server\n",
								 name);
				}
				else
				{
					ereport(elevel,
							(0,
							 errmsg("parameter \"%s\" cannot be changed without restarting the server",
									name)));
				}
				return false;
			}
			break;
		case GTMC_SIGHUP:
			if (context != GTMC_SIGHUP && context != GTMC_STARTUP)
			{
				if (isStartUp)
				{
					write_stderr("parameter \"%s\" cannot be changed now\n",
								 name);
				}
				else
				{
					ereport(elevel,
							(0,
							 errmsg("parameter \"%s\" cannot be changed now",
									name)));
				}
				return false;
			}

			/*
			 * Hmm, the idea of the SIGHUP context is "ought to be global, but
			 * can be changed after postmaster start". But there's nothing
			 * that prevents a crafty administrator from sending SIGHUP
			 * signals to individual backends only.
			 */
			break;
		default:
			if (isStartUp)
			{
				write_stderr("GtmOptContext invalid (%d)\n",
							 context);
			}
			else
			{
				ereport(elevel,
						(0,
						 errmsg("GtmOptContext invalid (%d)",
								context)));
			}
			return false;
	}

	/*
	 * Should we set reset/stacked values?	(If so, the behavior is not
	 * transactional.)	This is done either when we get a default value from
	 * the database's/user's/client's default settings or when we reset a
	 * value to its default.
	 */
	makeDefault = changeVal && (source <= GTMC_S_OVERRIDE) &&
		((value != NULL) || source == GTMC_S_DEFAULT);

	/*
	 * Ignore attempted set if overridden by previously processed setting.
	 * However, if changeVal is false then plow ahead anyway since we are
	 * trying to find out if the value is potentially good, not actually use
	 * it. Also keep going if makeDefault is true, since we may want to set
	 * the reset/stacked values even if we can't set the variable itself.
	 */
	if (record->source > source)
	{
		if (changeVal && !makeDefault)
		{
			if (isStartUp)
			{
				write_stderr("\"%s\": setting ignored because previous source is higher priority\n",
							 name);
			}
			else
			{
				elog(DEBUG3, "\"%s\": setting ignored because previous source is higher priority",
					 name);
			}
			return true;
		}
		changeVal = false;
	}

	/*
	 * Evaluate value and set variable.
	 */
	switch (record->vartype)
	{
		case GTMC_BOOL:
			{
				struct config_bool *conf = (struct config_bool *) record;
				bool		newval;
				void	   *newextra = NULL;

				if (value)
				{
					if (!gtm_opt_parse_bool(value, &newval))
					{
						if (isStartUp)
						{
							write_stderr("parameter \"%s\" requires a Boolean value\n",
										 name);
						}
						else
						{
							ereport(elevel,
									(0,
									 errmsg("parameter \"%s\" requires a Boolean value",
											name)));
						}
						return false;
					}
				}
				else if (source == GTMC_S_DEFAULT)
				{
					newval = conf->boot_val;
				}
				else
				{
					newval = conf->reset_val;
					newextra = conf->reset_extra;
					source = conf->gen.reset_source;
				}

				if (prohibitValueChange)
				{
					if (*conf->variable != newval)
					{
						if (isStartUp)
						{
							write_stderr("parameter \"%s\" cannot be changed without restarting the server\n",
										 name);
						}
						else
						{
							ereport(elevel,
									(0,
									 errmsg("parameter \"%s\" cannot be changed without restarting the server",
											name)));
						}
					}
					return false;
				}

				if (changeVal)
				{
					/* Save old value to support transaction abort */
					if (!makeDefault)
						push_old_value(&conf->gen);

					*conf->variable = newval;
					set_extra_field(&conf->gen, &conf->gen.extra,
									newextra);
					conf->gen.source = source;
				}
				if (makeDefault)
				{
					GtmOptStack   *stack;

					if (conf->gen.reset_source <= source)
					{
						conf->reset_val = newval;
						set_extra_field(&conf->gen, &conf->reset_extra,
										newextra);
						conf->gen.reset_source = source;
					}
					for (stack = conf->gen.stack; stack; stack = stack->prev)
					{
						if (stack->source <= source)
						{
							stack->prior.val.boolval = newval;
							set_extra_field(&conf->gen, &stack->prior.extra,
											newextra);
							stack->source = source;
						}
					}
				}

				/* Perhaps we didn't install newextra anywhere */
				if (newextra && !extra_field_used(&conf->gen, newextra))
					free(newextra);
				break;
			}

		case GTMC_INT:
			{
				struct config_int *conf = (struct config_int *) record;
				int			newval;
				void	   *newextra = NULL;

				if (value)
				{
					const char *hintmsg;

					if (!parse_int(value, &newval, conf->gen.flags, &hintmsg))
					{
						if (isStartUp)
						{
							write_stderr("invalid value for parameter \"%s\": \"%s\"\n",
										 name, value);
						}
						else
						{
							ereport(elevel,
									(0,
									 errmsg("invalid value for parameter \"%s\": \"%s\"",
											name, value),
									 hintmsg ? errhint("%s", _(hintmsg)) : 0));
						}
						return false;
					}
					if (newval < conf->min || newval > conf->max)
					{
						if (isStartUp)
						{
							write_stderr("%d is outside the valid range for parameter \"%s\" (%d .. %d)\n",
										 newval, name, conf->min, conf->max);
						}
						else
						{
							ereport(elevel,
									(0,
									 errmsg("%d is outside the valid range for parameter \"%s\" (%d .. %d)",
											newval, name, conf->min, conf->max)));
						}
						return false;
					}
				}
				else if (source == GTMC_S_DEFAULT)
				{
					newval = conf->boot_val;
				}
				else
				{
					newval = conf->reset_val;
					newextra = conf->reset_extra;
					source = conf->gen.reset_source;
				}

				if (prohibitValueChange)
				{
					if (*conf->variable != newval)
					{
						if (isStartUp)
						{
							write_stderr("parameter \"%s\" cannot be changed without restarting the server\n",
										 name);
						}
						else
						{
							ereport(elevel,
									(0,
									 errmsg("parameter \"%s\" cannot be changed without restarting the server",
											name)));
						}
					}
					return false;
				}

				if (changeVal)
				{
					/* Save old value to support transaction abort */
					if (!makeDefault)
						push_old_value(&conf->gen);

					*conf->variable = newval;
					set_extra_field(&conf->gen, &conf->gen.extra,
									newextra);
					conf->gen.source = source;
				}
				if (makeDefault)
				{
					GtmOptStack   *stack;

					if (conf->gen.reset_source <= source)
					{
						conf->reset_val = newval;
						set_extra_field(&conf->gen, &conf->reset_extra,
										newextra);
						conf->gen.reset_source = source;
					}
					for (stack = conf->gen.stack; stack; stack = stack->prev)
					{
						if (stack->source <= source)
						{
							stack->prior.val.intval = newval;
							set_extra_field(&conf->gen, &stack->prior.extra,
											newextra);
							stack->source = source;
						}
					}
				}

				/* Perhaps we didn't install newextra anywhere */
				if (newextra && !extra_field_used(&conf->gen, newextra))
					free(newextra);
				break;
			}

		case GTMC_REAL:
			{
				struct config_real *conf = (struct config_real *) record;
				double		newval;
				void	   *newextra = NULL;

				if (value)
				{
					if (!parse_real(value, &newval))
					{
						if (isStartUp)
						{
							write_stderr("parameter \"%s\" requires a numeric value\n",
										 name);
						}
						else
						{
							ereport(elevel,
									(0,
									 errmsg("parameter \"%s\" requires a numeric value",
											name)));
						}
						return false;
					}
					if (newval < conf->min || newval > conf->max)
					{
						if (isStartUp)
						{
							write_stderr("%g is outside the valid range for parameter \"%s\" (%g .. %g)\n",
										 newval, name, conf->min, conf->max);
						}
						else
						{
							ereport(elevel,
									(0,
									 errmsg("%g is outside the valid range for parameter \"%s\" (%g .. %g)",
											newval, name, conf->min, conf->max)));
						}
						return false;
					}
				}
				else if (source == GTMC_S_DEFAULT)
				{
					newval = conf->boot_val;
				}
				else
				{
					newval = conf->reset_val;
					newextra = conf->reset_extra;
					source = conf->gen.reset_source;
				}

				if (prohibitValueChange)
				{
					if (*conf->variable != newval)
					{
						if (isStartUp)
						{
							write_stderr("parameter \"%s\" cannot be changed without restarting the server\n",
										 name);
						}
						else
						{
							ereport(elevel,
									(0,
									 errmsg("parameter \"%s\" cannot be changed without restarting the server",
											name)));
						}
					}
					return false;
				}

				if (changeVal)
				{
					/* Save old value to support transaction abort */
					if (!makeDefault)
						push_old_value(&conf->gen);

					*conf->variable = newval;
					set_extra_field(&conf->gen, &conf->gen.extra,
									newextra);
					conf->gen.source = source;
				}
				if (makeDefault)
				{
					GtmOptStack   *stack;

					if (conf->gen.reset_source <= source)
					{
						conf->reset_val = newval;
						set_extra_field(&conf->gen, &conf->reset_extra,
										newextra);
						conf->gen.reset_source = source;
					}
					for (stack = conf->gen.stack; stack; stack = stack->prev)
					{
						if (stack->source <= source)
						{
							stack->prior.val.realval = newval;
							set_extra_field(&conf->gen, &stack->prior.extra,
											newextra);
							stack->source = source;
						}
					}
				}

				/* Perhaps we didn't install newextra anywhere */
				if (newextra && !extra_field_used(&conf->gen, newextra))
					free(newextra);
				break;
			}

		case GTMC_STRING:
			{
				struct config_string *conf = (struct config_string *) record;
				char	   *newval;
				void	   *newextra = NULL;

				if (value)
				{
					/*
					 * The value passed by the caller could be transient, so
					 * we always strdup it.
					 */
					newval = gtm_opt_strdup(elevel, value);
					if (newval == NULL)
						return false;
				}
				else if (source == GTMC_S_DEFAULT)
				{
					/* non-NULL boot_val must always get strdup'd */
					if (conf->boot_val != NULL)
					{
						newval = gtm_opt_strdup(elevel, conf->boot_val);
						if (newval == NULL)
							return false;
					}
					else
						newval = NULL;

				}
				else
				{
					/*
					 * strdup not needed, since reset_val is already under
					 * guc.c's control
					 */
					newval = conf->reset_val;
					newextra = conf->reset_extra;
					source = conf->gen.reset_source;
				}

				if (prohibitValueChange)
				{
					/* newval shouldn't be NULL, so we're a bit sloppy here */
					if (*conf->variable == NULL || newval == NULL ||
						strcmp(*conf->variable, newval) != 0)
					{
						if (isStartUp)
						{
							write_stderr("parameter \"%s\" cannot be changed without restarting the server\n",
										 name);
						}
						else
						{
							ereport(elevel,
									(0,
									 errmsg("parameter \"%s\" cannot be changed without restarting the server",
											name)));
						}
					}
					return false;
				}

				if (changeVal)
				{
					/* Save old value to support transaction abort */
					if (!makeDefault)
						push_old_value(&conf->gen);

					set_string_field(conf, conf->variable, newval);
					set_extra_field(&conf->gen, &conf->gen.extra,
									newextra);
					conf->gen.source = source;
				}

				if (makeDefault)
				{
					GtmOptStack   *stack;

					if (conf->gen.reset_source <= source)
					{
						set_string_field(conf, &conf->reset_val, newval);
						set_extra_field(&conf->gen, &conf->reset_extra,
										newextra);
						conf->gen.reset_source = source;
					}
					for (stack = conf->gen.stack; stack; stack = stack->prev)
					{
						if (stack->source <= source)
						{
							set_string_field(conf, &stack->prior.val.stringval,
											 newval);
							set_extra_field(&conf->gen, &stack->prior.extra,
											newextra);
							stack->source = source;
						}
					}
				}

				/* Perhaps we didn't install newval anywhere */
				if (newval && !string_field_used(conf, newval))
					free(newval);
				/* Perhaps we didn't install newextra anywhere */
				if (newextra && !extra_field_used(&conf->gen, newextra))
					free(newextra);
				break;
			}

		case GTMC_ENUM:
			{
				struct config_enum *conf = (struct config_enum *) record;
				int			newval;
				void	   *newextra = NULL;

				if (value)
				{
					if (!config_enum_lookup_by_name(conf, value, &newval))
					{
						char	   *hintmsg;

						hintmsg = config_enum_get_options(conf,
														"Available values: ",
														  ".", ", ");

						if (isStartUp)
						{
							write_stderr("invalid value for parameter \"%s\": \"%s\". %s\n",
										 name, value, hintmsg);
						}
						else
						{
							ereport(elevel,
									(0,
									 errmsg("invalid value for parameter \"%s\": \"%s\"",
											name, value),
									 hintmsg ? errhint("%s", _(hintmsg)) : 0));
						}

						if (hintmsg)
							pfree(hintmsg);
						return false;
					}
				}
				else if (source == GTMC_S_DEFAULT)
				{
					newval = conf->boot_val;
				}
				else
				{
					newval = conf->reset_val;
					newextra = conf->reset_extra;
					source = conf->gen.reset_source;
				}

				if (prohibitValueChange)
				{
					if (*conf->variable != newval)
					{
						if (isStartUp)
						{
							write_stderr("parameter \"%s\" cannot be changed without restarting the server\n",
										 name);
						}
						else
						{
							ereport(elevel,
									(0,
									 errmsg("parameter \"%s\" cannot be changed without restarting the server",
											name)));
						}
					}
					return false;
				}

				if (changeVal)
				{
					/* Save old value to support transaction abort */
					if (!makeDefault)
						push_old_value(&conf->gen);

					*conf->variable = newval;
					set_extra_field(&conf->gen, &conf->gen.extra,
									newextra);
					conf->gen.source = source;
				}
				if (makeDefault)
				{
					GtmOptStack   *stack;

					if (conf->gen.reset_source <= source)
					{
						conf->reset_val = newval;
						set_extra_field(&conf->gen, &conf->reset_extra,
										newextra);
						conf->gen.reset_source = source;
					}
					for (stack = conf->gen.stack; stack; stack = stack->prev)
					{
						if (stack->source <= source)
						{
							stack->prior.val.enumval = newval;
							set_extra_field(&conf->gen, &stack->prior.extra,
											newextra);
							stack->source = source;
						}
					}
				}

				/* Perhaps we didn't install newextra anywhere */
				if (newextra && !extra_field_used(&conf->gen, newextra))
					free(newextra);
				break;
			}
	}

	if (changeVal && (record->flags & GTMOPT_REPORT))
		ReportGTMOption(record);

	return true;
}




/*
 * Set the fields for source file and line number the setting came from.
 */
static void
set_config_sourcefile(const char *name, char *sourcefile, int sourceline)
{
	struct config_generic *record;
	int			elevel;

	/*
	 * To avoid cluttering the log, only the postmaster bleats loudly about
	 * problems with the config file.
	 */
	elevel = DEBUG3;

	record = find_option(name, true, elevel);
	/* should not happen */
	if (record == NULL)
	{
		if (isStartUp)
			write_stderr("unrecognized configuration parameter \"%s\"\n", name);
		else
			elog(ERROR, "unrecognized configuration parameter \"%s\"", name);
	}

	sourcefile = gtm_opt_strdup(elevel, sourcefile);
	if (record->sourcefile)
		free(record->sourcefile);
	record->sourcefile = sourcefile;
	record->sourceline = sourceline;
}


/*
 * Set a config option to the given value. See also set_config_option,
 * this is just the wrapper to be called from outside GTM.	NB: this
 * is used only for non-transactional operations.
 *
 * Note: there is no support here for setting source file/line, as it
 * is currently not needed.
 */
void
SetConfigOption(const char *name, const char *value,
				GtmOptContext context, GtmOptSource source)
{
	(void) set_config_option(name, value, context, source,
							 true);
}




/*
 * Fetch the current value of the option `name'. If the option doesn't exist,
 * throw an ereport and don't return.
 *
 * If restrict_superuser is true, we also enforce that only superusers can
 * see GTMOPT_SUPERUSER_ONLY variables.  This should only be passed as true
 * in user-driven calls.
 *
 * The string is *not* allocated for modification and is really only
 * valid until the next call to configuration related functions.
 */
const char *
GetConfigOption(const char *name, bool restrict_superuser)
{
	struct config_generic *record;
	static char buffer[256];

	record = find_option(name, false, ERROR);
	if (record == NULL)
	{
		if (isStartUp)
			write_stderr("unrecognized configuration parameter \"%s\"\n", name);
		else
			ereport(ERROR,
					(0,
					 errmsg("unrecognized configuration parameter \"%s\"", name)));
	}
	switch (record->vartype)
	{
		case GTMC_BOOL:
			return *((struct config_bool *) record)->variable ? "on" : "off";

		case GTMC_INT:
			snprintf(buffer, sizeof(buffer), "%d",
					 *((struct config_int *) record)->variable);
			return buffer;

		case GTMC_REAL:
			snprintf(buffer, sizeof(buffer), "%g",
					 *((struct config_real *) record)->variable);
			return buffer;

		case GTMC_STRING:
			return *((struct config_string *) record)->variable;

		case GTMC_ENUM:
			return config_enum_lookup_by_value((struct config_enum *) record,
								 *((struct config_enum *) record)->variable);
	}
	return NULL;
}


/*
 * Get the RESET value associated with the given option.
 *
 * Note: this is not re-entrant, due to use of static result buffer;
 * not to mention that a string variable could have its reset_val changed.
 * Beware of assuming the result value is good for very long.
 */
const char *
GetConfigOptionResetString(const char *name)
{
	struct config_generic *record;
	static char buffer[256];

	record = find_option(name, false, ERROR);
	if (record == NULL)
	{
		if (isStartUp)
			write_stderr("unrecognized configuration parameter \"%s\"\n", name);
		else
			ereport(ERROR,
					(0,
					 errmsg("unrecognized configuration parameter \"%s\"", name)));
	}

	switch (record->vartype)
	{
		case GTMC_BOOL:
			return ((struct config_bool *) record)->reset_val ? "on" : "off";

		case GTMC_INT:
			snprintf(buffer, sizeof(buffer), "%d",
					 ((struct config_int *) record)->reset_val);
			return buffer;

		case GTMC_REAL:
			snprintf(buffer, sizeof(buffer), "%g",
					 ((struct config_real *) record)->reset_val);
			return buffer;

		case GTMC_STRING:
			return ((struct config_string *) record)->reset_val;

		case GTMC_ENUM:
			return config_enum_lookup_by_value((struct config_enum *) record,
								 ((struct config_enum *) record)->reset_val);
	}
	return NULL;
}


void
EmitWarningsOnPlaceholders(const char *className)
{
	int			classLen = strlen(className);
	int			i;

	for (i = 0; i < num_gtm_opt_variables; i++)
	{
		struct config_generic *var = gtm_opt_variables[i];

		if ((var->flags & GTMOPT_CUSTOM_PLACEHOLDER) != 0 &&
			strncmp(className, var->name, classLen) == 0 &&
			var->name[classLen] == GTMOPT_QUALIFIER_SEPARATOR)
		{
			if (isStartUp)
				write_stderr("unrecognized configuration parameter \"%s\"\n",
							 var->name);
			else
				ereport(WARNING,
						(0,
						 errmsg("unrecognized configuration parameter \"%s\"",
								var->name)));
		}
	}
}


/*
 * Return GTM variable value by name; optionally return canonical
 * form of name.  Return value is malloc'd.
 */
char *
GetConfigOptionByName(const char *name, const char **varname)
{
	struct config_generic *record;

	record = find_option(name, false, ERROR);
	if (record == NULL)
	{
		if (isStartUp)
			write_stderr("unrecognized configuration parameter \"%s\"\n", name);
		else
			ereport(ERROR,
					(0,
					 errmsg("unrecognized configuration parameter \"%s\"", name)));
	}
	if (varname)
		*varname = record->name;

	return _ShowOption(record, true);
}

/*
 * Return GTM variable value by variable number; optionally return canonical
 * form of name.  Return value is malloc'd.
 */
void
GetConfigOptionByNum(int varnum, const char **values, bool *noshow)
{
	char		buffer[256];
	struct config_generic *conf;

	/* check requested variable number valid */
	Assert((varnum >= 0) && (varnum < num_gtm_opt_variables));

	conf = gtm_opt_variables[varnum];

	if (noshow)
	{
		if (conf->flags & GTMOPT_NO_SHOW_ALL)
			*noshow = true;
		else
			*noshow = false;
	}

	/* first get the generic attributes */

	/* name */
	values[0] = conf->name;

	/* setting : use _ShowOption in order to avoid duplicating the logic */
	values[1] = _ShowOption(conf, false);

	/* unit */
	if (conf->vartype == GTMC_INT)
	{
		static char buf[8];

		switch (conf->flags & (GTMOPT_UNIT_MEMORY | GTMOPT_UNIT_TIME))
		{
			case GTMOPT_UNIT_KB:
				values[2] = "kB";
				break;
			case GTMOPT_UNIT_BLOCKS:
				snprintf(buf, sizeof(buf), "%dkB", BLCKSZ / 1024);
				values[2] = buf;
				break;
			case GTMOPT_UNIT_XBLOCKS:
				snprintf(buf, sizeof(buf), "%dkB", XLOG_BLCKSZ / 1024);
				values[2] = buf;
				break;
			case GTMOPT_UNIT_MS:
				values[2] = "ms";
				break;
			case GTMOPT_UNIT_S:
				values[2] = "s";
				break;
			case GTMOPT_UNIT_MIN:
				values[2] = "min";
				break;
			default:
				values[2] = "";
				break;
		}
	}
	else
		values[2] = NULL;

#if 0
	/* PGXCTODO: Group parameters are not used yet */
	/* group */
	values[3] = config_group_names[conf->group];
#endif

	/* short_desc */
	values[4] = conf->short_desc;

	/* extra_desc */
	values[5] = conf->long_desc;

	/* context */
	values[6] = GtmOptContext_Names[conf->context];

	/* vartype */
	values[7] = config_type_names[conf->vartype];

	/* source */
	values[8] = GtmOptSource_Names[conf->source];

	/* now get the type specifc attributes */
	switch (conf->vartype)
	{
		case GTMC_BOOL:
			{
				struct config_bool *lconf = (struct config_bool *) conf;

				/* min_val */
				values[9] = NULL;

				/* max_val */
				values[10] = NULL;

				/* enumvals */
				values[11] = NULL;

				/* boot_val */
				values[12] = strdup(lconf->boot_val ? "on" : "off");

				/* reset_val */
				values[13] = strdup(lconf->reset_val ? "on" : "off");
			}
			break;

		case GTMC_INT:
			{
				struct config_int *lconf = (struct config_int *) conf;

				/* min_val */
				snprintf(buffer, sizeof(buffer), "%d", lconf->min);
				values[9] = strdup(buffer);

				/* max_val */
				snprintf(buffer, sizeof(buffer), "%d", lconf->max);
				values[10] = strdup(buffer);

				/* enumvals */
				values[11] = NULL;

				/* boot_val */
				snprintf(buffer, sizeof(buffer), "%d", lconf->boot_val);
				values[12] = strdup(buffer);

				/* reset_val */
				snprintf(buffer, sizeof(buffer), "%d", lconf->reset_val);
				values[13] = strdup(buffer);
			}
			break;

		case GTMC_REAL:
			{
				struct config_real *lconf = (struct config_real *) conf;

				/* min_val */
				snprintf(buffer, sizeof(buffer), "%g", lconf->min);
				values[9] = strdup(buffer);

				/* max_val */
				snprintf(buffer, sizeof(buffer), "%g", lconf->max);
				values[10] = strdup(buffer);

				/* enumvals */
				values[11] = NULL;

				/* boot_val */
				snprintf(buffer, sizeof(buffer), "%g", lconf->boot_val);
				values[12] = strdup(buffer);

				/* reset_val */
				snprintf(buffer, sizeof(buffer), "%g", lconf->reset_val);
				values[13] = strdup(buffer);
			}
			break;

		case GTMC_STRING:
			{
				struct config_string *lconf = (struct config_string *) conf;

				/* min_val */
				values[9] = NULL;

				/* max_val */
				values[10] = NULL;

				/* enumvals */
				values[11] = NULL;

				/* boot_val */
				if (lconf->boot_val == NULL)
					values[12] = NULL;
				else
					values[12] = strdup(lconf->boot_val);

				/* reset_val */
				if (lconf->reset_val == NULL)
					values[13] = NULL;
				else
					values[13] = strdup(lconf->reset_val);
			}
			break;

		case GTMC_ENUM:
			{
				struct config_enum *lconf = (struct config_enum *) conf;

				/* min_val */
				values[9] = NULL;

				/* max_val */
				values[10] = NULL;

				/* enumvals */

				/*
				 * NOTE! enumvals with double quotes in them are not
				 * supported!
				 */
				values[11] = config_enum_get_options((struct config_enum *) conf,
													 "{\"", "\"}", "\",\"");

				/* boot_val */
				values[12] = strdup(config_enum_lookup_by_value(lconf,
														   lconf->boot_val));

				/* reset_val */
				values[13] = strdup(config_enum_lookup_by_value(lconf,
														  lconf->reset_val));
			}
			break;

		default:
			{
				/*
				 * should never get here, but in case we do, set 'em to NULL
				 */

				/* min_val */
				values[9] = NULL;

				/* max_val */
				values[10] = NULL;

				/* enumvals */
				values[11] = NULL;

				/* boot_val */
				values[12] = NULL;

				/* reset_val */
				values[13] = NULL;
			}
			break;
	}

	/*
	 * If the setting came from a config file, set the source location. For
	 * security reasons, we don't show source file/line number for
	 * non-superusers.
	 */
	if (conf->source == GTMC_S_FILE)
	{
		values[14] = conf->sourcefile;
		snprintf(buffer, sizeof(buffer), "%d", conf->sourceline);
		values[15] = strdup(buffer);
	}
	else
	{
		values[14] = NULL;
		values[15] = NULL;
	}
}

/*
 * Return the total number of GTM variables
 */
int
GetNumConfigOptions(void)
{
	return num_gtm_opt_variables;
}


static char *
_ShowOption(struct config_generic * record, bool use_units)
{
	char		buffer[256];
	const char *val;

	switch (record->vartype)
	{
		case GTMC_BOOL:
			{
				struct config_bool *conf = (struct config_bool *) record;

				val = *conf->variable ? "on" : "off";
			}
			break;

		case GTMC_INT:
			{
				struct config_int *conf = (struct config_int *) record;

				/*
				 * Use int64 arithmetic to avoid overflows in units
				 * conversion.
				 */
				int64		result = *conf->variable;
				const char *unit;

				if (use_units && result > 0 &&
					(record->flags & GTMOPT_UNIT_MEMORY))
				{
					switch (record->flags & GTMOPT_UNIT_MEMORY)
					{
						case GTMOPT_UNIT_BLOCKS:
							result *= BLCKSZ / 1024;
							break;
						case GTMOPT_UNIT_XBLOCKS:
							result *= XLOG_BLCKSZ / 1024;
							break;
					}

					if (result % KB_PER_GB == 0)
					{
						result /= KB_PER_GB;
						unit = "GB";
					}
					else if (result % KB_PER_MB == 0)
					{
						result /= KB_PER_MB;
						unit = "MB";
					}
					else
					{
						unit = "kB";
					}
				}
				else if (use_units && result > 0 &&
						 (record->flags & GTMOPT_UNIT_TIME))
				{
					switch (record->flags & GTMOPT_UNIT_TIME)
					{
						case GTMOPT_UNIT_S:
							result *= MS_PER_S;
							break;
						case GTMOPT_UNIT_MIN:
							result *= MS_PER_MIN;
							break;
					}

					if (result % MS_PER_D == 0)
					{
						result /= MS_PER_D;
						unit = "d";
					}
					else if (result % MS_PER_H == 0)
					{
						result /= MS_PER_H;
						unit = "h";
					}
					else if (result % MS_PER_MIN == 0)
					{
						result /= MS_PER_MIN;
						unit = "min";
					}
					else if (result % MS_PER_S == 0)
					{
						result /= MS_PER_S;
						unit = "s";
					}
					else
					{
						unit = "ms";
					}
				}
				else
					unit = "";

				snprintf(buffer, sizeof(buffer), INT64_FORMAT "%s",
						 result, unit);
				val = buffer;

			}
			break;

		case GTMC_REAL:
			{
				struct config_real *conf = (struct config_real *) record;

				snprintf(buffer, sizeof(buffer), "%g",
						 *conf->variable);
				val = buffer;
			}
			break;

		case GTMC_STRING:
			{
				struct config_string *conf = (struct config_string *) record;

				 if (*conf->variable && **conf->variable)
					val = *conf->variable;
				else
					val = "";
			}
			break;

		case GTMC_ENUM:
			{
				struct config_enum *conf = (struct config_enum *) record;

				val = config_enum_lookup_by_value(conf, *conf->variable);
			}
			break;

		default:
			/* just to keep compiler quiet */
			val = "???";
			break;
	}

	return strdup(val);
}



/*
 * A little "long argument" simulation, although not quite GNU
 * compliant. Takes a string of the form "some-option=some value" and
 * returns name = "some_option" and value = "some value" in malloc'ed
 * storage. Note that '-' is converted to '_' in the option name. If
 * there is no '=' in the input string then value will be NULL.
 */
void
ParseLongOption(const char *string, char **name, char **value)
{
	size_t		equal_pos;
	char	   *cp;

	AssertArg(string);
	AssertArg(name);
	AssertArg(value);

	equal_pos = strcspn(string, "=");

	if (string[equal_pos] == '=')
	{
		*name = gtm_opt_malloc(FATAL, equal_pos + 1);
		strlcpy(*name, string, equal_pos + 1);

		*value = gtm_opt_strdup(FATAL, &string[equal_pos + 1]);
	}
	else
	{
		/* no equal sign in string */
		*name = gtm_opt_strdup(FATAL, string);
		*value = NULL;
	}

	for (cp = *name; *cp; cp++)
		if (*cp == '-')
			*cp = '_';
}

#if 0
/*
 * keep-alive related APIs will be used in future extensions
 */
void
gtm_assign_tcp_keepalives_idle(int newval, void *extra)
{
	/*
	 * The kernel API provides no way to test a value without setting it; and
	 * once we set it we might fail to unset it.  So there seems little point
	 * in fully implementing the check-then-assign GTM API for these
	 * variables.  Instead we just do the assignment on demand.  pqcomm.c
	 * reports any problems via elog(LOG).
	 *
	 * This approach means that the GTM value might have little to do with the
	 * actual kernel value, so we use a show_hook that retrieves the kernel
	 * value rather than trusting GTM's copy.
	 */
#if 0
	(void) pq_setkeepalivesidle(newval, MyProcPort);
#else
	(void) pq_setkeepalivesidle_all(newval);
#endif
}

const char *
gtm_show_tcp_keepalives_idle(void)
{
	/* See comments in assign_tcp_keepalives_idle */
	static char nbuf[16];

#if 0
	snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesidle(MyProcPort));
#else
	snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesidle_all());
#endif
	return nbuf;
}

void
gtm_assign_tcp_keepalives_interval(int newval, void *extra)
{
	/* See comments in assign_tcp_keepalives_idle */
#if 0
	(void) pq_setkeepalivesinterval(newval, MyProcPort);
#else
	(void) pq_setkeepalivesinterval_all(newval);
#endif
}

const char *
gtm_show_tcp_keepalives_interval(void)
{
	/* See comments in assign_tcp_keepalives_idle */
	static char nbuf[16];

#if 0
	snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesinterval(MyProcPort));
#else
	snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesinterval_all());
#endif
	return nbuf;
}

void
gtm_assign_tcp_keepalives_count(int newval, void *extra)
{
	/* See comments in assign_tcp_keepalives_idle */
#if 0
	(void) pq_setkeepalivescount(newval, MyProcPort);
#else
	(void) pq_setkeepalivescount_all(newval);
#endif
}

const char *
gtm_show_tcp_keepalives_count(void)
{
	/* See comments in assign_tcp_keepalives_idle */
	static char nbuf[16];

#if 0
	snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivescount(MyProcPort));
#else
	snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivescount_all());
#endif
	return nbuf;
}
#endif

/*
 * Try to interpret value as boolean value.  Valid values are: true,
 * false, yes, no, on, off, 1, 0; as well as unique prefixes thereof.
 * If the string parses okay, return true, else false.
 * If okay and result is not NULL, return the value in *result.
 */
static bool
gtm_opt_parse_bool(const char *value, bool *result)
{
	return gtm_opt_parse_bool_with_len(value, strlen(value), result);
}

static bool
gtm_opt_parse_bool_with_len(const char *value, size_t len, bool *result)
{
	switch (*value)
	{
		case 't':
		case 'T':
			if (pg_strncasecmp(value, "true", len) == 0)
			{
				if (result)
					*result = true;
				return true;
			}
			break;
		case 'f':
		case 'F':
			if (pg_strncasecmp(value, "false", len) == 0)
			{
				if (result)
					*result = false;
				return true;
			}
			break;
		case 'y':
		case 'Y':
			if (pg_strncasecmp(value, "yes", len) == 0)
			{
				if (result)
					*result = true;
				return true;
			}
			break;
		case 'n':
		case 'N':
			if (pg_strncasecmp(value, "no", len) == 0)
			{
				if (result)
					*result = false;
				return true;
			}
			break;
		case 'o':
		case 'O':
			/* 'o' is not unique enough */
			if (pg_strncasecmp(value, "on", (len > 2 ? len : 2)) == 0)
			{
				if (result)
					*result = true;
				return true;
			}
			else if (pg_strncasecmp(value, "off", (len > 2 ? len : 2)) == 0)
			{
				if (result)
					*result = false;
				return true;
			}
			break;
		case '1':
			if (len == 1)
			{
				if (result)
					*result = true;
				return true;
			}
			break;
		case '0':
			if (len == 1)
			{
				if (result)
					*result = false;
				return true;
			}
			break;
		default:
			break;
	}

	if (result)
		*result = false;		/* suppress compiler warning */
	return false;
}

/*
 * ReportGUCOption: if appropriate, transmit option value to frontend
 */
static void
ReportGTMOption(struct config_generic * record)
{
	/* So far, it is empty. */
}

/*
 * Lookup the name for an enum option with the selected value.
 * Should only ever be called with known-valid values, so throws
 * an elog(ERROR) if the enum option is not found.
 *
 * The returned string is a pointer to static data and not
 * allocated for modification.
 */
const char *
config_enum_lookup_by_value(struct config_enum * record, int val)
{
	const struct config_enum_entry *entry;

	for (entry = record->options; entry && entry->name; entry++)
	{
		if (entry->val == val)
			return entry->name;
	}

	if (isStartUp)
		write_stderr("could not find enum option %d for %s\n",
					 val, record->gen.name);
	else
		elog(ERROR, "could not find enum option %d for %s",
			 val, record->gen.name);
	return NULL;				/* silence compiler */
}