File: libfakeroot.c

package info (click to toggle)
fakeroot 1.20.2-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 2,628 kB
  • ctags: 1,130
  • sloc: sh: 11,765; ansic: 4,701; makefile: 260; perl: 14
file content (2420 lines) | stat: -rw-r--r-- 55,158 bytes parent folder | download | duplicates (3)
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
/*
  Copyright Ⓒ 1997, 1998, 1999, 2000, 2001  joost witteveen
  Copyright Ⓒ 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009  Clint Adams
  Copyright Ⓒ 2012 Mikhail Gusarov

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

*/
/* #define _POSIX_C_SOURCE 199309L whatever that may mean...*/
/* #define _BSD_SOURCE             I use strdup, S_IFDIR, etc */

/* Roderich Schupp writes (bug #79100):
   /usr/include/dlfcn.h from libc6 2.2-5 defines RTLD_NEXT only
   when compiled with _GNU_SOURCE defined. Hence libfakeroot.c doesn't pick
   it
   up and does a dlopen("/lib/libc.so.6",...) in get_libc().
   This works most of the time, but explodes if you have an arch-optimized
   libc installed: the program now has two versions of libc.so
   (/lib/libc.so.6 and, say, /lib/i586/libc.so.6) mapped. Again for
   some programs you might get away with this, but running bash under
   fakeroot
   always bombs. Simple fix:
*/
#define _GNU_SOURCE

#define FAKEROOT_LIBFAKEROOT

#ifdef __APPLE__
/*
   In this file, we want 'struct stat' to have a 32-bit 'ino_t'.
   We use 'struct stat64' when we need a 64-bit 'ino_t'.
*/
#define _DARWIN_NO_64_BIT_INODE

/* The helper _unix2003 version of this file calls a few functions in this file
   that are marked with static_nonapple so that needs to become private instead
*/
#define static_nonapple __attribute__((visibility("hidden")))

#ifndef __LP64__
/*
   This file is for 32-bit symbols which do not have the "$UNIX2003" version.
*/
#define _NONSTD_SOURCE
#endif
#else /* !__APPLE__ */
/* static_nonapple needs to become static in this case */
#define static_nonapple static
#endif /* !__APPLE__ */

#include "config.h"
#include "communicate.h"

#ifdef __APPLE__
/* The *xattr functions are currently disabled on __APPLE__ since the prototypes
   are all different from the Linux versions and there is, as of yet, no
   STUPID_APPLE_HACK (or similar) to deal with the differences.
   Note that __APPLE__ does not have the l*xattr variants or capset so those
   will already be undefined.
*/
#undef HAVE_LISTXATTR
#undef HAVE_FLISTXATTR
#undef HAVE_GETXATTR
#undef HAVE_FGETXATTR
#undef HAVE_SETXATTR
#undef HAVE_FSETXATTR
#undef HAVE_REMOVEXATTR
#undef HAVE_FREMOVEXATTR
#endif /* __APPLE__ */

#ifdef STUPID_ALPHA_HACK
#define SEND_STAT(a,b,c) send_stat(a,b,c)
#define SEND_STAT64(a,b,c) send_stat64(a,b,c)
#define SEND_GET_STAT(a,b) send_get_stat(a,b)
#define SEND_GET_STAT64(a,b) send_get_stat64(a,b)
#define SEND_GET_XATTR64(a,b,c) send_get_xattr64(a,b,c)
#else
#define SEND_STAT(a,b,c) send_stat(a,b)
#define SEND_STAT64(a,b,c) send_stat64(a,b)
#define SEND_GET_STAT(a,b) send_get_stat(a)
#define SEND_GET_STAT64(a,b) send_get_stat64(a)
#define SEND_GET_XATTR64(a,b,c) send_get_xattr64(a,b)
#endif

/*
   These INT_* (which stands for internal) macros should always be used when
   the fakeroot library owns the storage of the stat variable.
*/
#ifdef STAT64_SUPPORT
#define INT_STRUCT_STAT struct stat64
#define INT_NEXT_STAT(a,b) NEXT_STAT64(_STAT_VER,a,b)
#define INT_NEXT_LSTAT(a,b) NEXT_LSTAT64(_STAT_VER,a,b)
#define INT_NEXT_FSTAT(a,b) NEXT_FSTAT64(_STAT_VER,a,b)
#define INT_NEXT_FSTATAT(a,b,c,d) NEXT_FSTATAT64(_STAT_VER,a,b,c,d)
#define INT_SEND_STAT(a,b) SEND_STAT64(a,b,_STAT_VER)
#define INT_SEND_GET_XATTR(a,b) SEND_GET_XATTR64(a,b,_STAT_VER)
#else
#define INT_STRUCT_STAT struct stat
#define INT_NEXT_STAT(a,b) NEXT_STAT(_STAT_VER,a,b)
#define INT_NEXT_LSTAT(a,b) NEXT_LSTAT(_STAT_VER,a,b)
#define INT_NEXT_FSTAT(a,b) NEXT_FSTAT(_STAT_VER,a,b)
#define INT_NEXT_FSTATAT(a,b,c,d) NEXT_FSTATAT(_STAT_VER,a,b,c,d)
#define INT_SEND_STAT(a,b) SEND_STAT(a,b,_STAT_VER)
#define INT_SEND_GET_XATTR(a,b) SEND_GET_XATTR(a,b,_STAT_VER)
#endif

#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <dlfcn.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
#ifdef HAVE_SYS_ACL_H
#include <sys/acl.h>
#endif /* HAVE_SYS_ACL_H */
#ifdef HAVE_SYS_CAPABILITY_H
#include <sys/capability.h>
#endif
#if HAVE_FTS_H
#include <fts.h>
#endif /* HAVE_FTS_H */
#ifdef __sun
#include <sys/systeminfo.h>
#endif
#ifdef __APPLE__
#include <paths.h>
#include <sys/stat.h>
#include <crt_externs.h>
#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
#include <spawn.h>
#endif
#ifndef va_copy
#define va_copy(dest,src) ((dest)=(src))
#endif
#endif /* __APPLE__ */

#if !HAVE_DECL_SETENV
extern int setenv (const char *name, const char *value, int replace);
#endif
#if !HAVE_DECL_UNSETENV
extern int unsetenv (const char *name);
#endif


/*
   Where are those shared libraries?
   If I knew of a configure/libtool way to find that out, I'd use it. Or
   any other way other than the method I'm using below. Does anybody know
   how I can get that location? (BTW, symply linking a programme, and running
   `ldd' on it isn't the option, as Digital Unix doesn't have ldd)
*/


/*
   Note that LIBCPATH isn't actually used on Linux or Solaris, as RTLD_NEXT
   is defined and we use that to get the `next_*' functions

   Linux:
*/

/* OSF1 :*/
/*#define LIBCPATH "/usr/shlib/libc.so"*/

#undef __xstat
#undef __fxstat
#undef __lxstat
#undef __xstat64
#undef __fxstat64
#undef __lxstat64
#undef _FILE_OFFSET_BITS

/*
// next_wrap_st:
// this structure is used in next_wrap, which is defined in
// wrapstruct.h, included below
*/

struct next_wrap_st{
  void **doit;
  char *name;
};

void *get_libc(){

#ifndef RTLD_NEXT
 void *lib=0;
 if(!lib){
   lib= dlopen(LIBCPATH,RTLD_LAZY);
 }
 if (NULL==lib) {
   fprintf(stderr, "Couldn't find libc at: %s\n", LIBCPATH);
   abort();
 }
 return lib;
#else
  return RTLD_NEXT;
#endif
}
void load_library_symbols(void);

int fakeroot_disabled = 0;
#ifdef LIBFAKEROOT_DEBUGGING
int fakeroot_debug = 0;
#endif /* LIBFAKEROOT_DEBUGGING */

#ifdef __APPLE__
#include "patchattr.h"
#endif
#include "wrapped.h"
#include "wraptmpf.h"
#include "wrapdef.h"
#include "wrapstruct.h"


