File: vfs.c

package info (click to toggle)
tclvfs 1.3-2
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 1,240 kB
  • ctags: 416
  • sloc: tcl: 3,670; xml: 2,882; sh: 2,833; ansic: 1,264; makefile: 58
file content (2037 lines) | stat: -rw-r--r-- 58,435 bytes parent folder | download | duplicates (2)
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
/* 
 * vfs.c --
 *
 *	This file contains the implementation of the Vfs extension
 *	to Tcl.  It provides a script level interface to Tcl's 
 *	virtual file system support, and therefore allows 
 *	vfs's to be implemented in Tcl.
 *	
 *	Some of this file could be used as a basis for a hard-coded
 *	vfs implemented in C (e.g. a zipvfs).
 *	
 *	The code is thread-safe.  Although under normal use only
 *	one interpreter will be used to add/remove mounts and volumes,
 *	it does cope with multiple interpreters in multiple threads.
 *	
 * Copyright (c) 2001-2004 Vince Darley.
 * 
 * See the file "license.terms" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include <tcl.h>
/* Required to access the 'stat' structure fields, and TclInExit() */
#include "tclInt.h"
#include "tclPort.h"

/*
 * Windows needs to know which symbols to export.  Unix does not.
 * BUILD_vfs should be undefined for Unix.
 */

#ifdef BUILD_vfs
#undef TCL_STORAGE_CLASS
#define TCL_STORAGE_CLASS DLLEXPORT
#endif /* BUILD_vfs */

#ifndef TCL_GLOB_TYPE_MOUNT
#define TCL_GLOB_TYPE_MOUNT		(1<<7)
#endif

/*
 * Only the _Init function is exported.
 */

EXTERN int Vfs_Init _ANSI_ARGS_((Tcl_Interp*));

/* 
 * Functions to add and remove a volume from the list of volumes.
 * These aren't currently exported, but could be in the future.
 */
static void Vfs_AddVolume    _ANSI_ARGS_((Tcl_Obj*));
static int  Vfs_RemoveVolume _ANSI_ARGS_((Tcl_Obj*));

/* 
 * Stores the list of volumes registered with the vfs (and therefore
 * also registered with Tcl).  It is maintained as a valid Tcl list at
 * all times, or NULL if there are none (we don't keep it as an empty
 * list just as a slight optimisation to improve Tcl's efficiency in
 * determining whether paths are absolute or relative).
 * 
 * We keep a refCount on this object whenever it is non-NULL.
 */
static Tcl_Obj *vfsVolumes = NULL;

/* 
 * Declare a mutex for thread-safety of modification of the
 * list of vfs volumes.
 */
TCL_DECLARE_MUTEX(vfsVolumesMutex)

/* 
 * Stores a script to evaluate when an internal error is detected in
 * a tclvfs implementation.  This is most useful for debugging.
 * 
 * When it is not NULL we keep a refCount on it.
 */
static Tcl_Obj *internalErrorScript = NULL;

/* 
 * Declare a mutex for thread-safety of modification of the
 * internal error script.
 */
TCL_DECLARE_MUTEX(internalErrorMutex)

/*
 * struct Vfs_InterpCmd --
 * 
 * Any vfs action which is exposed to Tcl requires both an interpreter
 * and a command prefix for evaluation.  To carry out any filesystem
 * action inside a vfs, this extension will lappend various additional
 * parameters to the command string, evaluate it in the interpreter and
 * then extract the result (the way the result is handled is documented
 * in each individual vfs callback below).
 * 
 * We retain a refCount on the 'mountCmd' object, but there is no need
 * for us to register our interpreter reference, since we will be
 * made invalid when the interpreter disappears.  Also, Tcl_Objs of
 * "path" type which use one of these structures as part of their
 * internal representation also do not need to add to any refCounts,
 * because if this object disappears, all internal representations will
 * be made invalid.
 */

typedef struct Vfs_InterpCmd {
    Tcl_Obj *mountCmd;    /* The Tcl command prefix which will be used
                           * to perform all filesystem actions on this
                           * file. */
    Tcl_Interp *interp;   /* The Tcl interpreter in which the above
                           * command will be evaluated. */
} Vfs_InterpCmd;

/*
 * struct VfsNativeRep --
 * 
 * Structure used for the native representation of a path in a Tcl vfs.
 * To fully specify a file, the string representation is also required.
 * 
 * When a Tcl interpreter is deleted, all mounts whose callbacks
 * are in it are removed and freed.  This also means that the
 * global filesystem epoch that Tcl retains is modified, and all
 * path internal representations are therefore discarded.  Therefore we
 * don't have to worry about vfs files containing stale VfsNativeRep
 * structures (but it also means we mustn't touch the fsCmd field
 * of one of these structures if the interpreter has gone).  This
 * means when we free one of these structures, we just free the
 * memory allocated, and ignore the fsCmd pointer (which may or may
 * not point to valid memory).
 */

typedef struct VfsNativeRep {
    int splitPosition;    /* The index into the string representation
                           * of the file which indicates where the 
                           * vfs filesystem is mounted. */
    Vfs_InterpCmd* fsCmd; /* The Tcl interpreter and command pair
                           * which will be used to perform all filesystem 
                           * actions on this file. */
} VfsNativeRep;

/*
 * struct VfsChannelCleanupInfo --
 * 
 * Structure we use to retain sufficient information about
 * a channel that we can properly clean up all resources
 * when the channel is closed.  This is required when using
 * 'open' on things inside the vfs.
 * 
 * When the channel in question is begin closed, we will
 * temporarily register the channel with the given interpreter,
 * evaluate the closeCallBack, and then detach the channel
 * from the interpreter and return (allowing Tcl to continue
 * closing the channel as normal).
 * 
 * Nothing in the callback can prevent the channel from
 * being closed.
 */

typedef struct VfsChannelCleanupInfo {
    Tcl_Channel channel;    /* The channel which needs cleaning up */
    Tcl_Obj* closeCallback; /* The Tcl command string to evaluate
                             * when the channel is closing, which will
                             * carry out any cleanup that is necessary. */
    Tcl_Interp* interp;     /* The interpreter in which to evaluate the
                             * cleanup operation. */
} VfsChannelCleanupInfo;


/*
 * Forward declarations for procedures defined later in this file:
 */

static int		 VfsFilesystemObjCmd _ANSI_ARGS_((ClientData dummy,
			    Tcl_Interp *interp, int objc, 
			    Tcl_Obj *CONST objv[]));

/* 
 * Now we define the virtual filesystem callbacks.  Note that some
 * of these callbacks are passed a Tcl_Interp for error messages.
 * We will copy over the error messages from the vfs interp to the
 * calling interp.  Currently this is done directly, but we
 * could investigate using 'TclTransferResult' which would allow
 * error traces to be copied over as well.
 */

static Tcl_FSStatProc VfsStat;
static Tcl_FSAccessProc VfsAccess;
static Tcl_FSOpenFileChannelProc VfsOpenFileChannel;
static Tcl_FSMatchInDirectoryProc VfsMatchInDirectory;
static Tcl_FSDeleteFileProc VfsDeleteFile;
static Tcl_FSCreateDirectoryProc VfsCreateDirectory;
static Tcl_FSRemoveDirectoryProc VfsRemoveDirectory; 
static Tcl_FSFileAttrStringsProc VfsFileAttrStrings;
static Tcl_FSFileAttrsGetProc VfsFileAttrsGet;
static Tcl_FSFileAttrsSetProc VfsFileAttrsSet;
static Tcl_FSUtimeProc VfsUtime;
static Tcl_FSPathInFilesystemProc VfsPathInFilesystem;
static Tcl_FSFilesystemPathTypeProc VfsFilesystemPathType;
static Tcl_FSFilesystemSeparatorProc VfsFilesystemSeparator;
static Tcl_FSFreeInternalRepProc VfsFreeInternalRep;
static Tcl_FSDupInternalRepProc VfsDupInternalRep;
static Tcl_FSListVolumesProc VfsListVolumes;

static Tcl_Filesystem vfsFilesystem = {
    "tclvfs",
    sizeof(Tcl_Filesystem),
    TCL_FILESYSTEM_VERSION_1,
    &VfsPathInFilesystem,
    &VfsDupInternalRep,
    &VfsFreeInternalRep,
    /* No internal to normalized, since we don't create any
     * pure 'internal' Tcl_Obj path representations */
    NULL,
    /* No create native rep function, since we don't use it
     * or 'Tcl_FSNewNativePath' */
    NULL,
    /* Normalize path isn't needed - we assume paths only have
     * one representation */
    NULL,
    &VfsFilesystemPathType,
    &VfsFilesystemSeparator,
    &VfsStat,
    &VfsAccess,
    &VfsOpenFileChannel,
    &VfsMatchInDirectory,
    &VfsUtime,
    /* We choose not to support symbolic links inside our vfs's */
    NULL,
    &VfsListVolumes,
    &VfsFileAttrStrings,
    &VfsFileAttrsGet,
    &VfsFileAttrsSet,
    &VfsCreateDirectory,
    &VfsRemoveDirectory, 
    &VfsDeleteFile,
    /* No copy file - fallback will occur at Tcl level */
    NULL,
    /* No rename file - fallback will occur at Tcl level */
    NULL,
    /* No copy directory - fallback will occur at Tcl level */
    NULL, 
    /* Use stat for lstat */
    NULL,
    /* No load - fallback on core implementation */
    NULL,
    /* We don't need a getcwd or chdir - fallback on Tcl's versions */
    NULL,
    NULL
};

