Debian Codegraph @

pTk/mTk/tclGeneric/tclFileName.c

raw symbols SCIP
1 /*
2 * tclFileName.c --
3 *
4 * This file contains routines for converting file names betwen
5 * native and network form.
6 *
7 * Copyright (c) 1995-1998 Sun Microsystems, Inc.
8 * Copyright (c) 1998-1999 by Scriptics Corporation.
9 *
10 * See the file "license.terms" for information on usage and redistribution
11 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
12 *
13 * RCS: @(#) $Id: tclFileName.c,v 1.40.2.5 2003/10/06 09:49:19 vincentdarley Exp $
14 */
15
16 #include "tclInt.h"
17 #include "tclPort.h"
18 #include "tclRegexp.h"
19
20 /*
21 * This define is used to activate Tcl's interpretation of Unix-style
22 * paths (containing forward slashes, '.' and '..') on MacOS. A
23 * side-effect of this is that some paths become ambiguous.
24 */
25 #define MAC_UNDERSTANDS_UNIX_PATHS
26
27 #ifdef MAC_UNDERSTANDS_UNIX_PATHS
28 /*
29 * The following regular expression matches the root portion of a Macintosh
30 * absolute path. It will match degenerate Unix-style paths, tilde paths,
31 * Unix-style paths, and Mac paths. The various subexpressions in this
32 * can be summarised as follows: ^(/..|~user/unix|~user:mac|/unix|mac:dir).
33 * The subexpression indices which match the root portions, are as follows:
34 *
35 * degenerate unix-style: 2
36 * unix-tilde: 5
37 * mac-tilde: 7
38 * unix-style: 9 (or 10 to cut off the irrelevant header).
39 * mac: 12
40 *
41 */
42
43 #define MAC_ROOT_PATTERN "^((/+([.][.]?/+)*([.][.]?)?)|(~[^:/]*)(/[^:]*)?|(~[^:]*)(:.*)?|/+([.][.]?/+)*([^:/]+)(/[^:]*)?|([^:]+):.*)$"
44
45 /*
46 * The following variables are used to hold precompiled regular expressions
47 * for use in filename matching.
48 */
49
50 typedef struct ThreadSpecificData {
51 int initialized;
52 Tcl_Obj *macRootPatternPtr;
53 } ThreadSpecificData;
54
55 static Tcl_ThreadDataKey dataKey;
56
57 static void FileNameCleanup _ANSI_ARGS_((ClientData clientData));
58 static void FileNameInit _ANSI_ARGS_((void));
59
60 #endif
61
62 /*
63 * The following variable is set in the TclPlatformInit call to one
64 * of: TCL_PLATFORM_UNIX, TCL_PLATFORM_MAC, or TCL_PLATFORM_WINDOWS.
65 */
66
67 TclPlatformType tclPlatform = TCL_PLATFORM_UNIX;
68
69 /*
70 * Prototypes for local procedures defined in this file:
71 */
72
73 static CONST char * DoTildeSubst _ANSI_ARGS_((Tcl_Interp *interp,
74 CONST char *user, Tcl_DString *resultPtr));
75 static CONST char * ExtractWinRoot _ANSI_ARGS_((CONST char *path,
76 Tcl_DString *resultPtr, int offset,
77 Tcl_PathType *typePtr));
78 static int SkipToChar _ANSI_ARGS_((char **stringPtr,
79 char *match));
80 static Tcl_Obj* SplitMacPath _ANSI_ARGS_((CONST char *path));
81 static Tcl_Obj* SplitWinPath _ANSI_ARGS_((CONST char *path));
82 static Tcl_Obj* SplitUnixPath _ANSI_ARGS_((CONST char *path));
83 #ifdef MAC_UNDERSTANDS_UNIX_PATHS
84
85 /*
86 *----------------------------------------------------------------------
87 *
88 * FileNameInit --
89 *
90 * This procedure initializes the patterns used by this module.
91 *
92 * Results:
93 * None.
94 *
95 * Side effects:
96 * Compiles the regular expressions.
97 *
98 *----------------------------------------------------------------------
99 */
100
101 static void
102 FileNameInit()
103 {
104 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
105 if (!tsdPtr->initialized) {
106 tsdPtr->initialized = 1;
107 tsdPtr->macRootPatternPtr = Tcl_NewStringObj(MAC_ROOT_PATTERN, -1);
108 Tcl_CreateThreadExitHandler(FileNameCleanup, NULL);
109 }
110 }
111
112 /*
113 *----------------------------------------------------------------------
114 *
115 * FileNameCleanup --
116 *
117 * This procedure is a Tcl_ExitProc used to clean up the static
118 * data structures used in this file.
119 *
120 * Results:
121 * None.
122 *
123 * Side effects:
124 * Deallocates storage used by the procedures in this file.
125 *
126 *----------------------------------------------------------------------
127 */
128
129 static void
130 FileNameCleanup(clientData)
131 ClientData clientData; /* Not used. */
132 {
133 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
134 Tcl_DecrRefCount(tsdPtr->macRootPatternPtr);
135 tsdPtr->initialized = 0;
136 }
137 #endif
138
139 /*
140 *----------------------------------------------------------------------
141 *
142 * ExtractWinRoot --
143 *
144 * Matches the root portion of a Windows path and appends it
145 * to the specified Tcl_DString.
146 *
147 * Results:
148 * Returns the position in the path immediately after the root
149 * including any trailing slashes.
150 * Appends a cleaned up version of the root to the Tcl_DString
151 * at the specified offest.
152 *
153 * Side effects:
154 * Modifies the specified Tcl_DString.
155 *
156 *----------------------------------------------------------------------
157 */
158
159 static CONST char *
160 ExtractWinRoot(path, resultPtr, offset, typePtr)
161 CONST char *path; /* Path to parse. */
162 Tcl_DString *resultPtr; /* Buffer to hold result. */
163 int offset; /* Offset in buffer where result should be
164 * stored. */
165 Tcl_PathType *typePtr; /* Where to store pathType result */
166 {
167 if (path[0] == '/' || path[0] == '\\') {
168 /* Might be a UNC or Vol-Relative path */
169 CONST char *host, *share, *tail;
170 int hlen, slen;
171 if (path[1] != '/' && path[1] != '\\') {
172 Tcl_DStringSetLength(resultPtr, offset);
173 *typePtr = TCL_PATH_VOLUME_RELATIVE;
174 Tcl_DStringAppend(resultPtr, "/", 1);
175 return &path[1];
176 }
177 host = &path[2];
178
179 /* Skip separators */
180 while (host[0] == '/' || host[0] == '\\') host++;
181
182 for (hlen = 0; host[hlen];hlen++) {
183 if (host[hlen] == '/' || host[hlen] == '\\')
184 break;
185 }
186 if (host[hlen] == 0 || host[hlen+1] == 0) {
187 /*
188 * The path given is simply of the form
189 * '/foo', '//foo', '/////foo' or the same
190 * with backslashes. If there is exactly
191 * one leading '/' the path is volume relative
192 * (see filename man page). If there are more
193 * than one, we are simply assuming they
194 * are superfluous and we trim them away.
195 * (An alternative interpretation would
196 * be that it is a host name, but we have
197 * been documented that that is not the case).
198 */
199 *typePtr = TCL_PATH_VOLUME_RELATIVE;
200 Tcl_DStringAppend(resultPtr, "/", 1);
201 return &path[2];
202 }
203 Tcl_DStringSetLength(resultPtr, offset);
204 share = &host[hlen];
205
206 /* Skip separators */
207 while (share[0] == '/' || share[0] == '\\') share++;
208
209 for (slen = 0; share[slen];slen++) {
210 if (share[slen] == '/' || share[slen] == '\\')
211 break;
212 }
213 Tcl_DStringAppend(resultPtr, "//", 2);
214 Tcl_DStringAppend(resultPtr, host, hlen);
215 Tcl_DStringAppend(resultPtr, "/", 1);
216 Tcl_DStringAppend(resultPtr, share, slen);
217
218 tail = &share[slen];
219
220 /* Skip separators */
221 while (tail[0] == '/' || tail[0] == '\\') tail++;
222
223 *typePtr = TCL_PATH_ABSOLUTE;
224 return tail;
225 } else if (*path && path[1] == ':') {
226 /* Might be a drive sep */
227 Tcl_DStringSetLength(resultPtr, offset);
228
229 if (path[2] != '/' && path[2] != '\\') {
230 *typePtr = TCL_PATH_VOLUME_RELATIVE;
231 Tcl_DStringAppend(resultPtr, path, 2);
232 return &path[2];
233 } else {
234 char *tail = (char*)&path[3];
235
236 /* Skip separators */
237 while (*tail && (tail[0] == '/' || tail[0] == '\\')) tail++;
238
239 *typePtr = TCL_PATH_ABSOLUTE;
240 Tcl_DStringAppend(resultPtr, path, 2);
241 Tcl_DStringAppend(resultPtr, "/", 1);
242
243 return tail;
244 }
245 } else {
246 int abs = 0;
247 if (path[0] == 'c' && path[1] == 'o') {
248 if (path[2] == 'm' && path[3] >= '1' && path[3] <= '9') {
249 /* May have match for 'com[1-9]:?', which is a serial port */
250 if (path[4] == '\0') {
251 abs = 4;
252 } else if (path [4] == ':' && path[5] == '\0') {
253 abs = 5;
254 }
255 } else if (path[2] == 'n' && path[3] == '\0') {
256 /* Have match for 'con' */
257 abs = 3;
258 }
259 } else if (path[0] == 'l' && path[1] == 'p' && path[2] == 't') {
260 if (path[3] >= '1' && path[3] <= '9') {
261 /* May have match for 'lpt[1-9]:?' */
262 if (path[4] == '\0') {
263 abs = 4;
264 } else if (path [4] == ':' && path[5] == '\0') {
265 abs = 5;
266 }
267 }
268 } else if (path[0] == 'p' && path[1] == 'r'
269 && path[2] == 'n' && path[3] == '\0') {
270 /* Have match for 'prn' */
271 abs = 3;
272 } else if (path[0] == 'n' && path[1] == 'u'
273 && path[2] == 'l' && path[3] == '\0') {
274 /* Have match for 'nul' */
275 abs = 3;
276 } else if (path[0] == 'a' && path[1] == 'u'
277 && path[2] == 'x' && path[3] == '\0') {
278 /* Have match for 'aux' */
279 abs = 3;
280 }
281 if (abs != 0) {
282 *typePtr = TCL_PATH_ABSOLUTE;
283 Tcl_DStringSetLength(resultPtr, offset);
284 Tcl_DStringAppend(resultPtr, path, abs);
285 return path + abs;
286 }
287 }
288 /* Anything else is treated as relative */
289 *typePtr = TCL_PATH_RELATIVE;
290 return path;
291 }
292
293 /*
294 *----------------------------------------------------------------------
295 *
296 * Tcl_GetPathType --
297 *
298 * Determines whether a given path is relative to the current
299 * directory, relative to the current volume, or absolute.
300 *
301 * The objectified Tcl_FSGetPathType should be used in
302 * preference to this function (as you can see below, this
303 * is just a wrapper around that other function).
304 *
305 * Results:
306 * Returns one of TCL_PATH_ABSOLUTE, TCL_PATH_RELATIVE, or
307 * TCL_PATH_VOLUME_RELATIVE.
308 *
309 * Side effects:
310 * None.
311 *
312 *----------------------------------------------------------------------
313 */
314
315 Tcl_PathType
316 Tcl_GetPathType(path)
317 CONST char *path;
318 {
319 Tcl_PathType type;
320 Tcl_Obj *tempObj = Tcl_NewStringObj(path,-1);
321 Tcl_IncrRefCount(tempObj);
322 type = Tcl_FSGetPathType(tempObj);
323 Tcl_DecrRefCount(tempObj);
324 return type;
325 }
326
327 /*
328 *----------------------------------------------------------------------
329 *
330 * TclpGetNativePathType --
331 *
332 * Determines whether a given path is relative to the current
333 * directory, relative to the current volume, or absolute, but
334 * ONLY FOR THE NATIVE FILESYSTEM. This function is called from
335 * tclIOUtil.c (but needs to be here due to its dependence on
336 * static variables/functions in this file). The exported
337 * function Tcl_FSGetPathType should be used by extensions.
338 *
339 * Results:
340 * Returns one of TCL_PATH_ABSOLUTE, TCL_PATH_RELATIVE, or
341 * TCL_PATH_VOLUME_RELATIVE.
342 *
343 * Side effects:
344 * None.
345 *
346 *----------------------------------------------------------------------
347 */
348
349 Tcl_PathType
350 TclpGetNativePathType(pathObjPtr, driveNameLengthPtr, driveNameRef)
351 Tcl_Obj *pathObjPtr;
352 int *driveNameLengthPtr;
353 Tcl_Obj **driveNameRef;
354 {
355 Tcl_PathType type = TCL_PATH_ABSOLUTE;
356 int pathLen;
357 char *path = Tcl_GetStringFromObj(pathObjPtr, &pathLen);
358
359 if (path[0] == '~') {
360 /*
361 * This case is common to all platforms.
362 * Paths that begin with ~ are absolute.
363 */
364 if (driveNameLengthPtr != NULL) {
365 char *end = path + 1;
366 while ((*end != '\0') && (*end != '/')) {
367 end++;
368 }
369 *driveNameLengthPtr = end - path;
370 }
371 } else {
372 switch (tclPlatform) {
373 case TCL_PLATFORM_UNIX: {
374 char *origPath = path;
375
376 /*
377 * Paths that begin with / are absolute.
378 */
379
380 #ifdef __QNX__
381 /*
382 * Check for QNX //<node id> prefix
383 */
384 if (*path && (pathLen > 3) && (path[0] == '/')
385 && (path[1] == '/') && isdigit(UCHAR(path[2]))) {
386 path += 3;
387 while (isdigit(UCHAR(*path))) {
388 ++path;
389 }
390 }
391 #endif
392 if (path[0] == '/') {
393 if (driveNameLengthPtr != NULL) {
394 /*
395 * We need this addition in case the QNX code
396 * was used
397 */
398 *driveNameLengthPtr = (1 + path - origPath);
399 }
400 } else {
401 type = TCL_PATH_RELATIVE;
402 }
403 break;
404 }
405 case TCL_PLATFORM_MAC:
406 if (path[0] == ':') {
407 type = TCL_PATH_RELATIVE;
408 } else {
409 #ifdef MAC_UNDERSTANDS_UNIX_PATHS
410 ThreadSpecificData *tsdPtr;
411 Tcl_RegExp re;
412
413 tsdPtr = TCL_TSD_INIT(&dataKey);
414
415 /*
416 * Since we have eliminated the easy cases, use the
417 * root pattern to look for the other types.
418 */
419
420 FileNameInit();
421 re = Tcl_GetRegExpFromObj(NULL, tsdPtr->macRootPatternPtr,
422 REG_ADVANCED);
423
424 if (!Tcl_RegExpExec(NULL, re, path, path)) {
425 type = TCL_PATH_RELATIVE;
426 } else {
427 CONST char *root, *end;
428 Tcl_RegExpRange(re, 2, &root, &end);
429 if (root != NULL) {
430 type = TCL_PATH_RELATIVE;
431 } else {
432 if (driveNameLengthPtr != NULL) {
433 Tcl_RegExpRange(re, 0, &root, &end);
434 *driveNameLengthPtr = end - root;
435 }
436 if (driveNameRef != NULL) {
437 if (*root == '/') {
438 char *c;
439 int gotColon = 0;
440 *driveNameRef = Tcl_NewStringObj(root + 1,
441 end - root -1);
442 c = Tcl_GetString(*driveNameRef);
443 while (*c != '\0') {
444 if (*c == '/') {
445 gotColon++;
446 *c = ':';
447 }
448 c++;
449 }
450 /*
451 * If there is no colon, we have just a
452 * volume name so we must add a colon so
453 * it is an absolute path.
454 */
455 if (gotColon == 0) {
456 Tcl_AppendToObj(*driveNameRef, ":", 1);
457 } else if ((gotColon > 1) &&
458 (*(c-1) == ':')) {
459 /* We have an extra colon */
460 Tcl_SetObjLength(*driveNameRef,
461 c - Tcl_GetString(*driveNameRef) - 1);
462 }
463 }
464 }
465 }
466 }
467 #else
468 if (path[0] == '~') {
469 } else if (path[0] == ':') {
470 type = TCL_PATH_RELATIVE;
471 } else {
472 char *colonPos = strchr(path,':');
473 if (colonPos == NULL) {
474 type = TCL_PATH_RELATIVE;
475 } else {
476 }
477 }
478 if (type == TCL_PATH_ABSOLUTE) {
479 if (driveNameLengthPtr != NULL) {
480 *driveNameLengthPtr = strlen(path);
481 }
482 }
483 #endif
484 }
485 break;
486
487 case TCL_PLATFORM_WINDOWS: {
488 Tcl_DString ds;
489 CONST char *rootEnd;
490
491 Tcl_DStringInit(&ds);
492 rootEnd = ExtractWinRoot(path, &ds, 0, &type);
493 if ((rootEnd != path) && (driveNameLengthPtr != NULL)) {
494 *driveNameLengthPtr = rootEnd - path;
495 if (driveNameRef != NULL) {
496 *driveNameRef = Tcl_NewStringObj(Tcl_DStringValue(&ds),
497 Tcl_DStringLength(&ds));
498 Tcl_IncrRefCount(*driveNameRef);
499 }
500 }
501 Tcl_DStringFree(&ds);
502 break;
503 }
504 }
505 }
506 return type;
507 }
508
509 /*
510 *---------------------------------------------------------------------------
511 *
512 * TclpNativeSplitPath --
513 *
514 * This function takes the given Tcl_Obj, which should be a valid
515 * path, and returns a Tcl List object containing each segment
516 * of that path as an element.
517 *
518 * Note this function currently calls the older Split(Plat)Path
519 * functions, which require more memory allocation than is
520 * desirable.
521 *
522 * Results:
523 * Returns list object with refCount of zero. If the passed in
524 * lenPtr is non-NULL, we use it to return the number of elements
525 * in the returned list.
526 *
527 * Side effects:
528 * None.
529 *
530 *---------------------------------------------------------------------------
531 */
532
533 Tcl_Obj*
534 TclpNativeSplitPath(pathPtr, lenPtr)
535 Tcl_Obj *pathPtr; /* Path to split. */
536 int *lenPtr; /* int to store number of path elements. */
537 {
538 Tcl_Obj *resultPtr = NULL; /* Needed only to prevent gcc warnings. */
539
540 /*
541 * Perform platform specific splitting.
542 */
543
544 switch (tclPlatform) {
545 case TCL_PLATFORM_UNIX:
546 resultPtr = SplitUnixPath(Tcl_GetString(pathPtr));
547 break;
548
549 case TCL_PLATFORM_WINDOWS:
550 resultPtr = SplitWinPath(Tcl_GetString(pathPtr));
551 break;
552
553 case TCL_PLATFORM_MAC:
554 resultPtr = SplitMacPath(Tcl_GetString(pathPtr));
555 break;
556 }
557
558 /*
559 * Compute the number of elements in the result.
560 */
561
562 if (lenPtr != NULL) {
563 Tcl_ListObjLength(NULL, resultPtr, lenPtr);
564 }
565 return resultPtr;
566 }
567
568 /*
569 *----------------------------------------------------------------------
570 *
571 * Tcl_SplitPath --
572 *
573 * Split a path into a list of path components. The first element
574 * of the list will have the same path type as the original path.
575 *
576 * Results:
577 * Returns a standard Tcl result. The interpreter result contains
578 * a list of path components.
579 * *argvPtr will be filled in with the address of an array
580 * whose elements point to the elements of path, in order.
581 * *argcPtr will get filled in with the number of valid elements
582 * in the array. A single block of memory is dynamically allocated
583 * to hold both the argv array and a copy of the path elements.
584 * The caller must eventually free this memory by calling ckfree()
585 * on *argvPtr. Note: *argvPtr and *argcPtr are only modified
586 * if the procedure returns normally.
587 *
588 * Side effects:
589 * Allocates memory.
590 *
591 *----------------------------------------------------------------------
592 */
593
594 void
595 Tcl_SplitPath(path, argcPtr, argvPtr)
596 CONST char *path; /* Pointer to string containing a path. */
597 int *argcPtr; /* Pointer to location to fill in with
598 * the number of elements in the path. */
599 CONST char ***argvPtr; /* Pointer to place to store pointer to array
600 * of pointers to path elements. */
601 {
602 Tcl_Obj *resultPtr = NULL; /* Needed only to prevent gcc warnings. */
603 Tcl_Obj *tmpPtr, *eltPtr;
604 int i, size, len;
605 char *p, *str;
606
607 /*
608 * Perform the splitting, using objectified, vfs-aware code.
609 */
610
611 tmpPtr = Tcl_NewStringObj(path, -1);
612 Tcl_IncrRefCount(tmpPtr);
613 resultPtr = Tcl_FSSplitPath(tmpPtr, argcPtr);
614 Tcl_DecrRefCount(tmpPtr);
615
616 /* Calculate space required for the result */
617
618 size = 1;
619 for (i = 0; i < *argcPtr; i++) {
620 Tcl_ListObjIndex(NULL, resultPtr, i, &eltPtr);
621 Tcl_GetStringFromObj(eltPtr, &len);
622 size += len + 1;
623 }
624
625 /*
626 * Allocate a buffer large enough to hold the contents of all of
627 * the list plus the argv pointers and the terminating NULL pointer.
628 */
629
630 *argvPtr = (CONST char **) ckalloc((unsigned)
631 ((((*argcPtr) + 1) * sizeof(char *)) + size));
632
633 /*
634 * Position p after the last argv pointer and copy the contents of
635 * the list in, piece by piece.
636 */
637
638 p = (char *) &(*argvPtr)[(*argcPtr) + 1];
639 for (i = 0; i < *argcPtr; i++) {
640 Tcl_ListObjIndex(NULL, resultPtr, i, &eltPtr);
641 str = Tcl_GetStringFromObj(eltPtr, &len);
642 memcpy((VOID *) p, (VOID *) str, (size_t) len+1);
643 p += len+1;
644 }
645
646 /*
647 * Now set up the argv pointers.
648 */
649
650 p = (char *) &(*argvPtr)[(*argcPtr) + 1];
651
652 for (i = 0; i < *argcPtr; i++) {
653 (*argvPtr)[i] = p;
654 while ((*p++) != '\0') {}
655 }
656 (*argvPtr)[i] = NULL;
657
658 /*
659 * Free the result ptr given to us by Tcl_FSSplitPath
660 */
661
662 Tcl_DecrRefCount(resultPtr);
663 }
664
665 /*
666 *----------------------------------------------------------------------
667 *
668 * SplitUnixPath --
669 *
670 * This routine is used by Tcl_(FS)SplitPath to handle splitting
671 * Unix paths.
672 *
673 * Results:
674 * Returns a newly allocated Tcl list object.
675 *
676 * Side effects:
677 * None.
678 *
679 *----------------------------------------------------------------------
680 */
681
682 static Tcl_Obj*
683 SplitUnixPath(path)
684 CONST char *path; /* Pointer to string containing a path. */
685 {
686 int length;
687 CONST char *p, *elementStart;
688 Tcl_Obj *result = Tcl_NewObj();
689
690 /*
691 * Deal with the root directory as a special case.
692 */
693
694 #ifdef __QNX__
695 /*
696 * Check for QNX //<node id> prefix
697 */
698 if ((path[0] == '/') && (path[1] == '/')
699 && isdigit(UCHAR(path[2]))) { /* INTL: digit */
700 path += 3;
701 while (isdigit(UCHAR(*path))) { /* INTL: digit */
702 ++path;
703 }
704 }
705 #endif
706
707 if (path[0] == '/') {
708 Tcl_ListObjAppendElement(NULL, result, Tcl_NewStringObj("/",1));
709 p = path+1;
710 } else {
711 p = path;
712 }
713
714 /*
715 * Split on slashes. Embedded elements that start with tilde will be
716 * prefixed with "./" so they are not affected by tilde substitution.
717 */
718
719 for (;;) {
720 elementStart = p;
721 while ((*p != '\0') && (*p != '/')) {
722 p++;
723 }
724 length = p - elementStart;
725 if (length > 0) {
726 Tcl_Obj *nextElt;
727 if ((elementStart[0] == '~') && (elementStart != path)) {
728 nextElt = Tcl_NewStringObj("./",2);
729 Tcl_AppendToObj(nextElt, elementStart, length);
730 } else {
731 nextElt = Tcl_NewStringObj(elementStart, length);
732 }
733 Tcl_ListObjAppendElement(NULL, result, nextElt);
734 }
735 if (*p++ == '\0') {
736 break;
737 }
738 }
739 return result;
740 }
741
742
743 /*
744 *----------------------------------------------------------------------
745 *
746 * SplitWinPath --
747 *
748 * This routine is used by Tcl_(FS)SplitPath to handle splitting
749 * Windows paths.
750 *
751 * Results:
752 * Returns a newly allocated Tcl list object.
753 *
754 * Side effects:
755 * None.
756 *
757 *----------------------------------------------------------------------
758 */
759
760 static Tcl_Obj*
761 SplitWinPath(path)
762 CONST char *path; /* Pointer to string containing a path. */
763 {
764 int length;
765 CONST char *p, *elementStart;
766 Tcl_PathType type = TCL_PATH_ABSOLUTE;
767 Tcl_DString buf;
768 Tcl_Obj *result = Tcl_NewObj();
769 Tcl_DStringInit(&buf);
770
771 p = ExtractWinRoot(path, &buf, 0, &type);
772
773 /*
774 * Terminate the root portion, if we matched something.
775 */
776
777 if (p != path) {
778 Tcl_ListObjAppendElement(NULL, result,
779 Tcl_NewStringObj(Tcl_DStringValue(&buf),
780 Tcl_DStringLength(&buf)));
781 }
782 Tcl_DStringFree(&buf);
783
784 /*
785 * Split on slashes. Embedded elements that start with tilde will be
786 * prefixed with "./" so they are not affected by tilde substitution.
787 */
788
789 do {
790 elementStart = p;
791 while ((*p != '\0') && (*p != '/') && (*p != '\\')) {
792 p++;
793 }
794 length = p - elementStart;
795 if (length > 0) {
796 Tcl_Obj *nextElt;
797 if ((elementStart[0] == '~') && (elementStart != path)) {
798 nextElt = Tcl_NewStringObj("./",2);
799 Tcl_AppendToObj(nextElt, elementStart, length);
800 } else {
801 nextElt = Tcl_NewStringObj(elementStart, length);
802 }
803 Tcl_ListObjAppendElement(NULL, result, nextElt);
804 }
805 } while (*p++ != '\0');
806
807 return result;
808 }
809
810 /*
811 *----------------------------------------------------------------------
812 *
813 * SplitMacPath --
814 *
815 * This routine is used by Tcl_(FS)SplitPath to handle splitting
816 * Macintosh paths.
817 *
818 * Results:
819 * Returns a newly allocated Tcl list object.
820 *
821 * Side effects:
822 * None.
823 *
824 *----------------------------------------------------------------------
825 */
826
827 static Tcl_Obj*
828 SplitMacPath(path)
829 CONST char *path; /* Pointer to string containing a path. */
830 {
831 int isMac = 0; /* 1 if is Mac-style, 0 if Unix-style path. */
832 int length;
833 CONST char *p, *elementStart;
834 Tcl_Obj *result;
835 #ifdef MAC_UNDERSTANDS_UNIX_PATHS
836 Tcl_RegExp re;
837 int i;
838 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
839 #endif
840
841 result = Tcl_NewObj();
842
843 #ifdef MAC_UNDERSTANDS_UNIX_PATHS
844 /*
845 * Initialize the path name parser for Macintosh path names.
846 */
847
848 FileNameInit();
849
850 /*
851 * Match the root portion of a Mac path name.
852 */
853
854 i = 0; /* Needed only to prevent gcc warnings. */
855
856 re = Tcl_GetRegExpFromObj(NULL, tsdPtr->macRootPatternPtr, REG_ADVANCED);
857
858 if (Tcl_RegExpExec(NULL, re, path, path) == 1) {
859 CONST char *start, *end;
860 Tcl_Obj *nextElt;
861
862 /*
863 * Treat degenerate absolute paths like / and /../.. as
864 * Mac relative file names for lack of anything else to do.
865 */
866
867 Tcl_RegExpRange(re, 2, &start, &end);
868 if (start) {
869 Tcl_Obj *elt = Tcl_NewStringObj(":", 1);
870 Tcl_RegExpRange(re, 0, &start, &end);
871 Tcl_AppendToObj(elt, path, end - start);
872 Tcl_ListObjAppendElement(NULL, result, elt);
873 return result;
874 }
875
876 Tcl_RegExpRange(re, 5, &start, &end);
877 if (start) {
878 /*
879 * Unix-style tilde prefixed paths.
880 */
881
882 isMac = 0;
883 i = 5;
884 } else {
885 Tcl_RegExpRange(re, 7, &start, &end);
886 if (start) {
887 /*
888 * Mac-style tilde prefixed paths.
889 */
890
891 isMac = 1;
892 i = 7;
893 } else {
894 Tcl_RegExpRange(re, 10, &start, &end);
895 if (start) {
896 /*
897 * Normal Unix style paths.
898 */
899
900 isMac = 0;
901 i = 10;
902 } else {
903 Tcl_RegExpRange(re, 12, &start, &end);
904 if (start) {
905 /*
906 * Normal Mac style paths.
907 */
908
909 isMac = 1;
910 i = 12;
911 }
912 }
913 }
914 }
915 Tcl_RegExpRange(re, i, &start, &end);
916 length = end - start;
917
918 /*
919 * Append the element and terminate it with a :
920 */
921
922 nextElt = Tcl_NewStringObj(start, length);
923 Tcl_AppendToObj(nextElt, ":", 1);
924 Tcl_ListObjAppendElement(NULL, result, nextElt);
925 p = end;
926 } else {
927 isMac = (strchr(path, ':') != NULL);
928 p = path;
929 }
930 #else
931 if ((path[0] != ':') && (path[0] == '~' || (strchr(path,':') != NULL))) {
932 CONST char *end;
933 Tcl_Obj *nextElt;
934
935 isMac = 1;
936
937 end = strchr(path,':');
938 if (end == NULL) {
939 length = strlen(path);
940 } else {
941 length = end - path;
942 }
943
944 /*
945 * Append the element and terminate it with a :
946 */
947
948 nextElt = Tcl_NewStringObj(path, length);
949 Tcl_AppendToObj(nextElt, ":", 1);
950 Tcl_ListObjAppendElement(NULL, result, nextElt);
951 p = path + length;
952 } else {
953 isMac = (strchr(path, ':') != NULL);
954 isMac = 1;
955 p = path;
956 }
957 #endif
958
959 if (isMac) {
960
961 /*
962 * p is pointing at the first colon in the path. There
963 * will always be one, since this is a Mac-style path.
964 * (This is no longer true if MAC_UNDERSTANDS_UNIX_PATHS
965 * is false, so we must check whether 'p' points to the
966 * end of the string.)
967 */
968 elementStart = p;
969 if (*p == ':') {
970 p++;
971 }
972
973 while ((p = strchr(p, ':')) != NULL) {
974 length = p - elementStart;
975 if (length == 1) {
976 while (*p == ':') {
977 Tcl_ListObjAppendElement(NULL, result,
978 Tcl_NewStringObj("::", 2));
979 elementStart = p++;
980 }
981 } else {
982 /*
983 * If this is a simple component, drop the leading colon.
984 */
985
986 if ((elementStart[1] != '~')
987 && (strchr(elementStart+1, '/') == NULL)) {
988 elementStart++;
989 length--;
990 }
991 Tcl_ListObjAppendElement(NULL, result,
992 Tcl_NewStringObj(elementStart, length));
993 elementStart = p++;
994 }
995 }
996 if (elementStart[0] != ':') {
997 if (elementStart[0] != '\0') {
998 Tcl_ListObjAppendElement(NULL, result,
999 Tcl_NewStringObj(elementStart, -1));
1000 }
1001 } else {
1002 if (elementStart[1] != '\0' || elementStart == path) {
1003 if ((elementStart[1] != '~') && (elementStart[1] != '\0')
1004 && (strchr(elementStart+1, '/') == NULL)) {
1005 elementStart++;
1006 }
1007 Tcl_ListObjAppendElement(NULL, result,
1008 Tcl_NewStringObj(elementStart, -1));
1009 }
1010 }
1011 } else {
1012
1013 /*
1014 * Split on slashes, suppress extra /'s, and convert .. to ::.
1015 */
1016
1017 for (;;) {
1018 elementStart = p;
1019 while ((*p != '\0') && (*p != '/')) {
1020 p++;
1021 }
1022 length = p - elementStart;
1023 if (length > 0) {
1024 if ((length == 1) && (elementStart[0] == '.')) {
1025 Tcl_ListObjAppendElement(NULL, result,
1026 Tcl_NewStringObj(":", 1));
1027 } else if ((length == 2) && (elementStart[0] == '.')
1028 && (elementStart[1] == '.')) {
1029 Tcl_ListObjAppendElement(NULL, result,
1030 Tcl_NewStringObj("::", 2));
1031 } else {
1032 Tcl_Obj *nextElt;
1033 if (*elementStart == '~') {
1034 nextElt = Tcl_NewStringObj(":",1);
1035 Tcl_AppendToObj(nextElt, elementStart, length);
1036 } else {
1037 nextElt = Tcl_NewStringObj(elementStart, length);
1038 }
1039 Tcl_ListObjAppendElement(NULL, result, nextElt);
1040 }
1041 }
1042 if (*p++ == '\0') {
1043 break;
1044 }
1045 }
1046 }
1047 return result;
1048 }
1049
1050 /*
1051 *---------------------------------------------------------------------------
1052 *
1053 * Tcl_FSJoinToPath --
1054 *
1055 * This function takes the given object, which should usually be a
1056 * valid path or NULL, and joins onto it the array of paths
1057 * segments given.
1058 *
1059 * Results:
1060 * Returns object with refCount of zero
1061 *
1062 * Side effects:
1063 * None.
1064 *
1065 *---------------------------------------------------------------------------
1066 */
1067
1068 Tcl_Obj*
1069 Tcl_FSJoinToPath(basePtr, objc, objv)
1070 Tcl_Obj *basePtr;
1071 int objc;
1072 Tcl_Obj *CONST objv[];
1073 {
1074 int i;
1075 Tcl_Obj *lobj, *ret;
1076
1077 if (basePtr == NULL) {
1078 lobj = Tcl_NewListObj(0, NULL);
1079 } else {
1080 lobj = Tcl_NewListObj(1, &basePtr);
1081 }
1082
1083 for (i = 0; i<objc;i++) {
1084 Tcl_ListObjAppendElement(NULL, lobj, objv[i]);
1085 }
1086 ret = Tcl_FSJoinPath(lobj, -1);
1087 Tcl_DecrRefCount(lobj);
1088 return ret;
1089 }
1090
1091 /*
1092 *---------------------------------------------------------------------------
1093 *
1094 * TclpNativeJoinPath --
1095 *
1096 * 'prefix' is absolute, 'joining' is relative to prefix.
1097 *
1098 * Results:
1099 * modifies prefix
1100 *
1101 * Side effects:
1102 * None.
1103 *
1104 *---------------------------------------------------------------------------
1105 */
1106
1107 void
1108 TclpNativeJoinPath(prefix, joining)
1109 Tcl_Obj *prefix;
1110 char* joining;
1111 {
1112 int length, needsSep;
1113 char *dest, *p, *start;
1114
1115 start = Tcl_GetStringFromObj(prefix, &length);
1116
1117 /*
1118 * Remove the ./ from tilde prefixed elements unless
1119 * it is the first component.
1120 */
1121
1122 p = joining;
1123
1124 if (length != 0) {
1125 if ((p[0] == '.') && (p[1] == '/') && (p[2] == '~')) {
1126 p += 2;
1127 }
1128 }
1129
1130 if (*p == '\0') {
1131 return;
1132 }
1133
1134
1135 switch (tclPlatform) {
1136 case TCL_PLATFORM_UNIX:
1137 /*
1138 * Append a separator if needed.
1139 */
1140
1141 if (length > 0 && (start[length-1] != '/')) {
1142 Tcl_AppendToObj(prefix, "/", 1);
1143 length++;
1144 }
1145 needsSep = 0;
1146
1147 /*
1148 * Append the element, eliminating duplicate and trailing
1149 * slashes.
1150 */
1151
1152 Tcl_SetObjLength(prefix, length + (int) strlen(p));
1153
1154 dest = Tcl_GetString(prefix) + length;
1155 for (; *p != '\0'; p++) {
1156 if (*p == '/') {
1157 while (p[1] == '/') {
1158 p++;
1159 }
1160 if (p[1] != '\0') {
1161 if (needsSep) {
1162 *dest++ = '/';
1163 }
1164 }
1165 } else {
1166 *dest++ = *p;
1167 needsSep = 1;
1168 }
1169 }
1170 length = dest - Tcl_GetString(prefix);
1171 Tcl_SetObjLength(prefix, length);
1172 break;
1173
1174 case TCL_PLATFORM_WINDOWS:
1175 /*
1176 * Check to see if we need to append a separator.
1177 */
1178
1179 if ((length > 0) &&
1180 (start[length-1] != '/') && (start[length-1] != ':')) {
1181 Tcl_AppendToObj(prefix, "/", 1);
1182 length++;
1183 }
1184 needsSep = 0;
1185
1186 /*
1187 * Append the element, eliminating duplicate and
1188 * trailing slashes.
1189 */
1190
1191 Tcl_SetObjLength(prefix, length + (int) strlen(p));
1192 dest = Tcl_GetString(prefix) + length;
1193 for (; *p != '\0'; p++) {
1194 if ((*p == '/') || (*p == '\\')) {
1195 while ((p[1] == '/') || (p[1] == '\\')) {
1196 p++;
1197 }
1198 if ((p[1] != '\0') && needsSep) {
1199 *dest++ = '/';
1200 }
1201 } else {
1202 *dest++ = *p;
1203 needsSep = 1;
1204 }
1205 }
1206 length = dest - Tcl_GetString(prefix);
1207 Tcl_SetObjLength(prefix, length);
1208 break;
1209
1210 case TCL_PLATFORM_MAC: {
1211 int newLength;
1212
1213 /*
1214 * Sort out separators. We basically add the object we've
1215 * been given, but we have to make sure that there is
1216 * exactly one separator inbetween (unless the object we're
1217 * adding contains multiple contiguous colons, all of which
1218 * we must add). Also if an object is just ':' we don't
1219 * bother to add it unless it's the very first element.
1220 */
1221
1222 #ifdef MAC_UNDERSTANDS_UNIX_PATHS
1223 int adjustedPath = 0;
1224 if ((strchr(p, ':') == NULL) && (strchr(p, '/') != NULL)) {
1225 char *start = p;
1226 adjustedPath = 1;
1227 while (*start != '\0') {
1228 if (*start == '/') {
1229 *start = ':';
1230 }
1231 start++;
1232 }
1233 }
1234 #endif
1235 if (length > 0) {
1236 if ((p[0] == ':') && (p[1] == '\0')) {
1237 return;
1238 }
1239 if (start[length-1] != ':') {
1240 if (*p != '\0' && *p != ':') {
1241 Tcl_AppendToObj(prefix, ":", 1);
1242 length++;
1243 }
1244 } else if (*p == ':') {
1245 p++;
1246 }
1247 } else {
1248 if (*p != '\0' && *p != ':') {
1249 Tcl_AppendToObj(prefix, ":", 1);
1250 length++;
1251 }
1252 }
1253
1254 /*
1255 * Append the element
1256 */
1257
1258 newLength = strlen(p);
1259 /*
1260 * It may not be good to just do 'Tcl_AppendToObj(prefix,
1261 * p, newLength)' because the object may contain duplicate
1262 * colons which we want to get rid of.
1263 */
1264 Tcl_AppendToObj(prefix, p, newLength);
1265
1266 /* Remove spurious trailing single ':' */
1267 dest = Tcl_GetString(prefix) + length + newLength;
1268 if (*(dest-1) == ':') {
1269 if (dest-1 > Tcl_GetString(prefix)) {
1270 if (*(dest-2) != ':') {
1271 Tcl_SetObjLength(prefix, length + newLength -1);
1272 }
1273 }
1274 }
1275 #ifdef MAC_UNDERSTANDS_UNIX_PATHS
1276 /* Revert the path to what it was */
1277 if (adjustedPath) {
1278 char *start = joining;
1279 while (*start != '\0') {
1280 if (*start == ':') {
1281 *start = '/';
1282 }
1283 start++;
1284 }
1285 }
1286 #endif
1287 break;
1288 }
1289 }
1290 return;
1291 }
1292
1293 /*
1294 *----------------------------------------------------------------------
1295 *
1296 * Tcl_JoinPath --
1297 *
1298 * Combine a list of paths in a platform specific manner. The
1299 * function 'Tcl_FSJoinPath' should be used in preference where
1300 * possible.
1301 *
1302 * Results:
1303 * Appends the joined path to the end of the specified
1304 * Tcl_DString returning a pointer to the resulting string. Note
1305 * that the Tcl_DString must already be initialized.
1306 *
1307 * Side effects:
1308 * Modifies the Tcl_DString.
1309 *
1310 *----------------------------------------------------------------------
1311 */
1312
1313 char *
1314 Tcl_JoinPath(argc, argv, resultPtr)
1315 int argc;
1316 CONST char * CONST *argv;
1317 Tcl_DString *resultPtr; /* Pointer to previously initialized DString */
1318 {
1319 int i, len;
1320 Tcl_Obj *listObj = Tcl_NewObj();
1321 Tcl_Obj *resultObj;
1322 char *resultStr;
1323
1324 /* Build the list of paths */
1325 for (i = 0; i < argc; i++) {
1326 Tcl_ListObjAppendElement(NULL, listObj,
1327 Tcl_NewStringObj(argv[i], -1));
1328 }
1329
1330 /* Ask the objectified code to join the paths */
1331 Tcl_IncrRefCount(listObj);
1332 resultObj = Tcl_FSJoinPath(listObj, argc);
1333 Tcl_IncrRefCount(resultObj);
1334 Tcl_DecrRefCount(listObj);
1335
1336 /* Store the result */
1337 resultStr = Tcl_GetStringFromObj(resultObj, &len);
1338 Tcl_DStringAppend(resultPtr, resultStr, len);
1339 Tcl_DecrRefCount(resultObj);
1340
1341 /* Return a pointer to the result */
1342 return Tcl_DStringValue(resultPtr);
1343 }
1344
1345 /*
1346 *---------------------------------------------------------------------------
1347 *
1348 * Tcl_TranslateFileName --
1349 *
1350 * Converts a file name into a form usable by the native system
1351 * interfaces. If the name starts with a tilde, it will produce a
1352 * name where the tilde and following characters have been replaced
1353 * by the home directory location for the named user.
1354 *
1355 * Results:
1356 * The return value is a pointer to a string containing the name
1357 * after tilde substitution. If there was no tilde substitution,
1358 * the return value is a pointer to a copy of the original string.
1359 * If there was an error in processing the name, then an error
1360 * message is left in the interp's result (if interp was not NULL)
1361 * and the return value is NULL. Space for the return value is
1362 * allocated in bufferPtr; the caller must call Tcl_DStringFree()
1363 * to free the space if the return value was not NULL.
1364 *
1365 * Side effects:
1366 * None.
1367 *
1368 *----------------------------------------------------------------------
1369 */
1370
1371 char *
1372 Tcl_TranslateFileName(interp, name, bufferPtr)
1373 Tcl_Interp *interp; /* Interpreter in which to store error
1374 * message (if necessary). */
1375 CONST char *name; /* File name, which may begin with "~" (to
1376 * indicate current user's home directory) or
1377 * "~<user>" (to indicate any user's home
1378 * directory). */
1379 Tcl_DString *bufferPtr; /* Uninitialized or free DString filled
1380 * with name after tilde substitution. */
1381 {
1382 Tcl_Obj *path = Tcl_NewStringObj(name, -1);
1383 Tcl_Obj *transPtr;
1384
1385 Tcl_IncrRefCount(path);
1386 transPtr = Tcl_FSGetTranslatedPath(interp, path);
1387 if (transPtr == NULL) {
1388 Tcl_DecrRefCount(path);
1389 return NULL;
1390 }
1391
1392 Tcl_DStringInit(bufferPtr);
1393 Tcl_DStringAppend(bufferPtr, Tcl_GetString(transPtr), -1);
1394 Tcl_DecrRefCount(path);
1395 Tcl_DecrRefCount(transPtr);
1396
1397 /*
1398 * Convert forward slashes to backslashes in Windows paths because
1399 * some system interfaces don't accept forward slashes.
1400 */
1401
1402 if (tclPlatform == TCL_PLATFORM_WINDOWS) {
1403 register char *p;
1404 for (p = Tcl_DStringValue(bufferPtr); *p != '\0'; p++) {
1405 if (*p == '/') {
1406 *p = '\\';
1407 }
1408 }
1409 }
1410 return Tcl_DStringValue(bufferPtr);
1411 }
1412
1413 /*
1414 *----------------------------------------------------------------------
1415 *
1416 * TclGetExtension --
1417 *
1418 * This function returns a pointer to the beginning of the
1419 * extension part of a file name.
1420 *
1421 * Results:
1422 * Returns a pointer into name which indicates where the extension
1423 * starts. If there is no extension, returns NULL.
1424 *
1425 * Side effects:
1426 * None.
1427 *
1428 *----------------------------------------------------------------------
1429 */
1430
1431 char *
1432 TclGetExtension(name)
1433 char *name; /* File name to parse. */
1434 {
1435 char *p, *lastSep;
1436
1437 /*
1438 * First find the last directory separator.
1439 */
1440
1441 lastSep = NULL; /* Needed only to prevent gcc warnings. */
1442 switch (tclPlatform) {
1443 case TCL_PLATFORM_UNIX:
1444 lastSep = strrchr(name, '/');
1445 break;
1446
1447 case TCL_PLATFORM_MAC:
1448 #ifdef MAC_UNDERSTANDS_UNIX_PATHS
1449 if (strchr(name, ':') == NULL) {
1450 lastSep = strrchr(name, '/');
1451 } else {
1452 lastSep = strrchr(name, ':');
1453 }
1454 #else
1455 lastSep = strrchr(name, ':');
1456 #endif
1457 break;
1458
1459 case TCL_PLATFORM_WINDOWS:
1460 lastSep = NULL;
1461 for (p = name; *p != '\0'; p++) {
1462 if (strchr("/\\:", *p) != NULL) {
1463 lastSep = p;
1464 }
1465 }
1466 break;
1467 }
1468 p = strrchr(name, '.');
1469 if ((p != NULL) && (lastSep != NULL) && (lastSep > p)) {
1470 p = NULL;
1471 }
1472
1473 /*
1474 * In earlier versions, we used to back up to the first period in a series
1475 * so that "foo..o" would be split into "foo" and "..o". This is a
1476 * confusing and usually incorrect behavior, so now we split at the last
1477 * period in the name.
1478 */
1479
1480 return p;
1481 }
1482
1483 /*
1484 *----------------------------------------------------------------------
1485 *
1486 * DoTildeSubst --
1487 *
1488 * Given a string following a tilde, this routine returns the
1489 * corresponding home directory.
1490 *
1491 * Results:
1492 * The result is a pointer to a static string containing the home
1493 * directory in native format. If there was an error in processing
1494 * the substitution, then an error message is left in the interp's
1495 * result and the return value is NULL. On success, the results
1496 * are appended to resultPtr, and the contents of resultPtr are
1497 * returned.
1498 *
1499 * Side effects:
1500 * Information may be left in resultPtr.
1501 *
1502 *----------------------------------------------------------------------
1503 */
1504
1505 static CONST char *
1506 DoTildeSubst(interp, user, resultPtr)
1507 Tcl_Interp *interp; /* Interpreter in which to store error
1508 * message (if necessary). */
1509 CONST char *user; /* Name of user whose home directory should be
1510 * substituted, or "" for current user. */
1511 Tcl_DString *resultPtr; /* Initialized DString filled with name
1512 * after tilde substitution. */
1513 {
1514 CONST char *dir;
1515
1516 if (*user == '\0') {
1517 Tcl_DString dirString;
1518
1519 dir = TclGetEnv("HOME", &dirString);
1520 if (dir == NULL) {
1521 if (interp) {
1522 Tcl_ResetResult(interp);
1523 Tcl_AppendResult(interp, "couldn't find HOME environment ",
1524 "variable to expand path", (char *) NULL);
1525 }
1526 return NULL;
1527 }
1528 Tcl_JoinPath(1, &dir, resultPtr);
1529 Tcl_DStringFree(&dirString);
1530 } else {
1531 if (TclpGetUserHome(user, resultPtr) == NULL) {
1532 if (interp) {
1533 Tcl_ResetResult(interp);
1534 Tcl_AppendResult(interp, "user \"", user, "\" doesn't exist",
1535 (char *) NULL);
1536 }
1537 return NULL;
1538 }
1539 }
1540 return Tcl_DStringValue(resultPtr);
1541 }
1542
1543 /*
1544 *----------------------------------------------------------------------
1545 *
1546 * Tcl_GlobObjCmd --
1547 *
1548 * This procedure is invoked to process the "glob" Tcl command.
1549 * See the user documentation for details on what it does.
1550 *
1551 * Results:
1552 * A standard Tcl result.
1553 *
1554 * Side effects:
1555 * See the user documentation.
1556 *
1557 *----------------------------------------------------------------------
1558 */
1559
1560 /* ARGSUSED */
1561 int
1562 Tcl_GlobObjCmd(dummy, interp, objc, objv)
1563 ClientData dummy; /* Not used. */
1564 Tcl_Interp *interp; /* Current interpreter. */
1565 int objc; /* Number of arguments. */
1566 Tcl_Obj *CONST objv[]; /* Argument objects. */
1567 {
1568 int index, i, globFlags, length, join, dir, result;
1569 char *string, *separators;
1570 Tcl_Obj *typePtr, *resultPtr, *look;
1571 Tcl_Obj *pathOrDir = NULL;
1572 Tcl_DString prefix;
1573 static CONST char *options[] = {
1574 "-directory", "-join", "-nocomplain", "-path", "-tails",
1575 "-types", "--", NULL
1576 };
1577 enum options {
1578 GLOB_DIR, GLOB_JOIN, GLOB_NOCOMPLAIN, GLOB_PATH, GLOB_TAILS,
1579 GLOB_TYPE, GLOB_LAST
1580 };
1581 enum pathDirOptions {PATH_NONE = -1 , PATH_GENERAL = 0, PATH_DIR = 1};
1582 Tcl_GlobTypeData *globTypes = NULL;
1583
1584 globFlags = 0;
1585 join = 0;
1586 dir = PATH_NONE;
1587 typePtr = NULL;
1588 resultPtr = Tcl_GetObjResult(interp);
1589 for (i = 1; i < objc; i++) {
1590 if (Tcl_GetIndexFromObj(interp, objv[i], options, "option", 0, &index)
1591 != TCL_OK) {
1592 string = Tcl_GetStringFromObj(objv[i], &length);
1593 if (string[0] == '-') {
1594 /*
1595 * It looks like the command contains an option so signal
1596 * an error
1597 */
1598 return TCL_ERROR;
1599 } else {
1600 /*
1601 * This clearly isn't an option; assume it's the first
1602 * glob pattern. We must clear the error
1603 */
1604 Tcl_ResetResult(interp);
1605 break;
1606 }
1607 }
1608 switch (index) {
1609 case GLOB_NOCOMPLAIN: /* -nocomplain */
1610 globFlags |= TCL_GLOBMODE_NO_COMPLAIN;
1611 break;
1612 case GLOB_DIR: /* -dir */
1613 if (i == (objc-1)) {
1614 Tcl_AppendToObj(resultPtr,
1615 "missing argument to \"-directory\"", -1);
1616 return TCL_ERROR;
1617 }
1618 if (dir != PATH_NONE) {
1619 Tcl_AppendToObj(resultPtr,
1620 "\"-directory\" cannot be used with \"-path\"",
1621 -1);
1622 return TCL_ERROR;
1623 }
1624 dir = PATH_DIR;
1625 globFlags |= TCL_GLOBMODE_DIR;
1626 pathOrDir = objv[i+1];
1627 i++;
1628 break;
1629 case GLOB_JOIN: /* -join */
1630 join = 1;
1631 break;
1632 case GLOB_TAILS: /* -tails */
1633 globFlags |= TCL_GLOBMODE_TAILS;
1634 break;
1635 case GLOB_PATH: /* -path */
1636 if (i == (objc-1)) {
1637 Tcl_AppendToObj(resultPtr,
1638 "missing argument to \"-path\"", -1);
1639 return TCL_ERROR;
1640 }
1641 if (dir != PATH_NONE) {
1642 Tcl_AppendToObj(resultPtr,
1643 "\"-path\" cannot be used with \"-directory\"",
1644 -1);
1645 return TCL_ERROR;
1646 }
1647 dir = PATH_GENERAL;
1648 pathOrDir = objv[i+1];
1649 i++;
1650 break;
1651 case GLOB_TYPE: /* -types */
1652 if (i == (objc-1)) {
1653 Tcl_AppendToObj(resultPtr,
1654 "missing argument to \"-types\"", -1);
1655 return TCL_ERROR;
1656 }
1657 typePtr = objv[i+1];
1658 if (Tcl_ListObjLength(interp, typePtr, &length) != TCL_OK) {
1659 return TCL_ERROR;
1660 }
1661 i++;
1662 break;
1663 case GLOB_LAST: /* -- */
1664 i++;
1665 goto endOfForLoop;
1666 }
1667 }
1668 endOfForLoop:
1669 if (objc - i < 1) {
1670 Tcl_WrongNumArgs(interp, 1, objv, "?switches? name ?name ...?");
1671 return TCL_ERROR;
1672 }
1673 if ((globFlags & TCL_GLOBMODE_TAILS) && (pathOrDir == NULL)) {
1674 Tcl_AppendToObj(resultPtr,
1675 "\"-tails\" must be used with either \"-directory\" or \"-path\"",
1676 -1);
1677 return TCL_ERROR;
1678 }
1679
1680 separators = NULL; /* lint. */
1681 switch (tclPlatform) {
1682 case TCL_PLATFORM_UNIX:
1683 separators = "/";
1684 break;
1685 case TCL_PLATFORM_WINDOWS:
1686 separators = "/\\:";
1687 break;
1688 case TCL_PLATFORM_MAC:
1689 separators = ":";
1690 break;
1691 }
1692 if (dir == PATH_GENERAL) {
1693 int pathlength;
1694 char *last;
1695 char *first = Tcl_GetStringFromObj(pathOrDir,&pathlength);
1696
1697 /*
1698 * Find the last path separator in the path
1699 */
1700 last = first + pathlength;
1701 for (; last != first; last--) {
1702 if (strchr(separators, *(last-1)) != NULL) {
1703 break;
1704 }
1705 }
1706 if (last == first + pathlength) {
1707 /* It's really a directory */
1708 dir = PATH_DIR;
1709 } else {
1710 Tcl_DString pref;
1711 char *search, *find;
1712 Tcl_DStringInit(&pref);
1713 if (last == first) {
1714 /* The whole thing is a prefix */
1715 Tcl_DStringAppend(&pref, first, -1);
1716 pathOrDir = NULL;
1717 } else {
1718 /* Have to split off the end */
1719 Tcl_DStringAppend(&pref, last, first+pathlength-last);
1720 pathOrDir = Tcl_NewStringObj(first, last-first-1);
1721 }
1722 /* Need to quote 'prefix' */
1723 Tcl_DStringInit(&prefix);
1724 search = Tcl_DStringValue(&pref);
1725 while ((find = (strpbrk(search, "\\[]*?{}"))) != NULL) {
1726 Tcl_DStringAppend(&prefix, search, find-search);
1727 Tcl_DStringAppend(&prefix, "\\", 1);
1728 Tcl_DStringAppend(&prefix, find, 1);
1729 search = find+1;
1730 if (*search == '\0') {
1731 break;
1732 }
1733 }
1734 if (*search != '\0') {
1735 Tcl_DStringAppend(&prefix, search, -1);
1736 }
1737 Tcl_DStringFree(&pref);
1738 }
1739 }
1740
1741 if (pathOrDir != NULL) {
1742 Tcl_IncrRefCount(pathOrDir);
1743 }
1744
1745 if (typePtr != NULL) {
1746 /*
1747 * The rest of the possible type arguments (except 'd') are
1748 * platform specific. We don't complain when they are used
1749 * on an incompatible platform.
1750 */
1751 Tcl_ListObjLength(interp, typePtr, &length);
1752 globTypes = (Tcl_GlobTypeData*) ckalloc(sizeof(Tcl_GlobTypeData));
1753 globTypes->type = 0;
1754 globTypes->perm = 0;
1755 globTypes->macType = NULL;
1756 globTypes->macCreator = NULL;
1757 while(--length >= 0) {
1758 int len;
1759 char *str;
1760 Tcl_ListObjIndex(interp, typePtr, length, &look);
1761 str = Tcl_GetStringFromObj(look, &len);
1762 if (strcmp("readonly", str) == 0) {
1763 globTypes->perm |= TCL_GLOB_PERM_RONLY;
1764 } else if (strcmp("hidden", str) == 0) {
1765 globTypes->perm |= TCL_GLOB_PERM_HIDDEN;
1766 } else if (len == 1) {
1767 switch (str[0]) {
1768 case 'r':
1769 globTypes->perm |= TCL_GLOB_PERM_R;
1770 break;
1771 case 'w':
1772 globTypes->perm |= TCL_GLOB_PERM_W;
1773 break;
1774 case 'x':
1775 globTypes->perm |= TCL_GLOB_PERM_X;
1776 break;
1777 case 'b':
1778 globTypes->type |= TCL_GLOB_TYPE_BLOCK;
1779 break;
1780 case 'c':
1781 globTypes->type |= TCL_GLOB_TYPE_CHAR;
1782 break;
1783 case 'd':
1784 globTypes->type |= TCL_GLOB_TYPE_DIR;
1785 break;
1786 case 'p':
1787 globTypes->type |= TCL_GLOB_TYPE_PIPE;
1788 break;
1789 case 'f':
1790 globTypes->type |= TCL_GLOB_TYPE_FILE;
1791 break;
1792 case 'l':
1793 globTypes->type |= TCL_GLOB_TYPE_LINK;
1794 break;
1795 case 's':
1796 globTypes->type |= TCL_GLOB_TYPE_SOCK;
1797 break;
1798 default:
1799 goto badTypesArg;
1800 }
1801 } else if (len == 4) {
1802 /* This is assumed to be a MacOS file type */
1803 if (globTypes->macType != NULL) {
1804 goto badMacTypesArg;
1805 }
1806 globTypes->macType = look;
1807 Tcl_IncrRefCount(look);
1808 } else {
1809 Tcl_Obj* item;
1810 if ((Tcl_ListObjLength(NULL, look, &len) == TCL_OK) &&
1811 (len == 3)) {
1812 Tcl_ListObjIndex(interp, look, 0, &item);
1813 if (!strcmp("macintosh", Tcl_GetString(item))) {
1814 Tcl_ListObjIndex(interp, look, 1, &item);
1815 if (!strcmp("type", Tcl_GetString(item))) {
1816 Tcl_ListObjIndex(interp, look, 2, &item);
1817 if (globTypes->macType != NULL) {
1818 goto badMacTypesArg;
1819 }
1820 globTypes->macType = item;
1821 Tcl_IncrRefCount(item);
1822 continue;
1823 } else if (!strcmp("creator", Tcl_GetString(item))) {
1824 Tcl_ListObjIndex(interp, look, 2, &item);
1825 if (globTypes->macCreator != NULL) {
1826 goto badMacTypesArg;
1827 }
1828 globTypes->macCreator = item;
1829 Tcl_IncrRefCount(item);
1830 continue;
1831 }
1832 }
1833 }
1834 /*
1835 * Error cases. We re-get the interpreter's result,
1836 * just to be sure it hasn't changed, and we reset
1837 * the 'join' flag to zero, since we haven't yet
1838 * made use of it.
1839 */
1840 badTypesArg:
1841 resultPtr = Tcl_GetObjResult(interp);
1842 Tcl_AppendToObj(resultPtr, "bad argument to \"-types\": ", -1);
1843 Tcl_AppendObjToObj(resultPtr, look);
1844 result = TCL_ERROR;
1845 join = 0;
1846 goto endOfGlob;
1847 badMacTypesArg:
1848 resultPtr = Tcl_GetObjResult(interp);
1849 Tcl_AppendToObj(resultPtr,
1850 "only one MacOS type or creator argument"
1851 " to \"-types\" allowed", -1);
1852 result = TCL_ERROR;
1853 join = 0;
1854 goto endOfGlob;
1855 }
1856 }
1857 }
1858
1859 /*
1860 * Now we perform the actual glob below. This may involve joining
1861 * together the pattern arguments, dealing with particular file types
1862 * etc. We use a 'goto' to ensure we free any memory allocated along
1863 * the way.
1864 */
1865 objc -= i;
1866 objv += i;
1867 /*
1868 * We re-retrieve this, in case it was changed in
1869 * the Tcl_ResetResult above
1870 */
1871 resultPtr = Tcl_GetObjResult(interp);
1872 result = TCL_OK;
1873 if (join) {
1874 if (dir != PATH_GENERAL) {
1875 Tcl_DStringInit(&prefix);
1876 }
1877 for (i = 0; i < objc; i++) {
1878 string = Tcl_GetStringFromObj(objv[i], &length);
1879 Tcl_DStringAppend(&prefix, string, length);
1880 if (i != objc -1) {
1881 Tcl_DStringAppend(&prefix, separators, 1);
1882 }
1883 }
1884 if (TclGlob(interp, Tcl_DStringValue(&prefix), pathOrDir,
1885 globFlags, globTypes) != TCL_OK) {
1886 result = TCL_ERROR;
1887 goto endOfGlob;
1888 }
1889 } else {
1890 if (dir == PATH_GENERAL) {
1891 Tcl_DString str;
1892 for (i = 0; i < objc; i++) {
1893 Tcl_DStringInit(&str);
1894 if (dir == PATH_GENERAL) {
1895 Tcl_DStringAppend(&str, Tcl_DStringValue(&prefix),
1896 Tcl_DStringLength(&prefix));
1897 }
1898 string = Tcl_GetStringFromObj(objv[i], &length);
1899 Tcl_DStringAppend(&str, string, length);
1900 if (TclGlob(interp, Tcl_DStringValue(&str), pathOrDir,
1901 globFlags, globTypes) != TCL_OK) {
1902 result = TCL_ERROR;
1903 Tcl_DStringFree(&str);
1904 goto endOfGlob;
1905 }
1906 }
1907 Tcl_DStringFree(&str);
1908 } else {
1909 for (i = 0; i < objc; i++) {
1910 string = Tcl_GetString(objv[i]);
1911 if (TclGlob(interp, string, pathOrDir,
1912 globFlags, globTypes) != TCL_OK) {
1913 result = TCL_ERROR;
1914 goto endOfGlob;
1915 }
1916 }
1917 }
1918 }
1919 if ((globFlags & TCL_GLOBMODE_NO_COMPLAIN) == 0) {
1920 if (Tcl_ListObjLength(interp, Tcl_GetObjResult(interp),
1921 &length) != TCL_OK) {
1922 /* This should never happen. Maybe we should be more dramatic */
1923 result = TCL_ERROR;
1924 goto endOfGlob;
1925 }
1926 if (length == 0) {
1927 Tcl_AppendResult(interp, "no files matched glob pattern",
1928 (join || (objc == 1)) ? " \"" : "s \"", (char *) NULL);
1929 if (join) {
1930 Tcl_AppendResult(interp, Tcl_DStringValue(&prefix),
1931 (char *) NULL);
1932 } else {
1933 char *sep = "";
1934 for (i = 0; i < objc; i++) {
1935 string = Tcl_GetString(objv[i]);
1936 Tcl_AppendResult(interp, sep, string, (char *) NULL);
1937 sep = " ";
1938 }
1939 }
1940 Tcl_AppendResult(interp, "\"", (char *) NULL);
1941 result = TCL_ERROR;
1942 }
1943 }
1944 endOfGlob:
1945 if (join || (dir == PATH_GENERAL)) {
1946 Tcl_DStringFree(&prefix);
1947 }
1948 if (pathOrDir != NULL) {
1949 Tcl_DecrRefCount(pathOrDir);
1950 }
1951 if (globTypes != NULL) {
1952 if (globTypes->macType != NULL) {
1953 Tcl_DecrRefCount(globTypes->macType);
1954 }
1955 if (globTypes->macCreator != NULL) {
1956 Tcl_DecrRefCount(globTypes->macCreator);
1957 }
1958 ckfree((char *) globTypes);
1959 }
1960 return result;
1961 }
1962
1963 /*
1964 *----------------------------------------------------------------------
1965 *
1966 * TclGlob --
1967 *
1968 * This procedure prepares arguments for the TclDoGlob call.
1969 * It sets the separator string based on the platform, performs
1970 * tilde substitution, and calls TclDoGlob.
1971 *
1972 * The interpreter's result, on entry to this function, must
1973 * be a valid Tcl list (e.g. it could be empty), since we will
1974 * lappend any new results to that list. If it is not a valid
1975 * list, this function will fail to do anything very meaningful.
1976 *
1977 * Results:
1978 * The return value is a standard Tcl result indicating whether
1979 * an error occurred in globbing. After a normal return the
1980 * result in interp (set by TclDoGlob) holds all of the file names
1981 * given by the pattern and unquotedPrefix arguments. After an
1982 * error the result in interp will hold an error message, unless
1983 * the 'TCL_GLOBMODE_NO_COMPLAIN' flag was given, in which case
1984 * an error results in a TCL_OK return leaving the interpreter's
1985 * result unmodified.
1986 *
1987 * Side effects:
1988 * The 'pattern' is written to.
1989 *
1990 *----------------------------------------------------------------------
1991 */
1992
1993 /* ARGSUSED */
1994 int
1995 TclGlob(interp, pattern, unquotedPrefix, globFlags, types)
1996 Tcl_Interp *interp; /* Interpreter for returning error message
1997 * or appending list of matching file names. */
1998 char *pattern; /* Glob pattern to match. Must not refer
1999 * to a static string. */
2000 Tcl_Obj *unquotedPrefix; /* Prefix to glob pattern, if non-null, which
2001 * is considered literally. */
2002 int globFlags; /* Stores or'ed combination of flags */
2003 Tcl_GlobTypeData *types; /* Struct containing acceptable types.
2004 * May be NULL. */
2005 {
2006 char *separators;
2007 CONST char *head;
2008 char *tail, *start;
2009 char c;
2010 int result, prefixLen;
2011 Tcl_DString buffer;
2012 Tcl_Obj *oldResult;
2013
2014 separators = NULL; /* lint. */
2015 switch (tclPlatform) {
2016 case TCL_PLATFORM_UNIX:
2017 separators = "/";
2018 break;
2019 case TCL_PLATFORM_WINDOWS:
2020 separators = "/\\:";
2021 break;
2022 case TCL_PLATFORM_MAC:
2023 #ifdef MAC_UNDERSTANDS_UNIX_PATHS
2024 if (unquotedPrefix == NULL) {
2025 separators = (strchr(pattern, ':') == NULL) ? "/" : ":";
2026 } else {
2027 separators = ":";
2028 }
2029 #else
2030 separators = ":";
2031 #endif
2032 break;
2033 }
2034
2035 Tcl_DStringInit(&buffer);
2036 if (unquotedPrefix != NULL) {
2037 start = Tcl_GetString(unquotedPrefix);
2038 } else {
2039 start = pattern;
2040 }
2041
2042 /*
2043 * Perform tilde substitution, if needed.
2044 */
2045
2046 if (start[0] == '~') {
2047
2048 /*
2049 * Find the first path separator after the tilde.
2050 */
2051 for (tail = start; *tail != '\0'; tail++) {
2052 if (*tail == '\\') {
2053 if (strchr(separators, tail[1]) != NULL) {
2054 break;
2055 }
2056 } else if (strchr(separators, *tail) != NULL) {
2057 break;
2058 }
2059 }
2060
2061 /*
2062 * Determine the home directory for the specified user.
2063 */
2064
2065 c = *tail;
2066 *tail = '\0';
2067 if (globFlags & TCL_GLOBMODE_NO_COMPLAIN) {
2068 /*
2069 * We will ignore any error message here, and we
2070 * don't want to mess up the interpreter's result.
2071 */
2072 head = DoTildeSubst(NULL, start+1, &buffer);
2073 } else {
2074 head = DoTildeSubst(interp, start+1, &buffer);
2075 }
2076 *tail = c;
2077 if (head == NULL) {
2078 if (globFlags & TCL_GLOBMODE_NO_COMPLAIN) {
2079 return TCL_OK;
2080 } else {
2081 return TCL_ERROR;
2082 }
2083 }
2084 if (head != Tcl_DStringValue(&buffer)) {
2085 Tcl_DStringAppend(&buffer, head, -1);
2086 }
2087 if (unquotedPrefix != NULL) {
2088 Tcl_DStringAppend(&buffer, tail, -1);
2089 tail = pattern;
2090 }
2091 } else {
2092 tail = pattern;
2093 if (unquotedPrefix != NULL) {
2094 Tcl_DStringAppend(&buffer,Tcl_GetString(unquotedPrefix),-1);
2095 }
2096 }
2097
2098 /*
2099 * We want to remember the length of the current prefix,
2100 * in case we are using TCL_GLOBMODE_TAILS. Also if we
2101 * are using TCL_GLOBMODE_DIR, we must make sure the
2102 * prefix ends in a directory separator.
2103 */
2104 prefixLen = Tcl_DStringLength(&buffer);
2105
2106 if (prefixLen > 0) {
2107 c = Tcl_DStringValue(&buffer)[prefixLen-1];
2108 if (strchr(separators, c) == NULL) {
2109 /*
2110 * If the prefix is a directory, make sure it ends in a
2111 * directory separator.
2112 */
2113 if (globFlags & TCL_GLOBMODE_DIR) {
2114 Tcl_DStringAppend(&buffer,separators,1);
2115 }
2116 prefixLen++;
2117 }
2118 }
2119
2120 /*
2121 * We need to get the old result, in case it is over-written
2122 * below when we still need it.
2123 */
2124 oldResult = Tcl_GetObjResult(interp);
2125 Tcl_IncrRefCount(oldResult);
2126 Tcl_ResetResult(interp);
2127
2128 result = TclDoGlob(interp, separators, &buffer, tail, types);
2129
2130 if (result != TCL_OK) {
2131 if (globFlags & TCL_GLOBMODE_NO_COMPLAIN) {
2132 /* Put back the old result and reset the return code */
2133 Tcl_SetObjResult(interp, oldResult);
2134 result = TCL_OK;
2135 }
2136 } else {
2137 /*
2138 * Now we must concatenate the 'oldResult' and the current
2139 * result, and then place that into the interpreter.
2140 *
2141 * If we only want the tails, we must strip off the prefix now.
2142 * It may seem more efficient to pass the tails flag down into
2143 * TclDoGlob, Tcl_FSMatchInDirectory, but those functions are
2144 * continually adjusting the prefix as the various pieces of
2145 * the pattern are assimilated, so that would add a lot of
2146 * complexity to the code. This way is a little slower (when
2147 * the -tails flag is given), but much simpler to code.
2148 */
2149 int objc, i;
2150 Tcl_Obj **objv;
2151
2152 /* Ensure sole ownership */
2153 if (Tcl_IsShared(oldResult)) {
2154 Tcl_DecrRefCount(oldResult);
2155 oldResult = Tcl_DuplicateObj(oldResult);
2156 Tcl_IncrRefCount(oldResult);
2157 }
2158
2159 Tcl_ListObjGetElements(NULL, Tcl_GetObjResult(interp),
2160 &objc, &objv);
2161 #ifdef MAC_TCL
2162 /* adjust prefixLen if TclDoGlob prepended a ':' */
2163 if ((prefixLen > 0) && (objc > 0)
2164 && (Tcl_DStringValue(&buffer)[0] != ':')) {
2165 char *str = Tcl_GetStringFromObj(objv[0],NULL);
2166 if (str[0] == ':') {
2167 prefixLen++;
2168 }
2169 }
2170 #endif
2171 for (i = 0; i< objc; i++) {
2172 Tcl_Obj* elt;
2173 if (globFlags & TCL_GLOBMODE_TAILS) {
2174 int len;
2175 char *oldStr = Tcl_GetStringFromObj(objv[i],&len);
2176 if (len == prefixLen) {
2177 if ((pattern[0] == '\0')
2178 || (strchr(separators, pattern[0]) == NULL)) {
2179 elt = Tcl_NewStringObj(".",1);
2180 } else {
2181 elt = Tcl_NewStringObj("/",1);
2182 }
2183 } else {
2184 elt = Tcl_NewStringObj(oldStr + prefixLen,
2185 len - prefixLen);
2186 }
2187 } else {
2188 elt = objv[i];
2189 }
2190 /* Assumption that 'oldResult' is a valid list */
2191 Tcl_ListObjAppendElement(interp, oldResult, elt);
2192 }
2193 Tcl_SetObjResult(interp, oldResult);
2194 }
2195 /*
2196 * Release our temporary copy. All code paths above must
2197 * end here so we free our reference.
2198 */
2199 Tcl_DecrRefCount(oldResult);
2200 Tcl_DStringFree(&buffer);
2201 return result;
2202 }
2203
2204 /*
2205 *----------------------------------------------------------------------
2206 *
2207 * SkipToChar --
2208 *
2209 * This function traverses a glob pattern looking for the next
2210 * unquoted occurance of the specified character at the same braces
2211 * nesting level.
2212 *
2213 * Results:
2214 * Updates stringPtr to point to the matching character, or to
2215 * the end of the string if nothing matched. The return value
2216 * is 1 if a match was found at the top level, otherwise it is 0.
2217 *
2218 * Side effects:
2219 * None.
2220 *
2221 *----------------------------------------------------------------------
2222 */
2223
2224 static int
2225 SkipToChar(stringPtr, match)
2226 char **stringPtr; /* Pointer string to check. */
2227 char *match; /* Pointer to character to find. */
2228 {
2229 int quoted, level;
2230 register char *p;
2231
2232 quoted = 0;
2233 level = 0;
2234
2235 for (p = *stringPtr; *p != '\0'; p++) {
2236 if (quoted) {
2237 quoted = 0;
2238 continue;
2239 }
2240 if ((level == 0) && (*p == *match)) {
2241 *stringPtr = p;
2242 return 1;
2243 }
2244 if (*p == '{') {
2245 level++;
2246 } else if (*p == '}') {
2247 level--;
2248 } else if (*p == '\\') {
2249 quoted = 1;
2250 }
2251 }
2252 *stringPtr = p;
2253 return 0;
2254 }
2255
2256 /*
2257 *----------------------------------------------------------------------
2258 *
2259 * TclDoGlob --
2260 *
2261 * This recursive procedure forms the heart of the globbing
2262 * code. It performs a depth-first traversal of the tree
2263 * given by the path name to be globbed. The directory and
2264 * remainder are assumed to be native format paths. The prefix
2265 * contained in 'headPtr' is not used as a glob pattern, simply
2266 * as a path specifier, so it can contain unquoted glob-sensitive
2267 * characters (if the directories to which it points contain
2268 * such strange characters).
2269 *
2270 * Results:
2271 * The return value is a standard Tcl result indicating whether
2272 * an error occurred in globbing. After a normal return the
2273 * result in interp will be set to hold all of the file names
2274 * given by the dir and rem arguments. After an error the
2275 * result in interp will hold an error message.
2276 *
2277 * Side effects:
2278 * None.
2279 *
2280 *----------------------------------------------------------------------
2281 */
2282
2283 int
2284 TclDoGlob(interp, separators, headPtr, tail, types)
2285 Tcl_Interp *interp; /* Interpreter to use for error reporting
2286 * (e.g. unmatched brace). */
2287 char *separators; /* String containing separator characters
2288 * that should be used to identify globbing
2289 * boundaries. */
2290 Tcl_DString *headPtr; /* Completely expanded prefix. */
2291 char *tail; /* The unexpanded remainder of the path.
2292 * Must not be a pointer to a static string. */
2293 Tcl_GlobTypeData *types; /* List object containing list of acceptable
2294 * types. May be NULL. */
2295 {
2296 int baseLength, quoted, count;
2297 int result = TCL_OK;
2298 char *name, *p, *openBrace, *closeBrace, *firstSpecialChar, savedChar;
2299 char lastChar = 0;
2300
2301 int length = Tcl_DStringLength(headPtr);
2302
2303 if (length > 0) {
2304 lastChar = Tcl_DStringValue(headPtr)[length-1];
2305 }
2306
2307 /*
2308 * Consume any leading directory separators, leaving tail pointing
2309 * just past the last initial separator.
2310 */
2311
2312 count = 0;
2313 name = tail;
2314 for (; *tail != '\0'; tail++) {
2315 if (*tail == '\\') {
2316 /*
2317 * If the first character is escaped, either we have a directory
2318 * separator, or we have any other character. In the latter case
2319 * the rest of tail is a pattern, and we must break from the loop.
2320 * This is particularly important on Windows where '\' is both
2321 * the escaping character and a directory separator.
2322 */
2323 if (strchr(separators, tail[1]) != NULL) {
2324 tail++;
2325 } else {
2326 break;
2327 }
2328 } else if (strchr(separators, *tail) == NULL) {
2329 break;
2330 }
2331 count++;
2332 }
2333
2334 /*
2335 * Deal with path separators. On the Mac, we have to watch out
2336 * for multiple separators, since they are special in Mac-style
2337 * paths.
2338 */
2339
2340 switch (tclPlatform) {
2341 case TCL_PLATFORM_MAC:
2342 #ifdef MAC_UNDERSTANDS_UNIX_PATHS
2343 if (*separators == '/') {
2344 if (((length == 0) && (count == 0))
2345 || ((length > 0) && (lastChar != ':'))) {
2346 Tcl_DStringAppend(headPtr, ":", 1);
2347 }
2348 } else {
2349 #endif
2350 if (count == 0) {
2351 if ((length > 0) && (lastChar != ':')) {
2352 Tcl_DStringAppend(headPtr, ":", 1);
2353 }
2354 } else {
2355 if (lastChar == ':') {
2356 count--;
2357 }
2358 while (count-- > 0) {
2359 Tcl_DStringAppend(headPtr, ":", 1);
2360 }
2361 }
2362 #ifdef MAC_UNDERSTANDS_UNIX_PATHS
2363 }
2364 #endif
2365 break;
2366 case TCL_PLATFORM_WINDOWS:
2367 /*
2368 * If this is a drive relative path, add the colon and the
2369 * trailing slash if needed. Otherwise add the slash if
2370 * this is the first absolute element, or a later relative
2371 * element. Add an extra slash if this is a UNC path.
2372 */
2373
2374 if (*name == ':') {
2375 Tcl_DStringAppend(headPtr, ":", 1);
2376 if (count > 1) {
2377 Tcl_DStringAppend(headPtr, "/", 1);
2378 }
2379 } else if ((*tail != '\0')
2380 && (((length > 0)
2381 && (strchr(separators, lastChar) == NULL))
2382 || ((length == 0) && (count > 0)))) {
2383 Tcl_DStringAppend(headPtr, "/", 1);
2384 if ((length == 0) && (count > 1)) {
2385 Tcl_DStringAppend(headPtr, "/", 1);
2386 }
2387 }
2388
2389 break;
2390 case TCL_PLATFORM_UNIX:
2391 /*
2392 * Add a separator if this is the first absolute element, or
2393 * a later relative element.
2394 */
2395
2396 if ((*tail != '\0')
2397 && (((length > 0)
2398 && (strchr(separators, lastChar) == NULL))
2399 || ((length == 0) && (count > 0)))) {
2400 Tcl_DStringAppend(headPtr, "/", 1);
2401 }
2402 break;
2403 }
2404
2405 /*
2406 * Look for the first matching pair of braces or the first
2407 * directory separator that is not inside a pair of braces.
2408 */
2409
2410 openBrace = closeBrace = NULL;
2411 quoted = 0;
2412 for (p = tail; *p != '\0'; p++) {
2413 if (quoted) {
2414 quoted = 0;
2415 } else if (*p == '\\') {
2416 quoted = 1;
2417 if (strchr(separators, p[1]) != NULL) {
2418 break; /* Quoted directory separator. */
2419 }
2420 } else if (strchr(separators, *p) != NULL) {
2421 break; /* Unquoted directory separator. */
2422 } else if (*p == '{') {
2423 openBrace = p;
2424 p++;
2425 if (SkipToChar(&p, "}")) {
2426 closeBrace = p; /* Balanced braces. */
2427 break;
2428 }
2429 Tcl_SetResult(interp, "unmatched open-brace in file name",
2430 TCL_STATIC);
2431 return TCL_ERROR;
2432 } else if (*p == '}') {
2433 Tcl_SetResult(interp, "unmatched close-brace in file name",
2434 TCL_STATIC);
2435 return TCL_ERROR;
2436 }
2437 }
2438
2439 /*
2440 * Substitute the alternate patterns from the braces and recurse.
2441 */
2442
2443 if (openBrace != NULL) {
2444 char *element;
2445 Tcl_DString newName;
2446 Tcl_DStringInit(&newName);
2447
2448 /*
2449 * For each element within in the outermost pair of braces,
2450 * append the element and the remainder to the fixed portion
2451 * before the first brace and recursively call TclDoGlob.
2452 */
2453
2454 Tcl_DStringAppend(&newName, tail, openBrace-tail);
2455 baseLength = Tcl_DStringLength(&newName);
2456 length = Tcl_DStringLength(headPtr);
2457 *closeBrace = '\0';
2458 for (p = openBrace; p != closeBrace; ) {
2459 p++;
2460 element = p;
2461 SkipToChar(&p, ",");
2462 Tcl_DStringSetLength(headPtr, length);
2463 Tcl_DStringSetLength(&newName, baseLength);
2464 Tcl_DStringAppend(&newName, element, p-element);
2465 Tcl_DStringAppend(&newName, closeBrace+1, -1);
2466 result = TclDoGlob(interp, separators, headPtr,
2467 Tcl_DStringValue(&newName), types);
2468 if (result != TCL_OK) {
2469 break;
2470 }
2471 }
2472 *closeBrace = '}';
2473 Tcl_DStringFree(&newName);
2474 return result;
2475 }
2476
2477 /*
2478 * At this point, there are no more brace substitutions to perform on
2479 * this path component. The variable p is pointing at a quoted or
2480 * unquoted directory separator or the end of the string. So we need
2481 * to check for special globbing characters in the current pattern.
2482 * We avoid modifying tail if p is pointing at the end of the string.
2483 */
2484
2485 if (*p != '\0') {
2486
2487 /*
2488 * Note that we are modifying the string in place. This won't work
2489 * if the string is a static.
2490 */
2491
2492 savedChar = *p;
2493 *p = '\0';
2494 firstSpecialChar = strpbrk(tail, "*[]?\\");
2495 *p = savedChar;
2496 } else {
2497 firstSpecialChar = strpbrk(tail, "*[]?\\");
2498 }
2499
2500 if (firstSpecialChar != NULL) {
2501 int ret;
2502 Tcl_Obj *head = Tcl_NewStringObj(Tcl_DStringValue(headPtr),-1);
2503 Tcl_IncrRefCount(head);
2504 /*
2505 * Look for matching files in the given directory. The
2506 * implementation of this function is platform specific. For
2507 * each file that matches, it will add the match onto the
2508 * resultPtr given.
2509 */
2510 if (*p == '\0') {
2511 ret = Tcl_FSMatchInDirectory(interp, Tcl_GetObjResult(interp),
2512 head, tail, types);
2513 } else {
2514 Tcl_Obj* resultPtr;
2515
2516 /*
2517 * We do the recursion ourselves. This makes implementing
2518 * Tcl_FSMatchInDirectory for each filesystem much easier.
2519 */
2520 Tcl_GlobTypeData dirOnly = { TCL_GLOB_TYPE_DIR, 0, NULL, NULL };
2521 char save = *p;
2522
2523 *p = '\0';
2524 resultPtr = Tcl_NewListObj(0, NULL);
2525 ret = Tcl_FSMatchInDirectory(interp, resultPtr,
2526 head, tail, &dirOnly);
2527 *p = save;
2528 if (ret == TCL_OK) {
2529 int resLength;
2530 ret = Tcl_ListObjLength(interp, resultPtr, &resLength);
2531 if (ret == TCL_OK) {
2532 int i;
2533 for (i =0; i< resLength; i++) {
2534 Tcl_Obj *elt;
2535 Tcl_DString ds;
2536 Tcl_ListObjIndex(interp, resultPtr, i, &elt);
2537 Tcl_DStringInit(&ds);
2538 Tcl_DStringAppend(&ds, Tcl_GetString(elt), -1);
2539 if(tclPlatform == TCL_PLATFORM_MAC) {
2540 Tcl_DStringAppend(&ds, ":",1);
2541 } else {
2542 Tcl_DStringAppend(&ds, "/",1);
2543 }
2544 ret = TclDoGlob(interp, separators, &ds, p+1, types);
2545 Tcl_DStringFree(&ds);
2546 if (ret != TCL_OK) {
2547 break;
2548 }
2549 }
2550 }
2551 }
2552 Tcl_DecrRefCount(resultPtr);
2553 }
2554 Tcl_DecrRefCount(head);
2555 return ret;
2556 }
2557 Tcl_DStringAppend(headPtr, tail, p-tail);
2558 if (*p != '\0') {
2559 return TclDoGlob(interp, separators, headPtr, p, types);
2560 } else {
2561 /*
2562 * This is the code path reached by a command like 'glob foo'.
2563 *
2564 * There are no more wildcards in the pattern and no more
2565 * unprocessed characters in the tail, so now we can construct
2566 * the path, and pass it to Tcl_FSMatchInDirectory with an
2567 * empty pattern to verify the existence of the file and check
2568 * it is of the correct type (if a 'types' flag it given -- if
2569 * no such flag was given, we could just use 'Tcl_FSLStat', but
2570 * for simplicity we keep to a common approach).
2571 */
2572
2573 Tcl_Obj *nameObj;
2574
2575 switch (tclPlatform) {
2576 case TCL_PLATFORM_MAC: {
2577 if (strchr(Tcl_DStringValue(headPtr), ':') == NULL) {
2578 Tcl_DStringAppend(headPtr, ":", 1);
2579 }
2580 break;
2581 }
2582 case TCL_PLATFORM_WINDOWS: {
2583 if (Tcl_DStringLength(headPtr) == 0) {
2584 if (((*name == '\\') && (name[1] == '/' || name[1] == '\\'))
2585 || (*name == '/')) {
2586 Tcl_DStringAppend(headPtr, "/", 1);
2587 } else {
2588 Tcl_DStringAppend(headPtr, ".", 1);
2589 }
2590 }
2591 #if defined(__CYGWIN__) && defined(__WIN32__)
2592 {
2593 extern int cygwin_conv_to_win32_path
2594 _ANSI_ARGS_((CONST char *, char *));
2595 char winbuf[MAX_PATH+1];
2596
2597 cygwin_conv_to_win32_path(Tcl_DStringValue(headPtr), winbuf);
2598 Tcl_DStringFree(headPtr);
2599 Tcl_DStringAppend(headPtr, winbuf, -1);
2600 }
2601 #endif /* __CYGWIN__ && __WIN32__ */
2602 /*
2603 * Convert to forward slashes. This is required to pass
2604 * some Tcl tests. We should probably remove the conversions
2605 * here and in tclWinFile.c, since they aren't needed since
2606 * the dropping of support for Win32s.
2607 */
2608 for (p = Tcl_DStringValue(headPtr); *p != '\0'; p++) {
2609 if (*p == '\\') {
2610 *p = '/';
2611 }
2612 }
2613 break;
2614 }
2615 case TCL_PLATFORM_UNIX: {
2616 if (Tcl_DStringLength(headPtr) == 0) {
2617 if ((*name == '\\' && name[1] == '/') || (*name == '/')) {
2618 Tcl_DStringAppend(headPtr, "/", 1);
2619 } else {
2620 Tcl_DStringAppend(headPtr, ".", 1);
2621 }
2622 }
2623 break;
2624 }
2625 }
2626 /* Common for all platforms */
2627 name = Tcl_DStringValue(headPtr);
2628 nameObj = Tcl_NewStringObj(name, Tcl_DStringLength(headPtr));
2629
2630 Tcl_IncrRefCount(nameObj);
2631 Tcl_FSMatchInDirectory(interp, Tcl_GetObjResult(interp), nameObj,
2632 NULL, types);
2633 Tcl_DecrRefCount(nameObj);
2634 return TCL_OK;
2635 }
2636 }
2637
2638
2639 /*
2640 *---------------------------------------------------------------------------
2641 *
2642 * TclFileDirname
2643 *
2644 * This procedure calculates the directory above a given
2645 * path: basically 'file dirname'. It is used both by
2646 * the 'dirname' subcommand of file and by code in tclIOUtil.c.
2647 *
2648 * Results:
2649 * NULL if an error occurred, otherwise a Tcl_Obj owned by
2650 * the caller (i.e. most likely with refCount 1).
2651 *
2652 * Side effects:
2653 * None.
2654 *
2655 *---------------------------------------------------------------------------
2656 */
2657
2658 Tcl_Obj*
2659 TclFileDirname(interp, pathPtr)
2660 Tcl_Interp *interp; /* Used for error reporting */
2661 Tcl_Obj *pathPtr; /* Path to take dirname of */
2662 {
2663 int splitElements;
2664 Tcl_Obj *splitPtr;
2665 Tcl_Obj *splitResultPtr = NULL;
2666
2667 /*
2668 * The behaviour we want here is slightly different to
2669 * the standard Tcl_FSSplitPath in the handling of home
2670 * directories; Tcl_FSSplitPath preserves the "~" while
2671 * this code computes the actual full path name, if we
2672 * had just a single component.
2673 */
2674 splitPtr = Tcl_FSSplitPath(pathPtr, &splitElements);
2675 if ((splitElements == 1) && (Tcl_GetString(pathPtr)[0] == '~')) {
2676 Tcl_DecrRefCount(splitPtr);
2677 splitPtr = Tcl_FSGetNormalizedPath(interp, pathPtr);
2678 if (splitPtr == NULL) {
2679 return NULL;
2680 }
2681 splitPtr = Tcl_FSSplitPath(splitPtr, &splitElements);
2682 }
2683
2684 /*
2685 * Return all but the last component. If there is only one
2686 * component, return it if the path was non-relative, otherwise
2687 * return the current directory.
2688 */
2689
2690 if (splitElements > 1) {
2691 splitResultPtr = Tcl_FSJoinPath(splitPtr, splitElements - 1);
2692 } else if (splitElements == 0 ||
2693 (Tcl_FSGetPathType(pathPtr) == TCL_PATH_RELATIVE)) {
2694 splitResultPtr = Tcl_NewStringObj(
2695 ((tclPlatform == TCL_PLATFORM_MAC) ? ":" : "."), 1);
2696 } else {
2697 Tcl_ListObjIndex(NULL, splitPtr, 0, &splitResultPtr);
2698 }
2699 Tcl_IncrRefCount(splitResultPtr);
2700 Tcl_DecrRefCount(splitPtr);
2701 return splitResultPtr;
2702 }
2703
2704 /*
2705 *---------------------------------------------------------------------------
2706 *
2707 * Tcl_AllocStatBuf
2708 *
2709 * This procedure allocates a Tcl_StatBuf on the heap. It exists
2710 * so that extensions may be used unchanged on systems where
2711 * largefile support is optional.
2712 *
2713 * Results:
2714 * A pointer to a Tcl_StatBuf which may be deallocated by being
2715 * passed to ckfree().
2716 *
2717 * Side effects:
2718 * None.
2719 *
2720 *---------------------------------------------------------------------------
2721 */
2722
2723 Tcl_StatBuf *
2724 Tcl_AllocStatBuf() {
2725 return (Tcl_StatBuf *) ckalloc(sizeof(Tcl_StatBuf));
2726 }