void load_library_symbols(void){
  /* this function loads all original functions from the C library.
     This function is only called once.
     I ran into problems when  each function individually
     loaded it's original counterpart, as RTLD_NEXT seems to have
     a different meaning in files with different names than libtricks.c
     (I.E, dlsym(RTLD_NEXT, ...) called in vsearch.c returned funtions
     defined in libtricks */
  /* The calling of this function itself is somewhat tricky:
     the awk script wrapawk generates several .h files. In wraptmpf.h
     there are temporary definitions for tmp_*, that do the call
     to this function. The other generated .h files do even more tricky
     things :) */

  int i;
  const char *msg;

#ifdef LIBFAKEROOT_DEBUGGING
  if (getenv("FAKEROOT_DEBUG")) {
    fakeroot_debug=1;
  }
  if (fakeroot_debug) {
    fprintf(stderr, "load_library_symbols\n");
  }

#endif /* LIBFAKEROOT_DEBUGGING */
  for(i=0; next_wrap[i].doit; i++){
 /* clear dlerror() just in case dlsym() legitimately returns NULL */
    msg = dlerror();
    *(next_wrap[i].doit)=dlsym(get_libc(), next_wrap[i].name);
    if ( (msg = dlerror()) != NULL){
      fprintf (stderr, "dlsym(%s): %s\n", next_wrap[i].name, msg);
/*    abort ();*/
    }
  }
}


/*
 * Fake implementations for the setuid family of functions.
 * The fake IDs are inherited by child processes via environment variables.
 *
 * Issues:
 *   o Privileges are not checked, which results in incorrect behaviour.
 *     Example: process changes its (real, effective and saved) uid to 1000
 *     and then tries to regain root privileges.  This should normally result
 *     in an EPERM, but our implementation doesn't care...
 *   o If one of the setenv calls fails, the state may get corrupted.
 *   o Not thread-safe.
 */


/* Generic set/get ID functions */

static int env_get_id(const char *key) {
  char *str = getenv(key);
  if (str)
    return atoi(str);
  return 0;
}

static int env_set_id(const char *key, int id) {
  if (id == 0) {
    unsetenv(key);
    return 0;
  } else {
    char str[12];
    snprintf(str, sizeof (str), "%d", id);
    return setenv(key, str, 1);
  }
}

static void read_id(unsigned int *id, const char *key) {
  if (*id == (unsigned int)-1)
    *id = env_get_id(key);
}

static int write_id(const char *key, int id) {
  if (env_get_id(key) != id)
    return env_set_id(key, id);
  return 0;
}

/* Fake ID storage */

static uid_t faked_real_uid = (uid_t)-1;
static gid_t faked_real_gid = (gid_t)-1;
static uid_t faked_effective_uid = (uid_t)-1;
static gid_t faked_effective_gid = (gid_t)-1;
static uid_t faked_saved_uid = (uid_t)-1;
static gid_t faked_saved_gid = (gid_t)-1;
static uid_t faked_fs_uid = (uid_t)-1;
static gid_t faked_fs_gid = (gid_t)-1;

/* Read user ID */

static void read_real_uid() {
  read_id(&faked_real_uid, FAKEROOTUID_ENV);
}

static void read_effective_uid() {
  read_id(&faked_effective_uid, FAKEROOTEUID_ENV);
}

static void read_saved_uid() {
  read_id(&faked_saved_uid, FAKEROOTSUID_ENV);
}

static void read_fs_uid() {
  read_id(&faked_fs_uid, FAKEROOTFUID_ENV);
}

static void read_uids() {
  read_real_uid();
  read_effective_uid();
  read_saved_uid();
  read_fs_uid();
}

/* Read group ID */

static void read_real_gid() {
  read_id(&faked_real_gid, FAKEROOTGID_ENV);
}

static void read_effective_gid() {
  read_id(&faked_effective_gid, FAKEROOTEGID_ENV);
}

static void read_saved_gid() {
  read_id(&faked_saved_gid, FAKEROOTSGID_ENV);
}

static void read_fs_gid() {
  read_id(&faked_fs_gid, FAKEROOTFGID_ENV);
}

static void read_gids() {
  read_real_gid();
  read_effective_gid();
  read_saved_gid();
  read_fs_gid();
}

/* Write user ID */

static int write_real_uid() {
  return write_id(FAKEROOTUID_ENV, faked_real_uid);
}

static int write_effective_uid() {
  return write_id(FAKEROOTEUID_ENV, faked_effective_uid);
}

static int write_saved_uid() {
  return write_id(FAKEROOTSUID_ENV, faked_saved_uid);
}

static int write_fs_uid() {
  return write_id(FAKEROOTFUID_ENV, faked_fs_uid);
}

static int write_uids() {
  if (write_real_uid() < 0)
    return -1;
  if (write_effective_uid() < 0)
    return -1;
  if (write_saved_uid() < 0)
    return -1;
  if (write_fs_uid() < 0)
    return -1;
  return 0;
}

/* Write group ID */

static int write_real_gid() {
  return write_id(FAKEROOTGID_ENV, faked_real_gid);
}

static int write_effective_gid() {
  return write_id(FAKEROOTEGID_ENV, faked_effective_gid);
}

static int write_saved_gid() {
  return write_id(FAKEROOTSGID_ENV, faked_saved_gid);
}

static int write_fs_gid() {
  return write_id(FAKEROOTFGID_ENV, faked_fs_gid);
}

static int write_gids() {
  if (write_real_gid() < 0)
    return -1;
  if (write_effective_gid() < 0)
    return -1;
  if (write_saved_gid() < 0)
    return -1;
  if (write_fs_gid() < 0)
    return -1;
  return 0;
}

/* Faked get functions */

static uid_t get_faked_uid() {
  read_real_uid();
  return faked_real_uid;
}

static gid_t get_faked_gid() {
  read_real_gid();
  return faked_real_gid;
}

static uid_t get_faked_euid() {
  read_effective_uid();
  return faked_effective_uid;
}

static gid_t get_faked_egid() {
  read_effective_gid();
  return faked_effective_gid;
}

static uid_t get_faked_suid() {
  read_saved_uid();
  return faked_saved_uid;
}

static gid_t get_faked_sgid() {
  read_saved_gid();
  return faked_saved_gid;
}

static uid_t get_faked_fsuid() {
  read_fs_uid();
  return faked_fs_uid;
}

static gid_t get_faked_fsgid() {
  read_fs_gid();
  return faked_fs_gid;
}

/* Faked set functions */

static int set_faked_uid(uid_t uid) {
  read_uids();
  if (faked_effective_uid == 0) {
    faked_real_uid = uid;
    faked_effective_uid = uid;
    faked_saved_uid = uid;
  } else {
    faked_effective_uid = uid;
  }
  faked_fs_uid = uid;
  return write_uids();
}

static int set_faked_gid(gid_t gid) {
  read_gids();
  if (faked_effective_gid == 0) {
    faked_real_gid = gid;
    faked_effective_gid = gid;
    faked_saved_gid = gid;
  } else {
    faked_effective_gid = gid;
  }
  faked_fs_gid = gid;
  return write_gids();
}

static int set_faked_euid(uid_t euid) {
  read_effective_uid();
  faked_effective_uid = euid;
  read_fs_uid();
  faked_fs_uid = euid;
  if (write_effective_uid() < 0)
    return -1;
  if (write_fs_uid() < 0)
    return -1;
  return 0;
}

static int set_faked_egid(gid_t egid) {
  read_effective_gid();
  faked_effective_gid = egid;
  read_fs_gid();
  faked_fs_gid = egid;
  if (write_effective_gid() < 0)
    return -1;
  if (write_fs_gid() < 0)
    return -1;
  return 0;
}

static_nonapple int set_faked_reuid(uid_t ruid, uid_t euid) {
  read_uids();
  if (ruid != (uid_t)-1 || euid != (uid_t)-1)
    faked_saved_uid = faked_effective_uid;
  if (ruid != (uid_t)-1)
    faked_real_uid = ruid;
  if (euid != (uid_t)-1)
    faked_effective_uid = euid;
  faked_fs_uid = faked_effective_uid;
  return write_uids();
}

