File: isc_sync.cpp

package info (click to toggle)
firebird3.0 3.0.7.33374.ds4-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 41,416 kB
  • sloc: ansic: 374,395; cpp: 319,714; sql: 14,345; pascal: 14,195; yacc: 7,540; fortran: 5,645; sh: 5,251; makefile: 1,033; perl: 135; sed: 83; awk: 75; xml: 19; csh: 15
file content (3714 lines) | stat: -rw-r--r-- 82,390 bytes parent folder | download
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
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
/*
 *	PROGRAM:	JRD Access Method
 *	MODULE:		isc_sync.cpp
 *	DESCRIPTION:	OS-dependent IPC: shared memory, mutex and event.
 *
 * The contents of this file are subject to the Interbase Public
 * License Version 1.0 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy
 * of the License at http://www.Inprise.com/IPL.html
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * rights and limitations under the License.
 *
 * The Original Code was created by Inprise Corporation
 * and its predecessors. Portions created by Inprise Corporation are
 * Copyright (C) Inprise Corporation.
 *
 * All Rights Reserved.
 * Contributor(s): ______________________________________.
 *
 * 2002.02.15 Sean Leyne - Code Cleanup, removed obsolete "XENIX" port
 * 2002.02.15 Sean Leyne - Code Cleanup, removed obsolete "DELTA" port
 * 2002.02.15 Sean Leyne - Code Cleanup, removed obsolete "IMP" port
 *
 * 2002-02-23 Sean Leyne - Code Cleanup, removed old M88K and NCR3000 port
 *
 * 2002.10.27 Sean Leyne - Completed removal of obsolete "DG_X86" port
 * 2002.10.27 Sean Leyne - Completed removal of obsolete "M88K" port
 *
 * 2002.10.28 Sean Leyne - Completed removal of obsolete "DGUX" port
 * 2002.10.28 Sean Leyne - Code cleanup, removed obsolete "DecOSF" port
 * 2002.10.28 Sean Leyne - Code cleanup, removed obsolete "SGI" port
 *
 * 2002.10.29 Sean Leyne - Removed obsolete "Netware" port
 *
 */

#include "firebird.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef SOLARIS
#include "../common/gdsassert.h"
#endif

#ifdef HPUX
#include <sys/pstat.h>
#endif

#include "gen/iberror.h"
#include "../yvalve/gds_proto.h"
#include "../common/isc_proto.h"
#include "../common/os/isc_i_proto.h"
#include "../common/os/os_utils.h"
#include "../common/isc_s_proto.h"
#include "../common/file_params.h"
#include "../common/gdsassert.h"
#include "../common/config/config.h"
#include "../common/utils_proto.h"
#include "../common/StatusArg.h"
#include "../common/ThreadData.h"
#include "../common/ThreadStart.h"
#include "../common/classes/rwlock.h"
#include "../common/classes/GenericMap.h"
#include "../common/classes/RefMutex.h"
#include "../common/classes/array.h"
#include "../common/StatusHolder.h"

static int process_id;

// Unix specific stuff

#ifdef UNIX
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>

#ifdef HAVE_SYS_SIGNAL_H
#include <sys/signal.h>
#endif

#include <errno.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#ifdef USE_SYS5SEMAPHORE
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <sys/time.h>
#endif

#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif

#include <sys/mman.h>

#define FTOK_KEY	15
#define PRIV		S_IRUSR | S_IWUSR

//#ifndef SHMEM_DELTA
//#define SHMEM_DELTA	(1 << 22)
//#endif

#endif // UNIX

#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif

#ifndef WIN_NT
#ifndef HAVE_GETPAGESIZE
static size_t getpagesize()
{
	return PAGESIZE;
}
#endif
#endif

//#define DEBUG_IPC
#ifdef DEBUG_IPC
#define IPC_TRACE(x)	{ /*time_t t; time(&t); printf("%s", ctime(&t) ); printf x; fflush (stdout);*/ gds__log x; }
#else
#define IPC_TRACE(x)
#endif


// Windows NT

#ifdef WIN_NT

#include <process.h>
#include <windows.h>

#endif

using namespace Firebird;

static void		error(CheckStatusWrapper*, const TEXT*, ISC_STATUS);
static bool		event_blocked(const event_t* event, const SLONG value);

#ifdef UNIX

static GlobalPtr<Mutex> openFdInit;

class DevNode
{
public:
	DevNode()
		: f_dev(0), f_ino(0)
	{ }

	DevNode(dev_t d, ino_t i)
		: f_dev(d), f_ino(i)
	{ }

	DevNode(const DevNode& v)
		: f_dev(v.f_dev), f_ino(v.f_ino)
	{ }

	dev_t	f_dev;
	ino_t	f_ino;

	bool operator==(const DevNode& v) const
	{
		return f_dev == v.f_dev && f_ino == v.f_ino;
	}

	bool operator>(const DevNode& v) const
	{
		return f_dev > v.f_dev ? true :
			   f_dev < v.f_dev ? false :
			   f_ino > v.f_ino;
	}

	const DevNode& operator=(const DevNode& v)
	{
		f_dev = v.f_dev;
		f_ino = v.f_ino;
		return *this;
	}
};

namespace Firebird {

class CountedRWLock
{
public:
	CountedRWLock()
		: sharedAccessCounter(0)
	{ }
	RWLock rwlock;
	AtomicCounter cnt;
	Mutex sharedAccessMutex;
	int sharedAccessCounter;
};

class CountedFd
{
public:
	explicit CountedFd(int f)
		: fd(f), useCount(0)
	{ }

	~CountedFd()
	{
		fb_assert(useCount == 0);
	}

	int fd;
	int useCount;

private:
	CountedFd(const CountedFd&);
	const CountedFd& operator=(const CountedFd&);
};

} // namespace Firebird

namespace {

	typedef GenericMap<Pair<Left<string, Firebird::CountedRWLock*> > > RWLocks;
	GlobalPtr<RWLocks> rwlocks;
	GlobalPtr<Mutex> rwlocksMutex;
#ifdef USE_FCNTL
	const char* NAME = "fcntl";
#else
	const char* NAME = "flock";
#endif

	class FileLockHolder
	{
	public:
		explicit FileLockHolder(FileLock* l)
			: lock(l)
		{
			LocalStatus ls;
			CheckStatusWrapper status(&ls);
			if (!lock->setlock(&status, FileLock::FLM_EXCLUSIVE))
				status_exception::raise(&status);
		}

		~FileLockHolder()
		{
			lock->unlock();
		}

	private:
		FileLock* lock;
	};

	DevNode getNode(const char* name)
	{
		struct stat statistics;
		if (stat(name, &statistics) != 0)
		{
			if (errno == ENOENT)
			{
				//file not found
				return DevNode();
			}

			system_call_failed::raise("stat");
		}

		return DevNode(statistics.st_dev, statistics.st_ino);
	}

	DevNode getNode(int fd)
	{
		struct stat statistics;
		if (fstat(fd, &statistics) != 0)
		{
			system_call_failed::raise("stat");
		}

		return DevNode(statistics.st_dev, statistics.st_ino);
	}

} // anonymous namespace


typedef GenericMap<Pair<NonPooled<DevNode, Firebird::CountedFd*> > > FdNodes;
static GlobalPtr<Mutex> fdNodesMutex;
static GlobalPtr<FdNodes> fdNodes;

FileLock::FileLock(const char* fileName, InitFunction* init)
	: level(LCK_NONE), oFile(NULL),
#ifdef USE_FCNTL
	  lStart(0),
#endif
	  rwcl(NULL)
{
	MutexLockGuard g(fdNodesMutex, FB_FUNCTION);

	DevNode id(getNode(fileName));

	if (id.f_ino)
	{
		CountedFd** got = fdNodes->get(id);
		if (got)
		{
			oFile = *got;
		}
	}

	if (!oFile)
	{
		int fd = os_utils::openCreateSharedFile(fileName, 0);
		oFile = FB_NEW_POOL(*getDefaultMemoryPool()) CountedFd(fd);
		CountedFd** put = fdNodes->put(getNode(fd));
		fb_assert(put);
		*put = oFile;

		if (init)
		{
			init(fd);
		}
	}

	rwcl = getRw();
	++(oFile->useCount);
}

#ifdef USE_FILELOCKS
FileLock::FileLock(const FileLock* main, int s)
	: level(LCK_NONE), oFile(main->oFile),
	  lStart(s), rwcl(getRw())
{
	MutexLockGuard g(fdNodesMutex, FB_FUNCTION);
	++(oFile->useCount);
}
#endif

FileLock::~FileLock()
{
	unlock();

	{ // guard scope
		MutexLockGuard g(rwlocksMutex, FB_FUNCTION);

		if (--(rwcl->cnt) == 0)
		{
			rwlocks->remove(getLockId());
			delete rwcl;
		}
	}
	{ // guard scope
		MutexLockGuard g(fdNodesMutex, FB_FUNCTION);

		if (--(oFile->useCount) == 0)
		{
			fdNodes->remove(getNode(oFile->fd));
			close(oFile->fd);
			delete oFile;
		}
	}
}

int FileLock::getFd()
{
	return oFile->fd;
}

