Debian Codegraph @

pTk/mTk/tclGeneric/tclIOUtil.c

raw symbols SCIP
1 /*
2 * tclIOUtil.c --
3 *
4 * This file contains the implementation of Tcl's generic
5 * filesystem code, which supports a pluggable filesystem
6 * architecture allowing both platform specific filesystems and
7 * 'virtual filesystems'. All filesystem access should go through
8 * the functions defined in this file. Most of this code was
9 * contributed by Vince Darley.
10 *
11 * Parts of this file are based on code contributed by Karl
12 * Lehenbauer, Mark Diekhans and Peter da Silva.
13 *
14 * Copyright (c) 1991-1994 The Regents of the University of California.
15 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
16 *
17 * See the file "license.terms" for information on usage and redistribution
18 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
19 *
20 * RCS: @(#) $Id: tclIOUtil.c,v 1.77.2.12 2003/11/20 19:05:44 vincentdarley Exp $
21 */
22
23 #include "tclInt.h"
24 #include "tclPort.h"
25 #ifdef MAC_TCL
26 #include "tclMacInt.h"
27 #endif
28 #ifdef __WIN32__
29 /* for tclWinProcs->useWide */
30 #include "tclWinInt.h"
31 #endif
32
33 /*
34 * struct FilesystemRecord --
35 *
36 * A filesystem record is used to keep track of each
37 * filesystem currently registered with the core,
38 * in a linked list. Pointers to these structures
39 * are also kept by each "path" Tcl_Obj, and we must
40 * retain a refCount on the number of such references.
41 */
42 typedef struct FilesystemRecord {
43 ClientData clientData; /* Client specific data for the new
44 * filesystem (can be NULL) */
45 Tcl_Filesystem *fsPtr; /* Pointer to filesystem dispatch
46 * table. */
47 int fileRefCount; /* How many Tcl_Obj's use this
48 * filesystem. */
49 struct FilesystemRecord *nextPtr;
50 /* The next filesystem registered
51 * to Tcl, or NULL if no more. */
52 struct FilesystemRecord *prevPtr;
53 /* The previous filesystem registered
54 * to Tcl, or NULL if no more. */
55 } FilesystemRecord;
56
57 /*
58 * The internal TclFS API provides routines for handling and
59 * manipulating paths efficiently, taking direct advantage of
60 * the "path" Tcl_Obj type.
61 *
62 * These functions are not exported at all at present.
63 */
64
65 int TclFSCwdPointerEquals _ANSI_ARGS_((Tcl_Obj* objPtr));
66 int TclFSMakePathFromNormalized _ANSI_ARGS_((Tcl_Interp *interp,
67 Tcl_Obj *objPtr, ClientData clientData));
68 int TclFSNormalizeToUniquePath _ANSI_ARGS_((Tcl_Interp *interp,
69 Tcl_Obj *pathPtr, int startAt, ClientData *clientDataPtr));
70 Tcl_Obj* TclFSMakePathRelative _ANSI_ARGS_((Tcl_Interp *interp,
71 Tcl_Obj *objPtr, Tcl_Obj *cwdPtr));
72 Tcl_Obj* TclFSInternalToNormalized _ANSI_ARGS_((
73 Tcl_Filesystem *fromFilesystem, ClientData clientData,
74 FilesystemRecord **fsRecPtrPtr));
75 int TclFSEnsureEpochOk _ANSI_ARGS_((Tcl_Obj* pathObjPtr,
76 Tcl_Filesystem **fsPtrPtr));
77 void TclFSSetPathDetails _ANSI_ARGS_((Tcl_Obj *pathObjPtr,
78 FilesystemRecord *fsRecPtr, ClientData clientData));
79
80 /*
81 * Private variables for use in this file
82 */
83 extern Tcl_Filesystem tclNativeFilesystem;
84 extern int theFilesystemEpoch;
85
86 /*
87 * Private functions for use in this file
88 */
89 Tcl_PathType FSGetPathType _ANSI_ARGS_((Tcl_Obj *pathObjPtr,
90 Tcl_Filesystem **filesystemPtrPtr,
91 int *driveNameLengthPtr));
92 Tcl_PathType GetPathType _ANSI_ARGS_((Tcl_Obj *pathObjPtr,
93 Tcl_Filesystem **filesystemPtrPtr,
94 int *driveNameLengthPtr, Tcl_Obj **driveNameRef));
95 Tcl_FSPathInFilesystemProc NativePathInFilesystem;
96 static Tcl_Obj* TclFSNormalizeAbsolutePath
97 _ANSI_ARGS_((Tcl_Interp* interp, Tcl_Obj *pathPtr,
98 ClientData *clientDataPtr));
99 /*
100 * Prototypes for procedures defined later in this file.
101 */
102
103 static FilesystemRecord* FsGetFirstFilesystem(void);
104 static void FsThrExitProc(ClientData cd);
105 static Tcl_Obj* FsListMounts _ANSI_ARGS_((Tcl_Obj *pathPtr,
106 CONST char *pattern));
107 static Tcl_Obj* FsAddMountsToGlobResult _ANSI_ARGS_((Tcl_Obj *result,
108 Tcl_Obj *pathPtr, CONST char *pattern, Tcl_GlobTypeData *types));
109
110 #ifdef TCL_THREADS
111 static void FsRecacheFilesystemList(void);
112 #endif
113
114 /*
115 * These form part of the native filesystem support. They are needed
116 * here because we have a few native filesystem functions (which are
117 * the same for mac/win/unix) in this file. There is no need to place
118 * them in tclInt.h, because they are not (and should not be) used
119 * anywhere else.
120 */
121 extern CONST char * tclpFileAttrStrings[];
122 extern CONST TclFileAttrProcs tclpFileAttrProcs[];
123
124 /*
125 * The following functions are obsolete string based APIs, and should
126 * be removed in a future release (Tcl 9 would be a good time).
127 */
128
129 /* Obsolete */
130 int
131 Tcl_Stat(path, oldStyleBuf)
132 CONST char *path; /* Path of file to stat (in current CP). */
133 struct stat *oldStyleBuf; /* Filled with results of stat call. */
134 {
135 int ret;
136 Tcl_StatBuf buf;
137 Tcl_Obj *pathPtr = Tcl_NewStringObj(path,-1);
138
139 Tcl_IncrRefCount(pathPtr);
140 ret = Tcl_FSStat(pathPtr, &buf);
141 Tcl_DecrRefCount(pathPtr);
142 if (ret != -1) {
143 #ifndef TCL_WIDE_INT_IS_LONG
144 # define OUT_OF_RANGE(x) \
145 (((Tcl_WideInt)(x)) < Tcl_LongAsWide(LONG_MIN) || \
146 ((Tcl_WideInt)(x)) > Tcl_LongAsWide(LONG_MAX))
147 # define OUT_OF_URANGE(x) \
148 (((Tcl_WideUInt)(x)) > (Tcl_WideUInt)ULONG_MAX)
149
150 /*
151 * Perform the result-buffer overflow check manually.
152 *
153 * Note that ino_t/ino64_t is unsigned...
154 */
155
156 if (OUT_OF_URANGE(buf.st_ino) || OUT_OF_RANGE(buf.st_size)
157 #ifdef HAVE_ST_BLOCKS
158 || OUT_OF_RANGE(buf.st_blocks)
159 #endif
160 ) {
161 #ifdef EFBIG
162 errno = EFBIG;
163 #else
164 # ifdef EOVERFLOW
165 errno = EOVERFLOW;
166 # else
167 # error "What status should be returned for file size out of range?"
168 # endif
169 #endif
170 return -1;
171 }
172
173 # undef OUT_OF_RANGE
174 # undef OUT_OF_URANGE
175 #endif /* !TCL_WIDE_INT_IS_LONG */
176
177 /*
178 * Copy across all supported fields, with possible type
179 * coercions on those fields that change between the normal
180 * and lf64 versions of the stat structure (on Solaris at
181 * least.) This is slow when the structure sizes coincide,
182 * but that's what you get for using an obsolete interface.
183 */
184
185 oldStyleBuf->st_mode = buf.st_mode;
186 oldStyleBuf->st_ino = (ino_t) buf.st_ino;
187 oldStyleBuf->st_dev = buf.st_dev;
188 oldStyleBuf->st_rdev = buf.st_rdev;
189 oldStyleBuf->st_nlink = buf.st_nlink;
190 oldStyleBuf->st_uid = buf.st_uid;
191 oldStyleBuf->st_gid = buf.st_gid;
192 oldStyleBuf->st_size = (off_t) buf.st_size;
193 oldStyleBuf->st_atime = buf.st_atime;
194 oldStyleBuf->st_mtime = buf.st_mtime;
195 oldStyleBuf->st_ctime = buf.st_ctime;
196 #ifdef HAVE_ST_BLOCKS
197 oldStyleBuf->st_blksize = buf.st_blksize;
198 oldStyleBuf->st_blocks = (blkcnt_t) buf.st_blocks;
199 #endif
200 }
201 return ret;
202 }
203
204 /* Obsolete */
205 int
206 Tcl_Access(path, mode)
207 CONST char *path; /* Path of file to access (in current CP). */
208 int mode; /* Permission setting. */
209 {
210 int ret;
211 Tcl_Obj *pathPtr = Tcl_NewStringObj(path,-1);
212 Tcl_IncrRefCount(pathPtr);
213 ret = Tcl_FSAccess(pathPtr,mode);
214 Tcl_DecrRefCount(pathPtr);
215 return ret;
216 }
217
218 /* Obsolete */
219 Tcl_Channel
220 Tcl_OpenFileChannel(interp, path, modeString, permissions)
221 Tcl_Interp *interp; /* Interpreter for error reporting;
222 * can be NULL. */
223 CONST char *path; /* Name of file to open. */
224 CONST char *modeString; /* A list of POSIX open modes or
225 * a string such as "rw". */
226 int permissions; /* If the open involves creating a
227 * file, with what modes to create
228 * it? */
229 {
230 Tcl_Channel ret;
231 Tcl_Obj *pathPtr = Tcl_NewStringObj(path,-1);
232 Tcl_IncrRefCount(pathPtr);
233 ret = Tcl_FSOpenFileChannel(interp, pathPtr, modeString, permissions);
234 Tcl_DecrRefCount(pathPtr);
235 return ret;
236
237 }
238
239 /* Obsolete */
240 int
241 Tcl_Chdir(dirName)
242 CONST char *dirName;
243 {
244 int ret;
245 Tcl_Obj *pathPtr = Tcl_NewStringObj(dirName,-1);
246 Tcl_IncrRefCount(pathPtr);
247 ret = Tcl_FSChdir(pathPtr);
248 Tcl_DecrRefCount(pathPtr);
249 return ret;
250 }
251
252 /* Obsolete */
253 char *
254 Tcl_GetCwd(interp, cwdPtr)
255 Tcl_Interp *interp;
256 Tcl_DString *cwdPtr;
257 {
258 Tcl_Obj *cwd;
259 cwd = Tcl_FSGetCwd(interp);
260 if (cwd == NULL) {
261 return NULL;
262 } else {
263 Tcl_DStringInit(cwdPtr);
264 Tcl_DStringAppend(cwdPtr, Tcl_GetString(cwd), -1);
265 Tcl_DecrRefCount(cwd);
266 return Tcl_DStringValue(cwdPtr);
267 }
268 }
269
270 /* Obsolete */
271 int
272 Tcl_EvalFile(interp, fileName)
273 Tcl_Interp *interp; /* Interpreter in which to process file. */
274 CONST char *fileName; /* Name of file to process. Tilde-substitution
275 * will be performed on this name. */
276 {
277 int ret;
278 Tcl_Obj *pathPtr = Tcl_NewStringObj(fileName,-1);
279 Tcl_IncrRefCount(pathPtr);
280 ret = Tcl_FSEvalFile(interp, pathPtr);
281 Tcl_DecrRefCount(pathPtr);
282 return ret;
283 }
284
285
286 /*
287 * The 3 hooks for Stat, Access and OpenFileChannel are obsolete. The
288 * complete, general hooked filesystem APIs should be used instead.
289 * This define decides whether to include the obsolete hooks and
290 * related code. If these are removed, we'll also want to remove them
291 * from stubs/tclInt. The only known users of these APIs are prowrap
292 * and mktclapp. New code/extensions should not use them, since they
293 * do not provide as full support as the full filesystem API.
294 *
295 * As soon as prowrap and mktclapp are updated to use the full
296 * filesystem support, I suggest all these hooks are removed.
297 */
298 #define USE_OBSOLETE_FS_HOOKS
299
300
301 #ifdef USE_OBSOLETE_FS_HOOKS
302 /*
303 * The following typedef declarations allow for hooking into the chain
304 * of functions maintained for 'Tcl_Stat(...)', 'Tcl_Access(...)' &
305 * 'Tcl_OpenFileChannel(...)'. Basically for each hookable function
306 * a linked list is defined.
307 */
308
309 typedef struct StatProc {
310 TclStatProc_ *proc; /* Function to process a 'stat()' call */
311 struct StatProc *nextPtr; /* The next 'stat()' function to call */
312 } StatProc;
313
314 typedef struct AccessProc {
315 TclAccessProc_ *proc; /* Function to process a 'access()' call */
316 struct AccessProc *nextPtr; /* The next 'access()' function to call */
317 } AccessProc;
318
319 typedef struct OpenFileChannelProc {
320 TclOpenFileChannelProc_ *proc; /* Function to process a
321 * 'Tcl_OpenFileChannel()' call */
322 struct OpenFileChannelProc *nextPtr;
323 /* The next 'Tcl_OpenFileChannel()'
324 * function to call */
325 } OpenFileChannelProc;
326
327 /*
328 * For each type of (obsolete) hookable function, a static node is
329 * declared to hold the function pointer for the "built-in" routine
330 * (e.g. 'TclpStat(...)') and the respective list is initialized as a
331 * pointer to that node.
332 *
333 * The "delete" functions (e.g. 'TclStatDeleteProc(...)') ensure that
334 * these statically declared list entry cannot be inadvertently removed.
335 *
336 * This method avoids the need to call any sort of "initialization"
337 * function.
338 *
339 * All three lists are protected by a global obsoleteFsHookMutex.
340 */
341
342 static StatProc *statProcList = NULL;
343 static AccessProc *accessProcList = NULL;
344 static OpenFileChannelProc *openFileChannelProcList = NULL;
345
346 TCL_DECLARE_MUTEX(obsoleteFsHookMutex)
347
348 #endif /* USE_OBSOLETE_FS_HOOKS */
349
350 /*
351 * Declare the native filesystem support. These functions should
352 * be considered private to Tcl, and should really not be called
353 * directly by any code other than this file (i.e. neither by
354 * Tcl's core nor by extensions). Similarly, the old string-based
355 * Tclp... native filesystem functions should not be called.
356 *
357 * The correct API to use now is the Tcl_FS... set of functions,
358 * which ensure correct and complete virtual filesystem support.
359 *
360 * We cannot make all of these static, since some of them
361 * are implemented in the platform-specific directories.
362 */
363 static Tcl_FSFilesystemSeparatorProc NativeFilesystemSeparator;
364 static Tcl_FSFreeInternalRepProc NativeFreeInternalRep;
365 Tcl_FSDupInternalRepProc NativeDupInternalRep;
366 static Tcl_FSCreateInternalRepProc NativeCreateNativeRep;
367 static Tcl_FSFileAttrStringsProc NativeFileAttrStrings;
368 static Tcl_FSFileAttrsGetProc NativeFileAttrsGet;
369 static Tcl_FSFileAttrsSetProc NativeFileAttrsSet;
370
371 /*
372 * The only reason these functions are not static is that they
373 * are either called by code in the native (win/unix/mac) directories
374 * or they are actually implemented in those directories. They
375 * should simply not be called by code outside Tcl's native
376 * filesystem core. i.e. they should be considered 'static' to
377 * Tcl's filesystem code (if we ever built the native filesystem
378 * support into a separate code library, this could actually be
379 * enforced).
380 */
381 Tcl_FSFilesystemPathTypeProc TclpFilesystemPathType;
382 Tcl_FSInternalToNormalizedProc TclpNativeToNormalized;
383 Tcl_FSStatProc TclpObjStat;
384 Tcl_FSAccessProc TclpObjAccess;
385 Tcl_FSMatchInDirectoryProc TclpMatchInDirectory;
386 Tcl_FSGetCwdProc TclpObjGetCwd;
387 Tcl_FSChdirProc TclpObjChdir;
388 Tcl_FSLstatProc TclpObjLstat;
389 Tcl_FSCopyFileProc TclpObjCopyFile;
390 Tcl_FSDeleteFileProc TclpObjDeleteFile;
391 Tcl_FSRenameFileProc TclpObjRenameFile;
392 Tcl_FSCreateDirectoryProc TclpObjCreateDirectory;
393 Tcl_FSCopyDirectoryProc TclpObjCopyDirectory;
394 Tcl_FSRemoveDirectoryProc TclpObjRemoveDirectory;
395 Tcl_FSUnloadFileProc TclpUnloadFile;
396 Tcl_FSLinkProc TclpObjLink;
397 Tcl_FSListVolumesProc TclpObjListVolumes;
398
399 /*
400 * Define the native filesystem dispatch table. If necessary, it
401 * is ok to make this non-static, but it should only be accessed
402 * by the functions actually listed within it (or perhaps other
403 * helper functions of them). Anything which is not part of this
404 * 'native filesystem implementation' should not be delving inside
405 * here!
406 */
407 Tcl_Filesystem tclNativeFilesystem = {
408 "native",
409 sizeof(Tcl_Filesystem),
410 TCL_FILESYSTEM_VERSION_1,
411 &NativePathInFilesystem,
412 &NativeDupInternalRep,
413 &NativeFreeInternalRep,
414 &TclpNativeToNormalized,
415 &NativeCreateNativeRep,
416 &TclpObjNormalizePath,
417 &TclpFilesystemPathType,
418 &NativeFilesystemSeparator,
419 &TclpObjStat,
420 &TclpObjAccess,
421 &TclpOpenFileChannel,
422 &TclpMatchInDirectory,
423 &TclpUtime,
424 #ifndef S_IFLNK
425 NULL,
426 #else
427 &TclpObjLink,
428 #endif /* S_IFLNK */
429 &TclpObjListVolumes,
430 &NativeFileAttrStrings,
431 &NativeFileAttrsGet,
432 &NativeFileAttrsSet,
433 &TclpObjCreateDirectory,
434 &TclpObjRemoveDirectory,
435 &TclpObjDeleteFile,
436 &TclpObjCopyFile,
437 &TclpObjRenameFile,
438 &TclpObjCopyDirectory,
439 &TclpObjLstat,
440 &TclpDlopen,
441 &TclpObjGetCwd,
442 &TclpObjChdir
443 };
444
445 /*
446 * Define the tail of the linked list. Note that for unconventional
447 * uses of Tcl without a native filesystem, we may in the future wish
448 * to modify the current approach of hard-coding the native filesystem
449 * in the lookup list 'filesystemList' below.
450 *
451 * We initialize the record so that it thinks one file uses it. This
452 * means it will never be freed.
453 */
454 static FilesystemRecord nativeFilesystemRecord = {
455 NULL,
456 &tclNativeFilesystem,
457 1,
458 NULL
459 };
460
461 /*
462 * This is incremented each time we modify the linked list of
463 * filesystems. Any time it changes, all cached filesystem
464 * representations are suspect and must be freed.
465 * For multithreading builds, change of the filesystem epoch
466 * will trigger cache cleanup in all threads.
467 */
468 int theFilesystemEpoch = 0;
469
470 /*
471 * Stores the linked list of filesystems. A 1:1 copy of this
472 * list is also maintained in the TSD for each thread. This
473 * is to avoid synchronization issues.
474 */
475 static FilesystemRecord *filesystemList = &nativeFilesystemRecord;
476
477 TCL_DECLARE_MUTEX(filesystemMutex)
478
479 /*
480 * Used to implement Tcl_FSGetCwd in a file-system independent way.
481 */
482 static Tcl_Obj* cwdPathPtr = NULL;
483 static int cwdPathEpoch = 0;
484 TCL_DECLARE_MUTEX(cwdMutex)
485
486 /*
487 * This structure holds per-thread private copies of
488 * some global data. This way we avoid most of the
489 * synchronization calls which boosts performance, at
490 * cost of having to update this information each
491 * time the corresponding epoch counter changes.
492 *
493 */
494 typedef struct ThreadSpecificData {
495 int initialized;
496 int cwdPathEpoch;
497 int filesystemEpoch;
498 Tcl_Obj *cwdPathPtr;
499 FilesystemRecord *filesystemList;
500 } ThreadSpecificData;
501
502 Tcl_ThreadDataKey dataKey;
503
504 /*
505 * Declare fallback support function and
506 * information for Tcl_FSLoadFile
507 */
508 static Tcl_FSUnloadFileProc FSUnloadTempFile;
509
510 /*
511 * One of these structures is used each time we successfully load a
512 * file from a file system by way of making a temporary copy of the
513 * file on the native filesystem. We need to store both the actual
514 * unloadProc/clientData combination which was used, and the original
515 * and modified filenames, so that we can correctly undo the entire
516 * operation when we want to unload the code.
517 */
518 typedef struct FsDivertLoad {
519 Tcl_LoadHandle loadHandle;
520 Tcl_FSUnloadFileProc *unloadProcPtr;
521 Tcl_Obj *divertedFile;
522 Tcl_Filesystem *divertedFilesystem;
523 ClientData divertedFileNativeRep;
524 } FsDivertLoad;
525
526 /* Now move on to the basic filesystem implementation */
527
528 static void
529 FsThrExitProc(cd)
530 ClientData cd;
531 {
532 ThreadSpecificData *tsdPtr = (ThreadSpecificData*)cd;
533 FilesystemRecord *fsRecPtr = NULL, *tmpFsRecPtr = NULL;
534
535 /* Trash the cwd copy */
536 if (tsdPtr->cwdPathPtr != NULL) {
537 Tcl_DecrRefCount(tsdPtr->cwdPathPtr);
538 }
539 /* Trash the filesystems cache */
540 fsRecPtr = tsdPtr->filesystemList;
541 while (fsRecPtr != NULL) {
542 tmpFsRecPtr = fsRecPtr->nextPtr;
543 if (--fsRecPtr->fileRefCount <= 0) {
544 ckfree((char *)fsRecPtr);
545 }
546 fsRecPtr = tmpFsRecPtr;
547 }
548 }
549
550 int
551 TclFSCwdPointerEquals(objPtr)
552 Tcl_Obj* objPtr;
553 {
554 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
555
556 Tcl_MutexLock(&cwdMutex);
557 if (tsdPtr->cwdPathPtr == NULL) {
558 if (cwdPathPtr == NULL) {
559 tsdPtr->cwdPathPtr = NULL;
560 } else {
561 tsdPtr->cwdPathPtr = Tcl_DuplicateObj(cwdPathPtr);
562 Tcl_IncrRefCount(tsdPtr->cwdPathPtr);
563 }
564 tsdPtr->cwdPathEpoch = cwdPathEpoch;
565 } else if (tsdPtr->cwdPathEpoch != cwdPathEpoch) {
566 Tcl_DecrRefCount(tsdPtr->cwdPathPtr);
567 if (cwdPathPtr == NULL) {
568 tsdPtr->cwdPathPtr = NULL;
569 } else {
570 tsdPtr->cwdPathPtr = Tcl_DuplicateObj(cwdPathPtr);
571 Tcl_IncrRefCount(tsdPtr->cwdPathPtr);
572 }
573 }
574 Tcl_MutexUnlock(&cwdMutex);
575
576 if (tsdPtr->initialized == 0) {
577 Tcl_CreateThreadExitHandler(FsThrExitProc, (ClientData)tsdPtr);
578 tsdPtr->initialized = 1;
579 }
580 return (tsdPtr->cwdPathPtr == objPtr);
581 }
582 #ifdef TCL_THREADS
583
584 static void
585 FsRecacheFilesystemList(void)
586 {
587 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
588 FilesystemRecord *fsRecPtr, *tmpFsRecPtr = NULL;
589
590 /* Trash the current cache */
591 fsRecPtr = tsdPtr->filesystemList;
592 while (fsRecPtr != NULL) {
593 tmpFsRecPtr = fsRecPtr->nextPtr;
594 if (--fsRecPtr->fileRefCount <= 0) {
595 ckfree((char *)fsRecPtr);
596 }
597 fsRecPtr = tmpFsRecPtr;
598 }
599 tsdPtr->filesystemList = NULL;
600
601 /*
602 * Code below operates on shared data. We
603 * are already called under mutex lock so
604 * we can safely proceede.
605 */
606
607 /* Locate tail of the global filesystem list */
608 fsRecPtr = filesystemList;
609 while (fsRecPtr != NULL) {
610 tmpFsRecPtr = fsRecPtr;
611 fsRecPtr = fsRecPtr->nextPtr;
612 }
613
614 /* Refill the cache honouring the order */
615 fsRecPtr = tmpFsRecPtr;
616 while (fsRecPtr != NULL) {
617 tmpFsRecPtr = (FilesystemRecord *)ckalloc(sizeof(FilesystemRecord));
618 *tmpFsRecPtr = *fsRecPtr;
619 tmpFsRecPtr->nextPtr = tsdPtr->filesystemList;
620 tmpFsRecPtr->prevPtr = NULL;
621 if (tsdPtr->filesystemList) {
622 tsdPtr->filesystemList->prevPtr = tmpFsRecPtr;
623 }
624 tsdPtr->filesystemList = tmpFsRecPtr;
625 fsRecPtr = fsRecPtr->prevPtr;
626 }
627
628 /* Make sure the above gets released on thread exit */
629 if (tsdPtr->initialized == 0) {
630 Tcl_CreateThreadExitHandler(FsThrExitProc, (ClientData)tsdPtr);
631 tsdPtr->initialized = 1;
632 }
633 }
634 #endif
635
636 static FilesystemRecord *
637 FsGetFirstFilesystem(void) {
638 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
639 FilesystemRecord *fsRecPtr;
640 #ifndef TCL_THREADS
641 tsdPtr->filesystemEpoch = theFilesystemEpoch;
642 fsRecPtr = filesystemList;
643 #else
644 Tcl_MutexLock(&filesystemMutex);
645 if (tsdPtr->filesystemList == NULL
646 || (tsdPtr->filesystemEpoch != theFilesystemEpoch)) {
647 FsRecacheFilesystemList();
648 tsdPtr->filesystemEpoch = theFilesystemEpoch;
649 }
650 Tcl_MutexUnlock(&filesystemMutex);
651 fsRecPtr = tsdPtr->filesystemList;
652 #endif
653 return fsRecPtr;
654 }
655
656 static void
657 FsUpdateCwd(cwdObj)
658 Tcl_Obj *cwdObj;
659 {
660 int len;
661 char *str = NULL;
662 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
663
664 if (cwdObj != NULL) {
665 str = Tcl_GetStringFromObj(cwdObj, &len);
666 }
667
668 Tcl_MutexLock(&cwdMutex);
669 if (cwdPathPtr != NULL) {
670 Tcl_DecrRefCount(cwdPathPtr);
671 }
672 if (cwdObj == NULL) {
673 cwdPathPtr = NULL;
674 } else {
675 /* This MUST be stored as string object! */
676 cwdPathPtr = Tcl_NewStringObj(str, len);
677 Tcl_IncrRefCount(cwdPathPtr);
678 }
679 cwdPathEpoch++;
680 tsdPtr->cwdPathEpoch = cwdPathEpoch;
681 Tcl_MutexUnlock(&cwdMutex);
682
683 if (tsdPtr->cwdPathPtr) {
684 Tcl_DecrRefCount(tsdPtr->cwdPathPtr);
685 }
686 if (cwdObj == NULL) {
687 tsdPtr->cwdPathPtr = NULL;
688 } else {
689 tsdPtr->cwdPathPtr = Tcl_NewStringObj(str, len);
690 Tcl_IncrRefCount(tsdPtr->cwdPathPtr);
691 }
692 }
693
694 /*
695 *----------------------------------------------------------------------
696 *
697 * TclFinalizeFilesystem --
698 *
699 * Clean up the filesystem. After this, calls to all Tcl_FS...
700 * functions will fail.
701 *
702 * We will later call TclResetFilesystem to restore the FS
703 * to a pristine state.
704 *
705 * Results:
706 * None.
707 *
708 * Side effects:
709 * Frees any memory allocated by the filesystem.
710 *
711 *----------------------------------------------------------------------
712 */
713
714 void
715 TclFinalizeFilesystem()
716 {
717 FilesystemRecord *fsRecPtr, *tmpFsRecPtr;
718
719 /*
720 * Assumption that only one thread is active now. Otherwise
721 * we would need to put various mutexes around this code.
722 */
723
724 if (cwdPathPtr != NULL) {
725 Tcl_DecrRefCount(cwdPathPtr);
726 cwdPathPtr = NULL;
727 cwdPathEpoch = 0;
728 }
729
730 /*
731 * Remove all filesystems, freeing any allocated memory
732 * that is no longer needed
733 */
734
735 fsRecPtr = filesystemList;
736 while (fsRecPtr != NULL) {
737 tmpFsRecPtr = filesystemList->nextPtr;
738 if (fsRecPtr->fileRefCount <= 0) {
739 /* The native filesystem is static, so we don't free it */
740 if (fsRecPtr != &nativeFilesystemRecord) {
741 ckfree((char *)fsRecPtr);
742 }
743 }
744 fsRecPtr = tmpFsRecPtr;
745 }
746 filesystemList = NULL;
747
748 /*
749 * Now filesystemList is NULL. This means that any attempt
750 * to use the filesystem is likely to fail.
751 */
752
753 statProcList = NULL;
754 accessProcList = NULL;
755 openFileChannelProcList = NULL;
756 #ifdef __WIN32__
757 TclWinEncodingsCleanup();
758 #endif
759 }
760
761 /*
762 *----------------------------------------------------------------------
763 *
764 * TclResetFilesystem --
765 *
766 * Restore the filesystem to a pristine state.
767 *
768 * Results:
769 * None.
770 *
771 * Side effects:
772 * None.
773 *
774 *----------------------------------------------------------------------
775 */
776
777 void
778 TclResetFilesystem()
779 {
780 filesystemList = &nativeFilesystemRecord;
781
782 /*
783 * Note, at this point, I believe nativeFilesystemRecord ->
784 * fileRefCount should equal 1 and if not, we should try to track
785 * down the cause.
786 */
787
788 #ifdef __WIN32__
789 /*
790 * Cleans up the win32 API filesystem proc lookup table. This must
791 * happen very late in finalization so that deleting of copied
792 * dlls can occur.
793 */
794 TclWinResetInterfaces();
795 #endif
796 }
797
798 /*
799 *----------------------------------------------------------------------
800 *
801 * Tcl_FSRegister --
802 *
803 * Insert the filesystem function table at the head of the list of
804 * functions which are used during calls to all file-system
805 * operations. The filesystem will be added even if it is
806 * already in the list. (You can use Tcl_FSData to
807 * check if it is in the list, provided the ClientData used was
808 * not NULL).
809 *
810 * Note that the filesystem handling is head-to-tail of the list.
811 * Each filesystem is asked in turn whether it can handle a
812 * particular request, _until_ one of them says 'yes'. At that
813 * point no further filesystems are asked.
814 *
815 * In particular this means if you want to add a diagnostic
816 * filesystem (which simply reports all fs activity), it must be
817 * at the head of the list: i.e. it must be the last registered.
818 *
819 * Results:
820 * Normally TCL_OK; TCL_ERROR if memory for a new node in the list
821 * could not be allocated.
822 *
823 * Side effects:
824 * Memory allocated and modifies the link list for filesystems.
825 *
826 *----------------------------------------------------------------------
827 */
828
829 int
830 Tcl_FSRegister(clientData, fsPtr)
831 ClientData clientData; /* Client specific data for this fs */
832 Tcl_Filesystem *fsPtr; /* The filesystem record for the new fs. */
833 {
834 FilesystemRecord *newFilesystemPtr;
835
836 if (fsPtr == NULL) {
837 return TCL_ERROR;
838 }
839
840 newFilesystemPtr = (FilesystemRecord *) ckalloc(sizeof(FilesystemRecord));
841
842 newFilesystemPtr->clientData = clientData;
843 newFilesystemPtr->fsPtr = fsPtr;
844 /*
845 * We start with a refCount of 1. If this drops to zero, then
846 * anyone is welcome to ckfree us.
847 */
848 newFilesystemPtr->fileRefCount = 1;
849
850 /*
851 * Is this lock and wait strictly speaking necessary? Since any
852 * iterators out there will have grabbed a copy of the head of
853 * the list and be iterating away from that, if we add a new
854 * element to the head of the list, it can't possibly have any
855 * effect on any of their loops. In fact it could be better not
856 * to wait, since we are adjusting the filesystem epoch, any
857 * cached representations calculated by existing iterators are
858 * going to have to be thrown away anyway.
859 *
860 * However, since registering and unregistering filesystems is
861 * a very rare action, this is not a very important point.
862 */
863 Tcl_MutexLock(&filesystemMutex);
864
865 newFilesystemPtr->nextPtr = filesystemList;
866 newFilesystemPtr->prevPtr = NULL;
867 if (filesystemList) {
868 filesystemList->prevPtr = newFilesystemPtr;
869 }
870 filesystemList = newFilesystemPtr;
871
872 /*
873 * Increment the filesystem epoch counter, since existing paths
874 * might conceivably now belong to different filesystems.
875 */
876 theFilesystemEpoch++;
877 Tcl_MutexUnlock(&filesystemMutex);
878
879 return TCL_OK;
880 }
881
882 /*
883 *----------------------------------------------------------------------
884 *
885 * Tcl_FSUnregister --
886 *
887 * Remove the passed filesystem from the list of filesystem
888 * function tables. It also ensures that the built-in
889 * (native) filesystem is not removable, although we may wish
890 * to change that decision in the future to allow a smaller
891 * Tcl core, in which the native filesystem is not used at
892 * all (we could, say, initialise Tcl completely over a network
893 * connection).
894 *
895 * Results:
896 * TCL_OK if the procedure pointer was successfully removed,
897 * TCL_ERROR otherwise.
898 *
899 * Side effects:
900 * Memory may be deallocated (or will be later, once no "path"
901 * objects refer to this filesystem), but the list of registered
902 * filesystems is updated immediately.
903 *
904 *----------------------------------------------------------------------
905 */
906
907 int
908 Tcl_FSUnregister(fsPtr)
909 Tcl_Filesystem *fsPtr; /* The filesystem record to remove. */
910 {
911 int retVal = TCL_ERROR;
912 FilesystemRecord *fsRecPtr;
913
914 Tcl_MutexLock(&filesystemMutex);
915
916 /*
917 * Traverse the 'filesystemList' looking for the particular node
918 * whose 'fsPtr' member matches 'fsPtr' and remove that one from
919 * the list. Ensure that the "default" node cannot be removed.
920 */
921
922 fsRecPtr = filesystemList;
923 while ((retVal == TCL_ERROR) && (fsRecPtr != &nativeFilesystemRecord)) {
924 if (fsRecPtr->fsPtr == fsPtr) {
925 if (fsRecPtr->prevPtr) {
926 fsRecPtr->prevPtr->nextPtr = fsRecPtr->nextPtr;
927 } else {
928 filesystemList = fsRecPtr->nextPtr;
929 }
930 if (fsRecPtr->nextPtr) {
931 fsRecPtr->nextPtr->prevPtr = fsRecPtr->prevPtr;
932 }
933 /*
934 * Increment the filesystem epoch counter, since existing
935 * paths might conceivably now belong to different
936 * filesystems. This should also ensure that paths which
937 * have cached the filesystem which is about to be deleted
938 * do not reference that filesystem (which would of course
939 * lead to memory exceptions).
940 */
941 theFilesystemEpoch++;
942
943 fsRecPtr->fileRefCount--;
944 if (fsRecPtr->fileRefCount <= 0) {
945 ckfree((char *)fsRecPtr);
946 }
947
948 retVal = TCL_OK;
949 } else {
950 fsRecPtr = fsRecPtr->nextPtr;
951 }
952 }
953
954 Tcl_MutexUnlock(&filesystemMutex);
955 return (retVal);
956 }
957
958 /*
959 *----------------------------------------------------------------------
960 *
961 * Tcl_FSMatchInDirectory --
962 *
963 * This routine is used by the globbing code to search a directory
964 * for all files which match a given pattern. The appropriate
965 * function for the filesystem to which pathPtr belongs will be
966 * called. If pathPtr does not belong to any filesystem and if it
967 * is NULL or the empty string, then we assume the pattern is to be
968 * matched in the current working directory. To avoid each
969 * filesystem's Tcl_FSMatchInDirectoryProc having to deal with this
970 * issue, we create a pathPtr on the fly (equal to the cwd), and
971 * then remove it from the results returned. This makes filesystems
972 * easy to write, since they can assume the pathPtr passed to them
973 * is an ordinary path. In fact this means we could remove such
974 * special case handling from Tcl's native filesystems.
975 *
976 * If 'pattern' is NULL, then pathPtr is assumed to be a fully
977 * specified path of a single file/directory which must be
978 * checked for existence and correct type.
979 *
980 * Results:
981 *
982 * The return value is a standard Tcl result indicating whether an
983 * error occurred in globbing. Error messages are placed in
984 * interp, but good results are placed in the resultPtr given.
985 *
986 * Recursive searches, e.g.
987 *
988 * glob -dir $dir -join * pkgIndex.tcl
989 *
990 * which must recurse through each directory matching '*' are
991 * handled internally by Tcl, by passing specific flags in a
992 * modified 'types' parameter. This means the actual filesystem
993 * only ever sees patterns which match in a single directory.
994 *
995 * Side effects:
996 * The interpreter may have an error message inserted into it.
997 *
998 *----------------------------------------------------------------------
999 */
1000
1001 int
1002 Tcl_FSMatchInDirectory(interp, result, pathPtr, pattern, types)
1003 Tcl_Interp *interp; /* Interpreter to receive error messages. */
1004 Tcl_Obj *result; /* List object to receive results. */
1005 Tcl_Obj *pathPtr; /* Contains path to directory to search. */
1006 CONST char *pattern; /* Pattern to match against. */
1007 Tcl_GlobTypeData *types; /* Object containing list of acceptable types.
1008 * May be NULL. In particular the directory
1009 * flag is very important. */
1010 {
1011 Tcl_Filesystem *fsPtr = Tcl_FSGetFileSystemForPath(pathPtr);
1012 if (fsPtr != NULL) {
1013 Tcl_FSMatchInDirectoryProc *proc = fsPtr->matchInDirectoryProc;
1014 if (proc != NULL) {
1015 int ret = (*proc)(interp, result, pathPtr, pattern, types);
1016 if (ret == TCL_OK && pattern != NULL) {
1017 result = FsAddMountsToGlobResult(result, pathPtr,
1018 pattern, types);
1019 }
1020 return ret;
1021 }
1022 } else {
1023 Tcl_Obj* cwd;
1024 int ret = -1;
1025 if (pathPtr != NULL) {
1026 int len;
1027 Tcl_GetStringFromObj(pathPtr,&len);
1028 if (len != 0) {
1029 /*
1030 * We have no idea how to match files in a directory
1031 * which belongs to no known filesystem
1032 */
1033 Tcl_SetErrno(ENOENT);
1034 return -1;
1035 }
1036 }
1037 /*
1038 * We have an empty or NULL path. This is defined to mean we
1039 * must search for files within the current 'cwd'. We
1040 * therefore use that, but then since the proc we call will
1041 * return results which include the cwd we must then trim it
1042 * off the front of each path in the result. We choose to deal
1043 * with this here (in the generic code), since if we don't,
1044 * every single filesystem's implementation of
1045 * Tcl_FSMatchInDirectory will have to deal with it for us.
1046 */
1047 cwd = Tcl_FSGetCwd(NULL);
1048 if (cwd == NULL) {
1049 if (interp != NULL) {
1050 Tcl_SetResult(interp, "glob couldn't determine "
1051 "the current working directory", TCL_STATIC);
1052 }
1053 return TCL_ERROR;
1054 }
1055 fsPtr = Tcl_FSGetFileSystemForPath(cwd);
1056 if (fsPtr != NULL) {
1057 Tcl_FSMatchInDirectoryProc *proc = fsPtr->matchInDirectoryProc;
1058 if (proc != NULL) {
1059 Tcl_Obj* tmpResultPtr = Tcl_NewListObj(0, NULL);
1060 Tcl_IncrRefCount(tmpResultPtr);
1061 ret = (*proc)(interp, tmpResultPtr, cwd, pattern, types);
1062 if (ret == TCL_OK) {
1063 int resLength;
1064
1065 tmpResultPtr = FsAddMountsToGlobResult(tmpResultPtr, cwd,
1066 pattern, types);
1067
1068 ret = Tcl_ListObjLength(interp, tmpResultPtr, &resLength);
1069 if (ret == TCL_OK) {
1070 int i;
1071
1072 for (i = 0; i < resLength; i++) {
1073 Tcl_Obj *elt;
1074
1075 Tcl_ListObjIndex(interp, tmpResultPtr, i, &elt);
1076 Tcl_ListObjAppendElement(interp, result,
1077 TclFSMakePathRelative(interp, elt, cwd));
1078 }
1079 }
1080 }
1081 Tcl_DecrRefCount(tmpResultPtr);
1082 }
1083 }
1084 Tcl_DecrRefCount(cwd);
1085 return ret;
1086 }
1087 Tcl_SetErrno(ENOENT);
1088 return -1;
1089 }
1090
1091 /*
1092 *----------------------------------------------------------------------
1093 *
1094 * FsAddMountsToGlobResult --
1095 *
1096 * This routine is used by the globbing code to take the results
1097 * of a directory listing and add any mounted paths to that
1098 * listing. This is required so that simple things like
1099 * 'glob *' merge mounts and listings correctly.
1100 *
1101 * Results:
1102 *
1103 * The passed in 'result' may be modified (in place, if
1104 * necessary), and the correct list is returned.
1105 *
1106 * Side effects:
1107 * None.
1108 *
1109 *----------------------------------------------------------------------
1110 */
1111 static Tcl_Obj*
1112 FsAddMountsToGlobResult(result, pathPtr, pattern, types)
1113 Tcl_Obj *result; /* The current list of matching paths */
1114 Tcl_Obj *pathPtr; /* The directory in question */
1115 CONST char *pattern;
1116 Tcl_GlobTypeData *types;
1117 {
1118 int mLength, gLength, i;
1119 int dir = (types == NULL || (types->type & TCL_GLOB_TYPE_DIR));
1120 Tcl_Obj *mounts = FsListMounts(pathPtr, pattern);
1121
1122 if (mounts == NULL) return result;
1123
1124 if (Tcl_ListObjLength(NULL, mounts, &mLength) != TCL_OK || mLength == 0) {
1125 goto endOfMounts;
1126 }
1127 if (Tcl_ListObjLength(NULL, result, &gLength) != TCL_OK) {
1128 goto endOfMounts;
1129 }
1130 for (i = 0; i < mLength; i++) {
1131 Tcl_Obj *mElt;
1132 int j;
1133 int found = 0;
1134
1135 Tcl_ListObjIndex(NULL, mounts, i, &mElt);
1136
1137 for (j = 0; j < gLength; j++) {
1138 Tcl_Obj *gElt;
1139 Tcl_ListObjIndex(NULL, result, j, &gElt);
1140 if (Tcl_FSEqualPaths(mElt, gElt)) {
1141 found = 1;
1142 if (!dir) {
1143 /* We don't want to list this */
1144 if (Tcl_IsShared(result)) {
1145 Tcl_Obj *newList;
1146 newList = Tcl_DuplicateObj(result);
1147 Tcl_DecrRefCount(result);
1148 result = newList;
1149 }
1150 Tcl_ListObjReplace(NULL, result, j, 1, 0, NULL);
1151 gLength--;
1152 }
1153 /* Break out of for loop */
1154 break;
1155 }
1156 }
1157 if (!found && dir) {
1158 if (Tcl_IsShared(result)) {
1159 Tcl_Obj *newList;
1160 newList = Tcl_DuplicateObj(result);
1161 Tcl_DecrRefCount(result);
1162 result = newList;
1163 }
1164 Tcl_ListObjAppendElement(NULL, result, mElt);
1165 /*
1166 * No need to increment gLength, since we
1167 * don't want to compare mounts against
1168 * mounts.
1169 */
1170 }
1171 }
1172 endOfMounts:
1173 Tcl_DecrRefCount(mounts);
1174 return result;
1175 }
1176
1177 /*
1178 *----------------------------------------------------------------------
1179 *
1180 * Tcl_FSMountsChanged --
1181 *
1182 * Notify the filesystem that the available mounted filesystems
1183 * (or within any one filesystem type, the number or location of
1184 * mount points) have changed.
1185 *
1186 * Results:
1187 * None.
1188 *
1189 * Side effects:
1190 * The global filesystem variable 'theFilesystemEpoch' is
1191 * incremented. The effect of this is to make all cached
1192 * path representations invalid. Clearly it should only therefore
1193 * be called when it is really required! There are a few
1194 * circumstances when it should be called:
1195 *
1196 * (1) when a new filesystem is registered or unregistered.
1197 * Strictly speaking this is only necessary if the new filesystem
1198 * accepts file paths as is (normally the filesystem itself is
1199 * really a shell which hasn't yet had any mount points established
1200 * and so its 'pathInFilesystem' proc will always fail). However,
1201 * for safety, Tcl always calls this for you in these circumstances.
1202 *
1203 * (2) when additional mount points are established inside any
1204 * existing filesystem (except the native fs)
1205 *
1206 * (3) when any filesystem (except the native fs) changes the list
1207 * of available volumes.
1208 *
1209 * (4) when the mapping from a string representation of a file to
1210 * a full, normalized path changes. For example, if 'env(HOME)'
1211 * is modified, then any path containing '~' will map to a different
1212 * filesystem location. Therefore all such paths need to have
1213 * their internal representation invalidated.
1214 *
1215 * Tcl has no control over (2) and (3), so any registered filesystem
1216 * must make sure it calls this function when those situations
1217 * occur.
1218 *
1219 * (Note: the reason for the exception in 2,3 for the native
1220 * filesystem is that the native filesystem by default claims all
1221 * unknown files even if it really doesn't understand them or if
1222 * they don't exist).
1223 *
1224 *----------------------------------------------------------------------
1225 */
1226
1227 void
1228 Tcl_FSMountsChanged(fsPtr)
1229 Tcl_Filesystem *fsPtr;
1230 {
1231 /*
1232 * We currently don't do anything with this parameter. We
1233 * could in the future only invalidate files for this filesystem
1234 * or otherwise take more advanced action.
1235 */
1236 (void)fsPtr;
1237 /*
1238 * Increment the filesystem epoch counter, since existing paths
1239 * might now belong to different filesystems.
1240 */
1241 Tcl_MutexLock(&filesystemMutex);
1242 theFilesystemEpoch++;
1243 Tcl_MutexUnlock(&filesystemMutex);
1244 }
1245
1246 /*
1247 *----------------------------------------------------------------------
1248 *
1249 * Tcl_FSData --
1250 *
1251 * Retrieve the clientData field for the filesystem given,
1252 * or NULL if that filesystem is not registered.
1253 *
1254 * Results:
1255 * A clientData value, or NULL. Note that if the filesystem
1256 * was registered with a NULL clientData field, this function
1257 * will return that NULL value.
1258 *
1259 * Side effects:
1260 * None.
1261 *
1262 *----------------------------------------------------------------------
1263 */
1264
1265 ClientData
1266 Tcl_FSData(fsPtr)
1267 Tcl_Filesystem *fsPtr; /* The filesystem record to query. */
1268 {
1269 ClientData retVal = NULL;
1270 FilesystemRecord *fsRecPtr = FsGetFirstFilesystem();
1271
1272 /*
1273 * Traverse the 'filesystemList' looking for the particular node
1274 * whose 'fsPtr' member matches 'fsPtr' and remove that one from
1275 * the list. Ensure that the "default" node cannot be removed.
1276 */
1277
1278 while ((retVal == NULL) && (fsRecPtr != NULL)) {
1279 if (fsRecPtr->fsPtr == fsPtr) {
1280 retVal = fsRecPtr->clientData;
1281 }
1282 fsRecPtr = fsRecPtr->nextPtr;
1283 }
1284
1285 return retVal;
1286 }
1287
1288 /*
1289 *---------------------------------------------------------------------------
1290 *
1291 * TclFSNormalizeAbsolutePath --
1292 *
1293 * Description:
1294 * Takes an absolute path specification and computes a 'normalized'
1295 * path from it.
1296 *
1297 * A normalized path is one which has all '../', './' removed.
1298 * Also it is one which is in the 'standard' format for the native
1299 * platform. On MacOS, Unix, this means the path must be free of
1300 * symbolic links/aliases, and on Windows it means we want the
1301 * long form, with that long form's case-dependence (which gives
1302 * us a unique, case-dependent path).
1303 *
1304 * The behaviour of this function if passed a non-absolute path
1305 * is NOT defined.
1306 *
1307 * Results:
1308 * The result is returned in a Tcl_Obj with a refCount of 1,
1309 * which is therefore owned by the caller. It must be
1310 * freed (with Tcl_DecrRefCount) by the caller when no longer needed.
1311 *
1312 * Side effects:
1313 * None (beyond the memory allocation for the result).
1314 *
1315 * Special note:
1316 * This code is based on code from Matt Newman and Jean-Claude
1317 * Wippler, with additions from Vince Darley and is copyright
1318 * those respective authors.
1319 *
1320 *---------------------------------------------------------------------------
1321 */
1322 Tcl_Obj*
1323 TclFSNormalizeAbsolutePath(interp, pathPtr, clientDataPtr)
1324 Tcl_Interp* interp; /* Interpreter to use */
1325 Tcl_Obj *pathPtr; /* Absolute path to normalize */
1326 ClientData *clientDataPtr;
1327 {
1328 int splen = 0, nplen, eltLen, i;
1329 char *eltName;
1330 Tcl_Obj *retVal;
1331 Tcl_Obj *split;
1332 Tcl_Obj *elt;
1333
1334 /* Split has refCount zero */
1335 split = Tcl_FSSplitPath(pathPtr, &splen);
1336
1337 /*
1338 * Modify the list of entries in place, by removing '.', and
1339 * removing '..' and the entry before -- unless that entry before
1340 * is the top-level entry, i.e. the name of a volume.
1341 */
1342 nplen = 0;
1343 for (i = 0; i < splen; i++) {
1344 Tcl_ListObjIndex(NULL, split, nplen, &elt);
1345 eltName = Tcl_GetStringFromObj(elt, &eltLen);
1346
1347 if ((eltLen == 1) && (eltName[0] == '.')) {
1348 Tcl_ListObjReplace(NULL, split, nplen, 1, 0, NULL);
1349 } else if ((eltLen == 2)
1350 && (eltName[0] == '.') && (eltName[1] == '.')) {
1351 if (nplen > 1) {
1352 nplen--;
1353 Tcl_ListObjReplace(NULL, split, nplen, 2, 0, NULL);
1354 } else {
1355 Tcl_ListObjReplace(NULL, split, nplen, 1, 0, NULL);
1356 }
1357 } else {
1358 nplen++;
1359 }
1360 }
1361 if (nplen > 0) {
1362 ClientData clientData = NULL;
1363
1364 retVal = Tcl_FSJoinPath(split, nplen);
1365 /*
1366 * Now we have an absolute path, with no '..', '.' sequences,
1367 * but it still may not be in 'unique' form, depending on the
1368 * platform. For instance, Unix is case-sensitive, so the
1369 * path is ok. Windows is case-insensitive, and also has the
1370 * weird 'longname/shortname' thing (e.g. C:/Program Files/ and
1371 * C:/Progra~1/ are equivalent). MacOS is case-insensitive.
1372 *
1373 * Virtual file systems which may be registered may have
1374 * other criteria for normalizing a path.
1375 */
1376 Tcl_IncrRefCount(retVal);
1377 TclFSNormalizeToUniquePath(interp, retVal, 0, &clientData);
1378 /*
1379 * Since we know it is a normalized path, we can
1380 * actually convert this object into an "path" object for
1381 * greater efficiency
1382 */
1383 TclFSMakePathFromNormalized(interp, retVal, clientData);
1384 if (clientDataPtr != NULL) {
1385 *clientDataPtr = clientData;
1386 }
1387 } else {
1388 /* Init to an empty string */
1389 retVal = Tcl_NewStringObj("",0);
1390 Tcl_IncrRefCount(retVal);
1391 }
1392 /*
1393 * We increment and then decrement the refCount of split to free
1394 * it. We do this right at the end, in case there are
1395 * optimisations in Tcl_FSJoinPath(split, nplen) above which would
1396 * let it make use of split more effectively if it has a refCount
1397 * of zero. Also we can't just decrement the ref count, in case
1398 * 'split' was actually returned by the join call above, in a
1399 * single-element optimisation when nplen == 1.
1400 */
1401 Tcl_IncrRefCount(split);
1402 Tcl_DecrRefCount(split);
1403
1404 /* This has a refCount of 1 for the caller */
1405 return retVal;
1406 }
1407
1408 /*
1409 *---------------------------------------------------------------------------
1410 *
1411 * TclFSNormalizeToUniquePath --
1412 *
1413 * Description:
1414 * Takes a path specification containing no ../, ./ sequences,
1415 * and converts it into a unique path for the given platform.
1416 * On MacOS, Unix, this means the path must be free of
1417 * symbolic links/aliases, and on Windows it means we want the
1418 * long form, with that long form's case-dependence (which gives
1419 * us a unique, case-dependent path).
1420 *
1421 * Results:
1422 * The pathPtr is modified in place. The return value is
1423 * the last byte offset which was recognised in the path
1424 * string.
1425 *
1426 * Side effects:
1427 * None (beyond the memory allocation for the result).
1428 *
1429 * Special notes:
1430 * If the filesystem-specific normalizePathProcs can re-introduce
1431 * ../, ./ sequences into the path, then this function will
1432 * not return the correct result. This may be possible with
1433 * symbolic links on unix/macos.
1434 *
1435 * Important assumption: if startAt is non-zero, it must point
1436 * to a directory separator that we know exists and is already
1437 * normalized (so it is important not to point to the char just
1438 * after the separator).
1439 *---------------------------------------------------------------------------
1440 */
1441 int
1442 TclFSNormalizeToUniquePath(interp, pathPtr, startAt, clientDataPtr)
1443 Tcl_Interp *interp;
1444 Tcl_Obj *pathPtr;
1445 int startAt;
1446 ClientData *clientDataPtr;
1447 {
1448 FilesystemRecord *fsRecPtr, *firstFsRecPtr;
1449 /* Ignore this variable */
1450 (void)clientDataPtr;
1451
1452 /*
1453 * Call each of the "normalise path" functions in succession. This is
1454 * a special case, in which if we have a native filesystem handler,
1455 * we call it first. This is because the root of Tcl's filesystem
1456 * is always a native filesystem (i.e. '/' on unix is native).
1457 */
1458
1459 firstFsRecPtr = FsGetFirstFilesystem();
1460
1461 fsRecPtr = firstFsRecPtr;
1462 while (fsRecPtr != NULL) {
1463 if (fsRecPtr == &nativeFilesystemRecord) {
1464 Tcl_FSNormalizePathProc *proc = fsRecPtr->fsPtr->normalizePathProc;
1465 if (proc != NULL) {
1466 startAt = (*proc)(interp, pathPtr, startAt);
1467 }
1468 break;
1469 }
1470 fsRecPtr = fsRecPtr->nextPtr;
1471 }
1472
1473 fsRecPtr = firstFsRecPtr;
1474 while (fsRecPtr != NULL) {
1475 /* Skip the native system next time through */
1476 if (fsRecPtr != &nativeFilesystemRecord) {
1477 Tcl_FSNormalizePathProc *proc = fsRecPtr->fsPtr->normalizePathProc;
1478 if (proc != NULL) {
1479 startAt = (*proc)(interp, pathPtr, startAt);
1480 }
1481 /*
1482 * We could add an efficiency check like this:
1483 *
1484 * if (retVal == length-of(pathPtr)) {break;}
1485 *
1486 * but there's not much benefit.
1487 */
1488 }
1489 fsRecPtr = fsRecPtr->nextPtr;
1490 }
1491
1492 return startAt;
1493 }
1494
1495 /*
1496 *---------------------------------------------------------------------------
1497 *
1498 * TclGetOpenMode --
1499 *
1500 * Description:
1501 * Computes a POSIX mode mask for opening a file, from a given string,
1502 * and also sets a flag to indicate whether the caller should seek to
1503 * EOF after opening the file.
1504 *
1505 * Results:
1506 * On success, returns mode to pass to "open". If an error occurs, the
1507 * return value is -1 and if interp is not NULL, sets interp's result
1508 * object to an error message.
1509 *
1510 * Side effects:
1511 * Sets the integer referenced by seekFlagPtr to 1 to tell the caller
1512 * to seek to EOF after opening the file.
1513 *
1514 * Special note:
1515 * This code is based on a prototype implementation contributed
1516 * by Mark Diekhans.
1517 *
1518 *---------------------------------------------------------------------------
1519 */
1520
1521 int
1522 TclGetOpenMode(interp, string, seekFlagPtr)
1523 Tcl_Interp *interp; /* Interpreter to use for error
1524 * reporting - may be NULL. */
1525 CONST char *string; /* Mode string, e.g. "r+" or
1526 * "RDONLY CREAT". */
1527 int *seekFlagPtr; /* Set this to 1 if the caller
1528 * should seek to EOF during the
1529 * opening of the file. */
1530 {
1531 int mode, modeArgc, c, i, gotRW;
1532 CONST char **modeArgv, *flag;
1533 #define RW_MODES (O_RDONLY|O_WRONLY|O_RDWR)
1534
1535 /*
1536 * Check for the simpler fopen-like access modes (e.g. "r"). They
1537 * are distinguished from the POSIX access modes by the presence
1538 * of a lower-case first letter.
1539 */
1540
1541 *seekFlagPtr = 0;
1542 mode = 0;
1543
1544 /*
1545 * Guard against international characters before using byte oriented
1546 * routines.
1547 */
1548
1549 if (!(string[0] & 0x80)
1550 && islower(UCHAR(string[0]))) { /* INTL: ISO only. */
1551 switch (string[0]) {
1552 case 'r':
1553 mode = O_RDONLY;
1554 break;
1555 case 'w':
1556 mode = O_WRONLY|O_CREAT|O_TRUNC;
1557 break;
1558 case 'a':
1559 mode = O_WRONLY|O_CREAT;
1560 *seekFlagPtr = 1;
1561 break;
1562 default:
1563 error:
1564 if (interp != (Tcl_Interp *) NULL) {
1565 Tcl_AppendResult(interp,
1566 "illegal access mode \"", string, "\"",
1567 (char *) NULL);
1568 }
1569 return -1;
1570 }
1571 if (string[1] == '+') {
1572 mode &= ~(O_RDONLY|O_WRONLY);
1573 mode |= O_RDWR;
1574 if (string[2] != 0) {
1575 goto error;
1576 }
1577 } else if (string[1] != 0) {
1578 goto error;
1579 }
1580 return mode;
1581 }
1582
1583 /*
1584 * The access modes are specified using a list of POSIX modes
1585 * such as O_CREAT.
1586 *
1587 * IMPORTANT NOTE: We rely on Tcl_SplitList working correctly when
1588 * a NULL interpreter is passed in.
1589 */
1590
1591 if (Tcl_SplitList(interp, string, &modeArgc, &modeArgv) != TCL_OK) {
1592 if (interp != (Tcl_Interp *) NULL) {
1593 Tcl_AddErrorInfo(interp,
1594 "\n while processing open access modes \"");
1595 Tcl_AddErrorInfo(interp, string);
1596 Tcl_AddErrorInfo(interp, "\"");
1597 }
1598 return -1;
1599 }
1600
1601 gotRW = 0;
1602 for (i = 0; i < modeArgc; i++) {
1603 flag = modeArgv[i];
1604 c = flag[0];
1605 if ((c == 'R') && (strcmp(flag, "RDONLY") == 0)) {
1606 mode = (mode & ~RW_MODES) | O_RDONLY;
1607 gotRW = 1;
1608 } else if ((c == 'W') && (strcmp(flag, "WRONLY") == 0)) {
1609 mode = (mode & ~RW_MODES) | O_WRONLY;
1610 gotRW = 1;
1611 } else if ((c == 'R') && (strcmp(flag, "RDWR") == 0)) {
1612 mode = (mode & ~RW_MODES) | O_RDWR;
1613 gotRW = 1;
1614 } else if ((c == 'A') && (strcmp(flag, "APPEND") == 0)) {
1615 mode |= O_APPEND;
1616 *seekFlagPtr = 1;
1617 } else if ((c == 'C') && (strcmp(flag, "CREAT") == 0)) {
1618 mode |= O_CREAT;
1619 } else if ((c == 'E') && (strcmp(flag, "EXCL") == 0)) {
1620 mode |= O_EXCL;
1621 } else if ((c == 'N') && (strcmp(flag, "NOCTTY") == 0)) {
1622 #ifdef O_NOCTTY
1623 mode |= O_NOCTTY;
1624 #else
1625 if (interp != (Tcl_Interp *) NULL) {
1626 Tcl_AppendResult(interp, "access mode \"", flag,
1627 "\" not supported by this system", (char *) NULL);
1628 }
1629 ckfree((char *) modeArgv);
1630 return -1;
1631 #endif
1632 } else if ((c == 'N') && (strcmp(flag, "NONBLOCK") == 0)) {
1633 #if defined(O_NDELAY) || defined(O_NONBLOCK)
1634 # ifdef O_NONBLOCK
1635 mode |= O_NONBLOCK;
1636 # else
1637 mode |= O_NDELAY;
1638 # endif
1639 #else
1640 if (interp != (Tcl_Interp *) NULL) {
1641 Tcl_AppendResult(interp, "access mode \"", flag,
1642 "\" not supported by this system", (char *) NULL);
1643 }
1644 ckfree((char *) modeArgv);
1645 return -1;
1646 #endif
1647 } else if ((c == 'T') && (strcmp(flag, "TRUNC") == 0)) {
1648 mode |= O_TRUNC;
1649 } else {
1650 if (interp != (Tcl_Interp *) NULL) {
1651 Tcl_AppendResult(interp, "invalid access mode \"", flag,
1652 "\": must be RDONLY, WRONLY, RDWR, APPEND, CREAT",
1653 " EXCL, NOCTTY, NONBLOCK, or TRUNC", (char *) NULL);
1654 }
1655 ckfree((char *) modeArgv);
1656 return -1;
1657 }
1658 }
1659 ckfree((char *) modeArgv);
1660 if (!gotRW) {
1661 if (interp != (Tcl_Interp *) NULL) {
1662 Tcl_AppendResult(interp, "access mode must include either",
1663 " RDONLY, WRONLY, or RDWR", (char *) NULL);
1664 }
1665 return -1;
1666 }
1667 return mode;
1668 }
1669
1670 /*
1671 *----------------------------------------------------------------------
1672 *
1673 * Tcl_FSEvalFile --
1674 *
1675 * Read in a file and process the entire file as one gigantic
1676 * Tcl command.
1677 *
1678 * Results:
1679 * A standard Tcl result, which is either the result of executing
1680 * the file or an error indicating why the file couldn't be read.
1681 *
1682 * Side effects:
1683 * Depends on the commands in the file. During the evaluation
1684 * of the contents of the file, iPtr->scriptFile is made to
1685 * point to pathPtr (the old value is cached and replaced when
1686 * this function returns).
1687 *
1688 *----------------------------------------------------------------------
1689 */
1690
1691 int
1692 Tcl_FSEvalFile(interp, pathPtr)
1693 Tcl_Interp *interp; /* Interpreter in which to process file. */
1694 Tcl_Obj *pathPtr; /* Path of file to process. Tilde-substitution
1695 * will be performed on this name. */
1696 {
1697 int result, length;
1698 Tcl_StatBuf statBuf;
1699 Tcl_Obj *oldScriptFile;
1700 Interp *iPtr;
1701 char *string;
1702 Tcl_Channel chan;
1703 Tcl_Obj *objPtr;
1704
1705 if (Tcl_FSGetNormalizedPath(interp, pathPtr) == NULL) {
1706 return TCL_ERROR;
1707 }
1708
1709 result = TCL_ERROR;
1710 objPtr = Tcl_NewObj();
1711
1712 if (Tcl_FSStat(pathPtr, &statBuf) == -1) {
1713 Tcl_SetErrno(errno);
1714 Tcl_AppendResult(interp, "couldn't read file \"",
1715 Tcl_GetString(pathPtr),
1716 "\": ", Tcl_PosixError(interp), (char *) NULL);
1717 goto end;
1718 }
1719 chan = Tcl_FSOpenFileChannel(interp, pathPtr, "r", 0644);
1720 if (chan == (Tcl_Channel) NULL) {
1721 Tcl_ResetResult(interp);
1722 Tcl_AppendResult(interp, "couldn't read file \"",
1723 Tcl_GetString(pathPtr),
1724 "\": ", Tcl_PosixError(interp), (char *) NULL);
1725 goto end;
1726 }
1727 /*
1728 * The eofchar is \32 (^Z). This is the usual on Windows, but we
1729 * effect this cross-platform to allow for scripted documents.
1730 * [Bug: 2040]
1731 */
1732 Tcl_SetChannelOption(interp, chan, "-eofchar", "\32");
1733 if (Tcl_ReadChars(chan, objPtr, -1, 0) < 0) {
1734 Tcl_Close(interp, chan);
1735 Tcl_AppendResult(interp, "couldn't read file \"",
1736 Tcl_GetString(pathPtr),
1737 "\": ", Tcl_PosixError(interp), (char *) NULL);
1738 goto end;
1739 }
1740 if (Tcl_Close(interp, chan) != TCL_OK) {
1741 goto end;
1742 }
1743
1744 iPtr = (Interp *) interp;
1745 oldScriptFile = iPtr->scriptFile;
1746 iPtr->scriptFile = pathPtr;
1747 Tcl_IncrRefCount(iPtr->scriptFile);
1748 string = Tcl_GetStringFromObj(objPtr, &length);
1749 result = Tcl_EvalEx(interp, string, length, 0);
1750 /*
1751 * Now we have to be careful; the script may have changed the
1752 * iPtr->scriptFile value, so we must reset it without
1753 * assuming it still points to 'pathPtr'.
1754 */
1755 if (iPtr->scriptFile != NULL) {
1756 Tcl_DecrRefCount(iPtr->scriptFile);
1757 }
1758 iPtr->scriptFile = oldScriptFile;
1759
1760 if (result == TCL_RETURN) {
1761 result = TclUpdateReturnInfo(iPtr);
1762 } else if (result == TCL_ERROR) {
1763 char msg[200 + TCL_INTEGER_SPACE];
1764
1765 /*
1766 * Record information telling where the error occurred.
1767 */
1768
1769 sprintf(msg, "\n (file \"%.150s\" line %d)", Tcl_GetString(pathPtr),
1770 interp->errorLine);
1771 Tcl_AddErrorInfo(interp, msg);
1772 }
1773
1774 end:
1775 Tcl_DecrRefCount(objPtr);
1776 return result;
1777 }
1778
1779 /*
1780 *----------------------------------------------------------------------
1781 *
1782 * Tcl_GetErrno --
1783 *
1784 * Gets the current value of the Tcl error code variable. This is
1785 * currently the global variable "errno" but could in the future
1786 * change to something else.
1787 *
1788 * Results:
1789 * The value of the Tcl error code variable.
1790 *
1791 * Side effects:
1792 * None. Note that the value of the Tcl error code variable is
1793 * UNDEFINED if a call to Tcl_SetErrno did not precede this call.
1794 *
1795 *----------------------------------------------------------------------
1796 */
1797
1798 int
1799 Tcl_GetErrno()
1800 {
1801 return errno;
1802 }
1803
1804 /*
1805 *----------------------------------------------------------------------
1806 *
1807 * Tcl_SetErrno --
1808 *
1809 * Sets the Tcl error code variable to the supplied value.
1810 *
1811 * Results:
1812 * None.
1813 *
1814 * Side effects:
1815 * Modifies the value of the Tcl error code variable.
1816 *
1817 *----------------------------------------------------------------------
1818 */
1819
1820 void
1821 Tcl_SetErrno(err)
1822 int err; /* The new value. */
1823 {
1824 errno = err;
1825 }
1826
1827 /*
1828 *----------------------------------------------------------------------
1829 *
1830 * Tcl_PosixError --
1831 *
1832 * This procedure is typically called after UNIX kernel calls
1833 * return errors. It stores machine-readable information about
1834 * the error in $errorCode returns an information string for
1835 * the caller's use.
1836 *
1837 * Results:
1838 * The return value is a human-readable string describing the
1839 * error.
1840 *
1841 * Side effects:
1842 * The global variable $errorCode is reset.
1843 *
1844 *----------------------------------------------------------------------
1845 */
1846
1847 CONST char *
1848 Tcl_PosixError(interp)
1849 Tcl_Interp *interp; /* Interpreter whose $errorCode variable
1850 * is to be changed. */
1851 {
1852 CONST char *id, *msg;
1853
1854 msg = Tcl_ErrnoMsg(errno);
1855 id = Tcl_ErrnoId();
1856 Tcl_SetErrorCode(interp, "POSIX", id, msg, (char *) NULL);
1857 return msg;
1858 }
1859
1860 /*
1861 *----------------------------------------------------------------------
1862 *
1863 * Tcl_FSStat --
1864 *
1865 * This procedure replaces the library version of stat and lsat.
1866 *
1867 * The appropriate function for the filesystem to which pathPtr
1868 * belongs will be called.
1869 *
1870 * Results:
1871 * See stat documentation.
1872 *
1873 * Side effects:
1874 * See stat documentation.
1875 *
1876 *----------------------------------------------------------------------
1877 */
1878
1879 int
1880 Tcl_FSStat(pathPtr, buf)
1881 Tcl_Obj *pathPtr; /* Path of file to stat (in current CP). */
1882 Tcl_StatBuf *buf; /* Filled with results of stat call. */
1883 {
1884 Tcl_Filesystem *fsPtr;
1885 #ifdef USE_OBSOLETE_FS_HOOKS
1886 struct stat oldStyleStatBuffer;
1887 int retVal = -1;
1888
1889 /*
1890 * Call each of the "stat" function in succession. A non-return
1891 * value of -1 indicates the particular function has succeeded.
1892 */
1893
1894 Tcl_MutexLock(&obsoleteFsHookMutex);
1895
1896 if (statProcList != NULL) {
1897 StatProc *statProcPtr;
1898 char *path;
1899 Tcl_Obj *transPtr = Tcl_FSGetTranslatedPath(NULL, pathPtr);
1900 if (transPtr == NULL) {
1901 path = NULL;
1902 } else {
1903 path = Tcl_GetString(transPtr);
1904 }
1905
1906 statProcPtr = statProcList;
1907 while ((retVal == -1) && (statProcPtr != NULL)) {
1908 retVal = (*statProcPtr->proc)(path, &oldStyleStatBuffer);
1909 statProcPtr = statProcPtr->nextPtr;
1910 }
1911 if (transPtr != NULL) {
1912 Tcl_DecrRefCount(transPtr);
1913 }
1914 }
1915
1916 Tcl_MutexUnlock(&obsoleteFsHookMutex);
1917 if (retVal != -1) {
1918 /*
1919 * Note that EOVERFLOW is not a problem here, and these
1920 * assignments should all be widening (if not identity.)
1921 */
1922 buf->st_mode = oldStyleStatBuffer.st_mode;
1923 buf->st_ino = oldStyleStatBuffer.st_ino;
1924 buf->st_dev = oldStyleStatBuffer.st_dev;
1925 buf->st_rdev = oldStyleStatBuffer.st_rdev;
1926 buf->st_nlink = oldStyleStatBuffer.st_nlink;
1927 buf->st_uid = oldStyleStatBuffer.st_uid;
1928 buf->st_gid = oldStyleStatBuffer.st_gid;
1929 buf->st_size = Tcl_LongAsWide(oldStyleStatBuffer.st_size);
1930 buf->st_atime = oldStyleStatBuffer.st_atime;
1931 buf->st_mtime = oldStyleStatBuffer.st_mtime;
1932 buf->st_ctime = oldStyleStatBuffer.st_ctime;
1933 #ifdef HAVE_ST_BLOCKS
1934 buf->st_blksize = oldStyleStatBuffer.st_blksize;
1935 buf->st_blocks = Tcl_LongAsWide(oldStyleStatBuffer.st_blocks);
1936 #endif
1937 return retVal;
1938 }
1939 #endif /* USE_OBSOLETE_FS_HOOKS */
1940 fsPtr = Tcl_FSGetFileSystemForPath(pathPtr);
1941 if (fsPtr != NULL) {
1942 Tcl_FSStatProc *proc = fsPtr->statProc;
1943 if (proc != NULL) {
1944 return (*proc)(pathPtr, buf);
1945 }
1946 }
1947 Tcl_SetErrno(ENOENT);
1948 return -1;
1949 }
1950
1951 /*
1952 *----------------------------------------------------------------------
1953 *
1954 * Tcl_FSLstat --
1955 *
1956 * This procedure replaces the library version of lstat.
1957 * The appropriate function for the filesystem to which pathPtr
1958 * belongs will be called. If no 'lstat' function is listed,
1959 * but a 'stat' function is, then Tcl will fall back on the
1960 * stat function.
1961 *
1962 * Results:
1963 * See lstat documentation.
1964 *
1965 * Side effects:
1966 * See lstat documentation.
1967 *
1968 *----------------------------------------------------------------------
1969 */
1970
1971 int
1972 Tcl_FSLstat(pathPtr, buf)
1973 Tcl_Obj *pathPtr; /* Path of file to stat (in current CP). */
1974 Tcl_StatBuf *buf; /* Filled with results of stat call. */
1975 {
1976 Tcl_Filesystem *fsPtr = Tcl_FSGetFileSystemForPath(pathPtr);
1977 if (fsPtr != NULL) {
1978 Tcl_FSLstatProc *proc = fsPtr->lstatProc;
1979 if (proc != NULL) {
1980 return (*proc)(pathPtr, buf);
1981 } else {
1982 Tcl_FSStatProc *sproc = fsPtr->statProc;
1983 if (sproc != NULL) {
1984 return (*sproc)(pathPtr, buf);
1985 }
1986 }
1987 }
1988 Tcl_SetErrno(ENOENT);
1989 return -1;
1990 }
1991
1992 /*
1993 *----------------------------------------------------------------------
1994 *
1995 * Tcl_FSAccess --
1996 *
1997 * This procedure replaces the library version of access.
1998 * The appropriate function for the filesystem to which pathPtr
1999 * belongs will be called.
2000 *
2001 * Results:
2002 * See access documentation.
2003 *
2004 * Side effects:
2005 * See access documentation.
2006 *
2007 *----------------------------------------------------------------------
2008 */
2009
2010 int
2011 Tcl_FSAccess(pathPtr, mode)
2012 Tcl_Obj *pathPtr; /* Path of file to access (in current CP). */
2013 int mode; /* Permission setting. */
2014 {
2015 Tcl_Filesystem *fsPtr;
2016 #ifdef USE_OBSOLETE_FS_HOOKS
2017 int retVal = -1;
2018
2019 /*
2020 * Call each of the "access" function in succession. A non-return
2021 * value of -1 indicates the particular function has succeeded.
2022 */
2023
2024 Tcl_MutexLock(&obsoleteFsHookMutex);
2025
2026 if (accessProcList != NULL) {
2027 AccessProc *accessProcPtr;
2028 char *path;
2029 Tcl_Obj *transPtr = Tcl_FSGetTranslatedPath(NULL, pathPtr);
2030 if (transPtr == NULL) {
2031 path = NULL;
2032 } else {
2033 path = Tcl_GetString(transPtr);
2034 }
2035
2036 accessProcPtr = accessProcList;
2037 while ((retVal == -1) && (accessProcPtr != NULL)) {
2038 retVal = (*accessProcPtr->proc)(path, mode);
2039 accessProcPtr = accessProcPtr->nextPtr;
2040 }
2041 if (transPtr != NULL) {
2042 Tcl_DecrRefCount(transPtr);
2043 }
2044 }
2045
2046 Tcl_MutexUnlock(&obsoleteFsHookMutex);
2047 if (retVal != -1) {
2048 return retVal;
2049 }
2050 #endif /* USE_OBSOLETE_FS_HOOKS */
2051 fsPtr = Tcl_FSGetFileSystemForPath(pathPtr);
2052 if (fsPtr != NULL) {
2053 Tcl_FSAccessProc *proc = fsPtr->accessProc;
2054 if (proc != NULL) {
2055 return (*proc)(pathPtr, mode);
2056 }
2057 }
2058
2059 Tcl_SetErrno(ENOENT);
2060 return -1;
2061 }
2062
2063 /*
2064 *----------------------------------------------------------------------
2065 *
2066 * Tcl_FSOpenFileChannel --
2067 *
2068 * The appropriate function for the filesystem to which pathPtr
2069 * belongs will be called.
2070 *
2071 * Results:
2072 * The new channel or NULL, if the named file could not be opened.
2073 *
2074 * Side effects:
2075 * May open the channel and may cause creation of a file on the
2076 * file system.
2077 *
2078 *----------------------------------------------------------------------
2079 */
2080
2081 Tcl_Channel
2082 Tcl_FSOpenFileChannel(interp, pathPtr, modeString, permissions)
2083 Tcl_Interp *interp; /* Interpreter for error reporting;
2084 * can be NULL. */
2085 Tcl_Obj *pathPtr; /* Name of file to open. */
2086 CONST char *modeString; /* A list of POSIX open modes or
2087 * a string such as "rw". */
2088 int permissions; /* If the open involves creating a
2089 * file, with what modes to create
2090 * it? */
2091 {
2092 Tcl_Filesystem *fsPtr;
2093 #ifdef USE_OBSOLETE_FS_HOOKS
2094 Tcl_Channel retVal = NULL;
2095
2096 /*
2097 * Call each of the "Tcl_OpenFileChannel" functions in succession.
2098 * A non-NULL return value indicates the particular function has
2099 * succeeded.
2100 */
2101
2102 Tcl_MutexLock(&obsoleteFsHookMutex);
2103 if (openFileChannelProcList != NULL) {
2104 OpenFileChannelProc *openFileChannelProcPtr;
2105 char *path;
2106 Tcl_Obj *transPtr = Tcl_FSGetTranslatedPath(interp, pathPtr);
2107
2108 if (transPtr == NULL) {
2109 path = NULL;
2110 } else {
2111 path = Tcl_GetString(transPtr);
2112 }
2113
2114 openFileChannelProcPtr = openFileChannelProcList;
2115
2116 while ((retVal == NULL) && (openFileChannelProcPtr != NULL)) {
2117 retVal = (*openFileChannelProcPtr->proc)(interp, path,
2118 modeString, permissions);
2119 openFileChannelProcPtr = openFileChannelProcPtr->nextPtr;
2120 }
2121 if (transPtr != NULL) {
2122 Tcl_DecrRefCount(transPtr);
2123 }
2124 }
2125 Tcl_MutexUnlock(&obsoleteFsHookMutex);
2126 if (retVal != NULL) {
2127 return retVal;
2128 }
2129 #endif /* USE_OBSOLETE_FS_HOOKS */
2130
2131 /*
2132 * We need this just to ensure we return the correct error messages
2133 * under some circumstances.
2134 */
2135 if (Tcl_FSGetNormalizedPath(interp, pathPtr) == NULL) {
2136 return NULL;
2137 }
2138
2139 fsPtr = Tcl_FSGetFileSystemForPath(pathPtr);
2140 if (fsPtr != NULL) {
2141 Tcl_FSOpenFileChannelProc *proc = fsPtr->openFileChannelProc;
2142 if (proc != NULL) {
2143 int mode, seekFlag;
2144 mode = TclGetOpenMode(interp, modeString, &seekFlag);
2145 if (mode == -1) {
2146 return NULL;
2147 }
2148 retVal = (*proc)(interp, pathPtr, mode, permissions);
2149 if (retVal != NULL) {
2150 if (seekFlag) {
2151 if (Tcl_Seek(retVal, (Tcl_WideInt)0,
2152 SEEK_END) < (Tcl_WideInt)0) {
2153 if (interp != (Tcl_Interp *) NULL) {
2154 Tcl_AppendResult(interp,
2155 "could not seek to end of file while opening \"",
2156 Tcl_GetString(pathPtr), "\": ",
2157 Tcl_PosixError(interp), (char *) NULL);
2158 }
2159 Tcl_Close(NULL, retVal);
2160 return NULL;
2161 }
2162 }
2163 }
2164 return retVal;
2165 }
2166 }
2167 /* File doesn't belong to any filesystem that can open it */
2168 Tcl_SetErrno(ENOENT);
2169 if (interp != NULL) {
2170 Tcl_AppendResult(interp, "couldn't open \"",
2171 Tcl_GetString(pathPtr), "\": ",
2172 Tcl_PosixError(interp), (char *) NULL);
2173 }
2174 return NULL;
2175 }
2176
2177 /*
2178 *----------------------------------------------------------------------
2179 *
2180 * Tcl_FSUtime --
2181 *
2182 * This procedure replaces the library version of utime.
2183 * The appropriate function for the filesystem to which pathPtr
2184 * belongs will be called.
2185 *
2186 * Results:
2187 * See utime documentation.
2188 *
2189 * Side effects:
2190 * See utime documentation.
2191 *
2192 *----------------------------------------------------------------------
2193 */
2194
2195 int
2196 Tcl_FSUtime (pathPtr, tval)
2197 Tcl_Obj *pathPtr; /* File to change access/modification times */
2198 struct utimbuf *tval; /* Structure containing access/modification
2199 * times to use. Should not be modified. */
2200 {
2201 Tcl_Filesystem *fsPtr = Tcl_FSGetFileSystemForPath(pathPtr);
2202 if (fsPtr != NULL) {
2203 Tcl_FSUtimeProc *proc = fsPtr->utimeProc;
2204 if (proc != NULL) {
2205 return (*proc)(pathPtr, tval);
2206 }
2207 }
2208 return -1;
2209 }
2210
2211 /*
2212 *----------------------------------------------------------------------
2213 *
2214 * NativeFileAttrStrings --
2215 *
2216 * This procedure implements the platform dependent 'file
2217 * attributes' subcommand, for the native filesystem, for listing
2218 * the set of possible attribute strings. This function is part
2219 * of Tcl's native filesystem support, and is placed here because
2220 * it is shared by Unix, MacOS and Windows code.
2221 *
2222 * Results:
2223 * An array of strings
2224 *
2225 * Side effects:
2226 * None.
2227 *
2228 *----------------------------------------------------------------------
2229 */
2230
2231 static CONST char**
2232 NativeFileAttrStrings(pathPtr, objPtrRef)
2233 Tcl_Obj *pathPtr;
2234 Tcl_Obj** objPtrRef;
2235 {
2236 return tclpFileAttrStrings;
2237 }
2238
2239 /*
2240 *----------------------------------------------------------------------
2241 *
2242 * NativeFileAttrsGet --
2243 *
2244 * This procedure implements the platform dependent
2245 * 'file attributes' subcommand, for the native
2246 * filesystem, for 'get' operations. This function is part
2247 * of Tcl's native filesystem support, and is placed here
2248 * because it is shared by Unix, MacOS and Windows code.
2249 *
2250 * Results:
2251 * Standard Tcl return code. The object placed in objPtrRef
2252 * (if TCL_OK was returned) is likely to have a refCount of zero.
2253 * Either way we must either store it somewhere (e.g. the Tcl
2254 * result), or Incr/Decr its refCount to ensure it is properly
2255 * freed.
2256 *
2257 * Side effects:
2258 * None.
2259 *
2260 *----------------------------------------------------------------------
2261 */
2262
2263 static int
2264 NativeFileAttrsGet(interp, index, pathPtr, objPtrRef)
2265 Tcl_Interp *interp; /* The interpreter for error reporting. */
2266 int index; /* index of the attribute command. */
2267 Tcl_Obj *pathPtr; /* path of file we are operating on. */
2268 Tcl_Obj **objPtrRef; /* for output. */
2269 {
2270 return (*tclpFileAttrProcs[index].getProc)(interp, index,
2271 pathPtr, objPtrRef);
2272 }
2273
2274 /*
2275 *----------------------------------------------------------------------
2276 *
2277 * NativeFileAttrsSet --
2278 *
2279 * This procedure implements the platform dependent
2280 * 'file attributes' subcommand, for the native
2281 * filesystem, for 'set' operations. This function is part
2282 * of Tcl's native filesystem support, and is placed here
2283 * because it is shared by Unix, MacOS and Windows code.
2284 *
2285 * Results:
2286 * Standard Tcl return code.
2287 *
2288 * Side effects:
2289 * None.
2290 *
2291 *----------------------------------------------------------------------
2292 */
2293
2294 static int
2295 NativeFileAttrsSet(interp, index, pathPtr, objPtr)
2296 Tcl_Interp *interp; /* The interpreter for error reporting. */
2297 int index; /* index of the attribute command. */
2298 Tcl_Obj *pathPtr; /* path of file we are operating on. */
2299 Tcl_Obj *objPtr; /* set to this value. */
2300 {
2301 return (*tclpFileAttrProcs[index].setProc)(interp, index,
2302 pathPtr, objPtr);
2303 }
2304
2305 /*
2306 *----------------------------------------------------------------------
2307 *
2308 * Tcl_FSFileAttrStrings --
2309 *
2310 * This procedure implements part of the hookable 'file
2311 * attributes' subcommand. The appropriate function for the
2312 * filesystem to which pathPtr belongs will be called.
2313 *
2314 * Results:
2315 * The called procedure may either return an array of strings,
2316 * or may instead return NULL and place a Tcl list into the
2317 * given objPtrRef. Tcl will take that list and first increment
2318 * its refCount before using it. On completion of that use, Tcl
2319 * will decrement its refCount. Hence if the list should be
2320 * disposed of by Tcl when done, it should have a refCount of zero,
2321 * and if the list should not be disposed of, the filesystem
2322 * should ensure it retains a refCount on the object.
2323 *
2324 * Side effects:
2325 * None.
2326 *
2327 *----------------------------------------------------------------------
2328 */
2329
2330 CONST char **
2331 Tcl_FSFileAttrStrings(pathPtr, objPtrRef)
2332 Tcl_Obj* pathPtr;
2333 Tcl_Obj** objPtrRef;
2334 {
2335 Tcl_Filesystem *fsPtr = Tcl_FSGetFileSystemForPath(pathPtr);
2336 if (fsPtr != NULL) {
2337 Tcl_FSFileAttrStringsProc *proc = fsPtr->fileAttrStringsProc;
2338 if (proc != NULL) {
2339 return (*proc)(pathPtr, objPtrRef);
2340 }
2341 }
2342 Tcl_SetErrno(ENOENT);
2343 return NULL;
2344 }
2345
2346 /*
2347 *----------------------------------------------------------------------
2348 *
2349 * Tcl_FSFileAttrsGet --
2350 *
2351 * This procedure implements read access for the hookable 'file
2352 * attributes' subcommand. The appropriate function for the
2353 * filesystem to which pathPtr belongs will be called.
2354 *
2355 * Results:
2356 * Standard Tcl return code. The object placed in objPtrRef
2357 * (if TCL_OK was returned) is likely to have a refCount of zero.
2358 * Either way we must either store it somewhere (e.g. the Tcl
2359 * result), or Incr/Decr its refCount to ensure it is properly
2360 * freed.
2361
2362 *
2363 * Side effects:
2364 * None.
2365 *
2366 *----------------------------------------------------------------------
2367 */
2368
2369 int
2370 Tcl_FSFileAttrsGet(interp, index, pathPtr, objPtrRef)
2371 Tcl_Interp *interp; /* The interpreter for error reporting. */
2372 int index; /* index of the attribute command. */
2373 Tcl_Obj *pathPtr; /* filename we are operating on. */
2374 Tcl_Obj **objPtrRef; /* for output. */
2375 {
2376 Tcl_Filesystem *fsPtr = Tcl_FSGetFileSystemForPath(pathPtr);
2377 if (fsPtr != NULL) {
2378 Tcl_FSFileAttrsGetProc *proc = fsPtr->fileAttrsGetProc;
2379 if (proc != NULL) {
2380 return (*proc)(interp, index, pathPtr, objPtrRef);
2381 }
2382 }
2383 Tcl_SetErrno(ENOENT);
2384 return -1;
2385 }
2386
2387 /*
2388 *----------------------------------------------------------------------
2389 *
2390 * Tcl_FSFileAttrsSet --
2391 *
2392 * This procedure implements write access for the hookable 'file
2393 * attributes' subcommand. The appropriate function for the
2394 * filesystem to which pathPtr belongs will be called.
2395 *
2396 * Results:
2397 * Standard Tcl return code.
2398 *
2399 * Side effects:
2400 * None.
2401 *
2402 *----------------------------------------------------------------------
2403 */
2404
2405 int
2406 Tcl_FSFileAttrsSet(interp, index, pathPtr, objPtr)
2407 Tcl_Interp *interp; /* The interpreter for error reporting. */
2408 int index; /* index of the attribute command. */
2409 Tcl_Obj *pathPtr; /* filename we are operating on. */
2410 Tcl_Obj *objPtr; /* Input value. */
2411 {
2412 Tcl_Filesystem *fsPtr = Tcl_FSGetFileSystemForPath(pathPtr);
2413 if (fsPtr != NULL) {
2414 Tcl_FSFileAttrsSetProc *proc = fsPtr->fileAttrsSetProc;
2415 if (proc != NULL) {
2416 return (*proc)(interp, index, pathPtr, objPtr);
2417 }
2418 }
2419 Tcl_SetErrno(ENOENT);
2420 return -1;
2421 }
2422
2423 /*
2424 *----------------------------------------------------------------------
2425 *
2426 * Tcl_FSGetCwd --
2427 *
2428 * This function replaces the library version of getcwd().
2429 *
2430 * Most VFS's will *not* implement a 'cwdProc'. Tcl now maintains
2431 * its own record (in a Tcl_Obj) of the cwd, and an attempt
2432 * is made to synchronise this with the cwd's containing filesystem,
2433 * if that filesystem provides a cwdProc (e.g. the native filesystem).
2434 *
2435 * Note that if Tcl's cwd is not in the native filesystem, then of
2436 * course Tcl's cwd and the native cwd are different: extensions
2437 * should therefore ensure they only access the cwd through this
2438 * function to avoid confusion.
2439 *
2440 * If a global cwdPathPtr already exists, it is cached in the thread's
2441 * private data structures and reference to the cached copy is returned,
2442 * subject to a synchronisation attempt in that cwdPathPtr's fs.
2443 *
2444 * Otherwise, the chain of functions that have been "inserted"
2445 * into the filesystem will be called in succession until either a
2446 * value other than NULL is returned, or the entire list is
2447 * visited.
2448 *
2449 * Results:
2450 * The result is a pointer to a Tcl_Obj specifying the current
2451 * directory, or NULL if the current directory could not be
2452 * determined. If NULL is returned, an error message is left in the
2453 * interp's result.
2454 *
2455 * The result already has its refCount incremented for the caller.
2456 * When it is no longer needed, that refCount should be decremented.
2457 *
2458 * Side effects:
2459 * Various objects may be freed and allocated.
2460 *
2461 *----------------------------------------------------------------------
2462 */
2463
2464 Tcl_Obj*
2465 Tcl_FSGetCwd(interp)
2466 Tcl_Interp *interp;
2467 {
2468 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
2469
2470 if (TclFSCwdPointerEquals(NULL)) {
2471 FilesystemRecord *fsRecPtr;
2472 Tcl_Obj *retVal = NULL;
2473
2474 /*
2475 * We've never been called before, try to find a cwd. Call
2476 * each of the "Tcl_GetCwd" function in succession. A non-NULL
2477 * return value indicates the particular function has
2478 * succeeded.
2479 */
2480
2481 fsRecPtr = FsGetFirstFilesystem();
2482 while ((retVal == NULL) && (fsRecPtr != NULL)) {
2483 Tcl_FSGetCwdProc *proc = fsRecPtr->fsPtr->getCwdProc;
2484 if (proc != NULL) {
2485 retVal = (*proc)(interp);
2486 }
2487 fsRecPtr = fsRecPtr->nextPtr;
2488 }
2489 /*
2490 * Now the 'cwd' may NOT be normalized, at least on some
2491 * platforms. For the sake of efficiency, we want a completely
2492 * normalized cwd at all times.
2493 *
2494 * Finally, if retVal is NULL, we do not have a cwd, which
2495 * could be problematic.
2496 */
2497 if (retVal != NULL) {
2498 Tcl_Obj *norm = TclFSNormalizeAbsolutePath(interp, retVal, NULL);
2499 if (norm != NULL) {
2500 /*
2501 * We found a cwd, which is now in our global storage.
2502 * We must make a copy. Norm already has a refCount of 1.
2503 *
2504 * Threading issue: note that multiple threads at system
2505 * startup could in principle call this procedure
2506 * simultaneously. They will therefore each set the
2507 * cwdPathPtr independently. That behaviour is a bit
2508 * peculiar, but should be fine. Once we have a cwd,
2509 * we'll always be in the 'else' branch below which
2510 * is simpler.
2511 */
2512 FsUpdateCwd(norm);
2513 }
2514 Tcl_DecrRefCount(retVal);
2515 }
2516 } else {
2517 /*
2518 * We already have a cwd cached, but we want to give the
2519 * filesystem it is in a chance to check whether that cwd
2520 * has changed, or is perhaps no longer accessible. This
2521 * allows an error to be thrown if, say, the permissions on
2522 * that directory have changed.
2523 */
2524 Tcl_Filesystem *fsPtr = Tcl_FSGetFileSystemForPath(tsdPtr->cwdPathPtr);
2525 /*
2526 * If the filesystem couldn't be found, or if no cwd function
2527 * exists for this filesystem, then we simply assume the cached
2528 * cwd is ok. If we do call a cwd, we must watch for errors
2529 * (if the cwd returns NULL). This ensures that, say, on Unix
2530 * if the permissions of the cwd change, 'pwd' does actually
2531 * throw the correct error in Tcl. (This is tested for in the
2532 * test suite on unix).
2533 */
2534 if (fsPtr != NULL) {
2535 Tcl_FSGetCwdProc *proc = fsPtr->getCwdProc;
2536 if (proc != NULL) {
2537 Tcl_Obj *retVal = (*proc)(interp);
2538 if (retVal != NULL) {
2539 Tcl_Obj *norm = TclFSNormalizeAbsolutePath(interp, retVal, NULL);
2540 /*
2541 * Check whether cwd has changed from the value
2542 * previously stored in cwdPathPtr. Really 'norm'
2543 * shouldn't be null, but we are careful.
2544 */
2545 if (norm == NULL) {
2546 /* Do nothing */
2547 } else if (Tcl_FSEqualPaths(tsdPtr->cwdPathPtr, norm)) {
2548 /*
2549 * If the paths were equal, we can be more
2550 * efficient and retain the old path object
2551 * which will probably already be shared. In
2552 * this case we can simply free the normalized
2553 * path we just calculated.
2554 */
2555 Tcl_DecrRefCount(norm);
2556 } else {
2557 FsUpdateCwd(norm);
2558 }
2559 Tcl_DecrRefCount(retVal);
2560 } else {
2561 /* The 'cwd' function returned an error; reset the cwd */
2562 FsUpdateCwd(NULL);
2563 }
2564 }
2565 }
2566 }
2567
2568 if (tsdPtr->cwdPathPtr != NULL) {
2569 Tcl_IncrRefCount(tsdPtr->cwdPathPtr);
2570 }
2571
2572 return tsdPtr->cwdPathPtr;
2573 }
2574
2575 /*
2576 *----------------------------------------------------------------------
2577 *
2578 * Tcl_FSChdir --
2579 *
2580 * This function replaces the library version of chdir().
2581 *
2582 * The path is normalized and then passed to the filesystem
2583 * which claims it.
2584 *
2585 * Results:
2586 * See chdir() documentation. If successful, we keep a
2587 * record of the successful path in cwdPathPtr for subsequent
2588 * calls to getcwd.
2589 *
2590 * Side effects:
2591 * See chdir() documentation. The global cwdPathPtr may
2592 * change value.
2593 *
2594 *----------------------------------------------------------------------
2595 */
2596 int
2597 Tcl_FSChdir(pathPtr)
2598 Tcl_Obj *pathPtr;
2599 {
2600 Tcl_Filesystem *fsPtr;
2601 int retVal = -1;
2602
2603 if (Tcl_FSGetNormalizedPath(NULL, pathPtr) == NULL) {
2604 return TCL_ERROR;
2605 }
2606
2607 fsPtr = Tcl_FSGetFileSystemForPath(pathPtr);
2608 if (fsPtr != NULL) {
2609 Tcl_FSChdirProc *proc = fsPtr->chdirProc;
2610 if (proc != NULL) {
2611 retVal = (*proc)(pathPtr);
2612 } else {
2613 /* Fallback on stat-based implementation */
2614 Tcl_StatBuf buf;
2615 /* If the file can be stat'ed and is a directory and
2616 * is readable, then we can chdir. */
2617 if ((Tcl_FSStat(pathPtr, &buf) == 0)
2618 && (S_ISDIR(buf.st_mode))
2619 && (Tcl_FSAccess(pathPtr, R_OK) == 0)) {
2620 /* We allow the chdir */
2621 retVal = 0;
2622 }
2623 }
2624 }
2625
2626 if (retVal != -1) {
2627 /*
2628 * The cwd changed, or an error was thrown. If an error was
2629 * thrown, we can just continue (and that will report the error
2630 * to the user). If there was no error we must assume that the
2631 * cwd was actually changed to the normalized value we
2632 * calculated above, and we must therefore cache that
2633 * information.
2634 */
2635 if (retVal == TCL_OK) {
2636 /*
2637 * Note that this normalized path may be different to what
2638 * we found above (or at least a different object), if the
2639 * filesystem epoch changed recently. This can actually
2640 * happen with scripted documents very easily. Therefore
2641 * we ask for the normalized path again (the correct value
2642 * will have been cached as a result of the
2643 * Tcl_FSGetFileSystemForPath call above anyway).
2644 */
2645 Tcl_Obj *normDirName = Tcl_FSGetNormalizedPath(NULL, pathPtr);
2646 if (normDirName == NULL) {
2647 return TCL_ERROR;
2648 }
2649 FsUpdateCwd(normDirName);
2650 }
2651 } else {
2652 Tcl_SetErrno(ENOENT);
2653 }
2654
2655 return (retVal);
2656 }
2657
2658 /*
2659 *----------------------------------------------------------------------
2660 *
2661 * Tcl_FSLoadFile --
2662 *
2663 * Dynamically loads a binary code file into memory and returns
2664 * the addresses of two procedures within that file, if they are
2665 * defined. The appropriate function for the filesystem to which
2666 * pathPtr belongs will be called.
2667 *
2668 * Note that the native filesystem doesn't actually assume
2669 * 'pathPtr' is a path. Rather it assumes filename is either
2670 * a path or just the name of a file which can be found somewhere
2671 * in the environment's loadable path. This behaviour is not
2672 * very compatible with virtual filesystems (and has other problems
2673 * documented in the load man-page), so it is advised that full
2674 * paths are always used.
2675 *
2676 * Results:
2677 * A standard Tcl completion code. If an error occurs, an error
2678 * message is left in the interp's result.
2679 *
2680 * Side effects:
2681 * New code suddenly appears in memory. This may later be
2682 * unloaded by passing the clientData to the unloadProc.
2683 *
2684 *----------------------------------------------------------------------
2685 */
2686
2687 int
2688 Tcl_FSLoadFile(interp, pathPtr, sym1, sym2, proc1Ptr, proc2Ptr,
2689 handlePtr, unloadProcPtr)
2690 Tcl_Interp *interp; /* Used for error reporting. */
2691 Tcl_Obj *pathPtr; /* Name of the file containing the desired
2692 * code. */
2693 CONST char *sym1, *sym2; /* Names of two procedures to look up in
2694 * the file's symbol table. */
2695 Tcl_PackageInitProc **proc1Ptr, **proc2Ptr;
2696 /* Where to return the addresses corresponding
2697 * to sym1 and sym2. */
2698 Tcl_LoadHandle *handlePtr; /* Filled with token for dynamically loaded
2699 * file which will be passed back to
2700 * (*unloadProcPtr)() to unload the file. */
2701 Tcl_FSUnloadFileProc **unloadProcPtr;
2702 /* Filled with address of Tcl_FSUnloadFileProc
2703 * function which should be used for
2704 * this file. */
2705 {
2706 Tcl_Filesystem *fsPtr = Tcl_FSGetFileSystemForPath(pathPtr);
2707 if (fsPtr != NULL) {
2708 Tcl_FSLoadFileProc *proc = fsPtr->loadFileProc;
2709 if (proc != NULL) {
2710 int retVal = (*proc)(interp, pathPtr, handlePtr, unloadProcPtr);
2711 if (retVal != TCL_OK) {
2712 return retVal;
2713 }
2714 if (*handlePtr == NULL) {
2715 return TCL_ERROR;
2716 }
2717 if (sym1 != NULL) {
2718 *proc1Ptr = TclpFindSymbol(interp, *handlePtr, sym1);
2719 }
2720 if (sym2 != NULL) {
2721 *proc2Ptr = TclpFindSymbol(interp, *handlePtr, sym2);
2722 }
2723 return retVal;
2724 } else {
2725 Tcl_Filesystem *copyFsPtr;
2726 Tcl_Obj *copyToPtr;
2727
2728 /* First check if it is readable -- and exists! */
2729 if (Tcl_FSAccess(pathPtr, R_OK) != 0) {
2730 Tcl_AppendResult(interp, "couldn't load library \"",
2731 Tcl_GetString(pathPtr), "\": ",
2732 Tcl_PosixError(interp), (char *) NULL);
2733 return TCL_ERROR;
2734 }
2735
2736 /*
2737 * Get a temporary filename to use, first to
2738 * copy the file into, and then to load.
2739 */
2740 copyToPtr = TclpTempFileName();
2741 if (copyToPtr == NULL) {
2742 return -1;
2743 }
2744 Tcl_IncrRefCount(copyToPtr);
2745
2746 copyFsPtr = Tcl_FSGetFileSystemForPath(copyToPtr);
2747 if ((copyFsPtr == NULL) || (copyFsPtr == fsPtr)) {
2748 /*
2749 * We already know we can't use Tcl_FSLoadFile from
2750 * this filesystem, and we must avoid a possible
2751 * infinite loop. Try to delete the file we
2752 * probably created, and then exit.
2753 */
2754 Tcl_FSDeleteFile(copyToPtr);
2755 Tcl_DecrRefCount(copyToPtr);
2756 return -1;
2757 }
2758
2759 if (TclCrossFilesystemCopy(interp, pathPtr,
2760 copyToPtr) == TCL_OK) {
2761 Tcl_LoadHandle newLoadHandle = NULL;
2762 Tcl_FSUnloadFileProc *newUnloadProcPtr = NULL;
2763 FsDivertLoad *tvdlPtr;
2764 int retVal;
2765
2766 #if !defined(__WIN32__) && !defined(MAC_TCL)
2767 /*
2768 * Do we need to set appropriate permissions
2769 * on the file? This may be required on some
2770 * systems. On Unix we could loop over
2771 * the file attributes, and set any that are
2772 * called "-permissions" to 0700. However,
2773 * we just do this directly, like this:
2774 */
2775
2776 Tcl_Obj* perm = Tcl_NewStringObj("0700",-1);
2777 Tcl_IncrRefCount(perm);
2778 Tcl_FSFileAttrsSet(NULL, 2, copyToPtr, perm);
2779 Tcl_DecrRefCount(perm);
2780 #endif
2781
2782 /*
2783 * We need to reset the result now, because the cross-
2784 * filesystem copy may have stored the number of bytes
2785 * in the result
2786 */
2787 Tcl_ResetResult(interp);
2788
2789 retVal = Tcl_FSLoadFile(interp, copyToPtr, sym1, sym2,
2790 proc1Ptr, proc2Ptr,
2791 &newLoadHandle,
2792 &newUnloadProcPtr);
2793 if (retVal != TCL_OK) {
2794 /* The file didn't load successfully */
2795 Tcl_FSDeleteFile(copyToPtr);
2796 Tcl_DecrRefCount(copyToPtr);
2797 return retVal;
2798 }
2799 /*
2800 * Try to delete the file immediately -- this is
2801 * possible in some OSes, and avoids any worries
2802 * about leaving the copy laying around on exit.
2803 */
2804 if (Tcl_FSDeleteFile(copyToPtr) == TCL_OK) {
2805 Tcl_DecrRefCount(copyToPtr);
2806 /*
2807 * We tell our caller about the real shared
2808 * library which was loaded. Note that this
2809 * does mean that the package list maintained
2810 * by 'load' will store the original (vfs)
2811 * path alongside the temporary load handle
2812 * and unload proc ptr.
2813 */
2814 (*handlePtr) = newLoadHandle;
2815 (*unloadProcPtr) = newUnloadProcPtr;
2816 return TCL_OK;
2817 }
2818 /*
2819 * When we unload this file, we need to divert the
2820 * unloading so we can unload and cleanup the
2821 * temporary file correctly.
2822 */
2823 tvdlPtr = (FsDivertLoad*) ckalloc(sizeof(FsDivertLoad));
2824
2825 /*
2826 * Remember three pieces of information. This allows
2827 * us to cleanup the diverted load completely, on
2828 * platforms which allow proper unloading of code.
2829 */
2830 tvdlPtr->loadHandle = newLoadHandle;
2831 tvdlPtr->unloadProcPtr = newUnloadProcPtr;
2832
2833 if (copyFsPtr != &tclNativeFilesystem) {
2834 /* copyToPtr is already incremented for this reference */
2835 tvdlPtr->divertedFile = copyToPtr;
2836
2837 /*
2838 * This is the filesystem we loaded it into. Since
2839 * we have a reference to 'copyToPtr', we already
2840 * have a refCount on this filesystem, so we don't
2841 * need to worry about it disappearing on us.
2842 */
2843 tvdlPtr->divertedFilesystem = copyFsPtr;
2844 tvdlPtr->divertedFileNativeRep = NULL;
2845 } else {
2846 /* We need the native rep */
2847 tvdlPtr->divertedFileNativeRep =
2848 NativeDupInternalRep(Tcl_FSGetInternalRep(copyToPtr,
2849 copyFsPtr));
2850 /*
2851 * We don't need or want references to the copied
2852 * Tcl_Obj or the filesystem if it is the native
2853 * one.
2854 */
2855 tvdlPtr->divertedFile = NULL;
2856 tvdlPtr->divertedFilesystem = NULL;
2857 Tcl_DecrRefCount(copyToPtr);
2858 }
2859
2860 copyToPtr = NULL;
2861 (*handlePtr) = (Tcl_LoadHandle) tvdlPtr;
2862 (*unloadProcPtr) = &FSUnloadTempFile;
2863 return retVal;
2864 } else {
2865 /* Cross-platform copy failed */
2866 Tcl_FSDeleteFile(copyToPtr);
2867 Tcl_DecrRefCount(copyToPtr);
2868 return TCL_ERROR;
2869 }
2870 }
2871 }
2872 Tcl_SetErrno(ENOENT);
2873 return -1;
2874 }
2875 /*
2876 * This function used to be in the platform specific directories, but it
2877 * has now been made to work cross-platform
2878 */
2879 int
2880 TclpLoadFile(interp, pathPtr, sym1, sym2, proc1Ptr, proc2Ptr,
2881 clientDataPtr, unloadProcPtr)
2882 Tcl_Interp *interp; /* Used for error reporting. */
2883 Tcl_Obj *pathPtr; /* Name of the file containing the desired
2884 * code (UTF-8). */
2885 CONST char *sym1, *sym2; /* Names of two procedures to look up in
2886 * the file's symbol table. */
2887 Tcl_PackageInitProc **proc1Ptr, **proc2Ptr;
2888 /* Where to return the addresses corresponding
2889 * to sym1 and sym2. */
2890 ClientData *clientDataPtr; /* Filled with token for dynamically loaded
2891 * file which will be passed back to
2892 * (*unloadProcPtr)() to unload the file. */
2893 Tcl_FSUnloadFileProc **unloadProcPtr;
2894 /* Filled with address of Tcl_FSUnloadFileProc
2895 * function which should be used for
2896 * this file. */
2897 {
2898 Tcl_LoadHandle handle = NULL;
2899 int res;
2900
2901 res = TclpDlopen(interp, pathPtr, &handle, unloadProcPtr);
2902
2903 if (res != TCL_OK) {
2904 return res;
2905 }
2906
2907 if (handle == NULL) {
2908 return TCL_ERROR;
2909 }
2910
2911 *clientDataPtr = (ClientData)handle;
2912
2913 *proc1Ptr = TclpFindSymbol(interp, handle, sym1);
2914 *proc2Ptr = TclpFindSymbol(interp, handle, sym2);
2915 return TCL_OK;
2916 }
2917
2918 /*
2919 *---------------------------------------------------------------------------
2920 *
2921 * FSUnloadTempFile --
2922 *
2923 * This function is called when we loaded a library of code via
2924 * an intermediate temporary file. This function ensures
2925 * the library is correctly unloaded and the temporary file
2926 * is correctly deleted.
2927 *
2928 * Results:
2929 * None.
2930 *
2931 * Side effects:
2932 * The effects of the 'unload' function called, and of course
2933 * the temporary file will be deleted.
2934 *
2935 *---------------------------------------------------------------------------
2936 */
2937 static void
2938 FSUnloadTempFile(loadHandle)
2939 Tcl_LoadHandle loadHandle; /* loadHandle returned by a previous call
2940 * to Tcl_FSLoadFile(). The loadHandle is
2941 * a token that represents the loaded
2942 * file. */
2943 {
2944 FsDivertLoad *tvdlPtr = (FsDivertLoad*)loadHandle;
2945 /*
2946 * This test should never trigger, since we give
2947 * the client data in the function above.
2948 */
2949 if (tvdlPtr == NULL) { return; }
2950
2951 /*
2952 * Call the real 'unloadfile' proc we actually used. It is very
2953 * important that we call this first, so that the shared library
2954 * is actually unloaded by the OS. Otherwise, the following
2955 * 'delete' may well fail because the shared library is still in
2956 * use.
2957 */
2958 if (tvdlPtr->unloadProcPtr != NULL) {
2959 (*tvdlPtr->unloadProcPtr)(tvdlPtr->loadHandle);
2960 }
2961
2962 if (tvdlPtr->divertedFilesystem == NULL) {
2963 /*
2964 * It was the native filesystem, and we have a special
2965 * function available just for this purpose, which we
2966 * know works even at this late stage.
2967 */
2968 TclpDeleteFile(tvdlPtr->divertedFileNativeRep);
2969 NativeFreeInternalRep(tvdlPtr->divertedFileNativeRep);
2970 } else {
2971 /*
2972 * Remove the temporary file we created. Note, we may crash
2973 * here because encodings have been taken down already.
2974 */
2975 if (tvdlPtr->divertedFilesystem->deleteFileProc(tvdlPtr->divertedFile)
2976 != TCL_OK) {
2977 /*
2978 * The above may have failed because the filesystem, or something
2979 * it depends upon (e.g. encodings) have been taken down because
2980 * Tcl is exiting.
2981 *
2982 * We may need to work out how to delete this file more
2983 * robustly (or give the filesystem the information it needs
2984 * to delete the file more robustly).
2985 *
2986 * In particular, one problem might be that the filesystem
2987 * cannot extract the information it needs from the above
2988 * path object because Tcl's entire filesystem apparatus
2989 * (the code in this file) has been finalized, and it
2990 * refuses to pass the internal representation to the
2991 * filesystem.
2992 */
2993 }
2994
2995 /*
2996 * And free up the allocations. This will also of course remove
2997 * a refCount from the Tcl_Filesystem to which this file belongs,
2998 * which could then free up the filesystem if we are exiting.
2999 */
3000 Tcl_DecrRefCount(tvdlPtr->divertedFile);
3001 }
3002
3003 ckfree((char*)tvdlPtr);
3004 }
3005
3006 /*
3007 *---------------------------------------------------------------------------
3008 *
3009 * Tcl_FSLink --
3010 *
3011 * This function replaces the library version of readlink() and
3012 * can also be used to make links. The appropriate function for
3013 * the filesystem to which pathPtr belongs will be called.
3014 *
3015 * Results:
3016 * If toPtr is NULL, then the result is a Tcl_Obj specifying the
3017 * contents of the symbolic link given by 'pathPtr', or NULL if
3018 * the symbolic link could not be read. The result is owned by
3019 * the caller, which should call Tcl_DecrRefCount when the result
3020 * is no longer needed.
3021 *
3022 * If toPtr is non-NULL, then the result is toPtr if the link action
3023 * was successful, or NULL if not. In this case the result has no
3024 * additional reference count, and need not be freed. The actual
3025 * action to perform is given by the 'linkAction' flags, which is
3026 * an or'd combination of:
3027 *
3028 * TCL_CREATE_SYMBOLIC_LINK
3029 * TCL_CREATE_HARD_LINK
3030 *
3031 * Note that most filesystems will not support linking across
3032 * to different filesystems, so this function will usually
3033 * fail unless toPtr is in the same FS as pathPtr.
3034 *
3035 * Side effects:
3036 * See readlink() documentation. A new filesystem link
3037 * object may appear
3038 *
3039 *---------------------------------------------------------------------------
3040 */
3041
3042 Tcl_Obj *
3043 Tcl_FSLink(pathPtr, toPtr, linkAction)
3044 Tcl_Obj *pathPtr; /* Path of file to readlink or link */
3045 Tcl_Obj *toPtr; /* NULL or path to be linked to */
3046 int linkAction; /* Action to perform */
3047 {
3048 Tcl_Filesystem *fsPtr = Tcl_FSGetFileSystemForPath(pathPtr);
3049 if (fsPtr != NULL) {
3050 Tcl_FSLinkProc *proc = fsPtr->linkProc;
3051 if (proc != NULL) {
3052 return (*proc)(pathPtr, toPtr, linkAction);
3053 }
3054 }
3055 /*
3056 * If S_IFLNK isn't defined it means that the machine doesn't
3057 * support symbolic links, so the file can't possibly be a
3058 * symbolic link. Generate an EINVAL error, which is what
3059 * happens on machines that do support symbolic links when
3060 * you invoke readlink on a file that isn't a symbolic link.
3061 */
3062 #ifndef S_IFLNK
3063 errno = EINVAL;
3064 #else
3065 Tcl_SetErrno(ENOENT);
3066 #endif /* S_IFLNK */
3067 return NULL;
3068 }
3069
3070 /*
3071 *---------------------------------------------------------------------------
3072 *
3073 * Tcl_FSListVolumes --
3074 *
3075 * Lists the currently mounted volumes. The chain of functions
3076 * that have been "inserted" into the filesystem will be called in
3077 * succession; each may return a list of volumes, all of which are
3078 * added to the result until all mounted file systems are listed.
3079 *
3080 * Notice that we assume the lists returned by each filesystem
3081 * (if non NULL) have been given a refCount for us already.
3082 * However, we are NOT allowed to hang on to the list itself
3083 * (it belongs to the filesystem we called). Therefore we
3084 * quite naturally add its contents to the result we are
3085 * building, and then decrement the refCount.
3086 *
3087 * Results:
3088 * The list of volumes, in an object which has refCount 0.
3089 *
3090 * Side effects:
3091 * None
3092 *
3093 *---------------------------------------------------------------------------
3094 */
3095
3096 Tcl_Obj*
3097 Tcl_FSListVolumes(void)
3098 {
3099 FilesystemRecord *fsRecPtr;
3100 Tcl_Obj *resultPtr = Tcl_NewObj();
3101
3102 /*
3103 * Call each of the "listVolumes" function in succession.
3104 * A non-NULL return value indicates the particular function has
3105 * succeeded. We call all the functions registered, since we want
3106 * a list of all drives from all filesystems.
3107 */
3108
3109 fsRecPtr = FsGetFirstFilesystem();
3110 while (fsRecPtr != NULL) {
3111 Tcl_FSListVolumesProc *proc = fsRecPtr->fsPtr->listVolumesProc;
3112 if (proc != NULL) {
3113 Tcl_Obj *thisFsVolumes = (*proc)();
3114 if (thisFsVolumes != NULL) {
3115 Tcl_ListObjAppendList(NULL, resultPtr, thisFsVolumes);
3116 Tcl_DecrRefCount(thisFsVolumes);
3117 }
3118 }
3119 fsRecPtr = fsRecPtr->nextPtr;
3120 }
3121
3122 return resultPtr;
3123 }
3124
3125 /*
3126 *---------------------------------------------------------------------------
3127 *
3128 * FsListMounts --
3129 *
3130 * List all mounts within the given directory, which match the
3131 * given pattern.
3132 *
3133 * Results:
3134 * The list of mounts, in a list object which has refCount 0, or
3135 * NULL if we didn't even find any filesystems to try to list
3136 * mounts.
3137 *
3138 * Side effects:
3139 * None
3140 *
3141 *---------------------------------------------------------------------------
3142 */
3143
3144 static Tcl_Obj*
3145 FsListMounts(pathPtr, pattern)
3146 Tcl_Obj *pathPtr; /* Contains path to directory to search. */
3147 CONST char *pattern; /* Pattern to match against. */
3148 {
3149 FilesystemRecord *fsRecPtr;
3150 Tcl_GlobTypeData mountsOnly = { TCL_GLOB_TYPE_MOUNT, 0, NULL, NULL };
3151 Tcl_Obj *resultPtr = NULL;
3152
3153 /*
3154 * Call each of the "listMounts" functions in succession.
3155 * A non-NULL return value indicates the particular function has
3156 * succeeded. We call all the functions registered, since we want
3157 * a list from each filesystems.
3158 */
3159
3160 fsRecPtr = FsGetFirstFilesystem();
3161 while (fsRecPtr != NULL) {
3162 if (fsRecPtr != &nativeFilesystemRecord) {
3163 Tcl_FSMatchInDirectoryProc *proc =
3164 fsRecPtr->fsPtr->matchInDirectoryProc;
3165 if (proc != NULL) {
3166 if (resultPtr == NULL) {
3167 resultPtr = Tcl_NewObj();
3168 }
3169 (*proc)(NULL, resultPtr, pathPtr, pattern, &mountsOnly);
3170 }
3171 }
3172 fsRecPtr = fsRecPtr->nextPtr;
3173 }
3174
3175 return resultPtr;
3176 }
3177
3178 /*
3179 *---------------------------------------------------------------------------
3180 *
3181 * Tcl_FSSplitPath --
3182 *
3183 * This function takes the given Tcl_Obj, which should be a valid
3184 * path, and returns a Tcl List object containing each segment of
3185 * that path as an element.
3186 *
3187 * Results:
3188 * Returns list object with refCount of zero. If the passed in
3189 * lenPtr is non-NULL, we use it to return the number of elements
3190 * in the returned list.
3191 *
3192 * Side effects:
3193 * None.
3194 *
3195 *---------------------------------------------------------------------------
3196 */
3197
3198 Tcl_Obj*
3199 Tcl_FSSplitPath(pathPtr, lenPtr)
3200 Tcl_Obj *pathPtr; /* Path to split. */
3201 int *lenPtr; /* int to store number of path elements. */
3202 {
3203 Tcl_Obj *result = NULL; /* Needed only to prevent gcc warnings. */
3204 Tcl_Filesystem *fsPtr;
3205 char separator = '/';
3206 int driveNameLength;
3207 char *p;
3208
3209 /*
3210 * Perform platform specific splitting.
3211 */
3212
3213 if (FSGetPathType(pathPtr, &fsPtr, &driveNameLength)
3214 == TCL_PATH_ABSOLUTE) {
3215 if (fsPtr == &tclNativeFilesystem) {
3216 return TclpNativeSplitPath(pathPtr, lenPtr);
3217 }
3218 } else {
3219 return TclpNativeSplitPath(pathPtr, lenPtr);
3220 }
3221
3222 /* We assume separators are single characters */
3223 if (fsPtr->filesystemSeparatorProc != NULL) {
3224 Tcl_Obj *sep = (*fsPtr->filesystemSeparatorProc)(pathPtr);
3225 if (sep != NULL) {
3226 separator = Tcl_GetString(sep)[0];
3227 }
3228 }
3229
3230 /*
3231 * Place the drive name as first element of the
3232 * result list. The drive name may contain strange
3233 * characters, like colons and multiple forward slashes
3234 * (for example 'ftp://' is a valid vfs drive name)
3235 */
3236 result = Tcl_NewObj();
3237 p = Tcl_GetString(pathPtr);
3238 Tcl_ListObjAppendElement(NULL, result,
3239 Tcl_NewStringObj(p, driveNameLength));
3240 p+= driveNameLength;
3241
3242 /* Add the remaining path elements to the list */
3243 for (;;) {
3244 char *elementStart = p;
3245 int length;
3246 while ((*p != '\0') && (*p != separator)) {
3247 p++;
3248 }
3249 length = p - elementStart;
3250 if (length > 0) {
3251 Tcl_Obj *nextElt;
3252 if (elementStart[0] == '~') {
3253 nextElt = Tcl_NewStringObj("./",2);
3254 Tcl_AppendToObj(nextElt, elementStart, length);
3255 } else {
3256 nextElt = Tcl_NewStringObj(elementStart, length);
3257 }
3258 Tcl_ListObjAppendElement(NULL, result, nextElt);
3259 }
3260 if (*p++ == '\0') {
3261 break;
3262 }
3263 }
3264
3265 /*
3266 * Compute the number of elements in the result.
3267 */
3268
3269 if (lenPtr != NULL) {
3270 Tcl_ListObjLength(NULL, result, lenPtr);
3271 }
3272 return result;
3273 }
3274
3275 /* Simple helper function */
3276 Tcl_Obj*
3277 TclFSInternalToNormalized(fromFilesystem, clientData, fsRecPtrPtr)
3278 Tcl_Filesystem *fromFilesystem;
3279 ClientData clientData;
3280 FilesystemRecord **fsRecPtrPtr;
3281 {
3282 FilesystemRecord *fsRecPtr = FsGetFirstFilesystem();
3283
3284 while (fsRecPtr != NULL) {
3285 if (fsRecPtr->fsPtr == fromFilesystem) {
3286 *fsRecPtrPtr = fsRecPtr;
3287 break;
3288 }
3289 fsRecPtr = fsRecPtr->nextPtr;
3290 }
3291
3292 if ((fsRecPtr != NULL)
3293 && (fromFilesystem->internalToNormalizedProc != NULL)) {
3294 return (*fromFilesystem->internalToNormalizedProc)(clientData);
3295 } else {
3296 return NULL;
3297 }
3298 }
3299
3300 /*
3301 *----------------------------------------------------------------------
3302 *
3303 * GetPathType --
3304 *
3305 * Helper function used by FSGetPathType.
3306 *
3307 * Results:
3308 * Returns one of TCL_PATH_ABSOLUTE, TCL_PATH_RELATIVE, or
3309 * TCL_PATH_VOLUME_RELATIVE. The filesystem reference will
3310 * be set if and only if it is non-NULL and the function's
3311 * return value is TCL_PATH_ABSOLUTE.
3312 *
3313 * Side effects:
3314 * None.
3315 *
3316 *----------------------------------------------------------------------
3317 */
3318
3319 Tcl_PathType
3320 GetPathType(pathObjPtr, filesystemPtrPtr, driveNameLengthPtr, driveNameRef)
3321 Tcl_Obj *pathObjPtr;
3322 Tcl_Filesystem **filesystemPtrPtr;
3323 int *driveNameLengthPtr;
3324 Tcl_Obj **driveNameRef;
3325 {
3326 FilesystemRecord *fsRecPtr;
3327 int pathLen;
3328 char *path;
3329 Tcl_PathType type = TCL_PATH_RELATIVE;
3330
3331 path = Tcl_GetStringFromObj(pathObjPtr, &pathLen);
3332
3333 /*
3334 * Call each of the "listVolumes" function in succession, checking
3335 * whether the given path is an absolute path on any of the volumes
3336 * returned (this is done by checking whether the path's prefix
3337 * matches).
3338 */
3339
3340 fsRecPtr = FsGetFirstFilesystem();
3341 while (fsRecPtr != NULL) {
3342 Tcl_FSListVolumesProc *proc = fsRecPtr->fsPtr->listVolumesProc;
3343 /*
3344 * We want to skip the native filesystem in this loop because
3345 * otherwise we won't necessarily pass all the Tcl testsuite --
3346 * this is because some of the tests artificially change the
3347 * current platform (between mac, win, unix) but the list
3348 * of volumes we get by calling (*proc) will reflect the current
3349 * (real) platform only and this may cause some tests to fail.
3350 * In particular, on unix '/' will match the beginning of
3351 * certain absolute Windows paths starting '//' and those tests
3352 * will go wrong.
3353 *
3354 * Besides these test-suite issues, there is one other reason
3355 * to skip the native filesystem --- since the tclFilename.c
3356 * code has nice fast 'absolute path' checkers, we don't want
3357 * to waste time repeating that effort here, and this
3358 * function is actually called quite often, so if we can
3359 * save the overhead of the native filesystem returning us
3360 * a list of volumes all the time, it is better.
3361 */
3362 if ((fsRecPtr->fsPtr != &tclNativeFilesystem) && (proc != NULL)) {
3363 int numVolumes;
3364 Tcl_Obj *thisFsVolumes = (*proc)();
3365 if (thisFsVolumes != NULL) {
3366 if (Tcl_ListObjLength(NULL, thisFsVolumes,
3367 &numVolumes) != TCL_OK) {
3368 /*
3369 * This is VERY bad; the Tcl_FSListVolumesProc
3370 * didn't return a valid list. Set numVolumes to
3371 * -1 so that we skip the while loop below and just
3372 * return with the current value of 'type'.
3373 *
3374 * It would be better if we could signal an error
3375 * here (but panic seems a bit excessive).
3376 */
3377 numVolumes = -1;
3378 }
3379 while (numVolumes > 0) {
3380 Tcl_Obj *vol;
3381 int len;
3382 char *strVol;
3383
3384 numVolumes--;
3385 Tcl_ListObjIndex(NULL, thisFsVolumes, numVolumes, &vol);
3386 strVol = Tcl_GetStringFromObj(vol,&len);
3387 if (pathLen < len) {
3388 continue;
3389 }
3390 if (strncmp(strVol, path, (size_t) len) == 0) {
3391 type = TCL_PATH_ABSOLUTE;
3392 if (filesystemPtrPtr != NULL) {
3393 *filesystemPtrPtr = fsRecPtr->fsPtr;
3394 }
3395 if (driveNameLengthPtr != NULL) {
3396 *driveNameLengthPtr = len;
3397 }
3398 if (driveNameRef != NULL) {
3399 *driveNameRef = vol;
3400 Tcl_IncrRefCount(vol);
3401 }
3402 break;
3403 }
3404 }
3405 Tcl_DecrRefCount(thisFsVolumes);
3406 if (type == TCL_PATH_ABSOLUTE) {
3407 /* We don't need to examine any more filesystems */
3408 break;
3409 }
3410 }
3411 }
3412 fsRecPtr = fsRecPtr->nextPtr;
3413 }
3414
3415 if (type != TCL_PATH_ABSOLUTE) {
3416 type = TclpGetNativePathType(pathObjPtr, driveNameLengthPtr,
3417 driveNameRef);
3418 if ((type == TCL_PATH_ABSOLUTE) && (filesystemPtrPtr != NULL)) {
3419 *filesystemPtrPtr = &tclNativeFilesystem;
3420 }
3421 }
3422 return type;
3423 }
3424
3425 /*
3426 *---------------------------------------------------------------------------
3427 *
3428 * Tcl_FSRenameFile --
3429 *
3430 * If the two paths given belong to the same filesystem, we call
3431 * that filesystems rename function. Otherwise we simply
3432 * return the posix error 'EXDEV', and -1.
3433 *
3434 * Results:
3435 * Standard Tcl error code if a function was called.
3436 *
3437 * Side effects:
3438 * A file may be renamed.
3439 *
3440 *---------------------------------------------------------------------------
3441 */
3442
3443 int
3444 Tcl_FSRenameFile(srcPathPtr, destPathPtr)
3445 Tcl_Obj* srcPathPtr; /* Pathname of file or dir to be renamed
3446 * (UTF-8). */
3447 Tcl_Obj *destPathPtr; /* New pathname of file or directory
3448 * (UTF-8). */
3449 {
3450 int retVal = -1;
3451 Tcl_Filesystem *fsPtr, *fsPtr2;
3452 fsPtr = Tcl_FSGetFileSystemForPath(srcPathPtr);
3453 fsPtr2 = Tcl_FSGetFileSystemForPath(destPathPtr);
3454
3455 if (fsPtr == fsPtr2 && fsPtr != NULL) {
3456 Tcl_FSRenameFileProc *proc = fsPtr->renameFileProc;
3457 if (proc != NULL) {
3458 retVal = (*proc)(srcPathPtr, destPathPtr);
3459 }
3460 }
3461 if (retVal == -1) {
3462 Tcl_SetErrno(EXDEV);
3463 }
3464 return retVal;
3465 }
3466
3467 /*
3468 *---------------------------------------------------------------------------
3469 *
3470 * Tcl_FSCopyFile --
3471 *
3472 * If the two paths given belong to the same filesystem, we call
3473 * that filesystem's copy function. Otherwise we simply
3474 * return the posix error 'EXDEV', and -1.
3475 *
3476 * Note that in the native filesystems, 'copyFileProc' is defined
3477 * to copy soft links (i.e. it copies the links themselves, not
3478 * the things they point to).
3479 *
3480 * Results:
3481 * Standard Tcl error code if a function was called.
3482 *
3483 * Side effects:
3484 * A file may be copied.
3485 *
3486 *---------------------------------------------------------------------------
3487 */
3488
3489 int
3490 Tcl_FSCopyFile(srcPathPtr, destPathPtr)
3491 Tcl_Obj* srcPathPtr; /* Pathname of file to be copied (UTF-8). */
3492 Tcl_Obj *destPathPtr; /* Pathname of file to copy to (UTF-8). */
3493 {
3494 int retVal = -1;
3495 Tcl_Filesystem *fsPtr, *fsPtr2;
3496 fsPtr = Tcl_FSGetFileSystemForPath(srcPathPtr);
3497 fsPtr2 = Tcl_FSGetFileSystemForPath(destPathPtr);
3498
3499 if (fsPtr == fsPtr2 && fsPtr != NULL) {
3500 Tcl_FSCopyFileProc *proc = fsPtr->copyFileProc;
3501 if (proc != NULL) {
3502 retVal = (*proc)(srcPathPtr, destPathPtr);
3503 }
3504 }
3505 if (retVal == -1) {
3506 Tcl_SetErrno(EXDEV);
3507 }
3508 return retVal;
3509 }
3510
3511 /*
3512 *---------------------------------------------------------------------------
3513 *
3514 * TclCrossFilesystemCopy --
3515 *
3516 * Helper for above function, and for Tcl_FSLoadFile, to copy
3517 * files from one filesystem to another. This function will
3518 * overwrite the target file if it already exists.
3519 *
3520 * Results:
3521 * Standard Tcl error code.
3522 *
3523 * Side effects:
3524 * A file may be created.
3525 *
3526 *---------------------------------------------------------------------------
3527 */
3528 int
3529 TclCrossFilesystemCopy(interp, source, target)
3530 Tcl_Interp *interp; /* For error messages */
3531 Tcl_Obj *source; /* Pathname of file to be copied (UTF-8). */
3532 Tcl_Obj *target; /* Pathname of file to copy to (UTF-8). */
3533 {
3534 int result = TCL_ERROR;
3535 int prot = 0666;
3536
3537 Tcl_Channel out = Tcl_FSOpenFileChannel(interp, target, "w", prot);
3538 if (out != NULL) {
3539 /* It looks like we can copy it over */
3540 Tcl_Channel in = Tcl_FSOpenFileChannel(interp, source,
3541 "r", prot);
3542 if (in == NULL) {
3543 /* This is very strange, we checked this above */
3544 Tcl_Close(interp, out);
3545 } else {
3546 Tcl_StatBuf sourceStatBuf;
3547 struct utimbuf tval;
3548 /*
3549 * Copy it synchronously. We might wish to add an
3550 * asynchronous option to support vfs's which are
3551 * slow (e.g. network sockets).
3552 */
3553 Tcl_SetChannelOption(interp, in, "-translation", "binary");
3554 Tcl_SetChannelOption(interp, out, "-translation", "binary");
3555
3556 if (TclCopyChannel(interp, in, out, -1, NULL) == TCL_OK) {
3557 result = TCL_OK;
3558 }
3559 /*
3560 * If the copy failed, assume that copy channel left
3561 * a good error message.
3562 */
3563 Tcl_Close(interp, in);
3564 Tcl_Close(interp, out);
3565
3566 /* Set modification date of copied file */
3567 if (Tcl_FSLstat(source, &sourceStatBuf) == 0) {
3568 tval.actime = sourceStatBuf.st_atime;
3569 tval.modtime = sourceStatBuf.st_mtime;
3570 Tcl_FSUtime(target, &tval);
3571 }
3572 }
3573 }
3574 return result;
3575 }
3576
3577 /*
3578 *---------------------------------------------------------------------------
3579 *
3580 * Tcl_FSDeleteFile --
3581 *
3582 * The appropriate function for the filesystem to which pathPtr
3583 * belongs will be called.
3584 *
3585 * Results:
3586 * Standard Tcl error code.
3587 *
3588 * Side effects:
3589 * A file may be deleted.
3590 *
3591 *---------------------------------------------------------------------------
3592 */
3593
3594 int
3595 Tcl_FSDeleteFile(pathPtr)
3596 Tcl_Obj *pathPtr; /* Pathname of file to be removed (UTF-8). */
3597 {
3598 Tcl_Filesystem *fsPtr = Tcl_FSGetFileSystemForPath(pathPtr);
3599 if (fsPtr != NULL) {
3600 Tcl_FSDeleteFileProc *proc = fsPtr->deleteFileProc;
3601 if (proc != NULL) {
3602 return (*proc)(pathPtr);
3603 }
3604 }
3605 Tcl_SetErrno(ENOENT);
3606 return -1;
3607 }
3608
3609 /*
3610 *---------------------------------------------------------------------------
3611 *
3612 * Tcl_FSCreateDirectory --
3613 *
3614 * The appropriate function for the filesystem to which pathPtr
3615 * belongs will be called.
3616 *
3617 * Results:
3618 * Standard Tcl error code.
3619 *
3620 * Side effects:
3621 * A directory may be created.
3622 *
3623 *---------------------------------------------------------------------------
3624 */
3625
3626 int
3627 Tcl_FSCreateDirectory(pathPtr)
3628 Tcl_Obj *pathPtr; /* Pathname of directory to create (UTF-8). */
3629 {
3630 Tcl_Filesystem *fsPtr = Tcl_FSGetFileSystemForPath(pathPtr);
3631 if (fsPtr != NULL) {
3632 Tcl_FSCreateDirectoryProc *proc = fsPtr->createDirectoryProc;
3633 if (proc != NULL) {
3634 return (*proc)(pathPtr);
3635 }
3636 }
3637 Tcl_SetErrno(ENOENT);
3638 return -1;
3639 }
3640
3641 /*
3642 *---------------------------------------------------------------------------
3643 *
3644 * Tcl_FSCopyDirectory --
3645 *
3646 * If the two paths given belong to the same filesystem, we call
3647 * that filesystems copy-directory function. Otherwise we simply
3648 * return the posix error 'EXDEV', and -1.
3649 *
3650 * Results:
3651 * Standard Tcl error code if a function was called.
3652 *
3653 * Side effects:
3654 * A directory may be copied.
3655 *
3656 *---------------------------------------------------------------------------
3657 */
3658
3659 int
3660 Tcl_FSCopyDirectory(srcPathPtr, destPathPtr, errorPtr)
3661 Tcl_Obj* srcPathPtr; /* Pathname of directory to be copied
3662 * (UTF-8). */
3663 Tcl_Obj *destPathPtr; /* Pathname of target directory (UTF-8). */
3664 Tcl_Obj **errorPtr; /* If non-NULL, then will be set to a
3665 * new object containing name of file
3666 * causing error, with refCount 1. */
3667 {
3668 int retVal = -1;
3669 Tcl_Filesystem *fsPtr, *fsPtr2;
3670 fsPtr = Tcl_FSGetFileSystemForPath(srcPathPtr);
3671 fsPtr2 = Tcl_FSGetFileSystemForPath(destPathPtr);
3672
3673 if (fsPtr == fsPtr2 && fsPtr != NULL) {
3674 Tcl_FSCopyDirectoryProc *proc = fsPtr->copyDirectoryProc;
3675 if (proc != NULL) {
3676 retVal = (*proc)(srcPathPtr, destPathPtr, errorPtr);
3677 }
3678 }
3679 if (retVal == -1) {
3680 Tcl_SetErrno(EXDEV);
3681 }
3682 return retVal;
3683 }
3684
3685 /*
3686 *---------------------------------------------------------------------------
3687 *
3688 * Tcl_FSRemoveDirectory --
3689 *
3690 * The appropriate function for the filesystem to which pathPtr
3691 * belongs will be called.
3692 *
3693 * Results:
3694 * Standard Tcl error code.
3695 *
3696 * Side effects:
3697 * A directory may be deleted.
3698 *
3699 *---------------------------------------------------------------------------
3700 */
3701
3702 int
3703 Tcl_FSRemoveDirectory(pathPtr, recursive, errorPtr)
3704 Tcl_Obj *pathPtr; /* Pathname of directory to be removed
3705 * (UTF-8). */
3706 int recursive; /* If non-zero, removes directories that
3707 * are nonempty. Otherwise, will only remove
3708 * empty directories. */
3709 Tcl_Obj **errorPtr; /* If non-NULL, then will be set to a
3710 * new object containing name of file
3711 * causing error, with refCount 1. */
3712 {
3713 Tcl_Filesystem *fsPtr = Tcl_FSGetFileSystemForPath(pathPtr);
3714 if (fsPtr != NULL) {
3715 Tcl_FSRemoveDirectoryProc *proc = fsPtr->removeDirectoryProc;
3716 if (proc != NULL) {
3717 if (recursive) {
3718 /*
3719 * We check whether the cwd lies inside this directory
3720 * and move it if it does.
3721 */
3722 Tcl_Obj *cwdPtr = Tcl_FSGetCwd(NULL);
3723 if (cwdPtr != NULL) {
3724 char *cwdStr, *normPathStr;
3725 int cwdLen, normLen;
3726 Tcl_Obj *normPath = Tcl_FSGetNormalizedPath(NULL, pathPtr);
3727 if (normPath != NULL) {
3728 normPathStr = Tcl_GetStringFromObj(normPath, &normLen);
3729 cwdStr = Tcl_GetStringFromObj(cwdPtr, &cwdLen);
3730 if ((cwdLen >= normLen) && (strncmp(normPathStr,
3731 cwdStr, (size_t) normLen) == 0)) {
3732 /*
3733 * the cwd is inside the directory, so we
3734 * perform a 'cd [file dirname $path]'
3735 */
3736 Tcl_Obj *dirPtr = TclFileDirname(NULL, pathPtr);
3737 Tcl_FSChdir(dirPtr);
3738 Tcl_DecrRefCount(dirPtr);
3739 }
3740 }
3741 Tcl_DecrRefCount(cwdPtr);
3742 }
3743 }
3744 return (*proc)(pathPtr, recursive, errorPtr);
3745 }
3746 }
3747 Tcl_SetErrno(ENOENT);
3748 return -1;
3749 }
3750
3751 /*
3752 *---------------------------------------------------------------------------
3753 *
3754 * Tcl_FSGetFileSystemForPath --
3755 *
3756 * This function determines which filesystem to use for a
3757 * particular path object, and returns the filesystem which
3758 * accepts this file. If no filesystem will accept this object
3759 * as a valid file path, then NULL is returned.
3760 *
3761 * Results:
3762 .* NULL or a filesystem which will accept this path.
3763 *
3764 * Side effects:
3765 * The object may be converted to a path type.
3766 *
3767 *---------------------------------------------------------------------------
3768 */
3769
3770 Tcl_Filesystem*
3771 Tcl_FSGetFileSystemForPath(pathObjPtr)
3772 Tcl_Obj* pathObjPtr;
3773 {
3774 FilesystemRecord *fsRecPtr;
3775 Tcl_Filesystem* retVal = NULL;
3776
3777 /*
3778 * If the object has a refCount of zero, we reject it. This
3779 * is to avoid possible segfaults or nondeterministic memory
3780 * leaks (i.e. the user doesn't know if they should decrement
3781 * the ref count on return or not).
3782 */
3783
3784 if (pathObjPtr->refCount == 0) {
3785 panic("Tcl_FSGetFileSystemForPath called with object with refCount == 0");
3786 return NULL;
3787 }
3788
3789 /*
3790 * Check if the filesystem has changed in some way since
3791 * this object's internal representation was calculated.
3792 */
3793 if (TclFSEnsureEpochOk(pathObjPtr, &retVal) != TCL_OK) {
3794 return NULL;
3795 }
3796
3797 /*
3798 * Call each of the "pathInFilesystem" functions in succession. A
3799 * non-return value of -1 indicates the particular function has
3800 * succeeded.
3801 */
3802
3803 fsRecPtr = FsGetFirstFilesystem();
3804 while ((retVal == NULL) && (fsRecPtr != NULL)) {
3805 Tcl_FSPathInFilesystemProc *proc = fsRecPtr->fsPtr->pathInFilesystemProc;
3806 if (proc != NULL) {
3807 ClientData clientData = NULL;
3808 int ret = (*proc)(pathObjPtr, &clientData);
3809 if (ret != -1) {
3810 /*
3811 * We assume the type of pathObjPtr hasn't been changed
3812 * by the above call to the pathInFilesystemProc.
3813 */
3814 TclFSSetPathDetails(pathObjPtr, fsRecPtr, clientData);
3815 retVal = fsRecPtr->fsPtr;
3816 }
3817 }
3818 fsRecPtr = fsRecPtr->nextPtr;
3819 }
3820
3821 return retVal;
3822 }
3823
3824 /*
3825 *---------------------------------------------------------------------------
3826 *
3827 * Tcl_FSGetNativePath --
3828 *
3829 * This function is for use by the Win/Unix/MacOS native filesystems,
3830 * so that they can easily retrieve the native (char* or TCHAR*)
3831 * representation of a path. Other filesystems will probably
3832 * want to implement similar functions. They basically act as a
3833 * safety net around Tcl_FSGetInternalRep. Normally your file-
3834 * system procedures will always be called with path objects
3835 * already converted to the correct filesystem, but if for
3836 * some reason they are called directly (i.e. by procedures
3837 * not in this file), then one cannot necessarily guarantee that
3838 * the path object pointer is from the correct filesystem.
3839 *
3840 * Note: in the future it might be desireable to have separate
3841 * versions of this function with different signatures, for
3842 * example Tcl_FSGetNativeMacPath, Tcl_FSGetNativeUnixPath etc.
3843 * Right now, since native paths are all string based, we use just
3844 * one function. On MacOS we could possibly use an FSSpec or
3845 * FSRef as the native representation.
3846 *
3847 * Results:
3848 * NULL or a valid native path.
3849 *
3850 * Side effects:
3851 * See Tcl_FSGetInternalRep.
3852 *
3853 *---------------------------------------------------------------------------
3854 */
3855
3856 CONST char *
3857 Tcl_FSGetNativePath(pathObjPtr)
3858 Tcl_Obj *pathObjPtr;
3859 {
3860 return (CONST char *)Tcl_FSGetInternalRep(pathObjPtr, &tclNativeFilesystem);
3861 }
3862
3863 /*
3864 *---------------------------------------------------------------------------
3865 *
3866 * NativeCreateNativeRep --
3867 *
3868 * Create a native representation for the given path.
3869 *
3870 * Results:
3871 * None.
3872 *
3873 * Side effects:
3874 * None.
3875 *
3876 *---------------------------------------------------------------------------
3877 */
3878 static ClientData
3879 NativeCreateNativeRep(pathObjPtr)
3880 Tcl_Obj* pathObjPtr;
3881 {
3882 char *nativePathPtr;
3883 Tcl_DString ds;
3884 Tcl_Obj* validPathObjPtr;
3885 int len;
3886 char *str;
3887
3888 /* Make sure the normalized path is set */
3889 validPathObjPtr = Tcl_FSGetNormalizedPath(NULL, pathObjPtr);
3890
3891 str = Tcl_GetStringFromObj(validPathObjPtr, &len);
3892 #ifdef __WIN32__
3893 Tcl_WinUtfToTChar(str, len, &ds);
3894 if (tclWinProcs->useWide) {
3895 len = Tcl_DStringLength(&ds) + sizeof(WCHAR);
3896 } else {
3897 len = Tcl_DStringLength(&ds) + sizeof(char);
3898 }
3899 #else
3900 Tcl_UtfToExternalDString(NULL, str, len, &ds);
3901 len = Tcl_DStringLength(&ds) + sizeof(char);
3902 #endif
3903 nativePathPtr = ckalloc((unsigned) len);
3904 memcpy((VOID*)nativePathPtr, (VOID*)Tcl_DStringValue(&ds), (size_t) len);
3905
3906 Tcl_DStringFree(&ds);
3907 return (ClientData)nativePathPtr;
3908 }
3909
3910 /*
3911 *---------------------------------------------------------------------------
3912 *
3913 * TclpNativeToNormalized --
3914 *
3915 * Convert native format to a normalized path object, with refCount
3916 * of zero.
3917 *
3918 * Results:
3919 * A valid normalized path.
3920 *
3921 * Side effects:
3922 * None.
3923 *
3924 *---------------------------------------------------------------------------
3925 */
3926 Tcl_Obj*
3927 TclpNativeToNormalized(clientData)
3928 ClientData clientData;
3929 {
3930 Tcl_DString ds;
3931 Tcl_Obj *objPtr;
3932 CONST char *copy;
3933 int len;
3934
3935 #ifdef __WIN32__
3936 Tcl_WinTCharToUtf((CONST char*)clientData, -1, &ds);
3937 #else
3938 Tcl_ExternalToUtfDString(NULL, (CONST char*)clientData, -1, &ds);
3939 #endif
3940
3941 copy = Tcl_DStringValue(&ds);
3942 len = Tcl_DStringLength(&ds);
3943
3944 #ifdef __WIN32__
3945 /*
3946 * Certain native path representations on Windows have this special
3947 * prefix to indicate that they are to be treated specially. For
3948 * example extremely long paths, or symlinks
3949 */
3950 if (*copy == '\\') {
3951 if (0 == strncmp(copy,"\\??\\",4)) {
3952 copy += 4;
3953 len -= 4;
3954 } else if (0 == strncmp(copy,"\\\\?\\",4)) {
3955 copy += 4;
3956 len -= 4;
3957 }
3958 }
3959 #endif
3960
3961 objPtr = Tcl_NewStringObj(copy,len);
3962 Tcl_DStringFree(&ds);
3963
3964 return objPtr;
3965 }
3966
3967
3968 /*
3969 *---------------------------------------------------------------------------
3970 *
3971 * NativeDupInternalRep --
3972 *
3973 * Duplicate the native representation.
3974 *
3975 * Results:
3976 * The copied native representation, or NULL if it is not possible
3977 * to copy the representation.
3978 *
3979 * Side effects:
3980 * None.
3981 *
3982 *---------------------------------------------------------------------------
3983 */
3984 ClientData
3985 NativeDupInternalRep(clientData)
3986 ClientData clientData;
3987 {
3988 ClientData copy;
3989 size_t len;
3990
3991 if (clientData == NULL) {
3992 return NULL;
3993 }
3994
3995 #ifdef __WIN32__
3996 if (tclWinProcs->useWide) {
3997 /* unicode representation when running on NT/2K/XP */
3998 len = sizeof(WCHAR) + (wcslen((CONST WCHAR*)clientData) * sizeof(WCHAR));
3999 } else {
4000 /* ansi representation when running on 95/98/ME */
4001 len = sizeof(char) + (strlen((CONST char*)clientData) * sizeof(char));
4002 }
4003 #else
4004 /* ansi representation when running on Unix/MacOS */
4005 len = sizeof(char) + (strlen((CONST char*)clientData) * sizeof(char));
4006 #endif
4007
4008 copy = (ClientData) ckalloc(len);
4009 memcpy((VOID*)copy, (VOID*)clientData, len);
4010 return copy;
4011 }
4012
4013 /*
4014 *---------------------------------------------------------------------------
4015 *
4016 * NativeFreeInternalRep --
4017 *
4018 * Free a native internal representation, which will be non-NULL.
4019 *
4020 * Results:
4021 * None.
4022 *
4023 * Side effects:
4024 * Memory is released.
4025 *
4026 *---------------------------------------------------------------------------
4027 */
4028 static void
4029 NativeFreeInternalRep(clientData)
4030 ClientData clientData;
4031 {
4032 ckfree((char*)clientData);
4033 }
4034
4035 /*
4036 *---------------------------------------------------------------------------
4037 *
4038 * Tcl_FSFileSystemInfo --
4039 *
4040 * This function returns a list of two elements. The first
4041 * element is the name of the filesystem (e.g. "native" or "vfs"),
4042 * and the second is the particular type of the given path within
4043 * that filesystem.
4044 *
4045 * Results:
4046 * A list of two elements.
4047 *
4048 * Side effects:
4049 * The object may be converted to a path type.
4050 *
4051 *---------------------------------------------------------------------------
4052 */
4053 Tcl_Obj*
4054 Tcl_FSFileSystemInfo(pathObjPtr)
4055 Tcl_Obj* pathObjPtr;
4056 {
4057 Tcl_Obj *resPtr;
4058 Tcl_FSFilesystemPathTypeProc *proc;
4059 Tcl_Filesystem *fsPtr = Tcl_FSGetFileSystemForPath(pathObjPtr);
4060
4061 if (fsPtr == NULL) {
4062 return NULL;
4063 }
4064
4065 resPtr = Tcl_NewListObj(0,NULL);
4066
4067 Tcl_ListObjAppendElement(NULL, resPtr,
4068 Tcl_NewStringObj(fsPtr->typeName,-1));
4069
4070 proc = fsPtr->filesystemPathTypeProc;
4071 if (proc != NULL) {
4072 Tcl_Obj *typePtr = (*proc)(pathObjPtr);
4073 if (typePtr != NULL) {
4074 Tcl_ListObjAppendElement(NULL, resPtr, typePtr);
4075 }
4076 }
4077
4078 return resPtr;
4079 }
4080
4081 /*
4082 *---------------------------------------------------------------------------
4083 *
4084 * Tcl_FSPathSeparator --
4085 *
4086 * This function returns the separator to be used for a given
4087 * path. The object returned should have a refCount of zero
4088 *
4089 * Results:
4090 * A Tcl object, with a refCount of zero. If the caller
4091 * needs to retain a reference to the object, it should
4092 * call Tcl_IncrRefCount.
4093 *
4094 * Side effects:
4095 * The path object may be converted to a path type.
4096 *
4097 *---------------------------------------------------------------------------
4098 */
4099 Tcl_Obj*
4100 Tcl_FSPathSeparator(pathObjPtr)
4101 Tcl_Obj* pathObjPtr;
4102 {
4103 Tcl_Filesystem *fsPtr = Tcl_FSGetFileSystemForPath(pathObjPtr);
4104
4105 if (fsPtr == NULL) {
4106 return NULL;
4107 }
4108 if (fsPtr->filesystemSeparatorProc != NULL) {
4109 return (*fsPtr->filesystemSeparatorProc)(pathObjPtr);
4110 }
4111
4112 return NULL;
4113 }
4114
4115 /*
4116 *---------------------------------------------------------------------------
4117 *
4118 * NativeFilesystemSeparator --
4119 *
4120 * This function is part of the native filesystem support, and
4121 * returns the separator for the given path.
4122 *
4123 * Results:
4124 * String object containing the separator character.
4125 *
4126 * Side effects:
4127 * None.
4128 *
4129 *---------------------------------------------------------------------------
4130 */
4131 static Tcl_Obj*
4132 NativeFilesystemSeparator(pathObjPtr)
4133 Tcl_Obj* pathObjPtr;
4134 {
4135 char *separator = NULL; /* lint */
4136 switch (tclPlatform) {
4137 case TCL_PLATFORM_UNIX:
4138 separator = "/";
4139 break;
4140 case TCL_PLATFORM_WINDOWS:
4141 separator = "\\";
4142 break;
4143 case TCL_PLATFORM_MAC:
4144 separator = ":";
4145 break;
4146 }
4147 return Tcl_NewStringObj(separator,1);
4148 }
4149
4150 /* Everything from here on is contained in this obsolete ifdef */
4151 #ifdef USE_OBSOLETE_FS_HOOKS
4152
4153 /*
4154 *----------------------------------------------------------------------
4155 *
4156 * TclStatInsertProc --
4157 *
4158 * Insert the passed procedure pointer at the head of the list of
4159 * functions which are used during a call to 'TclStat(...)'. The
4160 * passed function should behave exactly like 'TclStat' when called
4161 * during that time (see 'TclStat(...)' for more information).
4162 * The function will be added even if it already in the list.
4163 *
4164 * Results:
4165 * Normally TCL_OK; TCL_ERROR if memory for a new node in the list
4166 * could not be allocated.
4167 *
4168 * Side effects:
4169 * Memory allocated and modifies the link list for 'TclStat'
4170 * functions.
4171 *
4172 *----------------------------------------------------------------------
4173 */
4174
4175 int
4176 TclStatInsertProc (proc)
4177 TclStatProc_ *proc;
4178 {
4179 int retVal = TCL_ERROR;
4180
4181 if (proc != NULL) {
4182 StatProc *newStatProcPtr;
4183
4184 newStatProcPtr = (StatProc *)ckalloc(sizeof(StatProc));
4185
4186 if (newStatProcPtr != NULL) {
4187 newStatProcPtr->proc = proc;
4188 Tcl_MutexLock(&obsoleteFsHookMutex);
4189 newStatProcPtr->nextPtr = statProcList;
4190 statProcList = newStatProcPtr;
4191 Tcl_MutexUnlock(&obsoleteFsHookMutex);
4192
4193 retVal = TCL_OK;
4194 }
4195 }
4196
4197 return retVal;
4198 }
4199
4200 /*
4201 *----------------------------------------------------------------------
4202 *
4203 * TclStatDeleteProc --
4204 *
4205 * Removed the passed function pointer from the list of 'TclStat'
4206 * functions. Ensures that the built-in stat function is not
4207 * removvable.
4208 *
4209 * Results:
4210 * TCL_OK if the procedure pointer was successfully removed,
4211 * TCL_ERROR otherwise.
4212 *
4213 * Side effects:
4214 * Memory is deallocated and the respective list updated.
4215 *
4216 *----------------------------------------------------------------------
4217 */
4218
4219 int
4220 TclStatDeleteProc (proc)
4221 TclStatProc_ *proc;
4222 {
4223 int retVal = TCL_ERROR;
4224 StatProc *tmpStatProcPtr;
4225 StatProc *prevStatProcPtr = NULL;
4226
4227 Tcl_MutexLock(&obsoleteFsHookMutex);
4228 tmpStatProcPtr = statProcList;
4229 /*
4230 * Traverse the 'statProcList' looking for the particular node
4231 * whose 'proc' member matches 'proc' and remove that one from
4232 * the list. Ensure that the "default" node cannot be removed.
4233 */
4234
4235 while ((retVal == TCL_ERROR) && (tmpStatProcPtr != NULL)) {
4236 if (tmpStatProcPtr->proc == proc) {
4237 if (prevStatProcPtr == NULL) {
4238 statProcList = tmpStatProcPtr->nextPtr;
4239 } else {
4240 prevStatProcPtr->nextPtr = tmpStatProcPtr->nextPtr;
4241 }
4242
4243 ckfree((char *)tmpStatProcPtr);
4244
4245 retVal = TCL_OK;
4246 } else {
4247 prevStatProcPtr = tmpStatProcPtr;
4248 tmpStatProcPtr = tmpStatProcPtr->nextPtr;
4249 }
4250 }
4251
4252 Tcl_MutexUnlock(&obsoleteFsHookMutex);
4253
4254 return retVal;
4255 }
4256
4257 /*
4258 *----------------------------------------------------------------------
4259 *
4260 * TclAccessInsertProc --
4261 *
4262 * Insert the passed procedure pointer at the head of the list of
4263 * functions which are used during a call to 'TclAccess(...)'.
4264 * The passed function should behave exactly like 'TclAccess' when
4265 * called during that time (see 'TclAccess(...)' for more
4266 * information). The function will be added even if it already in
4267 * the list.
4268 *
4269 * Results:
4270 * Normally TCL_OK; TCL_ERROR if memory for a new node in the list
4271 * could not be allocated.
4272 *
4273 * Side effects:
4274 * Memory allocated and modifies the link list for 'TclAccess'
4275 * functions.
4276 *
4277 *----------------------------------------------------------------------
4278 */
4279
4280 int
4281 TclAccessInsertProc(proc)
4282 TclAccessProc_ *proc;
4283 {
4284 int retVal = TCL_ERROR;
4285
4286 if (proc != NULL) {
4287 AccessProc *newAccessProcPtr;
4288
4289 newAccessProcPtr = (AccessProc *)ckalloc(sizeof(AccessProc));
4290
4291 if (newAccessProcPtr != NULL) {
4292 newAccessProcPtr->proc = proc;
4293 Tcl_MutexLock(&obsoleteFsHookMutex);
4294 newAccessProcPtr->nextPtr = accessProcList;
4295 accessProcList = newAccessProcPtr;
4296 Tcl_MutexUnlock(&obsoleteFsHookMutex);
4297
4298 retVal = TCL_OK;
4299 }
4300 }
4301
4302 return retVal;
4303 }
4304
4305 /*
4306 *----------------------------------------------------------------------
4307 *
4308 * TclAccessDeleteProc --
4309 *
4310 * Removed the passed function pointer from the list of 'TclAccess'
4311 * functions. Ensures that the built-in access function is not
4312 * removvable.
4313 *
4314 * Results:
4315 * TCL_OK if the procedure pointer was successfully removed,
4316 * TCL_ERROR otherwise.
4317 *
4318 * Side effects:
4319 * Memory is deallocated and the respective list updated.
4320 *
4321 *----------------------------------------------------------------------
4322 */
4323
4324 int
4325 TclAccessDeleteProc(proc)
4326 TclAccessProc_ *proc;
4327 {
4328 int retVal = TCL_ERROR;
4329 AccessProc *tmpAccessProcPtr;
4330 AccessProc *prevAccessProcPtr = NULL;
4331
4332 /*
4333 * Traverse the 'accessProcList' looking for the particular node
4334 * whose 'proc' member matches 'proc' and remove that one from
4335 * the list. Ensure that the "default" node cannot be removed.
4336 */
4337
4338 Tcl_MutexLock(&obsoleteFsHookMutex);
4339 tmpAccessProcPtr = accessProcList;
4340 while ((retVal == TCL_ERROR) && (tmpAccessProcPtr != NULL)) {
4341 if (tmpAccessProcPtr->proc == proc) {
4342 if (prevAccessProcPtr == NULL) {
4343 accessProcList = tmpAccessProcPtr->nextPtr;
4344 } else {
4345 prevAccessProcPtr->nextPtr = tmpAccessProcPtr->nextPtr;
4346 }
4347
4348 ckfree((char *)tmpAccessProcPtr);
4349
4350 retVal = TCL_OK;
4351 } else {
4352 prevAccessProcPtr = tmpAccessProcPtr;
4353 tmpAccessProcPtr = tmpAccessProcPtr->nextPtr;
4354 }
4355 }
4356 Tcl_MutexUnlock(&obsoleteFsHookMutex);
4357
4358 return retVal;
4359 }
4360
4361 /*
4362 *----------------------------------------------------------------------
4363 *
4364 * TclOpenFileChannelInsertProc --
4365 *
4366 * Insert the passed procedure pointer at the head of the list of
4367 * functions which are used during a call to
4368 * 'Tcl_OpenFileChannel(...)'. The passed function should behave
4369 * exactly like 'Tcl_OpenFileChannel' when called during that time
4370 * (see 'Tcl_OpenFileChannel(...)' for more information). The
4371 * function will be added even if it already in the list.
4372 *
4373 * Results:
4374 * Normally TCL_OK; TCL_ERROR if memory for a new node in the list
4375 * could not be allocated.
4376 *
4377 * Side effects:
4378 * Memory allocated and modifies the link list for
4379 * 'Tcl_OpenFileChannel' functions.
4380 *
4381 *----------------------------------------------------------------------
4382 */
4383
4384 int
4385 TclOpenFileChannelInsertProc(proc)
4386 TclOpenFileChannelProc_ *proc;
4387 {
4388 int retVal = TCL_ERROR;
4389
4390 if (proc != NULL) {
4391 OpenFileChannelProc *newOpenFileChannelProcPtr;
4392
4393 newOpenFileChannelProcPtr =
4394 (OpenFileChannelProc *)ckalloc(sizeof(OpenFileChannelProc));
4395
4396 if (newOpenFileChannelProcPtr != NULL) {
4397 newOpenFileChannelProcPtr->proc = proc;
4398 Tcl_MutexLock(&obsoleteFsHookMutex);
4399 newOpenFileChannelProcPtr->nextPtr = openFileChannelProcList;
4400 openFileChannelProcList = newOpenFileChannelProcPtr;
4401 Tcl_MutexUnlock(&obsoleteFsHookMutex);
4402
4403 retVal = TCL_OK;
4404 }
4405 }
4406
4407 return retVal;
4408 }
4409
4410 /*
4411 *----------------------------------------------------------------------
4412 *
4413 * TclOpenFileChannelDeleteProc --
4414 *
4415 * Removed the passed function pointer from the list of
4416 * 'Tcl_OpenFileChannel' functions. Ensures that the built-in
4417 * open file channel function is not removable.
4418 *
4419 * Results:
4420 * TCL_OK if the procedure pointer was successfully removed,
4421 * TCL_ERROR otherwise.
4422 *
4423 * Side effects:
4424 * Memory is deallocated and the respective list updated.
4425 *
4426 *----------------------------------------------------------------------
4427 */
4428
4429 int
4430 TclOpenFileChannelDeleteProc(proc)
4431 TclOpenFileChannelProc_ *proc;
4432 {
4433 int retVal = TCL_ERROR;
4434 OpenFileChannelProc *tmpOpenFileChannelProcPtr = openFileChannelProcList;
4435 OpenFileChannelProc *prevOpenFileChannelProcPtr = NULL;
4436
4437 /*
4438 * Traverse the 'openFileChannelProcList' looking for the particular
4439 * node whose 'proc' member matches 'proc' and remove that one from
4440 * the list.
4441 */
4442
4443 Tcl_MutexLock(&obsoleteFsHookMutex);
4444 tmpOpenFileChannelProcPtr = openFileChannelProcList;
4445 while ((retVal == TCL_ERROR) &&
4446 (tmpOpenFileChannelProcPtr != NULL)) {
4447 if (tmpOpenFileChannelProcPtr->proc == proc) {
4448 if (prevOpenFileChannelProcPtr == NULL) {
4449 openFileChannelProcList = tmpOpenFileChannelProcPtr->nextPtr;
4450 } else {
4451 prevOpenFileChannelProcPtr->nextPtr =
4452 tmpOpenFileChannelProcPtr->nextPtr;
4453 }
4454
4455 ckfree((char *)tmpOpenFileChannelProcPtr);
4456
4457 retVal = TCL_OK;
4458 } else {
4459 prevOpenFileChannelProcPtr = tmpOpenFileChannelProcPtr;
4460 tmpOpenFileChannelProcPtr = tmpOpenFileChannelProcPtr->nextPtr;
4461 }
4462 }
4463 Tcl_MutexUnlock(&obsoleteFsHookMutex);
4464
4465 return retVal;
4466 }
4467 #endif /* USE_OBSOLETE_FS_HOOKS */
4468
4469
4470 /*
4471 * Prototypes for procedures defined later in this file.
4472 */
4473
4474 static void DupFsPathInternalRep _ANSI_ARGS_((Tcl_Obj *srcPtr,
4475 Tcl_Obj *copyPtr));
4476 static void FreeFsPathInternalRep _ANSI_ARGS_((Tcl_Obj *listPtr));
4477 static void UpdateStringOfFsPath _ANSI_ARGS_((Tcl_Obj *objPtr));
4478 static int SetFsPathFromAny _ANSI_ARGS_((Tcl_Interp *interp,
4479 Tcl_Obj *objPtr));
4480 static int FindSplitPos _ANSI_ARGS_((char *path, char *separator));
4481
4482
4483
4484 /*
4485 * Define the 'path' object type, which Tcl uses to represent
4486 * file paths internally.
4487 */
4488 Tcl_ObjType tclFsPathType = {
4489 "path", /* name */
4490 FreeFsPathInternalRep, /* freeIntRepProc */
4491 DupFsPathInternalRep, /* dupIntRepProc */
4492 UpdateStringOfFsPath, /* updateStringProc */
4493 SetFsPathFromAny /* setFromAnyProc */
4494 };
4495
4496 /*
4497 * struct FsPath --
4498 *
4499 * Internal representation of a Tcl_Obj of "path" type. This
4500 * can be used to represent relative or absolute paths, and has
4501 * certain optimisations when used to represent paths which are
4502 * already normalized and absolute.
4503 *
4504 * Note that 'normPathPtr' can be a circular reference to the
4505 * container Tcl_Obj of this FsPath.
4506 */
4507 typedef struct FsPath {
4508 Tcl_Obj *translatedPathPtr; /* Name without any ~user sequences.
4509 * If this is NULL, then this is a
4510 * pure normalized, absolute path
4511 * object, in which the parent Tcl_Obj's
4512 * string rep is already both translated
4513 * and normalized. */
4514 Tcl_Obj *normPathPtr; /* Normalized absolute path, without
4515 * ., .. or ~user sequences. If the
4516 * Tcl_Obj containing
4517 * this FsPath is already normalized,
4518 * this may be a circular reference back
4519 * to the container. If that is NOT the
4520 * case, we have a refCount on the object. */
4521 Tcl_Obj *cwdPtr; /* If null, path is absolute, else
4522 * this points to the cwd object used
4523 * for this path. We have a refCount
4524 * on the object. */
4525 int flags; /* Flags to describe interpretation */
4526 ClientData nativePathPtr; /* Native representation of this path,
4527 * which is filesystem dependent. */
4528 int filesystemEpoch; /* Used to ensure the path representation
4529 * was generated during the correct
4530 * filesystem epoch. The epoch changes
4531 * when filesystem-mounts are changed. */
4532 struct FilesystemRecord *fsRecPtr;
4533 /* Pointer to the filesystem record
4534 * entry to use for this path. */
4535 } FsPath;
4536
4537 /*
4538 * Define some macros to give us convenient access to path-object
4539 * specific fields.
4540 */
4541 #define PATHOBJ(objPtr) (objPtr->internalRep.otherValuePtr)
4542 #define PATHFLAGS(objPtr) \
4543 (((FsPath*)(objPtr->internalRep.otherValuePtr))->flags)
4544
4545 #define TCLPATH_APPENDED 1
4546 #define TCLPATH_RELATIVE 2
4547
4548 /*
4549 *----------------------------------------------------------------------
4550 *
4551 * Tcl_FSGetPathType --
4552 *
4553 * Determines whether a given path is relative to the current
4554 * directory, relative to the current volume, or absolute.
4555 *
4556 * Results:
4557 * Returns one of TCL_PATH_ABSOLUTE, TCL_PATH_RELATIVE, or
4558 * TCL_PATH_VOLUME_RELATIVE.
4559 *
4560 * Side effects:
4561 * None.
4562 *
4563 *----------------------------------------------------------------------
4564 */
4565
4566 Tcl_PathType
4567 Tcl_FSGetPathType(pathObjPtr)
4568 Tcl_Obj *pathObjPtr;
4569 {
4570 return FSGetPathType(pathObjPtr, NULL, NULL);
4571 }
4572
4573 /*
4574 *----------------------------------------------------------------------
4575 *
4576 * FSGetPathType --
4577 *
4578 * Determines whether a given path is relative to the current
4579 * directory, relative to the current volume, or absolute. If the
4580 * caller wishes to know which filesystem claimed the path (in the
4581 * case for which the path is absolute), then a reference to a
4582 * filesystem pointer can be passed in (but passing NULL is
4583 * acceptable).
4584 *
4585 * Results:
4586 * Returns one of TCL_PATH_ABSOLUTE, TCL_PATH_RELATIVE, or
4587 * TCL_PATH_VOLUME_RELATIVE. The filesystem reference will
4588 * be set if and only if it is non-NULL and the function's
4589 * return value is TCL_PATH_ABSOLUTE.
4590 *
4591 * Side effects:
4592 * None.
4593 *
4594 *----------------------------------------------------------------------
4595 */
4596
4597 Tcl_PathType
4598 FSGetPathType(pathObjPtr, filesystemPtrPtr, driveNameLengthPtr)
4599 Tcl_Obj *pathObjPtr;
4600 Tcl_Filesystem **filesystemPtrPtr;
4601 int *driveNameLengthPtr;
4602 {
4603 if (Tcl_FSConvertToPathType(NULL, pathObjPtr) != TCL_OK) {
4604 return GetPathType(pathObjPtr, filesystemPtrPtr,
4605 driveNameLengthPtr, NULL);
4606 } else {
4607 FsPath *fsPathPtr = (FsPath*) PATHOBJ(pathObjPtr);
4608 if (fsPathPtr->cwdPtr != NULL) {
4609 if (PATHFLAGS(pathObjPtr) == 0) {
4610 return TCL_PATH_RELATIVE;
4611 }
4612 return FSGetPathType(fsPathPtr->cwdPtr, filesystemPtrPtr,
4613 driveNameLengthPtr);
4614 } else {
4615 return GetPathType(pathObjPtr, filesystemPtrPtr,
4616 driveNameLengthPtr, NULL);
4617 }
4618 }
4619 }
4620
4621 /*
4622 *---------------------------------------------------------------------------
4623 *
4624 * Tcl_FSJoinPath --
4625 *
4626 * This function takes the given Tcl_Obj, which should be a valid
4627 * list, and returns the path object given by considering the
4628 * first 'elements' elements as valid path segments. If elements < 0,
4629 * we use the entire list.
4630 *
4631 * Results:
4632 * Returns object with refCount of zero, (or if non-zero, it has
4633 * references elsewhere in Tcl). Either way, the caller must
4634 * increment its refCount before use.
4635 *
4636 * Side effects:
4637 * None.
4638 *
4639 *---------------------------------------------------------------------------
4640 */
4641 Tcl_Obj*
4642 Tcl_FSJoinPath(listObj, elements)
4643 Tcl_Obj *listObj;
4644 int elements;
4645 {
4646 Tcl_Obj *res;
4647 int i;
4648 Tcl_Filesystem *fsPtr = NULL;
4649
4650 if (elements < 0) {
4651 if (Tcl_ListObjLength(NULL, listObj, &elements) != TCL_OK) {
4652 return NULL;
4653 }
4654 } else {
4655 /* Just make sure it is a valid list */
4656 int listTest;
4657 if (Tcl_ListObjLength(NULL, listObj, &listTest) != TCL_OK) {
4658 return NULL;
4659 }
4660 /*
4661 * Correct this if it is too large, otherwise we will
4662 * waste our time joining null elements to the path
4663 */
4664 if (elements > listTest) {
4665 elements = listTest;
4666 }
4667 }
4668
4669 res = Tcl_NewObj();
4670
4671 for (i = 0; i < elements; i++) {
4672 Tcl_Obj *elt;
4673 int driveNameLength;
4674 Tcl_PathType type;
4675 char *strElt;
4676 int strEltLen;
4677 int length;
4678 char *ptr;
4679 Tcl_Obj *driveName = NULL;
4680
4681 Tcl_ListObjIndex(NULL, listObj, i, &elt);
4682
4683 /*
4684 * This is a special case where we can be much more
4685 * efficient, where we are joining a single relative path
4686 * onto an object that is already of path type. The
4687 * 'TclNewFSPathObj' call below creates an object which
4688 * can be normalized more efficiently. Currently we only
4689 * use the special case when we have exactly two elements,
4690 * but we could expand that in the future.
4691 */
4692 if ((i == (elements-2)) && (i == 0) && (elt->typePtr == &tclFsPathType)
4693 && !(elt->bytes != NULL && (elt->bytes[0] == '\0'))) {
4694 Tcl_Obj *tail;
4695 Tcl_PathType type;
4696 Tcl_ListObjIndex(NULL, listObj, i+1, &tail);
4697 type = GetPathType(tail, NULL, NULL, NULL);
4698 if (type == TCL_PATH_RELATIVE) {
4699 CONST char *str;
4700 int len;
4701 str = Tcl_GetStringFromObj(tail,&len);
4702 if (len == 0) {
4703 /*
4704 * This happens if we try to handle the root volume
4705 * '/'. There's no need to return a special path
4706 * object, when the base itself is just fine!
4707 */
4708 Tcl_DecrRefCount(res);
4709 return elt;
4710 }
4711 /*
4712 * If it doesn't begin with '.' and is a mac or unix
4713 * path or it a windows path without backslashes, then we
4714 * can be very efficient here. (In fact even a windows
4715 * path with backslashes can be joined efficiently, but
4716 * the path object would not have forward slashes only,
4717 * and this would therefore contradict our 'file join'
4718 * documentation).
4719 */
4720 if (str[0] != '.' && ((tclPlatform != TCL_PLATFORM_WINDOWS)
4721 || (strchr(str, '\\') == NULL))) {
4722 Tcl_DecrRefCount(res);
4723 return TclNewFSPathObj(elt, str, len);
4724 }
4725 /*
4726 * Otherwise we don't have an easy join, and
4727 * we must let the more general code below handle
4728 * things
4729 */
4730 } else {
4731 if (tclPlatform == TCL_PLATFORM_UNIX) {
4732 Tcl_DecrRefCount(res);
4733 return tail;
4734 } else {
4735 CONST char *str;
4736 int len;
4737 str = Tcl_GetStringFromObj(tail,&len);
4738 if (tclPlatform == TCL_PLATFORM_WINDOWS) {
4739 if (strchr(str, '\\') == NULL) {
4740 Tcl_DecrRefCount(res);
4741 return tail;
4742 }
4743 } else if (tclPlatform == TCL_PLATFORM_MAC) {
4744 if (strchr(str, '/') == NULL) {
4745 Tcl_DecrRefCount(res);
4746 return tail;
4747 }
4748 }
4749 }
4750 }
4751 }
4752 strElt = Tcl_GetStringFromObj(elt, &strEltLen);
4753 type = GetPathType(elt, &fsPtr, &driveNameLength, &driveName);
4754 if (type != TCL_PATH_RELATIVE) {
4755 /* Zero out the current result */
4756 Tcl_DecrRefCount(res);
4757 if (driveName != NULL) {
4758 res = Tcl_DuplicateObj(driveName);
4759 Tcl_DecrRefCount(driveName);
4760 } else {
4761 res = Tcl_NewStringObj(strElt, driveNameLength);
4762 }
4763 strElt += driveNameLength;
4764 }
4765
4766 ptr = Tcl_GetStringFromObj(res, &length);
4767
4768 /*
4769 * Strip off any './' before a tilde, unless this is the
4770 * beginning of the path.
4771 */
4772 if (length > 0 && strEltLen > 0) {
4773 if ((strElt[0] == '.') && (strElt[1] == '/')
4774 && (strElt[2] == '~')) {
4775 strElt += 2;
4776 }
4777 }
4778
4779 /*
4780 * A NULL value for fsPtr at this stage basically means
4781 * we're trying to join a relative path onto something
4782 * which is also relative (or empty). There's nothing
4783 * particularly wrong with that.
4784 */
4785 if (*strElt == '\0') continue;
4786
4787 if (fsPtr == &tclNativeFilesystem || fsPtr == NULL) {
4788 TclpNativeJoinPath(res, strElt);
4789 } else {
4790 char separator = '/';
4791 int needsSep = 0;
4792
4793 if (fsPtr->filesystemSeparatorProc != NULL) {
4794 Tcl_Obj *sep = (*fsPtr->filesystemSeparatorProc)(res);
4795 if (sep != NULL) {
4796 separator = Tcl_GetString(sep)[0];
4797 }
4798 }
4799
4800 if (length > 0 && ptr[length -1] != '/') {
4801 Tcl_AppendToObj(res, &separator, 1);
4802 length++;
4803 }
4804 Tcl_SetObjLength(res, length + (int) strlen(strElt));
4805
4806 ptr = Tcl_GetString(res) + length;
4807 for (; *strElt != '\0'; strElt++) {
4808 if (*strElt == separator) {
4809 while (strElt[1] == separator) {
4810 strElt++;
4811 }
4812 if (strElt[1] != '\0') {
4813 if (needsSep) {
4814 *ptr++ = separator;
4815 }
4816 }
4817 } else {
4818 *ptr++ = *strElt;
4819 needsSep = 1;
4820 }
4821 }
4822 length = ptr - Tcl_GetString(res);
4823 Tcl_SetObjLength(res, length);
4824 }
4825 }
4826 return res;
4827 }
4828
4829 /*
4830 *---------------------------------------------------------------------------
4831 *
4832 * Tcl_FSConvertToPathType --
4833 *
4834 * This function tries to convert the given Tcl_Obj to a valid
4835 * Tcl path type, taking account of the fact that the cwd may
4836 * have changed even if this object is already supposedly of
4837 * the correct type.
4838 *
4839 * The filename may begin with "~" (to indicate current user's
4840 * home directory) or "~<user>" (to indicate any user's home
4841 * directory).
4842 *
4843 * Results:
4844 * Standard Tcl error code.
4845 *
4846 * Side effects:
4847 * The old representation may be freed, and new memory allocated.
4848 *
4849 *---------------------------------------------------------------------------
4850 */
4851 int
4852 Tcl_FSConvertToPathType(interp, objPtr)
4853 Tcl_Interp *interp; /* Interpreter in which to store error
4854 * message (if necessary). */
4855 Tcl_Obj *objPtr; /* Object to convert to a valid, current
4856 * path type. */
4857 {
4858 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
4859
4860 /*
4861 * While it is bad practice to examine an object's type directly,
4862 * this is actually the best thing to do here. The reason is that
4863 * if we are converting this object to FsPath type for the first
4864 * time, we don't need to worry whether the 'cwd' has changed.
4865 * On the other hand, if this object is already of FsPath type,
4866 * and is a relative path, we do have to worry about the cwd.
4867 * If the cwd has changed, we must recompute the path.
4868 */
4869 if (objPtr->typePtr == &tclFsPathType) {
4870 FsPath *fsPathPtr = (FsPath*) PATHOBJ(objPtr);
4871 if (fsPathPtr->filesystemEpoch != tsdPtr->filesystemEpoch) {
4872 if (objPtr->bytes == NULL) {
4873 UpdateStringOfFsPath(objPtr);
4874 }
4875 FreeFsPathInternalRep(objPtr);
4876 objPtr->typePtr = NULL;
4877 return Tcl_ConvertToType(interp, objPtr, &tclFsPathType);
4878 }
4879 return TCL_OK;
4880 } else {
4881 return Tcl_ConvertToType(interp, objPtr, &tclFsPathType);
4882 }
4883 }
4884
4885 /*
4886 * Helper function for SetFsPathFromAny. Returns position of first
4887 * directory delimiter in the path.
4888 */
4889 static int
4890 FindSplitPos(path, separator)
4891 char *path;
4892 char *separator;
4893 {
4894 int count = 0;
4895 switch (tclPlatform) {
4896 case TCL_PLATFORM_UNIX:
4897 case TCL_PLATFORM_MAC:
4898 while (path[count] != 0) {
4899 if (path[count] == *separator) {
4900 return count;
4901 }
4902 count++;
4903 }
4904 break;
4905
4906 case TCL_PLATFORM_WINDOWS:
4907 while (path[count] != 0) {
4908 if (path[count] == *separator || path[count] == '\\') {
4909 return count;
4910 }
4911 count++;
4912 }
4913 break;
4914 }
4915 return count;
4916 }
4917
4918 /*
4919 *---------------------------------------------------------------------------
4920 *
4921 * TclNewFSPathObj --
4922 *
4923 * Creates a path object whose string representation is
4924 * '[file join dirPtr addStrRep]', but does so in a way that
4925 * allows for more efficient caching of normalized paths.
4926 *
4927 * Assumptions:
4928 * 'dirPtr' must be an absolute path.
4929 * 'len' may not be zero.
4930 *
4931 * Results:
4932 * The new Tcl object, with refCount zero.
4933 *
4934 * Side effects:
4935 * Memory is allocated. 'dirPtr' gets an additional refCount.
4936 *
4937 *---------------------------------------------------------------------------
4938 */
4939
4940 Tcl_Obj*
4941 TclNewFSPathObj(Tcl_Obj *dirPtr, CONST char *addStrRep, int len)
4942 {
4943 FsPath *fsPathPtr;
4944 Tcl_Obj *objPtr;
4945 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
4946
4947 objPtr = Tcl_NewObj();
4948 fsPathPtr = (FsPath*)ckalloc((unsigned)sizeof(FsPath));
4949
4950 if (tclPlatform == TCL_PLATFORM_MAC) {
4951 /*
4952 * Mac relative paths may begin with a directory separator ':'.
4953 * If present, we need to skip this ':' because we assume that
4954 * we can join dirPtr and addStrRep by concatenating them as
4955 * strings (and we ensure that dirPtr is terminated by a ':').
4956 */
4957 if (addStrRep[0] == ':') {
4958 addStrRep++;
4959 len--;
4960 }
4961 }
4962 /* Setup the path */
4963 fsPathPtr->translatedPathPtr = NULL;
4964 fsPathPtr->normPathPtr = Tcl_NewStringObj(addStrRep, len);
4965 Tcl_IncrRefCount(fsPathPtr->normPathPtr);
4966 fsPathPtr->cwdPtr = dirPtr;
4967 Tcl_IncrRefCount(dirPtr);
4968 fsPathPtr->nativePathPtr = NULL;
4969 fsPathPtr->fsRecPtr = NULL;
4970 fsPathPtr->filesystemEpoch = tsdPtr->filesystemEpoch;
4971
4972 PATHOBJ(objPtr) = (VOID *) fsPathPtr;
4973 PATHFLAGS(objPtr) = TCLPATH_RELATIVE | TCLPATH_APPENDED;
4974 objPtr->typePtr = &tclFsPathType;
4975 objPtr->bytes = NULL;
4976 objPtr->length = 0;
4977
4978 return objPtr;
4979 }
4980
4981 /*
4982 *---------------------------------------------------------------------------
4983 *
4984 * TclFSMakePathRelative --
4985 *
4986 * Like SetFsPathFromAny, but assumes the given object is an
4987 * absolute normalized path. Only for internal use.
4988 *
4989 * Results:
4990 * Standard Tcl error code.
4991 *
4992 * Side effects:
4993 * The old representation may be freed, and new memory allocated.
4994 *
4995 *---------------------------------------------------------------------------
4996 */
4997
4998 Tcl_Obj*
4999 TclFSMakePathRelative(interp, objPtr, cwdPtr)
5000 Tcl_Interp *interp; /* Used for error reporting if not NULL. */
5001 Tcl_Obj *objPtr; /* The object we have. */
5002 Tcl_Obj *cwdPtr; /* Make it relative to this. */
5003 {
5004 int cwdLen, len;
5005 CONST char *tempStr;
5006 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
5007
5008 if (objPtr->typePtr == &tclFsPathType) {
5009 FsPath *fsPathPtr = (FsPath*) PATHOBJ(objPtr);
5010 if (PATHFLAGS(objPtr) != 0
5011 && fsPathPtr->cwdPtr == cwdPtr) {
5012 objPtr = fsPathPtr->normPathPtr;
5013 /* Free old representation */
5014 if (objPtr->typePtr != NULL) {
5015 if (objPtr->bytes == NULL) {
5016 if (objPtr->typePtr->updateStringProc == NULL) {
5017 if (interp != NULL) {
5018 Tcl_ResetResult(interp);
5019 Tcl_AppendResult(interp, "can't find object",
5020 "string representation", (char *) NULL);
5021 }
5022 return NULL;
5023 }
5024 objPtr->typePtr->updateStringProc(objPtr);
5025 }
5026 if ((objPtr->typePtr->freeIntRepProc) != NULL) {
5027 (*objPtr->typePtr->freeIntRepProc)(objPtr);
5028 }
5029 }
5030
5031 fsPathPtr = (FsPath*)ckalloc((unsigned)sizeof(FsPath));
5032
5033 /* Circular reference, by design */
5034 fsPathPtr->translatedPathPtr = objPtr;
5035 fsPathPtr->normPathPtr = NULL;
5036 fsPathPtr->cwdPtr = cwdPtr;
5037 Tcl_IncrRefCount(cwdPtr);
5038 fsPathPtr->nativePathPtr = NULL;
5039 fsPathPtr->fsRecPtr = NULL;
5040 fsPathPtr->filesystemEpoch = tsdPtr->filesystemEpoch;
5041
5042 PATHOBJ(objPtr) = (VOID *) fsPathPtr;
5043 PATHFLAGS(objPtr) = 0;
5044 objPtr->typePtr = &tclFsPathType;
5045
5046 return objPtr;
5047 }
5048 }
5049 /*
5050 * We know the cwd is a normalised object which does
5051 * not end in a directory delimiter, unless the cwd
5052 * is the name of a volume, in which case it will
5053 * end in a delimiter! We handle this situation here.
5054 * A better test than the '!= sep' might be to simply
5055 * check if 'cwd' is a root volume.
5056 *
5057 * Note that if we get this wrong, we will strip off
5058 * either too much or too little below, leading to
5059 * wrong answers returned by glob.
5060 */
5061 tempStr = Tcl_GetStringFromObj(cwdPtr, &cwdLen);
5062 /*
5063 * Should we perhaps use 'Tcl_FSPathSeparator'?
5064 * But then what about the Windows special case?
5065 * Perhaps we should just check if cwd is a root
5066 * volume.
5067 */
5068 switch (tclPlatform) {
5069 case TCL_PLATFORM_UNIX:
5070 if (tempStr[cwdLen-1] != '/') {
5071 cwdLen++;
5072 }
5073 break;
5074 case TCL_PLATFORM_WINDOWS:
5075 if (tempStr[cwdLen-1] != '/'
5076 && tempStr[cwdLen-1] != '\\') {
5077 cwdLen++;
5078 }
5079 break;
5080 case TCL_PLATFORM_MAC:
5081 if (tempStr[cwdLen-1] != ':') {
5082 cwdLen++;
5083 }
5084 break;
5085 }
5086 tempStr = Tcl_GetStringFromObj(objPtr, &len);
5087
5088 return Tcl_NewStringObj(tempStr + cwdLen, len - cwdLen);
5089 }
5090
5091 /*
5092 *---------------------------------------------------------------------------
5093 *
5094 * TclFSMakePathFromNormalized --
5095 *
5096 * Like SetFsPathFromAny, but assumes the given object is an
5097 * absolute normalized path. Only for internal use.
5098 *
5099 * Results:
5100 * Standard Tcl error code.
5101 *
5102 * Side effects:
5103 * The old representation may be freed, and new memory allocated.
5104 *
5105 *---------------------------------------------------------------------------
5106 */
5107
5108 int
5109 TclFSMakePathFromNormalized(interp, objPtr, nativeRep)
5110 Tcl_Interp *interp; /* Used for error reporting if not NULL. */
5111 Tcl_Obj *objPtr; /* The object to convert. */
5112 ClientData nativeRep; /* The native rep for the object, if known
5113 * else NULL. */
5114 {
5115 FsPath *fsPathPtr;
5116 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
5117
5118 if (objPtr->typePtr == &tclFsPathType) {
5119 return TCL_OK;
5120 }
5121
5122 /* Free old representation */
5123 if (objPtr->typePtr != NULL) {
5124 if (objPtr->bytes == NULL) {
5125 if (objPtr->typePtr->updateStringProc == NULL) {
5126 if (interp != NULL) {
5127 Tcl_ResetResult(interp);
5128 Tcl_AppendResult(interp, "can't find object",
5129 "string representation", (char *) NULL);
5130 }
5131 return TCL_ERROR;
5132 }
5133 objPtr->typePtr->updateStringProc(objPtr);
5134 }
5135 if ((objPtr->typePtr->freeIntRepProc) != NULL) {
5136 (*objPtr->typePtr->freeIntRepProc)(objPtr);
5137 }
5138 }
5139
5140 fsPathPtr = (FsPath*)ckalloc((unsigned)sizeof(FsPath));
5141 /* It's a pure normalized absolute path */
5142 fsPathPtr->translatedPathPtr = NULL;
5143 fsPathPtr->normPathPtr = objPtr;
5144 fsPathPtr->cwdPtr = NULL;
5145 fsPathPtr->nativePathPtr = nativeRep;
5146 fsPathPtr->fsRecPtr = NULL;
5147 fsPathPtr->filesystemEpoch = tsdPtr->filesystemEpoch;
5148
5149 PATHOBJ(objPtr) = (VOID *) fsPathPtr;
5150 PATHFLAGS(objPtr) = 0;
5151 objPtr->typePtr = &tclFsPathType;
5152
5153 return TCL_OK;
5154 }
5155
5156 /*
5157 *---------------------------------------------------------------------------
5158 *
5159 * Tcl_FSNewNativePath --
5160 *
5161 * This function performs the something like that reverse of the
5162 * usual obj->path->nativerep conversions. If some code retrieves
5163 * a path in native form (from, e.g. readlink or a native dialog),
5164 * and that path is to be used at the Tcl level, then calling
5165 * this function is an efficient way of creating the appropriate
5166 * path object type.
5167 *
5168 * Any memory which is allocated for 'clientData' should be retained
5169 * until clientData is passed to the filesystem's freeInternalRepProc
5170 * when it can be freed. The built in platform-specific filesystems
5171 * use 'ckalloc' to allocate clientData, and ckfree to free it.
5172 *
5173 * Results:
5174 * NULL or a valid path object pointer, with refCount zero.
5175 *
5176 * Side effects:
5177 * New memory may be allocated.
5178 *
5179 *---------------------------------------------------------------------------
5180 */
5181
5182 Tcl_Obj *
5183 Tcl_FSNewNativePath(fromFilesystem, clientData)
5184 Tcl_Filesystem* fromFilesystem;
5185 ClientData clientData;
5186 {
5187 Tcl_Obj *objPtr;
5188 FsPath *fsPathPtr;
5189
5190 FilesystemRecord *fsFromPtr;
5191 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
5192
5193 objPtr = TclFSInternalToNormalized(fromFilesystem, clientData, &fsFromPtr);
5194 if (objPtr == NULL) {
5195 return NULL;
5196 }
5197
5198 /*
5199 * Free old representation; shouldn't normally be any,
5200 * but best to be safe.
5201 */
5202 if (objPtr->typePtr != NULL) {
5203 if (objPtr->bytes == NULL) {
5204 if (objPtr->typePtr->updateStringProc == NULL) {
5205 return NULL;
5206 }
5207 objPtr->typePtr->updateStringProc(objPtr);
5208 }
5209 if ((objPtr->typePtr->freeIntRepProc) != NULL) {
5210 (*objPtr->typePtr->freeIntRepProc)(objPtr);
5211 }
5212 }
5213
5214 fsPathPtr = (FsPath*)ckalloc((unsigned)sizeof(FsPath));
5215
5216 fsPathPtr->translatedPathPtr = NULL;
5217 /* Circular reference, by design */
5218 fsPathPtr->normPathPtr = objPtr;
5219 fsPathPtr->cwdPtr = NULL;
5220 fsPathPtr->nativePathPtr = clientData;
5221 fsPathPtr->fsRecPtr = fsFromPtr;
5222 fsPathPtr->fsRecPtr->fileRefCount++;
5223 fsPathPtr->filesystemEpoch = tsdPtr->filesystemEpoch;
5224
5225 PATHOBJ(objPtr) = (VOID *) fsPathPtr;
5226 PATHFLAGS(objPtr) = 0;
5227 objPtr->typePtr = &tclFsPathType;
5228
5229 return objPtr;
5230 }
5231
5232 /*
5233 *---------------------------------------------------------------------------
5234 *
5235 * Tcl_FSGetTranslatedPath --
5236 *
5237 * This function attempts to extract the translated path
5238 * from the given Tcl_Obj. If the translation succeeds (i.e. the
5239 * object is a valid path), then it is returned. Otherwise NULL
5240 * will be returned, and an error message may be left in the
5241 * interpreter (if it is non-NULL)
5242 *
5243 * Results:
5244 * NULL or a valid Tcl_Obj pointer.
5245 *
5246 * Side effects:
5247 * Only those of 'Tcl_FSConvertToPathType'
5248 *
5249 *---------------------------------------------------------------------------
5250 */
5251
5252 Tcl_Obj*
5253 Tcl_FSGetTranslatedPath(interp, pathPtr)
5254 Tcl_Interp *interp;
5255 Tcl_Obj* pathPtr;
5256 {
5257 Tcl_Obj *retObj = NULL;
5258 FsPath *srcFsPathPtr;
5259
5260 if (Tcl_FSConvertToPathType(interp, pathPtr) != TCL_OK) {
5261 return NULL;
5262 }
5263 srcFsPathPtr = (FsPath*) PATHOBJ(pathPtr);
5264 if (srcFsPathPtr->translatedPathPtr == NULL) {
5265 if (PATHFLAGS(pathPtr) != 0) {
5266 return Tcl_FSGetNormalizedPath(interp, pathPtr);
5267 }
5268 /*
5269 * It is a pure absolute, normalized path object.
5270 * This is something like being a 'pure list'. The
5271 * object's string, translatedPath and normalizedPath
5272 * are all identical.
5273 */
5274 retObj = srcFsPathPtr->normPathPtr;
5275 } else {
5276 /* It is an ordinary path object */
5277 retObj = srcFsPathPtr->translatedPathPtr;
5278 }
5279
5280 Tcl_IncrRefCount(retObj);
5281 return retObj;
5282 }
5283
5284 /*
5285 *---------------------------------------------------------------------------
5286 *
5287 * Tcl_FSGetTranslatedStringPath --
5288 *
5289 * This function attempts to extract the translated path
5290 * from the given Tcl_Obj. If the translation succeeds (i.e. the
5291 * object is a valid path), then the path is returned. Otherwise NULL
5292 * will be returned, and an error message may be left in the
5293 * interpreter (if it is non-NULL)
5294 *
5295 * Results:
5296 * NULL or a valid string.
5297 *
5298 * Side effects:
5299 * Only those of 'Tcl_FSConvertToPathType'
5300 *
5301 *---------------------------------------------------------------------------
5302 */
5303 CONST char*
5304 Tcl_FSGetTranslatedStringPath(interp, pathPtr)
5305 Tcl_Interp *interp;
5306 Tcl_Obj* pathPtr;
5307 {
5308 Tcl_Obj *transPtr = Tcl_FSGetTranslatedPath(interp, pathPtr);
5309
5310 if (transPtr != NULL) {
5311 int len;
5312 CONST char *result, *orig;
5313 orig = Tcl_GetStringFromObj(transPtr, &len);
5314 result = (char*) ckalloc((unsigned)(len+1));
5315 memcpy((VOID*) result, (VOID*) orig, (size_t) (len+1));
5316 Tcl_DecrRefCount(transPtr);
5317 return result;
5318 }
5319
5320 return NULL;
5321 }
5322
5323 /*
5324 *---------------------------------------------------------------------------
5325 *
5326 * Tcl_FSGetNormalizedPath --
5327 *
5328 * This important function attempts to extract from the given Tcl_Obj
5329 * a unique normalised path representation, whose string value can
5330 * be used as a unique identifier for the file.
5331 *
5332 * Results:
5333 * NULL or a valid path object pointer.
5334 *
5335 * Side effects:
5336 * New memory may be allocated. The Tcl 'errno' may be modified
5337 * in the process of trying to examine various path possibilities.
5338 *
5339 *---------------------------------------------------------------------------
5340 */
5341
5342 Tcl_Obj*
5343 Tcl_FSGetNormalizedPath(interp, pathObjPtr)
5344 Tcl_Interp *interp;
5345 Tcl_Obj* pathObjPtr;
5346 {
5347 FsPath *fsPathPtr;
5348
5349 if (Tcl_FSConvertToPathType(interp, pathObjPtr) != TCL_OK) {
5350 return NULL;
5351 }
5352 fsPathPtr = (FsPath*) PATHOBJ(pathObjPtr);
5353
5354 if (PATHFLAGS(pathObjPtr) != 0) {
5355 /*
5356 * This is a special path object which is the result of
5357 * something like 'file join'
5358 */
5359 Tcl_Obj *dir, *copy;
5360 int cwdLen;
5361 int pathType;
5362 CONST char *cwdStr;
5363 ClientData clientData = NULL;
5364
5365 pathType = Tcl_FSGetPathType(fsPathPtr->cwdPtr);
5366 dir = Tcl_FSGetNormalizedPath(interp, fsPathPtr->cwdPtr);
5367 if (dir == NULL) {
5368 return NULL;
5369 }
5370 if (pathObjPtr->bytes == NULL) {
5371 UpdateStringOfFsPath(pathObjPtr);
5372 }
5373 copy = Tcl_DuplicateObj(dir);
5374 Tcl_IncrRefCount(copy);
5375 Tcl_IncrRefCount(dir);
5376 /* We now own a reference on both 'dir' and 'copy' */
5377
5378 cwdStr = Tcl_GetStringFromObj(copy, &cwdLen);
5379 /*
5380 * Should we perhaps use 'Tcl_FSPathSeparator'?
5381 * But then what about the Windows special case?
5382 * Perhaps we should just check if cwd is a root volume.
5383 * We should never get cwdLen == 0 in this code path.
5384 */
5385 switch (tclPlatform) {
5386 case TCL_PLATFORM_UNIX:
5387 if (cwdStr[cwdLen-1] != '/') {
5388 Tcl_AppendToObj(copy, "/", 1);
5389 cwdLen++;
5390 }
5391 break;
5392 case TCL_PLATFORM_WINDOWS:
5393 if (cwdStr[cwdLen-1] != '/'
5394 && cwdStr[cwdLen-1] != '\\') {
5395 Tcl_AppendToObj(copy, "/", 1);
5396 cwdLen++;
5397 }
5398 break;
5399 case TCL_PLATFORM_MAC:
5400 if (cwdStr[cwdLen-1] != ':') {
5401 Tcl_AppendToObj(copy, ":", 1);
5402 cwdLen++;
5403 }
5404 break;
5405 }
5406 Tcl_AppendObjToObj(copy, fsPathPtr->normPathPtr);
5407 /*
5408 * Normalize the combined string, but only starting after
5409 * the end of the previously normalized 'dir'. This should
5410 * be much faster! We use 'cwdLen-1' so that we are
5411 * already pointing at the dir-separator that we know about.
5412 * The normalization code will actually start off directly
5413 * after that separator.
5414 */
5415 TclFSNormalizeToUniquePath(interp, copy, cwdLen-1,
5416 (fsPathPtr->nativePathPtr == NULL ? &clientData : NULL));
5417 /* Now we need to construct the new path object */
5418
5419 if (pathType == TCL_PATH_RELATIVE) {
5420 FsPath* origDirFsPathPtr;
5421 Tcl_Obj *origDir = fsPathPtr->cwdPtr;
5422 origDirFsPathPtr = (FsPath*) PATHOBJ(origDir);
5423
5424 fsPathPtr->cwdPtr = origDirFsPathPtr->cwdPtr;
5425 Tcl_IncrRefCount(fsPathPtr->cwdPtr);
5426
5427 Tcl_DecrRefCount(fsPathPtr->normPathPtr);
5428 fsPathPtr->normPathPtr = copy;
5429 /* That's our reference to copy used */
5430 Tcl_DecrRefCount(dir);
5431 Tcl_DecrRefCount(origDir);
5432 } else {
5433 Tcl_DecrRefCount(fsPathPtr->cwdPtr);
5434 fsPathPtr->cwdPtr = NULL;
5435 Tcl_DecrRefCount(fsPathPtr->normPathPtr);
5436 fsPathPtr->normPathPtr = copy;
5437 /* That's our reference to copy used */
5438 Tcl_DecrRefCount(dir);
5439 }
5440 if (clientData != NULL) {
5441 fsPathPtr->nativePathPtr = clientData;
5442 }
5443 PATHFLAGS(pathObjPtr) = 0;
5444 }
5445 /* Ensure cwd hasn't changed */
5446 if (fsPathPtr->cwdPtr != NULL) {
5447 if (!TclFSCwdPointerEquals(fsPathPtr->cwdPtr)) {
5448 if (pathObjPtr->bytes == NULL) {
5449 UpdateStringOfFsPath(pathObjPtr);
5450 }
5451 FreeFsPathInternalRep(pathObjPtr);
5452 pathObjPtr->typePtr = NULL;
5453 if (Tcl_ConvertToType(interp, pathObjPtr,
5454 &tclFsPathType) != TCL_OK) {
5455 return NULL;
5456 }
5457 fsPathPtr = (FsPath*) PATHOBJ(pathObjPtr);
5458 } else if (fsPathPtr->normPathPtr == NULL) {
5459 int cwdLen;
5460 Tcl_Obj *copy;
5461 CONST char *cwdStr;
5462 ClientData clientData = NULL;
5463
5464 copy = Tcl_DuplicateObj(fsPathPtr->cwdPtr);
5465 Tcl_IncrRefCount(copy);
5466 cwdStr = Tcl_GetStringFromObj(copy, &cwdLen);
5467 /*
5468 * Should we perhaps use 'Tcl_FSPathSeparator'?
5469 * But then what about the Windows special case?
5470 * Perhaps we should just check if cwd is a root volume.
5471 * We should never get cwdLen == 0 in this code path.
5472 */
5473 switch (tclPlatform) {
5474 case TCL_PLATFORM_UNIX:
5475 if (cwdStr[cwdLen-1] != '/') {
5476 Tcl_AppendToObj(copy, "/", 1);
5477 cwdLen++;
5478 }
5479 break;
5480 case TCL_PLATFORM_WINDOWS:
5481 if (cwdStr[cwdLen-1] != '/'
5482 && cwdStr[cwdLen-1] != '\\') {
5483 Tcl_AppendToObj(copy, "/", 1);
5484 cwdLen++;
5485 }
5486 break;
5487 case TCL_PLATFORM_MAC:
5488 if (cwdStr[cwdLen-1] != ':') {
5489 Tcl_AppendToObj(copy, ":", 1);
5490 cwdLen++;
5491 }
5492 break;
5493 }
5494 Tcl_AppendObjToObj(copy, pathObjPtr);
5495 /*
5496 * Normalize the combined string, but only starting after
5497 * the end of the previously normalized 'dir'. This should
5498 * be much faster!
5499 */
5500 TclFSNormalizeToUniquePath(interp, copy, cwdLen-1,
5501 (fsPathPtr->nativePathPtr == NULL ? &clientData : NULL));
5502 fsPathPtr->normPathPtr = copy;
5503 if (clientData != NULL) {
5504 fsPathPtr->nativePathPtr = clientData;
5505 }
5506 }
5507 }
5508 if (fsPathPtr->normPathPtr == NULL) {
5509 ClientData clientData = NULL;
5510 Tcl_Obj *useThisCwd = NULL;
5511 /*
5512 * Since normPathPtr is NULL, but this is a valid path
5513 * object, we know that the translatedPathPtr cannot be NULL.
5514 */
5515 Tcl_Obj *absolutePath = fsPathPtr->translatedPathPtr;
5516 char *path = Tcl_GetString(absolutePath);
5517
5518 /*
5519 * We have to be a little bit careful here to avoid infinite loops
5520 * we're asking Tcl_FSGetPathType to return the path's type, but
5521 * that call can actually result in a lot of other filesystem
5522 * action, which might loop back through here.
5523 */
5524 if (path[0] != '\0') {
5525 Tcl_PathType type = Tcl_FSGetPathType(pathObjPtr);
5526 if (type == TCL_PATH_RELATIVE) {
5527 useThisCwd = Tcl_FSGetCwd(interp);
5528
5529 if (useThisCwd == NULL) return NULL;
5530
5531 absolutePath = Tcl_FSJoinToPath(useThisCwd, 1, &absolutePath);
5532 Tcl_IncrRefCount(absolutePath);
5533 /* We have a refCount on the cwd */
5534 #ifdef __WIN32__
5535 } else if (type == TCL_PATH_VOLUME_RELATIVE) {
5536 /*
5537 * Only Windows has volume-relative paths. These
5538 * paths are rather rare, but is is nice if Tcl can
5539 * handle them. It is much better if we can
5540 * handle them here, rather than in the native fs code,
5541 * because we really need to have a real absolute path
5542 * just below.
5543 *
5544 * We do not let this block compile on non-Windows
5545 * platforms because the test suite's manual forcing
5546 * of tclPlatform can otherwise cause this code path
5547 * to be executed, causing various errors because
5548 * volume-relative paths really do not exist.
5549 */
5550 useThisCwd = Tcl_FSGetCwd(interp);
5551 if (useThisCwd == NULL) return NULL;
5552
5553 if (path[0] == '/') {
5554 /*
5555 * Path of form /foo/bar which is a path in the
5556 * root directory of the current volume.
5557 */
5558 CONST char *drive = Tcl_GetString(useThisCwd);
5559 absolutePath = Tcl_NewStringObj(drive,2);
5560 Tcl_AppendToObj(absolutePath, path, -1);
5561 Tcl_IncrRefCount(absolutePath);
5562 /* We have a refCount on the cwd */
5563 } else {
5564 /*
5565 * Path of form C:foo/bar, but this only makes
5566 * sense if the cwd is also on drive C.
5567 */
5568 CONST char *drive = Tcl_GetString(useThisCwd);
5569 char drive_c = path[0];
5570 if (drive_c >= 'a') {
5571 drive_c -= ('a' - 'A');
5572 }
5573 if (drive[0] == drive_c) {
5574 absolutePath = Tcl_DuplicateObj(useThisCwd);
5575 /* We have a refCount on the cwd */
5576 } else {
5577 Tcl_DecrRefCount(useThisCwd);
5578 useThisCwd = NULL;
5579 /*
5580 * The path is not in the current drive, but
5581 * is volume-relative. The way Tcl 8.3 handles
5582 * this is that it treats such a path as
5583 * relative to the root of the drive. We
5584 * therefore behave the same here.
5585 */
5586 absolutePath = Tcl_NewStringObj(path, 2);
5587 }
5588 Tcl_IncrRefCount(absolutePath);
5589 Tcl_AppendToObj(absolutePath, "/", 1);
5590 Tcl_AppendToObj(absolutePath, path+2, -1);
5591 }
5592 #endif /* __WIN32__ */
5593 }
5594 }
5595 /* Already has refCount incremented */
5596 fsPathPtr->normPathPtr = TclFSNormalizeAbsolutePath(interp, absolutePath,
5597 (fsPathPtr->nativePathPtr == NULL ? &clientData : NULL));
5598 if (0 && (clientData != NULL)) {
5599 fsPathPtr->nativePathPtr =
5600 (*fsPathPtr->fsRecPtr->fsPtr->dupInternalRepProc)(clientData);
5601 }
5602 if (!strcmp(Tcl_GetString(fsPathPtr->normPathPtr),
5603 Tcl_GetString(pathObjPtr))) {
5604 /*
5605 * The path was already normalized.
5606 * Get rid of the duplicate.
5607 */
5608 Tcl_DecrRefCount(fsPathPtr->normPathPtr);
5609 /*
5610 * We do *not* increment the refCount for
5611 * this circular reference
5612 */
5613 fsPathPtr->normPathPtr = pathObjPtr;
5614 }
5615 if (useThisCwd != NULL) {
5616 /* This was returned by Tcl_FSJoinToPath above */
5617 Tcl_DecrRefCount(absolutePath);
5618 fsPathPtr->cwdPtr = useThisCwd;
5619 }
5620 }
5621
5622 return fsPathPtr->normPathPtr;
5623 }
5624
5625 /*
5626 *---------------------------------------------------------------------------
5627 *
5628 * Tcl_FSGetInternalRep --
5629 *
5630 * Extract the internal representation of a given path object,
5631 * in the given filesystem. If the path object belongs to a
5632 * different filesystem, we return NULL.
5633 *
5634 * If the internal representation is currently NULL, we attempt
5635 * to generate it, by calling the filesystem's
5636 * 'Tcl_FSCreateInternalRepProc'.
5637 *
5638 * Results:
5639 * NULL or a valid internal representation.
5640 *
5641 * Side effects:
5642 * An attempt may be made to convert the object.
5643 *
5644 *---------------------------------------------------------------------------
5645 */
5646
5647 ClientData
5648 Tcl_FSGetInternalRep(pathObjPtr, fsPtr)
5649 Tcl_Obj* pathObjPtr;
5650 Tcl_Filesystem *fsPtr;
5651 {
5652 FsPath *srcFsPathPtr;
5653
5654 if (Tcl_FSConvertToPathType(NULL, pathObjPtr) != TCL_OK) {
5655 return NULL;
5656 }
5657 srcFsPathPtr = (FsPath*) PATHOBJ(pathObjPtr);
5658
5659 /*
5660 * We will only return the native representation for the caller's
5661 * filesystem. Otherwise we will simply return NULL. This means
5662 * that there must be a unique bi-directional mapping between paths
5663 * and filesystems, and that this mapping will not allow 'remapped'
5664 * files -- files which are in one filesystem but mapped into
5665 * another. Another way of putting this is that 'stacked'
5666 * filesystems are not allowed. We recognise that this is a
5667 * potentially useful feature for the future.
5668 *
5669 * Even something simple like a 'pass through' filesystem which
5670 * logs all activity and passes the calls onto the native system
5671 * would be nice, but not easily achievable with the current
5672 * implementation.
5673 */
5674 if (srcFsPathPtr->fsRecPtr == NULL) {
5675 /*
5676 * This only usually happens in wrappers like TclpStat which
5677 * create a string object and pass it to TclpObjStat. Code
5678 * which calls the Tcl_FS.. functions should always have a
5679 * filesystem already set. Whether this code path is legal or
5680 * not depends on whether we decide to allow external code to
5681 * call the native filesystem directly. It is at least safer
5682 * to allow this sub-optimal routing.
5683 */
5684 Tcl_FSGetFileSystemForPath(pathObjPtr);
5685
5686 /*
5687 * If we fail through here, then the path is probably not a
5688 * valid path in the filesystsem, and is most likely to be a
5689 * use of the empty path "" via a direct call to one of the
5690 * objectified interfaces (e.g. from the Tcl testsuite).
5691 */
5692 srcFsPathPtr = (FsPath*) PATHOBJ(pathObjPtr);
5693 if (srcFsPathPtr->fsRecPtr == NULL) {
5694 return NULL;
5695 }
5696 }
5697
5698 if (fsPtr != srcFsPathPtr->fsRecPtr->fsPtr) {
5699 /*
5700 * There is still one possibility we should consider; if the
5701 * file belongs to a different filesystem, perhaps it is
5702 * actually linked through to a file in our own filesystem
5703 * which we do care about. The way we can check for this
5704 * is we ask what filesystem this path belongs to.
5705 */
5706 Tcl_Filesystem *actualFs = Tcl_FSGetFileSystemForPath(pathObjPtr);
5707 if (actualFs == fsPtr) {
5708 return Tcl_FSGetInternalRep(pathObjPtr, fsPtr);
5709 }
5710 return NULL;
5711 }
5712
5713 if (srcFsPathPtr->nativePathPtr == NULL) {
5714 Tcl_FSCreateInternalRepProc *proc;
5715 proc = srcFsPathPtr->fsRecPtr->fsPtr->createInternalRepProc;
5716
5717 if (proc == NULL) {
5718 return NULL;
5719 }
5720 srcFsPathPtr->nativePathPtr = (*proc)(pathObjPtr);
5721 }
5722
5723 return srcFsPathPtr->nativePathPtr;
5724 }
5725
5726 /*
5727 *---------------------------------------------------------------------------
5728 *
5729 * TclFSEnsureEpochOk --
5730 *
5731 * This will ensure the pathObjPtr is up to date and can be
5732 * converted into a "path" type, and that we are able to generate a
5733 * complete normalized path which is used to determine the
5734 * filesystem match.
5735 *
5736 * Results:
5737 * Standard Tcl return code.
5738 *
5739 * Side effects:
5740 * An attempt may be made to convert the object.
5741 *
5742 *---------------------------------------------------------------------------
5743 */
5744
5745 int
5746 TclFSEnsureEpochOk(pathObjPtr, fsPtrPtr)
5747 Tcl_Obj* pathObjPtr;
5748 Tcl_Filesystem **fsPtrPtr;
5749 {
5750 FsPath *srcFsPathPtr;
5751 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
5752
5753 /*
5754 * SHOULD BE ABLE TO IMPROVE EFFICIENCY HERE.
5755 */
5756
5757 if (Tcl_FSGetNormalizedPath(NULL, pathObjPtr) == NULL) {
5758 return TCL_ERROR;
5759 }
5760
5761 srcFsPathPtr = (FsPath*) PATHOBJ(pathObjPtr);
5762
5763 /*
5764 * Check if the filesystem has changed in some way since
5765 * this object's internal representation was calculated.
5766 */
5767 if (srcFsPathPtr->filesystemEpoch != tsdPtr->filesystemEpoch) {
5768 /*
5769 * We have to discard the stale representation and
5770 * recalculate it
5771 */
5772 if (pathObjPtr->bytes == NULL) {
5773 UpdateStringOfFsPath(pathObjPtr);
5774 }
5775 FreeFsPathInternalRep(pathObjPtr);
5776 pathObjPtr->typePtr = NULL;
5777 if (SetFsPathFromAny(NULL, pathObjPtr) != TCL_OK) {
5778 return TCL_ERROR;
5779 }
5780 srcFsPathPtr = (FsPath*) PATHOBJ(pathObjPtr);
5781 }
5782 /* Check whether the object is already assigned to a fs */
5783 if (srcFsPathPtr->fsRecPtr != NULL) {
5784 *fsPtrPtr = srcFsPathPtr->fsRecPtr->fsPtr;
5785 }
5786
5787 return TCL_OK;
5788 }
5789
5790 void
5791 TclFSSetPathDetails(pathObjPtr, fsRecPtr, clientData)
5792 Tcl_Obj *pathObjPtr;
5793 FilesystemRecord *fsRecPtr;
5794 ClientData clientData;
5795 {
5796 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
5797 /* We assume pathObjPtr is already of the correct type */
5798 FsPath *srcFsPathPtr;
5799
5800 srcFsPathPtr = (FsPath*) PATHOBJ(pathObjPtr);
5801 srcFsPathPtr->fsRecPtr = fsRecPtr;
5802 srcFsPathPtr->nativePathPtr = clientData;
5803 srcFsPathPtr->filesystemEpoch = tsdPtr->filesystemEpoch;
5804 fsRecPtr->fileRefCount++;
5805 }
5806
5807 /*
5808 *---------------------------------------------------------------------------
5809 *
5810 * Tcl_FSEqualPaths --
5811 *
5812 * This function tests whether the two paths given are equal path
5813 * objects. If either or both is NULL, 0 is always returned.
5814 *
5815 * Results:
5816 * 1 or 0.
5817 *
5818 * Side effects:
5819 * None.
5820 *
5821 *---------------------------------------------------------------------------
5822 */
5823
5824 int
5825 Tcl_FSEqualPaths(firstPtr, secondPtr)
5826 Tcl_Obj* firstPtr;
5827 Tcl_Obj* secondPtr;
5828 {
5829 if (firstPtr == secondPtr) {
5830 return 1;
5831 } else {
5832 char *firstStr, *secondStr;
5833 int firstLen, secondLen, tempErrno;
5834
5835 if (firstPtr == NULL || secondPtr == NULL) {
5836 return 0;
5837 }
5838 firstStr = Tcl_GetStringFromObj(firstPtr, &firstLen);
5839 secondStr = Tcl_GetStringFromObj(secondPtr, &secondLen);
5840 if ((firstLen == secondLen) && (strcmp(firstStr, secondStr) == 0)) {
5841 return 1;
5842 }
5843 /*
5844 * Try the most thorough, correct method of comparing fully
5845 * normalized paths
5846 */
5847
5848 tempErrno = Tcl_GetErrno();
5849 firstPtr = Tcl_FSGetNormalizedPath(NULL, firstPtr);
5850 secondPtr = Tcl_FSGetNormalizedPath(NULL, secondPtr);
5851 Tcl_SetErrno(tempErrno);
5852
5853 if (firstPtr == NULL || secondPtr == NULL) {
5854 return 0;
5855 }
5856 firstStr = Tcl_GetStringFromObj(firstPtr, &firstLen);
5857 secondStr = Tcl_GetStringFromObj(secondPtr, &secondLen);
5858 if ((firstLen == secondLen) && (strcmp(firstStr, secondStr) == 0)) {
5859 return 1;
5860 }
5861 }
5862
5863 return 0;
5864 }
5865
5866 /*
5867 *---------------------------------------------------------------------------
5868 *
5869 * SetFsPathFromAny --
5870 *
5871 * This function tries to convert the given Tcl_Obj to a valid
5872 * Tcl path type.
5873 *
5874 * The filename may begin with "~" (to indicate current user's
5875 * home directory) or "~<user>" (to indicate any user's home
5876 * directory).
5877 *
5878 * Results:
5879 * Standard Tcl error code.
5880 *
5881 * Side effects:
5882 * The old representation may be freed, and new memory allocated.
5883 *
5884 *---------------------------------------------------------------------------
5885 */
5886
5887 static int
5888 SetFsPathFromAny(interp, objPtr)
5889 Tcl_Interp *interp; /* Used for error reporting if not NULL. */
5890 Tcl_Obj *objPtr; /* The object to convert. */
5891 {
5892 int len;
5893 FsPath *fsPathPtr;
5894 Tcl_Obj *transPtr;
5895 char *name;
5896 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
5897
5898 if (objPtr->typePtr == &tclFsPathType) {
5899 return TCL_OK;
5900 }
5901
5902 /*
5903 * First step is to translate the filename. This is similar to
5904 * Tcl_TranslateFilename, but shouldn't convert everything to
5905 * windows backslashes on that platform. The current
5906 * implementation of this piece is a slightly optimised version
5907 * of the various Tilde/Split/Join stuff to avoid multiple
5908 * split/join operations.
5909 *
5910 * We remove any trailing directory separator.
5911 *
5912 * However, the split/join routines are quite complex, and
5913 * one has to make sure not to break anything on Unix, Win
5914 * or MacOS (fCmd.test, fileName.test and cmdAH.test exercise
5915 * most of the code).
5916 */
5917 name = Tcl_GetStringFromObj(objPtr,&len);
5918
5919 /*
5920 * Handle tilde substitutions, if needed.
5921 */
5922 if (name[0] == '~') {
5923 char *expandedUser;
5924 Tcl_DString temp;
5925 int split;
5926 char separator='/';
5927
5928 if (tclPlatform==TCL_PLATFORM_MAC) {
5929 if (strchr(name, ':') != NULL) separator = ':';
5930 }
5931
5932 split = FindSplitPos(name, &separator);
5933 if (split != len) {
5934 /* We have multiple pieces '~user/foo/bar...' */
5935 name[split] = '\0';
5936 }
5937 /* Do some tilde substitution */
5938 if (name[1] == '\0') {
5939 /* We have just '~' */
5940 CONST char *dir;
5941 Tcl_DString dirString;
5942 if (split != len) { name[split] = separator; }
5943
5944 dir = TclGetEnv("HOME", &dirString);
5945 if (dir == NULL) {
5946 if (interp) {
5947 Tcl_ResetResult(interp);
5948 Tcl_AppendResult(interp, "couldn't find HOME environment ",
5949 "variable to expand path", (char *) NULL);
5950 }
5951 return TCL_ERROR;
5952 }
5953 Tcl_DStringInit(&temp);
5954 Tcl_JoinPath(1, &dir, &temp);
5955 Tcl_DStringFree(&dirString);
5956 } else {
5957 /* We have a user name '~user' */
5958 Tcl_DStringInit(&temp);
5959 if (TclpGetUserHome(name+1, &temp) == NULL) {
5960 if (interp != NULL) {
5961 Tcl_ResetResult(interp);
5962 Tcl_AppendResult(interp, "user \"", (name+1),
5963 "\" doesn't exist", (char *) NULL);
5964 }
5965 Tcl_DStringFree(&temp);
5966 if (split != len) { name[split] = separator; }
5967 return TCL_ERROR;
5968 }
5969 if (split != len) { name[split] = separator; }
5970 }
5971
5972 expandedUser = Tcl_DStringValue(&temp);
5973 transPtr = Tcl_NewStringObj(expandedUser, Tcl_DStringLength(&temp));
5974
5975 if (split != len) {
5976 /* Join up the tilde substitution with the rest */
5977 if (name[split+1] == separator) {
5978
5979 /*
5980 * Somewhat tricky case like ~//foo/bar.
5981 * Make use of Split/Join machinery to get it right.
5982 * Assumes all paths beginning with ~ are part of the
5983 * native filesystem.
5984 */
5985
5986 int objc;
5987 Tcl_Obj **objv;
5988 Tcl_Obj *parts = TclpNativeSplitPath(objPtr, NULL);
5989 Tcl_ListObjGetElements(NULL, parts, &objc, &objv);
5990 /* Skip '~'. It's replaced by its expansion */
5991 objc--; objv++;
5992 while (objc--) {
5993 TclpNativeJoinPath(transPtr, Tcl_GetString(*objv++));
5994 }
5995 Tcl_DecrRefCount(parts);
5996 } else {
5997 /* Simple case. "rest" is relative path. Just join it. */
5998 Tcl_Obj *rest = Tcl_NewStringObj(name+split+1,-1);
5999 transPtr = Tcl_FSJoinToPath(transPtr, 1, &rest);
6000 }
6001 }
6002 Tcl_DStringFree(&temp);
6003 } else {
6004 transPtr = Tcl_FSJoinToPath(objPtr,0,NULL);
6005 }
6006
6007 #if defined(__CYGWIN__) && defined(__WIN32__)
6008 {
6009 extern int cygwin_conv_to_win32_path
6010 _ANSI_ARGS_((CONST char *, char *));
6011 char winbuf[MAX_PATH+1];
6012
6013 /*
6014 * In the Cygwin world, call conv_to_win32_path in order to use the
6015 * mount table to translate the file name into something Windows will
6016 * understand. Take care when converting empty strings!
6017 */
6018 name = Tcl_GetStringFromObj(transPtr, &len);
6019 if (len > 0) {
6020 cygwin_conv_to_win32_path(name, winbuf);
6021 TclWinNoBackslash(winbuf);
6022 Tcl_SetStringObj(transPtr, winbuf, -1);
6023 }
6024 }
6025 #endif /* __CYGWIN__ && __WIN32__ */
6026
6027 /*
6028 * Now we have a translated filename in 'transPtr'. This will have
6029 * forward slashes on Windows, and will not contain any ~user
6030 * sequences.
6031 */
6032
6033 fsPathPtr = (FsPath*)ckalloc((unsigned)sizeof(FsPath));
6034
6035 fsPathPtr->translatedPathPtr = transPtr;
6036 Tcl_IncrRefCount(fsPathPtr->translatedPathPtr);
6037 fsPathPtr->normPathPtr = NULL;
6038 fsPathPtr->cwdPtr = NULL;
6039 fsPathPtr->nativePathPtr = NULL;
6040 fsPathPtr->fsRecPtr = NULL;
6041 fsPathPtr->filesystemEpoch = tsdPtr->filesystemEpoch;
6042
6043 /*
6044 * Free old representation before installing our new one.
6045 */
6046 if (objPtr->typePtr != NULL && objPtr->typePtr->freeIntRepProc != NULL) {
6047 (objPtr->typePtr->freeIntRepProc)(objPtr);
6048 }
6049 PATHOBJ(objPtr) = (VOID *) fsPathPtr;
6050 PATHFLAGS(objPtr) = 0;
6051 objPtr->typePtr = &tclFsPathType;
6052
6053 return TCL_OK;
6054 }
6055
6056 static void
6057 FreeFsPathInternalRep(pathObjPtr)
6058 Tcl_Obj *pathObjPtr; /* Path object with internal rep to free. */
6059 {
6060 FsPath *fsPathPtr = (FsPath*) PATHOBJ(pathObjPtr);
6061
6062 if (fsPathPtr->translatedPathPtr != NULL) {
6063 if (fsPathPtr->translatedPathPtr != pathObjPtr) {
6064 Tcl_DecrRefCount(fsPathPtr->translatedPathPtr);
6065 }
6066 }
6067 if (fsPathPtr->normPathPtr != NULL) {
6068 if (fsPathPtr->normPathPtr != pathObjPtr) {
6069 Tcl_DecrRefCount(fsPathPtr->normPathPtr);
6070 }
6071 fsPathPtr->normPathPtr = NULL;
6072 }
6073 if (fsPathPtr->cwdPtr != NULL) {
6074 Tcl_DecrRefCount(fsPathPtr->cwdPtr);
6075 }
6076 if (fsPathPtr->nativePathPtr != NULL) {
6077 if (fsPathPtr->fsRecPtr != NULL) {
6078 if (fsPathPtr->fsRecPtr->fsPtr->freeInternalRepProc != NULL) {
6079 (*fsPathPtr->fsRecPtr->fsPtr
6080 ->freeInternalRepProc)(fsPathPtr->nativePathPtr);
6081 fsPathPtr->nativePathPtr = NULL;
6082 }
6083 }
6084 }
6085 if (fsPathPtr->fsRecPtr != NULL) {
6086 fsPathPtr->fsRecPtr->fileRefCount--;
6087 if (fsPathPtr->fsRecPtr->fileRefCount <= 0) {
6088 /* It has been unregistered already, so simply free it */
6089 ckfree((char *)fsPathPtr->fsRecPtr);
6090 }
6091 }
6092
6093 ckfree((char*) fsPathPtr);
6094 }
6095
6096
6097 static void
6098 DupFsPathInternalRep(srcPtr, copyPtr)
6099 Tcl_Obj *srcPtr; /* Path obj with internal rep to copy. */
6100 Tcl_Obj *copyPtr; /* Path obj with internal rep to set. */
6101 {
6102 FsPath *srcFsPathPtr = (FsPath*) PATHOBJ(srcPtr);
6103 FsPath *copyFsPathPtr = (FsPath*) ckalloc((unsigned)sizeof(FsPath));
6104
6105 Tcl_FSDupInternalRepProc *dupProc;
6106
6107 PATHOBJ(copyPtr) = (VOID *) copyFsPathPtr;
6108
6109 if (srcFsPathPtr->translatedPathPtr != NULL) {
6110 copyFsPathPtr->translatedPathPtr = srcFsPathPtr->translatedPathPtr;
6111 if (copyFsPathPtr->translatedPathPtr != copyPtr) {
6112 Tcl_IncrRefCount(copyFsPathPtr->translatedPathPtr);
6113 }
6114 } else {
6115 copyFsPathPtr->translatedPathPtr = NULL;
6116 }
6117
6118 if (srcFsPathPtr->normPathPtr != NULL) {
6119 copyFsPathPtr->normPathPtr = srcFsPathPtr->normPathPtr;
6120 if (copyFsPathPtr->normPathPtr != copyPtr) {
6121 Tcl_IncrRefCount(copyFsPathPtr->normPathPtr);
6122 }
6123 } else {
6124 copyFsPathPtr->normPathPtr = NULL;
6125 }
6126
6127 if (srcFsPathPtr->cwdPtr != NULL) {
6128 copyFsPathPtr->cwdPtr = srcFsPathPtr->cwdPtr;
6129 Tcl_IncrRefCount(copyFsPathPtr->cwdPtr);
6130 } else {
6131 copyFsPathPtr->cwdPtr = NULL;
6132 }
6133
6134 copyFsPathPtr->flags = srcFsPathPtr->flags;
6135
6136 if (srcFsPathPtr->fsRecPtr != NULL
6137 && srcFsPathPtr->nativePathPtr != NULL) {
6138 dupProc = srcFsPathPtr->fsRecPtr->fsPtr->dupInternalRepProc;
6139 if (dupProc != NULL) {
6140 copyFsPathPtr->nativePathPtr =
6141 (*dupProc)(srcFsPathPtr->nativePathPtr);
6142 } else {
6143 copyFsPathPtr->nativePathPtr = NULL;
6144 }
6145 } else {
6146 copyFsPathPtr->nativePathPtr = NULL;
6147 }
6148 copyFsPathPtr->fsRecPtr = srcFsPathPtr->fsRecPtr;
6149 copyFsPathPtr->filesystemEpoch = srcFsPathPtr->filesystemEpoch;
6150 if (copyFsPathPtr->fsRecPtr != NULL) {
6151 copyFsPathPtr->fsRecPtr->fileRefCount++;
6152 }
6153
6154 copyPtr->typePtr = &tclFsPathType;
6155 }
6156
6157 /*
6158 *---------------------------------------------------------------------------
6159 *
6160 * UpdateStringOfFsPath --
6161 *
6162 * Gives an object a valid string rep.
6163 *
6164 * Results:
6165 * None.
6166 *
6167 * Side effects:
6168 * Memory may be allocated.
6169 *
6170 *---------------------------------------------------------------------------
6171 */
6172
6173 static void
6174 UpdateStringOfFsPath(objPtr)
6175 register Tcl_Obj *objPtr; /* path obj with string rep to update. */
6176 {
6177 FsPath *fsPathPtr = (FsPath*) PATHOBJ(objPtr);
6178 CONST char *cwdStr;
6179 int cwdLen;
6180 Tcl_Obj *copy;
6181
6182 if (PATHFLAGS(objPtr) == 0 || fsPathPtr->cwdPtr == NULL) {
6183 panic("Called UpdateStringOfFsPath with invalid object");
6184 }
6185
6186 copy = Tcl_DuplicateObj(fsPathPtr->cwdPtr);
6187 Tcl_IncrRefCount(copy);
6188
6189 cwdStr = Tcl_GetStringFromObj(copy, &cwdLen);
6190 /*
6191 * Should we perhaps use 'Tcl_FSPathSeparator'?
6192 * But then what about the Windows special case?
6193 * Perhaps we should just check if cwd is a root volume.
6194 * We should never get cwdLen == 0 in this code path.
6195 */
6196 switch (tclPlatform) {
6197 case TCL_PLATFORM_UNIX:
6198 if (cwdStr[cwdLen-1] != '/') {
6199 Tcl_AppendToObj(copy, "/", 1);
6200 cwdLen++;
6201 }
6202 break;
6203 case TCL_PLATFORM_WINDOWS:
6204 /*
6205 * We need the extra 'cwdLen != 2', and ':' checks because
6206 * a volume relative path doesn't get a '/'. For example
6207 * 'glob C:*cat*.exe' will return 'C:cat32.exe'
6208 */
6209 if (cwdStr[cwdLen-1] != '/'
6210 && cwdStr[cwdLen-1] != '\\') {
6211 if (cwdLen != 2 || cwdStr[1] != ':') {
6212 Tcl_AppendToObj(copy, "/", 1);
6213 cwdLen++;
6214 }
6215 }
6216 break;
6217 case TCL_PLATFORM_MAC:
6218 if (cwdStr[cwdLen-1] != ':') {
6219 Tcl_AppendToObj(copy, ":", 1);
6220 cwdLen++;
6221 }
6222 break;
6223 }
6224 Tcl_AppendObjToObj(copy, fsPathPtr->normPathPtr);
6225 objPtr->bytes = Tcl_GetStringFromObj(copy, &cwdLen);
6226 objPtr->length = cwdLen;
6227 copy->bytes = tclEmptyStringRep;
6228 copy->length = 0;
6229 Tcl_DecrRefCount(copy);
6230 }
6231
6232 /*
6233 *---------------------------------------------------------------------------
6234 *
6235 * NativePathInFilesystem --
6236 *
6237 * Any path object is acceptable to the native filesystem, by
6238 * default (we will throw errors when illegal paths are actually
6239 * tried to be used).
6240 *
6241 * However, this behavior means the native filesystem must be
6242 * the last filesystem in the lookup list (otherwise it will
6243 * claim all files belong to it, and other filesystems will
6244 * never get a look in).
6245 *
6246 * Results:
6247 * TCL_OK, to indicate 'yes', -1 to indicate no.
6248 *
6249 * Side effects:
6250 * None.
6251 *
6252 *---------------------------------------------------------------------------
6253 */
6254 int
6255 NativePathInFilesystem(pathPtr, clientDataPtr)
6256 Tcl_Obj *pathPtr;
6257 ClientData *clientDataPtr;
6258 {
6259 /*
6260 * A special case is required to handle the empty path "".
6261 * This is a valid path (i.e. the user should be able
6262 * to do 'file exists ""' without throwing an error), but
6263 * equally the path doesn't exist. Those are the semantics
6264 * of Tcl (at present anyway), so we have to abide by them
6265 * here.
6266 */
6267 if (pathPtr->typePtr == &tclFsPathType) {
6268 if (pathPtr->bytes != NULL && pathPtr->bytes[0] == '\0') {
6269 /* We reject the empty path "" */
6270 return -1;
6271 }
6272 /* Otherwise there is no way this path can be empty */
6273 } else {
6274 /*
6275 * It is somewhat unusual to reach this code path without
6276 * the object being of tclFsPathType. However, we do
6277 * our best to deal with the situation.
6278 */
6279 int len;
6280 Tcl_GetStringFromObj(pathPtr,&len);
6281 if (len == 0) {
6282 /* We reject the empty path "" */
6283 return -1;
6284 }
6285 }
6286 /*
6287 * Path is of correct type, or is of non-zero length,
6288 * so we accept it.
6289 */
6290 return TCL_OK;
6291 }