static_nonapple int set_faked_regid(gid_t rgid, gid_t egid) {
  read_gids();
  if (rgid != (gid_t)-1 || egid != (gid_t)-1)
    faked_saved_gid = faked_effective_gid;
  if (rgid != (gid_t)-1)
    faked_real_gid = rgid;
  if (egid != (gid_t)-1)
    faked_effective_gid = egid;
  faked_fs_gid = faked_effective_gid;
  return write_gids();
}

#ifdef HAVE_SETRESUID
static int set_faked_resuid(uid_t ruid, uid_t euid, uid_t suid) {
  read_uids();
  if (ruid != (uid_t)-1)
    faked_real_uid = ruid;
  if (euid != (uid_t)-1)
    faked_effective_uid = euid;
  if (suid != (uid_t)-1)
    faked_saved_uid = suid;
  faked_fs_uid = faked_effective_uid;
  return write_uids();
}
#endif

#ifdef HAVE_SETRESGID
static int set_faked_resgid(gid_t rgid, gid_t egid, gid_t sgid) {
  read_gids();
  if (rgid != (gid_t)-1)
    faked_real_gid = rgid;
  if (egid != (gid_t)-1)
    faked_effective_gid = egid;
  if (sgid != (gid_t)-1)
    faked_saved_gid = sgid;
  faked_fs_gid = faked_effective_gid;
  return write_gids();
}
#endif

#ifdef HAVE_SETFSUID
static uid_t set_faked_fsuid(uid_t fsuid) {
  uid_t prev_fsuid = get_faked_fsuid();
  faked_fs_uid = fsuid;
  return prev_fsuid;
}
#endif

#ifdef HAVE_SETFSGID
static gid_t set_faked_fsgid(gid_t fsgid) {
  gid_t prev_fsgid = get_faked_fsgid();
  faked_fs_gid = fsgid;
  return prev_fsgid;
}
#endif


static_nonapple int dont_try_chown(){
  static int inited=0;
  static int donttry;

  if(!inited){
    donttry=(env_var_set(FAKEROOTDONTTRYCHOWN_ENV)!=NULL);
    inited=1;
  }
  return donttry;
}


/* The wrapped functions */


int WRAP_LSTAT LSTAT_ARG(int ver,
		       const char *file_name,
		       struct stat *statbuf){

  int r;

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "lstat file_name %s\n", file_name);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=NEXT_LSTAT(ver, file_name, statbuf);
  if(r)
    return -1;
  SEND_GET_STAT(statbuf, ver);
  return 0;
}


int WRAP_STAT STAT_ARG(int ver,
		       const char *file_name,
		       struct stat *st){
  int r;

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "stat file_name %s\n", file_name);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=NEXT_STAT(ver, file_name, st);
  if(r)
    return -1;
  SEND_GET_STAT(st,ver);
  return 0;
}


int WRAP_FSTAT FSTAT_ARG(int ver,
			int fd,
			struct stat *st){


  int r;

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "fstat fd %d\n", fd);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=NEXT_FSTAT(ver, fd, st);
  if(r)
    return -1;
  SEND_GET_STAT(st,ver);
  return 0;
}

#ifdef HAVE_FSTATAT
int WRAP_FSTATAT FSTATAT_ARG(int ver,
			     int dir_fd,
			     const char *path,
			     struct stat *st,
			     int flags){


  int r;

  r=NEXT_FSTATAT(ver, dir_fd, path, st, flags);
  if(r)
    return -1;
  SEND_GET_STAT(st,ver);
  return 0;
}
#endif /* HAVE_FSTATAT */

#ifdef STAT64_SUPPORT

int WRAP_LSTAT64 LSTAT64_ARG (int ver,
			   const char *file_name,
			   struct stat64 *st){

  int r;

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "lstat64 file_name %s\n", file_name);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=NEXT_LSTAT64(ver, file_name, st);

  if(r)
    return -1;

  SEND_GET_STAT64(st,ver);
  return 0;
}


int WRAP_STAT64 STAT64_ARG(int ver,
			   const char *file_name,
			   struct stat64 *st){
  int r;

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "stat64 file_name %s\n", file_name);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=NEXT_STAT64(ver,file_name,st);
  if(r)
    return -1;
  SEND_GET_STAT64(st,ver);
  return 0;
}


int WRAP_FSTAT64 FSTAT64_ARG(int ver,
			     int fd,
			     struct stat64 *st){
  int r;

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "fstat64 fd %d\n", fd);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=NEXT_FSTAT64(ver, fd, st);
  if(r)
    return -1;
  SEND_GET_STAT64(st,ver);

  return 0;
}

#ifdef HAVE_FSTATAT
int WRAP_FSTATAT64 FSTATAT64_ARG(int ver,
				 int dir_fd,
				 const char *path,
				 struct stat64 *st,
				 int flags){


  int r;

  r=NEXT_FSTATAT64(ver, dir_fd, path, st, flags);
  if(r)
    return -1;
  SEND_GET_STAT64(st,ver);
  return 0;
}
#endif /* HAVE_FSTATAT */

#endif /* STAT64_SUPPORT */

/*************************************************************/
/*
  Wrapped functions general info:

  In general, the structure is as follows:
    - Then, if the function does things that (possibly) fail by
      other users than root, allow for `fake' root privileges.
      Do this by obtaining the inode the function works on, and then
      informing faked (the deamon that remembers all `fake' file
      permissions e.d.) about the intentions of the user.
      Faked maintains a list of inodes and their respective
      `fake' ownerships/filemodes.
    - Or, if the function requests information that we should
      fake, again get the inode of the file, and ask faked about the
      ownership/filemode data it maintains for that inode.

*/
/*************************************************************/



/* chown, lchown, fchown, chmod, fchmod, mknod functions

   quite general. See the `Wrapped functions general info:' above
   for more info.
 */

int chown(const char *path, uid_t owner, gid_t group){
  INT_STRUCT_STAT st;
  int r=0;


#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "chown path %s owner %d group %d\n", path, owner, group);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
#ifdef LCHOWN_SUPPORT
  /*chown(sym-link) works on the target of the symlink if lchown is
    present and enabled.*/
  r=INT_NEXT_STAT(path, &st);
#else
  /*chown(sym-link) works on the symlink itself, use lstat: */
  r=INT_NEXT_LSTAT(path, &st);
#endif

  if(r)
    return r;
  st.st_uid=owner;
  st.st_gid=group;
  INT_SEND_STAT(&st,chown_func);
  if(!dont_try_chown())
    r=next_lchown(path,owner,group);
  else
    r=0;
  if(r&&(errno==EPERM))
    r=0;

  return r;
}


#ifdef LCHOWN_SUPPORT
int lchown(const char *path, uid_t owner, gid_t group){
  INT_STRUCT_STAT st;
  int r=0;

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "lchown path %s owner %d group %d\n", path, owner, group);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=INT_NEXT_LSTAT(path, &st);
  if(r)
    return r;
  st.st_uid=owner;
  st.st_gid=group;
  INT_SEND_STAT(&st,chown_func);
  if(!dont_try_chown())
    r=next_lchown(path,owner,group);
  else
    r=0;
  if(r&&(errno==EPERM))
    r=0;

  return r;
}
#endif

int fchown(int fd, uid_t owner, gid_t group){
  INT_STRUCT_STAT st;
  int r;

  r=INT_NEXT_FSTAT(fd, &st);
  if(r)
    return r;

  st.st_uid=owner;
  st.st_gid=group;
  INT_SEND_STAT(&st, chown_func);

  if(!dont_try_chown())
    r=next_fchown(fd,owner,group);
  else
    r=0;

  if(r&&(errno==EPERM))
    r=0;

  return r;
}

#ifdef HAVE_FSTATAT
#ifdef HAVE_FCHOWNAT
int fchownat(int dir_fd, const char *path, uid_t owner, gid_t group, int flags) {
  int r;
  /* If AT_SYMLINK_NOFOLLOW is set in the fchownat call it should
     be when we stat it. */
  INT_STRUCT_STAT st;
  r=INT_NEXT_FSTATAT(dir_fd, path, &st, (flags & AT_SYMLINK_NOFOLLOW));

  if(r)
    return(r);

  st.st_uid=owner;
  st.st_gid=group;
  INT_SEND_STAT(&st,chown_func);

  if(!dont_try_chown())
    r=next_fchownat(dir_fd,path,owner,group,flags);
  else
    r=0;

  if(r&&(errno==EPERM))
    r=0;

  return r;
}
#endif /* HAVE_FCHOWNAT */
#endif /* HAVE_FSTATAT */