/*
 * struct VfsMount --
 * 
 * Each filesystem mount point which is registered will result in
 * the allocation of one of these structures.  They are stored
 * in a linked list whose head is 'listOfMounts'.
 */

typedef struct VfsMount {
    CONST char* mountPoint;
    int mountLen;
    int isVolume;
    Vfs_InterpCmd interpCmd;
    struct VfsMount* nextMount;
} VfsMount;

static VfsMount* listOfMounts = NULL;
/* 
 * Declare a mutex for thread-safety of modification of the
 * list of vfs mounts.
 */
TCL_DECLARE_MUTEX(vfsMountsMutex)

/* We might wish to consider exporting these in the future */

static int             Vfs_AddMount(Tcl_Obj* mountPoint, int isVolume, 
				    Tcl_Interp *interp, Tcl_Obj* mountCmd);
static int             Vfs_RemoveMount(Tcl_Obj* mountPoint, Tcl_Interp* interp);
static Vfs_InterpCmd*  Vfs_FindMount(Tcl_Obj *pathMount, int mountLen);
static Tcl_Obj*        Vfs_ListMounts(void);
static void            Vfs_UnregisterWithInterp _ANSI_ARGS_((ClientData, 
							     Tcl_Interp*));
static void            Vfs_RegisterWithInterp _ANSI_ARGS_((Tcl_Interp*));

/* Some private helper procedures */

static VfsNativeRep*   VfsGetNativePath(Tcl_Obj* pathPtr);
static Tcl_CloseProc   VfsCloseProc;
static void            VfsExitProc(ClientData clientData);
static Tcl_Obj*	       VfsFullyNormalizePath(Tcl_Interp *interp, 
				             Tcl_Obj *pathPtr);
static Tcl_Obj*        VfsBuildCommandForPath(Tcl_Interp **iRef, 
			          CONST char* cmd, Tcl_Obj * pathPtr);
static void            VfsInternalError(Tcl_Interp* interp);

/* 
 * Hard-code platform dependencies.  We do not need to worry 
 * about backslash-separators on windows, because a normalized
 * path will never contain them.
 */
#ifdef MAC_TCL
    #define VFS_SEPARATOR ':'
#else
    #define VFS_SEPARATOR '/'
#endif


/*
 *----------------------------------------------------------------------
 *
 * Vfs_Init --
 *
 *	This procedure is the main initialisation point of the Vfs
 *	extension.
 *
 * Results:
 *	Returns a standard Tcl completion code, and leaves an error
 *	message in the interp's result if an error occurs.
 *
 * Side effects:
 *	Adds a command to the Tcl interpreter.
 *
 *----------------------------------------------------------------------
 */

int
Vfs_Init(interp)
    Tcl_Interp *interp;		/* Interpreter for application. */
{
    if (Tcl_InitStubs(interp, "8.4", 0) == NULL) {
	return TCL_ERROR;
    }
    if (Tcl_PkgRequire(interp, "Tcl", "8.4", 0) == NULL) {
	return TCL_ERROR;
    }
    
    /* 
     * Safe interpreters are not allowed to modify the filesystem!
     * (Since those modifications will affect other interpreters).
     */
    if (Tcl_IsSafe(interp)) {
        return TCL_ERROR;
    }

#ifndef PACKAGE_VERSION
    /* keep in sync with actual version */
#define PACKAGE_VERSION "1.3"
#endif
    if (Tcl_PkgProvide(interp, "vfs", PACKAGE_VERSION) == TCL_ERROR) {
        return TCL_ERROR;
    }

    /*
     * Create 'vfs::filesystem' command, and interpreter-specific
     * initialisation.
     */

    Tcl_CreateObjCommand(interp, "vfs::filesystem", VfsFilesystemObjCmd, 
	    (ClientData) NULL, (Tcl_CmdDeleteProc *) NULL);
    Vfs_RegisterWithInterp(interp);
    return TCL_OK;
}


/*
 *----------------------------------------------------------------------
 *
 * Vfs_RegisterWithInterp --
 *
 *	Allow the given interpreter to be used to handle vfs callbacks.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	May register the entire vfs code (if not previously registered).
 *	Registers some cleanup action for when this interpreter is
 *	deleted.
 *
 *----------------------------------------------------------------------
 */
static void 
Vfs_RegisterWithInterp(interp)
    Tcl_Interp *interp;
{
    ClientData vfsAlreadyRegistered;
    /* 
     * We need to know if the interpreter is deleted, so we can
     * remove all interp-specific mounts.
     */
    Tcl_SetAssocData(interp, "vfs::inUse", (Tcl_InterpDeleteProc*) 
		     Vfs_UnregisterWithInterp, (ClientData) 1);
    /* 
     * Perform one-off registering of our filesystem if that
     * has not happened before.
     */
    vfsAlreadyRegistered = Tcl_FSData(&vfsFilesystem);
    if (vfsAlreadyRegistered == NULL) {
	Tcl_FSRegister((ClientData)1, &vfsFilesystem);
	Tcl_CreateExitHandler(VfsExitProc, (ClientData)NULL);
    }
}
   

/*
 *----------------------------------------------------------------------
 *
 * Vfs_UnregisterWithInterp --
 *
 *	Remove all of the mount points that this interpreter handles.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */
static void 
Vfs_UnregisterWithInterp(dummy, interp)
    ClientData dummy;
    Tcl_Interp *interp;
{
    int res = TCL_OK;
    /* Remove all of this interpreters mount points */
    while (res == TCL_OK) {
        res = Vfs_RemoveMount(NULL, interp);
    }
    /* Make sure our assoc data has been deleted */
    Tcl_DeleteAssocData(interp, "vfs::inUse");
}


/*
 *----------------------------------------------------------------------
 *
 * Vfs_AddMount --
 *
 *	Adds a new vfs mount point.  After this call all filesystem
 *	access within that mount point will be redirected to the
 *	interpreter/mountCmd pair.
 *	
 *	This command must not be called unless 'interp' has already
 *	been registered with 'Vfs_RegisterWithInterp' above.  This 
 *	usually happens automatically with a 'package require vfs'.
 *
 * Results:
 *	TCL_OK unless the inputs are bad or a memory allocation
 *	error occurred, or the interpreter is not vfs-registered.
 *
 * Side effects:
 *	A new volume may be added to the list of available volumes.
 *	Future filesystem access inside the mountPoint will be 
 *	redirected.  Tcl is informed that a new mount has been added
 *	and this will make all cached path representations invalid.
 *
 *----------------------------------------------------------------------
 */
static int 
Vfs_AddMount(mountPoint, isVolume, interp, mountCmd)
    Tcl_Obj* mountPoint;
    int isVolume;
    Tcl_Interp* interp;
    Tcl_Obj* mountCmd;
{
    char *strRep;
    int len;
    VfsMount *newMount;
    
    if (mountPoint == NULL || interp == NULL || mountCmd == NULL) {
	return TCL_ERROR;
    }
    /* 
     * Check whether this intepreter can properly clean up
     * mounts on exit.  If not, throw an error.
     */
    if (Tcl_GetAssocData(interp, "vfs::inUse", NULL) == NULL) {
        return TCL_ERROR;
    }
    
    newMount = (VfsMount*) ckalloc(sizeof(VfsMount));
    
    if (newMount == NULL) {
	return TCL_ERROR;
    }
    strRep = Tcl_GetStringFromObj(mountPoint, &len);
    newMount->mountPoint = (char*) ckalloc(1+(unsigned)len);
    newMount->mountLen = len;
    
    if (newMount->mountPoint == NULL) {
	ckfree((char*)newMount);
	return TCL_ERROR;
    }
    
    strcpy((char*)newMount->mountPoint, strRep);
    newMount->interpCmd.mountCmd = mountCmd;
    newMount->interpCmd.interp = interp;
    newMount->isVolume = isVolume;
    Tcl_IncrRefCount(mountCmd);
    
    Tcl_MutexLock(&vfsMountsMutex);
    newMount->nextMount = listOfMounts;
    listOfMounts = newMount;
    Tcl_MutexUnlock(&vfsMountsMutex);

    if (isVolume) {
	Vfs_AddVolume(mountPoint);
    }
    Tcl_FSMountsChanged(&vfsFilesystem);
    return TCL_OK;
}


