Debian Codegraph @

generic/tclPathObj.c

raw
1 /*
2 * tclPathObj.c --
3 *
4 * This file contains the implementation of Tcl's "path" object type used
5 * to represent and manipulate a general (virtual) filesystem entity in
6 * an efficient manner.
7 *
8 * Copyright (c) 2003 Vince Darley.
9 *
10 * See the file "license.terms" for information on usage and redistribution of
11 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
12 */
13
14 #include "tclInt.h"
15 #include "tclFileSystem.h"
16 #include <assert.h>
17
18 /*
19 * Prototypes for functions defined later in this file.
20 */
21
22 static Tcl_Obj * AppendPath(Tcl_Obj *head, Tcl_Obj *tail);
23 static void DupFsPathInternalRep(Tcl_Obj *srcPtr,
24 Tcl_Obj *copyPtr);
25 static void FreeFsPathInternalRep(Tcl_Obj *pathPtr);
26 static void UpdateStringOfFsPath(Tcl_Obj *pathPtr);
27 static int SetFsPathFromAny(Tcl_Interp *interp, Tcl_Obj *pathPtr);
28 static int FindSplitPos(const char *path, int separator);
29 static int IsSeparatorOrNull(int ch);
30 static Tcl_Obj * GetExtension(Tcl_Obj *pathPtr);
31 static int MakePathFromNormalized(Tcl_Interp *interp,
32 Tcl_Obj *pathPtr);
33
34 /*
35 * Define the 'path' object type, which Tcl uses to represent file paths
36 * internally.
37 */
38
39 static const Tcl_ObjType tclFsPathType = {
40 "path", /* name */
41 FreeFsPathInternalRep, /* freeIntRepProc */
42 DupFsPathInternalRep, /* dupIntRepProc */
43 UpdateStringOfFsPath, /* updateStringProc */
44 SetFsPathFromAny /* setFromAnyProc */
45 };
46
47 /*
48 * struct FsPath --
49 *
50 * Internal representation of a Tcl_Obj of "path" type. This can be used to
51 * represent relative or absolute paths, and has certain optimisations when
52 * used to represent paths which are already normalized and absolute.
53 *
54 * Note that both 'translatedPathPtr' and 'normPathPtr' can be a circular
55 * reference to the container Tcl_Obj of this FsPath.
56 *
57 * There are two cases, with the first being the most common:
58 *
59 * (i) flags == 0, => Ordinary path.
60 *
61 * translatedPathPtr contains the translated path (which may be a circular
62 * reference to the object itself). If it is NULL then the path is pure
63 * normalized (and the normPathPtr will be a circular reference). cwdPtr is
64 * null for an absolute path, and non-null for a relative path (unless the cwd
65 * has never been set, in which case the cwdPtr may also be null for a
66 * relative path).
67 *
68 * (ii) flags != 0, => Special path, see TclNewFSPathObj
69 *
70 * Now, this is a path like 'file join $dir $tail' where, cwdPtr is the $dir
71 * and normPathPtr is the $tail.
72 *
73 */
74
75 typedef struct FsPath {
76 Tcl_Obj *translatedPathPtr; /* Name without any ~user sequences. If this
77 * is NULL, then this is a pure normalized,
78 * absolute path object, in which the parent
79 * Tcl_Obj's string rep is already both
80 * translated and normalized. */
81 Tcl_Obj *normPathPtr; /* Normalized absolute path, without ., .. or
82 * ~user sequences. If the Tcl_Obj containing
83 * this FsPath is already normalized, this may
84 * be a circular reference back to the
85 * container. If that is NOT the case, we have
86 * a refCount on the object. */
87 Tcl_Obj *cwdPtr; /* If null, path is absolute, else this points
88 * to the cwd object used for this path. We
89 * have a refCount on the object. */
90 int flags; /* Flags to describe interpretation - see
91 * below. */
92 ClientData nativePathPtr; /* Native representation of this path, which
93 * is filesystem dependent. */
94 int filesystemEpoch; /* Used to ensure the path representation was
95 * generated during the correct filesystem
96 * epoch. The epoch changes when
97 * filesystem-mounts are changed. */
98 const Tcl_Filesystem *fsPtr;/* The Tcl_Filesystem that claims this path */
99 } FsPath;
100
101 /*
102 * Flag values for FsPath->flags.
103 */
104
105 #define TCLPATH_APPENDED 1
106 #define TCLPATH_NEEDNORM 4
107
108 /*
109 * Define some macros to give us convenient access to path-object specific
110 * fields.
111 */
112
113 #define PATHOBJ(pathPtr) ((FsPath *) (pathPtr)->internalRep.twoPtrValue.ptr1)
114 #define SETPATHOBJ(pathPtr,fsPathPtr) \
115 ((pathPtr)->internalRep.twoPtrValue.ptr1 = (void *) (fsPathPtr))
116 #define PATHFLAGS(pathPtr) (PATHOBJ(pathPtr)->flags)
117
118 /*
119 *---------------------------------------------------------------------------
120 *
121 * TclFSNormalizeAbsolutePath --
122 *
123 * Takes an absolute path specification and computes a 'normalized' path
124 * from it.
125 *
126 * A normalized path is one which has all '../', './' removed. Also it is
127 * one which is in the 'standard' format for the native platform. On
128 * Unix, this means the path must be free of symbolic links/aliases, and
129 * on Windows it means we want the long form, with that long form's
130 * case-dependence (which gives us a unique, case-dependent path).
131 *
132 * The behaviour of this function if passed a non-absolute path is NOT
133 * defined.
134 *
135 * pathPtr may have a refCount of zero, or may be a shared object.
136 *
137 * Results:
138 * The result is returned in a Tcl_Obj with a refCount of 1, which is
139 * therefore owned by the caller. It must be freed (with
140 * Tcl_DecrRefCount) by the caller when no longer needed.
141 *
142 * Side effects:
143 * None (beyond the memory allocation for the result).
144 *
145 * Special note:
146 * This code was originally based on code from Matt Newman and
147 * Jean-Claude Wippler, but has since been totally rewritten by Vince
148 * Darley to deal with symbolic links.
149 *
150 *---------------------------------------------------------------------------
151 */
152
153 Tcl_Obj *
154 TclFSNormalizeAbsolutePath(
155 Tcl_Interp *interp, /* Interpreter to use */
156 Tcl_Obj *pathPtr) /* Absolute path to normalize */
157 {
158 const char *dirSep, *oldDirSep;
159 int first = 1; /* Set to zero once we've passed the first
160 * directory separator - we can't use '..' to
161 * remove the volume in a path. */
162 Tcl_Obj *retVal = NULL;
163 dirSep = TclGetString(pathPtr);
164
165 if (tclPlatform == TCL_PLATFORM_WINDOWS) {
166 if ( (dirSep[0] == '/' || dirSep[0] == '\\')
167 && (dirSep[1] == '/' || dirSep[1] == '\\')
168 && (dirSep[2] == '?')
169 && (dirSep[3] == '/' || dirSep[3] == '\\')) {
170 /* NT extended path */
171 dirSep += 4;
172
173 if ( (dirSep[0] == 'U' || dirSep[0] == 'u')
174 && (dirSep[1] == 'N' || dirSep[1] == 'n')
175 && (dirSep[2] == 'C' || dirSep[2] == 'c')
176 && (dirSep[3] == '/' || dirSep[3] == '\\')) {
177 /* NT extended UNC path */
178 dirSep += 4;
179 }
180 }
181 if (dirSep[0] != 0 && dirSep[1] == ':' &&
182 (dirSep[2] == '/' || dirSep[2] == '\\')) {
183 /* Do nothing */
184 } else if ((dirSep[0] == '/' || dirSep[0] == '\\')
185 && (dirSep[1] == '/' || dirSep[1] == '\\')) {
186 /*
187 * UNC style path, where we must skip over the first separator,
188 * since the first two segments are actually inseparable.
189 */
190
191 dirSep += 2;
192 dirSep += FindSplitPos(dirSep, '/');
193 if (*dirSep != 0) {
194 dirSep++;
195 }
196 }
197 }
198
199 /*
200 * Scan forward from one directory separator to the next, checking for
201 * '..' and '.' sequences which must be handled specially. In particular
202 * handling of '..' can be complicated if the directory before is a link,
203 * since we will have to expand the link to be able to back up one level.
204 */
205
206 while (*dirSep != 0) {
207 oldDirSep = dirSep;
208 if (!first) {
209 dirSep++;
210 }
211 dirSep += FindSplitPos(dirSep, '/');
212 if (dirSep[0] == 0 || dirSep[1] == 0) {
213 if (retVal != NULL) {
214 Tcl_AppendToObj(retVal, oldDirSep, dirSep - oldDirSep);
215 }
216 break;
217 }
218 if (dirSep[1] == '.') {
219 if (retVal != NULL) {
220 Tcl_AppendToObj(retVal, oldDirSep, dirSep - oldDirSep);
221 oldDirSep = dirSep;
222 }
223 again:
224 if (IsSeparatorOrNull(dirSep[2])) {
225 /*
226 * Need to skip '.' in the path.
227 */
228 int curLen;
229
230 if (retVal == NULL) {
231 const char *path = TclGetString(pathPtr);
232 retVal = Tcl_NewStringObj(path, dirSep - path);
233 Tcl_IncrRefCount(retVal);
234 }
235 Tcl_GetStringFromObj(retVal, &curLen);
236 if (curLen == 0) {
237 Tcl_AppendToObj(retVal, dirSep, 1);
238 }
239 dirSep += 2;
240 oldDirSep = dirSep;
241 if (dirSep[0] != 0 && dirSep[1] == '.') {
242 goto again;
243 }
244 continue;
245 }
246 if (dirSep[2] == '.' && IsSeparatorOrNull(dirSep[3])) {
247 Tcl_Obj *linkObj;
248 int curLen;
249 char *linkStr;
250
251 /*
252 * Have '..' so need to skip previous directory.
253 */
254
255 if (retVal == NULL) {
256 const char *path = TclGetString(pathPtr);
257
258 retVal = Tcl_NewStringObj(path, dirSep - path);
259 Tcl_IncrRefCount(retVal);
260 }
261 Tcl_GetStringFromObj(retVal, &curLen);
262 if (curLen == 0) {
263 Tcl_AppendToObj(retVal, dirSep, 1);
264 }
265 if (!first || (tclPlatform == TCL_PLATFORM_UNIX)) {
266 linkObj = Tcl_FSLink(retVal, NULL, 0);
267
268 /* Safety check in case driver caused sharing */
269 if (Tcl_IsShared(retVal)) {
270 TclDecrRefCount(retVal);
271 retVal = Tcl_DuplicateObj(retVal);
272 Tcl_IncrRefCount(retVal);
273 }
274
275 if (linkObj != NULL) {
276 /*
277 * Got a link. Need to check if the link is relative
278 * or absolute, for those platforms where relative
279 * links exist.
280 */
281
282 if (tclPlatform != TCL_PLATFORM_WINDOWS
283 && Tcl_FSGetPathType(linkObj)
284 == TCL_PATH_RELATIVE) {
285 /*
286 * We need to follow this link which is relative
287 * to retVal's directory. This means concatenating
288 * the link onto the directory of the path so far.
289 */
290
291 const char *path =
292 Tcl_GetStringFromObj(retVal, &curLen);
293
294 while (--curLen >= 0) {
295 if (IsSeparatorOrNull(path[curLen])) {
296 break;
297 }
298 }
299
300 /*
301 * We want the trailing slash.
302 */
303
304 Tcl_SetObjLength(retVal, curLen+1);
305 Tcl_AppendObjToObj(retVal, linkObj);
306 TclDecrRefCount(linkObj);
307 linkStr = Tcl_GetStringFromObj(retVal, &curLen);
308 } else {
309 /*
310 * Absolute link.
311 */
312
313 TclDecrRefCount(retVal);
314 if (Tcl_IsShared(linkObj)) {
315 retVal = Tcl_DuplicateObj(linkObj);
316 TclDecrRefCount(linkObj);
317 } else {
318 retVal = linkObj;
319 }
320 linkStr = Tcl_GetStringFromObj(retVal, &curLen);
321
322 /*
323 * Convert to forward-slashes on windows.
324 */
325
326 if (tclPlatform == TCL_PLATFORM_WINDOWS) {
327 int i;
328
329 for (i = 0; i < curLen; i++) {
330 if (linkStr[i] == '\\') {
331 linkStr[i] = '/';
332 }
333 }
334 }
335 }
336 } else {
337 linkStr = Tcl_GetStringFromObj(retVal, &curLen);
338 }
339
340 /*
341 * Either way, we now remove the last path element (but
342 * not the first character of the path).
343 */
344
345 while (--curLen >= 0) {
346 if (IsSeparatorOrNull(linkStr[curLen])) {
347 if (curLen) {
348 Tcl_SetObjLength(retVal, curLen);
349 } else {
350 Tcl_SetObjLength(retVal, 1);
351 }
352 break;
353 }
354 }
355 }
356 dirSep += 3;
357 oldDirSep = dirSep;
358
359 if ((curLen == 0) && (dirSep[0] != 0)) {
360 Tcl_SetObjLength(retVal, 0);
361 }
362
363 if (dirSep[0] != 0 && dirSep[1] == '.') {
364 goto again;
365 }
366 continue;
367 }
368 }
369 first = 0;
370 if (retVal != NULL) {
371 Tcl_AppendToObj(retVal, oldDirSep, dirSep - oldDirSep);
372 }
373 }
374
375 /*
376 * If we didn't make any changes, just use the input path.
377 */
378
379 if (retVal == NULL) {
380 retVal = pathPtr;
381 Tcl_IncrRefCount(retVal);
382
383 if (Tcl_IsShared(retVal)) {
384 /*
385 * Unfortunately, the platform-specific normalization code which
386 * will be called below has no way of dealing with the case where
387 * an object is shared. It is expecting to modify an object in
388 * place. So, we must duplicate this here to ensure an object with
389 * a single ref-count.
390 *
391 * If that changes in the future (e.g. the normalize proc is given
392 * one object and is able to return a different one), then we
393 * could remove this code.
394 */
395
396 TclDecrRefCount(retVal);
397 retVal = Tcl_DuplicateObj(pathPtr);
398 Tcl_IncrRefCount(retVal);
399 }
400 }
401
402 /*
403 * Ensure a windows drive like C:/ has a trailing separator.
404 */
405
406 if (tclPlatform == TCL_PLATFORM_WINDOWS) {
407 int len;
408 const char *path = Tcl_GetStringFromObj(retVal, &len);
409
410 if (len == 2 && path[0] != 0 && path[1] == ':') {
411 if (Tcl_IsShared(retVal)) {
412 TclDecrRefCount(retVal);
413 retVal = Tcl_DuplicateObj(retVal);
414 Tcl_IncrRefCount(retVal);
415 }
416 Tcl_AppendToObj(retVal, "/", 1);
417 }
418 }
419
420 /*
421 * Now we have an absolute path, with no '..', '.' sequences, but it still
422 * may not be in 'unique' form, depending on the platform. For instance,
423 * Unix is case-sensitive, so the path is ok. Windows is case-insensitive,
424 * and also has the weird 'longname/shortname' thing (e.g. C:/Program
425 * Files/ and C:/Progra~1/ are equivalent).
426 *
427 * Virtual file systems which may be registered may have other criteria
428 * for normalizing a path.
429 */
430
431 TclFSNormalizeToUniquePath(interp, retVal, 0);
432
433 /*
434 * Since we know it is a normalized path, we can actually convert this
435 * object into an FsPath for greater efficiency
436 */
437
438 MakePathFromNormalized(interp, retVal);
439
440 /*
441 * This has a refCount of 1 for the caller, unlike many Tcl_Obj APIs.
442 */
443
444 return retVal;
445 }
446
447 /*
448 *----------------------------------------------------------------------
449 *
450 * Tcl_FSGetPathType --
451 *
452 * Determines whether a given path is relative to the current directory,
453 * relative to the current volume, or absolute.
454 *
455 * Results:
456 * Returns one of TCL_PATH_ABSOLUTE, TCL_PATH_RELATIVE, or
457 * TCL_PATH_VOLUME_RELATIVE.
458 *
459 * Side effects:
460 * None.
461 *
462 *----------------------------------------------------------------------
463 */
464
465 Tcl_PathType
466 Tcl_FSGetPathType(
467 Tcl_Obj *pathPtr)
468 {
469 return TclFSGetPathType(pathPtr, NULL, NULL);
470 }
471
472 /*
473 *----------------------------------------------------------------------
474 *
475 * TclFSGetPathType --
476 *
477 * Determines whether a given path is relative to the current directory,
478 * relative to the current volume, or absolute. If the caller wishes to
479 * know which filesystem claimed the path (in the case for which the path
480 * is absolute), then a reference to a filesystem pointer can be passed
481 * in (but passing NULL is acceptable).
482 *
483 * Results:
484 * Returns one of TCL_PATH_ABSOLUTE, TCL_PATH_RELATIVE, or
485 * TCL_PATH_VOLUME_RELATIVE. The filesystem reference will be set if and
486 * only if it is non-NULL and the function's return value is
487 * TCL_PATH_ABSOLUTE.
488 *
489 * Side effects:
490 * None.
491 *
492 *----------------------------------------------------------------------
493 */
494
495 Tcl_PathType
496 TclFSGetPathType(
497 Tcl_Obj *pathPtr,
498 const Tcl_Filesystem **filesystemPtrPtr,
499 int *driveNameLengthPtr)
500 {
501 FsPath *fsPathPtr;
502
503 if (Tcl_FSConvertToPathType(NULL, pathPtr) != TCL_OK) {
504 return TclGetPathType(pathPtr, filesystemPtrPtr, driveNameLengthPtr,
505 NULL);
506 }
507
508 fsPathPtr = PATHOBJ(pathPtr);
509 if (fsPathPtr->cwdPtr == NULL) {
510 return TclGetPathType(pathPtr, filesystemPtrPtr, driveNameLengthPtr,
511 NULL);
512 }
513
514 if (PATHFLAGS(pathPtr) == 0) {
515 /* The path is not absolute... */
516 #ifdef _WIN32
517 /* ... on Windows we must make another call to determine whether
518 * it's relative or volumerelative [Bug 2571597]. */
519 return TclGetPathType(pathPtr, filesystemPtrPtr, driveNameLengthPtr,
520 NULL);
521 #else
522 /* On other systems, quickly deduce !absolute -> relative */
523 return TCL_PATH_RELATIVE;
524 #endif
525 }
526 return TclFSGetPathType(fsPathPtr->cwdPtr, filesystemPtrPtr,
527 driveNameLengthPtr);
528 }
529
530 /*
531 *---------------------------------------------------------------------------
532 *
533 * TclPathPart
534 *
535 * This function calculates the requested part of the given path, which
536 * can be:
537 *
538 * - the directory above ('file dirname')
539 * - the tail ('file tail')
540 * - the extension ('file extension')
541 * - the root ('file root')
542 *
543 * The 'portion' parameter dictates which of these to calculate. There
544 * are a number of special cases both to be more efficient, and because
545 * the behaviour when given a path with only a single element is defined
546 * to require the expansion of that single element, where possible.
547 *
548 * Should look into integrating 'FileBasename' in tclFCmd.c into this
549 * function.
550 *
551 * Results:
552 * NULL if an error occurred, otherwise a Tcl_Obj owned by the caller
553 * (i.e. most likely with refCount 1).
554 *
555 * Side effects:
556 * None.
557 *
558 *---------------------------------------------------------------------------
559 */
560
561 Tcl_Obj *
562 TclPathPart(
563 Tcl_Interp *interp, /* Used for error reporting */
564 Tcl_Obj *pathPtr, /* Path to take dirname of */
565 Tcl_PathPart portion) /* Requested portion of name */
566 {
567 if (pathPtr->typePtr == &tclFsPathType) {
568 FsPath *fsPathPtr = PATHOBJ(pathPtr);
569
570 if (PATHFLAGS(pathPtr) != 0) {
571 switch (portion) {
572 case TCL_PATH_DIRNAME: {
573 /*
574 * Check if the joined-on bit has any directory delimiters in
575 * it. If so, the 'dirname' would be a joining of the main
576 * part with the dirname of the joined-on bit. We could handle
577 * that special case here, but we don't, and instead just use
578 * the standardPath code.
579 */
580
581 int numBytes;
582 const char *rest =
583 Tcl_GetStringFromObj(fsPathPtr->normPathPtr, &numBytes);
584
585 if (strchr(rest, '/') != NULL) {
586 goto standardPath;
587 }
588 /*
589 * If the joined-on bit is empty, then [file dirname] is
590 * documented to return all but the last non-empty element
591 * of the path, so we need to split apart the main part to
592 * get the right answer. We could do that here, but it's
593 * simpler to fall back to the standardPath code.
594 * [Bug 2710920]
595 */
596 if (numBytes == 0) {
597 goto standardPath;
598 }
599 if (tclPlatform == TCL_PLATFORM_WINDOWS
600 && strchr(rest, '\\') != NULL) {
601 goto standardPath;
602 }
603
604 /*
605 * The joined-on path is simple, so we can just return here.
606 */
607
608 Tcl_IncrRefCount(fsPathPtr->cwdPtr);
609 return fsPathPtr->cwdPtr;
610 }
611 case TCL_PATH_TAIL: {
612 /*
613 * Check if the joined-on bit has any directory delimiters in
614 * it. If so, the 'tail' would be only the part following the
615 * last delimiter. We could handle that special case here, but
616 * we don't, and instead just use the standardPath code.
617 */
618
619 int numBytes;
620 const char *rest =
621 Tcl_GetStringFromObj(fsPathPtr->normPathPtr, &numBytes);
622
623 if (strchr(rest, '/') != NULL) {
624 goto standardPath;
625 }
626 /*
627 * If the joined-on bit is empty, then [file tail] is
628 * documented to return the last non-empty element
629 * of the path, so we need to split off the last element
630 * of the main part to get the right answer. We could do
631 * that here, but it's simpler to fall back to the
632 * standardPath code. [Bug 2710920]
633 */
634 if (numBytes == 0) {
635 goto standardPath;
636 }
637 if (tclPlatform == TCL_PLATFORM_WINDOWS
638 && strchr(rest, '\\') != NULL) {
639 goto standardPath;
640 }
641 Tcl_IncrRefCount(fsPathPtr->normPathPtr);
642 return fsPathPtr->normPathPtr;
643 }
644 case TCL_PATH_EXTENSION:
645 return GetExtension(fsPathPtr->normPathPtr);
646 case TCL_PATH_ROOT: {
647 const char *fileName, *extension;
648 int length;
649
650 fileName = Tcl_GetStringFromObj(fsPathPtr->normPathPtr,
651 &length);
652 extension = TclGetExtension(fileName);
653 if (extension == NULL) {
654 /*
655 * There is no extension so the root is the same as the
656 * path we were given.
657 */
658
659 Tcl_IncrRefCount(pathPtr);
660 return pathPtr;
661 } else {
662 /*
663 * Need to return the whole path with the extension
664 * suffix removed. Do that by joining our "head" to
665 * our "tail" with the extension suffix removed from
666 * the tail.
667 */
668
669 Tcl_Obj *resultPtr =
670 TclNewFSPathObj(fsPathPtr->cwdPtr, fileName,
671 (int)(length - strlen(extension)));
672
673 Tcl_IncrRefCount(resultPtr);
674 return resultPtr;
675 }
676 }
677 default:
678 /* We should never get here */
679 Tcl_Panic("Bad portion to TclPathPart");
680 /* For less clever compilers */
681 return NULL;
682 }
683 } else if (fsPathPtr->cwdPtr != NULL) {
684 /* Relative path */
685 goto standardPath;
686 } else {
687 /* Absolute path */
688 goto standardPath;
689 }
690 } else {
691 int splitElements;
692 Tcl_Obj *splitPtr, *resultPtr;
693
694 standardPath:
695 resultPtr = NULL;
696 if (portion == TCL_PATH_EXTENSION) {
697 return GetExtension(pathPtr);
698 } else if (portion == TCL_PATH_ROOT) {
699 int length;
700 const char *fileName, *extension;
701
702 fileName = Tcl_GetStringFromObj(pathPtr, &length);
703 extension = TclGetExtension(fileName);
704 if (extension == NULL) {
705 Tcl_IncrRefCount(pathPtr);
706 return pathPtr;
707 } else {
708 Tcl_Obj *root = Tcl_NewStringObj(fileName,
709 (int) (length - strlen(extension)));
710
711 Tcl_IncrRefCount(root);
712 return root;
713 }
714 }
715
716 /*
717 * The behaviour we want here is slightly different to the standard
718 * Tcl_FSSplitPath in the handling of home directories;
719 * Tcl_FSSplitPath preserves the "~" while this code computes the
720 * actual full path name, if we had just a single component.
721 */
722
723 splitPtr = Tcl_FSSplitPath(pathPtr, &splitElements);
724 Tcl_IncrRefCount(splitPtr);
725 if (splitElements == 1 && TclGetString(pathPtr)[0] == '~') {
726 Tcl_Obj *norm;
727
728 TclDecrRefCount(splitPtr);
729 norm = Tcl_FSGetNormalizedPath(interp, pathPtr);
730 if (norm == NULL) {
731 return NULL;
732 }
733 splitPtr = Tcl_FSSplitPath(norm, &splitElements);
734 Tcl_IncrRefCount(splitPtr);
735 }
736 if (portion == TCL_PATH_TAIL) {
737 /*
738 * Return the last component, unless it is the only component, and
739 * it is the root of an absolute path.
740 */
741
742 if ((splitElements > 0) && ((splitElements > 1) ||
743 (Tcl_FSGetPathType(pathPtr) == TCL_PATH_RELATIVE))) {
744 Tcl_ListObjIndex(NULL, splitPtr, splitElements-1, &resultPtr);
745 } else {
746 TclNewObj(resultPtr);
747 }
748 } else {
749 /*
750 * Return all but the last component. If there is only one
751 * component, return it if the path was non-relative, otherwise
752 * return the current directory.
753 */
754
755 if (splitElements > 1) {
756 resultPtr = Tcl_FSJoinPath(splitPtr, splitElements - 1);
757 } else if (splitElements == 0 ||
758 (Tcl_FSGetPathType(pathPtr) == TCL_PATH_RELATIVE)) {
759 TclNewLiteralStringObj(resultPtr, ".");
760 } else {
761 Tcl_ListObjIndex(NULL, splitPtr, 0, &resultPtr);
762 }
763 }
764 Tcl_IncrRefCount(resultPtr);
765 TclDecrRefCount(splitPtr);
766 return resultPtr;
767 }
768 }
769
770 /*
771 * Simple helper function
772 */
773
774 static Tcl_Obj *
775 GetExtension(
776 Tcl_Obj *pathPtr)
777 {
778 const char *tail, *extension;
779 Tcl_Obj *ret;
780
781 tail = TclGetString(pathPtr);
782 extension = TclGetExtension(tail);
783 if (extension == NULL) {
784 TclNewObj(ret);
785 } else {
786 ret = Tcl_NewStringObj(extension, -1);
787 }
788 Tcl_IncrRefCount(ret);
789 return ret;
790 }
791
792 /*
793 *---------------------------------------------------------------------------
794 *
795 * Tcl_FSJoinPath --
796 *
797 * This function takes the given Tcl_Obj, which should be a valid list,
798 * and returns the path object given by considering the first 'elements'
799 * elements as valid path segments (each path segment may be a complete
800 * path, a partial path or just a single possible directory or file
801 * name). If any path segment is actually an absolute path, then all
802 * prior path segments are discarded.
803 *
804 * If elements < 0, we use the entire list that was given.
805 *
806 * It is possible that the returned object is actually an element of the
807 * given list, so the caller should be careful to store a refCount to it
808 * before freeing the list.
809 *
810 * Results:
811 * Returns object with refCount of zero, (or if non-zero, it has
812 * references elsewhere in Tcl). Either way, the caller must increment
813 * its refCount before use. Note that in the case where the caller has
814 * asked to join zero elements of the list, the return value will be an
815 * empty-string Tcl_Obj.
816 *
817 * If the given listObj was invalid, then the calling routine has a bug,
818 * and this function will just return NULL.
819 *
820 * Side effects:
821 * None.
822 *
823 *---------------------------------------------------------------------------
824 */
825
826 Tcl_Obj *
827 Tcl_FSJoinPath(
828 Tcl_Obj *listObj, /* Path elements to join, may have a zero
829 * reference count. */
830 int elements) /* Number of elements to use (-1 = all) */
831 {
832 Tcl_Obj *res;
833 int objc;
834 Tcl_Obj **objv;
835
836 if (TclListObjLength(NULL, listObj, &objc) != TCL_OK) {
837 return NULL;
838 }
839
840 elements = ((elements >= 0) && (elements <= objc)) ? elements : objc;
841 TclListObjGetElements(NULL, listObj, &objc, &objv);
842 res = TclJoinPath(elements, objv, 0);
843 return res;
844 }
845
846 Tcl_Obj *
847 TclJoinPath(
848 int elements, /* Number of elements to use (-1 = all) */
849 Tcl_Obj * const objv[], /* Path elements to join */
850 int forceRelative) /* If non-zero, assume all more paths are
851 * relative (e.g. simple normalization) */
852 {
853 Tcl_Obj *res = NULL;
854 int i;
855 const Tcl_Filesystem *fsPtr = NULL;
856
857 assert ( elements >= 0 );
858
859 if (elements == 0) {
860 TclNewObj(res);
861 return res;
862 }
863
864 assert ( elements > 0 );
865
866 if (elements == 2) {
867 Tcl_Obj *elt = objv[0];
868
869 /*
870 * This is a special case where we can be much more efficient, where
871 * we are joining a single relative path onto an object that is
872 * already of path type. The 'TclNewFSPathObj' call below creates an
873 * object which can be normalized more efficiently. Currently we only
874 * use the special case when we have exactly two elements, but we
875 * could expand that in the future.
876 *
877 * Bugfix [a47641a0]. TclNewFSPathObj requires first argument
878 * to be an absolute path. Added a check for that elt is absolute.
879 */
880
881 if ((elt->typePtr == &tclFsPathType)
882 && !((elt->bytes != NULL) && (elt->bytes[0] == '\0'))
883 && TclGetPathType(elt, NULL, NULL, NULL) == TCL_PATH_ABSOLUTE) {
884 Tcl_Obj *tailObj = objv[1];
885 Tcl_PathType type;
886
887 /* if forceRelative - second path is relative */
888 type = forceRelative ? TCL_PATH_RELATIVE :
889 TclGetPathType(tailObj, NULL, NULL, NULL);
890 if (type == TCL_PATH_RELATIVE) {
891 const char *str;
892 int len;
893
894 str = Tcl_GetStringFromObj(tailObj, &len);
895 if (len == 0) {
896 /*
897 * This happens if we try to handle the root volume '/'.
898 * There's no need to return a special path object, when
899 * the base itself is just fine!
900 */
901
902 return elt;
903 }
904
905 /*
906 * If it doesn't begin with '.' and is a Unix path or it a
907 * windows path without backslashes, then we can be very
908 * efficient here. (In fact even a windows path with
909 * backslashes can be joined efficiently, but the path object
910 * would not have forward slashes only, and this would
911 * therefore contradict our 'file join' documentation).
912 */
913
914 if (str[0] != '.' && ((tclPlatform != TCL_PLATFORM_WINDOWS)
915 || (strchr(str, '\\') == NULL))) {
916 /*
917 * Finally, on Windows, 'file join' is defined to convert
918 * all backslashes to forward slashes, so the base part
919 * cannot have backslashes either.
920 */
921
922 if ((tclPlatform != TCL_PLATFORM_WINDOWS)
923 || (strchr(Tcl_GetString(elt), '\\') == NULL)) {
924
925 if (PATHFLAGS(elt)) {
926 return TclNewFSPathObj(elt, str, len);
927 }
928 if (TCL_PATH_ABSOLUTE != Tcl_FSGetPathType(elt)) {
929 return TclNewFSPathObj(elt, str, len);
930 }
931 (void) Tcl_FSGetNormalizedPath(NULL, elt);
932 if (elt == PATHOBJ(elt)->normPathPtr) {
933 return TclNewFSPathObj(elt, str, len);
934 }
935 }
936 }
937
938 /*
939 * Otherwise we don't have an easy join, and we must let the
940 * more general code below handle things.
941 */
942 } else if (tclPlatform == TCL_PLATFORM_UNIX) {
943 return tailObj;
944 } else {
945 const char *str = TclGetString(tailObj);
946
947 if (tclPlatform == TCL_PLATFORM_WINDOWS) {
948 if (strchr(str, '\\') == NULL) {
949 return tailObj;
950 }
951 }
952 }
953 }
954 }
955
956 assert ( res == NULL );
957
958 for (i = 0; i < elements; i++) {
959 int driveNameLength, strEltLen, length;
960 Tcl_PathType type;
961 char *strElt, *ptr;
962 Tcl_Obj *driveName = NULL;
963 Tcl_Obj *elt = objv[i];
964
965 strElt = Tcl_GetStringFromObj(elt, &strEltLen);
966 driveNameLength = 0;
967 /* if forceRelative - all paths excepting first one are relative */
968 type = (forceRelative && (i > 0)) ? TCL_PATH_RELATIVE :
969 TclGetPathType(elt, &fsPtr, &driveNameLength, &driveName);
970 if (type != TCL_PATH_RELATIVE) {
971 /*
972 * Zero out the current result.
973 */
974
975 if (res != NULL) {
976 TclDecrRefCount(res);
977 }
978
979 if (driveName != NULL) {
980 /*
981 * We've been given a separate drive-name object, because the
982 * prefix in 'elt' is not in a suitable format for us (e.g. it
983 * may contain irrelevant multiple separators, like
984 * C://///foo).
985 */
986
987 res = Tcl_DuplicateObj(driveName);
988 TclDecrRefCount(driveName);
989
990 /*
991 * Do not set driveName to NULL, because we will check its
992 * value below (but we won't access the contents, since those
993 * have been cleaned-up).
994 */
995 } else {
996 res = Tcl_NewStringObj(strElt, driveNameLength);
997 }
998 strElt += driveNameLength;
999 } else if (driveName != NULL) {
1000 Tcl_DecrRefCount(driveName);
1001 }
1002
1003 /*
1004 * Optimisation block: if this is the last element to be examined, and
1005 * it is absolute or the only element, and the drive-prefix was ok (if
1006 * there is one), it might be that the path is already in a suitable
1007 * form to be returned. Then we can short-cut the rest of this
1008 * function.
1009 */
1010
1011 if ((driveName == NULL) && (i == (elements - 1))
1012 && (type != TCL_PATH_RELATIVE || res == NULL)) {
1013 /*
1014 * It's the last path segment. Perform a quick check if the path
1015 * is already in a suitable form.
1016 */
1017
1018 if (tclPlatform == TCL_PLATFORM_WINDOWS) {
1019 if (strchr(strElt, '\\') != NULL) {
1020 goto noQuickReturn;
1021 }
1022 }
1023 ptr = strElt;
1024 /* [Bug f34cf83dd0] */
1025 if (driveNameLength > 0) {
1026 if (ptr[0] == '/' && ptr[-1] == '/') {
1027 goto noQuickReturn;
1028 }
1029 }
1030 while (*ptr != '\0') {
1031 if (*ptr == '/' && (ptr[1] == '/' || ptr[1] == '\0')) {
1032 /*
1033 * We have a repeated file separator, which means the path
1034 * is not in normalized form
1035 */
1036
1037 goto noQuickReturn;
1038 }
1039 ptr++;
1040 }
1041 if (res != NULL) {
1042 TclDecrRefCount(res);
1043 }
1044
1045 /*
1046 * This element is just what we want to return already; no further
1047 * manipulation is requred.
1048 */
1049
1050 return elt;
1051 }
1052
1053 /*
1054 * The path element was not of a suitable form to be returned as is.
1055 * We need to perform a more complex operation here.
1056 */
1057
1058 noQuickReturn:
1059 if (res == NULL) {
1060 TclNewObj(res);
1061 ptr = Tcl_GetStringFromObj(res, &length);
1062 } else {
1063 ptr = Tcl_GetStringFromObj(res, &length);
1064 }
1065
1066 /*
1067 * Strip off any './' before a tilde, unless this is the beginning of
1068 * the path.
1069 */
1070
1071 if (length > 0 && strEltLen > 0 && (strElt[0] == '.') &&
1072 (strElt[1] == '/') && (strElt[2] == '~')) {
1073 strElt += 2;
1074 }
1075
1076 /*
1077 * A NULL value for fsPtr at this stage basically means we're trying
1078 * to join a relative path onto something which is also relative (or
1079 * empty). There's nothing particularly wrong with that.
1080 */
1081
1082 if (*strElt == '\0') {
1083 continue;
1084 }
1085
1086 if (fsPtr == &tclNativeFilesystem || fsPtr == NULL) {
1087 TclpNativeJoinPath(res, strElt);
1088 } else {
1089 char separator = '/';
1090 int needsSep = 0;
1091
1092 if (fsPtr->filesystemSeparatorProc != NULL) {
1093 Tcl_Obj *sep = fsPtr->filesystemSeparatorProc(res);
1094
1095 if (sep != NULL) {
1096 separator = TclGetString(sep)[0];
1097 Tcl_DecrRefCount(sep);
1098 }
1099 /* Safety check in case the VFS driver caused sharing */
1100 if (Tcl_IsShared(res)) {
1101 TclDecrRefCount(res);
1102 res = Tcl_DuplicateObj(res);
1103 Tcl_IncrRefCount(res);
1104 }
1105 }
1106
1107 if (length > 0 && ptr[length -1] != '/') {
1108 Tcl_AppendToObj(res, &separator, 1);
1109 Tcl_GetStringFromObj(res, &length);
1110 }
1111 Tcl_SetObjLength(res, length + (int) strlen(strElt));
1112
1113 ptr = TclGetString(res) + length;
1114 for (; *strElt != '\0'; strElt++) {
1115 if (*strElt == separator) {
1116 while (strElt[1] == separator) {
1117 strElt++;
1118 }
1119 if (strElt[1] != '\0') {
1120 if (needsSep) {
1121 *ptr++ = separator;
1122 }
1123 }
1124 } else {
1125 *ptr++ = *strElt;
1126 needsSep = 1;
1127 }
1128 }
1129 length = ptr - TclGetString(res);
1130 Tcl_SetObjLength(res, length);
1131 }
1132 }
1133 assert ( res != NULL );
1134 return res;
1135 }
1136
1137 /*
1138 *---------------------------------------------------------------------------
1139 *
1140 * Tcl_FSConvertToPathType --
1141 *
1142 * This function tries to convert the given Tcl_Obj to a valid Tcl path
1143 * type, taking account of the fact that the cwd may have changed even if
1144 * this object is already supposedly of the correct type.
1145 *
1146 * The filename may begin with "~" (to indicate current user's home
1147 * directory) or "~<user>" (to indicate any user's home directory).
1148 *
1149 * Results:
1150 * Standard Tcl error code.
1151 *
1152 * Side effects:
1153 * The old representation may be freed, and new memory allocated.
1154 *
1155 *---------------------------------------------------------------------------
1156 */
1157
1158 int
1159 Tcl_FSConvertToPathType(
1160 Tcl_Interp *interp, /* Interpreter in which to store error message
1161 * (if necessary). */
1162 Tcl_Obj *pathPtr) /* Object to convert to a valid, current path
1163 * type. */
1164 {
1165 /*
1166 * While it is bad practice to examine an object's type directly, this is
1167 * actually the best thing to do here. The reason is that if we are
1168 * converting this object to FsPath type for the first time, we don't need
1169 * to worry whether the 'cwd' has changed. On the other hand, if this
1170 * object is already of FsPath type, and is a relative path, we do have to
1171 * worry about the cwd. If the cwd has changed, we must recompute the
1172 * path.
1173 */
1174
1175 if (pathPtr->typePtr == &tclFsPathType) {
1176 if (TclFSEpochOk(PATHOBJ(pathPtr)->filesystemEpoch)) {
1177 return TCL_OK;
1178 }
1179
1180 if (pathPtr->bytes == NULL) {
1181 UpdateStringOfFsPath(pathPtr);
1182 }
1183 FreeFsPathInternalRep(pathPtr);
1184 }
1185
1186 return SetFsPathFromAny(interp, pathPtr);
1187
1188 /*
1189 * We used to have more complex code here:
1190 *
1191 * FsPath *fsPathPtr = PATHOBJ(pathPtr);
1192 * if (fsPathPtr->cwdPtr == NULL || PATHFLAGS(pathPtr) != 0) {
1193 * return TCL_OK;
1194 * } else {
1195 * if (TclFSCwdPointerEquals(&fsPathPtr->cwdPtr)) {
1196 * return TCL_OK;
1197 * } else {
1198 * if (pathPtr->bytes == NULL) {
1199 * UpdateStringOfFsPath(pathPtr);
1200 * }
1201 * FreeFsPathInternalRep(pathPtr);
1202 * return Tcl_ConvertToType(interp, pathPtr, &tclFsPathType);
1203 * }
1204 * }
1205 *
1206 * But we no longer believe this is necessary.
1207 */
1208 }
1209
1210 /*
1211 * Helper function for normalization.
1212 */
1213
1214 static int
1215 IsSeparatorOrNull(
1216 int ch)
1217 {
1218 if (ch == 0) {
1219 return 1;
1220 }
1221 switch (tclPlatform) {
1222 case TCL_PLATFORM_UNIX:
1223 return (ch == '/' ? 1 : 0);
1224 case TCL_PLATFORM_WINDOWS:
1225 return ((ch == '/' || ch == '\\') ? 1 : 0);
1226 }
1227 return 0;
1228 }
1229
1230 /*
1231 * Helper function for SetFsPathFromAny. Returns position of first directory
1232 * delimiter in the path. If no separator is found, then returns the position
1233 * of the end of the string.
1234 */
1235
1236 static int
1237 FindSplitPos(
1238 const char *path,
1239 int separator)
1240 {
1241 int count = 0;
1242 switch (tclPlatform) {
1243 case TCL_PLATFORM_UNIX:
1244 while (path[count] != 0) {
1245 if (path[count] == separator) {
1246 return count;
1247 }
1248 count++;
1249 }
1250 break;
1251
1252 case TCL_PLATFORM_WINDOWS:
1253 while (path[count] != 0) {
1254 if (path[count] == separator || path[count] == '\\') {
1255 return count;
1256 }
1257 count++;
1258 }
1259 break;
1260 }
1261 return count;
1262 }
1263
1264 /*
1265 *---------------------------------------------------------------------------
1266 *
1267 * TclNewFSPathObj --
1268 *
1269 * Creates a path object whose string representation is '[file join
1270 * dirPtr addStrRep]', but does so in a way that allows for more
1271 * efficient creation and caching of normalized paths, and more efficient
1272 * 'file dirname', 'file tail', etc.
1273 *
1274 * Assumptions:
1275 * 'dirPtr' must be an absolute path. 'len' may not be zero.
1276 *
1277 * Results:
1278 * The new Tcl object, with refCount zero.
1279 *
1280 * Side effects:
1281 * Memory is allocated. 'dirPtr' gets an additional refCount.
1282 *
1283 *---------------------------------------------------------------------------
1284 */
1285
1286 Tcl_Obj *
1287 TclNewFSPathObj(
1288 Tcl_Obj *dirPtr,
1289 const char *addStrRep,
1290 int len)
1291 {
1292 FsPath *fsPathPtr;
1293 Tcl_Obj *pathPtr;
1294 const char *p;
1295 int state = 0, count = 0;
1296
1297 /* [Bug 2806250] - this is only a partial solution of the problem.
1298 * The PATHFLAGS != 0 representation assumes in many places that
1299 * the "tail" part stored in the normPathPtr field is itself a
1300 * relative path. Strings that begin with "~" are not relative paths,
1301 * so we must prevent their storage in the normPathPtr field.
1302 *
1303 * More generally we ought to be testing "addStrRep" for any value
1304 * that is not a relative path, but in an unconstrained VFS world
1305 * that could be just about anything, and testing could be expensive.
1306 * Since this routine plays a big role in [glob], anything that slows
1307 * it down would be unwelcome. For now, continue the risk of further
1308 * bugs when some Tcl_Filesystem uses otherwise relative path strings
1309 * as absolute path strings. Sensible Tcl_Filesystems will avoid
1310 * that by mounting on path prefixes like foo:// which cannot be the
1311 * name of a file or directory read from a native [glob] operation.
1312 */
1313 if (addStrRep[0] == '~') {
1314 Tcl_Obj *tail = Tcl_NewStringObj(addStrRep, len);
1315
1316 pathPtr = AppendPath(dirPtr, tail);
1317 Tcl_DecrRefCount(tail);
1318 return pathPtr;
1319 }
1320
1321 TclNewObj(pathPtr);
1322 fsPathPtr = ckalloc(sizeof(FsPath));
1323
1324 /*
1325 * Set up the path.
1326 */
1327
1328 fsPathPtr->translatedPathPtr = NULL;
1329 fsPathPtr->normPathPtr = Tcl_NewStringObj(addStrRep, len);
1330 Tcl_IncrRefCount(fsPathPtr->normPathPtr);
1331 fsPathPtr->cwdPtr = dirPtr;
1332 Tcl_IncrRefCount(dirPtr);
1333 fsPathPtr->nativePathPtr = NULL;
1334 fsPathPtr->fsPtr = NULL;
1335 fsPathPtr->filesystemEpoch = 0;
1336
1337 SETPATHOBJ(pathPtr, fsPathPtr);
1338 PATHFLAGS(pathPtr) = TCLPATH_APPENDED;
1339 pathPtr->typePtr = &tclFsPathType;
1340 pathPtr->bytes = NULL;
1341 pathPtr->length = 0;
1342
1343 /*
1344 * Look for path components made up of only "."
1345 * This is overly conservative analysis to keep simple. It may mark some
1346 * things as needing more aggressive normalization that don't actually
1347 * need it. No harm done.
1348 */
1349 for (p = addStrRep; len > 0; p++, len--) {
1350 switch (state) {
1351 case 0: /* So far only "." since last dirsep or start */
1352 switch (*p) {
1353 case '.':
1354 count++;
1355 break;
1356 case '/':
1357 case '\\':
1358 case ':':
1359 if (count) {
1360 PATHFLAGS(pathPtr) |= TCLPATH_NEEDNORM;
1361 len = 0;
1362 }
1363 break;
1364 default:
1365 count = 0;
1366 state = 1;
1367 }
1368 break;
1369 case 1: /* Scanning for next dirsep */
1370 switch (*p) {
1371 case '/':
1372 case '\\':
1373 case ':':
1374 state = 0;
1375 break;
1376 }
1377 }
1378 }
1379 if (len == 0 && count) {
1380 PATHFLAGS(pathPtr) |= TCLPATH_NEEDNORM;
1381 }
1382
1383 return pathPtr;
1384 }
1385
1386 static Tcl_Obj *
1387 AppendPath(
1388 Tcl_Obj *head,
1389 Tcl_Obj *tail)
1390 {
1391 int numBytes;
1392 const char *bytes;
1393 Tcl_Obj *copy = Tcl_DuplicateObj(head);
1394
1395 /*
1396 * This is likely buggy when dealing with virtual filesystem drivers
1397 * that use some character other than "/" as a path separator. I know
1398 * of no evidence that such a foolish thing exists. This solution was
1399 * chosen so that "JoinPath" operations that pass through either path
1400 * internalrep produce the same results; that is, bugward compatibility. If
1401 * we need to fix that bug here, it needs fixing in TclJoinPath() too.
1402 */
1403 bytes = Tcl_GetStringFromObj(tail, &numBytes);
1404 if (numBytes == 0) {
1405 Tcl_AppendToObj(copy, "/", 1);
1406 } else {
1407 TclpNativeJoinPath(copy, bytes);
1408 }
1409 return copy;
1410 }
1411
1412 /*
1413 *---------------------------------------------------------------------------
1414 *
1415 * TclFSMakePathRelative --
1416 *
1417 * Only for internal use.
1418 *
1419 * Takes a path and a directory, where we _assume_ both path and
1420 * directory are absolute, normalized and that the path lies inside the
1421 * directory. Returns a Tcl_Obj representing filename of the path
1422 * relative to the directory.
1423 *
1424 * Results:
1425 * NULL on error, otherwise a valid object, typically with refCount of
1426 * zero, which it is assumed the caller will increment.
1427 *
1428 * Side effects:
1429 * The old representation may be freed, and new memory allocated.
1430 *
1431 *---------------------------------------------------------------------------
1432 */
1433
1434 Tcl_Obj *
1435 TclFSMakePathRelative(
1436 Tcl_Interp *interp, /* Used for error reporting if not NULL. */
1437 Tcl_Obj *pathPtr, /* The path we have. */
1438 Tcl_Obj *cwdPtr) /* Make it relative to this. */
1439 {
1440 int cwdLen, len;
1441 const char *tempStr;
1442
1443 if (pathPtr->typePtr == &tclFsPathType) {
1444 FsPath *fsPathPtr = PATHOBJ(pathPtr);
1445
1446 if (PATHFLAGS(pathPtr) != 0 && fsPathPtr->cwdPtr == cwdPtr) {
1447 return fsPathPtr->normPathPtr;
1448 }
1449 }
1450
1451 /*
1452 * We know the cwd is a normalised object which does not end in a
1453 * directory delimiter, unless the cwd is the name of a volume, in which
1454 * case it will end in a delimiter! We handle this situation here. A
1455 * better test than the '!= sep' might be to simply check if 'cwd' is a
1456 * root volume.
1457 *
1458 * Note that if we get this wrong, we will strip off either too much or
1459 * too little below, leading to wrong answers returned by glob.
1460 */
1461
1462 tempStr = Tcl_GetStringFromObj(cwdPtr, &cwdLen);
1463
1464 /*
1465 * Should we perhaps use 'Tcl_FSPathSeparator'? But then what about the
1466 * Windows special case? Perhaps we should just check if cwd is a root
1467 * volume.
1468 */
1469
1470 switch (tclPlatform) {
1471 case TCL_PLATFORM_UNIX:
1472 if (tempStr[cwdLen-1] != '/') {
1473 cwdLen++;
1474 }
1475 break;
1476 case TCL_PLATFORM_WINDOWS:
1477 if (tempStr[cwdLen-1] != '/' && tempStr[cwdLen-1] != '\\') {
1478 cwdLen++;
1479 }
1480 break;
1481 }
1482 tempStr = Tcl_GetStringFromObj(pathPtr, &len);
1483
1484 return Tcl_NewStringObj(tempStr + cwdLen, len - cwdLen);
1485 }
1486
1487 /*
1488 *---------------------------------------------------------------------------
1489 *
1490 * MakePathFromNormalized --
1491 *
1492 * Like SetFsPathFromAny, but assumes the given object is an absolute
1493 * normalized path. Only for internal use.
1494 *
1495 * Results:
1496 * Standard Tcl error code.
1497 *
1498 * Side effects:
1499 * The old representation may be freed, and new memory allocated.
1500 *
1501 *---------------------------------------------------------------------------
1502 */
1503
1504 static int
1505 MakePathFromNormalized(
1506 Tcl_Interp *interp, /* Used for error reporting if not NULL. */
1507 Tcl_Obj *pathPtr) /* The object to convert. */
1508 {
1509 FsPath *fsPathPtr;
1510
1511 if (pathPtr->typePtr == &tclFsPathType) {
1512 return TCL_OK;
1513 }
1514
1515 /*
1516 * Free old representation
1517 */
1518
1519 if (pathPtr->typePtr != NULL) {
1520 if (pathPtr->bytes == NULL) {
1521 if (pathPtr->typePtr->updateStringProc == NULL) {
1522 if (interp != NULL) {
1523 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1524 "can't find object string representation", -1));
1525 Tcl_SetErrorCode(interp, "TCL", "VALUE", "PATH", "WTF",
1526 (char *)NULL);
1527 }
1528 return TCL_ERROR;
1529 }
1530 pathPtr->typePtr->updateStringProc(pathPtr);
1531 }
1532 TclFreeIntRep(pathPtr);
1533 }
1534
1535 fsPathPtr = ckalloc(sizeof(FsPath));
1536
1537 /*
1538 * It's a pure normalized absolute path.
1539 */
1540
1541 fsPathPtr->translatedPathPtr = NULL;
1542
1543 /*
1544 * Circular reference by design.
1545 */
1546
1547 fsPathPtr->normPathPtr = pathPtr;
1548 fsPathPtr->cwdPtr = NULL;
1549 fsPathPtr->nativePathPtr = NULL;
1550 fsPathPtr->fsPtr = NULL;
1551 /* Remember the epoch under which we decided pathPtr was normalized */
1552 fsPathPtr->filesystemEpoch = TclFSEpoch();
1553
1554 SETPATHOBJ(pathPtr, fsPathPtr);
1555 PATHFLAGS(pathPtr) = 0;
1556 pathPtr->typePtr = &tclFsPathType;
1557
1558 return TCL_OK;
1559 }
1560
1561 /*
1562 *---------------------------------------------------------------------------
1563 *
1564 * Tcl_FSNewNativePath --
1565 *
1566 * This function performs the something like the reverse of the usual
1567 * obj->path->nativerep conversions. If some code retrieves a path in
1568 * native form (from, e.g. readlink or a native dialog), and that path is
1569 * to be used at the Tcl level, then calling this function is an
1570 * efficient way of creating the appropriate path object type.
1571 *
1572 * Any memory which is allocated for 'clientData' should be retained
1573 * until clientData is passed to the filesystem's freeInternalRepProc
1574 * when it can be freed. The built in platform-specific filesystems use
1575 * 'ckalloc' to allocate clientData, and ckfree to free it.
1576 *
1577 * Results:
1578 * NULL or a valid path object pointer, with refCount zero.
1579 *
1580 * Side effects:
1581 * New memory may be allocated.
1582 *
1583 *---------------------------------------------------------------------------
1584 */
1585
1586 Tcl_Obj *
1587 Tcl_FSNewNativePath(
1588 const Tcl_Filesystem *fromFilesystem,
1589 ClientData clientData)
1590 {
1591 Tcl_Obj *pathPtr = NULL;
1592 FsPath *fsPathPtr;
1593
1594
1595 if (fromFilesystem->internalToNormalizedProc != NULL) {
1596 pathPtr = (*fromFilesystem->internalToNormalizedProc)(clientData);
1597 }
1598 if (pathPtr == NULL) {
1599 return NULL;
1600 }
1601
1602 /*
1603 * Free old representation; shouldn't normally be any, but best to be
1604 * safe.
1605 */
1606
1607 if (pathPtr->typePtr != NULL) {
1608 if (pathPtr->bytes == NULL) {
1609 if (pathPtr->typePtr->updateStringProc == NULL) {
1610 return NULL;
1611 }
1612 pathPtr->typePtr->updateStringProc(pathPtr);
1613 }
1614 TclFreeIntRep(pathPtr);
1615 }
1616
1617 fsPathPtr = ckalloc(sizeof(FsPath));
1618
1619 fsPathPtr->translatedPathPtr = NULL;
1620
1621 /*
1622 * Circular reference, by design.
1623 */
1624
1625 fsPathPtr->normPathPtr = pathPtr;
1626 fsPathPtr->cwdPtr = NULL;
1627 fsPathPtr->nativePathPtr = clientData;
1628 fsPathPtr->fsPtr = fromFilesystem;
1629 fsPathPtr->filesystemEpoch = TclFSEpoch();
1630
1631 SETPATHOBJ(pathPtr, fsPathPtr);
1632 PATHFLAGS(pathPtr) = 0;
1633 pathPtr->typePtr = &tclFsPathType;
1634
1635 return pathPtr;
1636 }
1637
1638 /*
1639 *---------------------------------------------------------------------------
1640 *
1641 * Tcl_FSGetTranslatedPath --
1642 *
1643 * This function attempts to extract the translated path from the given
1644 * Tcl_Obj. If the translation succeeds (i.e. the object is a valid
1645 * path), then it is returned. Otherwise NULL will be returned, and an
1646 * error message may be left in the interpreter (if it is non-NULL)
1647 *
1648 * Results:
1649 * NULL or a valid Tcl_Obj pointer.
1650 *
1651 * Side effects:
1652 * Only those of 'Tcl_FSConvertToPathType'
1653 *
1654 *---------------------------------------------------------------------------
1655 */
1656
1657 Tcl_Obj *
1658 Tcl_FSGetTranslatedPath(
1659 Tcl_Interp *interp,
1660 Tcl_Obj *pathPtr)
1661 {
1662 Tcl_Obj *retObj = NULL;
1663 FsPath *srcFsPathPtr;
1664
1665 if (Tcl_FSConvertToPathType(interp, pathPtr) != TCL_OK) {
1666 return NULL;
1667 }
1668 srcFsPathPtr = PATHOBJ(pathPtr);
1669 if (srcFsPathPtr->translatedPathPtr == NULL) {
1670 if (PATHFLAGS(pathPtr) != 0) {
1671 /*
1672 * We lack a translated path result, but we have a directory
1673 * (cwdPtr) and a tail (normPathPtr), and if we join the
1674 * translated version of cwdPtr to normPathPtr, we'll get the
1675 * translated result we need, and can store it for future use.
1676 */
1677
1678 Tcl_Obj *translatedCwdPtr = Tcl_FSGetTranslatedPath(interp,
1679 srcFsPathPtr->cwdPtr);
1680 if (translatedCwdPtr == NULL) {
1681 return NULL;
1682 }
1683
1684 retObj = Tcl_FSJoinToPath(translatedCwdPtr, 1,
1685 &srcFsPathPtr->normPathPtr);
1686 srcFsPathPtr->translatedPathPtr = retObj;
1687 if (translatedCwdPtr->typePtr == &tclFsPathType) {
1688 srcFsPathPtr->filesystemEpoch
1689 = PATHOBJ(translatedCwdPtr)->filesystemEpoch;
1690 } else {
1691 srcFsPathPtr->filesystemEpoch = 0;
1692 }
1693 Tcl_IncrRefCount(retObj);
1694 Tcl_DecrRefCount(translatedCwdPtr);
1695 } else {
1696 /*
1697 * It is a pure absolute, normalized path object. This is
1698 * something like being a 'pure list'. The object's string,
1699 * translatedPath and normalizedPath are all identical.
1700 */
1701
1702 retObj = srcFsPathPtr->normPathPtr;
1703 }
1704 } else {
1705 /*
1706 * It is an ordinary path object.
1707 */
1708
1709 retObj = srcFsPathPtr->translatedPathPtr;
1710 }
1711
1712 if (retObj != NULL) {
1713 Tcl_IncrRefCount(retObj);
1714 }
1715 return retObj;
1716 }
1717
1718 /*
1719 *---------------------------------------------------------------------------
1720 *
1721 * Tcl_FSGetTranslatedStringPath --
1722 *
1723 * This function attempts to extract the translated path from the given
1724 * Tcl_Obj. If the translation succeeds (i.e. the object is a valid
1725 * path), then the path is returned. Otherwise NULL will be returned, and
1726 * an error message may be left in the interpreter (if it is non-NULL)
1727 *
1728 * Results:
1729 * NULL or a valid string.
1730 *
1731 * Side effects:
1732 * Only those of 'Tcl_FSConvertToPathType'
1733 *
1734 *---------------------------------------------------------------------------
1735 */
1736
1737 const char *
1738 Tcl_FSGetTranslatedStringPath(
1739 Tcl_Interp *interp,
1740 Tcl_Obj *pathPtr)
1741 {
1742 Tcl_Obj *transPtr = Tcl_FSGetTranslatedPath(interp, pathPtr);
1743
1744 if (transPtr != NULL) {
1745 int len;
1746 const char *orig = Tcl_GetStringFromObj(transPtr, &len);
1747 char *result = ckalloc(len+1);
1748
1749 memcpy(result, orig, len+1);
1750 TclDecrRefCount(transPtr);
1751 return result;
1752 }
1753
1754 return NULL;
1755 }
1756
1757 /*
1758 *---------------------------------------------------------------------------
1759 *
1760 * Tcl_FSGetNormalizedPath --
1761 *
1762 * This important function attempts to extract from the given Tcl_Obj a
1763 * unique normalised path representation, whose string value can be used
1764 * as a unique identifier for the file.
1765 *
1766 * Results:
1767 * NULL or a valid path object pointer.
1768 *
1769 * Side effects:
1770 * New memory may be allocated. The Tcl 'errno' may be modified in the
1771 * process of trying to examine various path possibilities.
1772 *
1773 *---------------------------------------------------------------------------
1774 */
1775
1776 Tcl_Obj *
1777 Tcl_FSGetNormalizedPath(
1778 Tcl_Interp *interp,
1779 Tcl_Obj *pathPtr)
1780 {
1781 FsPath *fsPathPtr;
1782
1783 if (Tcl_FSConvertToPathType(interp, pathPtr) != TCL_OK) {
1784 return NULL;
1785 }
1786 fsPathPtr = PATHOBJ(pathPtr);
1787
1788 if (PATHFLAGS(pathPtr) != 0) {
1789 /*
1790 * This is a special path object which is the result of something like
1791 * 'file join'
1792 */
1793
1794 Tcl_Obj *dir, *copy;
1795 int tailLen, cwdLen, pathType;
1796
1797 pathType = Tcl_FSGetPathType(fsPathPtr->cwdPtr);
1798 dir = Tcl_FSGetNormalizedPath(interp, fsPathPtr->cwdPtr);
1799 if (dir == NULL) {
1800 return NULL;
1801 }
1802 /* TODO: Figure out why this is needed. */
1803 if (pathPtr->bytes == NULL) {
1804 UpdateStringOfFsPath(pathPtr);
1805 }
1806
1807 Tcl_GetStringFromObj(fsPathPtr->normPathPtr, &tailLen);
1808 if (tailLen) {
1809 copy = AppendPath(dir, fsPathPtr->normPathPtr);
1810 } else {
1811 copy = Tcl_DuplicateObj(dir);
1812 }
1813 Tcl_IncrRefCount(dir);
1814 Tcl_IncrRefCount(copy);
1815
1816 /*
1817 * We now own a reference on both 'dir' and 'copy'
1818 */
1819
1820 (void) Tcl_GetStringFromObj(dir, &cwdLen);
1821
1822 /* Normalize the combined string. */
1823
1824 if (PATHFLAGS(pathPtr) & TCLPATH_NEEDNORM) {
1825 /*
1826 * If the "tail" part has components (like /../) that cause the
1827 * combined path to need more complete normalizing, call on the
1828 * more powerful routine to accomplish that so we avoid [Bug
1829 * 2385549] ...
1830 */
1831
1832 Tcl_Obj *newCopy = TclFSNormalizeAbsolutePath(interp, copy);
1833
1834 Tcl_DecrRefCount(copy);
1835 copy = newCopy;
1836 } else {
1837 /*
1838 * ... but in most cases where we join a trouble free tail to a
1839 * normalized head, we can more efficiently normalize the combined
1840 * path by passing over only the unnormalized tail portion. When
1841 * this is sufficient, prior developers claim this should be much
1842 * faster. We use 'cwdLen' so that we are already pointing at
1843 * the dir-separator that we know about. The normalization code
1844 * will actually start off directly after that separator.
1845 */
1846
1847 TclFSNormalizeToUniquePath(interp, copy, cwdLen);
1848 }
1849
1850 /* Now we need to construct the new path object. */
1851
1852 if (pathType == TCL_PATH_RELATIVE) {
1853 Tcl_Obj *origDir = fsPathPtr->cwdPtr;
1854
1855 /*
1856 * NOTE: here we are (dangerously?) assuming that origDir points
1857 * to a Tcl_Obj with Tcl_ObjType == &tclFsPathType. The
1858 * pathType = Tcl_FSGetPathType(fsPathPtr->cwdPtr);
1859 * above that set the pathType value should have established that,
1860 * but it's far less clear on what basis we know there's been no
1861 * shimmering since then.
1862 */
1863
1864 FsPath *origDirFsPathPtr = PATHOBJ(origDir);
1865
1866 fsPathPtr->cwdPtr = origDirFsPathPtr->cwdPtr;
1867 Tcl_IncrRefCount(fsPathPtr->cwdPtr);
1868
1869 TclDecrRefCount(fsPathPtr->normPathPtr);
1870 fsPathPtr->normPathPtr = copy;
1871
1872 /*
1873 * That's our reference to copy used.
1874 */
1875
1876 TclDecrRefCount(dir);
1877 TclDecrRefCount(origDir);
1878 } else {
1879 TclDecrRefCount(fsPathPtr->cwdPtr);
1880 fsPathPtr->cwdPtr = NULL;
1881 TclDecrRefCount(fsPathPtr->normPathPtr);
1882 fsPathPtr->normPathPtr = copy;
1883
1884 /*
1885 * That's our reference to copy used.
1886 */
1887
1888 TclDecrRefCount(dir);
1889 }
1890 PATHFLAGS(pathPtr) = 0;
1891 }
1892
1893 /*
1894 * Ensure cwd hasn't changed.
1895 */
1896
1897 if (fsPathPtr->cwdPtr != NULL) {
1898 if (!TclFSCwdPointerEquals(&fsPathPtr->cwdPtr)) {
1899 if (pathPtr->bytes == NULL) {
1900 UpdateStringOfFsPath(pathPtr);
1901 }
1902 FreeFsPathInternalRep(pathPtr);
1903 if (SetFsPathFromAny(interp, pathPtr) != TCL_OK) {
1904 return NULL;
1905 }
1906 fsPathPtr = PATHOBJ(pathPtr);
1907 } else if (fsPathPtr->normPathPtr == NULL) {
1908 int cwdLen;
1909 Tcl_Obj *copy;
1910
1911 copy = AppendPath(fsPathPtr->cwdPtr, pathPtr);
1912
1913 (void) Tcl_GetStringFromObj(fsPathPtr->cwdPtr, &cwdLen);
1914 cwdLen += (Tcl_GetString(copy)[cwdLen] == '/');
1915
1916 /*
1917 * Normalize the combined string, but only starting after the end
1918 * of the previously normalized 'dir'. This should be much faster!
1919 */
1920
1921 TclFSNormalizeToUniquePath(interp, copy, cwdLen-1);
1922 fsPathPtr->normPathPtr = copy;
1923 Tcl_IncrRefCount(fsPathPtr->normPathPtr);
1924 }
1925 }
1926 if (fsPathPtr->normPathPtr == NULL) {
1927 Tcl_Obj *useThisCwd = NULL;
1928 int pureNormalized = 1;
1929
1930 /*
1931 * Since normPathPtr is NULL, but this is a valid path object, we know
1932 * that the translatedPathPtr cannot be NULL.
1933 */
1934
1935 Tcl_Obj *absolutePath = fsPathPtr->translatedPathPtr;
1936 const char *path = TclGetString(absolutePath);
1937
1938 Tcl_IncrRefCount(absolutePath);
1939
1940 /*
1941 * We have to be a little bit careful here to avoid infinite loops
1942 * we're asking Tcl_FSGetPathType to return the path's type, but that
1943 * call can actually result in a lot of other filesystem action, which
1944 * might loop back through here.
1945 */
1946
1947 if (path[0] == '\0') {
1948 /*
1949 * Special handling for the empty string value. This one is very
1950 * weird with [file normalize {}] => {}. (The reasoning supporting
1951 * this is unknown to DGP, but he fears changing it.) Attempt here
1952 * to keep the expectations of other parts of Tcl_Filesystem code
1953 * about state of the FsPath fields satisfied.
1954 *
1955 * In particular, capture the cwd value and save so it can be
1956 * stored in the cwdPtr field below.
1957 */
1958
1959 useThisCwd = Tcl_FSGetCwd(interp);
1960 } else {
1961 /*
1962 * We don't ask for the type of 'pathPtr' here, because that is
1963 * not correct for our purposes when we have a path like '~'. Tcl
1964 * has a bit of a contradiction in that '~' paths are defined as
1965 * 'absolute', but in reality can be just about anything,
1966 * depending on how env(HOME) is set.
1967 */
1968
1969 Tcl_PathType type = Tcl_FSGetPathType(absolutePath);
1970
1971 if (type == TCL_PATH_RELATIVE) {
1972 useThisCwd = Tcl_FSGetCwd(interp);
1973
1974 if (useThisCwd == NULL) {
1975 return NULL;
1976 }
1977
1978 pureNormalized = 0;
1979 Tcl_DecrRefCount(absolutePath);
1980 absolutePath = Tcl_FSJoinToPath(useThisCwd, 1, &absolutePath);
1981 Tcl_IncrRefCount(absolutePath);
1982
1983 /*
1984 * We have a refCount on the cwd.
1985 */
1986 #ifdef _WIN32
1987 } else if (type == TCL_PATH_VOLUME_RELATIVE) {
1988 /*
1989 * Only Windows has volume-relative paths.
1990 */
1991
1992 Tcl_DecrRefCount(absolutePath);
1993 absolutePath = TclWinVolumeRelativeNormalize(interp,
1994 path, &useThisCwd);
1995 if (absolutePath == NULL) {
1996 return NULL;
1997 }
1998 pureNormalized = 0;
1999 #endif /* _WIN32 */
2000 }
2001 }
2002
2003 /*
2004 * Already has refCount incremented.
2005 */
2006
2007 fsPathPtr->normPathPtr = TclFSNormalizeAbsolutePath(interp,
2008 absolutePath);
2009
2010 /*
2011 * Check if path is pure normalized (this can only be the case if it
2012 * is an absolute path).
2013 */
2014
2015 if (pureNormalized) {
2016 int normPathLen, pathLen;
2017 const char *normPath;
2018
2019 path = TclGetStringFromObj(pathPtr, &pathLen);
2020 normPath = TclGetStringFromObj(fsPathPtr->normPathPtr, &normPathLen);
2021 if ((pathLen == normPathLen) && !memcmp(path, normPath, pathLen)) {
2022 /*
2023 * The path was already normalized. Get rid of the duplicate.
2024 */
2025
2026 TclDecrRefCount(fsPathPtr->normPathPtr);
2027
2028 /*
2029 * We do *not* increment the refCount for this circular
2030 * reference.
2031 */
2032
2033 fsPathPtr->normPathPtr = pathPtr;
2034 }
2035 }
2036 if (useThisCwd != NULL) {
2037 /*
2038 * We just need to free an object we allocated above for relative
2039 * paths (this was returned by Tcl_FSJoinToPath above), and then
2040 * of course store the cwd.
2041 */
2042
2043 fsPathPtr->cwdPtr = useThisCwd;
2044 }
2045 TclDecrRefCount(absolutePath);
2046 }
2047
2048 return fsPathPtr->normPathPtr;
2049 }
2050
2051 /*
2052 *---------------------------------------------------------------------------
2053 *
2054 * Tcl_FSGetInternalRep --
2055 *
2056 * Extract the internal representation of a given path object, in the
2057 * given filesystem. If the path object belongs to a different
2058 * filesystem, we return NULL.
2059 *
2060 * If the internal representation is currently NULL, we attempt to
2061 * generate it, by calling the filesystem's
2062 * 'Tcl_FSCreateInternalRepProc'.
2063 *
2064 * Results:
2065 * NULL or a valid internal representation.
2066 *
2067 * Side effects:
2068 * An attempt may be made to convert the object.
2069 *
2070 *---------------------------------------------------------------------------
2071 */
2072
2073 ClientData
2074 Tcl_FSGetInternalRep(
2075 Tcl_Obj *pathPtr,
2076 const Tcl_Filesystem *fsPtr)
2077 {
2078 FsPath *srcFsPathPtr;
2079
2080 if (Tcl_FSConvertToPathType(NULL, pathPtr) != TCL_OK) {
2081 return NULL;
2082 }
2083 srcFsPathPtr = PATHOBJ(pathPtr);
2084
2085 /*
2086 * We will only return the native representation for the caller's
2087 * filesystem. Otherwise we will simply return NULL. This means that there
2088 * must be a unique bi-directional mapping between paths and filesystems,
2089 * and that this mapping will not allow 'remapped' files -- files which
2090 * are in one filesystem but mapped into another. Another way of putting
2091 * this is that 'stacked' filesystems are not allowed. We recognise that
2092 * this is a potentially useful feature for the future.
2093 *
2094 * Even something simple like a 'pass through' filesystem which logs all
2095 * activity and passes the calls onto the native system would be nice, but
2096 * not easily achievable with the current implementation.
2097 */
2098
2099 if (srcFsPathPtr->fsPtr == NULL) {
2100 /*
2101 * This only usually happens in wrappers like TclpStat which create a
2102 * string object and pass it to TclpObjStat. Code which calls the
2103 * Tcl_FS.. functions should always have a filesystem already set.
2104 * Whether this code path is legal or not depends on whether we decide
2105 * to allow external code to call the native filesystem directly. It
2106 * is at least safer to allow this sub-optimal routing.
2107 */
2108
2109 Tcl_FSGetFileSystemForPath(pathPtr);
2110
2111 /*
2112 * If we fail through here, then the path is probably not a valid path
2113 * in the filesystsem, and is most likely to be a use of the empty
2114 * path "" via a direct call to one of the objectified interfaces
2115 * (e.g. from the Tcl testsuite).
2116 */
2117
2118 srcFsPathPtr = PATHOBJ(pathPtr);
2119 if (srcFsPathPtr->fsPtr == NULL) {
2120 return NULL;
2121 }
2122 }
2123
2124 /*
2125 * There is still one possibility we should consider; if the file belongs
2126 * to a different filesystem, perhaps it is actually linked through to a
2127 * file in our own filesystem which we do care about. The way we can check
2128 * for this is we ask what filesystem this path belongs to.
2129 */
2130
2131 if (fsPtr != srcFsPathPtr->fsPtr) {
2132 const Tcl_Filesystem *actualFs = Tcl_FSGetFileSystemForPath(pathPtr);
2133
2134 if (actualFs == fsPtr) {
2135 return Tcl_FSGetInternalRep(pathPtr, fsPtr);
2136 }
2137 return NULL;
2138 }
2139
2140 if (srcFsPathPtr->nativePathPtr == NULL) {
2141 Tcl_FSCreateInternalRepProc *proc;
2142 char *nativePathPtr;
2143
2144 proc = srcFsPathPtr->fsPtr->createInternalRepProc;
2145 if (proc == NULL) {
2146 return NULL;
2147 }
2148
2149 nativePathPtr = proc(pathPtr);
2150 srcFsPathPtr = PATHOBJ(pathPtr);
2151 srcFsPathPtr->nativePathPtr = nativePathPtr;
2152 srcFsPathPtr->filesystemEpoch = TclFSEpoch();
2153 }
2154
2155 return srcFsPathPtr->nativePathPtr;
2156 }
2157
2158 /*
2159 *---------------------------------------------------------------------------
2160 *
2161 * TclFSEnsureEpochOk --
2162 *
2163 * This will ensure the pathPtr is up to date and can be converted into a
2164 * "path" type, and that we are able to generate a complete normalized
2165 * path which is used to determine the filesystem match.
2166 *
2167 * Results:
2168 * Standard Tcl return code.
2169 *
2170 * Side effects:
2171 * An attempt may be made to convert the object.
2172 *
2173 *---------------------------------------------------------------------------
2174 */
2175
2176 int
2177 TclFSEnsureEpochOk(
2178 Tcl_Obj *pathPtr,
2179 const Tcl_Filesystem **fsPtrPtr)
2180 {
2181 FsPath *srcFsPathPtr;
2182
2183 if (pathPtr->typePtr != &tclFsPathType) {
2184 return TCL_OK;
2185 }
2186
2187 srcFsPathPtr = PATHOBJ(pathPtr);
2188
2189 /*
2190 * Check if the filesystem has changed in some way since this object's
2191 * internal representation was calculated.
2192 */
2193
2194 if (!TclFSEpochOk(srcFsPathPtr->filesystemEpoch)) {
2195 /*
2196 * We have to discard the stale representation and recalculate it.
2197 */
2198
2199 if (pathPtr->bytes == NULL) {
2200 UpdateStringOfFsPath(pathPtr);
2201 }
2202 FreeFsPathInternalRep(pathPtr);
2203 if (SetFsPathFromAny(NULL, pathPtr) != TCL_OK) {
2204 return TCL_ERROR;
2205 }
2206 srcFsPathPtr = PATHOBJ(pathPtr);
2207 }
2208
2209 /*
2210 * Check whether the object is already assigned to a fs.
2211 */
2212
2213 if (srcFsPathPtr->fsPtr != NULL) {
2214 *fsPtrPtr = srcFsPathPtr->fsPtr;
2215 }
2216 return TCL_OK;
2217 }
2218
2219 /*
2220 *---------------------------------------------------------------------------
2221 *
2222 * TclFSSetPathDetails --
2223 *
2224 * ???
2225 *
2226 * Results:
2227 * None
2228 *
2229 * Side effects:
2230 * ???
2231 *
2232 *---------------------------------------------------------------------------
2233 */
2234
2235 void
2236 TclFSSetPathDetails(
2237 Tcl_Obj *pathPtr,
2238 const Tcl_Filesystem *fsPtr,
2239 ClientData clientData)
2240 {
2241 FsPath *srcFsPathPtr;
2242
2243 /*
2244 * Make sure pathPtr is of the correct type.
2245 */
2246
2247 if (pathPtr->typePtr != &tclFsPathType) {
2248 if (SetFsPathFromAny(NULL, pathPtr) != TCL_OK) {
2249 return;
2250 }
2251 }
2252
2253 srcFsPathPtr = PATHOBJ(pathPtr);
2254 srcFsPathPtr->fsPtr = fsPtr;
2255 srcFsPathPtr->nativePathPtr = clientData;
2256 srcFsPathPtr->filesystemEpoch = TclFSEpoch();
2257 }
2258
2259 /*
2260 *---------------------------------------------------------------------------
2261 *
2262 * Tcl_FSEqualPaths --
2263 *
2264 * This function tests whether the two paths given are equal path
2265 * objects. If either or both is NULL, 0 is always returned.
2266 *
2267 * Results:
2268 * 1 or 0.
2269 *
2270 * Side effects:
2271 * None.
2272 *
2273 *---------------------------------------------------------------------------
2274 */
2275
2276 int
2277 Tcl_FSEqualPaths(
2278 Tcl_Obj *firstPtr,
2279 Tcl_Obj *secondPtr)
2280 {
2281 const char *firstStr, *secondStr;
2282 int firstLen, secondLen, tempErrno;
2283
2284 if (firstPtr == secondPtr) {
2285 return 1;
2286 }
2287
2288 if (firstPtr == NULL || secondPtr == NULL) {
2289 return 0;
2290 }
2291 firstStr = TclGetStringFromObj(firstPtr, &firstLen);
2292 secondStr = TclGetStringFromObj(secondPtr, &secondLen);
2293 if ((firstLen == secondLen) && !memcmp(firstStr, secondStr, firstLen)) {
2294 return 1;
2295 }
2296
2297 /*
2298 * Try the most thorough, correct method of comparing fully normalized
2299 * paths.
2300 */
2301
2302 tempErrno = Tcl_GetErrno();
2303 firstPtr = Tcl_FSGetNormalizedPath(NULL, firstPtr);
2304 secondPtr = Tcl_FSGetNormalizedPath(NULL, secondPtr);
2305 Tcl_SetErrno(tempErrno);
2306
2307 if (firstPtr == NULL || secondPtr == NULL) {
2308 return 0;
2309 }
2310
2311 firstStr = TclGetStringFromObj(firstPtr, &firstLen);
2312 secondStr = TclGetStringFromObj(secondPtr, &secondLen);
2313 return ((firstLen == secondLen) && !memcmp(firstStr, secondStr, firstLen));
2314 }
2315
2316 /*
2317 *---------------------------------------------------------------------------
2318 *
2319 * SetFsPathFromAny --
2320 *
2321 * This function tries to convert the given Tcl_Obj to a valid Tcl path
2322 * type.
2323 *
2324 * The filename may begin with "~" (to indicate current user's home
2325 * directory) or "~<user>" (to indicate any user's home directory).
2326 *
2327 * Results:
2328 * Standard Tcl error code.
2329 *
2330 * Side effects:
2331 * The old representation may be freed, and new memory allocated.
2332 *
2333 *---------------------------------------------------------------------------
2334 */
2335
2336 static int
2337 SetFsPathFromAny(
2338 Tcl_Interp *interp, /* Used for error reporting if not NULL. */
2339 Tcl_Obj *pathPtr) /* The object to convert. */
2340 {
2341 int len;
2342 FsPath *fsPathPtr;
2343 Tcl_Obj *transPtr;
2344 char *name;
2345
2346 if (pathPtr->typePtr == &tclFsPathType) {
2347 return TCL_OK;
2348 }
2349
2350 /*
2351 * First step is to translate the filename. This is similar to
2352 * Tcl_TranslateFilename, but shouldn't convert everything to windows
2353 * backslashes on that platform. The current implementation of this piece
2354 * is a slightly optimised version of the various Tilde/Split/Join stuff
2355 * to avoid multiple split/join operations.
2356 *
2357 * We remove any trailing directory separator.
2358 *
2359 * However, the split/join routines are quite complex, and one has to make
2360 * sure not to break anything on Unix or Win (fCmd.test, fileName.test and
2361 * cmdAH.test exercise most of the code).
2362 */
2363
2364 name = Tcl_GetStringFromObj(pathPtr, &len);
2365
2366 /*
2367 * Handle tilde substitutions, if needed.
2368 */
2369
2370 if (len && name[0] == '~') {
2371 Tcl_DString temp;
2372 int split;
2373 char separator = '/';
2374
2375 /*
2376 * We have multiple cases '~/foo/bar...', '~user/foo/bar...', etc.
2377 * split becomes value 1 for '~/...' as well as for '~'.
2378 */
2379 split = FindSplitPos(name, separator);
2380
2381 /*
2382 * Do some tilde substitution.
2383 */
2384
2385 if (split == 1) {
2386 /*
2387 * We have just '~' (or '~/...')
2388 */
2389
2390 const char *dir;
2391 Tcl_DString dirString;
2392
2393 dir = TclGetEnv("HOME", &dirString);
2394 if (dir == NULL) {
2395 if (interp) {
2396 Tcl_SetObjResult(interp, Tcl_NewStringObj(
2397 "couldn't find HOME environment variable to"
2398 " expand path", -1));
2399 Tcl_SetErrorCode(interp, "TCL", "VALUE", "PATH",
2400 "HOMELESS", (char *)NULL);
2401 }
2402 return TCL_ERROR;
2403 }
2404 Tcl_DStringInit(&temp);
2405 Tcl_JoinPath(1, &dir, &temp);
2406 Tcl_DStringFree(&dirString);
2407 } else {
2408 /*
2409 * We have a user name '~user'
2410 */
2411
2412 const char *expandedUser;
2413 Tcl_DString userName;
2414
2415 Tcl_DStringInit(&userName);
2416 Tcl_DStringAppend(&userName, name+1, split-1);
2417 expandedUser = Tcl_DStringValue(&userName);
2418
2419 Tcl_DStringInit(&temp);
2420 if (TclpGetUserHome(expandedUser, &temp) == NULL) {
2421 if (interp != NULL) {
2422 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2423 "user \"%s\" doesn't exist", expandedUser));
2424 Tcl_SetErrorCode(interp, "TCL", "VALUE", "PATH", "NOUSER",
2425 (char *)NULL);
2426 }
2427 Tcl_DStringFree(&userName);
2428 Tcl_DStringFree(&temp);
2429 return TCL_ERROR;
2430 }
2431 Tcl_DStringFree(&userName);
2432 }
2433
2434 transPtr = TclDStringToObj(&temp);
2435
2436 if (split != len) {
2437 /*
2438 * Join up the tilde substitution with the rest.
2439 */
2440
2441 if (name[split+1] == separator) {
2442 /*
2443 * Somewhat tricky case like ~//foo/bar. Make use of
2444 * Split/Join machinery to get it right. Assumes all paths
2445 * beginning with ~ are part of the native filesystem.
2446 */
2447
2448 int objc;
2449 Tcl_Obj **objv;
2450 Tcl_Obj *parts = TclpNativeSplitPath(pathPtr, NULL);
2451
2452 TclListObjGetElements(NULL, parts, &objc, &objv);
2453
2454 /*
2455 * Skip '~'. It's replaced by its expansion.
2456 */
2457
2458 objc--; objv++;
2459 while (objc--) {
2460 TclpNativeJoinPath(transPtr, Tcl_GetString(*objv++));
2461 }
2462 TclDecrRefCount(parts);
2463 } else {
2464 Tcl_Obj *pair[2];
2465
2466 pair[0] = transPtr;
2467 pair[1] = Tcl_NewStringObj(name+split+1, -1);
2468 transPtr = TclJoinPath(2, pair, 1);
2469 if (transPtr != pair[0]) {
2470 Tcl_DecrRefCount(pair[0]);
2471 }
2472 if (transPtr != pair[1]) {
2473 Tcl_DecrRefCount(pair[1]);
2474 }
2475 }
2476 }
2477 } else {
2478 transPtr = TclJoinPath(1, &pathPtr, 1);
2479 }
2480
2481 /*
2482 * Now we have a translated filename in 'transPtr'. This will have forward
2483 * slashes on Windows, and will not contain any ~user sequences.
2484 */
2485
2486 fsPathPtr = ckalloc(sizeof(FsPath));
2487
2488 fsPathPtr->translatedPathPtr = transPtr;
2489 if (transPtr != pathPtr) {
2490 Tcl_IncrRefCount(fsPathPtr->translatedPathPtr);
2491 /* Redo translation when $env(HOME) changes */
2492 fsPathPtr->filesystemEpoch = TclFSEpoch();
2493 } else {
2494 fsPathPtr->filesystemEpoch = 0;
2495 }
2496 fsPathPtr->normPathPtr = NULL;
2497 fsPathPtr->cwdPtr = NULL;
2498 fsPathPtr->nativePathPtr = NULL;
2499 fsPathPtr->fsPtr = NULL;
2500
2501 /*
2502 * Free old representation before installing our new one.
2503 */
2504
2505 TclFreeIntRep(pathPtr);
2506 SETPATHOBJ(pathPtr, fsPathPtr);
2507 PATHFLAGS(pathPtr) = 0;
2508 pathPtr->typePtr = &tclFsPathType;
2509 return TCL_OK;
2510 }
2511
2512 static void
2513 FreeFsPathInternalRep(
2514 Tcl_Obj *pathPtr) /* Path object with internal rep to free. */
2515 {
2516 FsPath *fsPathPtr = PATHOBJ(pathPtr);
2517
2518 if (fsPathPtr->translatedPathPtr != NULL) {
2519 if (fsPathPtr->translatedPathPtr != pathPtr) {
2520 TclDecrRefCount(fsPathPtr->translatedPathPtr);
2521 }
2522 }
2523 if (fsPathPtr->normPathPtr != NULL) {
2524 if (fsPathPtr->normPathPtr != pathPtr) {
2525 TclDecrRefCount(fsPathPtr->normPathPtr);
2526 }
2527 fsPathPtr->normPathPtr = NULL;
2528 }
2529 if (fsPathPtr->cwdPtr != NULL) {
2530 TclDecrRefCount(fsPathPtr->cwdPtr);
2531 }
2532 if (fsPathPtr->nativePathPtr != NULL && fsPathPtr->fsPtr != NULL) {
2533 Tcl_FSFreeInternalRepProc *freeProc =
2534 fsPathPtr->fsPtr->freeInternalRepProc;
2535
2536 if (freeProc != NULL) {
2537 freeProc(fsPathPtr->nativePathPtr);
2538 fsPathPtr->nativePathPtr = NULL;
2539 }
2540 }
2541
2542 ckfree(fsPathPtr);
2543 pathPtr->typePtr = NULL;
2544 }
2545
2546 static void
2547 DupFsPathInternalRep(
2548 Tcl_Obj *srcPtr, /* Path obj with internal rep to copy. */
2549 Tcl_Obj *copyPtr) /* Path obj with internal rep to set. */
2550 {
2551 FsPath *srcFsPathPtr = PATHOBJ(srcPtr);
2552 FsPath *copyFsPathPtr = ckalloc(sizeof(FsPath));
2553
2554 SETPATHOBJ(copyPtr, copyFsPathPtr);
2555
2556 if (srcFsPathPtr->translatedPathPtr == srcPtr) {
2557 /* Cycle in src -> make cycle in copy. */
2558 copyFsPathPtr->translatedPathPtr = copyPtr;
2559 } else {
2560 copyFsPathPtr->translatedPathPtr = srcFsPathPtr->translatedPathPtr;
2561 if (copyFsPathPtr->translatedPathPtr != NULL) {
2562 Tcl_IncrRefCount(copyFsPathPtr->translatedPathPtr);
2563 }
2564 }
2565
2566 if (srcFsPathPtr->normPathPtr == srcPtr) {
2567 /* Cycle in src -> make cycle in copy. */
2568 copyFsPathPtr->normPathPtr = copyPtr;
2569 } else {
2570 copyFsPathPtr->normPathPtr = srcFsPathPtr->normPathPtr;
2571 if (copyFsPathPtr->normPathPtr != NULL) {
2572 Tcl_IncrRefCount(copyFsPathPtr->normPathPtr);
2573 }
2574 }
2575
2576 copyFsPathPtr->cwdPtr = srcFsPathPtr->cwdPtr;
2577 if (copyFsPathPtr->cwdPtr != NULL) {
2578 Tcl_IncrRefCount(copyFsPathPtr->cwdPtr);
2579 }
2580
2581 copyFsPathPtr->flags = srcFsPathPtr->flags;
2582
2583 if (srcFsPathPtr->fsPtr != NULL
2584 && srcFsPathPtr->nativePathPtr != NULL) {
2585 Tcl_FSDupInternalRepProc *dupProc =
2586 srcFsPathPtr->fsPtr->dupInternalRepProc;
2587
2588 if (dupProc != NULL) {
2589 copyFsPathPtr->nativePathPtr =
2590 dupProc(srcFsPathPtr->nativePathPtr);
2591 } else {
2592 copyFsPathPtr->nativePathPtr = NULL;
2593 }
2594 } else {
2595 copyFsPathPtr->nativePathPtr = NULL;
2596 }
2597 copyFsPathPtr->fsPtr = srcFsPathPtr->fsPtr;
2598 copyFsPathPtr->filesystemEpoch = srcFsPathPtr->filesystemEpoch;
2599
2600 copyPtr->typePtr = &tclFsPathType;
2601 }
2602
2603 /*
2604 *---------------------------------------------------------------------------
2605 *
2606 * UpdateStringOfFsPath --
2607 *
2608 * Gives an object a valid string rep.
2609 *
2610 * Results:
2611 * None.
2612 *
2613 * Side effects:
2614 * Memory may be allocated.
2615 *
2616 *---------------------------------------------------------------------------
2617 */
2618
2619 static void
2620 UpdateStringOfFsPath(
2621 Tcl_Obj *pathPtr) /* path obj with string rep to update. */
2622 {
2623 FsPath *fsPathPtr = PATHOBJ(pathPtr);
2624 int cwdLen;
2625 Tcl_Obj *copy;
2626
2627 if (PATHFLAGS(pathPtr) == 0 || fsPathPtr->cwdPtr == NULL) {
2628 Tcl_Panic("Called UpdateStringOfFsPath with invalid object");
2629 }
2630
2631 copy = AppendPath(fsPathPtr->cwdPtr, fsPathPtr->normPathPtr);
2632
2633 pathPtr->bytes = Tcl_GetStringFromObj(copy, &cwdLen);
2634 pathPtr->length = cwdLen;
2635 copy->bytes = tclEmptyStringRep;
2636 copy->length = 0;
2637 TclDecrRefCount(copy);
2638 }
2639
2640 /*
2641 *---------------------------------------------------------------------------
2642 *
2643 * TclNativePathInFilesystem --
2644 *
2645 * Any path object is acceptable to the native filesystem, by default (we
2646 * will throw errors when illegal paths are actually tried to be used).
2647 *
2648 * However, this behavior means the native filesystem must be the last
2649 * filesystem in the lookup list (otherwise it will claim all files
2650 * belong to it, and other filesystems will never get a look in).
2651 *
2652 * Results:
2653 * TCL_OK, to indicate 'yes', -1 to indicate no.
2654 *
2655 * Side effects:
2656 * None.
2657 *
2658 *---------------------------------------------------------------------------
2659 */
2660
2661 int
2662 TclNativePathInFilesystem(
2663 Tcl_Obj *pathPtr,
2664 ClientData *clientDataPtr)
2665 {
2666 /*
2667 * A special case is required to handle the empty path "". This is a valid
2668 * path (i.e. the user should be able to do 'file exists ""' without
2669 * throwing an error), but equally the path doesn't exist. Those are the
2670 * semantics of Tcl (at present anyway), so we have to abide by them here.
2671 */
2672
2673 if (pathPtr->typePtr == &tclFsPathType) {
2674 if (pathPtr->bytes != NULL && pathPtr->bytes[0] == '\0') {
2675 /*
2676 * We reject the empty path "".
2677 */
2678
2679 return -1;
2680 }
2681
2682 /*
2683 * Otherwise there is no way this path can be empty.
2684 */
2685 } else {
2686 /*
2687 * It is somewhat unusual to reach this code path without the object
2688 * being of tclFsPathType. However, we do our best to deal with the
2689 * situation.
2690 */
2691
2692 int len;
2693
2694 (void) Tcl_GetStringFromObj(pathPtr, &len);
2695 if (len == 0) {
2696 /*
2697 * We reject the empty path "".
2698 */
2699
2700 return -1;
2701 }
2702 }
2703
2704 /*
2705 * Path is of correct type, or is of non-zero length, so we accept it.
2706 */
2707
2708 return TCL_OK;
2709 }
2710
2711 /*
2712 * Local Variables:
2713 * mode: c
2714 * c-basic-offset: 4
2715 * fill-column: 78
2716 * End:
2717 */