int chmod(const char *path, mode_t mode){
  INT_STRUCT_STAT st;
  int r;

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "chmod path %s\n", path);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=INT_NEXT_STAT(path, &st);
  if(r)
    return r;

  st.st_mode=(mode&ALLPERMS)|(st.st_mode&~ALLPERMS);

  INT_SEND_STAT(&st, chmod_func);

  /* if a file is unwritable, then root can still write to it
     (no matter who owns the file). If we are fakeroot, the only
     way to fake this is to always make the file writable, readable
     etc for the real user (who started fakeroot). Also holds for
     the exec bit of directories.
     Yes, packages requering that are broken. But we have lintian
     to get rid of broken packages, not fakeroot.
  */
  mode |= 0600;
  if(S_ISDIR(st.st_mode))
    mode |= 0100;

  r=next_chmod(path, mode);
  if(r&&(errno==EPERM))
    r=0;
#ifdef EFTYPE		/* available under FreeBSD kernel */
  if(r&&(errno==EFTYPE))
    r=0;
#endif
  return r;
}

#ifdef HAVE_LCHMOD
int lchmod(const char *path, mode_t mode){
  INT_STRUCT_STAT st;
  int r;

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "lchmod path %s\n", path);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=INT_NEXT_LSTAT(path, &st);
  if(r)
    return r;

  st.st_mode=(mode&ALLPERMS)|(st.st_mode&~ALLPERMS);

  INT_SEND_STAT(&st, chmod_func);

  /* see chmod() for comment */
  mode |= 0600;
  if(S_ISDIR(st.st_mode))
    mode |= 0100;

  r=next_lchmod(path, mode);
  if(r&&(errno==EPERM))
    r=0;
#ifdef EFTYPE		/* available under FreeBSD kernel */
  if(r&&(errno==EFTYPE))
    r=0;
#endif
  return r;
}
#endif

int fchmod(int fd, mode_t mode){
  int r;
  INT_STRUCT_STAT st;


#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "fchmod fd %d\n", fd);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=INT_NEXT_FSTAT(fd, &st);

  if(r)
    return(r);

  st.st_mode=(mode&ALLPERMS)|(st.st_mode&~ALLPERMS);
  INT_SEND_STAT(&st,chmod_func);

  /* see chmod() for comment */
  mode |= 0600;
  if(S_ISDIR(st.st_mode))
    mode |= 0100;

  r=next_fchmod(fd, mode);
  if(r&&(errno==EPERM))
    r=0;
#ifdef EFTYPE		/* available under FreeBSD kernel */
  if(r&&(errno==EFTYPE))
    r=0;
#endif
  return r;
}

#ifdef HAVE_FSTATAT
#ifdef HAVE_FCHMODAT
int fchmodat(int dir_fd, const char *path, mode_t mode, int flags) {
/*   (int fd, mode_t mode){*/
  int r;
  INT_STRUCT_STAT st;

  /* If AT_SYMLINK_NOFOLLOW is set in the fchownat call it should
     be when we stat it. */
  r=INT_NEXT_FSTATAT(dir_fd, path, &st, flags & AT_SYMLINK_NOFOLLOW);

  if(r)
    return(r);

  st.st_mode=(mode&ALLPERMS)|(st.st_mode&~ALLPERMS);
  INT_SEND_STAT(&st,chmod_func);

  /* see chmod() for comment */
  mode |= 0600;
  if(S_ISDIR(st.st_mode))
    mode |= 0100;

  r=next_fchmodat(dir_fd, path, mode, flags);
  if(r&&(errno==EPERM))
    r=0;
#ifdef EFTYPE		/* available under FreeBSD kernel */
  if(r&&(errno==EFTYPE))
    r=0;
#endif
  return r;
}
#endif /* HAVE_FCHMODAT */
#endif /* HAVE_FSTATAT */

int WRAP_MKNOD MKNOD_ARG(int ver UNUSED,
			 const char *pathname,
			 mode_t mode, dev_t XMKNOD_FRTH_ARG dev)
{
  INT_STRUCT_STAT st;
  mode_t old_mask=umask(022);
  int fd,r;

  umask(old_mask);

  /*Don't bother to mknod the file, that probably doesn't work.
    just create it as normal file, and leave the premissions
    to the fakemode.*/

  fd=open(pathname, O_WRONLY|O_CREAT|O_TRUNC, 00644);

  if(fd==-1)
    return -1;

  close(fd);
  /* get the inode, to communicate with faked */

  r=INT_NEXT_LSTAT(pathname, &st);

  if(r)
    return -1;

  st.st_mode= mode & ~old_mask;
  st.st_rdev= XMKNOD_FRTH_ARG dev;

  INT_SEND_STAT(&st,mknod_func);

  return 0;
}

#ifdef HAVE_FSTATAT
#ifdef HAVE_MKNODAT
int WRAP_MKNODAT MKNODAT_ARG(int ver UNUSED,
			     int dir_fd,
			     const char *pathname,
			     mode_t mode, dev_t XMKNODAT_FIFTH_ARG dev)
{
  INT_STRUCT_STAT st;
  mode_t old_mask=umask(022);
  int fd,r;

  umask(old_mask);

  /*Don't bother to mknod the file, that probably doesn't work.
    just create it as normal file, and leave the permissions
    to the fakemode.*/

  fd=openat(dir_fd, pathname, O_WRONLY|O_CREAT|O_TRUNC, 00644);

  if(fd==-1)
    return -1;

  close(fd);
  /* get the inode, to communicate with faked */

  /* The only known flag is AT_SYMLINK_NOFOLLOW and
     we don't want that here. */
  r=INT_NEXT_FSTATAT(dir_fd, pathname, &st, 0);

  if(r)
    return -1;

  st.st_mode= mode & ~old_mask;
  st.st_rdev= XMKNODAT_FIFTH_ARG dev;

  INT_SEND_STAT(&st,mknod_func);

  return 0;
}
#endif /* HAVE_MKNODAT */
#endif /* HAVE_FSTATAT */

int mkdir(const char *path, mode_t mode){
  INT_STRUCT_STAT st;
  int r;
  mode_t old_mask=umask(022);

  umask(old_mask);


  /* we need to tell the fake deamon the real mode. In order
     to communicate with faked we need a struct stat, so we now
     do a stat of the new directory (just for the inode/dev) */

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "mkdir path %s\n", path);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=next_mkdir(path, mode|0700);
  /* mode|0700: see comment in the chown() function above */
  if(r)
    return -1;
  r=INT_NEXT_STAT(path, &st);

  if(r)
    return -1;

  st.st_mode=(mode&~old_mask&ALLPERMS)|(st.st_mode&~ALLPERMS)|S_IFDIR;

  INT_SEND_STAT(&st, chmod_func);

  return 0;
}

#ifdef HAVE_FSTATAT
#ifdef HAVE_MKDIRAT
int mkdirat(int dir_fd, const char *path, mode_t mode){
  INT_STRUCT_STAT st;
  int r;
  mode_t old_mask=umask(022);

  umask(old_mask);


  /* we need to tell the fake deamon the real mode. In order
     to communicate with faked we need a struct stat, so we now
     do a stat of the new directory (just for the inode/dev) */

  r=next_mkdirat(dir_fd, path, mode|0700);
  /* mode|0700: see comment in the chown() function above */
  if(r)
    return -1;
  r=INT_NEXT_FSTATAT(dir_fd, path, &st, 0);

  if(r)
    return -1;

  st.st_mode=(mode&~old_mask&ALLPERMS)|(st.st_mode&~ALLPERMS)|S_IFDIR;

  INT_SEND_STAT(&st, chmod_func);

  return 0;
}
#endif /* HAVE_MKDIRAT */
#endif /* HAVE_FSTATAT */