/*
 *----------------------------------------------------------------------
 *
 * Vfs_RemoveMount --
 *
 *	This procedure searches for a matching mount point and removes
 *	it if one is found.  If 'mountPoint' is given, then both it and
 *	the interpreter must match for a mount point to be removed.
 *	
 *	If 'mountPoint' is NULL, then the first mount point for the
 *	given interpreter is removed (if any).
 *
 * Results:
 *	TCL_OK if a mount was removed, TCL_ERROR otherwise.
 *
 * Side effects:
 *	A volume may be removed from the current list of volumes
 *	(as returned by 'file volumes').  A vfs may be removed from
 *	the filesystem.  If successful, Tcl will be informed that
 *	the list of current mounts has changed, and all cached file
 *	representations will be made invalid.
 *
 *----------------------------------------------------------------------
 */
static int 
Vfs_RemoveMount(mountPoint, interp)
    Tcl_Obj* mountPoint;
    Tcl_Interp *interp;
{
    /* These two are only used if mountPoint is non-NULL */
    char *strRep = NULL;
    int len = 0;
    
    VfsMount *mountIter;
    /* Set to NULL just to avoid warnings */
    VfsMount *lastMount = NULL;
    
    if (mountPoint != NULL) {
	strRep = Tcl_GetStringFromObj(mountPoint, &len);
    }
       
    Tcl_MutexLock(&vfsMountsMutex);
    mountIter = listOfMounts;
    
    while (mountIter != NULL) {
	if ((interp == mountIter->interpCmd.interp) 
	    && ((mountPoint == NULL) ||
		(mountIter->mountLen == len && 
		 !strcmp(mountIter->mountPoint, strRep)))) {
	    /* We've found the mount. */
	    if (mountIter == listOfMounts) {
		listOfMounts = mountIter->nextMount;
	    } else {
		lastMount->nextMount = mountIter->nextMount;
	    }
	    /* Free the allocated memory */
	    if (mountIter->isVolume) {
		if (mountPoint == NULL) {
		    Tcl_Obj *volObj = Tcl_NewStringObj(mountIter->mountPoint, 
						       mountIter->mountLen);
		    Tcl_IncrRefCount(volObj);
		    Vfs_RemoveVolume(volObj);
		    Tcl_DecrRefCount(volObj);
		} else {
		    Vfs_RemoveVolume(mountPoint);
		}
	    }
	    ckfree((char*)mountIter->mountPoint);
	    Tcl_DecrRefCount(mountIter->interpCmd.mountCmd);
	    ckfree((char*)mountIter);
	    Tcl_FSMountsChanged(&vfsFilesystem);
	    Tcl_MutexUnlock(&vfsMountsMutex);
	    return TCL_OK;
	}
	lastMount = mountIter;
	mountIter = mountIter->nextMount;
    }
    Tcl_MutexUnlock(&vfsMountsMutex);
    return TCL_ERROR;
}


/*
 *----------------------------------------------------------------------
 *
 * Vfs_FindMount --
 *
 *	This procedure searches all currently mounted paths for one
 *	which matches the given path.  The given path must be the
 *	absolute, normalized, unique representation for the given path.
 *	If 'len' is -1, we use the entire string representation of the
 *	mountPoint, otherwise we treat 'len' as the length of the mount
 *	we are comparing.
 *
 * Results:
 *	Returns the interpreter, command-prefix pair for the given
 *	mount point, if one is found, otherwise NULL.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */
static Vfs_InterpCmd* 
Vfs_FindMount(pathMount, mountLen)
    Tcl_Obj *pathMount;
    int mountLen;
{
    VfsMount *mountIter;
    char *mountStr;
    
    if (pathMount == NULL) {
	return NULL;
    }
    
    if (mountLen == -1) {
        mountStr = Tcl_GetStringFromObj(pathMount, &mountLen);
    } else {
	mountStr = Tcl_GetString(pathMount);
    }

    Tcl_MutexLock(&vfsMountsMutex);

    mountIter = listOfMounts;
    while (mountIter != NULL) {
	if (mountIter->mountLen == mountLen && 
	  !strncmp(mountIter->mountPoint, mountStr, (size_t)mountLen)) {
	    Vfs_InterpCmd *ret = &mountIter->interpCmd;
	    Tcl_MutexUnlock(&vfsMountsMutex);
	    return ret;
	}
	mountIter = mountIter->nextMount;
    }
    Tcl_MutexUnlock(&vfsMountsMutex);
    return NULL;
}


/*
 *----------------------------------------------------------------------
 *
 * Vfs_ListMounts --
 *
 *	Returns a valid Tcl list, with refCount of zero, containing
 *	all currently mounted paths.
 *	
 *----------------------------------------------------------------------
 */
static Tcl_Obj* 
Vfs_ListMounts(void) 
{
    VfsMount *mountIter;
    Tcl_Obj *res = Tcl_NewObj();

    Tcl_MutexLock(&vfsMountsMutex);

    /* Build list of mounts */
    mountIter = listOfMounts;
    while (mountIter != NULL) {
	Tcl_Obj* mount = Tcl_NewStringObj(mountIter->mountPoint, 
					  mountIter->mountLen);
	Tcl_ListObjAppendElement(NULL, res, mount);
	mountIter = mountIter->nextMount;
    }
    Tcl_MutexUnlock(&vfsMountsMutex);
    return res;
}

/*
 *----------------------------------------------------------------------
 *
 * VfsFilesystemObjCmd --
 *
 *	This procedure implements the "vfs::filesystem" command.  It is
 *	used to mount/unmount particular interfaces to new filesystems,
 *	or to query for what is mounted where.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	Inserts or removes a filesystem from Tcl's stack.
 *
 *----------------------------------------------------------------------
 */

static int
VfsFilesystemObjCmd(dummy, interp, objc, objv)
    ClientData dummy;
    Tcl_Interp *interp;
    int		objc;
    Tcl_Obj	*CONST objv[];
{
    int index;

    static CONST char *optionStrings[] = {
	"info", "internalerror", "mount", "unmount", 
	"fullynormalize", "posixerror", 
	NULL
    };
    
    enum options {
	VFS_INFO, VFS_INTERNAL_ERROR, VFS_MOUNT, VFS_UNMOUNT, 
	VFS_NORMALIZE, VFS_POSIXERROR
    };

    if (objc < 2) {
	Tcl_WrongNumArgs(interp, 1, objv, "option ?arg ...?");
	return TCL_ERROR;
    }
    if (Tcl_GetIndexFromObj(interp, objv[1], optionStrings, "option", 0,
	    &index) != TCL_OK) {
	return TCL_ERROR;
    }

    switch ((enum options) index) {
	case VFS_INTERNAL_ERROR: {
	    if (objc > 3) {
		Tcl_WrongNumArgs(interp, 2, objv, "?script?");
		return TCL_ERROR;
	    }
	    if (objc == 2) {
	        /* Return the current script */
		Tcl_MutexLock(&internalErrorMutex);
		if (internalErrorScript != NULL) {
		    Tcl_SetObjResult(interp, internalErrorScript);
		}
		Tcl_MutexUnlock(&internalErrorMutex);
	    } else {
		/* Set the script */
		int len;
		Tcl_MutexLock(&internalErrorMutex);
		if (internalErrorScript != NULL) {
		    Tcl_DecrRefCount(internalErrorScript);
		}
		Tcl_GetStringFromObj(objv[2], &len);
		if (len == 0) {
		    /* Clear our script */
		    internalErrorScript = NULL;
		} else {
		    /* Set it */
		    internalErrorScript = objv[2];
		    Tcl_IncrRefCount(internalErrorScript);
		}
		Tcl_MutexUnlock(&internalErrorMutex);
	    }
	    return TCL_OK;
	}
	case VFS_POSIXERROR: {
	    int posixError = -1;
	    if (objc != 3) {
		Tcl_WrongNumArgs(interp, 2, objv, "errorcode");
		return TCL_ERROR;
	    }
	    if (Tcl_GetIntFromObj(NULL, objv[2], &posixError) != TCL_OK) {
		return TCL_ERROR;
	    }
	    Tcl_SetErrno(posixError);
	    return -1;
	}
	case VFS_NORMALIZE: {
	    Tcl_Obj *path;
	    if (objc != 3) {
		Tcl_WrongNumArgs(interp, 2, objv, "path");
		return TCL_ERROR;
	    }
	    path = VfsFullyNormalizePath(interp, objv[2]);
	    if (path == NULL) {
		Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
			"not a valid path \"", Tcl_GetString(objv[2]), 
			"\"", (char *) NULL);
	    } else {
		Tcl_SetObjResult(interp, path);
		Tcl_DecrRefCount(path);
		return TCL_OK;
	    }
	}
        case VFS_MOUNT: {
	    if (objc < 4 || objc > 5) {
		Tcl_WrongNumArgs(interp, 1, objv, "mount ?-volume? path cmd");
		return TCL_ERROR;
	    }
	    if (objc == 5) {
		char *option = Tcl_GetString(objv[2]);
		if (strcmp("-volume", option)) {
		    Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
			    "bad option \"", option,
			    "\": must be -volume", (char *) NULL);
		    return TCL_ERROR;
		}
		return Vfs_AddMount(objv[3], 1, interp, objv[4]);
	    } else {
		Tcl_Obj *path;
		int retVal;
		path = VfsFullyNormalizePath(interp, objv[2]);
		retVal = Vfs_AddMount(path, 0, interp, objv[3]);
		if (path != NULL) Tcl_DecrRefCount(path);
		return retVal;
	    }
	    break;
	}
	case VFS_INFO: {
	    if (objc > 3) {
		Tcl_WrongNumArgs(interp, 2, objv, "path");
		return TCL_ERROR;
	    }
	    if (objc == 2) {
		Tcl_SetObjResult(interp, Vfs_ListMounts());
	    } else {
		Vfs_InterpCmd *val;
		
		val = Vfs_FindMount(objv[2], -1);
		if (val == NULL) {
		    Tcl_Obj *path;
		    path = VfsFullyNormalizePath(interp, objv[2]);
		    val = Vfs_FindMount(path, -1);
		    Tcl_DecrRefCount(path);
		    if (val == NULL) {
			Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
				"no such mount \"", Tcl_GetString(objv[2]), 
				"\"", (char *) NULL);
			return TCL_ERROR;
		    }
		}
		Tcl_SetObjResult(interp, val->mountCmd);
	    }
	    break;
	}
	case VFS_UNMOUNT: {
	    if (objc != 3) {
		Tcl_WrongNumArgs(interp, 2, objv, "path");
		return TCL_ERROR;
	    }
	    if (Vfs_RemoveMount(objv[2], interp) == TCL_ERROR) {
		Tcl_Obj *path;
		int retVal;
		path = VfsFullyNormalizePath(interp, objv[2]);
		retVal = Vfs_RemoveMount(path, interp);
		Tcl_DecrRefCount(path);
		if (retVal == TCL_ERROR) {
		    Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
			    "no such mount \"", Tcl_GetString(objv[2]), 
			    "\"", (char *) NULL);
		    return TCL_ERROR;
		}
	    }
	    return TCL_OK;
	}
    }
    return TCL_OK;
}

