Debian Codegraph @

pTk/mTk/tclWin/tclWinFCmd.c

raw
1 /*
2 * tclWinFCmd.c
3 *
4 * This file implements the Windows specific portion of file manipulation
5 * subcommands of the "file" command.
6 *
7 * Copyright (c) 1996-1998 Sun Microsystems, Inc.
8 *
9 * See the file "license.terms" for information on usage and redistribution
10 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
11 *
12 * RCS: @(#) $Id: tclWinFCmd.c,v 1.35.2.1 2003/10/03 17:45:37 vincentdarley Exp $
13 */
14
15 #include "tclWinInt.h"
16
17 /*
18 * The following constants specify the type of callback when
19 * TraverseWinTree() calls the traverseProc()
20 */
21
22 #define DOTREE_PRED 1 /* pre-order directory */
23 #define DOTREE_POSTD 2 /* post-order directory */
24 #define DOTREE_F 3 /* regular file */
25
26 /*
27 * Callbacks for file attributes code.
28 */
29
30 static int GetWinFileAttributes _ANSI_ARGS_((Tcl_Interp *interp,
31 int objIndex, Tcl_Obj *fileName,
32 Tcl_Obj **attributePtrPtr));
33 static int GetWinFileLongName _ANSI_ARGS_((Tcl_Interp *interp,
34 int objIndex, Tcl_Obj *fileName,
35 Tcl_Obj **attributePtrPtr));
36 static int GetWinFileShortName _ANSI_ARGS_((Tcl_Interp *interp,
37 int objIndex, Tcl_Obj *fileName,
38 Tcl_Obj **attributePtrPtr));
39 static int SetWinFileAttributes _ANSI_ARGS_((Tcl_Interp *interp,
40 int objIndex, Tcl_Obj *fileName,
41 Tcl_Obj *attributePtr));
42 static int CannotSetAttribute _ANSI_ARGS_((Tcl_Interp *interp,
43 int objIndex, Tcl_Obj *fileName,
44 Tcl_Obj *attributePtr));
45
46 /*
47 * Constants and variables necessary for file attributes subcommand.
48 */
49
50 enum {
51 WIN_ARCHIVE_ATTRIBUTE,
52 WIN_HIDDEN_ATTRIBUTE,
53 WIN_LONGNAME_ATTRIBUTE,
54 WIN_READONLY_ATTRIBUTE,
55 WIN_SHORTNAME_ATTRIBUTE,
56 WIN_SYSTEM_ATTRIBUTE
57 };
58
59 static int attributeArray[] = {FILE_ATTRIBUTE_ARCHIVE, FILE_ATTRIBUTE_HIDDEN,
60 0, FILE_ATTRIBUTE_READONLY, 0, FILE_ATTRIBUTE_SYSTEM};
61
62
63 CONST char *tclpFileAttrStrings[] = {
64 "-archive", "-hidden", "-longname", "-readonly",
65 "-shortname", "-system", (char *) NULL
66 };
67
68 CONST TclFileAttrProcs tclpFileAttrProcs[] = {
69 {GetWinFileAttributes, SetWinFileAttributes},
70 {GetWinFileAttributes, SetWinFileAttributes},
71 {GetWinFileLongName, CannotSetAttribute},
72 {GetWinFileAttributes, SetWinFileAttributes},
73 {GetWinFileShortName, CannotSetAttribute},
74 {GetWinFileAttributes, SetWinFileAttributes}};
75
76 #if defined(HAVE_NO_SEH) && defined(TCL_MEM_DEBUG)
77 static void *INITIAL_ESP,
78 *INITIAL_EBP,
79 *INITIAL_HANDLER,
80 *RESTORED_ESP,
81 *RESTORED_EBP,
82 *RESTORED_HANDLER;
83 #endif /* HAVE_NO_SEH && TCL_MEM_DEBUG */
84
85 /*
86 * Prototype for the TraverseWinTree callback function.
87 */
88
89 typedef int (TraversalProc)(CONST TCHAR *srcPtr, CONST TCHAR *dstPtr,
90 int type, Tcl_DString *errorPtr);
91
92 /*
93 * Declarations for local procedures defined in this file:
94 */
95
96 static void StatError(Tcl_Interp *interp, Tcl_Obj *fileName);
97 static int ConvertFileNameFormat(Tcl_Interp *interp,
98 int objIndex, Tcl_Obj *fileName, int longShort,
99 Tcl_Obj **attributePtrPtr);
100 static int DoCopyFile(CONST TCHAR *srcPtr, CONST TCHAR *dstPtr);
101 static int DoCreateDirectory(CONST TCHAR *pathPtr);
102 static int DoRemoveJustDirectory(CONST TCHAR *nativeSrc,
103 int ignoreError, Tcl_DString *errorPtr);
104 static int DoRemoveDirectory(Tcl_DString *pathPtr, int recursive,
105 Tcl_DString *errorPtr);
106 static int DoRenameFile(CONST TCHAR *nativeSrc, CONST TCHAR *dstPtr);
107 static int TraversalCopy(CONST TCHAR *srcPtr, CONST TCHAR *dstPtr,
108 int type, Tcl_DString *errorPtr);
109 static int TraversalDelete(CONST TCHAR *srcPtr, CONST TCHAR *dstPtr,
110 int type, Tcl_DString *errorPtr);
111 static int TraverseWinTree(TraversalProc *traverseProc,
112 Tcl_DString *sourcePtr, Tcl_DString *dstPtr,
113 Tcl_DString *errorPtr);
114
115
116 /*
117 *---------------------------------------------------------------------------
118 *
119 * TclpObjRenameFile, DoRenameFile --
120 *
121 * Changes the name of an existing file or directory, from src to dst.
122 * If src and dst refer to the same file or directory, does nothing
123 * and returns success. Otherwise if dst already exists, it will be
124 * deleted and replaced by src subject to the following conditions:
125 * If src is a directory, dst may be an empty directory.
126 * If src is a file, dst may be a file.
127 * In any other situation where dst already exists, the rename will
128 * fail.
129 *
130 * Results:
131 * If the file or directory was successfully renamed, returns TCL_OK.
132 * Otherwise the return value is TCL_ERROR and errno is set to
133 * indicate the error. Some possible values for errno are:
134 *
135 * ENAMETOOLONG: src or dst names are too long.
136 * EACCES: src or dst parent directory can't be read and/or written.
137 * EEXIST: dst is a non-empty directory.
138 * EINVAL: src is a root directory or dst is a subdirectory of src.
139 * EISDIR: dst is a directory, but src is not.
140 * ENOENT: src doesn't exist. src or dst is "".
141 * ENOTDIR: src is a directory, but dst is not.
142 * EXDEV: src and dst are on different filesystems.
143 *
144 * EACCES: exists an open file already referring to src or dst.
145 * EACCES: src or dst specify the current working directory (NT).
146 * EACCES: src specifies a char device (nul:, com1:, etc.)
147 * EEXIST: dst specifies a char device (nul:, com1:, etc.) (NT)
148 * EACCES: dst specifies a char device (nul:, com1:, etc.) (95)
149 *
150 * Side effects:
151 * The implementation supports cross-filesystem renames of files,
152 * but the caller should be prepared to emulate cross-filesystem
153 * renames of directories if errno is EXDEV.
154 *
155 *---------------------------------------------------------------------------
156 */
157
158 int
159 TclpObjRenameFile(srcPathPtr, destPathPtr)
160 Tcl_Obj *srcPathPtr;
161 Tcl_Obj *destPathPtr;
162 {
163 return DoRenameFile(Tcl_FSGetNativePath(srcPathPtr),
164 Tcl_FSGetNativePath(destPathPtr));
165 }
166
167 static int
168 DoRenameFile(
169 CONST TCHAR *nativeSrc, /* Pathname of file or dir to be renamed
170 * (native). */
171 CONST TCHAR *nativeDst) /* New pathname for file or directory
172 * (native). */
173 {
174 DWORD srcAttr, dstAttr;
175 int retval = -1;
176
177 /*
178 * The MoveFile API acts differently under Win95/98 and NT
179 * WRT NULL and "". Avoid passing these values.
180 */
181
182 if (nativeSrc == NULL || nativeSrc[0] == '\0' ||
183 nativeDst == NULL || nativeDst[0] == '\0') {
184 Tcl_SetErrno(ENOENT);
185 return TCL_ERROR;
186 }
187
188 /*
189 * The MoveFile API would throw an exception under NT
190 * if one of the arguments is a char block device.
191 */
192
193 #ifdef HAVE_NO_SEH
194 # ifdef TCL_MEM_DEBUG
195 __asm__ __volatile__ (
196 "movl %%esp, %0" "\n\t"
197 "movl %%ebp, %1" "\n\t"
198 "movl %%fs:0, %2" "\n\t"
199 : "=m"(INITIAL_ESP),
200 "=m"(INITIAL_EBP),
201 "=r"(INITIAL_HANDLER) );
202 # endif /* TCL_MEM_DEBUG */
203
204 __asm__ __volatile__ (
205 "pushl %ebp" "\n\t"
206 "pushl $__except_dorenamefile_handler" "\n\t"
207 "pushl %fs:0" "\n\t"
208 "movl %esp, %fs:0");
209 #else
210 __try {
211 #endif /* HAVE_NO_SEH */
212 if ((*tclWinProcs->moveFileProc)(nativeSrc, nativeDst) != FALSE) {
213 retval = TCL_OK;
214 }
215 #ifdef HAVE_NO_SEH
216 __asm__ __volatile__ (
217 "jmp dorenamefile_pop" "\n"
218 "dorenamefile_reentry:" "\n\t"
219 "movl %%fs:0, %%eax" "\n\t"
220 "movl 0x8(%%eax), %%esp" "\n\t"
221 "movl 0x8(%%esp), %%ebp" "\n"
222 "dorenamefile_pop:" "\n\t"
223 "movl (%%esp), %%eax" "\n\t"
224 "movl %%eax, %%fs:0" "\n\t"
225 "add $12, %%esp" "\n\t"
226 :
227 :
228 : "%eax");
229
230 # ifdef TCL_MEM_DEBUG
231 __asm__ __volatile__ (
232 "movl %%esp, %0" "\n\t"
233 "movl %%ebp, %1" "\n\t"
234 "movl %%fs:0, %2" "\n\t"
235 : "=m"(RESTORED_ESP),
236 "=m"(RESTORED_EBP),
237 "=r"(RESTORED_HANDLER) );
238
239 if (INITIAL_ESP != RESTORED_ESP)
240 panic("ESP restored incorrectly");
241 if (INITIAL_EBP != RESTORED_EBP)
242 panic("EBP restored incorrectly");
243 if (INITIAL_HANDLER != RESTORED_HANDLER)
244 panic("HANDLER restored incorrectly");
245 # endif /* TCL_MEM_DEBUG */
246 #else
247 } __except (EXCEPTION_EXECUTE_HANDLER) {}
248 #endif /* HAVE_NO_SEH */
249
250 /*
251 * Avoid using control flow statements in the SEH guarded block!
252 */
253 if (retval != -1)
254 return retval;
255
256 TclWinConvertError(GetLastError());
257
258 srcAttr = (*tclWinProcs->getFileAttributesProc)(nativeSrc);
259 dstAttr = (*tclWinProcs->getFileAttributesProc)(nativeDst);
260 if (srcAttr == 0xffffffff) {
261 if ((*tclWinProcs->getFullPathNameProc)(nativeSrc, 0, NULL, NULL) >= MAX_PATH) {
262 errno = ENAMETOOLONG;
263 return TCL_ERROR;
264 }
265 srcAttr = 0;
266 }
267 if (dstAttr == 0xffffffff) {
268 if ((*tclWinProcs->getFullPathNameProc)(nativeDst, 0, NULL, NULL) >= MAX_PATH) {
269 errno = ENAMETOOLONG;
270 return TCL_ERROR;
271 }
272 dstAttr = 0;
273 }
274
275 if (errno == EBADF) {
276 errno = EACCES;
277 return TCL_ERROR;
278 }
279 if (errno == EACCES) {
280 decode:
281 if (srcAttr & FILE_ATTRIBUTE_DIRECTORY) {
282 TCHAR *nativeSrcRest, *nativeDstRest;
283 CONST char **srcArgv, **dstArgv;
284 int size, srcArgc, dstArgc;
285 WCHAR nativeSrcPath[MAX_PATH];
286 WCHAR nativeDstPath[MAX_PATH];
287 Tcl_DString srcString, dstString;
288 CONST char *src, *dst;
289
290 size = (*tclWinProcs->getFullPathNameProc)(nativeSrc, MAX_PATH,
291 nativeSrcPath, &nativeSrcRest);
292 if ((size == 0) || (size > MAX_PATH)) {
293 return TCL_ERROR;
294 }
295 size = (*tclWinProcs->getFullPathNameProc)(nativeDst, MAX_PATH,
296 nativeDstPath, &nativeDstRest);
297 if ((size == 0) || (size > MAX_PATH)) {
298 return TCL_ERROR;
299 }
300 (*tclWinProcs->charLowerProc)((TCHAR *) nativeSrcPath);
301 (*tclWinProcs->charLowerProc)((TCHAR *) nativeDstPath);
302
303 src = Tcl_WinTCharToUtf((TCHAR *) nativeSrcPath, -1, &srcString);
304 dst = Tcl_WinTCharToUtf((TCHAR *) nativeDstPath, -1, &dstString);
305 if (strncmp(src, dst, (size_t) Tcl_DStringLength(&srcString)) == 0) {
306 /*
307 * Trying to move a directory into itself.
308 */
309
310 errno = EINVAL;
311 Tcl_DStringFree(&srcString);
312 Tcl_DStringFree(&dstString);
313 return TCL_ERROR;
314 }
315 Tcl_SplitPath(src, &srcArgc, &srcArgv);
316 Tcl_SplitPath(dst, &dstArgc, &dstArgv);
317 Tcl_DStringFree(&srcString);
318 Tcl_DStringFree(&dstString);
319
320 if (srcArgc == 1) {
321 /*
322 * They are trying to move a root directory. Whether
323 * or not it is across filesystems, this cannot be
324 * done.
325 */
326
327 Tcl_SetErrno(EINVAL);
328 } else if ((srcArgc > 0) && (dstArgc > 0) &&
329 (strcmp(srcArgv[0], dstArgv[0]) != 0)) {
330 /*
331 * If src is a directory and dst filesystem != src
332 * filesystem, errno should be EXDEV. It is very
333 * important to get this behavior, so that the caller
334 * can respond to a cross filesystem rename by
335 * simulating it with copy and delete. The MoveFile
336 * system call already handles the case of moving a
337 * file between filesystems.
338 */
339
340 Tcl_SetErrno(EXDEV);
341 }
342
343 ckfree((char *) srcArgv);
344 ckfree((char *) dstArgv);
345 }
346
347 /*
348 * Other types of access failure is that dst is a read-only
349 * filesystem, that an open file referred to src or dest, or that
350 * src or dest specified the current working directory on the
351 * current filesystem. EACCES is returned for those cases.
352 */
353
354 } else if (Tcl_GetErrno() == EEXIST) {
355 /*
356 * Reports EEXIST any time the target already exists. If it makes
357 * sense, remove the old file and try renaming again.
358 */
359
360 if (srcAttr & FILE_ATTRIBUTE_DIRECTORY) {
361 if (dstAttr & FILE_ATTRIBUTE_DIRECTORY) {
362 /*
363 * Overwrite empty dst directory with src directory. The
364 * following call will remove an empty directory. If it
365 * fails, it's because it wasn't empty.
366 */
367
368 if (DoRemoveJustDirectory(nativeDst, 0, NULL) == TCL_OK) {
369 /*
370 * Now that that empty directory is gone, we can try
371 * renaming again. If that fails, we'll put this empty
372 * directory back, for completeness.
373 */
374
375 if ((*tclWinProcs->moveFileProc)(nativeSrc, nativeDst) != FALSE) {
376 return TCL_OK;
377 }
378
379 /*
380 * Some new error has occurred. Don't know what it
381 * could be, but report this one.
382 */
383
384 TclWinConvertError(GetLastError());
385 (*tclWinProcs->createDirectoryProc)(nativeDst, NULL);
386 (*tclWinProcs->setFileAttributesProc)(nativeDst, dstAttr);
387 if (Tcl_GetErrno() == EACCES) {
388 /*
389 * Decode the EACCES to a more meaningful error.
390 */
391
392 goto decode;
393 }
394 }
395 } else { /* (dstAttr & FILE_ATTRIBUTE_DIRECTORY) == 0 */
396 Tcl_SetErrno(ENOTDIR);
397 }
398 } else { /* (srcAttr & FILE_ATTRIBUTE_DIRECTORY) == 0 */
399 if (dstAttr & FILE_ATTRIBUTE_DIRECTORY) {
400 Tcl_SetErrno(EISDIR);
401 } else {
402 /*
403 * Overwrite existing file by:
404 *
405 * 1. Rename existing file to temp name.
406 * 2. Rename old file to new name.
407 * 3. If success, delete temp file. If failure,
408 * put temp file back to old name.
409 */
410
411 TCHAR *nativeRest, *nativeTmp, *nativePrefix;
412 int result, size;
413 WCHAR tempBuf[MAX_PATH];
414
415 size = (*tclWinProcs->getFullPathNameProc)(nativeDst, MAX_PATH,
416 tempBuf, &nativeRest);
417 if ((size == 0) || (size > MAX_PATH) || (nativeRest == NULL)) {
418 return TCL_ERROR;
419 }
420 nativeTmp = (TCHAR *) tempBuf;
421 ((char *) nativeRest)[0] = '\0';
422 ((char *) nativeRest)[1] = '\0'; /* In case it's Unicode. */
423
424 result = TCL_ERROR;
425 nativePrefix = (tclWinProcs->useWide)
426 ? (TCHAR *) L"tclr" : (TCHAR *) "tclr";
427 if ((*tclWinProcs->getTempFileNameProc)(nativeTmp,
428 nativePrefix, 0, tempBuf) != 0) {
429 /*
430 * Strictly speaking, need the following DeleteFile and
431 * MoveFile to be joined as an atomic operation so no
432 * other app comes along in the meantime and creates the
433 * same temp file.
434 */
435
436 nativeTmp = (TCHAR *) tempBuf;
437 (*tclWinProcs->deleteFileProc)(nativeTmp);
438 if ((*tclWinProcs->moveFileProc)(nativeDst, nativeTmp) != FALSE) {
439 if ((*tclWinProcs->moveFileProc)(nativeSrc, nativeDst) != FALSE) {
440 (*tclWinProcs->setFileAttributesProc)(nativeTmp,
441 FILE_ATTRIBUTE_NORMAL);
442 (*tclWinProcs->deleteFileProc)(nativeTmp);
443 return TCL_OK;
444 } else {
445 (*tclWinProcs->deleteFileProc)(nativeDst);
446 (*tclWinProcs->moveFileProc)(nativeTmp, nativeDst);
447 }
448 }
449
450 /*
451 * Can't backup dst file or move src file. Return that
452 * error. Could happen if an open file refers to dst.
453 */
454
455 TclWinConvertError(GetLastError());
456 if (Tcl_GetErrno() == EACCES) {
457 /*
458 * Decode the EACCES to a more meaningful error.
459 */
460
461 goto decode;
462 }
463 }
464 return result;
465 }
466 }
467 }
468 return TCL_ERROR;
469 }
470 #ifdef HAVE_NO_SEH
471 static
472 __attribute__ ((cdecl))
473 EXCEPTION_DISPOSITION
474 _except_dorenamefile_handler(
475 struct _EXCEPTION_RECORD *ExceptionRecord,
476 void *EstablisherFrame,
477 struct _CONTEXT *ContextRecord,
478 void *DispatcherContext)
479 {
480 __asm__ __volatile__ (
481 "jmp dorenamefile_reentry");
482 /* Nuke compiler warning about unused static function */
483 _except_dorenamefile_handler(NULL, NULL, NULL, NULL);
484 return 0; /* Function does not return */
485 }
486 #endif /* HAVE_NO_SEH */
487
488 /*
489 *---------------------------------------------------------------------------
490 *
491 * TclpObjCopyFile, DoCopyFile --
492 *
493 * Copy a single file (not a directory). If dst already exists and
494 * is not a directory, it is removed.
495 *
496 * Results:
497 * If the file was successfully copied, returns TCL_OK. Otherwise
498 * the return value is TCL_ERROR and errno is set to indicate the
499 * error. Some possible values for errno are:
500 *
501 * EACCES: src or dst parent directory can't be read and/or written.
502 * EISDIR: src or dst is a directory.
503 * ENOENT: src doesn't exist. src or dst is "".
504 *
505 * EACCES: exists an open file already referring to dst (95).
506 * EACCES: src specifies a char device (nul:, com1:, etc.) (NT)
507 * ENOENT: src specifies a char device (nul:, com1:, etc.) (95)
508 *
509 * Side effects:
510 * It is not an error to copy to a char device.
511 *
512 *---------------------------------------------------------------------------
513 */
514
515 int
516 TclpObjCopyFile(srcPathPtr, destPathPtr)
517 Tcl_Obj *srcPathPtr;
518 Tcl_Obj *destPathPtr;
519 {
520 return DoCopyFile(Tcl_FSGetNativePath(srcPathPtr),
521 Tcl_FSGetNativePath(destPathPtr));
522 }
523
524 static int
525 DoCopyFile(
526 CONST TCHAR *nativeSrc, /* Pathname of file to be copied (native). */
527 CONST TCHAR *nativeDst) /* Pathname of file to copy to (native). */
528 {
529 int retval = -1;
530
531 /*
532 * The CopyFile API acts differently under Win95/98 and NT
533 * WRT NULL and "". Avoid passing these values.
534 */
535
536 if (nativeSrc == NULL || nativeSrc[0] == '\0' ||
537 nativeDst == NULL || nativeDst[0] == '\0') {
538 Tcl_SetErrno(ENOENT);
539 return TCL_ERROR;
540 }
541
542 /*
543 * The CopyFile API would throw an exception under NT if one
544 * of the arguments is a char block device.
545 */
546
547 #ifdef HAVE_NO_SEH
548 # ifdef TCL_MEM_DEBUG
549 __asm__ __volatile__ (
550 "movl %%esp, %0" "\n\t"
551 "movl %%ebp, %1" "\n\t"
552 "movl %%fs:0, %2" "\n\t"
553 : "=m"(INITIAL_ESP),
554 "=m"(INITIAL_EBP),
555 "=r"(INITIAL_HANDLER) );
556 # endif /* TCL_MEM_DEBUG */
557
558 __asm__ __volatile__ (
559 "pushl %ebp" "\n\t"
560 "pushl $__except_docopyfile_handler" "\n\t"
561 "pushl %fs:0" "\n\t"
562 "movl %esp, %fs:0");
563 #else
564 __try {
565 #endif /* HAVE_NO_SEH */
566 if ((*tclWinProcs->copyFileProc)(nativeSrc, nativeDst, 0) != FALSE) {
567 retval = TCL_OK;
568 }
569 #ifdef HAVE_NO_SEH
570 __asm__ __volatile__ (
571 "jmp docopyfile_pop" "\n"
572 "docopyfile_reentry:" "\n\t"
573 "movl %%fs:0, %%eax" "\n\t"
574 "movl 0x8(%%eax), %%esp" "\n\t"
575 "movl 0x8(%%esp), %%ebp" "\n"
576 "docopyfile_pop:" "\n\t"
577 "movl (%%esp), %%eax" "\n\t"
578 "movl %%eax, %%fs:0" "\n\t"
579 "add $12, %%esp" "\n\t"
580 :
581 :
582 : "%eax");
583
584 # ifdef TCL_MEM_DEBUG
585 __asm__ __volatile__ (
586 "movl %%esp, %0" "\n\t"
587 "movl %%ebp, %1" "\n\t"
588 "movl %%fs:0, %2" "\n\t"
589 : "=m"(RESTORED_ESP),
590 "=m"(RESTORED_EBP),
591 "=r"(RESTORED_HANDLER) );
592
593 if (INITIAL_ESP != RESTORED_ESP)
594 panic("ESP restored incorrectly");
595 if (INITIAL_EBP != RESTORED_EBP)
596 panic("EBP restored incorrectly");
597 if (INITIAL_HANDLER != RESTORED_HANDLER)
598 panic("HANDLER restored incorrectly");
599 # endif /* TCL_MEM_DEBUG */
600 #else
601 } __except (EXCEPTION_EXECUTE_HANDLER) {}
602 #endif /* HAVE_NO_SEH */
603
604 /*
605 * Avoid using control flow statements in the SEH guarded block!
606 */
607 if (retval != -1)
608 return retval;
609
610 TclWinConvertError(GetLastError());
611 if (Tcl_GetErrno() == EBADF) {
612 Tcl_SetErrno(EACCES);
613 return TCL_ERROR;
614 }
615 if (Tcl_GetErrno() == EACCES) {
616 DWORD srcAttr, dstAttr;
617
618 srcAttr = (*tclWinProcs->getFileAttributesProc)(nativeSrc);
619 dstAttr = (*tclWinProcs->getFileAttributesProc)(nativeDst);
620 if (srcAttr != 0xffffffff) {
621 if (dstAttr == 0xffffffff) {
622 dstAttr = 0;
623 }
624 if ((srcAttr & FILE_ATTRIBUTE_DIRECTORY) ||
625 (dstAttr & FILE_ATTRIBUTE_DIRECTORY)) {
626 if (srcAttr & FILE_ATTRIBUTE_REPARSE_POINT) {
627 /* Source is a symbolic link -- copy it */
628 if (TclWinSymLinkCopyDirectory(nativeSrc, nativeDst) == 0) {
629 return TCL_OK;
630 }
631 }
632 Tcl_SetErrno(EISDIR);
633 }
634 if (dstAttr & FILE_ATTRIBUTE_READONLY) {
635 (*tclWinProcs->setFileAttributesProc)(nativeDst,
636 dstAttr & ~((DWORD)FILE_ATTRIBUTE_READONLY));
637 if ((*tclWinProcs->copyFileProc)(nativeSrc, nativeDst, 0) != FALSE) {
638 return TCL_OK;
639 }
640 /*
641 * Still can't copy onto dst. Return that error, and
642 * restore attributes of dst.
643 */
644
645 TclWinConvertError(GetLastError());
646 (*tclWinProcs->setFileAttributesProc)(nativeDst, dstAttr);
647 }
648 }
649 }
650 return TCL_ERROR;
651 }
652 #ifdef HAVE_NO_SEH
653 static
654 __attribute__ ((cdecl))
655 EXCEPTION_DISPOSITION
656 _except_docopyfile_handler(
657 struct _EXCEPTION_RECORD *ExceptionRecord,
658 void *EstablisherFrame,
659 struct _CONTEXT *ContextRecord,
660 void *DispatcherContext)
661 {
662 __asm__ __volatile__ (
663 "jmp docopyfile_reentry");
664 _except_docopyfile_handler(NULL,NULL,NULL,NULL);
665 return 0; /* Function does not return */
666 }
667 #endif /* HAVE_NO_SEH */
668
669 /*
670 *---------------------------------------------------------------------------
671 *
672 * TclpObjDeleteFile, TclpDeleteFile --
673 *
674 * Removes a single file (not a directory).
675 *
676 * Results:
677 * If the file was successfully deleted, returns TCL_OK. Otherwise
678 * the return value is TCL_ERROR and errno is set to indicate the
679 * error. Some possible values for errno are:
680 *
681 * EACCES: a parent directory can't be read and/or written.
682 * EISDIR: path is a directory.
683 * ENOENT: path doesn't exist or is "".
684 *
685 * EACCES: exists an open file already referring to path.
686 * EACCES: path is a char device (nul:, com1:, etc.)
687 *
688 * Side effects:
689 * The file is deleted, even if it is read-only.
690 *
691 *---------------------------------------------------------------------------
692 */
693
694 int
695 TclpObjDeleteFile(pathPtr)
696 Tcl_Obj *pathPtr;
697 {
698 return TclpDeleteFile(Tcl_FSGetNativePath(pathPtr));
699 }
700
701 int
702 TclpDeleteFile(
703 CONST TCHAR *nativePath) /* Pathname of file to be removed (native). */
704 {
705 DWORD attr;
706
707 /*
708 * The DeleteFile API acts differently under Win95/98 and NT
709 * WRT NULL and "". Avoid passing these values.
710 */
711
712 if (nativePath == NULL || nativePath[0] == '\0') {
713 Tcl_SetErrno(ENOENT);
714 return TCL_ERROR;
715 }
716
717 if ((*tclWinProcs->deleteFileProc)(nativePath) != FALSE) {
718 return TCL_OK;
719 }
720 TclWinConvertError(GetLastError());
721
722 if (Tcl_GetErrno() == EACCES) {
723 attr = (*tclWinProcs->getFileAttributesProc)(nativePath);
724 if (attr != 0xffffffff) {
725 if (attr & FILE_ATTRIBUTE_DIRECTORY) {
726 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
727 /* It is a symbolic link -- remove it */
728 if (TclWinSymLinkDelete(nativePath, 0) == 0) {
729 return TCL_OK;
730 }
731 }
732
733 /*
734 * If we fall through here, it is a directory.
735 *
736 * Windows NT reports removing a directory as EACCES instead
737 * of EISDIR.
738 */
739
740 Tcl_SetErrno(EISDIR);
741 } else if (attr & FILE_ATTRIBUTE_READONLY) {
742 int res = (*tclWinProcs->setFileAttributesProc)(nativePath,
743 attr & ~((DWORD)FILE_ATTRIBUTE_READONLY));
744 if ((res != 0) && ((*tclWinProcs->deleteFileProc)(nativePath)
745 != FALSE)) {
746 return TCL_OK;
747 }
748 TclWinConvertError(GetLastError());
749 if (res != 0) {
750 (*tclWinProcs->setFileAttributesProc)(nativePath, attr);
751 }
752 }
753 }
754 } else if (Tcl_GetErrno() == ENOENT) {
755 attr = (*tclWinProcs->getFileAttributesProc)(nativePath);
756 if (attr != 0xffffffff) {
757 if (attr & FILE_ATTRIBUTE_DIRECTORY) {
758 /*
759 * Windows 95 reports removing a directory as ENOENT instead
760 * of EISDIR.
761 */
762
763 Tcl_SetErrno(EISDIR);
764 }
765 }
766 } else if (Tcl_GetErrno() == EINVAL) {
767 /*
768 * Windows NT reports removing a char device as EINVAL instead of
769 * EACCES.
770 */
771
772 Tcl_SetErrno(EACCES);
773 }
774
775 return TCL_ERROR;
776 }
777
778 /*
779 *---------------------------------------------------------------------------
780 *
781 * TclpObjCreateDirectory --
782 *
783 * Creates the specified directory. All parent directories of the
784 * specified directory must already exist. The directory is
785 * automatically created with permissions so that user can access
786 * the new directory and create new files or subdirectories in it.
787 *
788 * Results:
789 * If the directory was successfully created, returns TCL_OK.
790 * Otherwise the return value is TCL_ERROR and errno is set to
791 * indicate the error. Some possible values for errno are:
792 *
793 * EACCES: a parent directory can't be read and/or written.
794 * EEXIST: path already exists.
795 * ENOENT: a parent directory doesn't exist.
796 *
797 * Side effects:
798 * A directory is created.
799 *
800 *---------------------------------------------------------------------------
801 */
802
803 int
804 TclpObjCreateDirectory(pathPtr)
805 Tcl_Obj *pathPtr;
806 {
807 return DoCreateDirectory(Tcl_FSGetNativePath(pathPtr));
808 }
809
810 static int
811 DoCreateDirectory(
812 CONST TCHAR *nativePath) /* Pathname of directory to create (native). */
813 {
814 DWORD error;
815 if ((*tclWinProcs->createDirectoryProc)(nativePath, NULL) == 0) {
816 error = GetLastError();
817 TclWinConvertError(error);
818 return TCL_ERROR;
819 }
820 return TCL_OK;
821 }
822
823 /*
824 *---------------------------------------------------------------------------
825 *
826 * TclpObjCopyDirectory --
827 *
828 * Recursively copies a directory. The target directory dst must
829 * not already exist. Note that this function does not merge two
830 * directory hierarchies, even if the target directory is an an
831 * empty directory.
832 *
833 * Results:
834 * If the directory was successfully copied, returns TCL_OK.
835 * Otherwise the return value is TCL_ERROR, errno is set to indicate
836 * the error, and the pathname of the file that caused the error
837 * is stored in errorPtr. See TclpCreateDirectory and TclpCopyFile
838 * for a description of possible values for errno.
839 *
840 * Side effects:
841 * An exact copy of the directory hierarchy src will be created
842 * with the name dst. If an error occurs, the error will
843 * be returned immediately, and remaining files will not be
844 * processed.
845 *
846 *---------------------------------------------------------------------------
847 */
848
849 int
850 TclpObjCopyDirectory(srcPathPtr, destPathPtr, errorPtr)
851 Tcl_Obj *srcPathPtr;
852 Tcl_Obj *destPathPtr;
853 Tcl_Obj **errorPtr;
854 {
855 Tcl_DString ds;
856 Tcl_DString srcString, dstString;
857 Tcl_Obj *normSrcPtr, *normDestPtr;
858 int ret;
859
860 normSrcPtr = Tcl_FSGetNormalizedPath(NULL,srcPathPtr);
861 Tcl_WinUtfToTChar(Tcl_GetString(normSrcPtr), -1, &srcString);
862 normDestPtr = Tcl_FSGetNormalizedPath(NULL,destPathPtr);
863 Tcl_WinUtfToTChar(Tcl_GetString(normDestPtr), -1, &dstString);
864
865 ret = TraverseWinTree(TraversalCopy, &srcString, &dstString, &ds);
866
867 Tcl_DStringFree(&srcString);
868 Tcl_DStringFree(&dstString);
869
870 if (ret != TCL_OK) {
871 if (!strcmp(Tcl_DStringValue(&ds), Tcl_GetString(normSrcPtr))) {
872 *errorPtr = srcPathPtr;
873 } else if (!strcmp(Tcl_DStringValue(&ds), Tcl_GetString(normDestPtr))) {
874 *errorPtr = destPathPtr;
875 } else {
876 *errorPtr = Tcl_NewStringObj(Tcl_DStringValue(&ds), -1);
877 }
878 Tcl_DStringFree(&ds);
879 Tcl_IncrRefCount(*errorPtr);
880 }
881 return ret;
882 }
883
884 /*
885 *----------------------------------------------------------------------
886 *
887 * TclpObjRemoveDirectory, DoRemoveDirectory --
888 *
889 * Removes directory (and its contents, if the recursive flag is set).
890 *
891 * Results:
892 * If the directory was successfully removed, returns TCL_OK.
893 * Otherwise the return value is TCL_ERROR, errno is set to indicate
894 * the error, and the pathname of the file that caused the error
895 * is stored in errorPtr. Some possible values for errno are:
896 *
897 * EACCES: path directory can't be read and/or written.
898 * EEXIST: path is a non-empty directory.
899 * EINVAL: path is root directory or current directory.
900 * ENOENT: path doesn't exist or is "".
901 * ENOTDIR: path is not a directory.
902 *
903 * EACCES: path is a char device (nul:, com1:, etc.) (95)
904 * EINVAL: path is a char device (nul:, com1:, etc.) (NT)
905 *
906 * Side effects:
907 * Directory removed. If an error occurs, the error will be returned
908 * immediately, and remaining files will not be deleted.
909 *
910 *----------------------------------------------------------------------
911 */
912
913 int
914 TclpObjRemoveDirectory(pathPtr, recursive, errorPtr)
915 Tcl_Obj *pathPtr;
916 int recursive;
917 Tcl_Obj **errorPtr;
918 {
919 Tcl_DString ds;
920 Tcl_Obj *normPtr = NULL;
921 int ret;
922 if (recursive) {
923 /*
924 * In the recursive case, the string rep is used to construct a
925 * Tcl_DString which may be used extensively, so we can't
926 * optimize this case easily.
927 */
928 Tcl_DString native;
929 normPtr = Tcl_FSGetNormalizedPath(NULL, pathPtr);
930 Tcl_WinUtfToTChar(Tcl_GetString(normPtr), -1, &native);
931 ret = DoRemoveDirectory(&native, recursive, &ds);
932 Tcl_DStringFree(&native);
933 } else {
934 ret = DoRemoveJustDirectory(Tcl_FSGetNativePath(pathPtr),
935 0, &ds);
936 }
937 if (ret != TCL_OK) {
938 int len = Tcl_DStringLength(&ds);
939 if (len > 0) {
940 if (normPtr != NULL
941 && !strcmp(Tcl_DStringValue(&ds), Tcl_GetString(normPtr))) {
942 *errorPtr = pathPtr;
943 } else {
944 *errorPtr = Tcl_NewStringObj(Tcl_DStringValue(&ds), -1);
945 }
946 Tcl_IncrRefCount(*errorPtr);
947 }
948 Tcl_DStringFree(&ds);
949 }
950 return ret;
951 }
952
953 static int
954 DoRemoveJustDirectory(
955 CONST TCHAR *nativePath, /* Pathname of directory to be removed
956 * (native). */
957 int ignoreError, /* If non-zero, don't initialize the
958 * errorPtr under some circumstances
959 * on return. */
960 Tcl_DString *errorPtr) /* If non-NULL, uninitialized or free
961 * DString filled with UTF-8 name of file
962 * causing error. */
963 {
964 /*
965 * The RemoveDirectory API acts differently under Win95/98 and NT
966 * WRT NULL and "". Avoid passing these values.
967 */
968
969 if (nativePath == NULL || nativePath[0] == '\0') {
970 Tcl_SetErrno(ENOENT);
971 goto end;
972 }
973
974 if ((*tclWinProcs->removeDirectoryProc)(nativePath) != FALSE) {
975 return TCL_OK;
976 }
977 TclWinConvertError(GetLastError());
978
979 if (Tcl_GetErrno() == EACCES) {
980 DWORD attr = (*tclWinProcs->getFileAttributesProc)(nativePath);
981 if (attr != 0xffffffff) {
982 if ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0) {
983 /*
984 * Windows 95 reports calling RemoveDirectory on a file as an
985 * EACCES, not an ENOTDIR.
986 */
987
988 Tcl_SetErrno(ENOTDIR);
989 goto end;
990 }
991
992 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
993 /* It is a symbolic link -- remove it */
994 if (TclWinSymLinkDelete(nativePath, 1) != 0) {
995 goto end;
996 }
997 }
998
999 if (attr & FILE_ATTRIBUTE_READONLY) {
1000 attr &= ~FILE_ATTRIBUTE_READONLY;
1001 if ((*tclWinProcs->setFileAttributesProc)(nativePath, attr) == FALSE) {
1002 goto end;
1003 }
1004 if ((*tclWinProcs->removeDirectoryProc)(nativePath) != FALSE) {
1005 return TCL_OK;
1006 }
1007 TclWinConvertError(GetLastError());
1008 (*tclWinProcs->setFileAttributesProc)(nativePath,
1009 attr | FILE_ATTRIBUTE_READONLY);
1010 }
1011
1012 /*
1013 * Windows 95 and Win32s report removing a non-empty directory
1014 * as EACCES, not EEXIST. If the directory is not empty,
1015 * change errno so caller knows what's going on.
1016 */
1017
1018 if (TclWinGetPlatformId() != VER_PLATFORM_WIN32_NT) {
1019 CONST char *path, *find;
1020 HANDLE handle;
1021 WIN32_FIND_DATAA data;
1022 Tcl_DString buffer;
1023 int len;
1024
1025 path = (CONST char *) nativePath;
1026
1027 Tcl_DStringInit(&buffer);
1028 len = strlen(path);
1029 find = Tcl_DStringAppend(&buffer, path, len);
1030 if ((len > 0) && (find[len - 1] != '\\')) {
1031 Tcl_DStringAppend(&buffer, "\\", 1);
1032 }
1033 find = Tcl_DStringAppend(&buffer, "*.*", 3);
1034 handle = FindFirstFileA(find, &data);
1035 if (handle != INVALID_HANDLE_VALUE) {
1036 while (1) {
1037 if ((strcmp(data.cFileName, ".") != 0)
1038 && (strcmp(data.cFileName, "..") != 0)) {
1039 /*
1040 * Found something in this directory.
1041 */
1042
1043 Tcl_SetErrno(EEXIST);
1044 break;
1045 }
1046 if (FindNextFileA(handle, &data) == FALSE) {
1047 break;
1048 }
1049 }
1050 FindClose(handle);
1051 }
1052 Tcl_DStringFree(&buffer);
1053 }
1054 }
1055 }
1056 if (Tcl_GetErrno() == ENOTEMPTY) {
1057 /*
1058 * The caller depends on EEXIST to signify that the directory is
1059 * not empty, not ENOTEMPTY.
1060 */
1061
1062 Tcl_SetErrno(EEXIST);
1063 }
1064 if ((ignoreError != 0) && (Tcl_GetErrno() == EEXIST)) {
1065 /*
1066 * If we're being recursive, this error may actually
1067 * be ok, so we don't want to initialise the errorPtr
1068 * yet.
1069 */
1070 return TCL_ERROR;
1071 }
1072
1073 end:
1074 if (errorPtr != NULL) {
1075 Tcl_WinTCharToUtf(nativePath, -1, errorPtr);
1076 }
1077 return TCL_ERROR;
1078
1079 }
1080
1081 static int
1082 DoRemoveDirectory(
1083 Tcl_DString *pathPtr, /* Pathname of directory to be removed
1084 * (native). */
1085 int recursive, /* If non-zero, removes directories that
1086 * are nonempty. Otherwise, will only remove
1087 * empty directories. */
1088 Tcl_DString *errorPtr) /* If non-NULL, uninitialized or free
1089 * DString filled with UTF-8 name of file
1090 * causing error. */
1091 {
1092 int res = DoRemoveJustDirectory(Tcl_DStringValue(pathPtr), recursive,
1093 errorPtr);
1094
1095 if ((res == TCL_ERROR) && (recursive != 0) && (Tcl_GetErrno() == EEXIST)) {
1096 /*
1097 * The directory is nonempty, but the recursive flag has been
1098 * specified, so we recursively remove all the files in the directory.
1099 */
1100 return TraverseWinTree(TraversalDelete, pathPtr, NULL, errorPtr);
1101 } else {
1102 return res;
1103 }
1104 }
1105
1106 /*
1107 *---------------------------------------------------------------------------
1108 *
1109 * TraverseWinTree --
1110 *
1111 * Traverse directory tree specified by sourcePtr, calling the function
1112 * traverseProc for each file and directory encountered. If destPtr
1113 * is non-null, each of name in the sourcePtr directory is appended to
1114 * the directory specified by destPtr and passed as the second argument
1115 * to traverseProc() .
1116 *
1117 * Results:
1118 * Standard Tcl result.
1119 *
1120 * Side effects:
1121 * None caused by TraverseWinTree, however the user specified
1122 * traverseProc() may change state. If an error occurs, the error will
1123 * be returned immediately, and remaining files will not be processed.
1124 *
1125 *---------------------------------------------------------------------------
1126 */
1127
1128 static int
1129 TraverseWinTree(
1130 TraversalProc *traverseProc,/* Function to call for every file and
1131 * directory in source hierarchy. */
1132 Tcl_DString *sourcePtr, /* Pathname of source directory to be
1133 * traversed (native). */
1134 Tcl_DString *targetPtr, /* Pathname of directory to traverse in
1135 * parallel with source directory (native),
1136 * may be NULL. */
1137 Tcl_DString *errorPtr) /* If non-NULL, uninitialized or free
1138 * DString filled with UTF-8 name of file
1139 * causing error. */
1140 {
1141 DWORD sourceAttr;
1142 TCHAR *nativeSource, *nativeTarget, *nativeErrfile;
1143 int result, found, sourceLen, targetLen, oldSourceLen, oldTargetLen;
1144 HANDLE handle;
1145 WIN32_FIND_DATAT data;
1146
1147 nativeErrfile = NULL;
1148 result = TCL_OK;
1149 oldTargetLen = 0; /* lint. */
1150
1151 nativeSource = (TCHAR *) Tcl_DStringValue(sourcePtr);
1152 nativeTarget = (TCHAR *) (targetPtr == NULL
1153 ? NULL : Tcl_DStringValue(targetPtr));
1154
1155 oldSourceLen = Tcl_DStringLength(sourcePtr);
1156 sourceAttr = (*tclWinProcs->getFileAttributesProc)(nativeSource);
1157 if (sourceAttr == 0xffffffff) {
1158 nativeErrfile = nativeSource;
1159 goto end;
1160 }
1161 if ((sourceAttr & FILE_ATTRIBUTE_DIRECTORY) == 0) {
1162 /*
1163 * Process the regular file
1164 */
1165
1166 return (*traverseProc)(nativeSource, nativeTarget, DOTREE_F, errorPtr);
1167 }
1168
1169 if (tclWinProcs->useWide) {
1170 Tcl_DStringAppend(sourcePtr, (char *) L"\\*.*", 4 * sizeof(WCHAR) + 1);
1171 Tcl_DStringSetLength(sourcePtr, Tcl_DStringLength(sourcePtr) - 1);
1172 } else {
1173 Tcl_DStringAppend(sourcePtr, "\\*.*", 4);
1174 }
1175 nativeSource = (TCHAR *) Tcl_DStringValue(sourcePtr);
1176 handle = (*tclWinProcs->findFirstFileProc)(nativeSource, &data);
1177 if (handle == INVALID_HANDLE_VALUE) {
1178 /*
1179 * Can't read directory
1180 */
1181
1182 TclWinConvertError(GetLastError());
1183 nativeErrfile = nativeSource;
1184 goto end;
1185 }
1186
1187 nativeSource[oldSourceLen + 1] = '\0';
1188 Tcl_DStringSetLength(sourcePtr, oldSourceLen);
1189 result = (*traverseProc)(nativeSource, nativeTarget, DOTREE_PRED, errorPtr);
1190 if (result != TCL_OK) {
1191 FindClose(handle);
1192 return result;
1193 }
1194
1195 sourceLen = oldSourceLen;
1196
1197 if (tclWinProcs->useWide) {
1198 sourceLen += sizeof(WCHAR);
1199 Tcl_DStringAppend(sourcePtr, (char *) L"\\", sizeof(WCHAR) + 1);
1200 Tcl_DStringSetLength(sourcePtr, sourceLen);
1201 } else {
1202 sourceLen += 1;
1203 Tcl_DStringAppend(sourcePtr, "\\", 1);
1204 }
1205 if (targetPtr != NULL) {
1206 oldTargetLen = Tcl_DStringLength(targetPtr);
1207
1208 targetLen = oldTargetLen;
1209 if (tclWinProcs->useWide) {
1210 targetLen += sizeof(WCHAR);
1211 Tcl_DStringAppend(targetPtr, (char *) L"\\", sizeof(WCHAR) + 1);
1212 Tcl_DStringSetLength(targetPtr, targetLen);
1213 } else {
1214 targetLen += 1;
1215 Tcl_DStringAppend(targetPtr, "\\", 1);
1216 }
1217 }
1218
1219 found = 1;
1220 for ( ; found; found = (*tclWinProcs->findNextFileProc)(handle, &data)) {
1221 TCHAR *nativeName;
1222 int len;
1223
1224 if (tclWinProcs->useWide) {
1225 WCHAR *wp;
1226
1227 wp = data.w.cFileName;
1228 if (*wp == '.') {
1229 wp++;
1230 if (*wp == '.') {
1231 wp++;
1232 }
1233 if (*wp == '\0') {
1234 continue;
1235 }
1236 }
1237 nativeName = (TCHAR *) data.w.cFileName;
1238 len = Tcl_UniCharLen(data.w.cFileName) * sizeof(WCHAR);
1239 } else {
1240 if ((strcmp(data.a.cFileName, ".") == 0)
1241 || (strcmp(data.a.cFileName, "..") == 0)) {
1242 continue;
1243 }
1244 nativeName = (TCHAR *) data.a.cFileName;
1245 len = strlen(data.a.cFileName);
1246 }
1247
1248 /*
1249 * Append name after slash, and recurse on the file.
1250 */
1251
1252 Tcl_DStringAppend(sourcePtr, (char *) nativeName, len + 1);
1253 Tcl_DStringSetLength(sourcePtr, Tcl_DStringLength(sourcePtr) - 1);
1254 if (targetPtr != NULL) {
1255 Tcl_DStringAppend(targetPtr, (char *) nativeName, len + 1);
1256 Tcl_DStringSetLength(targetPtr, Tcl_DStringLength(targetPtr) - 1);
1257 }
1258 result = TraverseWinTree(traverseProc, sourcePtr, targetPtr,
1259 errorPtr);
1260 if (result != TCL_OK) {
1261 break;
1262 }
1263
1264 /*
1265 * Remove name after slash.
1266 */
1267
1268 Tcl_DStringSetLength(sourcePtr, sourceLen);
1269 if (targetPtr != NULL) {
1270 Tcl_DStringSetLength(targetPtr, targetLen);
1271 }
1272 }
1273 FindClose(handle);
1274
1275 /*
1276 * Strip off the trailing slash we added
1277 */
1278
1279 Tcl_DStringSetLength(sourcePtr, oldSourceLen + 1);
1280 Tcl_DStringSetLength(sourcePtr, oldSourceLen);
1281 if (targetPtr != NULL) {
1282 Tcl_DStringSetLength(targetPtr, oldTargetLen + 1);
1283 Tcl_DStringSetLength(targetPtr, oldTargetLen);
1284 }
1285 if (result == TCL_OK) {
1286 /*
1287 * Call traverseProc() on a directory after visiting all the
1288 * files in that directory.
1289 */
1290
1291 result = (*traverseProc)(Tcl_DStringValue(sourcePtr),
1292 (targetPtr == NULL ? NULL : Tcl_DStringValue(targetPtr)),
1293 DOTREE_POSTD, errorPtr);
1294 }
1295 end:
1296 if (nativeErrfile != NULL) {
1297 TclWinConvertError(GetLastError());
1298 if (errorPtr != NULL) {
1299 Tcl_WinTCharToUtf(nativeErrfile, -1, errorPtr);
1300 }
1301 result = TCL_ERROR;
1302 }
1303
1304 return result;
1305 }
1306
1307 /*
1308 *----------------------------------------------------------------------
1309 *
1310 * TraversalCopy
1311 *
1312 * Called from TraverseUnixTree in order to execute a recursive
1313 * copy of a directory.
1314 *
1315 * Results:
1316 * Standard Tcl result.
1317 *
1318 * Side effects:
1319 * Depending on the value of type, src may be copied to dst.
1320 *
1321 *----------------------------------------------------------------------
1322 */
1323
1324 static int
1325 TraversalCopy(
1326 CONST TCHAR *nativeSrc, /* Source pathname to copy. */
1327 CONST TCHAR *nativeDst, /* Destination pathname of copy. */
1328 int type, /* Reason for call - see TraverseWinTree() */
1329 Tcl_DString *errorPtr) /* If non-NULL, initialized DString filled
1330 * with UTF-8 name of file causing error. */
1331 {
1332 switch (type) {
1333 case DOTREE_F: {
1334 if (DoCopyFile(nativeSrc, nativeDst) == TCL_OK) {
1335 return TCL_OK;
1336 }
1337 break;
1338 }
1339 case DOTREE_PRED: {
1340 if (DoCreateDirectory(nativeDst) == TCL_OK) {
1341 DWORD attr = (*tclWinProcs->getFileAttributesProc)(nativeSrc);
1342 if ((*tclWinProcs->setFileAttributesProc)(nativeDst, attr) != FALSE) {
1343 return TCL_OK;
1344 }
1345 TclWinConvertError(GetLastError());
1346 }
1347 break;
1348 }
1349 case DOTREE_POSTD: {
1350 return TCL_OK;
1351 }
1352 }
1353
1354 /*
1355 * There shouldn't be a problem with src, because we already
1356 * checked it to get here.
1357 */
1358
1359 if (errorPtr != NULL) {
1360 Tcl_WinTCharToUtf(nativeDst, -1, errorPtr);
1361 }
1362 return TCL_ERROR;
1363 }
1364
1365 /*
1366 *----------------------------------------------------------------------
1367 *
1368 * TraversalDelete --
1369 *
1370 * Called by procedure TraverseWinTree for every file and
1371 * directory that it encounters in a directory hierarchy. This
1372 * procedure unlinks files, and removes directories after all the
1373 * containing files have been processed.
1374 *
1375 * Results:
1376 * Standard Tcl result.
1377 *
1378 * Side effects:
1379 * Files or directory specified by src will be deleted. If an
1380 * error occurs, the windows error is converted to a Posix error
1381 * and errno is set accordingly.
1382 *
1383 *----------------------------------------------------------------------
1384 */
1385
1386 static int
1387 TraversalDelete(
1388 CONST TCHAR *nativeSrc, /* Source pathname to delete. */
1389 CONST TCHAR *dstPtr, /* Not used. */
1390 int type, /* Reason for call - see TraverseWinTree() */
1391 Tcl_DString *errorPtr) /* If non-NULL, initialized DString filled
1392 * with UTF-8 name of file causing error. */
1393 {
1394 switch (type) {
1395 case DOTREE_F: {
1396 if (TclpDeleteFile(nativeSrc) == TCL_OK) {
1397 return TCL_OK;
1398 }
1399 break;
1400 }
1401 case DOTREE_PRED: {
1402 return TCL_OK;
1403 }
1404 case DOTREE_POSTD: {
1405 if (DoRemoveJustDirectory(nativeSrc, 0, NULL) == TCL_OK) {
1406 return TCL_OK;
1407 }
1408 break;
1409 }
1410 }
1411
1412 if (errorPtr != NULL) {
1413 Tcl_WinTCharToUtf(nativeSrc, -1, errorPtr);
1414 }
1415 return TCL_ERROR;
1416 }
1417
1418 /*
1419 *----------------------------------------------------------------------
1420 *
1421 * StatError --
1422 *
1423 * Sets the object result with the appropriate error.
1424 *
1425 * Results:
1426 * None.
1427 *
1428 * Side effects:
1429 * The interp's object result is set with an error message
1430 * based on the objIndex, fileName and errno.
1431 *
1432 *----------------------------------------------------------------------
1433 */
1434
1435 static void
1436 StatError(
1437 Tcl_Interp *interp, /* The interp that has the error */
1438 Tcl_Obj *fileName) /* The name of the file which caused the
1439 * error. */
1440 {
1441 TclWinConvertError(GetLastError());
1442 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
1443 "could not read \"", Tcl_GetString(fileName),
1444 "\": ", Tcl_PosixError(interp),
1445 (char *) NULL);
1446 }
1447
1448 /*
1449 *----------------------------------------------------------------------
1450 *
1451 * GetWinFileAttributes --
1452 *
1453 * Returns a Tcl_Obj containing the value of a file attribute.
1454 * This routine gets the -hidden, -readonly or -system attribute.
1455 *
1456 * Results:
1457 * Standard Tcl result and a Tcl_Obj in attributePtrPtr. The object
1458 * will have ref count 0. If the return value is not TCL_OK,
1459 * attributePtrPtr is not touched.
1460 *
1461 * Side effects:
1462 * A new object is allocated if the file is valid.
1463 *
1464 *----------------------------------------------------------------------
1465 */
1466
1467 static int
1468 GetWinFileAttributes(
1469 Tcl_Interp *interp, /* The interp we are using for errors. */
1470 int objIndex, /* The index of the attribute. */
1471 Tcl_Obj *fileName, /* The name of the file. */
1472 Tcl_Obj **attributePtrPtr) /* A pointer to return the object with. */
1473 {
1474 DWORD result;
1475 CONST TCHAR *nativeName;
1476 int attr;
1477
1478 nativeName = Tcl_FSGetNativePath(fileName);
1479 result = (*tclWinProcs->getFileAttributesProc)(nativeName);
1480
1481 if (result == 0xffffffff) {
1482 StatError(interp, fileName);
1483 return TCL_ERROR;
1484 }
1485
1486 attr = (int)(result & attributeArray[objIndex]);
1487 if ((objIndex == WIN_HIDDEN_ATTRIBUTE) && (attr != 0)) {
1488 /*
1489 * It is hidden. However there is a bug on some Windows
1490 * OSes in which root volumes (drives) formatted as NTFS
1491 * are declared hidden when they are not (and cannot be).
1492 *
1493 * We test for, and fix that case, here.
1494 */
1495 int len;
1496 char *str = Tcl_GetStringFromObj(fileName,&len);
1497 if (len < 4) {
1498 if (len == 0) {
1499 /*
1500 * Not sure if this is possible, but we pass it on
1501 * anyway
1502 */
1503 } else if (len == 1 && (str[0] == '/' || str[0] == '\\')) {
1504 /* Path is pointing to the root volume */
1505 attr = 0;
1506 } else if ((str[1] == ':')
1507 && (len == 2 || (str[2] == '/' || str[2] == '\\'))) {
1508 /* Path is of the form 'x:' or 'x:/' or 'x:\' */
1509 attr = 0;
1510 }
1511 }
1512 }
1513 *attributePtrPtr = Tcl_NewBooleanObj(attr);
1514 return TCL_OK;
1515 }
1516
1517 /*
1518 *----------------------------------------------------------------------
1519 *
1520 * ConvertFileNameFormat --
1521 *
1522 * Returns a Tcl_Obj containing either the long or short version of the
1523 * file name.
1524 *
1525 * Results:
1526 * Standard Tcl result and a Tcl_Obj in attributePtrPtr. The object
1527 * will have ref count 0. If the return value is not TCL_OK,
1528 * attributePtrPtr is not touched.
1529 *
1530 * Warning: if you pass this function a drive name like 'c:' it
1531 * will actually return the current working directory on that
1532 * drive. To avoid this, make sure the drive name ends in a
1533 * slash, like this 'c:/'.
1534 *
1535 * Side effects:
1536 * A new object is allocated if the file is valid.
1537 *
1538 *----------------------------------------------------------------------
1539 */
1540
1541 static int
1542 ConvertFileNameFormat(
1543 Tcl_Interp *interp, /* The interp we are using for errors. */
1544 int objIndex, /* The index of the attribute. */
1545 Tcl_Obj *fileName, /* The name of the file. */
1546 int longShort, /* 0 to short name, 1 to long name. */
1547 Tcl_Obj **attributePtrPtr) /* A pointer to return the object with. */
1548 {
1549 int pathc, i;
1550 Tcl_Obj *splitPath;
1551 int result = TCL_OK;
1552
1553 splitPath = Tcl_FSSplitPath(fileName, &pathc);
1554
1555 if (splitPath == NULL || pathc == 0) {
1556 if (interp != NULL) {
1557 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
1558 "could not read \"", Tcl_GetString(fileName),
1559 "\": no such file or directory",
1560 (char *) NULL);
1561 }
1562 result = TCL_ERROR;
1563 goto cleanup;
1564 }
1565
1566 for (i = 0; i < pathc; i++) {
1567 Tcl_Obj *elt;
1568 char *pathv;
1569 int pathLen;
1570 Tcl_ListObjIndex(NULL, splitPath, i, &elt);
1571
1572 pathv = Tcl_GetStringFromObj(elt, &pathLen);
1573 if ((pathv[0] == '/')
1574 || ((pathLen == 3) && (pathv[1] == ':'))
1575 || (strcmp(pathv, ".") == 0)
1576 || (strcmp(pathv, "..") == 0)) {
1577 /*
1578 * Handle "/", "//machine/export", "c:/", "." or ".." by just
1579 * copying the string literally. Uppercase the drive letter,
1580 * just because it looks better under Windows to do so.
1581 */
1582
1583 simple:
1584 /* Here we are modifying the string representation in place */
1585 /* I believe this is legal, since this won't affect any
1586 * file representation this thing may have. */
1587 pathv[0] = (char) Tcl_UniCharToUpper(UCHAR(pathv[0]));
1588 } else {
1589 Tcl_Obj *tempPath;
1590 Tcl_DString ds;
1591 Tcl_DString dsTemp;
1592 TCHAR *nativeName;
1593 char *tempString;
1594 int tempLen;
1595 WIN32_FIND_DATAT data;
1596 HANDLE handle;
1597 DWORD attr;
1598
1599 tempPath = Tcl_FSJoinPath(splitPath, i+1);
1600 Tcl_IncrRefCount(tempPath);
1601 /*
1602 * We'd like to call Tcl_FSGetNativePath(tempPath)
1603 * but that is likely to lead to infinite loops
1604 */
1605 Tcl_DStringInit(&ds);
1606 tempString = Tcl_GetStringFromObj(tempPath,&tempLen);
1607 nativeName = Tcl_WinUtfToTChar(tempString, tempLen, &ds);
1608 Tcl_DecrRefCount(tempPath);
1609 handle = (*tclWinProcs->findFirstFileProc)(nativeName, &data);
1610 if (handle == INVALID_HANDLE_VALUE) {
1611 /*
1612 * FindFirstFile() doesn't like root directories. We
1613 * would only get a root directory here if the caller
1614 * specified "c:" or "c:." and the current directory on the
1615 * drive was the root directory
1616 */
1617
1618 attr = (*tclWinProcs->getFileAttributesProc)(nativeName);
1619 if ((attr != 0xFFFFFFFF) && (attr & FILE_ATTRIBUTE_DIRECTORY)) {
1620 Tcl_DStringFree(&ds);
1621 goto simple;
1622 }
1623 }
1624
1625 if (handle == INVALID_HANDLE_VALUE) {
1626 Tcl_DStringFree(&ds);
1627 if (interp != NULL) {
1628 StatError(interp, fileName);
1629 }
1630 result = TCL_ERROR;
1631 goto cleanup;
1632 }
1633 if (tclWinProcs->useWide) {
1634 nativeName = (TCHAR *) data.w.cAlternateFileName;
1635 if (longShort) {
1636 if (data.w.cFileName[0] != '\0') {
1637 nativeName = (TCHAR *) data.w.cFileName;
1638 }
1639 } else {
1640 if (data.w.cAlternateFileName[0] == '\0') {
1641 nativeName = (TCHAR *) data.w.cFileName;
1642 }
1643 }
1644 } else {
1645 nativeName = (TCHAR *) data.a.cAlternateFileName;
1646 if (longShort) {
1647 if (data.a.cFileName[0] != '\0') {
1648 nativeName = (TCHAR *) data.a.cFileName;
1649 }
1650 } else {
1651 if (data.a.cAlternateFileName[0] == '\0') {
1652 nativeName = (TCHAR *) data.a.cFileName;
1653 }
1654 }
1655 }
1656
1657 /*
1658 * Purify reports a extraneous UMR in Tcl_WinTCharToUtf() trying
1659 * to dereference nativeName as a Unicode string. I have proven
1660 * to myself that purify is wrong by running the following
1661 * example when nativeName == data.w.cAlternateFileName and
1662 * noting that purify doesn't complain about the first line,
1663 * but does complain about the second.
1664 *
1665 * fprintf(stderr, "%d\n", data.w.cAlternateFileName[0]);
1666 * fprintf(stderr, "%d\n", ((WCHAR *) nativeName)[0]);
1667 */
1668
1669 Tcl_DStringInit(&dsTemp);
1670 Tcl_WinTCharToUtf(nativeName, -1, &dsTemp);
1671 /* Deal with issues of tildes being absolute */
1672 if (Tcl_DStringValue(&dsTemp)[0] == '~') {
1673 tempPath = Tcl_NewStringObj("./",2);
1674 Tcl_AppendToObj(tempPath, Tcl_DStringValue(&dsTemp),
1675 Tcl_DStringLength(&dsTemp));
1676 } else {
1677 tempPath = Tcl_NewStringObj(Tcl_DStringValue(&dsTemp),
1678 Tcl_DStringLength(&dsTemp));
1679 }
1680 Tcl_ListObjReplace(NULL, splitPath, i, 1, 1, &tempPath);
1681 Tcl_DStringFree(&ds);
1682 Tcl_DStringFree(&dsTemp);
1683 FindClose(handle);
1684 }
1685 }
1686
1687 *attributePtrPtr = Tcl_FSJoinPath(splitPath, -1);
1688
1689 cleanup:
1690 if (splitPath != NULL) {
1691 Tcl_DecrRefCount(splitPath);
1692 }
1693
1694 return result;
1695 }
1696
1697 /*
1698 *----------------------------------------------------------------------
1699 *
1700 * GetWinFileLongName --
1701 *
1702 * Returns a Tcl_Obj containing the long version of the file
1703 * name.
1704 *
1705 * Results:
1706 * Standard Tcl result and a Tcl_Obj in attributePtrPtr. The object
1707 * will have ref count 0. If the return value is not TCL_OK,
1708 * attributePtrPtr is not touched.
1709 *
1710 * Side effects:
1711 * A new object is allocated if the file is valid.
1712 *
1713 *----------------------------------------------------------------------
1714 */
1715
1716 static int
1717 GetWinFileLongName(
1718 Tcl_Interp *interp, /* The interp we are using for errors. */
1719 int objIndex, /* The index of the attribute. */
1720 Tcl_Obj *fileName, /* The name of the file. */
1721 Tcl_Obj **attributePtrPtr) /* A pointer to return the object with. */
1722 {
1723 return ConvertFileNameFormat(interp, objIndex, fileName, 1, attributePtrPtr);
1724 }
1725
1726 /*
1727 *----------------------------------------------------------------------
1728 *
1729 * GetWinFileShortName --
1730 *
1731 * Returns a Tcl_Obj containing the short version of the file
1732 * name.
1733 *
1734 * Results:
1735 * Standard Tcl result and a Tcl_Obj in attributePtrPtr. The object
1736 * will have ref count 0. If the return value is not TCL_OK,
1737 * attributePtrPtr is not touched.
1738 *
1739 * Side effects:
1740 * A new object is allocated if the file is valid.
1741 *
1742 *----------------------------------------------------------------------
1743 */
1744
1745 static int
1746 GetWinFileShortName(
1747 Tcl_Interp *interp, /* The interp we are using for errors. */
1748 int objIndex, /* The index of the attribute. */
1749 Tcl_Obj *fileName, /* The name of the file. */
1750 Tcl_Obj **attributePtrPtr) /* A pointer to return the object with. */
1751 {
1752 return ConvertFileNameFormat(interp, objIndex, fileName, 0, attributePtrPtr);
1753 }
1754
1755 /*
1756 *----------------------------------------------------------------------
1757 *
1758 * SetWinFileAttributes --
1759 *
1760 * Set the file attributes to the value given by attributePtr.
1761 * This routine sets the -hidden, -readonly, or -system attributes.
1762 *
1763 * Results:
1764 * Standard TCL error.
1765 *
1766 * Side effects:
1767 * The file's attribute is set.
1768 *
1769 *----------------------------------------------------------------------
1770 */
1771
1772 static int
1773 SetWinFileAttributes(
1774 Tcl_Interp *interp, /* The interp we are using for errors. */
1775 int objIndex, /* The index of the attribute. */
1776 Tcl_Obj *fileName, /* The name of the file. */
1777 Tcl_Obj *attributePtr) /* The new value of the attribute. */
1778 {
1779 DWORD fileAttributes;
1780 int yesNo;
1781 int result;
1782 CONST TCHAR *nativeName;
1783
1784 nativeName = Tcl_FSGetNativePath(fileName);
1785 fileAttributes = (*tclWinProcs->getFileAttributesProc)(nativeName);
1786
1787 if (fileAttributes == 0xffffffff) {
1788 StatError(interp, fileName);
1789 return TCL_ERROR;
1790 }
1791
1792 result = Tcl_GetBooleanFromObj(interp, attributePtr, &yesNo);
1793 if (result != TCL_OK) {
1794 return result;
1795 }
1796
1797 if (yesNo) {
1798 fileAttributes |= (attributeArray[objIndex]);
1799 } else {
1800 fileAttributes &= ~(attributeArray[objIndex]);
1801 }
1802
1803 if (!(*tclWinProcs->setFileAttributesProc)(nativeName, fileAttributes)) {
1804 StatError(interp, fileName);
1805 return TCL_ERROR;
1806 }
1807
1808 return result;
1809 }
1810
1811 /*
1812 *----------------------------------------------------------------------
1813 *
1814 * SetWinFileLongName --
1815 *
1816 * The attribute in question is a readonly attribute and cannot
1817 * be set.
1818 *
1819 * Results:
1820 * TCL_ERROR
1821 *
1822 * Side effects:
1823 * The object result is set to a pertinent error message.
1824 *
1825 *----------------------------------------------------------------------
1826 */
1827
1828 static int
1829 CannotSetAttribute(
1830 Tcl_Interp *interp, /* The interp we are using for errors. */
1831 int objIndex, /* The index of the attribute. */
1832 Tcl_Obj *fileName, /* The name of the file. */
1833 Tcl_Obj *attributePtr) /* The new value of the attribute. */
1834 {
1835 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
1836 "cannot set attribute \"", tclpFileAttrStrings[objIndex],
1837 "\" for file \"", Tcl_GetString(fileName),
1838 "\": attribute is readonly",
1839 (char *) NULL);
1840 return TCL_ERROR;
1841 }
1842
1843
1844 /*
1845 *---------------------------------------------------------------------------
1846 *
1847 * TclpObjListVolumes --
1848 *
1849 * Lists the currently mounted volumes
1850 *
1851 * Results:
1852 * The list of volumes.
1853 *
1854 * Side effects:
1855 * None
1856 *
1857 *---------------------------------------------------------------------------
1858 */
1859
1860 Tcl_Obj*
1861 TclpObjListVolumes(void)
1862 {
1863 Tcl_Obj *resultPtr, *elemPtr;
1864 char buf[40 * 4]; /* There couldn't be more than 30 drives??? */
1865 int i;
1866 char *p;
1867
1868 resultPtr = Tcl_NewObj();
1869
1870 /*
1871 * On Win32s:
1872 * GetLogicalDriveStrings() isn't implemented.
1873 * GetLogicalDrives() returns incorrect information.
1874 */
1875
1876 if (GetLogicalDriveStringsA(sizeof(buf), buf) == 0) {
1877 /*
1878 * GetVolumeInformation() will detects all drives, but causes
1879 * chattering on empty floppy drives. We only do this if
1880 * GetLogicalDriveStrings() didn't work. It has also been reported
1881 * that on some laptops it takes a while for GetVolumeInformation()
1882 * to return when pinging an empty floppy drive, another reason to
1883 * try to avoid calling it.
1884 */
1885
1886 buf[1] = ':';
1887 buf[2] = '/';
1888 buf[3] = '\0';
1889
1890 for (i = 0; i < 26; i++) {
1891 buf[0] = (char) ('a' + i);
1892 if (GetVolumeInformationA(buf, NULL, 0, NULL, NULL, NULL, NULL, 0)
1893 || (GetLastError() == ERROR_NOT_READY)) {
1894 elemPtr = Tcl_NewStringObj(buf, -1);
1895 Tcl_ListObjAppendElement(NULL, resultPtr, elemPtr);
1896 }
1897 }
1898 } else {
1899 for (p = buf; *p != '\0'; p += 4) {
1900 p[2] = '/';
1901 elemPtr = Tcl_NewStringObj(p, -1);
1902 Tcl_ListObjAppendElement(NULL, resultPtr, elemPtr);
1903 }
1904 }
1905
1906 Tcl_IncrRefCount(resultPtr);
1907 return resultPtr;
1908 }