/*
   The remove funtions: unlink, rmdir, rename.
   These functions can all remove inodes from the system.
   I need to inform faked about the removal of these inodes because
   of the following:
    # rm -f file
    # touch file
    # chown admin file
    # rm file
    # touch file
   In the above example, assuming that for both touch-es, the same
   inode is generated, faked will still report the owner of `file'
   as `admin', unless it's informed about the removal of the inode.
*/

int unlink(const char *pathname){
  int r;
  INT_STRUCT_STAT st;


  r=INT_NEXT_LSTAT(pathname, &st);
  if(r)
    return -1;

  r=next_unlink(pathname);

  if(r)
    return -1;

  INT_SEND_STAT(&st, unlink_func);

  return 0;
}

#ifdef HAVE_FSTATAT
#ifdef HAVE_UNLINKAT
int unlinkat(int dir_fd, const char *pathname, int flags){
  int r;
  INT_STRUCT_STAT st;
  r=INT_NEXT_FSTATAT(dir_fd, pathname, &st, (flags&~AT_REMOVEDIR) | AT_SYMLINK_NOFOLLOW);
  if(r)
    return -1;

  r=next_unlinkat(dir_fd, pathname, flags);

  if(r)
    return -1;

  INT_SEND_STAT(&st, unlink_func);

  return 0;
}
#endif /* HAVE_UNLINKAT */
#endif /* HAVE_FSTATAT */

/*
  See the `remove funtions:' comments above for more info on
  these remove function wrappers.
*/
int rmdir(const char *pathname){
  int r;
  INT_STRUCT_STAT st;

  r=INT_NEXT_LSTAT(pathname, &st);
  if(r)
    return -1;
  r=next_rmdir(pathname);
  if(r)
    return -1;

  INT_SEND_STAT(&st,unlink_func);

  return 0;
}

/*
  See the `remove funtions:' comments above for more info on
  these remove function wrappers.
*/
int remove(const char *pathname){
  int r;
  INT_STRUCT_STAT st;

  r=INT_NEXT_LSTAT(pathname, &st);
  if(r)
    return -1;
  r=next_remove(pathname);
  if(r)
    return -1;
  INT_SEND_STAT(&st,unlink_func);

  return r;
}

/*
  if the second argument to the rename() call points to an
  existing file, then that file will be removed. So, we have
  to treat this function as one of the `remove functions'.

  See the `remove funtions:' comments above for more info on
  these remove function wrappers.
*/

int rename(const char *oldpath, const char *newpath){
  int r,s;
  INT_STRUCT_STAT st;

  /* If newpath points to an existing file, that file will be
     unlinked.   Make sure we tell the faked daemon about this! */

  /* we need the st_new struct in order to inform faked about the
     (possible) unlink of the file */

  r=INT_NEXT_LSTAT(newpath, &st);

  s=next_rename(oldpath, newpath);
  if(s)
    return -1;
  if(!r)
    INT_SEND_STAT(&st,unlink_func);

  return 0;
}

#ifdef HAVE_FSTATAT
#ifdef HAVE_RENAMEAT
int renameat(int olddir_fd, const char *oldpath,
             int newdir_fd, const char *newpath){
  int r,s;
  INT_STRUCT_STAT st;

  /* If newpath points to an existing file, that file will be
     unlinked.   Make sure we tell the faked daemon about this! */

  /* we need the st_new struct in order to inform faked about the
     (possible) unlink of the file */

  r=INT_NEXT_FSTATAT(newdir_fd, newpath, &st, AT_SYMLINK_NOFOLLOW);

  s=next_renameat(olddir_fd, oldpath, newdir_fd, newpath);
  if(s)
    return -1;
  if(!r)
    INT_SEND_STAT(&st,unlink_func);

  return 0;
}
#endif /* HAVE_RENAMEAT */
#endif /* HAVE_FSTATAT */


#ifdef FAKEROOT_FAKENET
pid_t fork(void)
{
  pid_t pid;

  pid = next_fork();

  if (pid == 0) {
    /* No need to lock in the child process. */
    if (comm_sd >= 0) {
      next_close(comm_sd);
      comm_sd = -1;
    }
  }

  return pid;
}

pid_t vfork(void)
{
  /* We can't wrap vfork(2) without breaking everything... */
  return fork();
}

/* Return an error when trying to close the comm_sd file descriptor
   (pretend that it's closed). */
int close(int fd)
{
  int retval, reterr;

  lock_comm_sd();

  if (comm_sd >= 0 && comm_sd == fd) {
    retval = -1;
    reterr = EBADF;
  } else {
    retval = next_close(fd);
    reterr = errno;
  }

  unlock_comm_sd();

  errno = reterr;
  return retval;
}

int dup2(int oldfd, int newfd)
{
  int retval, reterr;

  lock_comm_sd();

  if (comm_sd >= 0 && comm_sd == newfd) {
    /* If dup fails, comm_sd gets set to -1, which is fine. */
    comm_sd = dup(newfd);
    next_close(newfd);
  }

  retval = next_dup2(oldfd, newfd);
  reterr = errno;

  unlock_comm_sd();

  errno = reterr;
  return retval;
}
#endif /* FAKEROOT_FAKENET */

#ifdef __APPLE__
#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6

static int check_fakeroot_disabled(void *retaddr){
  Dl_info info;
  const char *suffix;
  if (fakeroot_disabled || !dladdr(retaddr, &info))
    return fakeroot_disabled;
  suffix = strrchr(info.dli_fname, '/');
  if (suffix && (strcmp(suffix, "/CarbonCore") == 0 ||
                 strcmp(suffix, "/CoreServicesInternal") == 0))
    return 1;
  return fakeroot_disabled;
}

#define fakeroot_disabled check_fakeroot_disabled(__builtin_return_address(0))

#endif
#endif /* __APPLE__ */

uid_t getuid(void){
  if (fakeroot_disabled)
    return next_getuid();
  return get_faked_uid();
}

uid_t geteuid(void){
  if (fakeroot_disabled)
    return next_geteuid();
  return get_faked_euid();
}

#ifdef HAVE_GETRESUID
int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid){
  if (fakeroot_disabled)
    return next_getresuid(ruid, euid, suid);
  *ruid = get_faked_uid();
  *euid = get_faked_euid();
  *suid = get_faked_suid();
  return 0;
}
#endif /* HAVE_GETRESUID */

uid_t getgid(void){
  if (fakeroot_disabled)
    return next_getgid();
  return get_faked_gid();
}

uid_t getegid(void){
  if (fakeroot_disabled)
    return next_getegid();
  return get_faked_egid();
}

#ifdef HAVE_GETRESGID
int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid){
  if (fakeroot_disabled)
    return next_getresgid(rgid, egid, sgid);
  *rgid = get_faked_gid();
  *egid = get_faked_egid();
  *sgid = get_faked_sgid();
  return 0;
}
#endif /* HAVE_GETRESGID */

int setuid(uid_t id){
  if (fakeroot_disabled)
    return next_setuid(id);
  return set_faked_uid(id);
}

int setgid(uid_t id){
  if (fakeroot_disabled)
    return next_setgid(id);
  return set_faked_gid(id);
}

int seteuid(uid_t id){
  if (fakeroot_disabled)
    return next_seteuid(id);
  return set_faked_euid(id);
}

int setegid(uid_t id){
  if (fakeroot_disabled)
    return next_setegid(id);
  return set_faked_egid(id);
}

int setreuid(SETREUID_ARG ruid, SETREUID_ARG euid){
#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "setreuid\n");
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  if (fakeroot_disabled)
    return next_setreuid(ruid, euid);
  return set_faked_reuid(ruid, euid);
}

int setregid(SETREGID_ARG rgid, SETREGID_ARG egid){
#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "setregid\n");
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  if (fakeroot_disabled)
    return next_setregid(rgid, egid);
  return set_faked_regid(rgid, egid);
}

#ifdef HAVE_SETRESUID
int setresuid(uid_t ruid, uid_t euid, uid_t suid){
  if (fakeroot_disabled)
    return next_setresuid(ruid, euid, suid);
  return set_faked_resuid(ruid, euid, suid);
}
#endif /* HAVE_SETRESUID */