/* Handle an error thrown by a tcl vfs implementation */
static void
VfsInternalError(Tcl_Interp* interp) {
    if (interp != NULL) {
	Tcl_MutexLock(&internalErrorMutex);
	if (internalErrorScript != NULL) {
	    Tcl_EvalObjEx(interp, internalErrorScript, 
			  TCL_EVAL_GLOBAL | TCL_EVAL_DIRECT);
	}
	Tcl_MutexUnlock(&internalErrorMutex);
    }
}

/* Return fully normalized path owned by the caller */
static Tcl_Obj*
VfsFullyNormalizePath(Tcl_Interp *interp, Tcl_Obj *pathPtr) {
    Tcl_Obj *path;
    int counter = 0;

    Tcl_IncrRefCount(pathPtr);
    while (1) {
	path = Tcl_FSLink(pathPtr,NULL,0);
	if (path == NULL) {
	    break;
	}
	if (Tcl_FSGetPathType(path) != TCL_PATH_ABSOLUTE) {
	    /* 
	     * This is more complex, we need to find the path
	     * relative to the original file, effectively:
	     * 
	     *  file join [file dirname $pathPtr] $path
	     *  
	     * or 
	     * 
	     *  file join $pathPtr .. $path
	     *  
	     * So...
	     */
	    Tcl_Obj *dotdotPtr, *joinedPtr;
	    Tcl_Obj *joinElements[2];
	    
	    dotdotPtr = Tcl_NewStringObj("..",2);
	    Tcl_IncrRefCount(dotdotPtr);
	    
	    joinElements[0] = dotdotPtr;
	    joinElements[1] = path;

	    joinedPtr = Tcl_FSJoinToPath(pathPtr, 2, joinElements);
	    
	    if (joinedPtr != NULL) {
		Tcl_IncrRefCount(joinedPtr);
		Tcl_DecrRefCount(path);
		path = joinedPtr;
	    } else {
		/* We failed, and our action is undefined */
	    }
	    Tcl_DecrRefCount(dotdotPtr);
	}
	Tcl_DecrRefCount(pathPtr);
	pathPtr = path;
	counter++;
	if (counter > 10) {
	    /* Too many links */
	    Tcl_DecrRefCount(pathPtr);
	    return NULL;
	}
    }
    path = Tcl_FSGetNormalizedPath(interp, pathPtr);
    Tcl_IncrRefCount(path);
    Tcl_DecrRefCount(pathPtr);
    return path;
}

/*
 *----------------------------------------------------------------------
 *
 * VfsPathInFilesystem --
 *
 *	Check whether a path is in any of the mounted points in this
 *	vfs.
 *	
 *	If it is in the vfs, set the clientData given to our private
 *	internal representation for a vfs path.
 *	
 * Results:
 *	Returns TCL_OK on success, or '-1' on failure.  If Tcl is
 *	exiting, we always return a failure code.
 *
 * Side effects:
 *	On success, we allocate some memory for our internal
 *	representation structure.  Tcl will call us to free this
 *	when necessary.
 *
 *----------------------------------------------------------------------
 */
static int 
VfsPathInFilesystem(Tcl_Obj *pathPtr, ClientData *clientDataPtr) {
    Tcl_Obj *normedObj;
    int len, splitPosition;
    char *normed;
    VfsNativeRep *nativeRep;
    Vfs_InterpCmd *interpCmd = NULL;
    
    if (TclInExit()) {
	/* 
	 * Even Tcl_FSGetNormalizedPath may fail due to lack of system
	 * encodings, so we just say we can't handle anything if we are
	 * in the middle of the exit sequence.  We could perhaps be
	 * more subtle than this!
	 */
	return -1;
    }

    normedObj = Tcl_FSGetNormalizedPath(NULL, pathPtr);
    if (normedObj == NULL) {
        return -1;
    }
    normed = Tcl_GetStringFromObj(normedObj, &len);
    splitPosition = len;

    /* 
     * Find the most specific mount point for this path.
     * Mount points are specified by unique strings, so
     * we have to use a unique normalised path for the
     * checks here.
     * 
     * Given mount points are paths, 'most specific' means
     * longest path, so we scan from end to beginning
     * checking for valid mount points at each separator.
     */
    while (1) {
	/* 
	 * We need this test here both for an empty string being
	 * passed in above, and so that if we are testing a unix
	 * absolute path /foo/bar we will come around the loop
	 * with splitPosition at 0 for the last iteration, and we
	 * must return then.
	 */
	if (splitPosition == 0) {
	    return -1;
	}
	
	/* Is the path up to 'splitPosition' a valid moint point? */
	interpCmd = Vfs_FindMount(normedObj, splitPosition);
	if (interpCmd != NULL) break;

	while (normed[--splitPosition] != VFS_SEPARATOR) {
	    if (splitPosition == 0) {
		/* 
		 * We've reached the beginning of the string without
		 * finding a mount, so we've failed.
		 */
		return -1;
	    }
	}
	
	/* 
	 * We now know that normed[splitPosition] is a separator.
	 * However, we might have mounted a root filesystem with a
	 * name (for example 'ftp://') which actually includes a
	 * separator.  Therefore we test whether the path with
	 * a separator is a mount point.
	 * 
	 * Since we must have decremented splitPosition at least once
	 * already (above) 'splitPosition+1 <= len' so this won't
	 * access invalid memory.
	 */
	interpCmd = Vfs_FindMount(normedObj, splitPosition+1);
	if (interpCmd != NULL) {
	    splitPosition++;
	    break;
	}
    }
    
    /* 
     * If we reach here we have a valid mount point, since the
     * only way to escape the above loop is through a 'break' when
     * an interpCmd is non-NULL.
     */
    nativeRep = (VfsNativeRep*) ckalloc(sizeof(VfsNativeRep));
    nativeRep->splitPosition = splitPosition;
    nativeRep->fsCmd = interpCmd;
    *clientDataPtr = (ClientData)nativeRep;
    return TCL_OK;
}

/* 
 * Simple helper function to extract the native vfs representation of a
 * path object, or NULL if no such representation exists.
 */
static VfsNativeRep* 
VfsGetNativePath(Tcl_Obj* pathPtr) {
    return (VfsNativeRep*) Tcl_FSGetInternalRep(pathPtr, &vfsFilesystem);
}

static void 
VfsFreeInternalRep(ClientData clientData) {
    VfsNativeRep *nativeRep = (VfsNativeRep*)clientData;
    if (nativeRep != NULL) {
	/* Free the native memory allocation */
	ckfree((char*)nativeRep);
    }
}

