Debian Codegraph @

win/tclWinPipe.c

raw
1 /*
2 * tclWinPipe.c --
3 *
4 * This file implements the Windows-specific exec pipeline functions, the
5 * "pipe" channel driver, and the "pid" Tcl command.
6 *
7 * Copyright (c) 1996-1997 by Sun Microsystems, Inc.
8 *
9 * See the file "license.terms" for information on usage and redistribution of
10 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
11 */
12
13 #include "tclWinInt.h"
14
15 /*
16 * The following variable is used to tell whether this module has been
17 * initialized.
18 */
19
20 static int initialized = 0;
21
22 /*
23 * The pipeMutex locks around access to the initialized and procList
24 * variables, and it is used to protect background threads from being
25 * terminated while they are using APIs that hold locks.
26 */
27
28 TCL_DECLARE_MUTEX(pipeMutex)
29
30 /*
31 * The following defines identify the various types of applications that run
32 * under windows. There is special case code for the various types.
33 */
34
35 #define APPL_NONE 0
36 #define APPL_DOS 1
37 #define APPL_WIN3X 2
38 #define APPL_WIN32 3
39
40 /*
41 * The following constants and structures are used to encapsulate the state of
42 * various types of files used in a pipeline. This used to have a 1 && 2 that
43 * supported Win32s.
44 */
45
46 #define WIN_FILE 3 /* Basic Win32 file. */
47
48 /*
49 * This structure encapsulates the common state associated with all file types
50 * used in a pipeline.
51 */
52
53 typedef struct {
54 int type; /* One of the file types defined above. */
55 HANDLE handle; /* Open file handle. */
56 } WinFile;
57
58 /*
59 * This list is used to map from pids to process handles.
60 */
61
62 typedef struct ProcInfo {
63 HANDLE hProcess;
64 DWORD dwProcessId;
65 struct ProcInfo *nextPtr;
66 } ProcInfo;
67
68 static ProcInfo *procList;
69
70 /*
71 * Bit masks used in the flags field of the PipeInfo structure below.
72 */
73
74 #define PIPE_PENDING (1<<0) /* Message is pending in the queue. */
75 #define PIPE_ASYNC (1<<1) /* Channel is non-blocking. */
76
77 /*
78 * Bit masks used in the sharedFlags field of the PipeInfo structure below.
79 */
80
81 #define PIPE_EOF (1<<2) /* Pipe has reached EOF. */
82 #define PIPE_EXTRABYTE (1<<3) /* The reader thread has consumed one byte. */
83
84 /*
85 * TODO: It appears the whole EXTRABYTE machinery is in place to support
86 * outdated Win 95 systems. If this can be confirmed, much code can be
87 * deleted.
88 */
89
90 /*
91 * This structure describes per-instance data for a pipe based channel.
92 */
93
94 typedef struct PipeInfo {
95 struct PipeInfo *nextPtr; /* Pointer to next registered pipe. */
96 Tcl_Channel channel; /* Pointer to channel structure. */
97 int validMask; /* OR'ed combination of TCL_READABLE,
98 * TCL_WRITABLE, or TCL_EXCEPTION: indicates
99 * which operations are valid on the file. */
100 int watchMask; /* OR'ed combination of TCL_READABLE,
101 * TCL_WRITABLE, or TCL_EXCEPTION: indicates
102 * which events should be reported. */
103 int flags; /* State flags, see above for a list. */
104 TclFile readFile; /* Output from pipe. */
105 TclFile writeFile; /* Input from pipe. */
106 TclFile errorFile; /* Error output from pipe. */
107 int numPids; /* Number of processes attached to pipe. */
108 Tcl_Pid *pidPtr; /* Pids of attached processes. */
109 Tcl_ThreadId threadId; /* Thread to which events should be reported.
110 * This value is used by the reader/writer
111 * threads. */
112 TclPipeThreadInfo *writeTI; /* Thread info of writer and reader, this */
113 TclPipeThreadInfo *readTI; /* structure owned by corresponding thread. */
114 HANDLE writeThread; /* Handle to writer thread. */
115 HANDLE readThread; /* Handle to reader thread. */
116
117 HANDLE writable; /* Manual-reset event to signal when the
118 * writer thread has finished waiting for the
119 * current buffer to be written. */
120 HANDLE readable; /* Manual-reset event to signal when the
121 * reader thread has finished waiting for
122 * input. */
123 DWORD writeError; /* An error caused by the last background
124 * write. Set to 0 if no error has been
125 * detected. This word is shared with the
126 * writer thread so access must be
127 * synchronized with the writable object. */
128 char *writeBuf; /* Current background output buffer. Access is
129 * synchronized with the writable object. */
130 int writeBufLen; /* Size of write buffer. Access is
131 * synchronized with the writable object. */
132 int toWrite; /* Current amount to be written. Access is
133 * synchronized with the writable object. */
134 int readFlags; /* Flags that are shared with the reader
135 * thread. Access is synchronized with the
136 * readable object. */
137 char extraByte; /* Buffer for extra character consumed by
138 * reader thread. This byte is shared with the
139 * reader thread so access must be
140 * synchronized with the readable object. */
141 } PipeInfo;
142
143 typedef struct {
144 /*
145 * The following pointer refers to the head of the list of pipes that are
146 * being watched for file events.
147 */
148
149 PipeInfo *firstPipePtr;
150 } ThreadSpecificData;
151
152 static Tcl_ThreadDataKey dataKey;
153
154 /*
155 * The following structure is what is added to the Tcl event queue when pipe
156 * events are generated.
157 */
158
159 typedef struct {
160 Tcl_Event header; /* Information that is standard for all
161 * events. */
162 PipeInfo *infoPtr; /* Pointer to pipe info structure. Note that
163 * we still have to verify that the pipe
164 * exists before dereferencing this
165 * pointer. */
166 } PipeEvent;
167
168 /*
169 * Declarations for functions used only in this file.
170 */
171
172 static int ApplicationType(Tcl_Interp *interp,
173 const char *fileName, char *fullName);
174 static void BuildCommandLine(const char *executable, int argc,
175 const char **argv, Tcl_DString *linePtr);
176 static BOOL HasConsole(void);
177 static int PipeBlockModeProc(ClientData instanceData, int mode);
178 static void PipeCheckProc(ClientData clientData, int flags);
179 static int PipeClose2Proc(ClientData instanceData,
180 Tcl_Interp *interp, int flags);
181 static int PipeEventProc(Tcl_Event *evPtr, int flags);
182 static int PipeGetHandleProc(ClientData instanceData,
183 int direction, ClientData *handlePtr);
184 static void PipeInit(void);
185 static int PipeInputProc(ClientData instanceData, char *buf,
186 int toRead, int *errorCode);
187 static int PipeOutputProc(ClientData instanceData,
188 const char *buf, int toWrite, int *errorCode);
189 static DWORD WINAPI PipeReaderThread(LPVOID arg);
190 static void PipeSetupProc(ClientData clientData, int flags);
191 static void PipeWatchProc(ClientData instanceData, int mask);
192 static DWORD WINAPI PipeWriterThread(LPVOID arg);
193 static int TempFileName(WCHAR name[MAX_PATH]);
194 static int WaitForRead(PipeInfo *infoPtr, int blocking);
195 static void PipeThreadActionProc(ClientData instanceData,
196 int action);
197
198 /*
199 * This structure describes the channel type structure for command pipe based
200 * I/O.
201 */
202
203 static const Tcl_ChannelType pipeChannelType = {
204 "pipe", /* Type name. */
205 TCL_CHANNEL_VERSION_5, /* v5 channel */
206 TCL_CLOSE2PROC, /* Close proc. */
207 PipeInputProc, /* Input proc. */
208 PipeOutputProc, /* Output proc. */
209 NULL, /* Seek proc. */
210 NULL, /* Set option proc. */
211 NULL, /* Get option proc. */
212 PipeWatchProc, /* Set up notifier to watch the channel. */
213 PipeGetHandleProc, /* Get an OS handle from channel. */
214 PipeClose2Proc, /* close2proc */
215 PipeBlockModeProc, /* Set blocking or non-blocking mode.*/
216 NULL, /* flush proc. */
217 NULL, /* handler proc. */
218 NULL, /* wide seek proc */
219 PipeThreadActionProc, /* thread action proc */
220 NULL /* truncate */
221 };
222
223 /*
224 *----------------------------------------------------------------------
225 *
226 * PipeInit --
227 *
228 * This function initializes the static variables for this file.
229 *
230 * Results:
231 * None.
232 *
233 * Side effects:
234 * Creates a new event source.
235 *
236 *----------------------------------------------------------------------
237 */
238
239 static void
240 PipeInit(void)
241 {
242 ThreadSpecificData *tsdPtr;
243
244 /*
245 * Check the initialized flag first, then check again in the mutex. This
246 * is a speed enhancement.
247 */
248
249 if (!initialized) {
250 Tcl_MutexLock(&pipeMutex);
251 if (!initialized) {
252 initialized = 1;
253 procList = NULL;
254 }
255 Tcl_MutexUnlock(&pipeMutex);
256 }
257
258 tsdPtr = (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey);
259 if (tsdPtr == NULL) {
260 tsdPtr = TCL_TSD_INIT(&dataKey);
261 tsdPtr->firstPipePtr = NULL;
262 Tcl_CreateEventSource(PipeSetupProc, PipeCheckProc, NULL);
263 }
264 }
265
266 /*
267 *----------------------------------------------------------------------
268 *
269 * TclpFinalizePipes --
270 *
271 * This function is called from Tcl_FinalizeThread to finalize the
272 * platform specific pipe subsystem.
273 *
274 * Results:
275 * None.
276 *
277 * Side effects:
278 * Removes the pipe event source.
279 *
280 *----------------------------------------------------------------------
281 */
282
283 void
284 TclpFinalizePipes(void)
285 {
286 ThreadSpecificData *tsdPtr;
287
288 tsdPtr = (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey);
289 if (tsdPtr != NULL) {
290 Tcl_DeleteEventSource(PipeSetupProc, PipeCheckProc, NULL);
291 }
292 }
293
294 /*
295 *----------------------------------------------------------------------
296 *
297 * PipeSetupProc --
298 *
299 * This function is invoked before Tcl_DoOneEvent blocks waiting for an
300 * event.
301 *
302 * Results:
303 * None.
304 *
305 * Side effects:
306 * Adjusts the block time if needed.
307 *
308 *----------------------------------------------------------------------
309 */
310
311 void
312 PipeSetupProc(
313 ClientData data, /* Not used. */
314 int flags) /* Event flags as passed to Tcl_DoOneEvent. */
315 {
316 PipeInfo *infoPtr;
317 Tcl_Time blockTime = { 0, 0 };
318 int block = 1;
319 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
320
321 if (!(flags & TCL_FILE_EVENTS)) {
322 return;
323 }
324
325 /*
326 * Look to see if any events are already pending. If they are, poll.
327 */
328
329 for (infoPtr = tsdPtr->firstPipePtr; infoPtr != NULL;
330 infoPtr = infoPtr->nextPtr) {
331 if (infoPtr->watchMask & TCL_WRITABLE) {
332 if (WaitForSingleObject(infoPtr->writable, 0) != WAIT_TIMEOUT) {
333 block = 0;
334 }
335 }
336 if (infoPtr->watchMask & TCL_READABLE) {
337 if (WaitForRead(infoPtr, 0) >= 0) {
338 block = 0;
339 }
340 }
341 }
342 if (!block) {
343 Tcl_SetMaxBlockTime(&blockTime);
344 }
345 }
346
347 /*
348 *----------------------------------------------------------------------
349 *
350 * PipeCheckProc --
351 *
352 * This function is called by Tcl_DoOneEvent to check the pipe event
353 * source for events.
354 *
355 * Results:
356 * None.
357 *
358 * Side effects:
359 * May queue an event.
360 *
361 *----------------------------------------------------------------------
362 */
363
364 static void
365 PipeCheckProc(
366 ClientData data, /* Not used. */
367 int flags) /* Event flags as passed to Tcl_DoOneEvent. */
368 {
369 PipeInfo *infoPtr;
370 PipeEvent *evPtr;
371 int needEvent;
372 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
373
374 if (!(flags & TCL_FILE_EVENTS)) {
375 return;
376 }
377
378 /*
379 * Queue events for any ready pipes that don't already have events queued.
380 */
381
382 for (infoPtr = tsdPtr->firstPipePtr; infoPtr != NULL;
383 infoPtr = infoPtr->nextPtr) {
384 if (infoPtr->flags & PIPE_PENDING) {
385 continue;
386 }
387
388 /*
389 * Queue an event if the pipe is signaled for reading or writing.
390 */
391
392 needEvent = 0;
393 if ((infoPtr->watchMask & TCL_WRITABLE) &&
394 (WaitForSingleObject(infoPtr->writable, 0) != WAIT_TIMEOUT)) {
395 needEvent = 1;
396 }
397
398 if ((infoPtr->watchMask & TCL_READABLE) &&
399 (WaitForRead(infoPtr, 0) >= 0)) {
400 needEvent = 1;
401 }
402
403 if (needEvent) {
404 infoPtr->flags |= PIPE_PENDING;
405 evPtr = (PipeEvent *)ckalloc(sizeof(PipeEvent));
406 evPtr->header.proc = PipeEventProc;
407 evPtr->infoPtr = infoPtr;
408 Tcl_QueueEvent((Tcl_Event *) evPtr, TCL_QUEUE_TAIL);
409 }
410 }
411 }
412
413 /*
414 *----------------------------------------------------------------------
415 *
416 * TclWinMakeFile --
417 *
418 * This function constructs a new TclFile from a given data and type
419 * value.
420 *
421 * Results:
422 * Returns a newly allocated WinFile as a TclFile.
423 *
424 * Side effects:
425 * None.
426 *
427 *----------------------------------------------------------------------
428 */
429
430 TclFile
431 TclWinMakeFile(
432 HANDLE handle) /* Type-specific data. */
433 {
434 WinFile *filePtr;
435
436 filePtr = (WinFile *)ckalloc(sizeof(WinFile));
437 filePtr->type = WIN_FILE;
438 filePtr->handle = handle;
439
440 return (TclFile)filePtr;
441 }
442
443 /*
444 *----------------------------------------------------------------------
445 *
446 * TempFileName --
447 *
448 * Gets a temporary file name and deals with the fact that the temporary
449 * file path provided by Windows may not actually exist if the TMP or
450 * TEMP environment variables refer to a non-existent directory.
451 *
452 * Results:
453 * 0 if error, non-zero otherwise. If non-zero is returned, the name
454 * buffer will be filled with a name that can be used to construct a
455 * temporary file.
456 *
457 * Side effects:
458 * None.
459 *
460 *----------------------------------------------------------------------
461 */
462
463 static int
464 TempFileName(
465 WCHAR name[MAX_PATH]) /* Buffer in which name for temporary file
466 * gets stored. */
467 {
468 const WCHAR *prefix = L"TCL";
469 if (GetTempPathW(MAX_PATH, name) != 0) {
470 if (GetTempFileNameW(name, prefix, 0, name) != 0) {
471 return 1;
472 }
473 }
474 name[0] = '.';
475 name[1] = '\0';
476 return GetTempFileNameW(name, prefix, 0, name);
477 }
478
479 /*
480 *----------------------------------------------------------------------
481 *
482 * TclpMakeFile --
483 *
484 * Make a TclFile from a channel.
485 *
486 * Results:
487 * Returns a new TclFile or NULL on failure.
488 *
489 * Side effects:
490 * None.
491 *
492 *----------------------------------------------------------------------
493 */
494
495 TclFile
496 TclpMakeFile(
497 Tcl_Channel channel, /* Channel to get file from. */
498 int direction) /* Either TCL_READABLE or TCL_WRITABLE. */
499 {
500 HANDLE handle;
501
502 if (Tcl_GetChannelHandle(channel, direction,
503 (ClientData *) &handle) == TCL_OK) {
504 return TclWinMakeFile(handle);
505 } else {
506 return (TclFile) NULL;
507 }
508 }
509
510 /*
511 *----------------------------------------------------------------------
512 *
513 * TclpOpenFile --
514 *
515 * This function opens files for use in a pipeline.
516 *
517 * Results:
518 * Returns a newly allocated TclFile structure containing the file
519 * handle.
520 *
521 * Side effects:
522 * None.
523 *
524 *----------------------------------------------------------------------
525 */
526
527 TclFile
528 TclpOpenFile(
529 const char *path, /* The name of the file to open. */
530 int mode) /* In what mode to open the file? */
531 {
532 HANDLE handle;
533 DWORD accessMode, createMode, shareMode, flags;
534 Tcl_DString ds;
535 const WCHAR *nativePath;
536
537 /*
538 * Map the access bits to the NT access mode.
539 */
540
541 switch (mode & O_ACCMODE) {
542 case O_RDONLY:
543 accessMode = GENERIC_READ;
544 break;
545 case O_WRONLY:
546 accessMode = GENERIC_WRITE;
547 break;
548 case O_RDWR:
549 accessMode = (GENERIC_READ | GENERIC_WRITE);
550 break;
551 default:
552 TclWinConvertError(ERROR_INVALID_FUNCTION);
553 return NULL;
554 }
555
556 /*
557 * Map the creation flags to the NT create mode.
558 */
559
560 switch (mode & (O_CREAT | O_EXCL | O_TRUNC)) {
561 case (O_CREAT | O_EXCL):
562 case (O_CREAT | O_EXCL | O_TRUNC):
563 createMode = CREATE_NEW;
564 break;
565 case (O_CREAT | O_TRUNC):
566 createMode = CREATE_ALWAYS;
567 break;
568 case O_CREAT:
569 createMode = OPEN_ALWAYS;
570 break;
571 case O_TRUNC:
572 case (O_TRUNC | O_EXCL):
573 createMode = TRUNCATE_EXISTING;
574 break;
575 default:
576 createMode = OPEN_EXISTING;
577 break;
578 }
579
580 nativePath = (WCHAR *)Tcl_WinUtfToTChar(path, -1, &ds);
581
582 /*
583 * If the file is not being created, use the existing file attributes.
584 */
585
586 flags = 0;
587 if (!(mode & O_CREAT)) {
588 flags = GetFileAttributesW(nativePath);
589 if (flags == 0xFFFFFFFF) {
590 flags = 0;
591 }
592 }
593
594 /*
595 * Set up the file sharing mode. We want to allow simultaneous access.
596 */
597
598 shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
599
600 /*
601 * Now we get to create the file.
602 */
603
604 handle = CreateFileW(nativePath, accessMode, shareMode,
605 NULL, createMode, flags, NULL);
606 Tcl_DStringFree(&ds);
607
608 if (handle == INVALID_HANDLE_VALUE) {
609 DWORD err;
610
611 err = GetLastError();
612 if ((err & 0xFFFFL) == ERROR_OPEN_FAILED) {
613 err = (mode & O_CREAT) ? ERROR_FILE_EXISTS : ERROR_FILE_NOT_FOUND;
614 }
615 TclWinConvertError(err);
616 return NULL;
617 }
618
619 /*
620 * Seek to the end of file if we are writing.
621 */
622
623 if (mode & (O_WRONLY|O_APPEND)) {
624 SetFilePointer(handle, 0, NULL, FILE_END);
625 }
626
627 return TclWinMakeFile(handle);
628 }
629
630 /*
631 *----------------------------------------------------------------------
632 *
633 * TclpCreateTempFile --
634 *
635 * This function opens a unique file with the property that it will be
636 * deleted when its file handle is closed. The temporary file is created
637 * in the system temporary directory.
638 *
639 * Results:
640 * Returns a valid TclFile, or NULL on failure.
641 *
642 * Side effects:
643 * Creates a new temporary file.
644 *
645 *----------------------------------------------------------------------
646 */
647
648 TclFile
649 TclpCreateTempFile(
650 const char *contents) /* String to write into temp file, or NULL. */
651 {
652 WCHAR name[MAX_PATH];
653 const char *native;
654 Tcl_DString dstring;
655 HANDLE handle;
656
657 if (TempFileName(name) == 0) {
658 return NULL;
659 }
660
661 handle = CreateFileW(name,
662 GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
663 FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE, NULL);
664 if (handle == INVALID_HANDLE_VALUE) {
665 goto error;
666 }
667
668 /*
669 * Write the file out, doing line translations on the way.
670 */
671
672 if (contents != NULL) {
673 DWORD result, length;
674 const char *p;
675 int toCopy;
676
677 /*
678 * Convert the contents from UTF to native encoding
679 */
680
681 native = Tcl_UtfToExternalDString(NULL, contents, -1, &dstring);
682
683 toCopy = Tcl_DStringLength(&dstring);
684 for (p = native; toCopy > 0; p++, toCopy--) {
685 if (*p == '\n') {
686 length = p - native;
687 if (length > 0) {
688 if (!WriteFile(handle, native, length, &result, NULL)) {
689 goto error;
690 }
691 }
692 if (!WriteFile(handle, "\r\n", 2, &result, NULL)) {
693 goto error;
694 }
695 native = p+1;
696 }
697 }
698 length = p - native;
699 if (length > 0) {
700 if (!WriteFile(handle, native, length, &result, NULL)) {
701 goto error;
702 }
703 }
704 Tcl_DStringFree(&dstring);
705 if (SetFilePointer(handle, 0, NULL, FILE_BEGIN) == 0xFFFFFFFF) {
706 goto error;
707 }
708 }
709
710 return TclWinMakeFile(handle);
711
712 error:
713 /*
714 * Free the native representation of the contents if necessary.
715 */
716
717 if (contents != NULL) {
718 Tcl_DStringFree(&dstring);
719 }
720
721 TclWinConvertError(GetLastError());
722 CloseHandle(handle);
723 DeleteFileW(name);
724 return NULL;
725 }
726
727 /*
728 *----------------------------------------------------------------------
729 *
730 * TclpTempFileName --
731 *
732 * This function returns a unique filename.
733 *
734 * Results:
735 * Returns a valid Tcl_Obj* with refCount 0, or NULL on failure.
736 *
737 * Side effects:
738 * None.
739 *
740 *----------------------------------------------------------------------
741 */
742
743 Tcl_Obj *
744 TclpTempFileName(void)
745 {
746 WCHAR fileName[MAX_PATH];
747
748 if (TempFileName(fileName) == 0) {
749 return NULL;
750 }
751
752 return TclpNativeToNormalized(fileName);
753 }
754
755 /*
756 *----------------------------------------------------------------------
757 *
758 * TclpCreatePipe --
759 *
760 * Creates an anonymous pipe.
761 *
762 * Results:
763 * Returns 1 on success, 0 on failure.
764 *
765 * Side effects:
766 * Creates a pipe.
767 *
768 *----------------------------------------------------------------------
769 */
770
771 int
772 TclpCreatePipe(
773 TclFile *readPipe, /* Location to store file handle for read side
774 * of pipe. */
775 TclFile *writePipe) /* Location to store file handle for write
776 * side of pipe. */
777 {
778 HANDLE readHandle, writeHandle;
779
780 if (CreatePipe(&readHandle, &writeHandle, NULL, 0) != 0) {
781 *readPipe = TclWinMakeFile(readHandle);
782 *writePipe = TclWinMakeFile(writeHandle);
783 return 1;
784 }
785
786 TclWinConvertError(GetLastError());
787 return 0;
788 }
789
790 /*
791 *----------------------------------------------------------------------
792 *
793 * TclpCloseFile --
794 *
795 * Closes a pipeline file handle. These handles are created by
796 * TclpOpenFile, TclpCreatePipe, or TclpMakeFile.
797 *
798 * Results:
799 * 0 on success, -1 on failure.
800 *
801 * Side effects:
802 * The file is closed and deallocated.
803 *
804 *----------------------------------------------------------------------
805 */
806
807 int
808 TclpCloseFile(
809 TclFile file) /* The file to close. */
810 {
811 WinFile *filePtr = (WinFile *) file;
812
813 switch (filePtr->type) {
814 case WIN_FILE:
815 /*
816 * Don't close the Win32 handle if the handle is a standard channel
817 * during the thread exit process. Otherwise, one thread may kill the
818 * stdio of another.
819 */
820
821 if (!TclInThreadExit()
822 || ((GetStdHandle(STD_INPUT_HANDLE) != filePtr->handle)
823 && (GetStdHandle(STD_OUTPUT_HANDLE) != filePtr->handle)
824 && (GetStdHandle(STD_ERROR_HANDLE) != filePtr->handle))) {
825 if (filePtr->handle != NULL &&
826 CloseHandle(filePtr->handle) == FALSE) {
827 TclWinConvertError(GetLastError());
828 ckfree(filePtr);
829 return -1;
830 }
831 }
832 break;
833
834 default:
835 Tcl_Panic("TclpCloseFile: unexpected file type");
836 }
837
838 ckfree(filePtr);
839 return 0;
840 }
841
842 /*
843 *--------------------------------------------------------------------------
844 *
845 * TclpGetPid --
846 *
847 * Given a HANDLE to a child process, return the process id for that
848 * child process.
849 *
850 * Results:
851 * Returns the process id for the child process. If the pid was not known
852 * by Tcl, either because the pid was not created by Tcl or the child
853 * process has already been reaped, -1 is returned.
854 *
855 * Side effects:
856 * None.
857 *
858 *--------------------------------------------------------------------------
859 */
860
861 int
862 TclpGetPid(
863 Tcl_Pid pid) /* The HANDLE of the child process. */
864 {
865 ProcInfo *infoPtr;
866
867 PipeInit();
868
869 Tcl_MutexLock(&pipeMutex);
870 for (infoPtr = procList; infoPtr != NULL; infoPtr = infoPtr->nextPtr) {
871 if (infoPtr->hProcess == (HANDLE) pid) {
872 Tcl_MutexUnlock(&pipeMutex);
873 return infoPtr->dwProcessId;
874 }
875 }
876 Tcl_MutexUnlock(&pipeMutex);
877 return (unsigned long) -1;
878 }
879
880 /*
881 *----------------------------------------------------------------------
882 *
883 * TclpCreateProcess --
884 *
885 * Create a child process that has the specified files as its standard
886 * input, output, and error. The child process runs asynchronously under
887 * Windows NT and Windows 9x, and runs with the same environment
888 * variables as the creating process.
889 *
890 * The complete Windows search path is searched to find the specified
891 * executable. If an executable by the given name is not found,
892 * automatically tries appending standard extensions to the
893 * executable name.
894 *
895 * Results:
896 * The return value is TCL_ERROR and an error message is left in the
897 * interp's result if there was a problem creating the child process.
898 * Otherwise, the return value is TCL_OK and *pidPtr is filled with the
899 * process id of the child process.
900 *
901 * Side effects:
902 * A process is created.
903 *
904 *----------------------------------------------------------------------
905 */
906
907 int
908 TclpCreateProcess(
909 Tcl_Interp *interp, /* Interpreter in which to leave errors that
910 * occurred when creating the child process.
911 * Error messages from the child process
912 * itself are sent to errorFile. */
913 int argc, /* Number of arguments in following array. */
914 const char **argv, /* Array of argument strings. argv[0] contains
915 * the name of the executable converted to
916 * native format (using the
917 * Tcl_TranslateFileName call). Additional
918 * arguments have not been converted. */
919 TclFile inputFile, /* If non-NULL, gives the file to use as input
920 * for the child process. If inputFile file is
921 * not readable or is NULL, the child will
922 * receive no standard input. */
923 TclFile outputFile, /* If non-NULL, gives the file that receives
924 * output from the child process. If
925 * outputFile file is not writable or is
926 * NULL, output from the child will be
927 * discarded. */
928 TclFile errorFile, /* If non-NULL, gives the file that receives
929 * errors from the child process. If errorFile
930 * file is not writable or is NULL, errors
931 * from the child will be discarded. errorFile
932 * may be the same as outputFile. */
933 Tcl_Pid *pidPtr) /* If this function is successful, pidPtr is
934 * filled with the process id of the child
935 * process. */
936 {
937 int result, applType, createFlags;
938 Tcl_DString cmdLine; /* Complete command line (WCHAR). */
939 STARTUPINFOW startInfo;
940 PROCESS_INFORMATION procInfo;
941 SECURITY_ATTRIBUTES secAtts;
942 HANDLE hProcess, h, inputHandle, outputHandle, errorHandle;
943 char execPath[MAX_PATH * TCL_UTF_MAX];
944 WinFile *filePtr;
945
946 PipeInit();
947
948 applType = ApplicationType(interp, argv[0], execPath);
949 if (applType == APPL_NONE) {
950 return TCL_ERROR;
951 }
952
953 result = TCL_ERROR;
954 Tcl_DStringInit(&cmdLine);
955 hProcess = GetCurrentProcess();
956
957 /*
958 * STARTF_USESTDHANDLES must be used to pass handles to child process.
959 * Using SetStdHandle() and/or dup2() only works when a console mode
960 * parent process is spawning an attached console mode child process.
961 */
962
963 ZeroMemory(&startInfo, sizeof(startInfo));
964 startInfo.cb = sizeof(startInfo);
965 startInfo.dwFlags = STARTF_USESTDHANDLES;
966 startInfo.hStdInput = INVALID_HANDLE_VALUE;
967 startInfo.hStdOutput= INVALID_HANDLE_VALUE;
968 startInfo.hStdError = INVALID_HANDLE_VALUE;
969
970 secAtts.nLength = sizeof(SECURITY_ATTRIBUTES);
971 secAtts.lpSecurityDescriptor = NULL;
972 secAtts.bInheritHandle = TRUE;
973
974 /*
975 * We have to check the type of each file, since we cannot duplicate some
976 * file types.
977 */
978
979 inputHandle = INVALID_HANDLE_VALUE;
980 if (inputFile != NULL) {
981 filePtr = (WinFile *)inputFile;
982 if (filePtr->type == WIN_FILE) {
983 inputHandle = filePtr->handle;
984 }
985 }
986 outputHandle = INVALID_HANDLE_VALUE;
987 if (outputFile != NULL) {
988 filePtr = (WinFile *)outputFile;
989 if (filePtr->type == WIN_FILE) {
990 outputHandle = filePtr->handle;
991 }
992 }
993 errorHandle = INVALID_HANDLE_VALUE;
994 if (errorFile != NULL) {
995 filePtr = (WinFile *)errorFile;
996 if (filePtr->type == WIN_FILE) {
997 errorHandle = filePtr->handle;
998 }
999 }
1000
1001 /*
1002 * Duplicate all the handles which will be passed off as stdin, stdout and
1003 * stderr of the child process. The duplicate handles are set to be
1004 * inheritable, so the child process can use them.
1005 */
1006
1007 if (inputHandle == INVALID_HANDLE_VALUE) {
1008 /*
1009 * If handle was not set, stdin should return immediate EOF. Under
1010 * Windows95, some applications (both 16 and 32 bit!) cannot read from
1011 * the NUL device; they read from console instead. When running tk,
1012 * this is fatal because the child process would hang forever waiting
1013 * for EOF from the unmapped console window used by the helper
1014 * application.
1015 *
1016 * Fortunately, the helper application detects a closed pipe as an
1017 * immediate EOF and can pass that information to the child process.
1018 */
1019
1020 if (CreatePipe(&startInfo.hStdInput, &h, &secAtts, 0) != FALSE) {
1021 CloseHandle(h);
1022 }
1023 } else {
1024 DuplicateHandle(hProcess, inputHandle, hProcess, &startInfo.hStdInput,
1025 0, TRUE, DUPLICATE_SAME_ACCESS);
1026 }
1027 if (startInfo.hStdInput == INVALID_HANDLE_VALUE) {
1028 TclWinConvertError(GetLastError());
1029 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1030 "couldn't duplicate input handle: %s",
1031 Tcl_PosixError(interp)));
1032 goto end;
1033 }
1034
1035 if (outputHandle == INVALID_HANDLE_VALUE) {
1036 /*
1037 * If handle was not set, output should be sent to an infinitely deep
1038 * sink. Under Windows 95, some 16 bit applications cannot have stdout
1039 * redirected to NUL; they send their output to the console instead.
1040 * Some applications, like "more" or "dir /p", when outputting
1041 * multiple pages to the console, also then try and read from the
1042 * console to go the next page. When running tk, this is fatal because
1043 * the child process would hang forever waiting for input from the
1044 * unmapped console window used by the helper application.
1045 *
1046 * Fortunately, the helper application will detect a closed pipe as a
1047 * sink.
1048 */
1049
1050 startInfo.hStdOutput = CreateFileW(L"NUL:", GENERIC_WRITE, 0,
1051 &secAtts, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1052 } else {
1053 DuplicateHandle(hProcess, outputHandle, hProcess,
1054 &startInfo.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS);
1055 }
1056 if (startInfo.hStdOutput == INVALID_HANDLE_VALUE) {
1057 TclWinConvertError(GetLastError());
1058 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1059 "couldn't duplicate output handle: %s",
1060 Tcl_PosixError(interp)));
1061 goto end;
1062 }
1063
1064 if (errorHandle == INVALID_HANDLE_VALUE) {
1065 /*
1066 * If handle was not set, errors should be sent to an infinitely deep
1067 * sink.
1068 */
1069
1070 startInfo.hStdError = CreateFileW(L"NUL:", GENERIC_WRITE, 0,
1071 &secAtts, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1072 } else {
1073 DuplicateHandle(hProcess, errorHandle, hProcess, &startInfo.hStdError,
1074 0, TRUE, DUPLICATE_SAME_ACCESS);
1075 }
1076 if (startInfo.hStdError == INVALID_HANDLE_VALUE) {
1077 TclWinConvertError(GetLastError());
1078 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1079 "couldn't duplicate error handle: %s",
1080 Tcl_PosixError(interp)));
1081 goto end;
1082 }
1083
1084 /*
1085 * If we do not have a console window, then we must run DOS and WIN32
1086 * console mode applications as detached processes. This tells the loader
1087 * that the child application should not inherit the console, and that it
1088 * should not create a new console window for the child application. The
1089 * child application should get its stdio from the redirection handles
1090 * provided by this application, and run in the background.
1091 *
1092 * If we are starting a GUI process, they don't automatically get a
1093 * console, so it doesn't matter if they are started as foreground or
1094 * detached processes. The GUI window will still pop up to the foreground.
1095 */
1096
1097 if (HasConsole()) {
1098 createFlags = 0;
1099 } else if (applType == APPL_DOS) {
1100 /*
1101 * Under NT, 16-bit DOS applications will not run unless they can
1102 * be attached to a console. If we are running without a console,
1103 * run the 16-bit program as an normal process inside of a hidden
1104 * console application, and then run that hidden console as a
1105 * detached process.
1106 */
1107
1108 startInfo.wShowWindow = SW_HIDE;
1109 startInfo.dwFlags |= STARTF_USESHOWWINDOW;
1110 createFlags = CREATE_NEW_CONSOLE;
1111 TclDStringAppendLiteral(&cmdLine, "cmd.exe /c");
1112 } else {
1113 createFlags = DETACHED_PROCESS;
1114 }
1115
1116 /*
1117 * cmdLine gets the full command line used to invoke the executable,
1118 * including the name of the executable itself. The command line arguments
1119 * in argv[] are stored in cmdLine separated by spaces. Special characters
1120 * in individual arguments from argv[] must be quoted when being stored in
1121 * cmdLine.
1122 *
1123 * When calling any application, bear in mind that arguments that specify
1124 * a path name are not converted. If an argument contains forward slashes
1125 * as path separators, it may or may not be recognized as a path name,
1126 * depending on the program. In general, most applications accept forward
1127 * slashes only as option delimiters and backslashes only as paths.
1128 *
1129 * Additionally, when calling a 16-bit dos or windows application, all
1130 * path names must use the short, cryptic, path format (e.g., using
1131 * ab~1.def instead of "a b.default").
1132 */
1133
1134 BuildCommandLine(execPath, argc, argv, &cmdLine);
1135
1136 if (CreateProcessW(NULL, (WCHAR *) Tcl_DStringValue(&cmdLine),
1137 NULL, NULL, TRUE, (DWORD) createFlags, NULL, NULL, &startInfo,
1138 &procInfo) == 0) {
1139 TclWinConvertError(GetLastError());
1140 Tcl_SetObjResult(interp, Tcl_ObjPrintf("couldn't execute \"%s\": %s",
1141 argv[0], Tcl_PosixError(interp)));
1142 goto end;
1143 }
1144
1145 /*
1146 * This wait is used to force the OS to give some time to the DOS process.
1147 */
1148
1149 if (applType == APPL_DOS) {
1150 WaitForSingleObject(procInfo.hProcess, 50);
1151 }
1152
1153 /*
1154 * "When an application spawns a process repeatedly, a new thread instance
1155 * will be created for each process but the previous instances may not be
1156 * cleaned up. This results in a significant virtual memory loss each time
1157 * the process is spawned. If there is a WaitForInputIdle() call between
1158 * CreateProcess() and CloseHandle(), the problem does not occur." PSS ID
1159 * Number: Q124121
1160 */
1161
1162 WaitForInputIdle(procInfo.hProcess, 5000);
1163 CloseHandle(procInfo.hThread);
1164
1165 *pidPtr = (Tcl_Pid) procInfo.hProcess;
1166 if (*pidPtr != 0) {
1167 TclWinAddProcess(procInfo.hProcess, procInfo.dwProcessId);
1168 }
1169 result = TCL_OK;
1170
1171 end:
1172 Tcl_DStringFree(&cmdLine);
1173 if (startInfo.hStdInput != INVALID_HANDLE_VALUE) {
1174 CloseHandle(startInfo.hStdInput);
1175 }
1176 if (startInfo.hStdOutput != INVALID_HANDLE_VALUE) {
1177 CloseHandle(startInfo.hStdOutput);
1178 }
1179 if (startInfo.hStdError != INVALID_HANDLE_VALUE) {
1180 CloseHandle(startInfo.hStdError);
1181 }
1182 return result;
1183 }
1184
1185
1186 /*
1187 *----------------------------------------------------------------------
1188 *
1189 * HasConsole --
1190 *
1191 * Determines whether the current application is attached to a console.
1192 *
1193 * Results:
1194 * Returns TRUE if this application has a console, else FALSE.
1195 *
1196 * Side effects:
1197 * None.
1198 *
1199 *----------------------------------------------------------------------
1200 */
1201
1202 static BOOL
1203 HasConsole(void)
1204 {
1205 HANDLE handle;
1206
1207 handle = CreateFileW(L"CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE,
1208 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1209
1210 if (handle != INVALID_HANDLE_VALUE) {
1211 CloseHandle(handle);
1212 return TRUE;
1213 } else {
1214 return FALSE;
1215 }
1216 }
1217
1218 /*
1219 *--------------------------------------------------------------------
1220 *
1221 * ApplicationType --
1222 *
1223 * Search for the specified program and identify if it refers to a DOS,
1224 * Windows 3.X, or Win32 program. Used to determine how to invoke a
1225 * program, or if it can even be invoked.
1226 *
1227 * It is possible to almost positively identify DOS and Windows
1228 * applications that contain the appropriate magic numbers. However, DOS
1229 * .com files do not seem to contain a magic number; if the program name
1230 * ends with .com and could not be identified as a Windows .com file, it
1231 * will be assumed to be a DOS application, even if it was just random
1232 * data. If the program name does not end with .com, no such assumption
1233 * is made.
1234 *
1235 * The Win32 function GetBinaryType incorrectly identifies any junk file
1236 * that ends with .exe as a dos executable and some executables that
1237 * don't end with .exe as not executable. Plus it doesn't exist under
1238 * win95, so I won't feel bad about reimplementing functionality.
1239 *
1240 * Results:
1241 * The return value is one of APPL_DOS, APPL_WIN3X, or APPL_WIN32 if the
1242 * filename referred to the corresponding application type. If the file
1243 * name could not be found or did not refer to any known application
1244 * type, APPL_NONE is returned and an error message is left in interp.
1245 * .bat files are identified as APPL_DOS.
1246 *
1247 * Side effects:
1248 * None.
1249 *
1250 *----------------------------------------------------------------------
1251 */
1252
1253 static int
1254 ApplicationType(
1255 Tcl_Interp *interp, /* Interp, for error message. */
1256 const char *originalName, /* Name of the application to find. */
1257 char fullName[]) /* Filled with complete path to
1258 * application. */
1259 {
1260 int applType, i, nameLen, found;
1261 HANDLE hFile;
1262 WCHAR *rest;
1263 char *ext;
1264 char buf[2];
1265 DWORD attr, read;
1266 IMAGE_DOS_HEADER header;
1267 Tcl_DString nameBuf, ds;
1268 const WCHAR *nativeName;
1269 WCHAR nativeFullPath[MAX_PATH];
1270 static const char extensions[][5] = {"", ".com", ".exe", ".bat", ".cmd"};
1271
1272 /*
1273 * Look for the program as an external program. First try the name as it
1274 * is, then try adding .com, .exe, .bat and .cmd, in that order, to the name,
1275 * looking for an executable.
1276 *
1277 * Using the raw SearchPathW() function doesn't do quite what is necessary.
1278 * If the name of the executable already contains a '.' character, it will
1279 * not try appending the specified extension when searching (in other
1280 * words, SearchPathW will not find the program "a.b.exe" if the arguments
1281 * specified "a.b" and ".exe"). So, first look for the file as it is
1282 * named. Then manually append the extensions, looking for a match.
1283 */
1284
1285 applType = APPL_NONE;
1286 Tcl_DStringInit(&nameBuf);
1287 Tcl_DStringAppend(&nameBuf, originalName, -1);
1288 nameLen = Tcl_DStringLength(&nameBuf);
1289
1290 for (i = 0; i < (int) (sizeof(extensions) / sizeof(extensions[0])); i++) {
1291 Tcl_DStringSetLength(&nameBuf, nameLen);
1292 Tcl_DStringAppend(&nameBuf, extensions[i], -1);
1293 nativeName = (WCHAR *)Tcl_WinUtfToTChar(Tcl_DStringValue(&nameBuf),
1294 Tcl_DStringLength(&nameBuf), &ds);
1295 found = SearchPathW(NULL, nativeName, NULL, MAX_PATH,
1296 nativeFullPath, &rest);
1297 Tcl_DStringFree(&ds);
1298 if (found == 0) {
1299 continue;
1300 }
1301
1302 /*
1303 * Ignore matches on directories or data files, return if identified a
1304 * known type.
1305 */
1306
1307 attr = GetFileAttributesW(nativeFullPath);
1308 if ((attr == 0xFFFFFFFF) || (attr & FILE_ATTRIBUTE_DIRECTORY)) {
1309 continue;
1310 }
1311 strcpy(fullName, Tcl_WinTCharToUtf((TCHAR *)nativeFullPath, -1, &ds));
1312 Tcl_DStringFree(&ds);
1313
1314 ext = strrchr(fullName, '.');
1315 if ((ext != NULL) &&
1316 (strcasecmp(ext, ".cmd") == 0 || strcasecmp(ext, ".bat") == 0)) {
1317 applType = APPL_DOS;
1318 break;
1319 }
1320
1321 hFile = CreateFileW(nativeFullPath,
1322 GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
1323 FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OPEN_REPARSE_POINT, NULL);
1324 if (hFile == INVALID_HANDLE_VALUE) {
1325 continue;
1326 }
1327
1328 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
1329 /*
1330 * But [4f0b5767ac]. Likely a App Execution Alias. This can only
1331 * be a Win32 APP. Attempt to ReadFile below will fail. We assume
1332 * that if it is on the PATH, and it is a reparse point, it is an
1333 * App Execution Alias.
1334 */
1335 CloseHandle(hFile);
1336 applType = APPL_WIN32;
1337 break;
1338 }
1339
1340 header.e_magic = 0;
1341 ReadFile(hFile, (void *) &header, sizeof(header), &read, NULL);
1342 if (header.e_magic != IMAGE_DOS_SIGNATURE) {
1343 /*
1344 * Doesn't have the magic number for relocatable executables. If
1345 * filename ends with .com, assume it's a DOS application anyhow.
1346 * Note that we didn't make this assumption at first, because some
1347 * supposed .com files are really 32-bit executables with all the
1348 * magic numbers and everything.
1349 */
1350
1351 CloseHandle(hFile);
1352 if ((ext != NULL) && (strcasecmp(ext, ".com") == 0)) {
1353 applType = APPL_DOS;
1354 break;
1355 }
1356 continue;
1357 }
1358 if (header.e_lfarlc != sizeof(header)) {
1359 /*
1360 * All Windows 3.X and Win32 and some DOS programs have this value
1361 * set here. If it doesn't, assume that since it already had the
1362 * other magic number it was a DOS application.
1363 */
1364
1365 CloseHandle(hFile);
1366 applType = APPL_DOS;
1367 break;
1368 }
1369
1370 /*
1371 * The DWORD at header.e_lfanew points to yet another magic number.
1372 */
1373
1374 buf[0] = '\0';
1375 SetFilePointer(hFile, header.e_lfanew, NULL, FILE_BEGIN);
1376 ReadFile(hFile, (void *) buf, 2, &read, NULL);
1377 CloseHandle(hFile);
1378
1379 if ((buf[0] == 'N') && (buf[1] == 'E')) {
1380 applType = APPL_WIN3X;
1381 } else if ((buf[0] == 'P') && (buf[1] == 'E')) {
1382 applType = APPL_WIN32;
1383 } else {
1384 /*
1385 * Strictly speaking, there should be a test that there is an 'L'
1386 * and 'E' at buf[0..1], to identify the type as DOS, but of
1387 * course we ran into a DOS executable that _doesn't_ have the
1388 * magic number - specifically, one compiled using the Lahey
1389 * Fortran90 compiler.
1390 */
1391
1392 applType = APPL_DOS;
1393 }
1394 break;
1395 }
1396 Tcl_DStringFree(&nameBuf);
1397
1398 if (applType == APPL_NONE) {
1399 TclWinConvertError(GetLastError());
1400 Tcl_SetObjResult(interp, Tcl_ObjPrintf("couldn't execute \"%s\": %s",
1401 originalName, Tcl_PosixError(interp)));
1402 return APPL_NONE;
1403 }
1404
1405 if (applType == APPL_WIN3X) {
1406 /*
1407 * Replace long path name of executable with short path name for
1408 * 16-bit applications. Otherwise the application may not be able to
1409 * correctly parse its own command line to separate off the
1410 * application name from the arguments.
1411 */
1412
1413 GetShortPathNameW(nativeFullPath, nativeFullPath, MAX_PATH);
1414 strcpy(fullName, Tcl_WinTCharToUtf((TCHAR *)nativeFullPath, -1, &ds));
1415 Tcl_DStringFree(&ds);
1416 }
1417 return applType;
1418 }
1419
1420 /*
1421 *----------------------------------------------------------------------
1422 *
1423 * BuildCommandLine --
1424 *
1425 * The command line arguments are stored in linePtr separated by spaces,
1426 * in a form that CreateProcess() understands. Special characters in
1427 * individual arguments from argv[] must be quoted when being stored in
1428 * cmdLine.
1429 *
1430 * Results:
1431 * None.
1432 *
1433 * Side effects:
1434 * None.
1435 *
1436 *----------------------------------------------------------------------
1437 */
1438
1439 static const char *
1440 BuildCmdLineBypassBS(
1441 const char *current,
1442 const char **bspos)
1443 {
1444 /*
1445 * Mark first backslash position.
1446 */
1447
1448 if (!*bspos) {
1449 *bspos = current;
1450 }
1451 do {
1452 current++;
1453 } while (*current == '\\');
1454 return current;
1455 }
1456
1457 static void
1458 QuoteCmdLineBackslash(
1459 Tcl_DString *dsPtr,
1460 const char *start,
1461 const char *current,
1462 const char *bspos)
1463 {
1464 if (!bspos) {
1465 if (current > start) { /* part before current (special) */
1466 Tcl_DStringAppend(dsPtr, start, (int) (current - start));
1467 }
1468 } else {
1469 if (bspos > start) { /* part before first backslash */
1470 Tcl_DStringAppend(dsPtr, start, (int) (bspos - start));
1471 }
1472 while (bspos++ < current) { /* each backslash twice */
1473 TclDStringAppendLiteral(dsPtr, "\\\\");
1474 }
1475 }
1476 }
1477
1478 static const char *
1479 QuoteCmdLinePart(
1480 Tcl_DString *dsPtr,
1481 const char *start,
1482 const char *special,
1483 const char *specMetaChars,
1484 const char **bspos)
1485 {
1486 if (!*bspos) {
1487 /*
1488 * Rest before special (before quote).
1489 */
1490
1491 QuoteCmdLineBackslash(dsPtr, start, special, NULL);
1492 start = special;
1493 } else {
1494 /*
1495 * Rest before first backslash and backslashes into new quoted block.
1496 */
1497
1498 QuoteCmdLineBackslash(dsPtr, start, *bspos, NULL);
1499 start = *bspos;
1500 }
1501
1502 /*
1503 * escape all special chars enclosed in quotes like `"..."`, note that
1504 * here we don't must escape `\` (with `\`), because it's outside of the
1505 * main quotes, so `\` remains `\`, but important - not at end of part,
1506 * because results as before the quote, so `%\%\` should be escaped as
1507 * `"%\%"\\`).
1508 */
1509
1510 TclDStringAppendLiteral(dsPtr, "\""); /* opening escape quote-char */
1511 do {
1512 *bspos = NULL;
1513 special++;
1514 if (*special == '\\') {
1515 /*
1516 * Bypass backslashes (and mark first backslash position).
1517 */
1518
1519 special = BuildCmdLineBypassBS(special, bspos);
1520 if (*special == '\0') {
1521 break;
1522 }
1523 }
1524 } while (*special && strchr(specMetaChars, *special));
1525 if (!*bspos) {
1526 /*
1527 * Unescaped rest before quote.
1528 */
1529
1530 QuoteCmdLineBackslash(dsPtr, start, special, NULL);
1531 } else {
1532 /*
1533 * Unescaped rest before first backslash (rather belongs to the main
1534 * block).
1535 */
1536
1537 QuoteCmdLineBackslash(dsPtr, start, *bspos, NULL);
1538 }
1539 TclDStringAppendLiteral(dsPtr, "\""); /* closing escape quote-char */
1540 return special;
1541 }
1542
1543 static void
1544 BuildCommandLine(
1545 const char *executable, /* Full path of executable (including
1546 * extension). Replacement for argv[0]. */
1547 int argc, /* Number of arguments. */
1548 const char **argv, /* Argument strings in UTF. */
1549 Tcl_DString *linePtr) /* Initialized Tcl_DString that receives the
1550 * command line (WCHAR). */
1551 {
1552 const char *arg, *start, *special, *bspos;
1553 int quote = 0, i;
1554 Tcl_DString ds;
1555 #ifdef TCL_WIN_PIPE_FULLESC
1556 /* full escape inclusive %-subst avoidance */
1557 static const char specMetaChars[] = "&|^<>!()%";
1558 /* Characters to enclose in quotes if unpaired
1559 * quote flag set. */
1560 static const char specMetaChars2[] = "%";
1561 /* Character to enclose in quotes in any case
1562 * (regardless of unpaired-flag). */
1563 #else
1564 /* escape considering quotation only (no %-subst avoidance) */
1565 static const char specMetaChars[] = "&|^<>!()";
1566 /* Characters to enclose in quotes if unpaired
1567 * quote flag set. */
1568 #endif
1569 /*
1570 * Quote flags:
1571 * CL_ESCAPE - escape argument;
1572 * CL_QUOTE - enclose in quotes;
1573 * CL_UNPAIRED - previous arguments chain contains unpaired quote-char;
1574 */
1575 enum {CL_ESCAPE = 1, CL_QUOTE = 2, CL_UNPAIRED = 4};
1576
1577 Tcl_DStringInit(&ds);
1578
1579 /*
1580 * Prime the path. Add a space separator if we were primed with something.
1581 */
1582
1583 TclDStringAppendDString(&ds, linePtr);
1584 if (Tcl_DStringLength(linePtr) > 0) {
1585 TclDStringAppendLiteral(&ds, " ");
1586 }
1587
1588 for (i = 0; i < argc; i++) {
1589 if (i == 0) {
1590 arg = executable;
1591 } else {
1592 arg = argv[i];
1593 TclDStringAppendLiteral(&ds, " ");
1594 }
1595
1596 quote &= ~(CL_ESCAPE|CL_QUOTE); /* reset escape flags */
1597 bspos = NULL;
1598 if (arg[0] == '\0') {
1599 quote = CL_QUOTE;
1600 } else {
1601 for (start = arg;
1602 *start != '\0' &&
1603 (quote & (CL_ESCAPE|CL_QUOTE)) != (CL_ESCAPE|CL_QUOTE);
1604 start++) {
1605 if (*start & 0x80) {
1606 continue;
1607 }
1608 if (TclIsSpaceProc(*start)) {
1609 quote |= CL_QUOTE; /* quote only */
1610 if (bspos) { /* if backslash found, escape & quote */
1611 quote |= CL_ESCAPE;
1612 break;
1613 }
1614 continue;
1615 }
1616 if (strchr(specMetaChars, *start)) {
1617 quote |= (CL_ESCAPE|CL_QUOTE); /* escape & quote */
1618 break;
1619 }
1620 if (*start == '"') {
1621 quote |= CL_ESCAPE; /* escape only */
1622 continue;
1623 }
1624 if (*start == '\\') {
1625 bspos = start;
1626 if (quote & CL_QUOTE) { /* if quote, escape & quote */
1627 quote |= CL_ESCAPE;
1628 break;
1629 }
1630 continue;
1631 }
1632 }
1633 bspos = NULL;
1634 }
1635 if (quote & CL_QUOTE) {
1636 /*
1637 * Start of argument (main opening quote-char).
1638 */
1639
1640 TclDStringAppendLiteral(&ds, "\"");
1641 }
1642 if (!(quote & CL_ESCAPE)) {
1643 /*
1644 * Nothing to escape.
1645 */
1646
1647 Tcl_DStringAppend(&ds, arg, -1);
1648 } else {
1649 start = arg;
1650 for (special = arg; *special != '\0'; ) {
1651 /*
1652 * Position of `\` is important before quote or at end (equal
1653 * `\"` because quoted).
1654 */
1655
1656 if (*special == '\\') {
1657 /*
1658 * Bypass backslashes (and mark first backslash position)
1659 */
1660
1661 special = BuildCmdLineBypassBS(special, &bspos);
1662 if (*special == '\0') {
1663 break;
1664 }
1665 }
1666 /* ["] */
1667 if (*special == '"') {
1668 /*
1669 * Invert the unpaired flag - observe unpaired quotes
1670 */
1671
1672 quote ^= CL_UNPAIRED;
1673
1674 /*
1675 * Add part before (and escape backslashes before quote).
1676 */
1677
1678 QuoteCmdLineBackslash(&ds, start, special, bspos);
1679 bspos = NULL;
1680
1681 /*
1682 * Escape using backslash
1683 */
1684
1685 TclDStringAppendLiteral(&ds, "\\\"");
1686 start = ++special;
1687 continue;
1688 }
1689
1690 /*
1691 * Unpaired (escaped) quote causes special handling on
1692 * meta-chars
1693 */
1694
1695 if ((quote & CL_UNPAIRED) && strchr(specMetaChars, *special)) {
1696 special = QuoteCmdLinePart(&ds, start, special,
1697 specMetaChars, &bspos);
1698
1699 /*
1700 * Start to current or first backslash
1701 */
1702
1703 start = !bspos ? special : bspos;
1704 continue;
1705 }
1706 #ifdef TCL_WIN_PIPE_FULLESC
1707 /*
1708 * Special case for % - should be enclosed always (paired
1709 * also)
1710 */
1711
1712 if (strchr(specMetaChars2, *special)) {
1713 special = QuoteCmdLinePart(&ds, start, special,
1714 specMetaChars2, &bspos);
1715
1716 /*
1717 * Start to current or first backslash.
1718 */
1719
1720 start = !bspos ? special : bspos;
1721 continue;
1722 }
1723 #endif
1724
1725 /*
1726 * Other not special (and not meta) character
1727 */
1728
1729 bspos = NULL; /* reset last backslash position (not
1730 * interesting) */
1731 special++;
1732 }
1733
1734 /*
1735 * Rest of argument (and escape backslashes before closing main
1736 * quote)
1737 */
1738
1739 QuoteCmdLineBackslash(&ds, start, special,
1740 (quote & CL_QUOTE) ? bspos : NULL);
1741 }
1742 if (quote & CL_QUOTE) {
1743 /*
1744 * End of argument (main closing quote-char)
1745 */
1746
1747 TclDStringAppendLiteral(&ds, "\"");
1748 }
1749 }
1750 Tcl_DStringFree(linePtr);
1751 Tcl_WinUtfToTChar(Tcl_DStringValue(&ds), Tcl_DStringLength(&ds), linePtr);
1752 Tcl_DStringFree(&ds);
1753 }
1754
1755 /*
1756 *----------------------------------------------------------------------
1757 *
1758 * TclpCreateCommandChannel --
1759 *
1760 * This function is called by Tcl_OpenCommandChannel to perform the
1761 * platform specific channel initialization for a command channel.
1762 *
1763 * Results:
1764 * Returns a new channel or NULL on failure.
1765 *
1766 * Side effects:
1767 * Allocates a new channel.
1768 *
1769 *----------------------------------------------------------------------
1770 */
1771
1772 Tcl_Channel
1773 TclpCreateCommandChannel(
1774 TclFile readFile, /* If non-null, gives the file for reading. */
1775 TclFile writeFile, /* If non-null, gives the file for writing. */
1776 TclFile errorFile, /* If non-null, gives the file where errors
1777 * can be read. */
1778 int numPids, /* The number of pids in the pid array. */
1779 Tcl_Pid *pidPtr) /* An array of process identifiers. */
1780 {
1781 char channelName[16 + TCL_INTEGER_SPACE];
1782 PipeInfo *infoPtr = (PipeInfo *)ckalloc(sizeof(PipeInfo));
1783
1784 PipeInit();
1785
1786 infoPtr->watchMask = 0;
1787 infoPtr->flags = 0;
1788 infoPtr->readFlags = 0;
1789 infoPtr->readFile = readFile;
1790 infoPtr->writeFile = writeFile;
1791 infoPtr->errorFile = errorFile;
1792 infoPtr->numPids = numPids;
1793 infoPtr->pidPtr = pidPtr;
1794 infoPtr->writeBuf = 0;
1795 infoPtr->writeBufLen = 0;
1796 infoPtr->writeError = 0;
1797 infoPtr->channel = NULL;
1798
1799 infoPtr->validMask = 0;
1800
1801 infoPtr->threadId = Tcl_GetCurrentThread();
1802
1803 if (readFile != NULL) {
1804 /*
1805 * Start the background reader thread.
1806 */
1807
1808 infoPtr->readable = CreateEventW(NULL, TRUE, TRUE, NULL);
1809 infoPtr->readThread = CreateThread(NULL, 256, PipeReaderThread,
1810 TclPipeThreadCreateTI(&infoPtr->readTI, infoPtr, infoPtr->readable),
1811 0, NULL);
1812 SetThreadPriority(infoPtr->readThread, THREAD_PRIORITY_HIGHEST);
1813 infoPtr->validMask |= TCL_READABLE;
1814 } else {
1815 infoPtr->readTI = NULL;
1816 infoPtr->readThread = 0;
1817 }
1818 if (writeFile != NULL) {
1819 /*
1820 * Start the background writer thread.
1821 */
1822
1823 infoPtr->writable = CreateEventW(NULL, TRUE, TRUE, NULL);
1824 infoPtr->writeThread = CreateThread(NULL, 256, PipeWriterThread,
1825 TclPipeThreadCreateTI(&infoPtr->writeTI, infoPtr, infoPtr->writable),
1826 0, NULL);
1827 SetThreadPriority(infoPtr->writeThread, THREAD_PRIORITY_HIGHEST);
1828 infoPtr->validMask |= TCL_WRITABLE;
1829 } else {
1830 infoPtr->writeTI = NULL;
1831 infoPtr->writeThread = 0;
1832 }
1833
1834 /*
1835 * For backward compatibility with previous versions of Tcl, we use
1836 * "file%d" as the base name for pipes even though it would be more
1837 * natural to use "pipe%d". Use the pointer to keep the channel names
1838 * unique, in case channels share handles (stdin/stdout).
1839 */
1840
1841 snprintf(channelName, sizeof(channelName), "file%" TCL_Z_MODIFIER "x", (size_t) infoPtr);
1842 infoPtr->channel = Tcl_CreateChannel(&pipeChannelType, channelName,
1843 infoPtr, infoPtr->validMask);
1844
1845 /*
1846 * Pipes have AUTO translation mode on Windows and ^Z eof char, which
1847 * means that a ^Z will be appended to them at close. This is needed for
1848 * Windows programs that expect a ^Z at EOF.
1849 */
1850
1851 Tcl_SetChannelOption(NULL, infoPtr->channel, "-translation", "auto");
1852 Tcl_SetChannelOption(NULL, infoPtr->channel, "-eofchar", "\032 {}");
1853 return infoPtr->channel;
1854 }
1855
1856 /*
1857 *----------------------------------------------------------------------
1858 *
1859 * Tcl_CreatePipe --
1860 *
1861 * System dependent interface to create a pipe for the [chan pipe]
1862 * command. Stolen from TclX.
1863 *
1864 * Results:
1865 * TCL_OK or TCL_ERROR.
1866 *
1867 *----------------------------------------------------------------------
1868 */
1869
1870 int
1871 Tcl_CreatePipe(
1872 Tcl_Interp *interp, /* Errors returned in result.*/
1873 Tcl_Channel *rchan, /* Where to return the read side. */
1874 Tcl_Channel *wchan, /* Where to return the write side. */
1875 int flags) /* Reserved for future use. */
1876 {
1877 HANDLE readHandle, writeHandle;
1878 SECURITY_ATTRIBUTES sec;
1879
1880 sec.nLength = sizeof(SECURITY_ATTRIBUTES);
1881 sec.lpSecurityDescriptor = NULL;
1882 sec.bInheritHandle = FALSE;
1883
1884 if (!CreatePipe(&readHandle, &writeHandle, &sec, 0)) {
1885 TclWinConvertError(GetLastError());
1886 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1887 "pipe creation failed: %s", Tcl_PosixError(interp)));
1888 return TCL_ERROR;
1889 }
1890
1891 *rchan = Tcl_MakeFileChannel((ClientData) readHandle, TCL_READABLE);
1892 Tcl_RegisterChannel(interp, *rchan);
1893
1894 *wchan = Tcl_MakeFileChannel((ClientData) writeHandle, TCL_WRITABLE);
1895 Tcl_RegisterChannel(interp, *wchan);
1896
1897 return TCL_OK;
1898 }
1899
1900 /*
1901 *----------------------------------------------------------------------
1902 *
1903 * TclGetAndDetachPids --
1904 *
1905 * Stores a list of the command PIDs for a command channel in the
1906 * interp's result.
1907 *
1908 * Results:
1909 * None.
1910 *
1911 * Side effects:
1912 * Modifies the interp's result.
1913 *
1914 *----------------------------------------------------------------------
1915 */
1916
1917 void
1918 TclGetAndDetachPids(
1919 Tcl_Interp *interp,
1920 Tcl_Channel chan)
1921 {
1922 PipeInfo *pipePtr;
1923 const Tcl_ChannelType *chanTypePtr;
1924 Tcl_Obj *pidsObj;
1925 int i;
1926
1927 /*
1928 * Punt if the channel is not a command channel.
1929 */
1930
1931 chanTypePtr = Tcl_GetChannelType(chan);
1932 if (chanTypePtr != &pipeChannelType) {
1933 return;
1934 }
1935
1936 pipePtr = (PipeInfo *)Tcl_GetChannelInstanceData(chan);
1937 TclNewObj(pidsObj);
1938 for (i = 0; i < pipePtr->numPids; i++) {
1939 Tcl_ListObjAppendElement(NULL, pidsObj,
1940 Tcl_NewWideIntObj((unsigned)
1941 TclpGetPid(pipePtr->pidPtr[i])));
1942 Tcl_DetachPids(1, &pipePtr->pidPtr[i]);
1943 }
1944 Tcl_SetObjResult(interp, pidsObj);
1945 if (pipePtr->numPids > 0) {
1946 ckfree(pipePtr->pidPtr);
1947 pipePtr->numPids = 0;
1948 }
1949 }
1950
1951 /*
1952 *----------------------------------------------------------------------
1953 *
1954 * PipeBlockModeProc --
1955 *
1956 * Set blocking or non-blocking mode on channel.
1957 *
1958 * Results:
1959 * 0 if successful, errno when failed.
1960 *
1961 * Side effects:
1962 * Sets the device into blocking or non-blocking mode.
1963 *
1964 *----------------------------------------------------------------------
1965 */
1966
1967 static int
1968 PipeBlockModeProc(
1969 ClientData instanceData, /* Instance data for channel. */
1970 int mode) /* TCL_MODE_BLOCKING or
1971 * TCL_MODE_NONBLOCKING. */
1972 {
1973 PipeInfo *infoPtr = (PipeInfo *) instanceData;
1974
1975 /*
1976 * Pipes on Windows can not be switched between blocking and nonblocking,
1977 * hence we have to emulate the behavior. This is done in the input
1978 * function by checking against a bit in the state. We set or unset the
1979 * bit here to cause the input function to emulate the correct behavior.
1980 */
1981
1982 if (mode == TCL_MODE_NONBLOCKING) {
1983 infoPtr->flags |= PIPE_ASYNC;
1984 } else {
1985 infoPtr->flags &= ~(PIPE_ASYNC);
1986 }
1987 return 0;
1988 }
1989
1990 /*
1991 *----------------------------------------------------------------------
1992 *
1993 * PipeClose2Proc --
1994 *
1995 * Closes a pipe based IO channel.
1996 *
1997 * Results:
1998 * 0 on success, errno otherwise.
1999 *
2000 * Side effects:
2001 * Closes the physical channel.
2002 *
2003 *----------------------------------------------------------------------
2004 */
2005
2006 static int
2007 PipeClose2Proc(
2008 ClientData instanceData, /* Pointer to PipeInfo structure. */
2009 Tcl_Interp *interp, /* For error reporting. */
2010 int flags) /* Flags that indicate which side to close. */
2011 {
2012 PipeInfo *pipePtr = (PipeInfo *) instanceData;
2013 Tcl_Channel errChan;
2014 int errorCode, result;
2015 PipeInfo *infoPtr, **nextPtrPtr;
2016 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
2017 int inExit = (TclInExit() || TclInThreadExit());
2018
2019 errorCode = 0;
2020 result = 0;
2021
2022 if ((!flags || flags & TCL_CLOSE_READ) && (pipePtr->readFile != NULL)) {
2023 /*
2024 * Clean up the background thread if necessary. Note that this must be
2025 * done before we can close the file, since the thread may be blocking
2026 * trying to read from the pipe.
2027 */
2028
2029 if (pipePtr->readThread) {
2030
2031 TclPipeThreadStop(&pipePtr->readTI, pipePtr->readThread);
2032 CloseHandle(pipePtr->readThread);
2033 CloseHandle(pipePtr->readable);
2034 pipePtr->readThread = NULL;
2035 }
2036 if (TclpCloseFile(pipePtr->readFile) != 0) {
2037 errorCode = errno;
2038 }
2039 pipePtr->validMask &= ~TCL_READABLE;
2040 pipePtr->readFile = NULL;
2041 }
2042 if ((!flags || flags & TCL_CLOSE_WRITE) && (pipePtr->writeFile != NULL)) {
2043 if (pipePtr->writeThread) {
2044
2045 /*
2046 * Wait for the writer thread to finish the current buffer, then
2047 * terminate the thread and close the handles. If the channel is
2048 * nonblocking or may block during exit, bail out since the worker
2049 * thread is not interruptible and we want TIP#398-fast-exit.
2050 */
2051 if ((pipePtr->flags & PIPE_ASYNC) && inExit) {
2052
2053 /* give it a chance to leave honorably */
2054 TclPipeThreadStopSignal(&pipePtr->writeTI, pipePtr->writable);
2055
2056 if (WaitForSingleObject(pipePtr->writable, 20) == WAIT_TIMEOUT) {
2057 return EWOULDBLOCK;
2058 }
2059
2060 } else {
2061
2062 WaitForSingleObject(pipePtr->writable, inExit ? 5000 : INFINITE);
2063
2064 }
2065
2066 TclPipeThreadStop(&pipePtr->writeTI, pipePtr->writeThread);
2067
2068 CloseHandle(pipePtr->writable);
2069 CloseHandle(pipePtr->writeThread);
2070 pipePtr->writeThread = NULL;
2071 }
2072 if (TclpCloseFile(pipePtr->writeFile) != 0) {
2073 if (errorCode == 0) {
2074 errorCode = errno;
2075 }
2076 }
2077 pipePtr->validMask &= ~TCL_WRITABLE;
2078 pipePtr->writeFile = NULL;
2079 }
2080
2081 pipePtr->watchMask &= pipePtr->validMask;
2082
2083 /*
2084 * Don't free the channel if any of the flags were set.
2085 */
2086
2087 if (flags) {
2088 return errorCode;
2089 }
2090
2091 /*
2092 * Remove the file from the list of watched files.
2093 */
2094
2095 for (nextPtrPtr = &(tsdPtr->firstPipePtr), infoPtr = *nextPtrPtr;
2096 infoPtr != NULL;
2097 nextPtrPtr = &infoPtr->nextPtr, infoPtr = *nextPtrPtr) {
2098 if (infoPtr == (PipeInfo *)pipePtr) {
2099 *nextPtrPtr = infoPtr->nextPtr;
2100 break;
2101 }
2102 }
2103
2104 if ((pipePtr->flags & PIPE_ASYNC) || inExit) {
2105 /*
2106 * If the channel is non-blocking or Tcl is being cleaned up, just
2107 * detach the children PIDs, reap them (important if we are in a
2108 * dynamic load module), and discard the errorFile.
2109 */
2110
2111 Tcl_DetachPids(pipePtr->numPids, pipePtr->pidPtr);
2112 Tcl_ReapDetachedProcs();
2113
2114 if (pipePtr->errorFile) {
2115 if (TclpCloseFile(pipePtr->errorFile) != 0) {
2116 if (errorCode == 0) {
2117 errorCode = errno;
2118 }
2119 }
2120 }
2121 result = 0;
2122 } else {
2123 /*
2124 * Wrap the error file into a channel and give it to the cleanup
2125 * routine.
2126 */
2127
2128 if (pipePtr->errorFile) {
2129 WinFile *filePtr = (WinFile *) pipePtr->errorFile;
2130
2131 errChan = Tcl_MakeFileChannel((ClientData) filePtr->handle,
2132 TCL_READABLE);
2133 ckfree(filePtr);
2134 } else {
2135 errChan = NULL;
2136 }
2137
2138 result = TclCleanupChildren(interp, pipePtr->numPids,
2139 pipePtr->pidPtr, errChan);
2140 }
2141
2142 if (pipePtr->numPids > 0) {
2143 ckfree(pipePtr->pidPtr);
2144 }
2145
2146 if (pipePtr->writeBuf != NULL) {
2147 ckfree(pipePtr->writeBuf);
2148 }
2149
2150 ckfree(pipePtr);
2151
2152 if (errorCode == 0) {
2153 return result;
2154 }
2155 return errorCode;
2156 }
2157
2158 /*
2159 *----------------------------------------------------------------------
2160 *
2161 * PipeInputProc --
2162 *
2163 * Reads input from the IO channel into the buffer given. Returns count
2164 * of how many bytes were actually read, and an error indication.
2165 *
2166 * Results:
2167 * A count of how many bytes were read is returned and an error
2168 * indication is returned in an output argument.
2169 *
2170 * Side effects:
2171 * Reads input from the actual channel.
2172 *
2173 *----------------------------------------------------------------------
2174 */
2175
2176 static int
2177 PipeInputProc(
2178 ClientData instanceData, /* Pipe state. */
2179 char *buf, /* Where to store data read. */
2180 int bufSize, /* How much space is available in the
2181 * buffer? */
2182 int *errorCode) /* Where to store error code. */
2183 {
2184 PipeInfo *infoPtr = (PipeInfo *) instanceData;
2185 WinFile *filePtr = (WinFile*) infoPtr->readFile;
2186 DWORD count, bytesRead = 0;
2187 int result;
2188
2189 *errorCode = 0;
2190 /*
2191 * Synchronize with the reader thread.
2192 */
2193
2194 result = WaitForRead(infoPtr, (infoPtr->flags & PIPE_ASYNC) ? 0 : 1);
2195
2196 /*
2197 * If an error occurred, return immediately.
2198 */
2199
2200 if (result == -1) {
2201 *errorCode = errno;
2202 return -1;
2203 }
2204
2205 if (infoPtr->readFlags & PIPE_EXTRABYTE) {
2206 /*
2207 * The reader thread consumed 1 byte as a side effect of waiting so we
2208 * need to move it into the buffer.
2209 */
2210
2211 *buf = infoPtr->extraByte;
2212 infoPtr->readFlags &= ~PIPE_EXTRABYTE;
2213 buf++;
2214 bufSize--;
2215 bytesRead = 1;
2216
2217 /*
2218 * If further read attempts would block, return what we have.
2219 */
2220
2221 if (result == 0) {
2222 return bytesRead;
2223 }
2224 }
2225
2226 /*
2227 * Attempt to read bufSize bytes. The read will return immediately if
2228 * there is any data available. Otherwise it will block until at least one
2229 * byte is available or an EOF occurs.
2230 */
2231
2232 if (ReadFile(filePtr->handle, (LPVOID) buf, (DWORD) bufSize, &count,
2233 (LPOVERLAPPED) NULL) == TRUE) {
2234 return bytesRead + count;
2235 } else if (bytesRead) {
2236 /*
2237 * Ignore errors if we have data to return.
2238 */
2239
2240 return bytesRead;
2241 }
2242
2243 TclWinConvertError(GetLastError());
2244 if (errno == EPIPE) {
2245 infoPtr->readFlags |= PIPE_EOF;
2246 return 0;
2247 }
2248 *errorCode = errno;
2249 return -1;
2250 }
2251
2252 /*
2253 *----------------------------------------------------------------------
2254 *
2255 * PipeOutputProc --
2256 *
2257 * Writes the given output on the IO channel. Returns count of how many
2258 * characters were actually written, and an error indication.
2259 *
2260 * Results:
2261 * A count of how many characters were written is returned and an error
2262 * indication is returned in an output argument.
2263 *
2264 * Side effects:
2265 * Writes output on the actual channel.
2266 *
2267 *----------------------------------------------------------------------
2268 */
2269
2270 static int
2271 PipeOutputProc(
2272 ClientData instanceData, /* Pipe state. */
2273 const char *buf, /* The data buffer. */
2274 int toWrite, /* How many bytes to write? */
2275 int *errorCode) /* Where to store error code. */
2276 {
2277 PipeInfo *infoPtr = (PipeInfo *) instanceData;
2278 WinFile *filePtr = (WinFile*) infoPtr->writeFile;
2279 DWORD bytesWritten, timeout;
2280
2281 *errorCode = 0;
2282
2283 /* avoid blocking if pipe-thread exited */
2284 timeout = ((infoPtr->flags & PIPE_ASYNC)
2285 || !TclPipeThreadIsAlive(&infoPtr->writeTI)
2286 || TclInExit() || TclInThreadExit()) ? 0 : INFINITE;
2287 if (WaitForSingleObject(infoPtr->writable, timeout) == WAIT_TIMEOUT) {
2288 /*
2289 * The writer thread is blocked waiting for a write to complete and
2290 * the channel is in non-blocking mode.
2291 */
2292
2293 errno = EWOULDBLOCK;
2294 goto error;
2295 }
2296
2297 /*
2298 * Check for a background error on the last write.
2299 */
2300
2301 if (infoPtr->writeError) {
2302 TclWinConvertError(infoPtr->writeError);
2303 infoPtr->writeError = 0;
2304 goto error;
2305 }
2306
2307 if (infoPtr->flags & PIPE_ASYNC) {
2308 /*
2309 * The pipe is non-blocking, so copy the data into the output buffer
2310 * and restart the writer thread.
2311 */
2312
2313 if (toWrite > infoPtr->writeBufLen) {
2314 /*
2315 * Reallocate the buffer to be large enough to hold the data.
2316 */
2317
2318 if (infoPtr->writeBuf) {
2319 ckfree(infoPtr->writeBuf);
2320 }
2321 infoPtr->writeBufLen = toWrite;
2322 infoPtr->writeBuf = (char *)ckalloc(toWrite);
2323 }
2324 memcpy(infoPtr->writeBuf, buf, toWrite);
2325 infoPtr->toWrite = toWrite;
2326 ResetEvent(infoPtr->writable);
2327 TclPipeThreadSignal(&infoPtr->writeTI);
2328 bytesWritten = toWrite;
2329 } else {
2330 /*
2331 * In the blocking case, just try to write the buffer directly. This
2332 * avoids an unnecessary copy.
2333 */
2334
2335 if (WriteFile(filePtr->handle, (LPVOID) buf, (DWORD) toWrite,
2336 &bytesWritten, (LPOVERLAPPED) NULL) == FALSE) {
2337 TclWinConvertError(GetLastError());
2338 goto error;
2339 }
2340 }
2341 return bytesWritten;
2342
2343 error:
2344 *errorCode = errno;
2345 return -1;
2346
2347 }
2348
2349 /*
2350 *----------------------------------------------------------------------
2351 *
2352 * PipeEventProc --
2353 *
2354 * This function is invoked by Tcl_ServiceEvent when a file event reaches
2355 * the front of the event queue. This function invokes Tcl_NotifyChannel
2356 * on the pipe.
2357 *
2358 * Results:
2359 * Returns 1 if the event was handled, meaning it should be removed from
2360 * the queue. Returns 0 if the event was not handled, meaning it should
2361 * stay on the queue. The only time the event isn't handled is if the
2362 * TCL_FILE_EVENTS flag bit isn't set.
2363 *
2364 * Side effects:
2365 * Whatever the notifier callback does.
2366 *
2367 *----------------------------------------------------------------------
2368 */
2369
2370 static int
2371 PipeEventProc(
2372 Tcl_Event *evPtr, /* Event to service. */
2373 int flags) /* Flags that indicate what events to
2374 * handle, such as TCL_FILE_EVENTS. */
2375 {
2376 PipeEvent *pipeEvPtr = (PipeEvent *)evPtr;
2377 PipeInfo *infoPtr;
2378 int mask;
2379 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
2380
2381 if (!(flags & TCL_FILE_EVENTS)) {
2382 return 0;
2383 }
2384
2385 /*
2386 * Search through the list of watched pipes for the one whose handle
2387 * matches the event. We do this rather than simply dereferencing the
2388 * handle in the event so that pipes can be deleted while the event is in
2389 * the queue.
2390 */
2391
2392 for (infoPtr = tsdPtr->firstPipePtr; infoPtr != NULL;
2393 infoPtr = infoPtr->nextPtr) {
2394 if (pipeEvPtr->infoPtr == infoPtr) {
2395 infoPtr->flags &= ~(PIPE_PENDING);
2396 break;
2397 }
2398 }
2399
2400 /*
2401 * Remove stale events.
2402 */
2403
2404 if (!infoPtr) {
2405 return 1;
2406 }
2407
2408 /*
2409 * Check to see if the pipe is readable. Note that we can't tell if a pipe
2410 * is writable, so we always report it as being writable unless we have
2411 * detected EOF.
2412 */
2413
2414 mask = 0;
2415 if ((infoPtr->watchMask & TCL_WRITABLE) &&
2416 (WaitForSingleObject(infoPtr->writable, 0) != WAIT_TIMEOUT)) {
2417 mask = TCL_WRITABLE;
2418 }
2419
2420 if ((infoPtr->watchMask & TCL_READABLE) && (WaitForRead(infoPtr,0) >= 0)) {
2421 if (infoPtr->readFlags & PIPE_EOF) {
2422 mask = TCL_READABLE;
2423 } else {
2424 mask |= TCL_READABLE;
2425 }
2426 }
2427
2428 /*
2429 * Inform the channel of the events.
2430 */
2431
2432 Tcl_NotifyChannel(infoPtr->channel, infoPtr->watchMask & mask);
2433 return 1;
2434 }
2435
2436 /*
2437 *----------------------------------------------------------------------
2438 *
2439 * PipeWatchProc --
2440 *
2441 * Called by the notifier to set up to watch for events on this channel.
2442 *
2443 * Results:
2444 * None.
2445 *
2446 * Side effects:
2447 * None.
2448 *
2449 *----------------------------------------------------------------------
2450 */
2451
2452 static void
2453 PipeWatchProc(
2454 ClientData instanceData, /* Pipe state. */
2455 int mask) /* What events to watch for, OR-ed combination
2456 * of TCL_READABLE, TCL_WRITABLE and
2457 * TCL_EXCEPTION. */
2458 {
2459 PipeInfo **nextPtrPtr, *ptr;
2460 PipeInfo *infoPtr = (PipeInfo *) instanceData;
2461 int oldMask = infoPtr->watchMask;
2462 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
2463
2464 /*
2465 * Since most of the work is handled by the background threads, we just
2466 * need to update the watchMask and then force the notifier to poll once.
2467 */
2468
2469 infoPtr->watchMask = mask & infoPtr->validMask;
2470 if (infoPtr->watchMask) {
2471 Tcl_Time blockTime = { 0, 0 };
2472
2473 if (!oldMask) {
2474 infoPtr->nextPtr = tsdPtr->firstPipePtr;
2475 tsdPtr->firstPipePtr = infoPtr;
2476 }
2477 Tcl_SetMaxBlockTime(&blockTime);
2478 } else {
2479 if (oldMask) {
2480 /*
2481 * Remove the pipe from the list of watched pipes.
2482 */
2483
2484 for (nextPtrPtr = &(tsdPtr->firstPipePtr), ptr = *nextPtrPtr;
2485 ptr != NULL;
2486 nextPtrPtr = &ptr->nextPtr, ptr = *nextPtrPtr) {
2487 if (infoPtr == ptr) {
2488 *nextPtrPtr = ptr->nextPtr;
2489 break;
2490 }
2491 }
2492 }
2493 }
2494 }
2495
2496 /*
2497 *----------------------------------------------------------------------
2498 *
2499 * PipeGetHandleProc --
2500 *
2501 * Called from Tcl_GetChannelHandle to retrieve OS handles from inside a
2502 * command pipeline based channel.
2503 *
2504 * Results:
2505 * Returns TCL_OK with the fd in handlePtr, or TCL_ERROR if there is no
2506 * handle for the specified direction.
2507 *
2508 * Side effects:
2509 * None.
2510 *
2511 *----------------------------------------------------------------------
2512 */
2513
2514 static int
2515 PipeGetHandleProc(
2516 ClientData instanceData, /* The pipe state. */
2517 int direction, /* TCL_READABLE or TCL_WRITABLE */
2518 ClientData *handlePtr) /* Where to store the handle. */
2519 {
2520 PipeInfo *infoPtr = (PipeInfo *) instanceData;
2521 WinFile *filePtr;
2522
2523 if (direction == TCL_READABLE && infoPtr->readFile) {
2524 filePtr = (WinFile*) infoPtr->readFile;
2525 *handlePtr = (ClientData) filePtr->handle;
2526 return TCL_OK;
2527 }
2528 if (direction == TCL_WRITABLE && infoPtr->writeFile) {
2529 filePtr = (WinFile*) infoPtr->writeFile;
2530 *handlePtr = (ClientData) filePtr->handle;
2531 return TCL_OK;
2532 }
2533 return TCL_ERROR;
2534 }
2535
2536 /*
2537 *----------------------------------------------------------------------
2538 *
2539 * Tcl_WaitPid --
2540 *
2541 * Emulates the waitpid system call.
2542 *
2543 * Results:
2544 * Returns 0 if the process is still alive, -1 on an error, or the pid on
2545 * a clean close.
2546 *
2547 * Side effects:
2548 * Unless WNOHANG is set and the wait times out, the process information
2549 * record will be deleted and the process handle will be closed.
2550 *
2551 *----------------------------------------------------------------------
2552 */
2553
2554 Tcl_Pid
2555 Tcl_WaitPid(
2556 Tcl_Pid pid,
2557 int *statPtr,
2558 int options)
2559 {
2560 ProcInfo *infoPtr = NULL, **prevPtrPtr;
2561 DWORD flags;
2562 Tcl_Pid result;
2563 DWORD ret, exitCode;
2564
2565 PipeInit();
2566
2567 /*
2568 * If no pid is specified, do nothing.
2569 */
2570
2571 if (pid == 0) {
2572 *statPtr = 0;
2573 return 0;
2574 }
2575
2576 /*
2577 * Find the process and cut it from the process list.
2578 */
2579
2580 Tcl_MutexLock(&pipeMutex);
2581 prevPtrPtr = &procList;
2582 for (infoPtr = procList; infoPtr != NULL;
2583 prevPtrPtr = &infoPtr->nextPtr, infoPtr = infoPtr->nextPtr) {
2584 if (infoPtr->hProcess == (HANDLE) pid) {
2585 *prevPtrPtr = infoPtr->nextPtr;
2586 break;
2587 }
2588 }
2589 Tcl_MutexUnlock(&pipeMutex);
2590
2591 /*
2592 * If the pid is not one of the processes we know about (we started it)
2593 * then do nothing.
2594 */
2595
2596 if (infoPtr == NULL) {
2597 *statPtr = 0;
2598 return 0;
2599 }
2600
2601 /*
2602 * Officially "wait" for it to finish. We either poll (WNOHANG) or wait
2603 * for an infinite amount of time.
2604 */
2605
2606 if (options & WNOHANG) {
2607 flags = 0;
2608 } else {
2609 flags = INFINITE;
2610 }
2611 ret = WaitForSingleObject(infoPtr->hProcess, flags);
2612 if (ret == WAIT_TIMEOUT) {
2613 *statPtr = 0;
2614 if (options & WNOHANG) {
2615 /*
2616 * Re-insert this infoPtr back on the list.
2617 */
2618
2619 Tcl_MutexLock(&pipeMutex);
2620 infoPtr->nextPtr = procList;
2621 procList = infoPtr;
2622 Tcl_MutexUnlock(&pipeMutex);
2623 return 0;
2624 } else {
2625 result = 0;
2626 }
2627 } else if (ret == WAIT_OBJECT_0) {
2628 GetExitCodeProcess(infoPtr->hProcess, &exitCode);
2629
2630 /*
2631 * Does the exit code look like one of the exception codes?
2632 */
2633
2634 switch (exitCode) {
2635 case EXCEPTION_FLT_DENORMAL_OPERAND:
2636 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
2637 case EXCEPTION_FLT_INEXACT_RESULT:
2638 case EXCEPTION_FLT_INVALID_OPERATION:
2639 case EXCEPTION_FLT_OVERFLOW:
2640 case EXCEPTION_FLT_STACK_CHECK:
2641 case EXCEPTION_FLT_UNDERFLOW:
2642 case EXCEPTION_INT_DIVIDE_BY_ZERO:
2643 case EXCEPTION_INT_OVERFLOW:
2644 *statPtr = 0xC0000000 | SIGFPE;
2645 break;
2646
2647 case EXCEPTION_PRIV_INSTRUCTION:
2648 case EXCEPTION_ILLEGAL_INSTRUCTION:
2649 *statPtr = 0xC0000000 | SIGILL;
2650 break;
2651
2652 case EXCEPTION_ACCESS_VIOLATION:
2653 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
2654 case EXCEPTION_STACK_OVERFLOW:
2655 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
2656 case EXCEPTION_INVALID_DISPOSITION:
2657 case EXCEPTION_GUARD_PAGE:
2658 case EXCEPTION_INVALID_HANDLE:
2659 *statPtr = 0xC0000000 | SIGSEGV;
2660 break;
2661
2662 case EXCEPTION_DATATYPE_MISALIGNMENT:
2663 *statPtr = 0xC0000000 | SIGBUS;
2664 break;
2665
2666 case EXCEPTION_BREAKPOINT:
2667 case EXCEPTION_SINGLE_STEP:
2668 *statPtr = 0xC0000000 | SIGTRAP;
2669 break;
2670
2671 case CONTROL_C_EXIT:
2672 *statPtr = 0xC0000000 | SIGINT;
2673 break;
2674
2675 default:
2676 /*
2677 * Non-exceptional, normal, exit code. Note that the exit code is
2678 * truncated to a signed short range [-32768,32768) whether it
2679 * fits into this range or not.
2680 *
2681 * BUG: Even though the exit code is a DWORD, it is understood by
2682 * convention to be a signed integer, yet there isn't enough room
2683 * to fit this into the POSIX style waitstatus mask without
2684 * truncating it.
2685 */
2686
2687 *statPtr = exitCode;
2688 break;
2689 }
2690 result = pid;
2691 } else {
2692 errno = ECHILD;
2693 *statPtr = 0xC0000000 | ECHILD;
2694 result = (Tcl_Pid) -1;
2695 }
2696
2697 /*
2698 * Officially close the process handle.
2699 */
2700
2701 CloseHandle(infoPtr->hProcess);
2702 ckfree(infoPtr);
2703
2704 return result;
2705 }
2706
2707 /*
2708 *----------------------------------------------------------------------
2709 *
2710 * TclWinAddProcess --
2711 *
2712 * Add a process to the process list so that we can use Tcl_WaitPid on
2713 * the process.
2714 *
2715 * Results:
2716 * None
2717 *
2718 * Side effects:
2719 * Adds the specified process handle to the process list so Tcl_WaitPid
2720 * knows about it.
2721 *
2722 *----------------------------------------------------------------------
2723 */
2724
2725 void
2726 TclWinAddProcess(
2727 void *hProcess, /* Handle to process */
2728 unsigned long id) /* Global process identifier */
2729 {
2730 ProcInfo *procPtr = (ProcInfo *)ckalloc(sizeof(ProcInfo));
2731
2732 PipeInit();
2733
2734 procPtr->hProcess = hProcess;
2735 procPtr->dwProcessId = id;
2736 Tcl_MutexLock(&pipeMutex);
2737 procPtr->nextPtr = procList;
2738 procList = procPtr;
2739 Tcl_MutexUnlock(&pipeMutex);
2740 }
2741
2742 /*
2743 *----------------------------------------------------------------------
2744 *
2745 * Tcl_PidObjCmd --
2746 *
2747 * This function is invoked to process the "pid" Tcl command. See the
2748 * user documentation for details on what it does.
2749 *
2750 * Results:
2751 * A standard Tcl result.
2752 *
2753 * Side effects:
2754 * See the user documentation.
2755 *
2756 *----------------------------------------------------------------------
2757 */
2758
2759 int
2760 Tcl_PidObjCmd(
2761 ClientData dummy, /* Not used. */
2762 Tcl_Interp *interp, /* Current interpreter. */
2763 int objc, /* Number of arguments. */
2764 Tcl_Obj *const *objv) /* Argument strings. */
2765 {
2766 Tcl_Channel chan;
2767 const Tcl_ChannelType *chanTypePtr;
2768 PipeInfo *pipePtr;
2769 int i;
2770 Tcl_Obj *resultPtr;
2771
2772 if (objc > 2) {
2773 Tcl_WrongNumArgs(interp, 1, objv, "?channelId?");
2774 return TCL_ERROR;
2775 }
2776 if (objc == 1) {
2777 Tcl_SetObjResult(interp, Tcl_NewWideIntObj((unsigned) getpid()));
2778 } else {
2779 chan = Tcl_GetChannel(interp, Tcl_GetString(objv[1]),
2780 NULL);
2781 if (chan == (Tcl_Channel) NULL) {
2782 return TCL_ERROR;
2783 }
2784 chanTypePtr = Tcl_GetChannelType(chan);
2785 if (chanTypePtr != &pipeChannelType) {
2786 return TCL_OK;
2787 }
2788
2789 pipePtr = (PipeInfo *) Tcl_GetChannelInstanceData(chan);
2790 TclNewObj(resultPtr);
2791 for (i = 0; i < pipePtr->numPids; i++) {
2792 Tcl_ListObjAppendElement(/*interp*/ NULL, resultPtr,
2793 Tcl_NewWideIntObj((unsigned)
2794 TclpGetPid(pipePtr->pidPtr[i])));
2795 }
2796 Tcl_SetObjResult(interp, resultPtr);
2797 }
2798 return TCL_OK;
2799 }
2800
2801 /*
2802 *----------------------------------------------------------------------
2803 *
2804 * WaitForRead --
2805 *
2806 * Wait until some data is available, the pipe is at EOF or the reader
2807 * thread is blocked waiting for data (if the channel is in non-blocking
2808 * mode).
2809 *
2810 * Results:
2811 * Returns 1 if pipe is readable. Returns 0 if there is no data on the
2812 * pipe, but there is buffered data. Returns -1 if an error occurred. If
2813 * an error occurred, the threads may not be synchronized.
2814 *
2815 * Side effects:
2816 * Updates the shared state flags and may consume 1 byte of data from the
2817 * pipe. If no error occurred, the reader thread is blocked waiting for a
2818 * signal from the main thread.
2819 *
2820 *----------------------------------------------------------------------
2821 */
2822
2823 static int
2824 WaitForRead(
2825 PipeInfo *infoPtr, /* Pipe state. */
2826 int blocking) /* Indicates whether call should be blocking
2827 * or not. */
2828 {
2829 DWORD timeout, count;
2830 HANDLE handle = ((WinFile *) infoPtr->readFile)->handle;
2831
2832 while (1) {
2833 /*
2834 * Synchronize with the reader thread.
2835 */
2836
2837 /* avoid blocking if pipe-thread exited */
2838 timeout = (!blocking || !TclPipeThreadIsAlive(&infoPtr->readTI)
2839 || TclInExit() || TclInThreadExit()) ? 0 : INFINITE;
2840 if (WaitForSingleObject(infoPtr->readable, timeout) == WAIT_TIMEOUT) {
2841 /*
2842 * The reader thread is blocked waiting for data and the channel
2843 * is in non-blocking mode.
2844 */
2845
2846 errno = EWOULDBLOCK;
2847 return -1;
2848 }
2849
2850 /*
2851 * At this point, the two threads are synchronized, so it is safe to
2852 * access shared state.
2853 */
2854
2855 /*
2856 * If the pipe has hit EOF, it is always readable.
2857 */
2858
2859 if (infoPtr->readFlags & PIPE_EOF) {
2860 return 1;
2861 }
2862
2863 /*
2864 * Check to see if there is any data sitting in the pipe.
2865 */
2866
2867 if (PeekNamedPipe(handle, (LPVOID) NULL, (DWORD) 0,
2868 (LPDWORD) NULL, &count, (LPDWORD) NULL) != TRUE) {
2869 TclWinConvertError(GetLastError());
2870
2871 /*
2872 * Check to see if the peek failed because of EOF.
2873 */
2874
2875 if (errno == EPIPE) {
2876 infoPtr->readFlags |= PIPE_EOF;
2877 return 1;
2878 }
2879
2880 /*
2881 * Ignore errors if there is data in the buffer.
2882 */
2883
2884 if (infoPtr->readFlags & PIPE_EXTRABYTE) {
2885 return 0;
2886 } else {
2887 return -1;
2888 }
2889 }
2890
2891 /*
2892 * We found some data in the pipe, so it must be readable.
2893 */
2894
2895 if (count > 0) {
2896 return 1;
2897 }
2898
2899 /*
2900 * The pipe isn't readable, but there is some data sitting in the
2901 * buffer, so return immediately.
2902 */
2903
2904 if (infoPtr->readFlags & PIPE_EXTRABYTE) {
2905 return 0;
2906 }
2907
2908 /*
2909 * There wasn't any data available, so reset the thread and try again.
2910 */
2911
2912 ResetEvent(infoPtr->readable);
2913 TclPipeThreadSignal(&infoPtr->readTI);
2914 }
2915 }
2916
2917 /*
2918 *----------------------------------------------------------------------
2919 *
2920 * PipeReaderThread --
2921 *
2922 * This function runs in a separate thread and waits for input to become
2923 * available on a pipe.
2924 *
2925 * Results:
2926 * None.
2927 *
2928 * Side effects:
2929 * Signals the main thread when input become available. May cause the
2930 * main thread to wake up by posting a message. May consume one byte from
2931 * the pipe for each wait operation. Will cause a memory leak of ~4k, if
2932 * forcefully terminated with TerminateThread().
2933 *
2934 *----------------------------------------------------------------------
2935 */
2936
2937 static DWORD WINAPI
2938 PipeReaderThread(
2939 LPVOID arg)
2940 {
2941 TclPipeThreadInfo *pipeTI = (TclPipeThreadInfo *) arg;
2942 PipeInfo *infoPtr = NULL; /* access info only after success init/wait */
2943 HANDLE handle = NULL;
2944 DWORD count, err;
2945 int done = 0;
2946
2947 while (!done) {
2948 /*
2949 * Wait for the main thread to signal before attempting to wait on the
2950 * pipe becoming readable.
2951 */
2952
2953 if (!TclPipeThreadWaitForSignal(&pipeTI)) {
2954 /* exit */
2955 break;
2956 }
2957
2958 if (!infoPtr) {
2959 infoPtr = (PipeInfo *) pipeTI->clientData;
2960 handle = ((WinFile *) infoPtr->readFile)->handle;
2961 }
2962
2963 /*
2964 * Try waiting for 0 bytes. This will block until some data is
2965 * available on NT, but will return immediately on Win 95. So, if no
2966 * data is available after the first read, we block until we can read
2967 * a single byte off of the pipe.
2968 */
2969
2970 if (ReadFile(handle, NULL, 0, &count, NULL) == FALSE ||
2971 PeekNamedPipe(handle, NULL, 0, NULL, &count, NULL) == FALSE) {
2972 /*
2973 * The error is a result of an EOF condition, so set the EOF bit
2974 * before signalling the main thread.
2975 */
2976
2977 err = GetLastError();
2978 if (err == ERROR_BROKEN_PIPE) {
2979 infoPtr->readFlags |= PIPE_EOF;
2980 done = 1;
2981 } else if (err == ERROR_INVALID_HANDLE) {
2982 done = 1;
2983 }
2984 } else if (count == 0) {
2985 if (ReadFile(handle, &(infoPtr->extraByte), 1, &count, NULL)
2986 != FALSE) {
2987 /*
2988 * One byte was consumed as a side effect of waiting for the
2989 * pipe to become readable.
2990 */
2991
2992 infoPtr->readFlags |= PIPE_EXTRABYTE;
2993 } else {
2994 err = GetLastError();
2995 if (err == ERROR_BROKEN_PIPE) {
2996 /*
2997 * The error is a result of an EOF condition, so set the
2998 * EOF bit before signalling the main thread.
2999 */
3000
3001 infoPtr->readFlags |= PIPE_EOF;
3002 done = 1;
3003 } else if (err == ERROR_INVALID_HANDLE) {
3004 done = 1;
3005 }
3006 }
3007 }
3008
3009 /*
3010 * Signal the main thread by signalling the readable event and then
3011 * waking up the notifier thread.
3012 */
3013
3014 SetEvent(infoPtr->readable);
3015
3016 /*
3017 * Alert the foreground thread. Note that we need to treat this like a
3018 * critical section so the foreground thread does not terminate this
3019 * thread while we are holding a mutex in the notifier code.
3020 */
3021
3022 Tcl_MutexLock(&pipeMutex);
3023 if (infoPtr->threadId != NULL) {
3024 /*
3025 * TIP #218. When in flight ignore the event, no one will receive
3026 * it anyway.
3027 */
3028
3029 Tcl_ThreadAlert(infoPtr->threadId);
3030 }
3031 Tcl_MutexUnlock(&pipeMutex);
3032 }
3033
3034 /*
3035 * If state of thread was set to stop, we can sane free info structure,
3036 * otherwise it is shared with main thread, so main thread will own it
3037 */
3038 TclPipeThreadExit(&pipeTI);
3039
3040 return 0;
3041 }
3042
3043 /*
3044 *----------------------------------------------------------------------
3045 *
3046 * PipeWriterThread --
3047 *
3048 * This function runs in a separate thread and writes data onto a pipe.
3049 *
3050 * Results:
3051 * Always returns 0.
3052 *
3053 * Side effects:
3054 * Signals the main thread when an output operation is completed. May
3055 * cause the main thread to wake up by posting a message.
3056 *
3057 *----------------------------------------------------------------------
3058 */
3059
3060 static DWORD WINAPI
3061 PipeWriterThread(
3062 LPVOID arg)
3063 {
3064 TclPipeThreadInfo *pipeTI = (TclPipeThreadInfo *)arg;
3065 PipeInfo *infoPtr = NULL; /* access info only after success init/wait */
3066 HANDLE handle = NULL;
3067 DWORD count, toWrite;
3068 char *buf;
3069 int done = 0;
3070
3071 while (!done) {
3072 /*
3073 * Wait for the main thread to signal before attempting to write.
3074 */
3075 if (!TclPipeThreadWaitForSignal(&pipeTI)) {
3076 /* exit */
3077 break;
3078 }
3079
3080 if (!infoPtr) {
3081 infoPtr = (PipeInfo *)pipeTI->clientData;
3082 handle = ((WinFile *) infoPtr->writeFile)->handle;
3083 }
3084
3085 buf = infoPtr->writeBuf;
3086 toWrite = infoPtr->toWrite;
3087
3088 /*
3089 * Loop until all of the bytes are written or an error occurs.
3090 */
3091
3092 while (toWrite > 0) {
3093 if (WriteFile(handle, buf, toWrite, &count, NULL) == FALSE) {
3094 infoPtr->writeError = GetLastError();
3095 done = 1;
3096 break;
3097 } else {
3098 toWrite -= count;
3099 buf += count;
3100 }
3101 }
3102
3103 /*
3104 * Signal the main thread by signalling the writable event and then
3105 * waking up the notifier thread.
3106 */
3107
3108 SetEvent(infoPtr->writable);
3109
3110 /*
3111 * Alert the foreground thread. Note that we need to treat this like a
3112 * critical section so the foreground thread does not terminate this
3113 * thread while we are holding a mutex in the notifier code.
3114 */
3115
3116 Tcl_MutexLock(&pipeMutex);
3117 if (infoPtr->threadId != NULL) {
3118 /*
3119 * TIP #218. When in flight ignore the event, no one will receive
3120 * it anyway.
3121 */
3122
3123 Tcl_ThreadAlert(infoPtr->threadId);
3124 }
3125 Tcl_MutexUnlock(&pipeMutex);
3126 }
3127
3128 /*
3129 * If state of thread was set to stop, we can sane free info structure,
3130 * otherwise it is shared with main thread, so main thread will own it.
3131 */
3132 TclPipeThreadExit(&pipeTI);
3133
3134 return 0;
3135 }
3136
3137 /*
3138 *----------------------------------------------------------------------
3139 *
3140 * PipeThreadActionProc --
3141 *
3142 * Insert or remove any thread local refs to this channel.
3143 *
3144 * Results:
3145 * None.
3146 *
3147 * Side effects:
3148 * Changes thread local list of valid channels.
3149 *
3150 *----------------------------------------------------------------------
3151 */
3152
3153 static void
3154 PipeThreadActionProc(
3155 ClientData instanceData,
3156 int action)
3157 {
3158 PipeInfo *infoPtr = (PipeInfo *) instanceData;
3159
3160 /*
3161 * We do not access firstPipePtr in the thread structures. This is not for
3162 * all pipes managed by the thread, but only those we are watching.
3163 * Removal of the fileevent handlers before transfer thus takes care of
3164 * this structure.
3165 */
3166
3167 Tcl_MutexLock(&pipeMutex);
3168 if (action == TCL_CHANNEL_THREAD_INSERT) {
3169 /*
3170 * We can't copy the thread information from the channel when the
3171 * channel is created. At this time the channel back pointer has not
3172 * been set yet. However in that case the threadId has already been
3173 * set by TclpCreateCommandChannel itself, so the structure is still
3174 * good.
3175 */
3176
3177 PipeInit();
3178 if (infoPtr->channel != NULL) {
3179 infoPtr->threadId = Tcl_GetChannelThread(infoPtr->channel);
3180 }
3181 } else {
3182 infoPtr->threadId = NULL;
3183 }
3184 Tcl_MutexUnlock(&pipeMutex);
3185 }
3186
3187 /*
3188 *----------------------------------------------------------------------
3189 *
3190 * TclpOpenTemporaryFile --
3191 *
3192 * Creates a temporary file, possibly based on the supplied bits and
3193 * pieces of template supplied in the first three arguments. If the
3194 * fourth argument is non-NULL, it contains a Tcl_Obj to store the name
3195 * of the temporary file in (and it is caller's responsibility to clean
3196 * up). If the fourth argument is NULL, try to arrange for the temporary
3197 * file to go away once it is no longer needed.
3198 *
3199 * Results:
3200 * A read-write Tcl Channel open on the file.
3201 *
3202 *----------------------------------------------------------------------
3203 */
3204
3205 Tcl_Channel
3206 TclpOpenTemporaryFile(
3207 Tcl_Obj *dirObj,
3208 Tcl_Obj *basenameObj,
3209 Tcl_Obj *extensionObj,
3210 Tcl_Obj *resultingNameObj)
3211 {
3212 WCHAR name[MAX_PATH];
3213 char *namePtr;
3214 HANDLE handle;
3215 DWORD flags = FILE_ATTRIBUTE_TEMPORARY;
3216 int length, counter, counter2;
3217 Tcl_DString buf;
3218
3219 if (!resultingNameObj) {
3220 flags |= FILE_FLAG_DELETE_ON_CLOSE;
3221 }
3222
3223 namePtr = (char *) name;
3224 length = GetTempPathW(MAX_PATH, name);
3225 if (length == 0) {
3226 goto gotError;
3227 }
3228 namePtr += length * sizeof(WCHAR);
3229 if (basenameObj) {
3230 const char *string = Tcl_GetString(basenameObj);
3231
3232 Tcl_WinUtfToTChar(string, basenameObj->length, &buf);
3233 memcpy(namePtr, Tcl_DStringValue(&buf), Tcl_DStringLength(&buf));
3234 namePtr += Tcl_DStringLength(&buf);
3235 Tcl_DStringFree(&buf);
3236 } else {
3237 const WCHAR *baseStr = L"TCL";
3238 length = 3 * sizeof(WCHAR);
3239
3240 memcpy(namePtr, baseStr, length);
3241 namePtr += length;
3242 }
3243 counter = TclpGetClicks() % 65533;
3244 counter2 = 1024; /* Only try this many times! Prevents
3245 * an infinite loop. */
3246
3247 do {
3248 char number[TCL_INTEGER_SPACE + 4];
3249
3250 snprintf(number, sizeof(number), "%d.TMP", counter);
3251 counter = (unsigned short) (counter + 1);
3252 Tcl_WinUtfToTChar(number, strlen(number), &buf);
3253 Tcl_DStringSetLength(&buf, Tcl_DStringLength(&buf) + 1);
3254 memcpy(namePtr, Tcl_DStringValue(&buf), Tcl_DStringLength(&buf) + 1);
3255 Tcl_DStringFree(&buf);
3256
3257 handle = CreateFileW(name,
3258 GENERIC_READ|GENERIC_WRITE, 0, NULL, CREATE_NEW, flags, NULL);
3259 } while (handle == INVALID_HANDLE_VALUE
3260 && --counter2 > 0
3261 && GetLastError() == ERROR_FILE_EXISTS);
3262 if (handle == INVALID_HANDLE_VALUE) {
3263 goto gotError;
3264 }
3265
3266 if (resultingNameObj) {
3267 Tcl_Obj *tmpObj = TclpNativeToNormalized(name);
3268
3269 Tcl_AppendObjToObj(resultingNameObj, tmpObj);
3270 TclDecrRefCount(tmpObj);
3271 }
3272
3273 return Tcl_MakeFileChannel((ClientData) handle,
3274 TCL_READABLE|TCL_WRITABLE);
3275
3276 gotError:
3277 TclWinConvertError(GetLastError());
3278 return NULL;
3279 }
3280
3281 /*
3282 *----------------------------------------------------------------------
3283 *
3284 * TclPipeThreadCreateTI --
3285 *
3286 * Creates a thread info structure, can be owned by worker.
3287 *
3288 * Results:
3289 * Pointer to created TI structure.
3290 *
3291 *----------------------------------------------------------------------
3292 */
3293
3294 TclPipeThreadInfo *
3295 TclPipeThreadCreateTI(
3296 TclPipeThreadInfo **pipeTIPtr,
3297 ClientData clientData,
3298 HANDLE wakeEvent)
3299 {
3300 TclPipeThreadInfo *pipeTI;
3301 #ifndef _PTI_USE_CKALLOC
3302 pipeTI = (TclPipeThreadInfo *)malloc(sizeof(TclPipeThreadInfo));
3303 #else
3304 pipeTI = (TclPipeThreadInfo *)ckalloc(sizeof(TclPipeThreadInfo));
3305 #endif /* !_PTI_USE_CKALLOC */
3306 pipeTI->evControl = CreateEventW(NULL, FALSE, FALSE, NULL);
3307 pipeTI->state = PTI_STATE_IDLE;
3308 pipeTI->clientData = clientData;
3309 pipeTI->evWakeUp = wakeEvent;
3310 return (*pipeTIPtr = pipeTI);
3311 }
3312
3313 /*
3314 *----------------------------------------------------------------------
3315 *
3316 * TclPipeThreadWaitForSignal --
3317 *
3318 * Wait for work/stop signals inside pipe worker.
3319 *
3320 * Results:
3321 * 1 if signaled to work, 0 if signaled to stop.
3322 *
3323 * Side effects:
3324 * If this function returns 0, TI-structure pointer given via pipeTIPtr
3325 * may be NULL, so not accessible (can be owned by main thread).
3326 *
3327 *----------------------------------------------------------------------
3328 */
3329
3330 int
3331 TclPipeThreadWaitForSignal(
3332 TclPipeThreadInfo **pipeTIPtr)
3333 {
3334 TclPipeThreadInfo *pipeTI = *pipeTIPtr;
3335 LONG state;
3336 DWORD waitResult;
3337 HANDLE wakeEvent;
3338
3339 if (!pipeTI) {
3340 return 0;
3341 }
3342
3343 wakeEvent = pipeTI->evWakeUp;
3344
3345 /*
3346 * Wait for the main thread to signal before attempting to do the work.
3347 */
3348
3349 /*
3350 * Reset work state of thread (idle/waiting)
3351 */
3352
3353 state = InterlockedCompareExchange(&pipeTI->state, PTI_STATE_IDLE,
3354 PTI_STATE_WORK);
3355 if (state & (PTI_STATE_STOP|PTI_STATE_END)) {
3356 /*
3357 * End of work, check the owner of structure.
3358 */
3359
3360 goto end;
3361 }
3362
3363 /*
3364 * Entering wait
3365 */
3366
3367 waitResult = WaitForSingleObject(pipeTI->evControl, INFINITE);
3368 if (waitResult != WAIT_OBJECT_0) {
3369 /*
3370 * The control event was not signaled, so end of work (unexpected
3371 * behaviour, main thread can be dead?).
3372 */
3373
3374 goto end;
3375 }
3376
3377 /*
3378 * Try to set work state of thread
3379 */
3380
3381 state = InterlockedCompareExchange(&pipeTI->state, PTI_STATE_WORK,
3382 PTI_STATE_IDLE);
3383 if (state & (PTI_STATE_STOP|PTI_STATE_END)) {
3384 /*
3385 * End of work
3386 */
3387
3388 goto end;
3389 }
3390
3391 /*
3392 * Signaled to work.
3393 */
3394
3395 return 1;
3396
3397 end:
3398 /*
3399 * End of work, check the owner of the TI structure.
3400 */
3401
3402 if (state != PTI_STATE_STOP) {
3403 *pipeTIPtr = NULL;
3404 } else {
3405 pipeTI->evWakeUp = NULL;
3406 }
3407 if (wakeEvent) {
3408 SetEvent(wakeEvent);
3409 }
3410 return 0;
3411 }
3412
3413 /*
3414 *----------------------------------------------------------------------
3415 *
3416 * TclPipeThreadStopSignal --
3417 *
3418 * Send stop signal to the pipe worker (without waiting).
3419 *
3420 * After calling of this function, TI-structure pointer given via pipeTIPtr
3421 * may be NULL.
3422 *
3423 * Results:
3424 * 1 if signaled (or pipe-thread is down), 0 if pipe thread still working.
3425 *
3426 *----------------------------------------------------------------------
3427 */
3428
3429 int
3430 TclPipeThreadStopSignal(
3431 TclPipeThreadInfo **pipeTIPtr,
3432 HANDLE wakeEvent)
3433 {
3434 TclPipeThreadInfo *pipeTI = *pipeTIPtr;
3435 HANDLE evControl;
3436 int state;
3437
3438 if (!pipeTI) {
3439 return 1;
3440 }
3441 evControl = pipeTI->evControl;
3442 pipeTI->evWakeUp = wakeEvent;
3443 state = InterlockedCompareExchange(&pipeTI->state, PTI_STATE_STOP,
3444 PTI_STATE_IDLE);
3445 switch (state) {
3446 case PTI_STATE_IDLE:
3447 /*
3448 * Thread was idle/waiting, notify it goes teardown
3449 */
3450
3451 SetEvent(evControl);
3452 *pipeTIPtr = NULL;
3453 /* FALLTHRU */
3454 case PTI_STATE_DOWN:
3455 return 1;
3456
3457 default:
3458 /*
3459 * Thread works currently, we should try to end it, own the TI
3460 * structure (because of possible sharing the joint structures with
3461 * thread)
3462 */
3463
3464 InterlockedExchange(&pipeTI->state, PTI_STATE_END);
3465 break;
3466 }
3467
3468 return 0;
3469 }
3470
3471 /*
3472 *----------------------------------------------------------------------
3473 *
3474 * TclPipeThreadStop --
3475 *
3476 * Send stop signal to the pipe worker and wait for thread completion.
3477 *
3478 * May be combined with TclPipeThreadStopSignal.
3479 *
3480 * After calling of this function, TI-structure pointer given via pipeTIPtr
3481 * is not accessible (owned by pipe worker or released here).
3482 *
3483 * Results:
3484 * None.
3485 *
3486 * Side effects:
3487 * Can terminate pipe worker (and / or stop its synchronous operations).
3488 *
3489 *----------------------------------------------------------------------
3490 */
3491
3492 void
3493 TclPipeThreadStop(
3494 TclPipeThreadInfo **pipeTIPtr,
3495 HANDLE hThread)
3496 {
3497 TclPipeThreadInfo *pipeTI = *pipeTIPtr;
3498 HANDLE evControl;
3499 int state;
3500
3501 if (!pipeTI) {
3502 return;
3503 }
3504 pipeTI = *pipeTIPtr;
3505 evControl = pipeTI->evControl;
3506 pipeTI->evWakeUp = NULL;
3507
3508 /*
3509 * Try to sane stop the pipe worker, corresponding its current state
3510 */
3511
3512 state = InterlockedCompareExchange(&pipeTI->state, PTI_STATE_STOP,
3513 PTI_STATE_IDLE);
3514 switch (state) {
3515 case PTI_STATE_IDLE:
3516 /*
3517 * Thread was idle/waiting, notify it goes teardown
3518 */
3519
3520 SetEvent(evControl);
3521
3522 /*
3523 * We don't need to wait for it at all, thread frees himself (owns the
3524 * TI structure)
3525 */
3526
3527 pipeTI = NULL;
3528 break;
3529
3530 case PTI_STATE_STOP:
3531 /*
3532 * Already stopped, thread frees himself (owns the TI structure)
3533 */
3534
3535 pipeTI = NULL;
3536 break;
3537 case PTI_STATE_DOWN:
3538 /*
3539 * Thread already down (?), do nothing
3540 */
3541
3542 /*
3543 * We don't need to wait for it, but we should free pipeTI
3544 */
3545 hThread = NULL;
3546 break;
3547
3548 /* case PTI_STATE_WORK: */
3549 default:
3550 /*
3551 * Thread works currently, we should try to end it, own the TI
3552 * structure (because of possible sharing the joint structures with
3553 * thread)
3554 */
3555
3556 state = InterlockedCompareExchange(&pipeTI->state, PTI_STATE_END,
3557 PTI_STATE_WORK);
3558 if (state == PTI_STATE_DOWN) {
3559 /*
3560 * We don't need to wait for it, but we should free pipeTI
3561 */
3562 hThread = NULL;
3563 }
3564 break;
3565 }
3566
3567 if (pipeTI && hThread) {
3568 DWORD exitCode;
3569
3570 /*
3571 * The thread may already have closed on its own. Check its exit
3572 * code.
3573 */
3574
3575 GetExitCodeThread(hThread, &exitCode);
3576
3577 if (exitCode == STILL_ACTIVE) {
3578 int inExit = (TclInExit() || TclInThreadExit());
3579
3580 /*
3581 * Set the stop event so that if the pipe thread is blocked
3582 * somewhere, it may hereafter sane exit cleanly.
3583 */
3584
3585 SetEvent(evControl);
3586
3587 /*
3588 * Cancel all sync-IO of this thread (may be blocked there).
3589 */
3590
3591 if (tclWinProcs.cancelSynchronousIo) {
3592 tclWinProcs.cancelSynchronousIo(hThread);
3593 }
3594
3595 /*
3596 * Wait at most 20 milliseconds for the reader thread to close
3597 * (regarding TIP#398-fast-exit).
3598 */
3599
3600 /*
3601 * If we want TIP#398-fast-exit.
3602 */
3603
3604 if (WaitForSingleObject(hThread, inExit ? 0 : 20) == WAIT_TIMEOUT) {
3605 /*
3606 * The thread must be blocked waiting for the pipe to become
3607 * readable in ReadFile(). There isn't a clean way to exit the
3608 * thread from this condition. We should terminate the child
3609 * process instead to get the reader thread to fall out of
3610 * ReadFile with a FALSE. (below) is not the correct way to do
3611 * this, but will stay here until a better solution is found.
3612 *
3613 * Note that we need to guard against terminating the thread
3614 * while it is in the middle of Tcl_ThreadAlert because it
3615 * won't be able to release the notifier lock.
3616 *
3617 * Also note that terminating threads during their
3618 * initialization or teardown phase may result in ntdll.dll's
3619 * LoaderLock to remain locked indefinitely. This causes
3620 * ntdll.dll's LdrpInitializeThread() to deadlock trying to
3621 * acquire LoaderLock. LdrpInitializeThread() is executed
3622 * within new threads to perform initialization and to execute
3623 * DllMain() of all loaded dlls. As a result, all new threads
3624 * are deadlocked in their initialization phase and never
3625 * execute, even though CreateThread() reports successful
3626 * thread creation. This results in a very weird process-wide
3627 * behavior, which is extremely hard to debug.
3628 *
3629 * THREADS SHOULD NEVER BE TERMINATED. Period.
3630 *
3631 * But for now, check if thread is exiting, and if so, let it
3632 * die peacefully.
3633 *
3634 * Also don't terminate if in exit (otherwise deadlocked in
3635 * ntdll.dll's).
3636 */
3637
3638 if (pipeTI->state != PTI_STATE_DOWN
3639 && WaitForSingleObject(hThread,
3640 inExit ? 50 : 5000) != WAIT_OBJECT_0) {
3641 /* BUG: this leaks memory */
3642 if (inExit || !TerminateThread(hThread, 0)) {
3643 /*
3644 * in exit or terminate fails, just give thread a
3645 * chance to exit
3646 */
3647
3648 if (InterlockedExchange(&pipeTI->state,
3649 PTI_STATE_STOP) != PTI_STATE_DOWN) {
3650 pipeTI = NULL;
3651 }
3652 }
3653 }
3654 }
3655 }
3656 }
3657
3658 *pipeTIPtr = NULL;
3659 if (pipeTI) {
3660 if (pipeTI->evWakeUp) {
3661 SetEvent(pipeTI->evWakeUp);
3662 }
3663 CloseHandle(pipeTI->evControl);
3664 #ifndef _PTI_USE_CKALLOC
3665 free(pipeTI);
3666 #else
3667 ckfree(pipeTI);
3668 #endif /* !_PTI_USE_CKALLOC */
3669 }
3670 }
3671
3672 /*
3673 *----------------------------------------------------------------------
3674 *
3675 * TclPipeThreadExit --
3676 *
3677 * Clean-up for the pipe thread (removes owned TI-structure in worker).
3678 *
3679 * Should be executed on worker exit, to inform the main thread or
3680 * free TI-structure (if owned).
3681 *
3682 * After calling of this function, TI-structure pointer given via pipeTIPtr
3683 * is not accessible (owned by main thread or released here).
3684 *
3685 * Results:
3686 * None.
3687 *
3688 *----------------------------------------------------------------------
3689 */
3690
3691 void
3692 TclPipeThreadExit(
3693 TclPipeThreadInfo **pipeTIPtr)
3694 {
3695 LONG state;
3696 TclPipeThreadInfo *pipeTI = *pipeTIPtr;
3697
3698 /*
3699 * If state of thread was set to stop (exactly), we can sane free its info
3700 * structure, otherwise it is shared with main thread, so main thread will
3701 * own it.
3702 */
3703
3704 if (!pipeTI) {
3705 return;
3706 }
3707 *pipeTIPtr = NULL;
3708 state = InterlockedExchange(&pipeTI->state, PTI_STATE_DOWN);
3709 if (state == PTI_STATE_STOP) {
3710 CloseHandle(pipeTI->evControl);
3711 if (pipeTI->evWakeUp) {
3712 SetEvent(pipeTI->evWakeUp);
3713 }
3714 #ifndef _PTI_USE_CKALLOC
3715 free(pipeTI);
3716 #else
3717 ckfree(pipeTI);
3718 /* be sure all subsystems used are finalized */
3719 Tcl_FinalizeThread();
3720 #endif /* !_PTI_USE_CKALLOC */
3721 }
3722 }
3723
3724 /*
3725 * Local Variables:
3726 * mode: c
3727 * c-basic-offset: 4
3728 * fill-column: 78
3729 * End:
3730 */