#ifdef HAVE_SETRESGID
int setresgid(gid_t rgid, gid_t egid, gid_t sgid){
  if (fakeroot_disabled)
    return next_setresgid(rgid, egid, sgid);
  return set_faked_resgid(rgid, egid, sgid);
}
#endif /* HAVE_SETRESGID */

#ifdef HAVE_SETFSUID
uid_t setfsuid(uid_t fsuid){
  if (fakeroot_disabled)
    return next_setfsuid(fsuid);
  return set_faked_fsuid(fsuid);
}
#endif /* HAVE_SETFSUID */

#ifdef HAVE_SETFSGID
gid_t setfsgid(gid_t fsgid){
  if (fakeroot_disabled)
    return next_setfsgid(fsgid);
  return set_faked_fsgid(fsgid);
}
#endif /* HAVE_SETFSGID */

int initgroups(const char* user, INITGROUPS_SECOND_ARG group){
  if (fakeroot_disabled)
    return next_initgroups(user, group);
  else
    return 0;
}

int setgroups(SETGROUPS_SIZE_TYPE size, const gid_t *list){
  if (fakeroot_disabled)
    return next_setgroups(size, list);
  else
    return 0;
}

#ifdef HAVE_CAPSET
int capset(cap_user_header_t hdrp, const cap_user_data_t datap)
{
  int rc = next_capset(hdrp, datap);
  return (fakeroot_disabled) ? (rc) : 0;
}
#endif /* HAVE_CAPSET */

#if defined(HAVE_SETXATTR) || defined(HAVE_LSETXATTR) || defined(HAVE_FSETXATTR)
static int common_setxattr(INT_STRUCT_STAT *st, const char *name, const void * value, size_t size, int flags)
{
  xattr_args xattr;
  xattr.name = name;
  xattr.value = value;
  xattr.size = size;
  xattr.flags = flags;
  xattr.func = setxattr_func;
  INT_SEND_GET_XATTR(st, &xattr);
  if (xattr.rc)
  {
    errno = xattr.rc;
    return -1;
  }
  return 0;
}
#endif /* defined(HAVE_SETXATTR) || defined(HAVE_LSETXATTR) || defined(HAVE_FSETXATTR) */

#if defined(HAVE_GETXATTR) || defined(HAVE_LGETXATTR) || defined(HAVE_FGETXATTR)
static size_t common_getxattr(INT_STRUCT_STAT *st, const char *name, void * value, size_t size)
{
  xattr_args xattr;
  xattr.name = name;
  xattr.value = value;
  xattr.size = size;
  xattr.func = getxattr_func;
  INT_SEND_GET_XATTR(st, &xattr);
  if (xattr.rc)
  {
    errno = xattr.rc;
    return -1;
  }
  return xattr.size;
}
#endif /* defined(HAVE_GETXATTR) || defined(HAVE_LGETXATTR) || defined(HAVE_FGETXATTR) */

#if defined(HAVE_LISTXATTR) || defined(HAVE_LLISTXATTR) || defined(HAVE_FLISTXATTR)
static size_t common_listxattr(INT_STRUCT_STAT *st, char *list, size_t size)
{
  xattr_args xattr;
  xattr.name = NULL;
  xattr.value = list;
  xattr.size = size;
  xattr.func = listxattr_func;
  INT_SEND_GET_XATTR(st, &xattr);
  if (xattr.rc)
  {
    errno = xattr.rc;
    return -1;
  }
  return xattr.size;
}
#endif /* defined(HAVE_LISTXATTR) || defined(HAVE_LLISTXATTR) || defined(HAVE_FLISTXATTR) */

#if defined(HAVE_REMOVEXATTR) || defined(HAVE_LREMOVEXATTR) || defined(HAVE_FREMOVEXATTR)
static int common_removexattr(INT_STRUCT_STAT *st, const char *name)
{
  xattr_args xattr;
  xattr.name = name;
  xattr.value = NULL;
  xattr.size = 0;
  xattr.func = removexattr_func;
  INT_SEND_GET_XATTR(st, &xattr);
  if (xattr.rc)
  {
    errno = xattr.rc;
    return -1;
  }
  return 0;
}
#endif /* defined(HAVE_REMOVEXATTR) || defined(HAVE_LREMOVEXATTR) || defined(HAVE_FREMOVEXATTR) */

#ifdef HAVE_SETXATTR
int setxattr(const char *path, const char *name, const void *value, size_t size, int flags)
{
  INT_STRUCT_STAT st;
  int r;
  if (fakeroot_disabled)
    return next_setxattr(path, name, value, size, flags);

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "setxattr path %s\n", path);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=INT_NEXT_STAT(path, &st);
  if(r)
    return r;

  return common_setxattr(&st, name, value, size, flags);
}
#endif /* HAVE_SETXATTR */

#ifdef HAVE_LSETXATTR
int lsetxattr(const char *path, const char *name, const void *value, size_t size, int flags)
{
  INT_STRUCT_STAT st;
  int r;
  if (fakeroot_disabled)
    return next_lsetxattr(path, name, value, size, flags);

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "lsetxattr path %s\n", path);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=INT_NEXT_LSTAT(path, &st);
  if(r)
    return r;

  return common_setxattr(&st, name, value, size, flags);
}
#endif /* HAVE_LSETXATTR */

#ifdef HAVE_FSETXATTR
int fsetxattr(int fd, const char *name, const void *value, size_t size, int flags)
{
  INT_STRUCT_STAT st;
  int r;
  if (fakeroot_disabled)
    return next_fsetxattr(fd, name, value, size, flags);

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "fsetxattr fd %d\n", fd);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=INT_NEXT_FSTAT(fd, &st);
  if(r)
    return r;

  return common_setxattr(&st, name, value, size, flags);
}
#endif /* HAVE_FSETXATTR */

#ifdef HAVE_GETXATTR
ssize_t getxattr(const char *path, const char *name, void *value, size_t size)
{
  INT_STRUCT_STAT st;
  int r;
  if (fakeroot_disabled)
    return next_getxattr(path, name, value, size);

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "getxattr path %s name %s size %d\n", path, name, size);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=INT_NEXT_STAT(path, &st);
  if(r)
    return r;

  return common_getxattr(&st, name, value, size);
}
#endif /* HAVE_GETXATTR */

#ifdef HAVE_LGETXATTR
ssize_t lgetxattr(const char *path, const char *name, void *value, size_t size)
{
  INT_STRUCT_STAT st;
  int r;
  if (fakeroot_disabled)
    return next_lgetxattr(path, name, value, size);

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "lgetxattr path %s\n", path);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=INT_NEXT_LSTAT(path, &st);
  if(r)
    return r;

  return common_getxattr(&st, name, value, size);
}
#endif /* HAVE_LGETXATTR */

#ifdef HAVE_FGETXATTR
ssize_t fgetxattr(int fd, const char *name, void *value, size_t size)
{
  INT_STRUCT_STAT st;
  int r;
  if (fakeroot_disabled)
    return next_fgetxattr(fd, name, value, size);

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "fgetxattr fd %d\n", fd);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=INT_NEXT_FSTAT(fd, &st);
  if(r)
    return r;

  return common_getxattr(&st, name, value, size);
}
#endif /* HAVE_FGETXATTR */

#ifdef HAVE_LISTXATTR
ssize_t listxattr(const char *path, char *list, size_t size)
{
  INT_STRUCT_STAT st;
  int r;
  if (fakeroot_disabled)
    return next_listxattr(path, list, size);

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "listxattr path %s size %d\n", path, size);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=INT_NEXT_STAT(path, &st);
  if(r)
    return r;

  return common_listxattr(&st, list, size);
}
#endif /* HAVE_LISTXATTR */

#ifdef HAVE_LLISTXATTR
ssize_t llistxattr(const char *path, char *list, size_t size)
{
  INT_STRUCT_STAT st;
  int r;
  if (fakeroot_disabled)
    return next_llistxattr(path, list, size);

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "llistxattr path %s\n", path);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=INT_NEXT_LSTAT(path, &st);
  if(r)
    return r;

  return common_listxattr(&st, list, size);
}
#endif /* HAVE_LLISTXATTR */