static ClientData 
VfsDupInternalRep(ClientData clientData) {
    VfsNativeRep *original = (VfsNativeRep*)clientData;

    VfsNativeRep *nativeRep = (VfsNativeRep*) ckalloc(sizeof(VfsNativeRep));
    nativeRep->splitPosition = original->splitPosition;
    nativeRep->fsCmd = original->fsCmd;
    
    return (ClientData)nativeRep;
}

static Tcl_Obj* 
VfsFilesystemPathType(Tcl_Obj *pathPtr) {
    VfsNativeRep* nativeRep = VfsGetNativePath(pathPtr);
    if (nativeRep == NULL) {
	return NULL;
    } else {
	return nativeRep->fsCmd->mountCmd;
    }
}

static Tcl_Obj*
VfsFilesystemSeparator(Tcl_Obj* pathPtr) {
    char sep=VFS_SEPARATOR;
    return Tcl_NewStringObj(&sep,1);
}

static int
VfsStat(pathPtr, bufPtr)
    Tcl_Obj *pathPtr;		/* Path of file to stat (in current CP). */
    Tcl_StatBuf *bufPtr;	/* Filled with results of stat call. */
{
    Tcl_Obj *mountCmd = NULL;
    Tcl_SavedResult savedResult;
    int returnVal;
    Tcl_Interp* interp;
    
    mountCmd = VfsBuildCommandForPath(&interp, "stat", pathPtr);
    if (mountCmd == NULL) {
	return -1;
    }

    Tcl_SaveResult(interp, &savedResult);
    /* Now we execute this mount point's callback. */
    returnVal = Tcl_EvalObjEx(interp, mountCmd, 
			      TCL_EVAL_GLOBAL | TCL_EVAL_DIRECT);
    if (returnVal == TCL_OK) {
	int statListLength;
	Tcl_Obj* resPtr = Tcl_GetObjResult(interp);
	if (Tcl_ListObjLength(interp, resPtr, &statListLength) == TCL_ERROR) {
	    returnVal = TCL_ERROR;
	} else if (statListLength & 1) {
	    /* It is odd! */
	    returnVal = TCL_ERROR;
	} else {
	    /* 
	     * The st_mode field is set part by the 'mode'
	     * and part by the 'type' stat fields.
	     */
	    bufPtr->st_mode = 0;
	    while (statListLength > 0) {
		Tcl_Obj *field, *val;
		char *fieldName;
		statListLength -= 2;
		Tcl_ListObjIndex(interp, resPtr, statListLength, &field);
		Tcl_ListObjIndex(interp, resPtr, statListLength+1, &val);
		fieldName = Tcl_GetString(field);
		if (!strcmp(fieldName,"dev")) {
		    long v;
		    if (Tcl_GetLongFromObj(interp, val, &v) != TCL_OK) {
			returnVal = TCL_ERROR;
			break;
		    }
		    bufPtr->st_dev = v;
		} else if (!strcmp(fieldName,"ino")) {
		    long v;
		    if (Tcl_GetLongFromObj(interp, val, &v) != TCL_OK) {
			returnVal = TCL_ERROR;
			break;
		    }
		    bufPtr->st_ino = (unsigned short)v;
		} else if (!strcmp(fieldName,"mode")) {
		    int v;
		    if (Tcl_GetIntFromObj(interp, val, &v) != TCL_OK) {
			returnVal = TCL_ERROR;
			break;
		    }
		    bufPtr->st_mode |= v;
		} else if (!strcmp(fieldName,"nlink")) {
		    long v;
		    if (Tcl_GetLongFromObj(interp, val, &v) != TCL_OK) {
			returnVal = TCL_ERROR;
			break;
		    }
		    bufPtr->st_nlink = (short)v;
		} else if (!strcmp(fieldName,"uid")) {
		    long v;
		    if (Tcl_GetLongFromObj(interp, val, &v) != TCL_OK) {
			returnVal = TCL_ERROR;
			break;
		    }
		    bufPtr->st_uid = (short)v;
		} else if (!strcmp(fieldName,"gid")) {
		    long v;
		    if (Tcl_GetLongFromObj(interp, val, &v) != TCL_OK) {
			returnVal = TCL_ERROR;
			break;
		    }
		    bufPtr->st_gid = (short)v;
		} else if (!strcmp(fieldName,"size")) {
		    Tcl_WideInt v;
		    if (Tcl_GetWideIntFromObj(interp, val, &v) != TCL_OK) {
			returnVal = TCL_ERROR;
			break;
		    }
		    bufPtr->st_size = v;
		} else if (!strcmp(fieldName,"atime")) {
		    long v;
		    if (Tcl_GetLongFromObj(interp, val, &v) != TCL_OK) {
			returnVal = TCL_ERROR;
			break;
		    }
		    bufPtr->st_atime = v;
		} else if (!strcmp(fieldName,"mtime")) {
		    long v;
		    if (Tcl_GetLongFromObj(interp, val, &v) != TCL_OK) {
			returnVal = TCL_ERROR;
			break;
		    }
		    bufPtr->st_mtime = v;
		} else if (!strcmp(fieldName,"ctime")) {
		    long v;
		    if (Tcl_GetLongFromObj(interp, val, &v) != TCL_OK) {
			returnVal = TCL_ERROR;
			break;
		    }
		    bufPtr->st_ctime = v;
		} else if (!strcmp(fieldName,"type")) {
		    char *str;
		    str = Tcl_GetString(val);
		    if (!strcmp(str,"directory")) {
			bufPtr->st_mode |= S_IFDIR;
		    } else if (!strcmp(str,"file")) {
			bufPtr->st_mode |= S_IFREG;
#ifdef S_ISLNK
		    } else if (!strcmp(str,"link")) {
			bufPtr->st_mode |= S_IFLNK;
#endif
		    } else {
			/* 
			 * Do nothing.  This means we do not currently
			 * support anything except files and directories
			 */
		    }
		} else {
		    /* Ignore additional stat arguments */
		}
	    }
	}
    }
    
    if (returnVal != TCL_OK && returnVal != -1) {
	VfsInternalError(interp);
    }

    Tcl_RestoreResult(interp, &savedResult);
    Tcl_DecrRefCount(mountCmd);
    
    if (returnVal != TCL_OK && returnVal != -1) {
	Tcl_SetErrno(ENOENT);
        return -1;
    } else {
	return returnVal;
    }
}

static int
VfsAccess(pathPtr, mode)
    Tcl_Obj *pathPtr;		/* Path of file to access (in current CP). */
    int mode;                   /* Permission setting. */
{
    Tcl_Obj *mountCmd = NULL;
    Tcl_SavedResult savedResult;
    int returnVal;
    Tcl_Interp* interp;
    
    mountCmd = VfsBuildCommandForPath(&interp, "access", pathPtr);
    if (mountCmd == NULL) {
	return -1;
    }

    Tcl_ListObjAppendElement(interp, mountCmd, Tcl_NewIntObj(mode));
    /* Now we execute this mount point's callback. */
    Tcl_SaveResult(interp, &savedResult);
    returnVal = Tcl_EvalObjEx(interp, mountCmd, 
			      TCL_EVAL_GLOBAL | TCL_EVAL_DIRECT);
    if (returnVal != TCL_OK && returnVal != -1) {
	VfsInternalError(interp);
    }
    Tcl_RestoreResult(interp, &savedResult);
    Tcl_DecrRefCount(mountCmd);

    if (returnVal != 0) {
	Tcl_SetErrno(ENOENT);
	return -1;
    } else {
	return returnVal;
    }
}

static Tcl_Obj*
VfsGetMode(int mode) {
    Tcl_Obj *ret = Tcl_NewObj();
    if (mode & O_RDONLY) {
        Tcl_AppendToObj(ret, "r", 1);
    } else if (mode & O_WRONLY || mode & O_RDWR) {
	if (mode & O_TRUNC) {
	    Tcl_AppendToObj(ret, "w", 1);
	} else {
	    Tcl_AppendToObj(ret, "a", 1);
	}
	if (mode & O_RDWR) {
	    Tcl_AppendToObj(ret, "+", 1);
	}
    }
    return ret;
}