int FileLock::setlock(const LockMode mode)
{
	bool shared = true, wait = true;
	switch (mode)
	{
		case FLM_TRY_EXCLUSIVE:
			wait = false;
			// fall through
		case FLM_EXCLUSIVE:
			shared = false;
			break;
		case FLM_TRY_SHARED:
			wait = false;
			// fall through
		case FLM_SHARED:
			break;
	}

	const LockLevel newLevel = shared ? LCK_SHARED : LCK_EXCL;
	if (newLevel == level)
	{
		return 0;
	}
	if (level != LCK_NONE)
	{
		return wait ? EBUSY : -1;
	}

	// first take appropriate rwlock to avoid conflicts with other threads in our process
	bool rc = true;
	try
	{
		switch (mode)
		{
		case FLM_TRY_EXCLUSIVE:
			rc = rwcl->rwlock.tryBeginWrite(FB_FUNCTION);
			break;
		case FLM_EXCLUSIVE:
			rwcl->rwlock.beginWrite(FB_FUNCTION);
			break;
		case FLM_TRY_SHARED:
			rc = rwcl->rwlock.tryBeginRead(FB_FUNCTION);
			break;
		case FLM_SHARED:
			rwcl->rwlock.beginRead(FB_FUNCTION);
			break;
		}
	}
	catch (const system_call_failed& fail)
	{
		return fail.getErrorCode();
	}
	if (!rc)
	{
		return -1;
	}

	// For shared lock we must take into an account reenterability
	MutexEnsureUnlock guard(rwcl->sharedAccessMutex, FB_FUNCTION);
	if (shared)
	{
		if (wait)
		{
			guard.enter();
		}
		else if (!guard.tryEnter())
		{
			return -1;
		}

		fb_assert(rwcl->sharedAccessCounter >= 0);
		if (rwcl->sharedAccessCounter++ > 0)
		{
			// counter is non-zero - we already have file lock
			level = LCK_SHARED;
			return 0;
		}
	}

#ifdef USE_FCNTL
	// Take lock on a file
	struct flock lock;
	lock.l_type = shared ? F_RDLCK : F_WRLCK;
	lock.l_whence = SEEK_SET;
	lock.l_start = lStart;
	lock.l_len = 1;
	if (fcntl(oFile->fd, wait ? F_SETLKW : F_SETLK, &lock) == -1)
	{
		int rc = errno;
		if (!wait && (rc == EACCES || rc == EAGAIN))
		{
			rc = -1;
		}
#else
	if (flock(oFile->fd, (shared ? LOCK_SH : LOCK_EX) | (wait ? 0 : LOCK_NB)))
	{
		int rc = errno;
		if (!wait && (rc == EWOULDBLOCK))
		{
			rc = -1;
		}
#endif

		try
		{
			if (shared)
			{
				rwcl->sharedAccessCounter--;
				rwcl->rwlock.endRead();
			}
			else
				rwcl->rwlock.endWrite();
		}
		catch (const Exception&)
		{ }

		return rc;
	}

	level = newLevel;
	return 0;
}

bool FileLock::setlock(CheckStatusWrapper* status, const LockMode mode)
{
	int rc = setlock(mode);
	if (rc != 0)
	{
		if (rc > 0)
		{
			error(status, NAME, rc);
		}
		return false;
	}
	return true;
}

void FileLock::rwUnlock()
{
	fb_assert(level != LCK_NONE);

	try
	{
		if (level == LCK_SHARED)
			rwcl->rwlock.endRead();
		else
			rwcl->rwlock.endWrite();
	}
	catch (const Exception& ex)
	{
		iscLogException("rwlock end-operation error", ex);
	}

	level = LCK_NONE;
}

void FileLock::unlock()
{
	if (level == LCK_NONE)
	{
		return;
	}

	// For shared lock we must take into an account reenterability
	MutexEnsureUnlock guard(rwcl->sharedAccessMutex, FB_FUNCTION);
	if (level == LCK_SHARED)
	{
		guard.enter();

		fb_assert(rwcl->sharedAccessCounter > 0);
		if (--(rwcl->sharedAccessCounter) > 0)
		{
			// counter is non-zero - we must keep file lock
			rwUnlock();
			return;
		}
	}

#ifdef USE_FCNTL
	struct flock lock;
	lock.l_type = F_UNLCK;
	lock.l_whence = SEEK_SET;
	lock.l_start = lStart;
	lock.l_len = 1;

	if (fcntl(oFile->fd, F_SETLK, &lock) != 0)
	{
#else
	if (flock(oFile->fd, LOCK_UN) != 0)
	{
#endif
		LocalStatus ls;
		CheckStatusWrapper local(&ls);
		error(&local, NAME, errno);
		iscLogStatus("Unlock error", &local);
	}

	rwUnlock();
}

string FileLock::getLockId()
{
	fb_assert(oFile);

	DevNode id(getNode(oFile->fd));

	const size_t len1 = sizeof(id.f_dev);
	const size_t len2 = sizeof(id.f_ino);
#ifdef USE_FCNTL
	const size_t len3 = sizeof(int);
#endif

	string rc(len1 + len2
#ifdef USE_FCNTL
						  + len3
#endif
								, ' ');
	char* p = rc.begin();

	memcpy(p, &id.f_dev, len1);
	p += len1;
	memcpy(p, &id.f_ino, len2);
#ifdef USE_FCNTL
	p += len2;
	memcpy(p, &lStart, len3);
#endif

	return rc;
}

CountedRWLock* FileLock::getRw()
{
	string id = getLockId();
	CountedRWLock* rc = NULL;

	MutexLockGuard g(rwlocksMutex, FB_FUNCTION);

	CountedRWLock** got = rwlocks->get(id);
	if (got)
	{
		rc = *got;
	}

	if (!rc)
	{
		rc = FB_NEW_POOL(*getDefaultMemoryPool()) CountedRWLock;
		CountedRWLock** put = rwlocks->put(id);
		fb_assert(put);
		*put = rc;
	}

	++(rc->cnt);

	return rc;
}


#ifdef USE_SYS5SEMAPHORE

#ifndef HAVE_SEMUN
union semun
{
	int val;
	struct semid_ds *buf;
	ushort *array;
};
#endif

static SLONG	create_semaphores(CheckStatusWrapper*, SLONG, int);

namespace {

	int sharedCount = 0;

	// this class is mapped into shared file
	class SemTable
	{
	public:
		const static int N_FILES = 128;
		const static int N_SETS = 256;
#if defined(DEV_BUILD)
		const static int SEM_PER_SET = 4;	// force multiple sets allocation
#else
		const static int SEM_PER_SET = 31;	// hard limit for some old systems, might set to 32
#endif
		const static unsigned char CURRENT_VERSION = 1;
		unsigned char version;

	private:
		int lastSet;

		struct
		{
			char name[MAXPATHLEN];
		} filesTable[N_FILES];

		struct
		{
			key_t semKey;
			int fileNum;
			SLONG mask;

			int get(int fNum)
			{
				if (fileNum == fNum && mask != 0)
				{
					for (int bit = 0; bit < SEM_PER_SET; ++bit)
					{
						if (mask & (1 << bit))
						{
							mask &= ~(1 << bit);
							return bit;
						}
					}
					// bad bits in mask ?
					mask = 0;
				}
				return -1;
			}

			int create(int fNum)
			{
				fileNum = fNum;
				mask = 1 << SEM_PER_SET;
				--mask;
				mask &= ~1;
				return 0;
			}

			void put(int bit)
			{
				// fb_assert(!(mask & (1 << bit)));
				mask |= (1 << bit);
			}
		} set[N_SETS];

	public:
		void cleanup(int fNum, bool release);

		key_t getKey(int semSet) const
		{
			fb_assert(semSet >= 0 && semSet < lastSet);

			return set[semSet].semKey;
		}

		void init(int fdSem)
		{
			if (sharedCount)
			{
				return;
			}

			FB_UNUSED(ftruncate(fdSem, sizeof(*this)));

			for (int i = 0; i < N_SETS; ++i)
			{
				if (set[i].fileNum > 0)
				{
					// may be some old data about really active semaphore sets?
					if (version == CURRENT_VERSION)
					{
						const int semId = semget(set[i].semKey, SEM_PER_SET, 0);
						if (semId > 0)
						{
							semctl(semId, 0, IPC_RMID);
						}
					}
					set[i].fileNum = 0;
				}
			}

			for (int i = 0; i < N_FILES; ++i)
			{
				filesTable[i].name[0] = 0;
			}

			version = CURRENT_VERSION;
			lastSet = 0;
		}

		bool get(int fileNum, Sys5Semaphore* sem)
		{
			// try to locate existing set
			int n;
			for (n = 0; n < lastSet; ++n)
			{
				const int semNum = set[n].get(fileNum);
				if (semNum >= 0)
				{
					sem->semSet = n;
					sem->semNum = semNum;
					return true;
				}
			}

			// create new set
			for (n = 0; n < lastSet; ++n)
			{
				if (set[n].fileNum <= 0)
				{
					break;
				}
			}

			if (n >= N_SETS)
			{
				fb_assert(false);	// Not supposed to overflow
				return false;
			}

			if (n >= lastSet)
			{
				lastSet = n + 1;
			}

			set[n].semKey = ftok(filesTable[fileNum - 1].name, n);
			sem->semSet = n;
			sem->semNum = set[n].create(fileNum);
			return true;
		}

		void put(Sys5Semaphore* sem)
		{
			fb_assert(sem->semSet >= 0 && sem->semSet < N_SETS);

			set[sem->semSet].put(sem->semNum);
		}

		int findFileByName(const PathName& name) const
		{
			// Get a file ID in filesTable.
			for (int fileId = 0; fileId < N_FILES; ++fileId)
			{
				if (name == filesTable[fileId].name)
				{
					return fileId + 1;
				}
			}

			// not found
			return 0;
		}

		int addFileByName(const PathName& name)
		{
			int id = findFileByName(name);
			if (id > 0)
			{
				return id;
			}

			// Get a file ID in filesTable.
			for (int fileId = 0; fileId < SemTable::N_FILES; ++fileId)
			{
				if (filesTable[fileId].name[0] == 0)
				{
					name.copyTo(filesTable[fileId].name, sizeof(filesTable[fileId].name));
					return fileId + 1;
				}
			}

			// not found
			fb_assert(false);
			return 0;
		}
	};

	SemTable* semTable = NULL;

	int idCache[SemTable::N_SETS];
	GlobalPtr<Mutex> idCacheMutex;

	void initCache()
	{
		MutexLockGuard guard(idCacheMutex, FB_FUNCTION);
		memset(idCache, 0xff, sizeof idCache);
	}

	void SemTable::cleanup(int fNum, bool release)
	{
		fb_assert(fNum > 0 && fNum <= N_FILES);

		if (release)
		{
			filesTable[fNum - 1].name[0] = 0;
		}

		MutexLockGuard guard(idCacheMutex, FB_FUNCTION);
		for (int n = 0; n < lastSet; ++n)
		{
			if (set[n].fileNum == fNum)
			{
				if (release)
				{
					Sys5Semaphore sem;
					sem.semSet = n;
					int id = sem.getId();
					if (id >= 0)
					{
						semctl(id, 0, IPC_RMID);
					}
					set[n].fileNum = -1;
				}
				idCache[n] = -1;
			}
		}
	}

	// Left from DEB_EVNT code, keep for a while 'as is'. To be cleaned up later!!!
	void initStart(const event_t* event) {}
	void initStop(const event_t* event, int code) {}
	void finiStart(const event_t* event) {}
	void finiStop(const event_t* event) {}

} // anonymous namespace

bool SharedMemoryBase::getSem5(Sys5Semaphore* sem)
{
	try
	{
		// Lock init file.
		FileLockHolder lock(initFile);

		if (!semTable->get(fileNum, sem))
		{
			gds__log("semTable->get() failed");
			return false;
		}

		return true;
	}
	catch (const Exception& ex)
	{
		iscLogException("FileLock ctor failed in getSem5", ex);
	}
	return false;
}

void SharedMemoryBase::freeSem5(Sys5Semaphore* sem)
{
	try
	{
		// Lock init file.
		FileLockHolder lock(initFile);

		semTable->put(sem);
	}
	catch (const Exception& ex)
	{
		iscLogException("FileLock ctor failed in freeSem5", ex);
	}
}

int Sys5Semaphore::getId()
{
	MutexLockGuard guard(idCacheMutex, FB_FUNCTION);
	fb_assert(semSet >= 0 && semSet < SemTable::N_SETS);

	int id = idCache[semSet];

	if (id < 0)
	{
		LocalStatus ls;
		CheckStatusWrapper st(&ls);
		id = create_semaphores(&st, semTable->getKey(semSet), SemTable::SEM_PER_SET);
		if (id >= 0)
		{
			idCache[semSet] = id;
		}
		else
		{
			iscLogStatus("create_semaphores failed:", &st);
		}
	}

	return id;
}
#endif // USE_SYS5SEMAPHORE

#endif // UNIX

#if defined(WIN_NT)
static bool make_object_name(TEXT*, size_t, const TEXT*, const TEXT*);
#endif


#ifdef USE_SYS5SEMAPHORE

namespace {

class TimerEntry FB_FINAL :
	public Firebird::RefCntIface<Firebird::ITimerImpl<TimerEntry, CheckStatusWrapper> >
{
public:
	TimerEntry(int id, USHORT num)
		: semId(id), semNum(num)
	{ }

	void handler()
	{
		for (;;)
		{
			union semun arg;
			arg.val = 0;
			int ret = semctl(semId, semNum, SETVAL, arg);
			if (ret != -1)
				break;
			if (!SYSCALL_INTERRUPTED(errno))
			{
				gds__log("semctl() failed, errno %d\n", errno);
				break;
			}
		}
	}

	int release()
	{
		if (--refCounter == 0)
		{
			delete this;
			return 0;
		}

		return 1;
	}

	bool operator== (Sys5Semaphore& sem)
	{
		return semId == sem.getId() && semNum == sem.semNum;
	}

private:
	int semId;
	USHORT semNum;
};

typedef HalfStaticArray<TimerEntry*, 64> TimerQueue;
GlobalPtr<TimerQueue> timerQueue;
GlobalPtr<Mutex> timerAccess;

void addTimer(Sys5Semaphore* sem, int microSeconds)
{
	TimerEntry* newTimer = FB_NEW TimerEntry(sem->getId(), sem->semNum);
	{
		MutexLockGuard guard(timerAccess, FB_FUNCTION);
		timerQueue->push(newTimer);
	}

	LocalStatus ls;
	CheckStatusWrapper st(&ls);
	TimerInterfacePtr()->start(&st, newTimer, microSeconds);
	check(&st);
}

void delTimer(Sys5Semaphore* sem)
{
	bool found = false;
	TimerEntry** t;

	{
		MutexLockGuard guard(timerAccess, FB_FUNCTION);

		for (t = timerQueue->begin(); t < timerQueue->end(); ++t)
		{
			if (**t == *sem)
			{
				timerQueue->remove(t);
				found = true;
				break;
			}
		}
	}

	if (found)
	{
		LocalStatus ls;
		CheckStatusWrapper st(&ls);
		TimerInterfacePtr()->stop(&st, *t);
		check(&st);
	}
}

SINT64 curTime()
{
	struct timeval cur_time;
	struct timezone tzUnused;

	if (gettimeofday(&cur_time, &tzUnused) != 0)
	{
		system_call_failed::raise("gettimeofday");
	}

	SINT64 rc = ((SINT64) cur_time.tv_sec) * 1000000 + cur_time.tv_usec;
	return rc;
}

} // anonymous namespace

#endif // USE_SYS5SEMAPHORE

#ifdef USE_SHARED_FUTEX

namespace {

	int isPthreadError(int rc, const char* function)
	{
		if (rc == 0)
			return 0;
		iscLogStatus("Pthread Error",
			(Arg::Gds(isc_sys_request) << Arg::Str(function) << Arg::Unix(rc)).value());
		return rc;
	}

}

#define PTHREAD_ERROR(x) if (isPthreadError((x), #x)) return FB_FAILURE
#define PTHREAD_ERRNO(x) { int tmpState = (x); if (isPthreadError(tmpState, #x)) return tmpState; }
#define LOG_PTHREAD_ERROR(x) isPthreadError((x), #x)
#define PTHREAD_ERR_STATUS(x, v) { int tmpState = (x); if (tmpState) { error(v, #x, tmpState); return false; } }
#define PTHREAD_ERR_RAISE(x) { int tmpState = (x); if (tmpState) { system_call_failed::raise(#x, tmpState); } }

#endif // USE_SHARED_FUTEX


int SharedMemoryBase::eventInit(event_t* event)
{
/**************************************
 *
 *	I S C _ e v e n t _ i n i t	( S Y S V )
 *
 **************************************
 *
 * Functional description
 *	Prepare an event object for use.
 *
 **************************************/

#if defined(WIN_NT)

	static AtomicCounter idCounter;

	event->event_id = ++idCounter;

	event->event_pid = process_id = getpid();
	event->event_count = 0;

	event->event_handle = ISC_make_signal(true, true, process_id, event->event_id);

	return (event->event_handle) ? FB_SUCCESS : FB_FAILURE;

#elif defined(USE_SYS5SEMAPHORE)

	initStart(event);

	event->event_count = 0;

	if (!getSem5(event))
	{
		IPC_TRACE(("ISC_event_init failed get sem %p\n", event));
		initStop(event, 1);
		return FB_FAILURE;
	}

	IPC_TRACE(("ISC_event_init set=%d num=%d\n", event->semSet, event->semNum));

	union semun arg;
	arg.val = 0;
	if (semctl(event->getId(), event->semNum, SETVAL, arg) < 0)
	{
		initStop(event, 2);
		iscLogStatus("event_init()",
			(Arg::Gds(isc_sys_request) << Arg::Str("semctl") << SYS_ERR(errno)).value());
		return FB_FAILURE;
	}

	initStop(event, 0);
	return FB_SUCCESS;

#else // pthread-based event

	event->event_count = 0;
	event->pid = getpid();

	// Prepare an Inter-Process event block
	pthread_mutexattr_t mattr;
	pthread_condattr_t cattr;

	PTHREAD_ERROR(pthread_mutexattr_init(&mattr));
	PTHREAD_ERROR(pthread_condattr_init(&cattr));
#ifdef PTHREAD_PROCESS_SHARED
	PTHREAD_ERROR(pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED));
	PTHREAD_ERROR(pthread_condattr_setpshared(&cattr, PTHREAD_PROCESS_SHARED));
#else
#error Your system must support PTHREAD_PROCESS_SHARED to use firebird.
#endif
	PTHREAD_ERROR(pthread_mutex_init(event->event_mutex, &mattr));
	PTHREAD_ERROR(pthread_cond_init(event->event_cond, &cattr));
	PTHREAD_ERROR(pthread_mutexattr_destroy(&mattr));
	PTHREAD_ERROR(pthread_condattr_destroy(&cattr));

	return FB_SUCCESS;

#endif // OS-dependent choice

}


void SharedMemoryBase::eventFini(event_t* event)
{
/**************************************
 *
 *	I S C _ e v e n t _ f i n i
 *
 **************************************
 *
 * Functional description
 *	Discard an event object.
 *
 **************************************/

#if defined(WIN_NT)

	if (event->event_pid == process_id)
	{
		CloseHandle((HANDLE) event->event_handle);
	}

#elif defined(USE_SYS5SEMAPHORE)

	IPC_TRACE(("ISC_event_fini set=%d num=%d\n", event->semSet, event->semNum));
	finiStart(event);
	freeSem5(event);
	finiStop(event);

#else // pthread-based event

	if (event->pid == getpid())
	{
		LOG_PTHREAD_ERROR(pthread_mutex_destroy(event->event_mutex));
		LOG_PTHREAD_ERROR(pthread_cond_destroy(event->event_cond));
	}

#endif // OS-dependent choice

}


SLONG SharedMemoryBase::eventClear(event_t* event)
{
/**************************************
 *
 *	I S C _ e v e n t _ c l e a r
 *
 **************************************
 *
 * Functional description
 *	Clear an event preparatory to waiting on it.  The order of
 *	battle for event synchronization is:
 *
 *	    1.  Clear event.
 *	    2.  Test data structure for event already completed
 *	    3.  Wait on event.
 *
 **************************************/

#if defined(WIN_NT)

	ResetEvent((HANDLE) event->event_handle);

	return event->event_count + 1;

#elif defined(USE_SYS5SEMAPHORE)

	union semun arg;

	arg.val = 1;
	if (semctl(event->getId(), event->semNum, SETVAL, arg) < 0)
	{
		iscLogStatus("event_clear()",
			(Arg::Gds(isc_sys_request) << Arg::Str("semctl") << SYS_ERR(errno)).value());
	}

	return (event->event_count + 1);

#else // pthread-based event

	LOG_PTHREAD_ERROR(pthread_mutex_lock(event->event_mutex));
	const SLONG ret = event->event_count + 1;
	LOG_PTHREAD_ERROR(pthread_mutex_unlock(event->event_mutex));
	return ret;

#endif // OS-dependent choice

}


int SharedMemoryBase::eventWait(event_t* event, const SLONG value, const SLONG micro_seconds)
{
/**************************************
 *
 *	I S C _ e v e n t _ w a i t
 *
 **************************************
 *
 * Functional description
 *	Wait on an event.
 *
 **************************************/

	// If we're not blocked, the rest is a gross waste of time

	if (!event_blocked(event, value)) {
		return FB_SUCCESS;
	}

#if defined(WIN_NT)

	// Go into wait loop

	const DWORD timeout = (micro_seconds > 0) ? micro_seconds / 1000 : INFINITE;

	for (;;)
	{
		if (!event_blocked(event, value))
			return FB_SUCCESS;

		const DWORD status = WaitForSingleObject(event->event_handle, timeout);

		if (status != WAIT_OBJECT_0)
			return FB_FAILURE;
	}

#elif defined(USE_SYS5SEMAPHORE)

	// Set up timers if a timeout period was specified.
	SINT64 timeout = 0;
	if (micro_seconds > 0)
	{
		timeout = curTime() + micro_seconds;
		addTimer(event, micro_seconds);
	}

	// Go into wait loop

	int ret = FB_SUCCESS;
	for (;;)
	{
		if (!event_blocked(event, value))
			break;

		struct sembuf sb;
		sb.sem_op = 0;
		sb.sem_flg = 0;
		sb.sem_num = event->semNum;

		int rc = semop(event->getId(), &sb, 1);
		if (rc == -1 && !SYSCALL_INTERRUPTED(errno))
		{
			gds__log("ISC_event_wait: semop failed with errno = %d", errno);
		}

		if (micro_seconds > 0)
		{
			// distinguish between timeout and actually happened event
			if (! event_blocked(event, value))
				break;

			// had timeout expired?
			if (curTime() >= timeout)	// really expired
			{
				ret = FB_FAILURE;
				break;
			}
		}
	}

	// Cancel the handler.  We only get here if a timeout was specified.
	if (micro_seconds > 0)
	{
		delTimer(event);
	}

	return ret;

#else // pthread-based event

	// Set up timers if a timeout period was specified.

	struct timespec timer;
	if (micro_seconds > 0)
	{
		timer.tv_sec = time(NULL);
		timer.tv_sec += micro_seconds / 1000000;
		timer.tv_nsec = 1000 * (micro_seconds % 1000000);
	}

	int ret = FB_SUCCESS;
	pthread_mutex_lock(event->event_mutex);
	for (;;)
	{
		if (!event_blocked(event, value))
		{
			ret = FB_SUCCESS;
			break;
		}

		// The Posix pthread_cond_wait & pthread_cond_timedwait calls
		// atomically release the mutex and start a wait.
		// The mutex is reacquired before the call returns.
		if (micro_seconds > 0)
		{
			ret = pthread_cond_timedwait(event->event_cond, event->event_mutex, &timer);

			if (ret == ETIMEDOUT)
			{

				// The timer expired - see if the event occurred and return
				// FB_SUCCESS or FB_FAILURE accordingly.

				if (event_blocked(event, value))
					ret = FB_FAILURE;
				else
					ret = FB_SUCCESS;
				break;
			}
		}
		else
			ret = pthread_cond_wait(event->event_cond, event->event_mutex);
	}
	pthread_mutex_unlock(event->event_mutex);
	return ret;

#endif // OS-dependent choice

}


int SharedMemoryBase::eventPost(event_t* event)
{
/**************************************
 *
 *	I S C _ e v e n t _ p o s t
 *
 **************************************
 *
 * Functional description
 *	Post an event to wake somebody else up.
 *
 **************************************/

#if defined(WIN_NT)

	++event->event_count;

	if (event->event_pid != process_id)
		return ISC_kill(event->event_pid, event->event_id, event->event_handle);

	return SetEvent((HANDLE) event->event_handle) ? FB_SUCCESS : FB_FAILURE;

#elif defined(USE_SYS5SEMAPHORE)

	union semun arg;

	++event->event_count;

	for (;;)
	{
		arg.val = 0;
		int ret = semctl(event->getId(), event->semNum, SETVAL, arg);
		if (ret != -1)
			break;
		if (!SYSCALL_INTERRUPTED(errno))
		{
			gds__log("ISC_event_post: semctl failed with errno = %d", errno);
			return FB_FAILURE;
		}
	}

	return FB_SUCCESS;

#else // pthread-based event

	PTHREAD_ERROR(pthread_mutex_lock(event->event_mutex));
	++event->event_count;
	const int ret = pthread_cond_broadcast(event->event_cond);
	PTHREAD_ERROR(pthread_mutex_unlock(event->event_mutex));
	if (ret)
	{
		gds__log ("ISC_event_post: pthread_cond_broadcast failed with errno = %d", ret);
		return FB_FAILURE;
	}

	return FB_SUCCESS;

#endif // OS-dependent choice

} // anonymous namespace


#ifdef UNIX
ULONG ISC_exception_post(ULONG sig_num, const TEXT* err_msg, ISC_STATUS& /*isc_error*/)
{
/**************************************
 *
 *	I S C _ e x c e p t i o n _ p o s t ( U N I X )
 *
 **************************************
 *
 * Functional description
 *     When we got a sync exception, fomulate the error code
 *     write it to the log file, and abort.
 *
 * 08-Mar-2004, Nickolay Samofatov.
 *   This function is dangerous and requires rewrite using signal-safe operations only.
 *   Main problem is that we call a lot of signal-unsafe functions from this signal handler,
 *   examples are gds__alloc, gds__log, etc... sprintf is safe on some BSD platforms,
 *   but not on Linux. This may result in lock-up during signal handling.
 *
 **************************************/
	// If there's no err_msg, we asumed the switch() finds no case or we crash.
	// Too much goodwill put on the caller. Weak programming style.
	// Therefore, lifted this safety net from the NT version.
	if (!err_msg)
	{
		err_msg = "";
	}

	TEXT* const log_msg = (TEXT *) gds__alloc(strlen(err_msg) + 256);
	// NOMEM: crash!
	log_msg[0] = '\0';

	switch (sig_num)
	{
	case SIGSEGV:
		sprintf(log_msg, "%s Segmentation Fault.\n"
				"\t\tThe code attempted to access memory\n"
				"\t\twithout privilege to do so.\n"
				"\tThis exception will cause the Firebird server\n"
				"\tto terminate abnormally.", err_msg);
		break;
	case SIGBUS:
		sprintf(log_msg, "%s Bus Error.\n"
				"\t\tThe code caused a system bus error.\n"
				"\tThis exception will cause the Firebird server\n"
				"\tto terminate abnormally.", err_msg);
		break;
	case SIGILL:

		sprintf(log_msg, "%s Illegal Instruction.\n"
				"\t\tThe code attempted to perform an\n"
				"\t\tillegal operation."
				"\tThis exception will cause the Firebird server\n"
				"\tto terminate abnormally.", err_msg);
		break;

	case SIGFPE:
		sprintf(log_msg, "%s Floating Point Error.\n"
				"\t\tThe code caused an arithmetic exception\n"
				"\t\tor floating point exception."
				"\tThis exception will cause the Firebird server\n"
				"\tto terminate abnormally.", err_msg);
		break;
	default:
		sprintf(log_msg, "%s Unknown Exception.\n"
				"\t\tException number %" ULONGFORMAT"."
				"\tThis exception will cause the Firebird server\n"
				"\tto terminate abnormally.", err_msg, sig_num);
		break;
	}

	if (err_msg)
	{
		gds__log(log_msg);
		gds__free(log_msg);
	}
	abort();

	return 0;	// compiler silencer
}
#endif // UNIX


#ifdef WIN_NT
ULONG ISC_exception_post(ULONG except_code, const TEXT* err_msg, ISC_STATUS& isc_error)
{
/**************************************
 *
 *	I S C _ e x c e p t i o n _ p o s t ( W I N _ N T )
 *
 **************************************
 *
 * Functional description
 *     When we got a sync exception, fomulate the error code
 *     write it to the log file, and abort. Note: We can not
 *     actually call "abort" since in windows this will cause
 *     a dialog to appear stating the obvious!  Since on NT we
 *     would not get a core file, there is actually no difference
 *     between abort() and exit(3).
 *
 **************************************/
	ULONG result = 0;
	bool is_critical = true;
	isc_error = 0;

	if (!err_msg)
	{
		err_msg = "";
	}

	TEXT* log_msg = (TEXT*) gds__alloc(static_cast<SLONG>(strlen(err_msg) + 256));
	// NOMEM: crash!
	log_msg[0] = '\0';

	switch (except_code)
	{
	case EXCEPTION_ACCESS_VIOLATION:
		sprintf(log_msg, "%s Access violation.\n"
				"\t\tThe code attempted to access a virtual\n"
				"\t\taddress without privilege to do so.\n"
				"\tThis exception will cause the Firebird server\n"
				"\tto terminate abnormally.", err_msg);
		break;
	case EXCEPTION_DATATYPE_MISALIGNMENT:
		sprintf(log_msg, "%s Datatype misalignment.\n"
				"\t\tThe attempted to read or write a value\n"
				"\t\tthat was not stored on a memory boundary.\n"
				"\tThis exception will cause the Firebird server\n"
				"\tto terminate abnormally.", err_msg);
		break;
	case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
		sprintf(log_msg, "%s Array bounds exceeded.\n"
				"\t\tThe code attempted to access an array\n"
				"\t\telement that is out of bounds.\n"
				"\tThis exception will cause the Firebird server\n"
				"\tto terminate abnormally.", err_msg);
		break;
	case EXCEPTION_FLT_DENORMAL_OPERAND:
		sprintf(log_msg, "%s Float denormal operand.\n"
				"\t\tOne of the floating-point operands is too\n"
				"\t\tsmall to represent as a standard floating-point\n"
				"\t\tvalue.\n"
				"\tThis exception will cause the Firebird server\n"
				"\tto terminate abnormally.", err_msg);
		break;
	case EXCEPTION_FLT_DIVIDE_BY_ZERO:
		sprintf(log_msg, "%s Floating-point divide by zero.\n"
				"\t\tThe code attempted to divide a floating-point\n"
				"\t\tvalue by a floating-point divisor of zero.\n"
				"\tThis exception will cause the Firebird server\n"
				"\tto terminate abnormally.", err_msg);
		break;
	case EXCEPTION_FLT_INEXACT_RESULT:
		sprintf(log_msg, "%s Floating-point inexact result.\n"
				"\t\tThe result of a floating-point operation cannot\n"
				"\t\tbe represented exactly as a decimal fraction.\n"
				"\tThis exception will cause the Firebird server\n"
				"\tto terminate abnormally.", err_msg);
		break;
	case EXCEPTION_FLT_INVALID_OPERATION:
		sprintf(log_msg, "%s Floating-point invalid operand.\n"
				"\t\tAn indeterminant error occurred during a\n"
				"\t\tfloating-point operation.\n"
				"\tThis exception will cause the Firebird server\n"
				"\tto terminate abnormally.", err_msg);
		break;
	case EXCEPTION_FLT_OVERFLOW:
		sprintf(log_msg, "%s Floating-point overflow.\n"
				"\t\tThe exponent of a floating-point operation\n"
				"\t\tis greater than the magnitude allowed.\n"
				"\tThis exception will cause the Firebird server\n"
				"\tto terminate abnormally.", err_msg);
		break;
	case EXCEPTION_FLT_STACK_CHECK:
		sprintf(log_msg, "%s Floating-point stack check.\n"
				"\t\tThe stack overflowed or underflowed as the\n"
				"result of a floating-point operation.\n"
				"\tThis exception will cause the Firebird server\n"
				"\tto terminate abnormally.", err_msg);
		break;
	case EXCEPTION_FLT_UNDERFLOW:
		sprintf(log_msg, "%s Floating-point underflow.\n"
				"\t\tThe exponent of a floating-point operation\n"
				"\t\tis less than the magnitude allowed.\n"
				"\tThis exception will cause the Firebird server\n"
				"\tto terminate abnormally.", err_msg);
		break;
	case EXCEPTION_INT_DIVIDE_BY_ZERO:
		sprintf(log_msg, "%s Integer divide by zero.\n"
				"\t\tThe code attempted to divide an integer value\n"
				"\t\tby an integer divisor of zero.\n"
				"\tThis exception will cause the Firebird server\n"
				"\tto terminate abnormally.", err_msg);
		break;
	case EXCEPTION_INT_OVERFLOW:
		sprintf(log_msg, "%s Interger overflow.\n"
				"\t\tThe result of an integer operation caused the\n"
				"\t\tmost significant bit of the result to carry.\n"
				"\tThis exception will cause the Firebird server\n"
				"\tto terminate abnormally.", err_msg);
		break;
	case EXCEPTION_STACK_OVERFLOW:
		isc_error = isc_exception_stack_overflow;
		result = (ULONG) EXCEPTION_EXECUTE_HANDLER;
		is_critical = false;
		break;

	case EXCEPTION_BREAKPOINT:
	case EXCEPTION_SINGLE_STEP:
	case EXCEPTION_NONCONTINUABLE_EXCEPTION:
	case EXCEPTION_INVALID_DISPOSITION:
	case EXCEPTION_PRIV_INSTRUCTION:
	case EXCEPTION_IN_PAGE_ERROR:
	case EXCEPTION_ILLEGAL_INSTRUCTION:
	case EXCEPTION_GUARD_PAGE:
		// Pass these exception on to someone else, probably the OS or the debugger,
		// since there isn't a dam thing we can do with them
		result = EXCEPTION_CONTINUE_SEARCH;
		is_critical = false;
		break;
	case 0xE06D7363: // E == Exception. 0x6D7363 == "msc". Intel and Borland use the same code to be compatible
		// If we've caught our own software exception,
		// continue rewinding the stack to properly handle it
		// and deliver an error information to the client side
		result = EXCEPTION_CONTINUE_SEARCH;
		is_critical = false;
		break;
	default:
		sprintf (log_msg, "%s An exception occurred that does\n"
				"\t\tnot have a description.  Exception number %" XLONGFORMAT".\n"
				"\tThis exception will cause the Firebird server\n"
				"\tto terminate abnormally.", err_msg, except_code);
		break;
	}

	if (is_critical)
	{
		gds__log(log_msg);
	}

	gds__free(log_msg);

	if (is_critical)
	{
		if (Config::getBugcheckAbort())
		{
			// Pass exception to outer handler in case debugger is present to collect memory dump
			return EXCEPTION_CONTINUE_SEARCH;
		}

		// Silently exit so guardian or service manager can restart the server.
		// If exception is getting out of the application Windows displays a message
		// asking if you want to send report to Microsoft or attach debugger,
		// application is not terminated until you press some button on resulting window.
		// This happens even if you run application as non-interactive service on
		// "server" OS like Windows Server 2003.
		exit(3);
	}

	return result;
}
#endif // WIN_NT


void SharedMemoryBase::removeMapFile()
{
#ifndef WIN_NT
	unlinkFile();
#else
	sh_mem_unlink = true;
#endif // WIN_NT
}

void SharedMemoryBase::unlinkFile()
{
	TEXT expanded_filename[MAXPATHLEN];
	iscPrefixLock(expanded_filename, sh_mem_name, false);

	// We can't do much (specially in dtors) when it fails
	// therefore do not check for errors - at least it's just /tmp.

#ifdef WIN_NT
	// Delete file only if it is not used by anyone else
	HANDLE hFile = CreateFile(expanded_filename,
		DELETE,
		0,
		NULL,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE,
		NULL);

	if (hFile != INVALID_HANDLE_VALUE)
		CloseHandle(hFile);
#else
	unlink(expanded_filename);
#endif // WIN_NT
}


#ifdef UNIX

void SharedMemoryBase::internalUnmap()
{
#ifdef USE_SYS5SEMAPHORE
	if (fileNum != -1 && mainLock.hasData())
	{
		LocalStatus ls;
		CheckStatusWrapper statusVector(&ls);
		semTable->cleanup(fileNum, mainLock->setlock(&statusVector, FileLock::FLM_TRY_EXCLUSIVE));
	}
#endif
	if (sh_mem_header)
	{
		munmap(sh_mem_header, sh_mem_length_mapped);
		sh_mem_header = NULL;
	}
}

SharedMemoryBase::SharedMemoryBase(const TEXT* filename, ULONG length, IpcObject* callback)
	:
#ifdef HAVE_SHARED_MUTEX_SECTION
	sh_mem_mutex(0),
#endif
	sh_mem_length_mapped(0), sh_mem_header(NULL),
#ifdef USE_SYS5SEMAPHORE
	fileNum(-1),
#endif
	sh_mem_callback(callback)
{
/**************************************
 *
 *	c t o r		( U N I X - m m a p )
 *
 **************************************
 *
 * Functional description
 *	Try to map a given file.  If we are the first (i.e. only)
 *	process to map the file, call a given initialization
 *	routine (if given) or punt (leaving the file unmapped).
 *
 **************************************/
	LocalStatus ls;
	CheckStatusWrapper statusVector(&ls);

	sh_mem_name[0] = '\0';

	TEXT expanded_filename[MAXPATHLEN];
	iscPrefixLock(expanded_filename, filename, true);

	// make the complete filename for the init file this file is to be used as a
	// master lock to eliminate possible race conditions with just a single file
	// locking. The race condition is caused as the conversion of an EXCLUSIVE
	// lock to a SHARED lock is not atomic

	TEXT init_filename[MAXPATHLEN];
	iscPrefixLock(init_filename, INIT_FILE, true);

	const bool trunc_flag = (length != 0);

	// open the init lock file
	MutexLockGuard guard(openFdInit, FB_FUNCTION);

	initFile.reset(FB_NEW_POOL(*getDefaultMemoryPool()) FileLock(init_filename));

	// get an exclusive lock on the INIT file with blocking
	FileLockHolder initLock(initFile);

#ifdef USE_SYS5SEMAPHORE
	class Sem5Init
	{
	public:
		static void init(int fd)
		{
			void* sTab = mmap(0, sizeof(SemTable), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
			if ((U_IPTR) sTab == (U_IPTR) -1)
			{
				system_call_failed::raise("mmap");
			}

			semTable = (SemTable*) sTab;
			initCache();
		}
	};


	TEXT sem_filename[MAXPATHLEN];
	iscPrefixLock(sem_filename, SEM_FILE, true);

	semFile.reset(FB_NEW_POOL(*getDefaultMemoryPool()) FileLock(sem_filename, Sem5Init::init));

	fb_assert(semTable);

	if (semFile->setlock(&statusVector, FileLock::FLM_TRY_EXCLUSIVE))
	{
		semTable->init(semFile->getFd());
		semFile->unlock();
	}
	if (!semFile->setlock(&statusVector, FileLock::FLM_SHARED))
	{
		if (statusVector.hasData())
			status_exception::raise(&statusVector);
		else
			(Arg::Gds(isc_random) << "Unknown error in setlock").raise();
	}
#endif

	// create lock in order to have file autoclosed on error
	mainLock.reset(FB_NEW_POOL(*getDefaultMemoryPool()) FileLock(expanded_filename));

	if (length == 0)
	{
		// Get and use the existing length of the shared segment
		struct stat file_stat;
		if (fstat(mainLock->getFd(), &file_stat) == -1)
		{
			system_call_failed::raise("fstat");
		}
		length = file_stat.st_size;

		if (length == 0)
		{
			// keep old text of message here -  will be assigned a bit later
			(Arg::Gds(isc_random) << "shmem_data->sh_mem_length_mapped is 0").raise();
		}
	}

	// map file to memory
	void* const address = mmap(0, length, PROT_READ | PROT_WRITE, MAP_SHARED, mainLock->getFd(), 0);
	if ((U_IPTR) address == (U_IPTR) -1)
	{
		system_call_failed::raise("mmap", errno);
	}

	// this class is needed to cleanup mapping in case of error
	class AutoUnmap
	{
	public:
		explicit AutoUnmap(SharedMemoryBase* sm) : sharedMemory(sm)
		{ }

		void success()
		{
			sharedMemory = NULL;
		}

		~AutoUnmap()
		{
			if (sharedMemory)
			{
				sharedMemory->internalUnmap();
			}
		}

	private:
		SharedMemoryBase* sharedMemory;
	};

	AutoUnmap autoUnmap(this);

	sh_mem_header = (MemoryHeader*) address;
	sh_mem_length_mapped = length;
	strcpy(sh_mem_name, filename);

#ifdef HAVE_SHARED_MUTEX_SECTION
#ifdef USE_MUTEX_MAP
	sh_mem_mutex = (mtx*) mapObject(&statusVector, offsetof(MemoryHeader, mhb_mutex), sizeof(mtx));
	if (!sh_mem_mutex)
	{
		system_call_failed::raise("mmap");
	}
#else
	sh_mem_mutex = &sh_mem_header->mhb_mutex;
#endif
#endif // HAVE_SHARED_MUTEX_SECTION

#if defined(USE_SYS5SEMAPHORE)
#if !defined(USE_FILELOCKS)

	sh_mem_mutex = &sh_mem_header->mhb_mutex;

#endif // USE_FILELOCKS

	fileNum = semTable->addFileByName(expanded_filename);

#endif // USE_SYS5SEMAPHORE

	// Try to get an exclusive lock on the lock file.  This will
	// fail if somebody else has the exclusive or shared lock

	if (mainLock->setlock(&statusVector, FileLock::FLM_TRY_EXCLUSIVE))
	{
		if (trunc_flag)
			FB_UNUSED(ftruncate(mainLock->getFd(), length));

		if (callback->initialize(this, true))
		{

#ifdef HAVE_SHARED_MUTEX_SECTION
#ifdef USE_SYS5SEMAPHORE

			if (!getSem5(sh_mem_mutex))
			{
				callback->mutexBug(0, "getSem5()");
				(Arg::Gds(isc_random) << "getSem5() failed").raise();
			}

			union semun arg;
			arg.val = 1;
			int state = semctl(sh_mem_mutex->getId(), sh_mem_mutex->semNum, SETVAL, arg);
			if (state == -1)
			{
				int err = errno;
				callback->mutexBug(errno, "semctl");
				system_call_failed::raise("semctl", err);
			}

#else // USE_SYS5SEMAPHORE

#if (defined(HAVE_PTHREAD_MUTEXATTR_SETPROTOCOL) || defined(USE_ROBUST_MUTEX)) && defined(LINUX)
// glibc in linux does not conform to the posix standard. When there is no RT kernel,
// ENOTSUP is returned not by pthread_mutexattr_setprotocol(), but by
// pthread_mutex_init(). Use a hack to deal with this broken error reporting.
#define BUGGY_LINUX_MUTEX
#endif

			int state = 0;

#ifdef BUGGY_LINUX_MUTEX
			static volatile bool staticBugFlag = false;

			do
			{
				bool bugFlag = staticBugFlag;
#endif

				pthread_mutexattr_t mattr;

				PTHREAD_ERR_RAISE(pthread_mutexattr_init(&mattr));
#ifdef PTHREAD_PROCESS_SHARED
				PTHREAD_ERR_RAISE(pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED));
#else
#error Your system must support PTHREAD_PROCESS_SHARED to use pthread shared futex in Firebird.
#endif

#ifdef HAVE_PTHREAD_MUTEXATTR_SETPROTOCOL
#ifdef BUGGY_LINUX_MUTEX
				if (!bugFlag)
				{
#endif
					int protocolRc = pthread_mutexattr_setprotocol(&mattr, PTHREAD_PRIO_INHERIT);
					if (protocolRc && (protocolRc != ENOTSUP))
					{
						iscLogStatus("Pthread Error", (Arg::Gds(isc_sys_request) <<
							"pthread_mutexattr_setprotocol" << Arg::Unix(protocolRc)).value());
					}
#ifdef BUGGY_LINUX_MUTEX
				}
#endif
#endif // HAVE_PTHREAD_MUTEXATTR_SETPROTOCOL

#ifdef USE_ROBUST_MUTEX
#ifdef BUGGY_LINUX_MUTEX
				if (!bugFlag)
				{
#endif
					LOG_PTHREAD_ERROR(pthread_mutexattr_setrobust_np(&mattr, PTHREAD_MUTEX_ROBUST_NP));
#ifdef BUGGY_LINUX_MUTEX
				}
#endif
#endif

				memset(sh_mem_mutex->mtx_mutex, 0, sizeof(*(sh_mem_mutex->mtx_mutex)));
				//int state = LOG_PTHREAD_ERROR(pthread_mutex_init(sh_mem_mutex->mtx_mutex, &mattr));
				state = pthread_mutex_init(sh_mem_mutex->mtx_mutex, &mattr);

				if (state
#ifdef BUGGY_LINUX_MUTEX
					&& (state != ENOTSUP || bugFlag)
#endif
						 )
				{
					iscLogStatus("Pthread Error", (Arg::Gds(isc_sys_request) <<
						"pthread_mutex_init" << Arg::Unix(state)).value());
				}

				LOG_PTHREAD_ERROR(pthread_mutexattr_destroy(&mattr));

#ifdef BUGGY_LINUX_MUTEX
				if (state == ENOTSUP && !bugFlag)
				{
					staticBugFlag = true;
					continue;
				}

			} while (false);
#endif

			if (state)
			{
				callback->mutexBug(state, "pthread_mutex_init");
				system_call_failed::raise("pthread_mutex_init", state);
			}

#endif // USE_SYS5SEMAPHORE
#endif // HAVE_SHARED_MUTEX_SECTION

			mainLock->unlock();
			if (!mainLock->setlock(&statusVector, FileLock::FLM_SHARED))
			{
				if (statusVector.hasData())
					status_exception::raise(&statusVector);
				else
					(Arg::Gds(isc_random) << "Unknown error in setlock(SHARED)").raise();
			}
		}
	}
	else
	{
		if (callback->initialize(this, false))
		{
			if (!mainLock->setlock(&statusVector, FileLock::FLM_SHARED))
			{
				if (statusVector.hasData())
					status_exception::raise(&statusVector);
				else
					(Arg::Gds(isc_random) << "Unknown error in setlock(SHARED)").raise();
			}
		}
	}

#ifdef USE_FILELOCKS
	sh_mem_fileMutex.reset(FB_NEW_POOL(*getDefaultMemoryPool()) FileLock(mainLock, 1));
#endif

#ifdef USE_SYS5SEMAPHORE
	++sharedCount;
#endif

	autoUnmap.success();
}

#endif // UNIX


#ifdef WIN_NT
SharedMemoryBase::SharedMemoryBase(const TEXT* filename, ULONG length, IpcObject* cb)
  :	sh_mem_mutex(0), sh_mem_length_mapped(0),
	sh_mem_handle(0), sh_mem_object(0), sh_mem_interest(0), sh_mem_hdr_object(0),
	sh_mem_hdr_address(0), sh_mem_header(NULL), sh_mem_callback(cb), sh_mem_unlink(false)
{
/**************************************
 *
 *	c t o r		( W I N _ N T )
 *
 **************************************
 *
 * Functional description
 *	Try to map a given file.  If we are the first (i.e. only)
 *	process to map the file, call a given initialization
 *	routine (if given) or punt (leaving the file unmapped).
 *
 **************************************/
	fb_assert(sh_mem_callback);
	sh_mem_name[0] = '\0';

	ISC_mutex_init(&sh_mem_winMutex, filename);
	sh_mem_mutex = &sh_mem_winMutex;

	HANDLE file_handle;
	HANDLE event_handle = 0;
	int retry_count = 0;

	TEXT expanded_filename[MAXPATHLEN];
	iscPrefixLock(expanded_filename, filename, true);

	bool init_flag = false;
	DWORD err = 0;

	// retry to attach to mmapped file if the process initializing dies during initialization.

  retry:
	if (retry_count++ > 0)
		Thread::sleep(10);

	// Create an event that can be used to determine if someone has already
	// initialized shared memory.

	TEXT object_name[MAXPATHLEN];
	if (!make_object_name(object_name, sizeof(object_name), filename, "_event"))
	{
		system_call_failed::raise("make_object_name");
	}

	if (!init_flag)
	{
		event_handle = CreateEvent(ISC_get_security_desc(), TRUE, FALSE, object_name);
		err = GetLastError();
		if (!event_handle)
		{
			system_call_failed::raise("CreateEvent", err);
		}

		init_flag = (err != ERROR_ALREADY_EXISTS);

		SetHandleInformation(event_handle, HANDLE_FLAG_INHERIT, 0);
	}

	// All but the initializer will wait until the event is set.  That
	// is done after initialization is complete.

	if (!init_flag)
	{
		// Wait for 10 seconds.  Then retry

		const DWORD ret_event = WaitForSingleObject(event_handle, 10000);

		// If we timed out, just retry.  It is possible that the
		// process doing the initialization died before setting the event.

		if (ret_event == WAIT_TIMEOUT)
		{
			CloseHandle(event_handle);
			if (retry_count > 10)
			{
				system_call_failed::raise("WaitForSingleObject", 0);
			}
			goto retry;
		}
	}

	file_handle = CreateFile(expanded_filename,
							 GENERIC_READ | GENERIC_WRITE,
							 FILE_SHARE_READ | FILE_SHARE_WRITE,
							 NULL,
							 OPEN_ALWAYS,
							 FILE_ATTRIBUTE_NORMAL,
							 NULL);
	err = GetLastError();

	if (file_handle == INVALID_HANDLE_VALUE)
	{
		if ((err == ERROR_SHARING_VIOLATION) || (err == ERROR_ACCESS_DENIED))
		{
			if (!init_flag) {
				CloseHandle(event_handle);
			}

			if (retry_count < 200)	// 2 sec
				goto retry;
		}

		CloseHandle(event_handle);
		system_call_failed::raise("CreateFile", err);
	}

	if (init_flag)
	{
		if (err == ERROR_ALREADY_EXISTS)
		{
			const DWORD file_size = GetFileSize(file_handle, NULL);
			if (file_size == INVALID_FILE_SIZE)
			{
				err = GetLastError();
				CloseHandle(event_handle);
				CloseHandle(file_handle);
				system_call_failed::raise("GetFileSize", err);
			}

			if (length == 0)
			{
				length = file_size;
			}
			else if (file_size &&
					 SetFilePointer(file_handle, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||
					 !SetEndOfFile(file_handle) || !FlushFileBuffers(file_handle))
			{
				err = GetLastError();
				CloseHandle(event_handle);
				CloseHandle(file_handle);

				if (err == ERROR_USER_MAPPED_FILE)
				{
					if (retry_count < 50)	// 0.5 sec
						goto retry;

					Arg::Gds(isc_instance_conflict).raise();
				}
				else
					system_call_failed::raise("SetFilePointer", err);
			}
		}

		if (length == 0)
		{
			CloseHandle(event_handle);
			CloseHandle(file_handle);

			if (err == 0)
			{
				strcpy(sh_mem_name, filename);
				unlinkFile();
			}

			(Arg::Gds(isc_random) << Arg::Str("File for memory mapping is empty.")).raise();
		}

		if (SetFilePointer(file_handle, length, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||
			!SetEndOfFile(file_handle) || !FlushFileBuffers(file_handle))
		{
			err = GetLastError();
			CloseHandle(event_handle);
			CloseHandle(file_handle);
			system_call_failed::raise("SetFilePointer", err);
		}
	}
	else
	{
		if ((err != ERROR_ALREADY_EXISTS) || SetFilePointer(file_handle, 0, NULL, FILE_END) == 0)
		{
			CloseHandle(event_handle);
			CloseHandle(file_handle);
			goto retry;
		}
	}

	// Create a file mapping object that will be used to make remapping possible.
	// The current length of real mapped file and its name are saved in it.

	if (!make_object_name(object_name, sizeof(object_name), filename, "_mapping"))
	{
		err = GetLastError();
		CloseHandle(event_handle);
		CloseHandle(file_handle);
		system_call_failed::raise("make_object_name", err);
	}

	HANDLE header_obj = CreateFileMapping(INVALID_HANDLE_VALUE,
										  ISC_get_security_desc(),
										  PAGE_READWRITE,
										  0, 2 * sizeof(ULONG),
										  object_name);
	err = GetLastError();
	if (header_obj == NULL)
	{
		CloseHandle(event_handle);
		CloseHandle(file_handle);
		system_call_failed::raise("CreateFileMapping", err);
	}

	if (!init_flag && err != ERROR_ALREADY_EXISTS)
	{
		// We have made header_obj but we are not initializing.
		// Previous owner is closed and clear all header_data.
		// One need to retry.
		CloseHandle(header_obj);
		CloseHandle(event_handle);
		CloseHandle(file_handle);
		goto retry;
	}

	SetHandleInformation(header_obj, HANDLE_FLAG_INHERIT, 0);

	ULONG* const header_address = (ULONG*) MapViewOfFile(header_obj, FILE_MAP_WRITE, 0, 0, 0);

	if (header_address == NULL)
	{
		err = GetLastError();
		CloseHandle(header_obj);
		CloseHandle(event_handle);
		CloseHandle(file_handle);
		system_call_failed::raise("MapViewOfFile", err);
	}

	// Set or get the true length of the file depending on whether or not we are the first user.

	if (init_flag)
	{
		header_address[0] = length;
		header_address[1] = 0;
	}
	else if (header_address[0] == 0)
	{
		UnmapViewOfFile(header_address);
		CloseHandle(header_obj);
		CloseHandle(event_handle);
		CloseHandle(file_handle);
		goto retry;
	}
	else
		length = header_address[0];

	fb_assert(length);

	// Create the real file mapping object.

	TEXT mapping_name[64]; // enough for int32 as text
	sprintf(mapping_name, "_mapping_%" ULONGFORMAT, header_address[1]);

	if (!make_object_name(object_name, sizeof(object_name), filename, mapping_name))
	{
		err = GetLastError();
		UnmapViewOfFile(header_address);
		CloseHandle(header_obj);
		CloseHandle(event_handle);
		CloseHandle(file_handle);
		system_call_failed::raise("make_object_name", err);
	}

	HANDLE file_obj = CreateFileMapping(file_handle,
										ISC_get_security_desc(),
										PAGE_READWRITE,
										0, length,
										object_name);
	if (file_obj == NULL)
	{
		err = GetLastError();
		UnmapViewOfFile(header_address);
		CloseHandle(header_obj);
		CloseHandle(event_handle);
		CloseHandle(file_handle);
		system_call_failed::raise("CreateFileMapping", err);
	}

	SetHandleInformation(file_obj, HANDLE_FLAG_INHERIT, 0);

	UCHAR* const address = (UCHAR*) MapViewOfFile(file_obj, FILE_MAP_WRITE, 0, 0, 0);

	if (address == NULL)
	{
		err = GetLastError();
		CloseHandle(file_obj);
		UnmapViewOfFile(header_address);
		CloseHandle(header_obj);
		CloseHandle(event_handle);
		CloseHandle(file_handle);
		system_call_failed::raise("MapViewOfFile", err);
	}

	sh_mem_header = (MemoryHeader*) address;
	sh_mem_length_mapped = length;
	sh_mem_handle = file_handle;
	sh_mem_object = file_obj;
	sh_mem_interest = event_handle;
	sh_mem_hdr_object = header_obj;
	sh_mem_hdr_address = header_address;
	strcpy(sh_mem_name, filename);

	sh_mem_callback->initialize(this, init_flag);

	if (init_flag)
	{
		err = 0;
		if (!FlushViewOfFile(address, 0))
		{
			err = GetLastError();
		}

		SetEvent(event_handle);
		if (err)
		{
			UnmapViewOfFile(address);
			CloseHandle(file_obj);
			UnmapViewOfFile(header_address);
			CloseHandle(header_obj);
			CloseHandle(event_handle);
			CloseHandle(file_handle);
			system_call_failed::raise("FlushViewOfFile", err);
		}
	}
}
#endif


#ifdef HAVE_MMAP

UCHAR* SharedMemoryBase::mapObject(CheckStatusWrapper* statusVector, ULONG object_offset, ULONG object_length)
{
/**************************************
 *
 *	I S C _ m a p _ o b j e c t
 *
 **************************************
 *
 * Functional description
 *	Try to map an object given a file mapping.
 *
 **************************************/

	// Get system page size as this is the unit of mapping.

#ifdef SOLARIS
	const long ps = sysconf(_SC_PAGESIZE);
	if (ps == -1)
	{
		error(statusVector, "sysconf", errno);
		return NULL;
	}
#else
	const int ps = getpagesize();
	if (ps == -1)
	{
		error(statusVector, "getpagesize", errno);
		return NULL;
	}
#endif
	const ULONG page_size = (ULONG) ps;

	// Compute the start and end page-aligned offsets which contain the object being mapped.

	const ULONG start = (object_offset / page_size) * page_size;
	const ULONG end = FB_ALIGN(object_offset + object_length, page_size);
	const ULONG length = end - start;

	UCHAR* address = (UCHAR*) mmap(0, length, PROT_READ | PROT_WRITE, MAP_SHARED, mainLock->getFd(), start);

	if ((U_IPTR) address == (U_IPTR) -1)
	{
		error(statusVector, "mmap", errno);
		return NULL;
	}

	// Return the virtual address of the mapped object.

	IPC_TRACE(("ISC_map_object in %p to %p %p\n", shmem_data->sh_mem_address, address, address + length));

	return address + (object_offset - start);
}


void SharedMemoryBase::unmapObject(CheckStatusWrapper* statusVector, UCHAR** object_pointer, ULONG object_length)
{
/**************************************
 *
 *	I S C _ u n m a p _ o b j e c t
 *
 **************************************
 *
 * Functional description
 *	Try to unmap an object given a file mapping.
 *	Zero the object pointer after a successful unmap.
 *
 **************************************/
	// Get system page size as this is the unit of mapping.

#ifdef SOLARIS
	const long ps = sysconf(_SC_PAGESIZE);
	if (ps == -1)
	{
		error(statusVector, "sysconf", errno);
		return;
	}
#else
	const int ps = getpagesize();
	if (ps == -1)
	{
		error(statusVector, "getpagesize", errno);
		return;
	}
#endif
	const size_t page_size = (ULONG) ps;

	// Compute the start and end page-aligned addresses which contain the mapped object.

	char* const start = (char*) ((U_IPTR) (*object_pointer) & ~(page_size - 1));
	char* const end =
		(char*) ((U_IPTR) ((*object_pointer + object_length) + (page_size - 1)) & ~(page_size - 1));
	const size_t length = end - start;

	if (munmap(start, length) == -1)
	{
		error(statusVector, "munmap", errno);
		return; // false;
	}

	*object_pointer = NULL;
	return; // true;
}
#endif // HAVE_MMAP


#ifdef WIN_NT

UCHAR* SharedMemoryBase::mapObject(CheckStatusWrapper* statusVector,
								   ULONG object_offset,
								   ULONG object_length)
{
/**************************************
 *
 *	I S C _ m a p _ o b j e c t
 *
 **************************************
 *
 * Functional description
 *	Try to map an object given a file mapping.
 *
 **************************************/

	SYSTEM_INFO sys_info;
	GetSystemInfo(&sys_info);
	const ULONG page_size = sys_info.dwAllocationGranularity;

	// Compute the start and end page-aligned offsets which
	// contain the object being mapped.

	const ULONG start = (object_offset / page_size) * page_size;
	const ULONG end = FB_ALIGN(object_offset + object_length, page_size);
	const ULONG length = end - start;
	const HANDLE handle = sh_mem_object;

	UCHAR* address = (UCHAR*) MapViewOfFile(handle, FILE_MAP_WRITE, 0, start, length);

	if (address == NULL)
	{
		error(statusVector, "MapViewOfFile", GetLastError());
		return NULL;
	}

	// Return the virtual address of the mapped object.

	return (address + (object_offset - start));
}


void SharedMemoryBase::unmapObject(CheckStatusWrapper* statusVector,
								   UCHAR** object_pointer, ULONG /*object_length*/)
{
/**************************************
 *
 *	I S C _ u n m a p _ o b j e c t
 *
 **************************************
 *
 * Functional description
 *	Try to unmap an object given a file mapping.
 *	Zero the object pointer after a successful unmap.
 *
 **************************************/
	SYSTEM_INFO sys_info;
	GetSystemInfo(&sys_info);
	const size_t page_size = sys_info.dwAllocationGranularity;

	// Compute the start and end page-aligned offsets which
	// contain the object being mapped.

	const UCHAR* start = (UCHAR*) ((U_IPTR) *object_pointer & ~(page_size - 1));
	if (!UnmapViewOfFile(start))
	{
		error(statusVector, "UnmapViewOfFile", GetLastError());
		return;
	}

	*object_pointer = NULL;
}
#endif


#ifdef WIN_NT

static const LPCSTR FAST_MUTEX_EVT_NAME	= "%s_FM_EVT";
static const LPCSTR FAST_MUTEX_MAP_NAME	= "%s_FM_MAP";

static const int DEFAULT_INTERLOCKED_SPIN_COUNT	= 0;
static const int DEFAULT_INTERLOCKED_SPIN_COUNT_SMP	= 200;

static SLONG pid = 0;

typedef WINBASEAPI BOOL (WINAPI *pfnSwitchToThread) ();
static inline BOOL switchToThread()
{
	static pfnSwitchToThread fnSwitchToThread = NULL;
	static bool bInit = false;

	if (!bInit)
	{
		HMODULE hLib = GetModuleHandle("kernel32.dll");
		if (hLib)
			fnSwitchToThread = (pfnSwitchToThread) GetProcAddress(hLib, "SwitchToThread");

		bInit = true;
	}

	BOOL res = FALSE;

	if (fnSwitchToThread)
	{
		const HANDLE hThread = GetCurrentThread();
		SetThreadPriority(hThread, THREAD_PRIORITY_ABOVE_NORMAL);

		res = (*fnSwitchToThread)();

		SetThreadPriority(hThread, THREAD_PRIORITY_NORMAL);
	}

	return res;
}


// MinGW has the wrong declaration for the operating system function.
#if defined __GNUC__
// Cast away volatile
#define FIX_TYPE(arg) const_cast<LPLONG>(arg)
#else
#define FIX_TYPE(arg) arg
#endif


static inline void lockSharedSection(volatile FAST_MUTEX_SHARED_SECTION* lpSect, ULONG SpinCount)
{
	while (InterlockedExchange(FIX_TYPE(&lpSect->lSpinLock), 1) != 0)
	{
		ULONG j = SpinCount;
		while (j != 0)
		{
			if (lpSect->lSpinLock == 0)
				goto next;
			j--;
		}
		switchToThread();
next:;
	}
}

static inline bool tryLockSharedSection(volatile FAST_MUTEX_SHARED_SECTION* lpSect)
{
	return (InterlockedExchange(FIX_TYPE(&lpSect->lSpinLock), 1) == 0);
}

static inline void unlockSharedSection(volatile FAST_MUTEX_SHARED_SECTION* lpSect)
{
	InterlockedExchange(FIX_TYPE(&lpSect->lSpinLock), 0);
}

static DWORD enterFastMutex(FAST_MUTEX* lpMutex, DWORD dwMilliseconds)
{
	volatile FAST_MUTEX_SHARED_SECTION* lpSect = lpMutex->lpSharedInfo;

	while (true)
	{
		if (dwMilliseconds == 0)
		{
			if (!tryLockSharedSection(lpSect))
				return WAIT_TIMEOUT;
		}
		else {
			lockSharedSection(lpSect, lpMutex->lSpinCount);
		}

		if (lpSect->lAvailable > 0)
		{
			lpSect->lAvailable--;
			lpSect->lOwnerPID = pid;
#ifdef DEV_BUILD
			lpSect->lThreadId = GetCurrentThreadId();
#endif
			unlockSharedSection(lpSect);
			return WAIT_OBJECT_0;
		}

		if (dwMilliseconds == 0)
		{
			unlockSharedSection(lpSect);
			return WAIT_TIMEOUT;
		}

		InterlockedIncrement(FIX_TYPE(&lpSect->lThreadsWaiting));
		unlockSharedSection(lpSect);

		// TODO actual timeout can be of any length
		const DWORD tm = (dwMilliseconds == INFINITE || dwMilliseconds > 5000) ? 5000 : dwMilliseconds;
		const DWORD dwResult = WaitForSingleObject(lpMutex->hEvent, tm);

		InterlockedDecrement(FIX_TYPE(&lpSect->lThreadsWaiting));

		if (dwMilliseconds != INFINITE)
			dwMilliseconds -= tm;

//		if (dwResult != WAIT_OBJECT_0)
//			return dwResult;

		if (dwResult == WAIT_OBJECT_0)
			continue;
		if (dwResult == WAIT_ABANDONED)
			return dwResult;
		if (dwResult == WAIT_TIMEOUT && !dwMilliseconds)
			return dwResult;

		lockSharedSection(lpSect, lpMutex->lSpinCount);
		if (lpSect->lOwnerPID > 0 && !lpSect->lAvailable)
		{
			if (!ISC_check_process_existence(lpSect->lOwnerPID))
			{
#ifdef DEV_BUILD
				gds__log("enterFastMutex: dead process detected, pid = %d", lpSect->lOwnerPID);
				lpSect->lThreadId = 0;
#endif
				lpSect->lOwnerPID = 0;
				lpSect->lAvailable++;
			}
		}
		unlockSharedSection(lpSect);
	}
}

static bool leaveFastMutex(FAST_MUTEX* lpMutex)
{
	volatile FAST_MUTEX_SHARED_SECTION* lpSect = lpMutex->lpSharedInfo;

	lockSharedSection(lpSect, lpMutex->lSpinCount);
	if (lpSect->lAvailable >= 1)
	{
		unlockSharedSection(lpSect);
		SetLastError(ERROR_INVALID_PARAMETER);
		return false;
	}
	lpSect->lAvailable++;
	if (lpSect->lThreadsWaiting)
		SetEvent(lpMutex->hEvent);
	fb_assert(lpSect->lOwnerPID == pid);
	lpSect->lOwnerPID = -lpSect->lOwnerPID;
#ifdef DEV_BUILD
	fb_assert(lpSect->lThreadId == GetCurrentThreadId());
	lpSect->lThreadId = -lpSect->lThreadId;
#endif
	unlockSharedSection(lpSect);

	return true;
}

static inline void deleteFastMutex(FAST_MUTEX* lpMutex)
{
	UnmapViewOfFile((FAST_MUTEX_SHARED_SECTION*)lpMutex->lpSharedInfo);
	CloseHandle(lpMutex->hFileMap);
	CloseHandle(lpMutex->hEvent);
}

static inline void setupMutex(FAST_MUTEX* lpMutex)
{
	SYSTEM_INFO si;
	GetSystemInfo(&si);

	if (si.dwNumberOfProcessors > 1)
		lpMutex->lSpinCount = DEFAULT_INTERLOCKED_SPIN_COUNT_SMP;
	else
		lpMutex->lSpinCount = DEFAULT_INTERLOCKED_SPIN_COUNT;
}

static bool initializeFastMutex(FAST_MUTEX* lpMutex, LPSECURITY_ATTRIBUTES lpAttributes,
								BOOL bInitialState, LPCSTR lpName)
{
	if (pid == 0)
		pid = GetCurrentProcessId();

	LPCSTR name = lpName;

	if (lpName && strlen(lpName) + strlen(FAST_MUTEX_EVT_NAME) - 2 >= MAXPATHLEN)
	{
		// this is the same error which CreateEvent will return for long name
		SetLastError(ERROR_FILENAME_EXCED_RANGE);
		return false;
	}

	setupMutex(lpMutex);

	char sz[MAXPATHLEN];
	if (lpName)
	{
		sprintf(sz, FAST_MUTEX_EVT_NAME, lpName);
		name = sz;
	}

#ifdef DONT_USE_FAST_MUTEX
	lpMutex->lpSharedInfo = NULL;
	lpMutex->hEvent = CreateMutex(lpAttributes, bInitialState, name);
	return (lpMutex->hEvent != NULL);
#else
	lpMutex->hEvent = CreateEvent(lpAttributes, FALSE, FALSE, name);
	DWORD dwLastError = GetLastError();

	if (lpMutex->hEvent)
	{
		SetHandleInformation(lpMutex->hEvent, HANDLE_FLAG_INHERIT, 0);

		if (lpName)
			sprintf(sz, FAST_MUTEX_MAP_NAME, lpName);

		lpMutex->hFileMap = CreateFileMapping(
			INVALID_HANDLE_VALUE,
			lpAttributes,
			PAGE_READWRITE,
			0,
			sizeof(FAST_MUTEX_SHARED_SECTION),
			name);

		dwLastError = GetLastError();

		if (lpMutex->hFileMap)
		{
			SetHandleInformation(lpMutex->hFileMap, HANDLE_FLAG_INHERIT, 0);

			lpMutex->lpSharedInfo = (FAST_MUTEX_SHARED_SECTION*)
				MapViewOfFile(lpMutex->hFileMap, FILE_MAP_WRITE, 0, 0, 0);

			if (lpMutex->lpSharedInfo)
			{
				if (dwLastError != ERROR_ALREADY_EXISTS)
				{
					lpMutex->lpSharedInfo->lSpinLock = 0;
					lpMutex->lpSharedInfo->lThreadsWaiting = 0;
					lpMutex->lpSharedInfo->lAvailable = bInitialState ? 0 : 1;
					lpMutex->lpSharedInfo->lOwnerPID = bInitialState ? pid : 0;
#ifdef DEV_BUILD
					lpMutex->lpSharedInfo->lThreadId = bInitialState ? GetCurrentThreadId() : 0;
#endif
					InterlockedExchange(FIX_TYPE(&lpMutex->lpSharedInfo->fInitialized), 1);
				}
				else
				{
					while (!lpMutex->lpSharedInfo->fInitialized)
						switchToThread();
				}

				SetLastError(dwLastError);
				return true;
			}
			CloseHandle(lpMutex->hFileMap);
		}
		CloseHandle(lpMutex->hEvent);
	}

	SetLastError(dwLastError);
	return false;
#endif // DONT_USE_FAST_MUTEX
}

#ifdef NOT_USED_OR_REPLACED
static bool openFastMutex(FAST_MUTEX* lpMutex, DWORD DesiredAccess, LPCSTR lpName)
{
	LPCSTR name = lpName;

	if (lpName && strlen(lpName) + strlen(FAST_MUTEX_EVT_NAME) - 2 >= MAXPATHLEN)
	{
		SetLastError(ERROR_FILENAME_EXCED_RANGE);
		return false;
	}

	setupMutex(lpMutex);

	char sz[MAXPATHLEN];
	if (lpName)
	{
		sprintf(sz, FAST_MUTEX_EVT_NAME, lpName);
		name = sz;
	}

	lpMutex->hEvent = OpenEvent(EVENT_ALL_ACCESS, FALSE, name);

	DWORD dwLastError = GetLastError();

	if (lpMutex->hEvent)
	{
		if (lpName)
			sprintf(sz, FAST_MUTEX_MAP_NAME, lpName);

		lpMutex->hFileMap = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, name);

		dwLastError = GetLastError();

		if (lpMutex->hFileMap)
		{
			lpMutex->lpSharedInfo = (FAST_MUTEX_SHARED_SECTION*)
				MapViewOfFile(lpMutex->hFileMap, FILE_MAP_WRITE, 0, 0, 0);

			if (lpMutex->lpSharedInfo)
				return true;

			CloseHandle(lpMutex->hFileMap);
		}
		CloseHandle(lpMutex->hEvent);
	}

	SetLastError(dwLastError);
	return false;
}
#endif

static inline void setFastMutexSpinCount(FAST_MUTEX* lpMutex, ULONG SpinCount)
{
	lpMutex->lSpinCount = SpinCount;
}


int ISC_mutex_init(struct mtx* mutex, const TEXT* mutex_name)
{
/**************************************
 *
 *	I S C _ m u t e x _ i n i t	( W I N _ N T )
 *
 **************************************
 *
 * Functional description
 *	Initialize a mutex.
 *
 **************************************/
	char name_buffer[MAXPATHLEN];

	if (!make_object_name(name_buffer, sizeof(name_buffer), mutex_name, "_mutex"))
	{
		return FB_FAILURE;
	}

	if (initializeFastMutex(&mutex->mtx_fast, ISC_get_security_desc(), FALSE, name_buffer))
		return FB_SUCCESS;

	fb_assert(GetLastError() != 0);
	return GetLastError();
}


void ISC_mutex_fini(struct mtx *mutex)
{
/**************************************
 *
 *	m u t e x _ f i n i ( W I N _ N T )
 *
 **************************************
 *
 * Functional description
 *	Destroy a mutex.
 *
 **************************************/
	if (mutex->mtx_fast.lpSharedInfo)
		deleteFastMutex(&mutex->mtx_fast);
}


int ISC_mutex_lock(struct mtx* mutex)
{
/**************************************
 *
 *	I S C _ m u t e x _ l o c k	( W I N _ N T )
 *
 **************************************
 *
 * Functional description
 *	Seize a mutex.
 *
 **************************************/

	const DWORD status = (mutex->mtx_fast.lpSharedInfo) ?
		enterFastMutex(&mutex->mtx_fast, INFINITE) :
			WaitForSingleObject(mutex->mtx_fast.hEvent, INFINITE);

    return (status == WAIT_OBJECT_0 || status == WAIT_ABANDONED) ? FB_SUCCESS : FB_FAILURE;
}


int ISC_mutex_lock_cond(struct mtx* mutex)
{
/**************************************
 *
 *	I S C _ m u t e x _ l o c k _ c o n d	( W I N _ N T )
 *
 **************************************
 *
 * Functional description
 *	Conditionally seize a mutex.
 *
 **************************************/

	const DWORD status = (mutex->mtx_fast.lpSharedInfo) ?
		enterFastMutex(&mutex->mtx_fast, 0) : WaitForSingleObject(mutex->mtx_fast.hEvent, 0L);

    return (status == WAIT_OBJECT_0 || status == WAIT_ABANDONED) ? FB_SUCCESS : FB_FAILURE;
}


int ISC_mutex_unlock(struct mtx* mutex)
{
/**************************************
 *
 *	I S C _ m u t e x _ u n l o c k		( W I N _ N T )
 *
 **************************************
 *
 * Functional description
 *	Release a mutex.
 *
 **************************************/

	if (mutex->mtx_fast.lpSharedInfo) {
		return !leaveFastMutex(&mutex->mtx_fast);
	}

	return !ReleaseMutex(mutex->mtx_fast.hEvent);
}


void ISC_mutex_set_spin_count (struct mtx *mutex, ULONG spins)
{
	if (mutex->mtx_fast.lpSharedInfo)
		setFastMutexSpinCount(&mutex->mtx_fast, spins);
}

#endif // WIN_NT


#ifdef UNIX
#ifdef HAVE_MMAP
#define ISC_REMAP_FILE_DEFINED
bool SharedMemoryBase::remapFile(CheckStatusWrapper* statusVector, ULONG new_length, bool flag)
{
/**************************************
 *
 *	I S C _ r e m a p _ f i l e		( U N I X - m m a p )
 *
 **************************************
 *
 * Functional description
 *	Try to re-map a given file.
 *
 **************************************/
	if (!new_length)
	{
		error(statusVector, "Zero new_length is requested", 0);
		return false;
	}

	if (flag)
		FB_UNUSED(ftruncate(mainLock->getFd(), new_length));

	MemoryHeader* const address = (MemoryHeader*)
		mmap(0, new_length, PROT_READ | PROT_WRITE, MAP_SHARED, mainLock->getFd(), 0);
	if ((U_IPTR) address == (U_IPTR) -1)
	{
		error(statusVector, "mmap() failed", errno);
		return false;
	}

	munmap(sh_mem_header, sh_mem_length_mapped);

	IPC_TRACE(("ISC_remap_file %p to %p %d\n", sh_mem_header, address, new_length));

	sh_mem_header = (MemoryHeader*) address;
	sh_mem_length_mapped = new_length;

#if defined(HAVE_SHARED_MUTEX_SECTION) && !defined(USE_MUTEX_MAP)
	sh_mem_mutex = &sh_mem_header->mhb_mutex;
#endif

	return address;
}
#endif // HAVE_MMAP
#endif // UNIX


#ifdef WIN_NT
#define ISC_REMAP_FILE_DEFINED
bool SharedMemoryBase::remapFile(CheckStatusWrapper* statusVector,
								 ULONG new_length, bool flag)
{
/**************************************
 *
 *	I S C _ r e m a p _ f i l e		( W I N _ N T )
 *
 **************************************
 *
 * Functional description
 *	Try to re-map a given file.
 *
 **************************************/

	if (flag)
	{
		if (SetFilePointer(sh_mem_handle, new_length, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||
			!SetEndOfFile(sh_mem_handle) ||
			!FlushViewOfFile(sh_mem_header, 0))
		{
			error(statusVector, "SetFilePointer", GetLastError());
			return NULL;
		}
	}

	/* If the remap file exists, remap does not occur correctly.
	* The file number is local to the process and when it is
	* incremented and a new filename is created, that file may
	* already exist.  In that case, the file is not expanded.
	* This will happen when the file is expanded more than once
	* by concurrently running processes.
	*
	* The problem will be fixed by making sure that a new file name
	* is generated with the mapped file is created.
	*/

	HANDLE file_obj = NULL;

	while (true)
	{
		TEXT mapping_name[64]; // enough for int32 as text
		sprintf(mapping_name, "_mapping_%" ULONGFORMAT, sh_mem_hdr_address[1] + 1);

		TEXT object_name[MAXPATHLEN];
		if (!make_object_name(object_name, sizeof(object_name), sh_mem_name, mapping_name))
			break;

		file_obj = CreateFileMapping(sh_mem_handle,
									 ISC_get_security_desc(),
									 PAGE_READWRITE,
									 0, new_length,
									 object_name);

		if (!(GetLastError() == ERROR_ALREADY_EXISTS && flag))
			break;

		CloseHandle(file_obj);
		file_obj = NULL;
		sh_mem_hdr_address[1]++;
	}

	if (file_obj == NULL)
	{
		error(statusVector, "CreateFileMapping", GetLastError());
		return NULL;
	}

	MemoryHeader* const address = (MemoryHeader*) MapViewOfFile(file_obj, FILE_MAP_WRITE, 0, 0, 0);

	if (address == NULL)
	{
		error(statusVector, "MapViewOfFile", GetLastError());
		CloseHandle(file_obj);
		return NULL;
	}

	if (flag)
	{
		sh_mem_hdr_address[0] = new_length;
		sh_mem_hdr_address[1]++;
	}

	UnmapViewOfFile(sh_mem_header);
	CloseHandle(sh_mem_object);

	sh_mem_header = (MemoryHeader*) address;
	sh_mem_length_mapped = new_length;
	sh_mem_object = file_obj;

	if (!sh_mem_length_mapped)
	{
		error(statusVector, "sh_mem_length_mapped is 0", 0);
		return NULL;
	}

	return (address);
}
#endif


#ifndef ISC_REMAP_FILE_DEFINED
bool SharedMemoryBase::remapFile(CheckStatusWrapper* statusVector, ULONG, bool)
{
/**************************************
 *
 *	I S C _ r e m a p _ f i l e		( G E N E R I C )
 *
 **************************************
 *
 * Functional description
 *	Try to re-map a given file.
 *
 **************************************/

	(Arg::Gds(isc_unavailable) <<
		Arg::Gds(isc_random) << "SharedMemory::remapFile").copyTo(statusVector);

	return NULL;
}
#endif


#ifdef USE_SYS5SEMAPHORE

static SLONG create_semaphores(CheckStatusWrapper* statusVector, SLONG key, int semaphores)
{
/**************************************
 *
 *	c r e a t e _ s e m a p h o r e s		( U N I X )
 *
 **************************************
 *
 * Functional description
 *	Create or find a block of semaphores.
 *
 **************************************/
	while (true)
	{
		// Try to open existing semaphore set
		SLONG semid = semget(key, 0, 0);
		if (semid == -1)
		{
			if (errno != ENOENT)
			{
				error(statusVector, "semget", errno);
				return -1;
			}
		}
		else
		{
			union semun arg;
			semid_ds buf;
			arg.buf = &buf;
			// Get number of semaphores in opened set
			if (semctl(semid, 0, IPC_STAT, arg) == -1)
			{
				error(statusVector, "semctl", errno);
				return -1;
			}
			if ((int) buf.sem_nsems >= semaphores)
				return semid;
			// Number of semaphores in existing set is too small. Discard it.
			if (semctl(semid, 0, IPC_RMID) == -1)
			{
				error(statusVector, "semctl", errno);
				return -1;
			}
		}

		// Try to create new semaphore set
		semid = semget(key, semaphores, IPC_CREAT | IPC_EXCL | PRIV);
		if (semid != -1)
		{
			// We want to limit access to semaphores, created here
			// Reasonable access rights to them - exactly like security database has
			const char* secDb = Config::getDefaultConfig()->getSecurityDatabase();
			struct stat st;
			if (stat(secDb, &st) == 0)
			{
				union semun arg;
				semid_ds ds;
				arg.buf = &ds;
				ds.sem_perm.uid = geteuid() == 0 ? st.st_uid : geteuid();
				ds.sem_perm.gid = st.st_gid;
				ds.sem_perm.mode = st.st_mode;
				semctl(semid, 0, IPC_SET, arg);
			}
			return semid;
		}

		if (errno != EEXIST)
		{
			error(statusVector, "semget", errno);
			return -1;
		}
	}
}

#endif // USE_SYS5SEMAPHORE


#ifdef WIN_NT
static bool make_object_name(TEXT* buffer, size_t bufsize,
							 const TEXT* object_name,
							 const TEXT* object_type)
{
/**************************************
 *
 *	m a k e _ o b j e c t _ n a m e		( W I N _ N T )
 *
 **************************************
 *
 * Functional description
 *	Create an object name from a name and type.
 *	Also replace the file separator with "_".
 *
 **************************************/
	char hostname[64];
	const int rc = snprintf(buffer, bufsize, object_name, ISC_get_host(hostname, sizeof(hostname)));
	if (size_t(rc) == bufsize || rc <= 0)
	{
		SetLastError(ERROR_FILENAME_EXCED_RANGE);
		return false;
	}

	char& limit = buffer[bufsize - 1];
	limit = 0;

	char* p;
	char c;
	for (p = buffer; c = *p; p++)
	{
		if (c == '/' || c == '\\' || c == ':')
			*p = '_';
	}

	// We either append the full object type or produce failure.
	if (p >= &limit || p + strlen(object_type) > &limit)
	{
		SetLastError(ERROR_FILENAME_EXCED_RANGE);
		return false;
	}

	strcpy(p, object_type);

	// hvlad: windows file systems use case-insensitive file names
	// while kernel objects such as events use case-sensitive names.
	// Since we use root directory as part of kernel objects names
	// we must use lower (or upper) register for object name to avoid
	// misunderstanding between processes
	strlwr(buffer);

	// CVC: I'm not convinced that if this call has no space to put the prefix,
	// we can ignore that fact, hence I changed that signature, too.
	if (!fb_utils::prefix_kernel_object_name(buffer, bufsize))
	{
		SetLastError(ERROR_FILENAME_EXCED_RANGE);
		return false;
	}
	return true;
}
#endif // WIN_NT


void SharedMemoryBase::mutexLock()
{
#if defined(WIN_NT)

	int state = ISC_mutex_lock(sh_mem_mutex);

#elif defined(USE_FILELOCKS)

	int state = 0;
	try
	{
		localMutex.enter(FB_FUNCTION);
	}
	catch (const system_call_failed& fail)
	{
		state = fail.getErrorCode();
	}
	if (!state)
	{
		state = sh_mem_fileMutex->setlock(FileLock::FLM_EXCLUSIVE);
		if (state)
		{
			try
			{
				localMutex.leave();
			}
			catch (const Exception&)
			{ }
		}
	}

#elif defined(USE_SYS5SEMAPHORE)

	struct sembuf sop;
	sop.sem_num = sh_mem_mutex->semNum;
	sop.sem_op = -1;
	sop.sem_flg = SEM_UNDO;

	int state;
	for (;;)
	{
		state = semop(sh_mem_mutex->getId(), &sop, 1);
		if (state == 0)
			break;
		if (!SYSCALL_INTERRUPTED(errno))
		{
			state = errno;
			break;
		}
	}

#else // POSIX SHARED MUTEX

	int state = pthread_mutex_lock(sh_mem_mutex->mtx_mutex);
#ifdef USE_ROBUST_MUTEX
	if (state == EOWNERDEAD)
	{
		// We always perform check for dead process
		// Therefore may safely mark mutex as recovered
		LOG_PTHREAD_ERROR(pthread_mutex_consistent_np(sh_mem_mutex->mtx_mutex));
		state = 0;
	}
#endif

#endif // os-dependent choice

	if (state != 0)
	{
		sh_mem_callback->mutexBug(state, "mutexLock");
	}
}


bool SharedMemoryBase::mutexLockCond()
{
#if defined(WIN_NT)

	return ISC_mutex_lock_cond(sh_mem_mutex) == 0;

#elif defined(USE_FILELOCKS)

	try
	{
		if (!localMutex.tryEnter(FB_FUNCTION))
		{
			return false;
		}
	}
	catch (const system_call_failed& fail)
	{
		int state = fail.getErrorCode();
		sh_mem_callback->mutexBug(state, "mutexLockCond");
		return false;
	}

	bool rc = (sh_mem_fileMutex->setlock(FileLock::FLM_TRY_EXCLUSIVE) == 0);
	if (!rc)
	{
		try
		{
			localMutex.leave();
		}
		catch (const Exception&)
		{ }
	}
	return rc;

#elif defined(USE_SYS5SEMAPHORE)

	struct sembuf sop;
	sop.sem_num = sh_mem_mutex->semNum;
	sop.sem_op = -1;
	sop.sem_flg = SEM_UNDO | IPC_NOWAIT;

	for (;;)
	{
		int state = semop(sh_mem_mutex->getId(), &sop, 1);
		if (state == 0)
			return true;
		if (!SYSCALL_INTERRUPTED(errno))
			return false;
	}

#else // POSIX SHARED MUTEX

	int state = pthread_mutex_trylock(sh_mem_mutex->mtx_mutex);
#ifdef USE_ROBUST_MUTEX
	if (state == EOWNERDEAD)
	{
		// We always perform check for dead process
		// Therefore may safely mark mutex as recovered
		LOG_PTHREAD_ERROR(pthread_mutex_consistent_np(sh_mem_mutex->mtx_mutex));
		state = 0;
	}
#endif
	return state == 0;

#endif // os-dependent choice

}


void SharedMemoryBase::mutexUnlock()
{
#if defined(WIN_NT)

	int state = ISC_mutex_unlock(sh_mem_mutex);

#elif defined(USE_FILELOCKS)

	int state = 0;
	try
	{
		localMutex.leave();
	}
	catch (const system_call_failed& fail)
	{
		state = fail.getErrorCode();
	}
	if (!state)
	{
		sh_mem_fileMutex->unlock();
	}

#elif defined(USE_SYS5SEMAPHORE)

	struct sembuf sop;
	sop.sem_num = sh_mem_mutex->semNum;
	sop.sem_op = 1;
	sop.sem_flg = SEM_UNDO;

	int state;
	for (;;)
	{
		state = semop(sh_mem_mutex->getId(), &sop, 1);
		if (state == 0)
			break;
		if (!SYSCALL_INTERRUPTED(errno))
		{
			state = errno;
			break;
		}
	}

#else // POSIX SHARED MUTEX

	int state = pthread_mutex_unlock(sh_mem_mutex->mtx_mutex);

#endif // os-dependent choice

	if (state != 0)
	{
		sh_mem_callback->mutexBug(state, "mutexUnlock");
	}
}


SharedMemoryBase::~SharedMemoryBase()
{
/**************************************
 *
 *	I S C _ u n m a p _ f i l e
 *
 **************************************
 *
 * Functional description
 *	Unmap a given file.
 *
 **************************************/

#ifdef USE_SYS5SEMAPHORE
	// freeSem5(sh_mem_mutex);		no need - all set of semaphores will be gone

	try
	{
		// Lock init file.
		FileLockHolder initLock(initFile);

		LocalStatus ls;
		CheckStatusWrapper statusVector(&ls);
		mainLock->unlock();
		semTable->cleanup(fileNum, mainLock->setlock(&statusVector, FileLock::FLM_TRY_EXCLUSIVE));
	}
	catch (const Exception& ex)
	{
		iscLogException("ISC_unmap_file failed to lock init file", ex);
	}

	--sharedCount;
#endif

#if defined(HAVE_SHARED_MUTEX_SECTION) && defined(USE_MUTEX_MAP)
	LocalStatus ls;
	CheckStatusWrapper statusVector(&ls);
	unmapObject(&statusVector, (UCHAR**) &sh_mem_mutex, sizeof(mtx));
	if (statusVector.hasData())
	{
		iscLogStatus("unmapObject failed", &statusVector);
	}
#endif

#ifdef UNIX
	internalUnmap();
#endif

#ifdef WIN_NT
	if (!UnmapViewOfFile(sh_mem_header))
	{
		return;
	}
	sh_mem_header = NULL;
	CloseHandle(sh_mem_object);
	CloseHandle(sh_mem_handle);

	CloseHandle(sh_mem_interest);

	if (!UnmapViewOfFile(sh_mem_hdr_address))
	{
		return;
	}
	sh_mem_hdr_address = NULL;
	CloseHandle(sh_mem_hdr_object);

	ISC_mutex_fini(&sh_mem_winMutex);
	sh_mem_mutex = NULL;

	if (sh_mem_unlink)
	{
		unlinkFile();
	}
#endif
}

void SharedMemoryBase::logError(const char* text, const CheckStatusWrapper* status)
{
	iscLogStatus(text, status);
}


static bool event_blocked(const event_t* event, const SLONG value)
{
/**************************************
 *
 *	e v e n t _ b l o c k e d
 *
 **************************************
 *
 * Functional description
 *	If a wait would block, return true.
 *
 **************************************/

	if (event->event_count >= value)
	{
#ifdef DEBUG_ISC_SYNC
		printf("event_blocked: FALSE (eg something to report)\n");
		fflush(stdout);
#endif
		return false;
	}

#ifdef DEBUG_ISC_SYNC
	printf("event_blocked: TRUE (eg nothing happened yet)\n");
	fflush(stdout);
#endif
	return true;
}


static void error(CheckStatusWrapper* statusVector, const TEXT* string, ISC_STATUS status)
{
/**************************************
 *
 *	e r r o r
 *
 **************************************
 *
 * Functional description
 *	We've encountered an error, report it.
 *
 **************************************/
	(Arg::StatusVector(statusVector) <<
		Arg::Gds(isc_sys_request) << string << SYS_ERR(status)).copyTo(statusVector);
}