#ifdef HAVE_FLISTXATTR
ssize_t flistxattr(int fd, char *list, size_t size)
{
  INT_STRUCT_STAT st;
  int r;
  if (fakeroot_disabled)
    return next_flistxattr(fd, list, size);

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "flistxattr fd %d\n", fd);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=INT_NEXT_FSTAT(fd, &st);
  if(r)
    return r;

  return common_listxattr(&st, list, size);
}
#endif /* HAVE_FLISTXATTR */

#ifdef HAVE_REMOVEXATTR
int removexattr(const char *path, const char *name)
{
  INT_STRUCT_STAT st;
  int r;
  if (fakeroot_disabled)
    return next_removexattr(path, name);

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "removexattr path %s\n", path);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=INT_NEXT_STAT(path, &st);
  if(r)
    return r;

  return common_removexattr(&st, name);
}
#endif /* HAVE_REMOVEXATTR */

#ifdef HAVE_LREMOVEXATTR
int lremovexattr(const char *path, const char *name)
{
  INT_STRUCT_STAT st;
  int r;
  if (fakeroot_disabled)
    return next_lremovexattr(path, name);

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "lremovexattr path %s\n", path);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=INT_NEXT_LSTAT(path, &st);
  if(r)
    return r;

  return common_removexattr(&st, name);
}
#endif /* HAVE_LREMOVEXATTR */

#ifdef HAVE_FREMOVEXATTR
int fremovexattr(int fd, const char *name)
{
  INT_STRUCT_STAT st;
  int r;
  if (fakeroot_disabled)
    return next_fremovexattr(fd, name);

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "fremovexattr fd %d\n", fd);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=INT_NEXT_FSTAT(fd, &st);
  if(r)
    return r;

  return common_removexattr(&st, name);
}
#endif /* HAVE_FREMOVEXATTR */

int setpriority(int which, int who, int prio){
  if (fakeroot_disabled)
    return next_setpriority(which, who, prio);
  next_setpriority(which, who, prio);
  return 0;
}

#undef fakeroot_disabled

int fakeroot_disable(int new)
{
  int old = fakeroot_disabled;
  fakeroot_disabled = new ? 1 : 0;
  return old;
}

int fakeroot_isdisabled(void)
{
  return fakeroot_disabled;
}

#ifdef HAVE_ACL_T
acl_t acl_get_fd(int fd) {
  errno = ENOTSUP;
  return (acl_t)NULL;
}
acl_t acl_get_file(const char *path_p, acl_type_t type) {
  errno = ENOTSUP;
  return (acl_t)NULL;
}
int acl_set_fd(int fd, acl_t acl) {
  errno = ENOTSUP;
  return -1;
}

int acl_set_file(const char *path_p, acl_type_t type, acl_t acl) {
  errno = ENOTSUP;
  return -1;
}
#endif /* HAVE_SYS_ACL_H */

#ifdef HAVE_FTS_READ
FTSENT *fts_read(FTS *ftsp) {
  FTSENT *r;

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "fts_read\n");
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=next_fts_read(ftsp);
  if (r && ((ftsp->fts_options & FTS_NOSTAT)
            || r->fts_info == FTS_NS || r->fts_info == FTS_NSOK))
    r->fts_statp = NULL;  /* Otherwise fts_statp may be a random pointer */
  if(r && r->fts_statp) {  /* Should we bother checking fts_info here? */
    SEND_GET_STAT(r->fts_statp, _STAT_VER);
  }

  return r;
}
#endif /* HAVE_FTS_READ */

#ifdef HAVE_FTS_CHILDREN
FTSENT *fts_children(FTS *ftsp, int options) {
  FTSENT *first, *r;

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "fts_children\n");
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  first=next_fts_children(ftsp, options);
  for(r = first; r; r = r->fts_link) {
    if(r && r->fts_statp) {  /* Should we bother checking fts_info here? */
      SEND_GET_STAT(r->fts_statp, _STAT_VER);
    }
  }

  return first;
}
#endif /* HAVE_FTS_CHILDREN */

#ifdef __APPLE__
#ifdef __LP64__
int
getattrlist(const char *path, void *attrList, void *attrBuf,
            size_t attrBufSize, unsigned int options)
#else
int
getattrlist(const char *path, void *attrList, void *attrBuf,
            size_t attrBufSize, unsigned long options)
#endif
{
  int r;
  struct stat st;

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "getattrlist path %s\n", path);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=next_getattrlist(path, attrList, attrBuf, attrBufSize, options);
  if (r) {
    return r;
  }
  if (options & FSOPT_NOFOLLOW) {
    r=WRAP_LSTAT(path, &st);
  } else {
    r=WRAP_STAT(path, &st);
  }
  if (r) {
    return r;
  }
  patchattr(attrList, attrBuf, st.st_uid, st.st_gid, st.st_mode);

  return 0;
}

#if HAVE_FGETATTRLIST
#ifdef __LP64__
int
fgetattrlist(int fd, void *attrList, void *attrBuf,
             size_t attrBufSize, unsigned int options)
#else
int
fgetattrlist(int fd, void *attrList, void *attrBuf,
             size_t attrBufSize, unsigned long options)
#endif
{
  int r;
  struct stat st;

#ifdef LIBFAKEROOT_DEBUGGING
  if (fakeroot_debug) {
    fprintf(stderr, "fgetattrlist fd %d\n", fd);
  }
#endif /* LIBFAKEROOT_DEBUGGING */
  r=next_fgetattrlist(fd, attrList, attrBuf, attrBufSize, options);
  if (r) {
    return r;
  }
  r=WRAP_FSTAT(fd, &st);
  if (r) {
    return r;
  }
  patchattr(attrList, attrBuf, st.st_uid, st.st_gid, st.st_mode);

  return 0;
}
#endif /* if HAVE_FGETATTRLIST */

/*
 * Prevent loss of DYLD_INSERT_LIBRARIES, FAKEROOTKEY and FAKED_MODE
 * environment variables during packaging (packagemaker otherwise clears them).
 */

static char *dylib_insert;
static char *fakeroot_key;
static char *faked_mode;
static int spawnexec_in_progress;
static pid_t spawnexec_pid;

static int is_spawnexec_active()
{
  if (getpid() != spawnexec_pid) {
    spawnexec_in_progress = 0;
  }
  return spawnexec_in_progress;
}

static void enter_spawnexec()
{
  (void)is_spawnexec_active();
  if (++spawnexec_in_progress == 1)
    spawnexec_pid = getpid();
}

static void exit_spawnexec()
{
  (void)is_spawnexec_active();
  if (spawnexec_in_progress)
    --spawnexec_in_progress;
}

__attribute__((__constructor__,__used__)) static void retrieve_dylib();
static void retrieve_dylib()
{
  const char *dil = getenv("DYLD_INSERT_LIBRARIES");
  const char *frk = fakeroot_key = getenv("FAKEROOTKEY");
  const char *fdm = faked_mode = getenv("FAKED_MODE");
  if (frk) {
    char *savekey = (char *)malloc(12 + strlen(frk) + 1);
    if (savekey) {
      sprintf(savekey, "FAKEROOTKEY=%s", frk);
      fakeroot_key = savekey;
    }
  }
  if (fdm) {
    char *savemode = (char *)malloc(11 + strlen(fdm) + 1);
    if (savemode) {
      sprintf(savemode, "FAKED_MODE=%s", fdm);
      faked_mode = savemode;
    }
  }
  if (dil) {
    char *dupe = strdup(dil);
    if (dupe) {
      char *ptr = dupe;
      do {
        char *next = strchr(ptr, ':');
        if (next)
          *next++ = '\0';
        if (strstr(ptr, "libfakeroot") && strstr(ptr, ".dylib")) {
          dylib_insert = ptr;
          return;
        }
        ptr = next;
      } while (ptr);
      free(dupe);
    }
  }
}