static Tcl_Channel
VfsOpenFileChannel(cmdInterp, pathPtr, mode, permissions)
    Tcl_Interp *cmdInterp;              /* Interpreter for error reporting;
					 * can be NULL. */
    Tcl_Obj *pathPtr;                   /* Name of file to open. */
    int mode;             		/* POSIX open mode. */
    int permissions;                    /* If the open involves creating a
					 * file, with what modes to create
					 * it? */
{
    Tcl_Channel chan = NULL;
    Tcl_Obj *mountCmd = NULL;
    Tcl_Obj *closeCallback = NULL;
    Tcl_SavedResult savedResult;
    int returnVal;
    Tcl_Interp* interp;
    
    mountCmd = VfsBuildCommandForPath(&interp, "open", pathPtr);
    if (mountCmd == NULL) {
	return NULL;
    }

    Tcl_ListObjAppendElement(interp, mountCmd, VfsGetMode(mode));
    Tcl_ListObjAppendElement(interp, mountCmd, Tcl_NewIntObj(permissions));
    Tcl_SaveResult(interp, &savedResult);
    /* Now we execute this mount point's callback. */
    returnVal = Tcl_EvalObjEx(interp, mountCmd, 
			      TCL_EVAL_GLOBAL | TCL_EVAL_DIRECT);
    if (returnVal == TCL_OK) {
	int reslen;
	Tcl_Obj *resultObj;
	/* 
	 * There may be file channel leaks on these two 
	 * error conditions, if the open command actually
	 * created a channel, but then passed us a bogus list.
	 */
	resultObj =  Tcl_GetObjResult(interp);
	if ((Tcl_ListObjLength(interp, resultObj, &reslen) == TCL_ERROR) 
	  || (reslen > 2) || (reslen == 0)) {
	    returnVal = TCL_ERROR;
	} else {
	    Tcl_Obj *element;
	    Tcl_ListObjIndex(interp, resultObj, 0, &element);
	    chan = Tcl_GetChannel(interp, Tcl_GetString(element), 0);
	    
	    if (chan == NULL) {
	        returnVal = TCL_ERROR;
	    } else {
		if (reslen == 2) {
		    Tcl_ListObjIndex(interp, resultObj, 1, &element);
		    closeCallback = element;
		    Tcl_IncrRefCount(closeCallback);
		}
	    }
	}
	Tcl_RestoreResult(interp, &savedResult);
    } else {
	/* Leave an error message if the cmdInterp is non NULL */
	if (cmdInterp != NULL) {
	    if (returnVal == -1) {
		Tcl_ResetResult(cmdInterp);
		Tcl_AppendResult(cmdInterp, "couldn't open \"", 
				 Tcl_GetString(pathPtr), "\": ",
				 Tcl_PosixError(cmdInterp), (char *) NULL);
	    } else {
		Tcl_Obj* error = Tcl_GetObjResult(interp);
		/* 
		 * Copy over the error message to cmdInterp,
		 * duplicating it in case of threading issues.
		 */
		Tcl_SetObjResult(cmdInterp, Tcl_DuplicateObj(error));
	    }
	} else {
	    /* Report any error, since otherwise it is lost */
	    if (returnVal != -1) {
		VfsInternalError(interp);
	    }
	}
	if (interp == cmdInterp) {
	    /* 
	     * We want our error message to propagate up,
	     * so we want to forget this result
	     */
	    Tcl_DiscardResult(&savedResult);
	} else {
	    Tcl_RestoreResult(interp, &savedResult);
	}
    }

    Tcl_DecrRefCount(mountCmd);

    if (chan != NULL) {
	/*
	 * We got the Channel from some Tcl code.  This means it was
	 * registered with the interpreter.  But we want a pristine
	 * channel which hasn't been registered with anyone.  We use
	 * Tcl_DetachChannel to do this for us.  We must use the
	 * correct interpreter.
	 */
	Tcl_DetachChannel(interp, chan);
	
	if (closeCallback != NULL) {
	    VfsChannelCleanupInfo *channelRet = NULL;
	    channelRet = (VfsChannelCleanupInfo*) 
			    ckalloc(sizeof(VfsChannelCleanupInfo));
	    channelRet->channel = chan;
	    channelRet->interp = interp;
	    channelRet->closeCallback = closeCallback;
	    /* The channelRet structure will be freed in the callback */
	    Tcl_CreateCloseHandler(chan, &VfsCloseProc, 
				   (ClientData)channelRet);
	}
    }
    return chan;
}

/* 
 * IMPORTANT: This procedure must *not* modify the interpreter's result
 * this leads to the objResultPtr being corrupted (somehow), and curious
 * crashes in the future (which are very hard to debug ;-).
 * 
 * This is particularly important since we are evaluating arbitrary
 * Tcl code in the callback.
 * 
 * Also note we are relying on the close-callback to occur just before
 * the channel is about to be properly closed, but after all output
 * has been flushed.  That way we can, in the callback, read in the
 * entire contents of the channel and, say, compress it for storage
 * into a tclkit or zip archive.
 */
static void 
VfsCloseProc(ClientData clientData) {
    VfsChannelCleanupInfo * channelRet = (VfsChannelCleanupInfo*) clientData;
    int returnVal;
    Tcl_SavedResult savedResult;
    Tcl_Channel chan = channelRet->channel;
    Tcl_Interp * interp = channelRet->interp;

    Tcl_SaveResult(interp, &savedResult);

    /* 
     * The interpreter needs to know about the channel, else the Tcl
     * callback will fail, so we register the channel (this allows
     * the Tcl code to use the channel's string-name).
     */
    Tcl_RegisterChannel(interp, chan);

    if (!(Tcl_GetChannelMode(chan) & TCL_READABLE)) {
	/* 
	 * We need to make this channel readable, since tclvfs
	 * documents that close callbacks are allowed to read
	 * from the channels we create.
	 */
	
	/* Currently if we reach here we have a bug */
    }
    
    returnVal = Tcl_EvalObjEx(interp, channelRet->closeCallback, 
		  TCL_EVAL_GLOBAL | TCL_EVAL_DIRECT);
    if (returnVal != TCL_OK) {
	VfsInternalError(interp);
    }
    Tcl_DecrRefCount(channelRet->closeCallback);

    /* 
     * More complications; we can't just unregister the channel,
     * because it is in the middle of being cleaned up, and the cleanup
     * code doesn't like a channel to be closed again while it is
     * already being closed.  So, we do the same trick as above to
     * unregister it without cleanup.
     */
    Tcl_DetachChannel(interp, chan);

    Tcl_RestoreResult(interp, &savedResult);
    ckfree((char*)channelRet);
}

static int
VfsMatchInDirectory(
    Tcl_Interp *cmdInterp,	/* Interpreter to receive error msgs. */
    Tcl_Obj *returnPtr,		/* Object to receive results. */
    Tcl_Obj *dirPtr,	        /* Contains path to directory to search. */
    CONST char *pattern,	/* Pattern to match against. */
    Tcl_GlobTypeData *types)	/* Object containing list of acceptable types.
				 * May be NULL. */
{
    if ((types != NULL) && (types->type & TCL_GLOB_TYPE_MOUNT)) {
	VfsMount *mountIter;
	int len;
	CONST char *prefix;

	prefix = Tcl_GetStringFromObj(Tcl_FSGetNormalizedPath(NULL, dirPtr), 
				      &len);
	if (prefix[len-1] == '/') {
	    /* 
	     * It's a root directory; we must subtract one for
	     * our comparisons below
	     */
	    len--;
	}

	Tcl_MutexLock(&vfsMountsMutex);

	/* Build list of mounts */
	mountIter = listOfMounts;
	while (mountIter != NULL) {
	    if (mountIter->mountLen > (len+1) 
		&& !strncmp(mountIter->mountPoint, prefix, (size_t)len) 
		&& mountIter->mountPoint[len] == '/'
		&& strchr(mountIter->mountPoint+len+1, '/') == NULL
		&& Tcl_StringCaseMatch(mountIter->mountPoint+len+1, 
				       pattern, 0)) {
		Tcl_Obj* mount = Tcl_NewStringObj(mountIter->mountPoint, 
						  mountIter->mountLen);
		Tcl_ListObjAppendElement(NULL, returnPtr, mount);
	    }
	    mountIter = mountIter->nextMount;
	}
	Tcl_MutexUnlock(&vfsMountsMutex);
	return TCL_OK;
    } else {
	Tcl_Obj *mountCmd = NULL;
	Tcl_SavedResult savedResult;
	int returnVal;
	Tcl_Interp* interp;
	int type = 0;
	Tcl_Obj *vfsResultPtr = NULL;
	
	mountCmd = VfsBuildCommandForPath(&interp, "matchindirectory", dirPtr);
	if (mountCmd == NULL) {
	    return -1;
	}

	if (types != NULL) {
	    type = types->type;
	}

	if (pattern == NULL) {
	    Tcl_ListObjAppendElement(interp, mountCmd, Tcl_NewObj());
	} else {
	    Tcl_ListObjAppendElement(interp, mountCmd, 
				     Tcl_NewStringObj(pattern,-1));
	}
	Tcl_ListObjAppendElement(interp, mountCmd, Tcl_NewIntObj(type));
	Tcl_SaveResult(interp, &savedResult);
	/* Now we execute this mount point's callback. */
	returnVal = Tcl_EvalObjEx(interp, mountCmd, 
				  TCL_EVAL_GLOBAL | TCL_EVAL_DIRECT);
	if (returnVal != -1) {
	    vfsResultPtr = Tcl_DuplicateObj(Tcl_GetObjResult(interp));
	}
	Tcl_RestoreResult(interp, &savedResult);
	Tcl_DecrRefCount(mountCmd);

	if (vfsResultPtr != NULL) {
	    if (returnVal == TCL_OK) {
		Tcl_IncrRefCount(vfsResultPtr);
		Tcl_ListObjAppendList(cmdInterp, returnPtr, vfsResultPtr);
		Tcl_DecrRefCount(vfsResultPtr);
	    } else {
		Tcl_SetObjResult(cmdInterp, vfsResultPtr);
	    }
	}
	return returnVal;
    }
}

static int
VfsDeleteFile(
    Tcl_Obj *pathPtr)		/* Pathname of file to be removed */
{
    Tcl_Obj *mountCmd = NULL;
    Tcl_SavedResult savedResult;
    int returnVal;
    Tcl_Interp* interp;
    
    mountCmd = VfsBuildCommandForPath(&interp, "deletefile", pathPtr);
    if (mountCmd == NULL) {
	return -1;
    }

    /* Now we execute this mount point's callback. */
    Tcl_SaveResult(interp, &savedResult);
    returnVal = Tcl_EvalObjEx(interp, mountCmd, 
			      TCL_EVAL_GLOBAL | TCL_EVAL_DIRECT);
    if (returnVal != TCL_OK && returnVal != -1) {
	VfsInternalError(interp);
    }
    Tcl_RestoreResult(interp, &savedResult);
    Tcl_DecrRefCount(mountCmd);
    return returnVal;
}

static int
VfsCreateDirectory(
    Tcl_Obj *pathPtr)		/* Pathname of directory to create */
{
    Tcl_Obj *mountCmd = NULL;
    Tcl_SavedResult savedResult;
    int returnVal;
    Tcl_Interp* interp;
    
    mountCmd = VfsBuildCommandForPath(&interp, "createdirectory", pathPtr);
    if (mountCmd == NULL) {
	return -1;
    }

    /* Now we execute this mount point's callback. */
    Tcl_SaveResult(interp, &savedResult);
    returnVal = Tcl_EvalObjEx(interp, mountCmd, 
			      TCL_EVAL_GLOBAL | TCL_EVAL_DIRECT);
    if (returnVal != TCL_OK && returnVal != -1) {
	VfsInternalError(interp);
    }
    Tcl_RestoreResult(interp, &savedResult);
    Tcl_DecrRefCount(mountCmd);
    return returnVal;
}

static int
VfsRemoveDirectory(
    Tcl_Obj *pathPtr,		/* Pathname of directory to be removed
				 * (UTF-8). */
    int recursive,		/* If non-zero, removes directories that
				 * are nonempty.  Otherwise, will only remove
				 * empty directories. */
    Tcl_Obj **errorPtr)	        /* Location to store name of file
				 * causing error. */
{
    Tcl_Obj *mountCmd = NULL;
    Tcl_SavedResult savedResult;
    int returnVal;
    Tcl_Interp* interp;
    
    mountCmd = VfsBuildCommandForPath(&interp, "removedirectory", pathPtr);
    if (mountCmd == NULL) {
	return -1;
    }

    Tcl_ListObjAppendElement(interp, mountCmd, Tcl_NewIntObj(recursive));
    /* Now we execute this mount point's callback. */
    Tcl_SaveResult(interp, &savedResult);
    returnVal = Tcl_EvalObjEx(interp, mountCmd, 
			      TCL_EVAL_GLOBAL | TCL_EVAL_DIRECT);
    if (returnVal != TCL_OK && returnVal != -1) {
	VfsInternalError(interp);
    }
    Tcl_RestoreResult(interp, &savedResult);
    Tcl_DecrRefCount(mountCmd);

    if (returnVal == TCL_ERROR) {
	/* Assume there was a problem with the directory being non-empty */
        if (errorPtr != NULL) {
            *errorPtr = pathPtr;
	    Tcl_IncrRefCount(*errorPtr);
        }
	Tcl_SetErrno(EEXIST);
    }
    return returnVal;
}

static CONST char**
VfsFileAttrStrings(pathPtr, objPtrRef)
    Tcl_Obj* pathPtr;
    Tcl_Obj** objPtrRef;
{
    Tcl_Obj *mountCmd = NULL;
    Tcl_SavedResult savedResult;
    int returnVal;
    Tcl_Interp* interp;
    
    mountCmd = VfsBuildCommandForPath(&interp, "fileattributes", pathPtr);
    if (mountCmd == NULL) {
	*objPtrRef = NULL;
	return NULL;
    }

    Tcl_SaveResult(interp, &savedResult);
    /* Now we execute this mount point's callback. */
    returnVal = Tcl_EvalObjEx(interp, mountCmd, 
			      TCL_EVAL_GLOBAL | TCL_EVAL_DIRECT);
    if (returnVal != TCL_OK && returnVal != -1) {
	VfsInternalError(interp);
    }
    if (returnVal == TCL_OK) {
	*objPtrRef = Tcl_DuplicateObj(Tcl_GetObjResult(interp));
    } else {
	*objPtrRef = NULL;
    }
    Tcl_RestoreResult(interp, &savedResult);
    Tcl_DecrRefCount(mountCmd);
    return NULL;
}

static int
VfsFileAttrsGet(cmdInterp, index, pathPtr, objPtrRef)
    Tcl_Interp *cmdInterp;	/* The interpreter for error reporting. */
    int index;			/* index of the attribute command. */
    Tcl_Obj *pathPtr;		/* filename we are operating on. */
    Tcl_Obj **objPtrRef;	/* for output. */
{
    Tcl_Obj *mountCmd = NULL;
    Tcl_SavedResult savedResult;
    int returnVal;
    Tcl_Interp* interp;
    
    mountCmd = VfsBuildCommandForPath(&interp, "fileattributes", pathPtr);
    if (mountCmd == NULL) {
	return -1;
    }

    Tcl_ListObjAppendElement(interp, mountCmd, Tcl_NewIntObj(index));
    Tcl_SaveResult(interp, &savedResult);
    /* Now we execute this mount point's callback. */
    returnVal = Tcl_EvalObjEx(interp, mountCmd, 
			      TCL_EVAL_GLOBAL | TCL_EVAL_DIRECT);
    if (returnVal != -1) {
	*objPtrRef = Tcl_DuplicateObj(Tcl_GetObjResult(interp));
    }
    Tcl_RestoreResult(interp, &savedResult);
    Tcl_DecrRefCount(mountCmd);
    
    if (returnVal != -1) {
	if (returnVal == TCL_OK) {
	    /* 
	     * Our caller expects a ref count of zero in
	     * the returned object pointer.
	     */
	} else {
	    /* Leave error message in correct interp */
	    if (cmdInterp != NULL) {
		Tcl_SetObjResult(cmdInterp, *objPtrRef);
	    } else {
		Tcl_DecrRefCount(*objPtrRef);
	    }
	    *objPtrRef = NULL;
	}
    } else {
	if (cmdInterp != NULL) {
	    Tcl_ResetResult(cmdInterp);
	    Tcl_AppendResult(cmdInterp, "couldn't read attributes for \"", 
			     Tcl_GetString(pathPtr), "\": ",
			     Tcl_PosixError(cmdInterp), (char *) NULL);
	}
    }
    
    return returnVal;
}

static int
VfsFileAttrsSet(cmdInterp, index, pathPtr, objPtr)
    Tcl_Interp *cmdInterp;	/* The interpreter for error reporting. */
    int index;			/* index of the attribute command. */
    Tcl_Obj *pathPtr;		/* filename we are operating on. */
    Tcl_Obj *objPtr;		/* for input. */
{
    Tcl_Obj *mountCmd = NULL;
    Tcl_SavedResult savedResult;
    int returnVal;
    Tcl_Interp* interp;
    Tcl_Obj *errorPtr = NULL;
    
    mountCmd = VfsBuildCommandForPath(&interp, "fileattributes", pathPtr);
    if (mountCmd == NULL) {
	return -1;
    }

    Tcl_ListObjAppendElement(interp, mountCmd, Tcl_NewIntObj(index));
    Tcl_ListObjAppendElement(interp, mountCmd, objPtr);
    Tcl_SaveResult(interp, &savedResult);
    /* Now we execute this mount point's callback. */
    returnVal = Tcl_EvalObjEx(interp, mountCmd, 
			      TCL_EVAL_GLOBAL | TCL_EVAL_DIRECT);
    if (returnVal != -1 && returnVal != TCL_OK) {
	errorPtr = Tcl_DuplicateObj(Tcl_GetObjResult(interp));
    }

    Tcl_RestoreResult(interp, &savedResult);
    Tcl_DecrRefCount(mountCmd);
    
    if (cmdInterp != NULL) {
	if (returnVal == -1) {
	    Tcl_ResetResult(cmdInterp);
	    Tcl_AppendResult(cmdInterp, "couldn't set attributes for \"", 
			     Tcl_GetString(pathPtr), "\": ",
			     Tcl_PosixError(cmdInterp), (char *) NULL);
	} else if (errorPtr != NULL) {
	    /* 
	     * Leave error message in correct interp, errorPtr was
	     * duplicated above, in case of threading issues.
	     */
	    Tcl_SetObjResult(cmdInterp, errorPtr);
	}
    } else if (errorPtr != NULL) {
	Tcl_DecrRefCount(errorPtr);
    }
    return returnVal;
}