static char **get_exec_envp(char *const envp[], char **insenvp)
{
  int i, envcount = 0;
  char **altenv = NULL;

  *insenvp = NULL;
  if (!envp || !dylib_insert || !fakeroot_key ||
      getenv("FAKEROOT_TEST_PRELOAD"))
    return (char **)envp;

  while (envp[envcount]) {
    ++envcount;
  }
  altenv = (char **)malloc((envcount + 4) * sizeof(char *));
  if (!altenv)
    return (char **)envp;
  memcpy(altenv, envp, (envcount + 1) * sizeof(char *));

  for (i=0; i<envcount; ++i) {
    if (strncmp(altenv[i], "FAKEROOTKEY=", 12) == 0)
      break;
  }
  if (i >= envcount) {
    altenv[envcount] = fakeroot_key;
    altenv[++envcount] = NULL;
  }

  for (i=0; i<envcount; ++i) {
    if (strncmp(altenv[i], "FAKED_MODE=", 11) == 0)
      break;
  }
  if (i >= envcount && faked_mode) {
    altenv[envcount] = faked_mode;
    altenv[++envcount] = NULL;
  }

  for (i=0; i<envcount; ++i) {
    if (strncmp(altenv[i], "DYLD_INSERT_LIBRARIES=", 22) == 0) {
      if (strstr(altenv[i], dylib_insert))
        return altenv;
      else {
        *insenvp = (char *)malloc(strlen(altenv[i]) + strlen(dylib_insert) + 2);
        if (!*insenvp) {
          free(altenv);
          return (char **)envp;
        }
        sprintf(*insenvp, "DYLD_INSERT_LIBRARIES=%s:%s", dylib_insert,
          altenv[i]+22);
        altenv[i] = *insenvp;
        return altenv;
      }
    }
  }
  *insenvp = (char *)malloc(22 + strlen(dylib_insert) + 1);
  if (!*insenvp) {
    free(altenv);
    return (char **)envp;
  }
  sprintf(*insenvp, "DYLD_INSERT_LIBRARIES=%s", dylib_insert);
  altenv[envcount] = *insenvp;
  altenv[envcount+1] = NULL;
  return altenv;
}

int execve(const char *path, char *const argv[], char *const envp[])
{
  int result;
  char **altenv;
  char *insenv;

  if (!path || !argv || !envp || is_spawnexec_active()) {
    enter_spawnexec();
    result = next_execve(path, argv, envp);
    exit_spawnexec();
    return result;
  }

  altenv = get_exec_envp(envp, &insenv);
  enter_spawnexec();
  result = next_execve(path, argv, altenv);
  exit_spawnexec();
  if (altenv != envp)
    free(altenv);
  if (insenv)
    free(insenv);
  return result;
}

/* funnel execl, execle, execlp, execv, execvp and execvP into execve */

int execv(const char *path, char *const argv[])
{
  return execve(path, argv, *_NSGetEnviron());
}

static char *find_exec_path(const char *file, const char *search_path)
{
  char *path = (char *)file;
  if (file && *file && !strchr(file, '/') && search_path && *search_path) {
    size_t splen = strlen(search_path);
    const char *search_end = search_path + splen;
    const char *next;
    char *buff = malloc(strlen(file) + splen + 2);
    if (!buff)
      return NULL;
    for (; search_path < search_end; search_path = next) {
      struct stat info;
      size_t plen;
      if ((next = strchr(search_path, ':')))
        plen = next++ - search_path;
      else
        plen = (next = search_end) - search_path;
      memcpy(buff, search_path, plen);
      sprintf(buff + plen, "%s%s", plen ? "/" : "", file);
      if (stat(buff, &info) || !S_ISREG(info.st_mode) || access(buff, X_OK))
        continue;
      path = buff;
      break;
    }
    if (path == file) {
      free(buff);
      errno = ENOENT;
      return NULL;
    }
  }
  return path;
}

int execvP(const char *file, const char *search_path, char *const argv[])
{
  int result;
  char *path = find_exec_path(file, search_path);
  if (!path)
    return -1;
  result = execve(path, argv, *_NSGetEnviron());
  if (path != file)
    free(path);
  return result;
}

int execvp(const char *file, char *const argv[])
{
  const char *path = getenv("PATH");
  return execvP(file, path ? path : _PATH_DEFPATH, argv);
}

static char **collect_args(const char *arg0, va_list args, char ***envp)
{
  char **arglist;
  size_t count = 0;
  char **outp;

  va_list args_copy;
  va_copy(args_copy, args);
  for (;;) {
    char *ap = va_arg(args_copy, char *);
    if (!ap)
      break;
    ++count;
  }
  va_end(args_copy);
  arglist = (char **)malloc((count + 2) * sizeof(char *));
  if (!arglist)
    return NULL;
  outp = arglist;
  *outp++ = (char *)arg0;
  for (;;) {
    char *ap = va_arg(args, char *);
    *outp++ = ap;
    if (!ap)
      break;
  }
  if (envp)
    *envp = va_arg(args, char **);
  return arglist;
}

int execl(const char *path, const char *arg0, ...)
{
  int result;
  char **arglist;
  va_list args;
  va_start(args, arg0);
  arglist = collect_args(arg0, args, NULL);
  va_end(args);
  if (!arglist)
    return -1;
  result = execve(path, arglist, *_NSGetEnviron());
  free(arglist);
  return result;
}

int execle(const char *path, const char *arg0, ...)
{
  int result;
  char **arglist;
  char **envp;
  va_list args;
  va_start(args, arg0);
  arglist = collect_args(arg0, args, &envp);
  va_end(args);
  if (!arglist)
    return -1;
  result = execve(path, arglist, envp);
  free(arglist);
  return result;
}

int execlp(const char *file, const char *arg0, ...)
{
  int result;
  char **arglist;
  va_list args;
  va_start(args, arg0);
  arglist = collect_args(arg0, args, NULL);
  va_end(args);
  if (!arglist)
    return -1;
  result = execvp(file, arglist);
  free(arglist);
  return result;
}

#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5

/* handle posix_spawn and posix_spawnp separately */

int posix_spawn(pid_t * __restrict pid, const char * __restrict path,
                const posix_spawn_file_actions_t *file_actions,
                const posix_spawnattr_t * __restrict attrp,
                char *const argv[ __restrict], char *const envp[ __restrict])
{
  int result;
  char **altenv;
  char *insenv;

  if (!path || !argv || !envp || is_spawnexec_active()) {
    enter_spawnexec();
    result = next_posix_spawn(pid, path, file_actions, attrp, argv, envp);
    exit_spawnexec();
    return result;
  }

  altenv = get_exec_envp(envp, &insenv);
  enter_spawnexec();
  result = next_posix_spawn(pid, path, file_actions, attrp, argv, altenv);
  exit_spawnexec();
  if (altenv != envp)
    free(altenv);
  if (insenv)
    free(insenv);
  return result;
}

int posix_spawnp(pid_t * __restrict pid, const char * __restrict file,
                 const posix_spawn_file_actions_t *file_actions,
                 const posix_spawnattr_t * __restrict attrp,
                 char *const argv[ __restrict], char *const envp[ __restrict])
{
  int result;
  const char *search_path = getenv("PATH");
  char *path = find_exec_path(file, search_path ? search_path : _PATH_DEFPATH);
  if (!path)
    return errno;
  result = posix_spawn(pid, path, file_actions, attrp, argv, envp);
  if (path != file)
    free(path);
  return result;
}
#endif /* MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 */
#endif /* ifdef __APPLE__ */

#ifdef __sun
/*
 * Disable the runtime selection of binaries on Solaris: libfakeroot is (yet?)
 * unable to cope with several bitnesses of binaries being run.
 */
int sysinfo(int command, char *buf, long count)
{
    if (command == SI_ISALIST)
    {
        /* do the evil trick */
#ifdef sparc
#ifdef __arch64__
        strncpy(buf, "sparcv9 sparc", count - 1);
        return sizeof("sparcv9 sparc");
#else
        strncpy(buf, "sparcv7 sparc", count - 1);
        return sizeof("sparcv7 sparc");
#endif
#else
        strncpy(buf, "i386 i86", count - 1);
        return sizeof("i386 i86");
#endif
    }
    else
    {
        return next_sysinfo(command, buf, count);
    }
}
#endif