static int 
VfsUtime(pathPtr, tval)
    Tcl_Obj* pathPtr;
    struct utimbuf *tval;
{
    Tcl_Obj *mountCmd = NULL;
    Tcl_SavedResult savedResult;
    int returnVal;
    Tcl_Interp* interp;
    
    mountCmd = VfsBuildCommandForPath(&interp, "utime", pathPtr);
    if (mountCmd == NULL) {
	return -1;
    }

    Tcl_ListObjAppendElement(interp, mountCmd, Tcl_NewLongObj(tval->actime));
    Tcl_ListObjAppendElement(interp, mountCmd, Tcl_NewLongObj(tval->modtime));
    /* Now we execute this mount point's callback. */
    Tcl_SaveResult(interp, &savedResult);
    returnVal = Tcl_EvalObjEx(interp, mountCmd, 
			      TCL_EVAL_GLOBAL | TCL_EVAL_DIRECT);
    if (returnVal != TCL_OK && returnVal != -1) {
	VfsInternalError(interp);
    }
    Tcl_RestoreResult(interp, &savedResult);
    Tcl_DecrRefCount(mountCmd);

    return returnVal;
}

static Tcl_Obj*
VfsListVolumes(void)
{
    Tcl_Obj *retVal;

    Tcl_MutexLock(&vfsVolumesMutex);
    if (vfsVolumes != NULL) {
	Tcl_IncrRefCount(vfsVolumes);
	retVal = vfsVolumes;
    } else {
	retVal = NULL;
    }
    Tcl_MutexUnlock(&vfsVolumesMutex);
    
    return retVal;
}

static void
Vfs_AddVolume(volume)
    Tcl_Obj *volume;
{
    Tcl_MutexLock(&vfsVolumesMutex);
    
    if (vfsVolumes == NULL) {
        vfsVolumes = Tcl_NewObj();
	Tcl_IncrRefCount(vfsVolumes);
    } else {
	if (Tcl_IsShared(vfsVolumes)) {
	    /* 
	     * Another thread is using this object, so we duplicate the
	     * object and reduce the refCount on the shared one.
	     */
	    Tcl_Obj *oldVols = vfsVolumes;
	    vfsVolumes = Tcl_DuplicateObj(oldVols);
	    Tcl_IncrRefCount(vfsVolumes);
	    Tcl_DecrRefCount(oldVols);
	}
    }
    Tcl_ListObjAppendElement(NULL, vfsVolumes, volume);
    
    Tcl_MutexUnlock(&vfsVolumesMutex);
}

static int
Vfs_RemoveVolume(volume)
    Tcl_Obj *volume;
{
    int i, len;

    Tcl_MutexLock(&vfsVolumesMutex);

    Tcl_ListObjLength(NULL, vfsVolumes, &len);
    for (i = 0;i < len; i++) {
	Tcl_Obj *vol;
        Tcl_ListObjIndex(NULL, vfsVolumes, i, &vol);
	if (!strcmp(Tcl_GetString(vol),Tcl_GetString(volume))) {
	    /* It's in the list, at index i */
	    if (len == 1) {
		/* An optimization here */
		Tcl_DecrRefCount(vfsVolumes);
		vfsVolumes = NULL;
	    } else {
		/* Make ourselves the unique owner */
		if (Tcl_IsShared(vfsVolumes)) {
		    Tcl_Obj *oldVols = vfsVolumes;
		    vfsVolumes = Tcl_DuplicateObj(oldVols);
		    Tcl_IncrRefCount(vfsVolumes);
		    Tcl_DecrRefCount(oldVols);
		}
		/* Remove the element */
		Tcl_ListObjReplace(NULL, vfsVolumes, i, 1, 0, NULL);
		Tcl_MutexUnlock(&vfsVolumesMutex);
		return TCL_OK;
	    }
	}
    }
    Tcl_MutexUnlock(&vfsVolumesMutex);

    return TCL_ERROR;
}


/*
 *----------------------------------------------------------------------
 *
 * VfsBuildCommandForPath --
 *
 *	Given a path object which we know belongs to the vfs, and a 
 *	command string (one of the standard filesystem operations
 *	"stat", "matchindirectory" etc), build the standard vfs
 *	Tcl command and arguments to carry out that operation.
 *	
 *	If the command is successfully built, it is returned to the
 *	caller with a refCount of 1.  The caller also needs to know
 *	which Tcl interpreter to evaluate the command in; this
 *	is returned in the 'iRef' provided.
 *	
 *	Each mount-point dictates a command prefix to use for a 
 *	particular file.  We start with that and then add 4 parameters,
 *	as follows:
 *	
 *	(1) the 'cmd' to use
 *	(2) the mount point of this path (which is the portion of the
 *	path string which lies outside the vfs).
 *	(3) the remainder of the path which lies inside the vfs
 *	(4) the original (possibly unnormalized) path string used
 *	in the command.
 *	
 *	Example (i):
 *	
 *	If 'C:/Apps/data.zip' is mounted on top of
 *	itself, then if we do:
 *	
 *	cd C:/Apps
 *	file exists data.zip/foo/bar.txt
 *	
 *	this will lead to:
 *	
 *	<mountcmd> "access" C:/Apps/data.zip foo/bar.txt data.zip/foo/bar.txt
 *	
 *	Example (ii)
 *	
 *	If 'ftp://' is mounted as a new volume,
 *	then 'glob -dir ftp://ftp.scriptics.com *' will lead to:
 *	
 *	<mountcmd> "matchindirectory" ftp:// ftp.scriptics.com \
 *	  ftp://ftp.scriptics.com
 *	  
 *	
 * Results:
 *	Returns a list containing the command, or NULL if an
 *	error occurred.  If the interpreter for this vfs command
 *	is in the process of being deleted, we always return NULL.
 *
 * Side effects:
 *	None except memory allocation.
 *
 *----------------------------------------------------------------------
 */

static Tcl_Obj* 
VfsBuildCommandForPath(Tcl_Interp **iRef, CONST char* cmd, Tcl_Obj *pathPtr) {
    Tcl_Obj *normed;
    Tcl_Obj *mountCmd;
    int len;
    int splitPosition;
    int dummyLen;
    VfsNativeRep *nativeRep;
    Tcl_Interp *interp;
    
    char *normedString;

    nativeRep = VfsGetNativePath(pathPtr);
    if (nativeRep == NULL) {
	return NULL;
    }
    
    interp = nativeRep->fsCmd->interp;
    
    if (Tcl_InterpDeleted(interp)) {
        return NULL;
    }
    
    splitPosition = nativeRep->splitPosition;
    normed = Tcl_FSGetNormalizedPath(NULL, pathPtr);
    normedString = Tcl_GetStringFromObj(normed, &len);
    
    mountCmd = Tcl_DuplicateObj(nativeRep->fsCmd->mountCmd);
    Tcl_IncrRefCount(mountCmd);
    if (Tcl_ListObjLength(NULL, mountCmd, &dummyLen) == TCL_ERROR) {
	Tcl_DecrRefCount(mountCmd);
	return NULL;
    }
    Tcl_ListObjAppendElement(NULL, mountCmd, Tcl_NewStringObj(cmd,-1));
    if (splitPosition == len) {
	Tcl_ListObjAppendElement(NULL, mountCmd, normed);
	Tcl_ListObjAppendElement(NULL, mountCmd, Tcl_NewStringObj("",0));
    } else {
	Tcl_ListObjAppendElement(NULL, mountCmd, 
		Tcl_NewStringObj(normedString,splitPosition));
	if ((normedString[splitPosition] != VFS_SEPARATOR) 
	    || (VFS_SEPARATOR ==':')) {
	    /* This will occur if we mount 'ftp://' */
	    splitPosition--;
	}
	Tcl_ListObjAppendElement(NULL, mountCmd, 
		Tcl_NewStringObj(normedString+splitPosition+1,
				 len-splitPosition-1));
    }
    Tcl_ListObjAppendElement(NULL, mountCmd, pathPtr);

    if (iRef != NULL) {
        *iRef = interp;
    }
    
    return mountCmd;
}

static void 
VfsExitProc(ClientData clientData)
{
    Tcl_FSUnregister(&vfsFilesystem);
    /* 
     * This is probably no longer needed, because each individual
     * interp's cleanup will trigger removal of all volumes which
     * belong to it.
     */
    if (vfsVolumes != NULL) {
        Tcl_DecrRefCount(vfsVolumes);
	vfsVolumes = NULL;
    }
}