diff options
author | Brad King <brad.king@kitware.com> | 2016-11-09 09:23:18 -0500 |
---|---|---|
committer | Brad King <brad.king@kitware.com> | 2016-11-09 09:23:18 -0500 |
commit | 95a97a40e48a0db2b206c4560d6962be3666812c (patch) | |
tree | e7f6f0e6ffca54ee18f8c276735e8a60e45f8833 /Source/kwsys/ProcessWin32.c | |
parent | 666bb0e3fa0d212c03f785bd9f6bc05d29925e1f (diff) | |
parent | 773b36e5d4af3ac040625e0ea16bcfd30fcdeb6d (diff) | |
download | cmake-95a97a40e48a0db2b206c4560d6962be3666812c.tar.gz |
Merge branch 'upstream-KWSys' into update-kwsys
* upstream-KWSys:
KWSys 2016-11-09 (18c65411)
Diffstat (limited to 'Source/kwsys/ProcessWin32.c')
-rw-r--r-- | Source/kwsys/ProcessWin32.c | 1837 |
1 files changed, 796 insertions, 1041 deletions
diff --git a/Source/kwsys/ProcessWin32.c b/Source/kwsys/ProcessWin32.c index 2b93e6963f..d10c7339a7 100644 --- a/Source/kwsys/ProcessWin32.c +++ b/Source/kwsys/ProcessWin32.c @@ -1,14 +1,5 @@ -/*============================================================================ - KWSys - Kitware System Library - Copyright 2000-2009 Kitware, Inc., Insight Software Consortium - - Distributed under the OSI-approved BSD License (the "License"); - see accompanying file Copyright.txt for details. - - This software is distributed WITHOUT ANY WARRANTY; without even the - implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - See the License for more information. -============================================================================*/ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing#kwsys for details. */ #include "kwsysPrivate.h" #include KWSYS_HEADER(Process.h) #include KWSYS_HEADER(Encoding.h) @@ -16,8 +7,8 @@ /* Work-around CMake dependency scanning limitation. This must duplicate the above list of headers. */ #if 0 -# include "Process.h.in" -# include "Encoding.h.in" +#include "Encoding.h.in" +#include "Process.h.in" #endif /* @@ -31,15 +22,15 @@ a UNIX-style select system call. */ #ifdef _MSC_VER -#pragma warning (push, 1) +#pragma warning(push, 1) #endif #include <windows.h> /* Windows API */ #if defined(_MSC_VER) && _MSC_VER >= 1800 -# define KWSYS_WINDOWS_DEPRECATED_GetVersionEx +#define KWSYS_WINDOWS_DEPRECATED_GetVersionEx #endif -#include <string.h> /* strlen, strdup */ -#include <stdio.h> /* sprintf */ -#include <io.h> /* _unlink */ +#include <io.h> /* _unlink */ +#include <stdio.h> /* sprintf */ +#include <string.h> /* strlen, strdup */ #ifdef __WATCOMC__ #define _unlink unlink #endif @@ -52,14 +43,14 @@ a UNIX-style select system call. #endif #ifdef _MSC_VER -#pragma warning (pop) -#pragma warning (disable: 4514) -#pragma warning (disable: 4706) +#pragma warning(pop) +#pragma warning(disable : 4514) +#pragma warning(disable : 4706) #endif #if defined(__BORLANDC__) -# pragma warn -8004 /* assigned a value that is never used */ -# pragma warn -8060 /* Assignment inside if() condition. */ +#pragma warn - 8004 /* assigned a value that is never used */ +#pragma warn - 8060 /* Assignment inside if() condition. */ #endif /* There are pipes for the process pipeline's stdout and stderr. */ @@ -72,18 +63,14 @@ a UNIX-style select system call. /* Debug output macro. */ #if 0 -# define KWSYSPE_DEBUG(x) \ -( \ - (void*)cp == (void*)0x00226DE0? \ - ( \ - fprintf(stderr, "%d/%p/%d ", (int)GetCurrentProcessId(), cp, __LINE__), \ - fprintf x, \ - fflush(stderr), \ - 1 \ - ) : (1) \ -) +#define KWSYSPE_DEBUG(x) \ + ((void*)cp == (void*)0x00226DE0 \ + ? (fprintf(stderr, "%d/%p/%d ", (int)GetCurrentProcessId(), cp, \ + __LINE__), \ + fprintf x, fflush(stderr), 1) \ + : (1)) #else -# define KWSYSPE_DEBUG(x) (void)1 +#define KWSYSPE_DEBUG(x) (void)1 #endif typedef LARGE_INTEGER kwsysProcessTime; @@ -99,7 +86,6 @@ typedef struct kwsysProcessCreateInformation_s HANDLE hStdError; } kwsysProcessCreateInformation; - /*--------------------------------------------------------------------------*/ typedef struct kwsysProcessPipeData_s kwsysProcessPipeData; static DWORD WINAPI kwsysProcessPipeThreadRead(LPVOID ptd); @@ -112,8 +98,7 @@ static int kwsysProcessInitialize(kwsysProcess* cp); static DWORD kwsysProcessCreate(kwsysProcess* cp, int index, kwsysProcessCreateInformation* si); static void kwsysProcessDestroy(kwsysProcess* cp, int event); -static DWORD kwsysProcessSetupOutputPipeFile(PHANDLE handle, - const char* name); +static DWORD kwsysProcessSetupOutputPipeFile(PHANDLE handle, const char* name); static void kwsysProcessSetupSharedPipe(DWORD nStdHandle, PHANDLE handle); static void kwsysProcessSetupPipeNative(HANDLE native, PHANDLE handle); static void kwsysProcessCleanupHandle(PHANDLE h); @@ -129,8 +114,10 @@ static DWORD kwsysProcessTimeToDWORD(kwsysProcessTime t); static double kwsysProcessTimeToDouble(kwsysProcessTime t); static kwsysProcessTime kwsysProcessTimeFromDouble(double d); static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2); -static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2); -static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2); +static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, + kwsysProcessTime in2); +static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, + kwsysProcessTime in2); static void kwsysProcessSetExitException(kwsysProcess* cp, int code); static void kwsysProcessKillTree(int pid); static void kwsysProcessDisablePipeThreads(kwsysProcess* cp); @@ -300,10 +287,10 @@ struct kwsysProcess_s int PipesLeft; /* Buffer for error messages. */ - char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE+1]; + char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE + 1]; /* Description for the ExitException. */ - char ExitExceptionString[KWSYSPE_PIPE_BUFFER_SIZE+1]; + char ExitExceptionString[KWSYSPE_PIPE_BUFFER_SIZE + 1]; /* Windows process information data. */ PROCESS_INFORMATION* ProcessInformation; @@ -337,18 +324,16 @@ kwsysProcess* kwsysProcess_New(void) first process. This prevents the risk of an orphaned process being started by the main thread while the default Ctrl handler is in progress. */ - if(!kwsysProcessesInitialize()) - { + if (!kwsysProcessesInitialize()) { return 0; - } + } /* Allocate a process control structure. */ cp = (kwsysProcess*)malloc(sizeof(kwsysProcess)); - if(!cp) - { + if (!cp) { /* Could not allocate memory for the control structure. */ return 0; - } + } ZeroMemory(cp, sizeof(*cp)); /* Share stdin with the parent process by default. */ @@ -362,42 +347,38 @@ kwsysProcess* kwsysProcess_New(void) ZeroMemory(&osv, sizeof(osv)); osv.dwOSVersionInfoSize = sizeof(osv); #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx -# pragma warning (push) -# ifdef __INTEL_COMPILER -# pragma warning (disable:1478) -# else -# pragma warning (disable:4996) -# endif +#pragma warning(push) +#ifdef __INTEL_COMPILER +#pragma warning(disable : 1478) +#else +#pragma warning(disable : 4996) +#endif #endif GetVersionEx(&osv); #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx -# pragma warning (pop) +#pragma warning(pop) #endif - if(osv.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) - { + if (osv.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) { /* Win9x no longer supported. */ kwsysProcess_Delete(cp); return 0; - } + } /* Initially no thread owns the mutex. Initialize semaphore to 1. */ - if(!(cp->SharedIndexMutex = CreateSemaphore(0, 1, 1, 0))) - { + if (!(cp->SharedIndexMutex = CreateSemaphore(0, 1, 1, 0))) { kwsysProcess_Delete(cp); return 0; - } + } /* Initially no data are available. Initialize semaphore to 0. */ - if(!(cp->Full = CreateSemaphore(0, 0, 1, 0))) - { + if (!(cp->Full = CreateSemaphore(0, 0, 1, 0))) { kwsysProcess_Delete(cp); return 0; - } + } /* Create the thread to read each pipe. */ - for(i=0; i < KWSYSPE_PIPE_COUNT; ++i) - { - DWORD dummy=0; + for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) { + DWORD dummy = 0; /* Assign the thread its index. */ cp->Pipe[i].Index = i; @@ -406,73 +387,62 @@ kwsysProcess* kwsysProcess_New(void) cp->Pipe[i].Process = cp; /* No process is yet running. Initialize semaphore to 0. */ - if(!(cp->Pipe[i].Reader.Ready = CreateSemaphore(0, 0, 1, 0))) - { + if (!(cp->Pipe[i].Reader.Ready = CreateSemaphore(0, 0, 1, 0))) { kwsysProcess_Delete(cp); return 0; - } + } /* The pipe is not yet reset. Initialize semaphore to 0. */ - if(!(cp->Pipe[i].Reader.Reset = CreateSemaphore(0, 0, 1, 0))) - { + if (!(cp->Pipe[i].Reader.Reset = CreateSemaphore(0, 0, 1, 0))) { kwsysProcess_Delete(cp); return 0; - } + } /* The thread's buffer is initially empty. Initialize semaphore to 1. */ - if(!(cp->Pipe[i].Reader.Go = CreateSemaphore(0, 1, 1, 0))) - { + if (!(cp->Pipe[i].Reader.Go = CreateSemaphore(0, 1, 1, 0))) { kwsysProcess_Delete(cp); return 0; - } + } /* Create the reading thread. It will block immediately. The thread will not make deeply nested calls, so we need only a small stack. */ - if(!(cp->Pipe[i].Reader.Thread = CreateThread(0, 1024, - kwsysProcessPipeThreadRead, - &cp->Pipe[i], 0, &dummy))) - { + if (!(cp->Pipe[i].Reader.Thread = CreateThread( + 0, 1024, kwsysProcessPipeThreadRead, &cp->Pipe[i], 0, &dummy))) { kwsysProcess_Delete(cp); return 0; - } + } /* No process is yet running. Initialize semaphore to 0. */ - if(!(cp->Pipe[i].Waker.Ready = CreateSemaphore(0, 0, 1, 0))) - { + if (!(cp->Pipe[i].Waker.Ready = CreateSemaphore(0, 0, 1, 0))) { kwsysProcess_Delete(cp); return 0; - } + } /* The pipe is not yet reset. Initialize semaphore to 0. */ - if(!(cp->Pipe[i].Waker.Reset = CreateSemaphore(0, 0, 1, 0))) - { + if (!(cp->Pipe[i].Waker.Reset = CreateSemaphore(0, 0, 1, 0))) { kwsysProcess_Delete(cp); return 0; - } + } /* The waker should not wake immediately. Initialize semaphore to 0. */ - if(!(cp->Pipe[i].Waker.Go = CreateSemaphore(0, 0, 1, 0))) - { + if (!(cp->Pipe[i].Waker.Go = CreateSemaphore(0, 0, 1, 0))) { kwsysProcess_Delete(cp); return 0; - } + } /* Create the waking thread. It will block immediately. The thread will not make deeply nested calls, so we need only a small stack. */ - if(!(cp->Pipe[i].Waker.Thread = CreateThread(0, 1024, - kwsysProcessPipeThreadWake, - &cp->Pipe[i], 0, &dummy))) - { + if (!(cp->Pipe[i].Waker.Thread = CreateThread( + 0, 1024, kwsysProcessPipeThreadWake, &cp->Pipe[i], 0, &dummy))) { kwsysProcess_Delete(cp); return 0; - } } - for(i=0; i < 3; ++i) - { + } + for (i = 0; i < 3; ++i) { cp->PipeChildStd[i] = INVALID_HANDLE_VALUE; - } + } return cp; } @@ -483,33 +453,26 @@ void kwsysProcess_Delete(kwsysProcess* cp) int i; /* Make sure we have an instance. */ - if(!cp) - { + if (!cp) { return; - } + } /* If the process is executing, wait for it to finish. */ - if(cp->State == kwsysProcess_State_Executing) - { - if(cp->Detached) - { + if (cp->State == kwsysProcess_State_Executing) { + if (cp->Detached) { kwsysProcess_Disown(cp); - } - else - { + } else { kwsysProcess_WaitForExit(cp, 0); - } } + } /* We are deleting the kwsysProcess instance. */ cp->Deleting = 1; /* Terminate each of the threads. */ - for(i=0; i < KWSYSPE_PIPE_COUNT; ++i) - { + for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) { /* Terminate this reading thread. */ - if(cp->Pipe[i].Reader.Thread) - { + if (cp->Pipe[i].Reader.Thread) { /* Signal the thread we are ready for it. It will terminate immediately since Deleting is set. */ ReleaseSemaphore(cp->Pipe[i].Reader.Ready, 1, 0); @@ -519,11 +482,10 @@ void kwsysProcess_Delete(kwsysProcess* cp) /* Close the handle to the thread. */ kwsysProcessCleanupHandle(&cp->Pipe[i].Reader.Thread); - } + } /* Terminate this waking thread. */ - if(cp->Pipe[i].Waker.Thread) - { + if (cp->Pipe[i].Waker.Thread) { /* Signal the thread we are ready for it. It will terminate immediately since Deleting is set. */ ReleaseSemaphore(cp->Pipe[i].Waker.Ready, 1, 0); @@ -533,7 +495,7 @@ void kwsysProcess_Delete(kwsysProcess* cp) /* Close the handle to the thread. */ kwsysProcessCleanupHandle(&cp->Pipe[i].Waker.Thread); - } + } /* Cleanup the pipe's semaphores. */ kwsysProcessCleanupHandle(&cp->Pipe[i].Reader.Ready); @@ -542,7 +504,7 @@ void kwsysProcess_Delete(kwsysProcess* cp) kwsysProcessCleanupHandle(&cp->Pipe[i].Waker.Ready); kwsysProcessCleanupHandle(&cp->Pipe[i].Waker.Go); kwsysProcessCleanupHandle(&cp->Pipe[i].Waker.Reset); - } + } /* Close the shared semaphores. */ kwsysProcessCleanupHandle(&cp->SharedIndexMutex); @@ -554,10 +516,9 @@ void kwsysProcess_Delete(kwsysProcess* cp) kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDIN, 0); kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDOUT, 0); kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDERR, 0); - if(cp->CommandExitCodes) - { + if (cp->CommandExitCodes) { free(cp->CommandExitCodes); - } + } free(cp); } @@ -565,24 +526,20 @@ void kwsysProcess_Delete(kwsysProcess* cp) int kwsysProcess_SetCommand(kwsysProcess* cp, char const* const* command) { int i; - if(!cp) - { + if (!cp) { return 0; - } - for(i=0; i < cp->NumberOfCommands; ++i) - { + } + for (i = 0; i < cp->NumberOfCommands; ++i) { free(cp->Commands[i]); - } + } cp->NumberOfCommands = 0; - if(cp->Commands) - { + if (cp->Commands) { free(cp->Commands); cp->Commands = 0; - } - if(command) - { + } + if (command) { return kwsysProcess_AddCommand(cp, command); - } + } return 1; } @@ -593,91 +550,87 @@ int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command) wchar_t** newCommands; /* Make sure we have a command to add. */ - if(!cp || !command || !*command) - { + if (!cp || !command || !*command) { return 0; - } - + } /* Allocate a new array for command pointers. */ newNumberOfCommands = cp->NumberOfCommands + 1; - if(!(newCommands = (wchar_t**)malloc(sizeof(wchar_t*) * newNumberOfCommands))) - { + if (!(newCommands = + (wchar_t**)malloc(sizeof(wchar_t*) * newNumberOfCommands))) { /* Out of memory. */ return 0; - } + } /* Copy any existing commands into the new array. */ { - int i; - for(i=0; i < cp->NumberOfCommands; ++i) - { - newCommands[i] = cp->Commands[i]; + int i; + for (i = 0; i < cp->NumberOfCommands; ++i) { + newCommands[i] = cp->Commands[i]; } } - if (cp->Verbatim) - { + if (cp->Verbatim) { /* Copy the verbatim command line into the buffer. */ newCommands[cp->NumberOfCommands] = kwsysEncoding_DupToWide(*command); - } - else - { + } else { /* Encode the arguments so CommandLineToArgvW can decode them from the command line string in the child. */ char buffer[32768]; /* CreateProcess max command-line length. */ char* end = buffer + sizeof(buffer); char* out = buffer; char const* const* a; - for (a = command; *a; ++a) - { + for (a = command; *a; ++a) { int quote = !**a; /* Quote the empty string. */ int slashes = 0; char const* c; - if (a != command && out != end) { *out++ = ' '; } - for (c = *a; !quote && *c; ++c) - { quote = (*c == ' ' || *c == '\t'); } - if (quote && out != end) { *out++ = '"'; } - for (c = *a; *c; ++c) - { - if (*c == '\\') - { + if (a != command && out != end) { + *out++ = ' '; + } + for (c = *a; !quote && *c; ++c) { + quote = (*c == ' ' || *c == '\t'); + } + if (quote && out != end) { + *out++ = '"'; + } + for (c = *a; *c; ++c) { + if (*c == '\\') { ++slashes; - } - else - { - if (*c == '"') - { + } else { + if (*c == '"') { // Add n+1 backslashes to total 2n+1 before internal '"'. - while(slashes-- >= 0 && out != end) { *out++ = '\\'; } + while (slashes-- >= 0 && out != end) { + *out++ = '\\'; } - slashes = 0; } - if (out != end) { *out++ = *c; } + slashes = 0; } - if (quote) - { + if (out != end) { + *out++ = *c; + } + } + if (quote) { // Add n backslashes to total 2n before ending '"'. - while (slashes-- > 0 && out != end) { *out++ = '\\'; } - if (out != end) { *out++ = '"'; } + while (slashes-- > 0 && out != end) { + *out++ = '\\'; + } + if (out != end) { + *out++ = '"'; } } - if(out != end) - { + } + if (out != end) { *out = '\0'; newCommands[cp->NumberOfCommands] = kwsysEncoding_DupToWide(buffer); - } - else - { + } else { newCommands[cp->NumberOfCommands] = 0; - } } - if (!newCommands[cp->NumberOfCommands]) - { + } + if (!newCommands[cp->NumberOfCommands]) { /* Out of memory or command line too long. */ free(newCommands); return 0; - } + } /* Save the new array of commands. */ free(cp->Commands); @@ -689,15 +642,13 @@ int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command) /*--------------------------------------------------------------------------*/ void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout) { - if(!cp) - { + if (!cp) { return; - } + } cp->Timeout = timeout; - if(cp->Timeout < 0) - { + if (cp->Timeout < 0) { cp->Timeout = 0; - } + } // Force recomputation of TimeoutTime. cp->TimeoutTime.QuadPart = -1; } @@ -705,38 +656,32 @@ void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout) /*--------------------------------------------------------------------------*/ int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir) { - if(!cp) - { + if (!cp) { return 0; - } - if(cp->WorkingDirectory) - { + } + if (cp->WorkingDirectory) { free(cp->WorkingDirectory); cp->WorkingDirectory = 0; - } - if(dir && dir[0]) - { + } + if (dir && dir[0]) { wchar_t* wdir = kwsysEncoding_DupToWide(dir); /* We must convert the working directory to a full path. */ DWORD length = GetFullPathNameW(wdir, 0, 0, 0); - if(length > 0) - { - wchar_t* work_dir = malloc(length*sizeof(wchar_t)); - if(!work_dir) - { + if (length > 0) { + wchar_t* work_dir = malloc(length * sizeof(wchar_t)); + if (!work_dir) { free(wdir); return 0; - } - if(!GetFullPathNameW(wdir, length, work_dir, 0)) - { + } + if (!GetFullPathNameW(wdir, length, work_dir, 0)) { free(work_dir); free(wdir); return 0; - } - cp->WorkingDirectory = work_dir; } - free(wdir); + cp->WorkingDirectory = work_dir; } + free(wdir); + } return 1; } @@ -744,39 +689,40 @@ int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir) int kwsysProcess_SetPipeFile(kwsysProcess* cp, int pipe, const char* file) { char** pfile; - if(!cp) - { + if (!cp) { return 0; - } - switch(pipe) - { - case kwsysProcess_Pipe_STDIN: pfile = &cp->PipeFileSTDIN; break; - case kwsysProcess_Pipe_STDOUT: pfile = &cp->PipeFileSTDOUT; break; - case kwsysProcess_Pipe_STDERR: pfile = &cp->PipeFileSTDERR; break; - default: return 0; - } - if(*pfile) - { + } + switch (pipe) { + case kwsysProcess_Pipe_STDIN: + pfile = &cp->PipeFileSTDIN; + break; + case kwsysProcess_Pipe_STDOUT: + pfile = &cp->PipeFileSTDOUT; + break; + case kwsysProcess_Pipe_STDERR: + pfile = &cp->PipeFileSTDERR; + break; + default: + return 0; + } + if (*pfile) { free(*pfile); *pfile = 0; - } - if(file) - { - *pfile = (char*)malloc(strlen(file)+1); - if(!*pfile) - { + } + if (file) { + *pfile = (char*)malloc(strlen(file) + 1); + if (!*pfile) { return 0; - } - strcpy(*pfile, file); } + strcpy(*pfile, file); + } /* If we are redirecting the pipe, do not share it or use a native pipe. */ - if(*pfile) - { + if (*pfile) { kwsysProcess_SetPipeNative(cp, pipe, 0); kwsysProcess_SetPipeShared(cp, pipe, 0); - } + } return 1; } @@ -784,26 +730,30 @@ int kwsysProcess_SetPipeFile(kwsysProcess* cp, int pipe, const char* file) /*--------------------------------------------------------------------------*/ void kwsysProcess_SetPipeShared(kwsysProcess* cp, int pipe, int shared) { - if(!cp) - { + if (!cp) { return; - } + } - switch(pipe) - { - case kwsysProcess_Pipe_STDIN: cp->PipeSharedSTDIN = shared?1:0; break; - case kwsysProcess_Pipe_STDOUT: cp->PipeSharedSTDOUT = shared?1:0; break; - case kwsysProcess_Pipe_STDERR: cp->PipeSharedSTDERR = shared?1:0; break; - default: return; - } + switch (pipe) { + case kwsysProcess_Pipe_STDIN: + cp->PipeSharedSTDIN = shared ? 1 : 0; + break; + case kwsysProcess_Pipe_STDOUT: + cp->PipeSharedSTDOUT = shared ? 1 : 0; + break; + case kwsysProcess_Pipe_STDERR: + cp->PipeSharedSTDERR = shared ? 1 : 0; + break; + default: + return; + } /* If we are sharing the pipe, do not redirect it to a file or use a native pipe. */ - if(shared) - { + if (shared) { kwsysProcess_SetPipeFile(cp, pipe, 0); kwsysProcess_SetPipeNative(cp, pipe, 0); - } + } } /*--------------------------------------------------------------------------*/ @@ -811,129 +761,135 @@ void kwsysProcess_SetPipeNative(kwsysProcess* cp, int pipe, HANDLE p[2]) { HANDLE* pPipeNative = 0; - if(!cp) - { + if (!cp) { return; - } + } - switch(pipe) - { - case kwsysProcess_Pipe_STDIN: pPipeNative = cp->PipeNativeSTDIN; break; - case kwsysProcess_Pipe_STDOUT: pPipeNative = cp->PipeNativeSTDOUT; break; - case kwsysProcess_Pipe_STDERR: pPipeNative = cp->PipeNativeSTDERR; break; - default: return; - } + switch (pipe) { + case kwsysProcess_Pipe_STDIN: + pPipeNative = cp->PipeNativeSTDIN; + break; + case kwsysProcess_Pipe_STDOUT: + pPipeNative = cp->PipeNativeSTDOUT; + break; + case kwsysProcess_Pipe_STDERR: + pPipeNative = cp->PipeNativeSTDERR; + break; + default: + return; + } /* Copy the native pipe handles provided. */ - if(p) - { + if (p) { pPipeNative[0] = p[0]; pPipeNative[1] = p[1]; - } - else - { + } else { pPipeNative[0] = 0; pPipeNative[1] = 0; - } + } /* If we are using a native pipe, do not share it or redirect it to a file. */ - if(p) - { + if (p) { kwsysProcess_SetPipeFile(cp, pipe, 0); kwsysProcess_SetPipeShared(cp, pipe, 0); - } + } } /*--------------------------------------------------------------------------*/ int kwsysProcess_GetOption(kwsysProcess* cp, int optionId) { - if(!cp) - { + if (!cp) { return 0; - } + } - switch(optionId) - { - case kwsysProcess_Option_Detach: return cp->OptionDetach; - case kwsysProcess_Option_HideWindow: return cp->HideWindow; - case kwsysProcess_Option_MergeOutput: return cp->MergeOutput; - case kwsysProcess_Option_Verbatim: return cp->Verbatim; + switch (optionId) { + case kwsysProcess_Option_Detach: + return cp->OptionDetach; + case kwsysProcess_Option_HideWindow: + return cp->HideWindow; + case kwsysProcess_Option_MergeOutput: + return cp->MergeOutput; + case kwsysProcess_Option_Verbatim: + return cp->Verbatim; case kwsysProcess_Option_CreateProcessGroup: return cp->CreateProcessGroup; - default: return 0; - } + default: + return 0; + } } /*--------------------------------------------------------------------------*/ void kwsysProcess_SetOption(kwsysProcess* cp, int optionId, int value) { - if(!cp) - { + if (!cp) { return; - } + } - switch(optionId) - { - case kwsysProcess_Option_Detach: cp->OptionDetach = value; break; - case kwsysProcess_Option_HideWindow: cp->HideWindow = value; break; - case kwsysProcess_Option_MergeOutput: cp->MergeOutput = value; break; - case kwsysProcess_Option_Verbatim: cp->Verbatim = value; break; + switch (optionId) { + case kwsysProcess_Option_Detach: + cp->OptionDetach = value; + break; + case kwsysProcess_Option_HideWindow: + cp->HideWindow = value; + break; + case kwsysProcess_Option_MergeOutput: + cp->MergeOutput = value; + break; + case kwsysProcess_Option_Verbatim: + cp->Verbatim = value; + break; case kwsysProcess_Option_CreateProcessGroup: - cp->CreateProcessGroup = value; break; - default: break; - } + cp->CreateProcessGroup = value; + break; + default: + break; + } } /*--------------------------------------------------------------------------*/ int kwsysProcess_GetState(kwsysProcess* cp) { - return cp? cp->State : kwsysProcess_State_Error; + return cp ? cp->State : kwsysProcess_State_Error; } /*--------------------------------------------------------------------------*/ int kwsysProcess_GetExitException(kwsysProcess* cp) { - return cp? cp->ExitException : kwsysProcess_Exception_Other; + return cp ? cp->ExitException : kwsysProcess_Exception_Other; } /*--------------------------------------------------------------------------*/ int kwsysProcess_GetExitValue(kwsysProcess* cp) { - return cp? cp->ExitValue : -1; + return cp ? cp->ExitValue : -1; } /*--------------------------------------------------------------------------*/ int kwsysProcess_GetExitCode(kwsysProcess* cp) { - return cp? cp->ExitCode : 0; + return cp ? cp->ExitCode : 0; } /*--------------------------------------------------------------------------*/ const char* kwsysProcess_GetErrorString(kwsysProcess* cp) { - if(!cp) - { + if (!cp) { return "Process management structure could not be allocated"; - } - else if(cp->State == kwsysProcess_State_Error) - { + } else if (cp->State == kwsysProcess_State_Error) { return cp->ErrorMessage; - } + } return "Success"; } /*--------------------------------------------------------------------------*/ const char* kwsysProcess_GetExceptionString(kwsysProcess* cp) { - if(!cp) - { + if (!cp) { return "GetExceptionString called with NULL process management structure"; - } - else if(cp->State == kwsysProcess_State_Exception) - { + } else if (cp->State == kwsysProcess_State_Exception) { return cp->ExitExceptionString; - } + } return "No exception"; } @@ -943,259 +899,210 @@ void kwsysProcess_Execute(kwsysProcess* cp) int i; /* Do not execute a second time. */ - if(!cp || cp->State == kwsysProcess_State_Executing) - { + if (!cp || cp->State == kwsysProcess_State_Executing) { return; - } + } /* Make sure we have something to run. */ - if(cp->NumberOfCommands < 1) - { + if (cp->NumberOfCommands < 1) { strcpy(cp->ErrorMessage, "No command"); cp->State = kwsysProcess_State_Error; return; - } + } /* Initialize the control structure for a new process. */ - if(!kwsysProcessInitialize(cp)) - { + if (!kwsysProcessInitialize(cp)) { strcpy(cp->ErrorMessage, "Out of memory"); cp->State = kwsysProcess_State_Error; return; - } + } /* Save the real working directory of this process and change to the working directory for the child processes. This is needed to make pipe file paths evaluate correctly. */ - if(cp->WorkingDirectory) - { - if(!GetCurrentDirectoryW(cp->RealWorkingDirectoryLength, - cp->RealWorkingDirectory)) - { + if (cp->WorkingDirectory) { + if (!GetCurrentDirectoryW(cp->RealWorkingDirectoryLength, + cp->RealWorkingDirectory)) { kwsysProcessCleanup(cp, GetLastError()); return; - } - SetCurrentDirectoryW(cp->WorkingDirectory); } - + SetCurrentDirectoryW(cp->WorkingDirectory); + } /* Setup the stdin pipe for the first process. */ - if(cp->PipeFileSTDIN) - { + if (cp->PipeFileSTDIN) { /* Create a handle to read a file for stdin. */ wchar_t* wstdin = kwsysEncoding_DupToWide(cp->PipeFileSTDIN); DWORD error; cp->PipeChildStd[0] = - CreateFileW(wstdin, GENERIC_READ|GENERIC_WRITE, - FILE_SHARE_READ|FILE_SHARE_WRITE, - 0, OPEN_EXISTING, 0, 0); + CreateFileW(wstdin, GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); error = GetLastError(); /* Check now in case free changes this. */ free(wstdin); - if(cp->PipeChildStd[0] == INVALID_HANDLE_VALUE) - { + if (cp->PipeChildStd[0] == INVALID_HANDLE_VALUE) { kwsysProcessCleanup(cp, error); return; - } } - else if(cp->PipeSharedSTDIN) - { + } else if (cp->PipeSharedSTDIN) { /* Share this process's stdin with the child. */ kwsysProcessSetupSharedPipe(STD_INPUT_HANDLE, &cp->PipeChildStd[0]); - } - else if(cp->PipeNativeSTDIN[0]) - { + } else if (cp->PipeNativeSTDIN[0]) { /* Use the provided native pipe. */ kwsysProcessSetupPipeNative(cp->PipeNativeSTDIN[0], &cp->PipeChildStd[0]); - } - else - { + } else { /* Explicitly give the child no stdin. */ cp->PipeChildStd[0] = INVALID_HANDLE_VALUE; - } + } /* Create the output pipe for the last process. We always create this so the pipe thread can run even if we do not end up giving the write end to the child below. */ - if(!CreatePipe(&cp->Pipe[KWSYSPE_PIPE_STDOUT].Read, - &cp->Pipe[KWSYSPE_PIPE_STDOUT].Write, 0, 0)) - { + if (!CreatePipe(&cp->Pipe[KWSYSPE_PIPE_STDOUT].Read, + &cp->Pipe[KWSYSPE_PIPE_STDOUT].Write, 0, 0)) { kwsysProcessCleanup(cp, GetLastError()); return; - } + } - if(cp->PipeFileSTDOUT) - { + if (cp->PipeFileSTDOUT) { /* Use a file for stdout. */ DWORD error = kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[1], cp->PipeFileSTDOUT); - if(error) - { + if (error) { kwsysProcessCleanup(cp, error); return; - } } - else if(cp->PipeSharedSTDOUT) - { + } else if (cp->PipeSharedSTDOUT) { /* Use the parent stdout. */ kwsysProcessSetupSharedPipe(STD_OUTPUT_HANDLE, &cp->PipeChildStd[1]); - } - else if(cp->PipeNativeSTDOUT[1]) - { + } else if (cp->PipeNativeSTDOUT[1]) { /* Use the given handle for stdout. */ kwsysProcessSetupPipeNative(cp->PipeNativeSTDOUT[1], &cp->PipeChildStd[1]); - } - else - { + } else { /* Use our pipe for stdout. Duplicate the handle since our waker thread will use the original. Do not make it inherited yet. */ - if(!DuplicateHandle(GetCurrentProcess(), - cp->Pipe[KWSYSPE_PIPE_STDOUT].Write, - GetCurrentProcess(), &cp->PipeChildStd[1], - 0, FALSE, DUPLICATE_SAME_ACCESS)) - { + if (!DuplicateHandle(GetCurrentProcess(), + cp->Pipe[KWSYSPE_PIPE_STDOUT].Write, + GetCurrentProcess(), &cp->PipeChildStd[1], 0, FALSE, + DUPLICATE_SAME_ACCESS)) { kwsysProcessCleanup(cp, GetLastError()); return; - } } + } /* Create stderr pipe to be shared by all processes in the pipeline. We always create this so the pipe thread can run even if we do not end up giving the write end to the child below. */ - if(!CreatePipe(&cp->Pipe[KWSYSPE_PIPE_STDERR].Read, - &cp->Pipe[KWSYSPE_PIPE_STDERR].Write, 0, 0)) - { + if (!CreatePipe(&cp->Pipe[KWSYSPE_PIPE_STDERR].Read, + &cp->Pipe[KWSYSPE_PIPE_STDERR].Write, 0, 0)) { kwsysProcessCleanup(cp, GetLastError()); return; - } + } - if(cp->PipeFileSTDERR) - { + if (cp->PipeFileSTDERR) { /* Use a file for stderr. */ DWORD error = kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[2], cp->PipeFileSTDERR); - if(error) - { + if (error) { kwsysProcessCleanup(cp, error); return; - } } - else if(cp->PipeSharedSTDERR) - { + } else if (cp->PipeSharedSTDERR) { /* Use the parent stderr. */ kwsysProcessSetupSharedPipe(STD_ERROR_HANDLE, &cp->PipeChildStd[2]); - } - else if(cp->PipeNativeSTDERR[1]) - { + } else if (cp->PipeNativeSTDERR[1]) { /* Use the given handle for stderr. */ kwsysProcessSetupPipeNative(cp->PipeNativeSTDERR[1], &cp->PipeChildStd[2]); - } - else - { + } else { /* Use our pipe for stderr. Duplicate the handle since our waker thread will use the original. Do not make it inherited yet. */ - if(!DuplicateHandle(GetCurrentProcess(), - cp->Pipe[KWSYSPE_PIPE_STDERR].Write, - GetCurrentProcess(), &cp->PipeChildStd[2], - 0, FALSE, DUPLICATE_SAME_ACCESS)) - { + if (!DuplicateHandle(GetCurrentProcess(), + cp->Pipe[KWSYSPE_PIPE_STDERR].Write, + GetCurrentProcess(), &cp->PipeChildStd[2], 0, FALSE, + DUPLICATE_SAME_ACCESS)) { kwsysProcessCleanup(cp, GetLastError()); return; - } } + } /* Create the pipeline of processes. */ { - /* Child startup control data. */ - kwsysProcessCreateInformation si; - HANDLE nextStdInput = cp->PipeChildStd[0]; - - /* Initialize startup info data. */ - ZeroMemory(&si, sizeof(si)); - si.StartupInfo.cb = sizeof(si.StartupInfo); - - /* Decide whether a child window should be shown. */ - si.StartupInfo.dwFlags |= STARTF_USESHOWWINDOW; - si.StartupInfo.wShowWindow = - (unsigned short)(cp->HideWindow?SW_HIDE:SW_SHOWDEFAULT); - - /* Connect the child's output pipes to the threads. */ - si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES; - - for(i=0; i < cp->NumberOfCommands; ++i) - { - /* Setup the process's pipes. */ - si.hStdInput = nextStdInput; - if (i == cp->NumberOfCommands-1) - { - /* The last child gets the overall stdout. */ - nextStdInput = INVALID_HANDLE_VALUE; - si.hStdOutput = cp->PipeChildStd[1]; - } - else - { - /* Create a pipe to sit between the children. */ - HANDLE p[2] = {INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE}; - if (!CreatePipe(&p[0], &p[1], 0, 0)) - { - DWORD error = GetLastError(); - if (nextStdInput != cp->PipeChildStd[0]) - { - kwsysProcessCleanupHandle(&nextStdInput); + /* Child startup control data. */ + kwsysProcessCreateInformation si; + HANDLE nextStdInput = cp->PipeChildStd[0]; + + /* Initialize startup info data. */ + ZeroMemory(&si, sizeof(si)); + si.StartupInfo.cb = sizeof(si.StartupInfo); + + /* Decide whether a child window should be shown. */ + si.StartupInfo.dwFlags |= STARTF_USESHOWWINDOW; + si.StartupInfo.wShowWindow = + (unsigned short)(cp->HideWindow ? SW_HIDE : SW_SHOWDEFAULT); + + /* Connect the child's output pipes to the threads. */ + si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES; + + for (i = 0; i < cp->NumberOfCommands; ++i) { + /* Setup the process's pipes. */ + si.hStdInput = nextStdInput; + if (i == cp->NumberOfCommands - 1) { + /* The last child gets the overall stdout. */ + nextStdInput = INVALID_HANDLE_VALUE; + si.hStdOutput = cp->PipeChildStd[1]; + } else { + /* Create a pipe to sit between the children. */ + HANDLE p[2] = { INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE }; + if (!CreatePipe(&p[0], &p[1], 0, 0)) { + DWORD error = GetLastError(); + if (nextStdInput != cp->PipeChildStd[0]) { + kwsysProcessCleanupHandle(&nextStdInput); } - kwsysProcessCleanup(cp, error); - return; + kwsysProcessCleanup(cp, error); + return; } - nextStdInput = p[0]; - si.hStdOutput = p[1]; + nextStdInput = p[0]; + si.hStdOutput = p[1]; } - si.hStdError = cp->MergeOutput? cp->PipeChildStd[1] : cp->PipeChildStd[2]; - - { - DWORD error = kwsysProcessCreate(cp, i, &si); + si.hStdError = + cp->MergeOutput ? cp->PipeChildStd[1] : cp->PipeChildStd[2]; - /* Close our copies of pipes used between children. */ - if (si.hStdInput != cp->PipeChildStd[0]) - { - kwsysProcessCleanupHandle(&si.hStdInput); - } - if (si.hStdOutput != cp->PipeChildStd[1]) - { - kwsysProcessCleanupHandle(&si.hStdOutput); - } - if (si.hStdError != cp->PipeChildStd[2] && !cp->MergeOutput) { - kwsysProcessCleanupHandle(&si.hStdError); - } - if (!error) - { - cp->ProcessEvents[i+1] = cp->ProcessInformation[i].hProcess; - } - else - { - if (nextStdInput != cp->PipeChildStd[0]) - { - kwsysProcessCleanupHandle(&nextStdInput); + DWORD error = kwsysProcessCreate(cp, i, &si); + + /* Close our copies of pipes used between children. */ + if (si.hStdInput != cp->PipeChildStd[0]) { + kwsysProcessCleanupHandle(&si.hStdInput); + } + if (si.hStdOutput != cp->PipeChildStd[1]) { + kwsysProcessCleanupHandle(&si.hStdOutput); + } + if (si.hStdError != cp->PipeChildStd[2] && !cp->MergeOutput) { + kwsysProcessCleanupHandle(&si.hStdError); + } + if (!error) { + cp->ProcessEvents[i + 1] = cp->ProcessInformation[i].hProcess; + } else { + if (nextStdInput != cp->PipeChildStd[0]) { + kwsysProcessCleanupHandle(&nextStdInput); + } + kwsysProcessCleanup(cp, error); + return; } - kwsysProcessCleanup(cp, error); - return; } } - } } /* The parent process does not need the child's pipe ends. */ - for (i=0; i < 3; ++i) - { + for (i = 0; i < 3; ++i) { kwsysProcessCleanupHandle(&cp->PipeChildStd[i]); - } + } /* Restore the working directory. */ - if(cp->RealWorkingDirectory) - { + if (cp->RealWorkingDirectory) { SetCurrentDirectoryW(cp->RealWorkingDirectory); free(cp->RealWorkingDirectory); cp->RealWorkingDirectory = 0; - } + } /* The timeout period starts now. */ cp->StartTime = kwsysProcessTimeGetCurrent(); @@ -1203,24 +1110,21 @@ void kwsysProcess_Execute(kwsysProcess* cp) /* All processes in the pipeline have been started in suspended mode. Resume them all now. */ - for(i=0; i < cp->NumberOfCommands; ++i) - { + for (i = 0; i < cp->NumberOfCommands; ++i) { ResumeThread(cp->ProcessInformation[i].hThread); - } + } /* ---- It is no longer safe to call kwsysProcessCleanup. ----- */ /* Tell the pipe threads that a process has started. */ - for(i=0; i < KWSYSPE_PIPE_COUNT; ++i) - { + for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) { ReleaseSemaphore(cp->Pipe[i].Reader.Ready, 1, 0); ReleaseSemaphore(cp->Pipe[i].Waker.Ready, 1, 0); - } + } /* We don't care about the children's main threads. */ - for(i=0; i < cp->NumberOfCommands; ++i) - { + for (i = 0; i < cp->NumberOfCommands; ++i) { kwsysProcessCleanupHandle(&cp->ProcessInformation[i].hThread); - } + } /* No pipe has reported data. */ cp->CurrentIndex = KWSYSPE_PIPE_COUNT; @@ -1237,21 +1141,19 @@ void kwsysProcess_Disown(kwsysProcess* cp) int i; /* Make sure we are executing a detached process. */ - if(!cp || !cp->Detached || cp->State != kwsysProcess_State_Executing || - cp->TimeoutExpired || cp->Killed || cp->Terminated) - { + if (!cp || !cp->Detached || cp->State != kwsysProcess_State_Executing || + cp->TimeoutExpired || cp->Killed || cp->Terminated) { return; - } + } /* Disable the reading threads. */ kwsysProcessDisablePipeThreads(cp); /* Wait for all pipe threads to reset. */ - for(i=0; i < KWSYSPE_PIPE_COUNT; ++i) - { + for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) { WaitForSingleObject(cp->Pipe[i].Reader.Reset, INFINITE); WaitForSingleObject(cp->Pipe[i].Waker.Reset, INFINITE); - } + } /* We will not wait for exit, so cleanup now. */ kwsysProcessCleanup(cp, 0); @@ -1276,11 +1178,10 @@ int kwsysProcess_WaitForData(kwsysProcess* cp, char** data, int* length, DWORD w; /* Make sure we are executing a process. */ - if(!cp || cp->State != kwsysProcess_State_Executing || cp->Killed || - cp->TimeoutExpired) - { + if (!cp || cp->State != kwsysProcess_State_Executing || cp->Killed || + cp->TimeoutExpired) { return kwsysProcess_Pipe_None; - } + } /* Record the time at which user timeout period starts. */ userStartTime = kwsysProcessTimeGetCurrent(); @@ -1290,125 +1191,102 @@ int kwsysProcess_WaitForData(kwsysProcess* cp, char** data, int* length, user = kwsysProcessGetTimeoutTime(cp, userTimeout, &timeoutTime); /* Loop until we have a reason to return. */ - while(!done && cp->PipesLeft > 0) - { + while (!done && cp->PipesLeft > 0) { /* If we previously got data from a thread, let it know we are done with the data. */ - if(cp->CurrentIndex < KWSYSPE_PIPE_COUNT) - { + if (cp->CurrentIndex < KWSYSPE_PIPE_COUNT) { KWSYSPE_DEBUG((stderr, "releasing reader %d\n", cp->CurrentIndex)); ReleaseSemaphore(cp->Pipe[cp->CurrentIndex].Reader.Go, 1, 0); cp->CurrentIndex = KWSYSPE_PIPE_COUNT; - } + } /* Setup a timeout if required. */ - if(kwsysProcessGetTimeoutLeft(&timeoutTime, user?userTimeout:0, - &timeoutLength)) - { + if (kwsysProcessGetTimeoutLeft(&timeoutTime, user ? userTimeout : 0, + &timeoutLength)) { /* Timeout has already expired. */ expired = 1; break; - } - if(timeoutTime.QuadPart < 0) - { + } + if (timeoutTime.QuadPart < 0) { timeout = INFINITE; - } - else - { + } else { timeout = kwsysProcessTimeToDWORD(timeoutLength); - } + } /* Wait for a pipe's thread to signal or a process to terminate. */ - w = WaitForMultipleObjects(cp->ProcessEventsLength, cp->ProcessEvents, - 0, timeout); - if(w == WAIT_TIMEOUT) - { + w = WaitForMultipleObjects(cp->ProcessEventsLength, cp->ProcessEvents, 0, + timeout); + if (w == WAIT_TIMEOUT) { /* Timeout has expired. */ expired = 1; done = 1; - } - else if(w == WAIT_OBJECT_0) - { + } else if (w == WAIT_OBJECT_0) { /* Save the index of the reporting thread and release the mutex. The thread will block until we signal its Empty mutex. */ cp->CurrentIndex = cp->SharedIndex; ReleaseSemaphore(cp->SharedIndexMutex, 1, 0); /* Data are available or a pipe closed. */ - if(cp->Pipe[cp->CurrentIndex].Closed) - { + if (cp->Pipe[cp->CurrentIndex].Closed) { /* The pipe closed at the write end. Close the read end and inform the wakeup thread it is done with this process. */ kwsysProcessCleanupHandle(&cp->Pipe[cp->CurrentIndex].Read); ReleaseSemaphore(cp->Pipe[cp->CurrentIndex].Waker.Go, 1, 0); KWSYSPE_DEBUG((stderr, "wakeup %d\n", cp->CurrentIndex)); --cp->PipesLeft; - } - else if(data && length) - { + } else if (data && length) { /* Report this data. */ *data = cp->Pipe[cp->CurrentIndex].DataBuffer; *length = cp->Pipe[cp->CurrentIndex].DataLength; - switch(cp->CurrentIndex) - { + switch (cp->CurrentIndex) { case KWSYSPE_PIPE_STDOUT: - pipeId = kwsysProcess_Pipe_STDOUT; break; + pipeId = kwsysProcess_Pipe_STDOUT; + break; case KWSYSPE_PIPE_STDERR: - pipeId = kwsysProcess_Pipe_STDERR; break; - } - done = 1; + pipeId = kwsysProcess_Pipe_STDERR; + break; } + done = 1; } - else - { + } else { /* A process has terminated. */ - kwsysProcessDestroy(cp, w-WAIT_OBJECT_0); - } + kwsysProcessDestroy(cp, w - WAIT_OBJECT_0); } + } /* Update the user timeout. */ - if(userTimeout) - { + if (userTimeout) { kwsysProcessTime userEndTime = kwsysProcessTimeGetCurrent(); - kwsysProcessTime difference = kwsysProcessTimeSubtract(userEndTime, - userStartTime); + kwsysProcessTime difference = + kwsysProcessTimeSubtract(userEndTime, userStartTime); double d = kwsysProcessTimeToDouble(difference); *userTimeout -= d; - if(*userTimeout < 0) - { + if (*userTimeout < 0) { *userTimeout = 0; - } } + } /* Check what happened. */ - if(pipeId) - { + if (pipeId) { /* Data are ready on a pipe. */ return pipeId; - } - else if(expired) - { + } else if (expired) { /* A timeout has expired. */ - if(user) - { + if (user) { /* The user timeout has expired. It has no time left. */ return kwsysProcess_Pipe_Timeout; - } - else - { + } else { /* The process timeout has expired. Kill the child now. */ KWSYSPE_DEBUG((stderr, "killing child because timeout expired\n")); kwsysProcess_Kill(cp); cp->TimeoutExpired = 1; cp->Killed = 0; return kwsysProcess_Pipe_None; - } } - else - { + } else { /* The children have terminated and no more data are available. */ return kwsysProcess_Pipe_None; - } + } } /*--------------------------------------------------------------------------*/ @@ -1418,75 +1296,62 @@ int kwsysProcess_WaitForExit(kwsysProcess* cp, double* userTimeout) int pipe; /* Make sure we are executing a process. */ - if(!cp || cp->State != kwsysProcess_State_Executing) - { + if (!cp || cp->State != kwsysProcess_State_Executing) { return 1; - } + } /* Wait for the process to terminate. Ignore all data. */ - while((pipe = kwsysProcess_WaitForData(cp, 0, 0, userTimeout)) > 0) - { - if(pipe == kwsysProcess_Pipe_Timeout) - { + while ((pipe = kwsysProcess_WaitForData(cp, 0, 0, userTimeout)) > 0) { + if (pipe == kwsysProcess_Pipe_Timeout) { /* The user timeout has expired. */ return 0; - } } + } KWSYSPE_DEBUG((stderr, "no more data\n")); /* When the last pipe closes in WaitForData, the loop terminates without releasing the pipe's thread. Release it now. */ - if(cp->CurrentIndex < KWSYSPE_PIPE_COUNT) - { + if (cp->CurrentIndex < KWSYSPE_PIPE_COUNT) { KWSYSPE_DEBUG((stderr, "releasing reader %d\n", cp->CurrentIndex)); ReleaseSemaphore(cp->Pipe[cp->CurrentIndex].Reader.Go, 1, 0); cp->CurrentIndex = KWSYSPE_PIPE_COUNT; - } + } /* Wait for all pipe threads to reset. */ - for(i=0; i < KWSYSPE_PIPE_COUNT; ++i) - { + for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) { KWSYSPE_DEBUG((stderr, "waiting reader reset %d\n", i)); WaitForSingleObject(cp->Pipe[i].Reader.Reset, INFINITE); KWSYSPE_DEBUG((stderr, "waiting waker reset %d\n", i)); WaitForSingleObject(cp->Pipe[i].Waker.Reset, INFINITE); - } + } /* ---- It is now safe again to call kwsysProcessCleanup. ----- */ /* Close all the pipes. */ kwsysProcessCleanup(cp, 0); /* Determine the outcome. */ - if(cp->Killed) - { + if (cp->Killed) { /* We killed the child. */ cp->State = kwsysProcess_State_Killed; - } - else if(cp->TimeoutExpired) - { + } else if (cp->TimeoutExpired) { /* The timeout expired. */ cp->State = kwsysProcess_State_Expired; - } - else - { + } else { /* The children exited. Report the outcome of the last process. */ - cp->ExitCode = cp->CommandExitCodes[cp->NumberOfCommands-1]; - if((cp->ExitCode & 0xF0000000) == 0xC0000000) - { + cp->ExitCode = cp->CommandExitCodes[cp->NumberOfCommands - 1]; + if ((cp->ExitCode & 0xF0000000) == 0xC0000000) { /* Child terminated due to exceptional behavior. */ cp->State = kwsysProcess_State_Exception; cp->ExitValue = 1; kwsysProcessSetExitException(cp, cp->ExitCode); - } - else - { + } else { /* Child exited without exception. */ cp->State = kwsysProcess_State_Exited; cp->ExitException = kwsysProcess_Exception_None; cp->ExitValue = cp->ExitCode; - } } + } return 1; } @@ -1496,45 +1361,37 @@ void kwsysProcess_Interrupt(kwsysProcess* cp) { int i; /* Make sure we are executing a process. */ - if(!cp || cp->State != kwsysProcess_State_Executing || cp->TimeoutExpired || - cp->Killed) - { + if (!cp || cp->State != kwsysProcess_State_Executing || cp->TimeoutExpired || + cp->Killed) { KWSYSPE_DEBUG((stderr, "interrupt: child not executing\n")); return; - } + } /* Skip actually interrupting the child if it has already terminated. */ - if(cp->Terminated) - { + if (cp->Terminated) { KWSYSPE_DEBUG((stderr, "interrupt: child already terminated\n")); return; - } + } /* Interrupt the children. */ - if (cp->CreateProcessGroup) - { - if(cp->ProcessInformation) - { - for(i=0; i < cp->NumberOfCommands; ++i) - { + if (cp->CreateProcessGroup) { + if (cp->ProcessInformation) { + for (i = 0; i < cp->NumberOfCommands; ++i) { /* Make sure the process handle isn't closed (e.g. from disowning). */ - if(cp->ProcessInformation[i].hProcess) - { + if (cp->ProcessInformation[i].hProcess) { /* The user created a process group for this process. The group ID is the process ID for the original process in the group. Note that we have to use Ctrl+Break: Ctrl+C is not allowed for process groups. */ GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, cp->ProcessInformation[i].dwProcessId); - } } } } - else - { + } else { /* No process group was created. Kill our own process group... */ GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, 0); - } + } } /*--------------------------------------------------------------------------*/ @@ -1542,34 +1399,31 @@ void kwsysProcess_Kill(kwsysProcess* cp) { int i; /* Make sure we are executing a process. */ - if(!cp || cp->State != kwsysProcess_State_Executing || cp->TimeoutExpired || - cp->Killed) - { + if (!cp || cp->State != kwsysProcess_State_Executing || cp->TimeoutExpired || + cp->Killed) { KWSYSPE_DEBUG((stderr, "kill: child not executing\n")); return; - } + } /* Disable the reading threads. */ KWSYSPE_DEBUG((stderr, "kill: disabling pipe threads\n")); kwsysProcessDisablePipeThreads(cp); /* Skip actually killing the child if it has already terminated. */ - if(cp->Terminated) - { + if (cp->Terminated) { KWSYSPE_DEBUG((stderr, "kill: child already terminated\n")); return; - } + } /* Kill the children. */ cp->Killed = 1; - for(i=0; i < cp->NumberOfCommands; ++i) - { + for (i = 0; i < cp->NumberOfCommands; ++i) { kwsysProcessKillTree(cp->ProcessInformation[i].dwProcessId); /* Remove from global list of processes and close handles. */ kwsysProcessesRemove(cp->ProcessInformation[i].hProcess); kwsysProcessCleanupHandle(&cp->ProcessInformation[i].hThread); kwsysProcessCleanupHandle(&cp->ProcessInformation[i].hProcess); - } + } /* We are killing the children and ignoring all data. Do not wait for them to exit. */ @@ -1587,14 +1441,13 @@ DWORD WINAPI kwsysProcessPipeThreadRead(LPVOID ptd) kwsysProcess* cp = td->Process; /* Wait for a process to be ready. */ - while((WaitForSingleObject(td->Reader.Ready, INFINITE), !cp->Deleting)) - { + while ((WaitForSingleObject(td->Reader.Ready, INFINITE), !cp->Deleting)) { /* Read output from the process for this thread's pipe. */ kwsysProcessPipeThreadReadPipe(cp, td); /* Signal the main thread we have reset for a new process. */ ReleaseSemaphore(td->Reader.Reset, 1, 0); - } + } return 0; } @@ -1607,24 +1460,21 @@ DWORD WINAPI kwsysProcessPipeThreadRead(LPVOID ptd) void kwsysProcessPipeThreadReadPipe(kwsysProcess* cp, kwsysProcessPipeData* td) { /* Wait for space in the thread's buffer. */ - while((KWSYSPE_DEBUG((stderr, "wait for read %d\n", td->Index)), - WaitForSingleObject(td->Reader.Go, INFINITE), !td->Closed)) - { + while ((KWSYSPE_DEBUG((stderr, "wait for read %d\n", td->Index)), + WaitForSingleObject(td->Reader.Go, INFINITE), !td->Closed)) { KWSYSPE_DEBUG((stderr, "reading %d\n", td->Index)); /* Read data from the pipe. This may block until data are available. */ - if(!ReadFile(td->Read, td->DataBuffer, KWSYSPE_PIPE_BUFFER_SIZE, - &td->DataLength, 0)) - { - if(GetLastError() != ERROR_BROKEN_PIPE) - { + if (!ReadFile(td->Read, td->DataBuffer, KWSYSPE_PIPE_BUFFER_SIZE, + &td->DataLength, 0)) { + if (GetLastError() != ERROR_BROKEN_PIPE) { /* UNEXPECTED failure to read the pipe. */ - } + } /* The pipe closed. There are no more data to read. */ td->Closed = 1; KWSYSPE_DEBUG((stderr, "read closed %d\n", td->Index)); - } + } KWSYSPE_DEBUG((stderr, "read %d\n", td->Index)); @@ -1636,7 +1486,7 @@ void kwsysProcessPipeThreadReadPipe(kwsysProcess* cp, kwsysProcessPipeData* td) /* Tell the main thread we have something to report. */ cp->SharedIndex = td->Index; ReleaseSemaphore(cp->Full, 1, 0); - } + } /* We were signalled to exit with our buffer empty. Reset the mutex for a new process. */ @@ -1656,14 +1506,13 @@ DWORD WINAPI kwsysProcessPipeThreadWake(LPVOID ptd) kwsysProcess* cp = td->Process; /* Wait for a process to be ready. */ - while((WaitForSingleObject(td->Waker.Ready, INFINITE), !cp->Deleting)) - { + while ((WaitForSingleObject(td->Waker.Ready, INFINITE), !cp->Deleting)) { /* Wait for a possible wakeup. */ kwsysProcessPipeThreadWakePipe(cp, td); /* Signal the main thread we have reset for a new process. */ ReleaseSemaphore(td->Waker.Reset, 1, 0); - } + } return 0; } @@ -1683,13 +1532,12 @@ void kwsysProcessPipeThreadWakePipe(kwsysProcess* cp, kwsysProcessPipeData* td) KWSYSPE_DEBUG((stderr, "waking %d\n", td->Index)); /* If the pipe is not closed, we need to wake up the reading thread. */ - if(!td->Closed) - { + if (!td->Closed) { DWORD dummy; KWSYSPE_DEBUG((stderr, "waker %d writing byte\n", td->Index)); WriteFile(td->Write, "", 1, &dummy, 0); KWSYSPE_DEBUG((stderr, "waker %d wrote byte\n", td->Index)); - } + } } /*--------------------------------------------------------------------------*/ @@ -1709,55 +1557,48 @@ int kwsysProcessInitialize(kwsysProcess* cp) strcpy(cp->ExitExceptionString, "No exception"); /* Allocate process information for each process. */ - cp->ProcessInformation = - (PROCESS_INFORMATION*)malloc(sizeof(PROCESS_INFORMATION) * - cp->NumberOfCommands); - if(!cp->ProcessInformation) - { + cp->ProcessInformation = (PROCESS_INFORMATION*)malloc( + sizeof(PROCESS_INFORMATION) * cp->NumberOfCommands); + if (!cp->ProcessInformation) { return 0; - } + } ZeroMemory(cp->ProcessInformation, sizeof(PROCESS_INFORMATION) * cp->NumberOfCommands); - if(cp->CommandExitCodes) - { + if (cp->CommandExitCodes) { free(cp->CommandExitCodes); - } - cp->CommandExitCodes = (DWORD*)malloc(sizeof(DWORD)*cp->NumberOfCommands); - if(!cp->CommandExitCodes) - { + } + cp->CommandExitCodes = (DWORD*)malloc(sizeof(DWORD) * cp->NumberOfCommands); + if (!cp->CommandExitCodes) { return 0; - } - ZeroMemory(cp->CommandExitCodes, sizeof(DWORD)*cp->NumberOfCommands); + } + ZeroMemory(cp->CommandExitCodes, sizeof(DWORD) * cp->NumberOfCommands); /* Allocate event wait array. The first event is cp->Full, the rest are the process termination events. */ - cp->ProcessEvents = (PHANDLE)malloc(sizeof(HANDLE)*(cp->NumberOfCommands+1)); - if(!cp->ProcessEvents) - { + cp->ProcessEvents = + (PHANDLE)malloc(sizeof(HANDLE) * (cp->NumberOfCommands + 1)); + if (!cp->ProcessEvents) { return 0; - } - ZeroMemory(cp->ProcessEvents, sizeof(HANDLE) * (cp->NumberOfCommands+1)); + } + ZeroMemory(cp->ProcessEvents, sizeof(HANDLE) * (cp->NumberOfCommands + 1)); cp->ProcessEvents[0] = cp->Full; - cp->ProcessEventsLength = cp->NumberOfCommands+1; + cp->ProcessEventsLength = cp->NumberOfCommands + 1; /* Allocate space to save the real working directory of this process. */ - if(cp->WorkingDirectory) - { + if (cp->WorkingDirectory) { cp->RealWorkingDirectoryLength = GetCurrentDirectoryW(0, 0); - if(cp->RealWorkingDirectoryLength > 0) - { - cp->RealWorkingDirectory = malloc(cp->RealWorkingDirectoryLength * sizeof(wchar_t)); - if(!cp->RealWorkingDirectory) - { + if (cp->RealWorkingDirectoryLength > 0) { + cp->RealWorkingDirectory = + malloc(cp->RealWorkingDirectoryLength * sizeof(wchar_t)); + if (!cp->RealWorkingDirectory) { return 0; - } } } + } { - int i; - for (i=0; i < 3; ++i) - { - cp->PipeChildStd[i] = INVALID_HANDLE_VALUE; + int i; + for (i = 0; i < 3; ++i) { + cp->PipeChildStd[i] = INVALID_HANDLE_VALUE; } } @@ -1770,28 +1611,21 @@ static DWORD kwsysProcessCreateChildHandle(PHANDLE out, HANDLE in, int isStdIn) DWORD flags; /* Check whether the handle is valid for this process. */ - if (in != INVALID_HANDLE_VALUE && GetHandleInformation(in, &flags)) - { + if (in != INVALID_HANDLE_VALUE && GetHandleInformation(in, &flags)) { /* Use the handle as-is if it is already inherited. */ - if (flags & HANDLE_FLAG_INHERIT) - { + if (flags & HANDLE_FLAG_INHERIT) { *out = in; return ERROR_SUCCESS; - } + } /* Create an inherited copy of this handle. */ - if (DuplicateHandle(GetCurrentProcess(), in, GetCurrentProcess(), out, - 0, TRUE, DUPLICATE_SAME_ACCESS)) - { + if (DuplicateHandle(GetCurrentProcess(), in, GetCurrentProcess(), out, 0, + TRUE, DUPLICATE_SAME_ACCESS)) { return ERROR_SUCCESS; - } - else - { + } else { return GetLastError(); - } } - else - { + } else { /* The given handle is not valid for this process. Some child processes may break if they do not have a valid standard handle, so open NUL to give to the child. */ @@ -1799,13 +1633,12 @@ static DWORD kwsysProcessCreateChildHandle(PHANDLE out, HANDLE in, int isStdIn) ZeroMemory(&sa, sizeof(sa)); sa.nLength = (DWORD)sizeof(sa); sa.bInheritHandle = 1; - *out = CreateFileW(L"NUL", - (isStdIn ? GENERIC_READ : - (GENERIC_WRITE | FILE_READ_ATTRIBUTES)), - FILE_SHARE_READ|FILE_SHARE_WRITE, - &sa, OPEN_EXISTING, 0, 0); + *out = CreateFileW( + L"NUL", + (isStdIn ? GENERIC_READ : (GENERIC_WRITE | FILE_READ_ATTRIBUTES)), + FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, 0); return (*out != INVALID_HANDLE_VALUE) ? ERROR_SUCCESS : GetLastError(); - } + } } /*--------------------------------------------------------------------------*/ @@ -1816,54 +1649,49 @@ DWORD kwsysProcessCreate(kwsysProcess* cp, int index, DWORD error = ERROR_SUCCESS; /* Check if we are currently exiting. */ - if (!kwsysTryEnterCreateProcessSection()) - { + if (!kwsysTryEnterCreateProcessSection()) { /* The Ctrl handler is currently working on exiting our process. Rather than return an error code, which could cause incorrect conclusions to be reached by the caller, we simply hang. (For example, a CMake try_run configure step might cause the project to configure wrong.) */ Sleep(INFINITE); - } + } /* Create the child in a suspended state so we can wait until all children have been created before running any one. */ creationFlags = CREATE_SUSPENDED; - if (cp->CreateProcessGroup) - { + if (cp->CreateProcessGroup) { creationFlags |= CREATE_NEW_PROCESS_GROUP; - } + } /* Create inherited copies of the handles. */ (error = kwsysProcessCreateChildHandle(&si->StartupInfo.hStdInput, - si->hStdInput, 1)) || - (error = kwsysProcessCreateChildHandle(&si->StartupInfo.hStdOutput, - si->hStdOutput, 0)) || - (error = kwsysProcessCreateChildHandle(&si->StartupInfo.hStdError, - si->hStdError, 0)) || - /* Create the process. */ - (!CreateProcessW(0, cp->Commands[index], 0, 0, TRUE, creationFlags, 0, - 0, &si->StartupInfo, &cp->ProcessInformation[index]) && - (error = GetLastError())); + si->hStdInput, 1)) || + (error = kwsysProcessCreateChildHandle(&si->StartupInfo.hStdOutput, + si->hStdOutput, 0)) || + (error = kwsysProcessCreateChildHandle(&si->StartupInfo.hStdError, + si->hStdError, 0)) || + /* Create the process. */ + (!CreateProcessW(0, cp->Commands[index], 0, 0, TRUE, creationFlags, 0, 0, + &si->StartupInfo, &cp->ProcessInformation[index]) && + (error = GetLastError())); /* Close the inherited copies of the handles. */ - if (si->StartupInfo.hStdInput != si->hStdInput) - { + if (si->StartupInfo.hStdInput != si->hStdInput) { kwsysProcessCleanupHandle(&si->StartupInfo.hStdInput); - } - if (si->StartupInfo.hStdOutput != si->hStdOutput) - { + } + if (si->StartupInfo.hStdOutput != si->hStdOutput) { kwsysProcessCleanupHandle(&si->StartupInfo.hStdOutput); - } - if (si->StartupInfo.hStdError != si->hStdError) - { + } + if (si->StartupInfo.hStdError != si->hStdError) { kwsysProcessCleanupHandle(&si->StartupInfo.hStdError); - } + } /* Add the process to the global list of processes. */ if (!error && !kwsysProcessesAdd(cp->ProcessInformation[index].hProcess, - cp->ProcessInformation[index].dwProcessId, cp->CreateProcessGroup)) - { + cp->ProcessInformation[index].dwProcessId, + cp->CreateProcessGroup)) { /* This failed for some reason. Kill the suspended process. */ TerminateProcess(cp->ProcessInformation[index].hProcess, 1); /* And clean up... */ @@ -1871,7 +1699,7 @@ DWORD kwsysProcessCreate(kwsysProcess* cp, int index, kwsysProcessCleanupHandle(&cp->ProcessInformation[index].hThread); strcpy(cp->ErrorMessage, "kwsysProcessesAdd function failed"); error = ERROR_NOT_ENOUGH_MEMORY; /* Most likely reason. */ - } + } /* If the console Ctrl handler is waiting for us, this will release it... */ kwsysLeaveCreateProcessSection(); @@ -1885,13 +1713,11 @@ void kwsysProcessDestroy(kwsysProcess* cp, int event) int index; /* Find the process index for the termination event. */ - for(index=0; index < cp->NumberOfCommands; ++index) - { - if(cp->ProcessInformation[index].hProcess == cp->ProcessEvents[event]) - { + for (index = 0; index < cp->NumberOfCommands; ++index) { + if (cp->ProcessInformation[index].hProcess == cp->ProcessEvents[event]) { break; - } } + } /* Check the exit code of the process. */ GetExitCodeProcess(cp->ProcessInformation[index].hProcess, @@ -1905,20 +1731,17 @@ void kwsysProcessDestroy(kwsysProcess* cp, int event) /* Remove the process from the available events. */ cp->ProcessEventsLength -= 1; - for(i=event; i < cp->ProcessEventsLength; ++i) - { - cp->ProcessEvents[i] = cp->ProcessEvents[i+1]; - } + for (i = event; i < cp->ProcessEventsLength; ++i) { + cp->ProcessEvents[i] = cp->ProcessEvents[i + 1]; + } /* Check if all processes have terminated. */ - if(cp->ProcessEventsLength == 1) - { + if (cp->ProcessEventsLength == 1) { cp->Terminated = 1; /* Close our copies of the pipe write handles so the pipe threads can detect end-of-data. */ - for(i=0; i < KWSYSPE_PIPE_COUNT; ++i) - { + for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) { /* TODO: If the child created its own child (our grandchild) which inherited a copy of the pipe write-end then the pipe may not close and we will still need the waker write pipe. @@ -1929,8 +1752,8 @@ void kwsysProcessDestroy(kwsysProcess* cp, int event) read on posix. */ KWSYSPE_DEBUG((stderr, "closing wakeup write %d\n", i)); kwsysProcessCleanupHandle(&cp->Pipe[i].Write); - } } + } } /*--------------------------------------------------------------------------*/ @@ -1939,24 +1762,22 @@ DWORD kwsysProcessSetupOutputPipeFile(PHANDLE phandle, const char* name) HANDLE fout; wchar_t* wname; DWORD error; - if(!name) - { + if (!name) { return ERROR_INVALID_PARAMETER; - } + } /* Close the existing handle. */ kwsysProcessCleanupHandle(phandle); /* Create a handle to write a file for the pipe. */ wname = kwsysEncoding_DupToWide(name); - fout = CreateFileW(wname, GENERIC_WRITE, FILE_SHARE_READ, 0, - CREATE_ALWAYS, 0, 0); + fout = + CreateFileW(wname, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0); error = GetLastError(); free(wname); - if(fout == INVALID_HANDLE_VALUE) - { + if (fout == INVALID_HANDLE_VALUE) { return error; - } + } /* Assign the replacement handle. */ *phandle = fout; @@ -1986,14 +1807,13 @@ void kwsysProcessSetupPipeNative(HANDLE native, PHANDLE handle) /* Close the given handle if it is open. Reset its value to 0. */ void kwsysProcessCleanupHandle(PHANDLE h) { - if(h && *h && *h != INVALID_HANDLE_VALUE && - *h != GetStdHandle(STD_INPUT_HANDLE) && - *h != GetStdHandle(STD_OUTPUT_HANDLE) && - *h != GetStdHandle(STD_ERROR_HANDLE)) - { + if (h && *h && *h != INVALID_HANDLE_VALUE && + *h != GetStdHandle(STD_INPUT_HANDLE) && + *h != GetStdHandle(STD_OUTPUT_HANDLE) && + *h != GetStdHandle(STD_ERROR_HANDLE)) { CloseHandle(*h); *h = INVALID_HANDLE_VALUE; - } + } } /*--------------------------------------------------------------------------*/ @@ -2003,35 +1823,31 @@ void kwsysProcessCleanup(kwsysProcess* cp, DWORD error) { int i; /* If this is an error case, report the error. */ - if(error) - { + if (error) { /* Construct an error message if one has not been provided already. */ - if(cp->ErrorMessage[0] == 0) - { + if (cp->ErrorMessage[0] == 0) { /* Format the error message. */ wchar_t err_msg[KWSYSPE_PIPE_BUFFER_SIZE]; - DWORD length = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, 0, error, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - err_msg, KWSYSPE_PIPE_BUFFER_SIZE, 0); - if(length < 1) - { + DWORD length = FormatMessageW( + FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, error, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), err_msg, + KWSYSPE_PIPE_BUFFER_SIZE, 0); + if (length < 1) { /* FormatMessage failed. Use a default message. */ _snprintf(cp->ErrorMessage, KWSYSPE_PIPE_BUFFER_SIZE, "Process execution failed with error 0x%X. " "FormatMessage failed with error 0x%X", error, GetLastError()); - } - if(!WideCharToMultiByte(CP_UTF8, 0, err_msg, -1, cp->ErrorMessage, - KWSYSPE_PIPE_BUFFER_SIZE, NULL, NULL)) - { + } + if (!WideCharToMultiByte(CP_UTF8, 0, err_msg, -1, cp->ErrorMessage, + KWSYSPE_PIPE_BUFFER_SIZE, NULL, NULL)) { /* WideCharToMultiByte failed. Use a default message. */ _snprintf(cp->ErrorMessage, KWSYSPE_PIPE_BUFFER_SIZE, "Process execution failed with error 0x%X. " "WideCharToMultiByte failed with error 0x%X", error, GetLastError()); - } } + } /* Remove trailing period and newline, if any. */ kwsysProcessCleanErrorMessage(cp); @@ -2040,60 +1856,50 @@ void kwsysProcessCleanup(kwsysProcess* cp, DWORD error) cp->State = kwsysProcess_State_Error; /* Cleanup any processes already started in a suspended state. */ - if(cp->ProcessInformation) - { - for(i=0; i < cp->NumberOfCommands; ++i) - { - if(cp->ProcessInformation[i].hProcess) - { + if (cp->ProcessInformation) { + for (i = 0; i < cp->NumberOfCommands; ++i) { + if (cp->ProcessInformation[i].hProcess) { TerminateProcess(cp->ProcessInformation[i].hProcess, 255); WaitForSingleObject(cp->ProcessInformation[i].hProcess, INFINITE); - } } - for(i=0; i < cp->NumberOfCommands; ++i) - { + } + for (i = 0; i < cp->NumberOfCommands; ++i) { /* Remove from global list of processes and close handles. */ kwsysProcessesRemove(cp->ProcessInformation[i].hProcess); kwsysProcessCleanupHandle(&cp->ProcessInformation[i].hThread); kwsysProcessCleanupHandle(&cp->ProcessInformation[i].hProcess); - } } + } /* Restore the working directory. */ - if(cp->RealWorkingDirectory) - { + if (cp->RealWorkingDirectory) { SetCurrentDirectoryW(cp->RealWorkingDirectory); - } } + } /* Free memory. */ - if(cp->ProcessInformation) - { + if (cp->ProcessInformation) { free(cp->ProcessInformation); cp->ProcessInformation = 0; - } - if(cp->ProcessEvents) - { + } + if (cp->ProcessEvents) { free(cp->ProcessEvents); cp->ProcessEvents = 0; - } - if(cp->RealWorkingDirectory) - { + } + if (cp->RealWorkingDirectory) { free(cp->RealWorkingDirectory); cp->RealWorkingDirectory = 0; - } + } /* Close each pipe. */ - for(i=0; i < KWSYSPE_PIPE_COUNT; ++i) - { + for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) { kwsysProcessCleanupHandle(&cp->Pipe[i].Write); kwsysProcessCleanupHandle(&cp->Pipe[i].Read); cp->Pipe[i].Closed = 0; - } - for(i=0; i < 3; ++i) - { + } + for (i = 0; i < 3; ++i) { kwsysProcessCleanupHandle(&cp->PipeChildStd[i]); - } + } } /*--------------------------------------------------------------------------*/ @@ -2101,20 +1907,17 @@ void kwsysProcessCleanErrorMessage(kwsysProcess* cp) { /* Remove trailing period and newline, if any. */ size_t length = strlen(cp->ErrorMessage); - if(cp->ErrorMessage[length-1] == '\n') - { - cp->ErrorMessage[length-1] = 0; + if (cp->ErrorMessage[length - 1] == '\n') { + cp->ErrorMessage[length - 1] = 0; --length; - if(length > 0 && cp->ErrorMessage[length-1] == '\r') - { - cp->ErrorMessage[length-1] = 0; + if (length > 0 && cp->ErrorMessage[length - 1] == '\r') { + cp->ErrorMessage[length - 1] = 0; --length; - } - } - if(length > 0 && cp->ErrorMessage[length-1] == '.') - { - cp->ErrorMessage[length-1] = 0; } + } + if (length > 0 && cp->ErrorMessage[length - 1] == '.') { + cp->ErrorMessage[length - 1] = 0; + } } /*--------------------------------------------------------------------------*/ @@ -2125,29 +1928,27 @@ int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout, { /* The first time this is called, we need to calculate the time at which the child will timeout. */ - if(cp->Timeout && cp->TimeoutTime.QuadPart < 0) - { + if (cp->Timeout && cp->TimeoutTime.QuadPart < 0) { kwsysProcessTime length = kwsysProcessTimeFromDouble(cp->Timeout); cp->TimeoutTime = kwsysProcessTimeAdd(cp->StartTime, length); - } + } /* Start with process timeout. */ *timeoutTime = cp->TimeoutTime; /* Check if the user timeout is earlier. */ - if(userTimeout) - { + if (userTimeout) { kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent(); - kwsysProcessTime userTimeoutLength = kwsysProcessTimeFromDouble(*userTimeout); - kwsysProcessTime userTimeoutTime = kwsysProcessTimeAdd(currentTime, - userTimeoutLength); - if(timeoutTime->QuadPart < 0 || - kwsysProcessTimeLess(userTimeoutTime, *timeoutTime)) - { + kwsysProcessTime userTimeoutLength = + kwsysProcessTimeFromDouble(*userTimeout); + kwsysProcessTime userTimeoutTime = + kwsysProcessTimeAdd(currentTime, userTimeoutLength); + if (timeoutTime->QuadPart < 0 || + kwsysProcessTimeLess(userTimeoutTime, *timeoutTime)) { *timeoutTime = userTimeoutTime; return 1; - } } + } return 0; } @@ -2158,34 +1959,27 @@ int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime, double* userTimeout, kwsysProcessTime* timeoutLength) { - if(timeoutTime->QuadPart < 0) - { + if (timeoutTime->QuadPart < 0) { /* No timeout time has been requested. */ return 0; - } - else - { + } else { /* Calculate the remaining time. */ kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent(); *timeoutLength = kwsysProcessTimeSubtract(*timeoutTime, currentTime); - if(timeoutLength->QuadPart < 0 && userTimeout && *userTimeout <= 0) - { + if (timeoutLength->QuadPart < 0 && userTimeout && *userTimeout <= 0) { /* Caller has explicitly requested a zero timeout. */ timeoutLength->QuadPart = 0; - } + } - if(timeoutLength->QuadPart < 0) - { + if (timeoutLength->QuadPart < 0) { /* Timeout has already expired. */ return 1; - } - else - { + } else { /* There is some time left. */ return 0; - } } + } } /*--------------------------------------------------------------------------*/ @@ -2215,7 +2009,7 @@ double kwsysProcessTimeToDouble(kwsysProcessTime t) kwsysProcessTime kwsysProcessTimeFromDouble(double d) { kwsysProcessTime t; - t.QuadPart = (LONGLONG)(d*10000000); + t.QuadPart = (LONGLONG)(d * 10000000); return t; } @@ -2226,7 +2020,8 @@ int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2) } /*--------------------------------------------------------------------------*/ -kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2) +kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, + kwsysProcessTime in2) { kwsysProcessTime out; out.QuadPart = in1.QuadPart + in2.QuadPart; @@ -2234,7 +2029,8 @@ kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2) } /*--------------------------------------------------------------------------*/ -kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2) +kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, + kwsysProcessTime in2) { kwsysProcessTime out; out.QuadPart = in1.QuadPart - in2.QuadPart; @@ -2242,71 +2038,93 @@ kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime } /*--------------------------------------------------------------------------*/ -#define KWSYSPE_CASE(type, str) \ - cp->ExitException = kwsysProcess_Exception_##type; \ +#define KWSYSPE_CASE(type, str) \ + cp->ExitException = kwsysProcess_Exception_##type; \ strcpy(cp->ExitExceptionString, str) static void kwsysProcessSetExitException(kwsysProcess* cp, int code) { - switch (code) - { + switch (code) { case STATUS_CONTROL_C_EXIT: - KWSYSPE_CASE(Interrupt, "User interrupt"); break; + KWSYSPE_CASE(Interrupt, "User interrupt"); + break; case STATUS_FLOAT_DENORMAL_OPERAND: - KWSYSPE_CASE(Numerical, "Floating-point exception (denormal operand)"); break; + KWSYSPE_CASE(Numerical, "Floating-point exception (denormal operand)"); + break; case STATUS_FLOAT_DIVIDE_BY_ZERO: - KWSYSPE_CASE(Numerical, "Divide-by-zero"); break; + KWSYSPE_CASE(Numerical, "Divide-by-zero"); + break; case STATUS_FLOAT_INEXACT_RESULT: - KWSYSPE_CASE(Numerical, "Floating-point exception (inexact result)"); break; + KWSYSPE_CASE(Numerical, "Floating-point exception (inexact result)"); + break; case STATUS_FLOAT_INVALID_OPERATION: - KWSYSPE_CASE(Numerical, "Invalid floating-point operation"); break; + KWSYSPE_CASE(Numerical, "Invalid floating-point operation"); + break; case STATUS_FLOAT_OVERFLOW: - KWSYSPE_CASE(Numerical, "Floating-point overflow"); break; + KWSYSPE_CASE(Numerical, "Floating-point overflow"); + break; case STATUS_FLOAT_STACK_CHECK: - KWSYSPE_CASE(Numerical, "Floating-point stack check failed"); break; + KWSYSPE_CASE(Numerical, "Floating-point stack check failed"); + break; case STATUS_FLOAT_UNDERFLOW: - KWSYSPE_CASE(Numerical, "Floating-point underflow"); break; + KWSYSPE_CASE(Numerical, "Floating-point underflow"); + break; #ifdef STATUS_FLOAT_MULTIPLE_FAULTS case STATUS_FLOAT_MULTIPLE_FAULTS: - KWSYSPE_CASE(Numerical, "Floating-point exception (multiple faults)"); break; + KWSYSPE_CASE(Numerical, "Floating-point exception (multiple faults)"); + break; #endif #ifdef STATUS_FLOAT_MULTIPLE_TRAPS case STATUS_FLOAT_MULTIPLE_TRAPS: - KWSYSPE_CASE(Numerical, "Floating-point exception (multiple traps)"); break; + KWSYSPE_CASE(Numerical, "Floating-point exception (multiple traps)"); + break; #endif case STATUS_INTEGER_DIVIDE_BY_ZERO: - KWSYSPE_CASE(Numerical, "Integer divide-by-zero"); break; + KWSYSPE_CASE(Numerical, "Integer divide-by-zero"); + break; case STATUS_INTEGER_OVERFLOW: - KWSYSPE_CASE(Numerical, "Integer overflow"); break; + KWSYSPE_CASE(Numerical, "Integer overflow"); + break; case STATUS_DATATYPE_MISALIGNMENT: - KWSYSPE_CASE(Fault, "Datatype misalignment"); break; + KWSYSPE_CASE(Fault, "Datatype misalignment"); + break; case STATUS_ACCESS_VIOLATION: - KWSYSPE_CASE(Fault, "Access violation"); break; + KWSYSPE_CASE(Fault, "Access violation"); + break; case STATUS_IN_PAGE_ERROR: - KWSYSPE_CASE(Fault, "In-page error"); break; + KWSYSPE_CASE(Fault, "In-page error"); + break; case STATUS_INVALID_HANDLE: - KWSYSPE_CASE(Fault, "Invalid hanlde"); break; + KWSYSPE_CASE(Fault, "Invalid hanlde"); + break; case STATUS_NONCONTINUABLE_EXCEPTION: - KWSYSPE_CASE(Fault, "Noncontinuable exception"); break; + KWSYSPE_CASE(Fault, "Noncontinuable exception"); + break; case STATUS_INVALID_DISPOSITION: - KWSYSPE_CASE(Fault, "Invalid disposition"); break; + KWSYSPE_CASE(Fault, "Invalid disposition"); + break; case STATUS_ARRAY_BOUNDS_EXCEEDED: - KWSYSPE_CASE(Fault, "Array bounds exceeded"); break; + KWSYSPE_CASE(Fault, "Array bounds exceeded"); + break; case STATUS_STACK_OVERFLOW: - KWSYSPE_CASE(Fault, "Stack overflow"); break; + KWSYSPE_CASE(Fault, "Stack overflow"); + break; case STATUS_ILLEGAL_INSTRUCTION: - KWSYSPE_CASE(Illegal, "Illegal instruction"); break; + KWSYSPE_CASE(Illegal, "Illegal instruction"); + break; case STATUS_PRIVILEGED_INSTRUCTION: - KWSYSPE_CASE(Illegal, "Privileged instruction"); break; + KWSYSPE_CASE(Illegal, "Privileged instruction"); + break; case STATUS_NO_MEMORY: default: cp->ExitException = kwsysProcess_Exception_Other; - _snprintf(cp->ExitExceptionString, KWSYSPE_PIPE_BUFFER_SIZE, "Exit code 0x%x\n", code); + _snprintf(cp->ExitExceptionString, KWSYSPE_PIPE_BUFFER_SIZE, + "Exit code 0x%x\n", code); break; - } + } } #undef KWSYSPE_CASE @@ -2338,21 +2156,21 @@ typedef struct _SYSTEM_PROCESS_INFORMATION SYSTEM_PROCESS_INFORMATION; typedef SYSTEM_PROCESS_INFORMATION* PSYSTEM_PROCESS_INFORMATION; struct _SYSTEM_PROCESS_INFORMATION { - ULONG NextEntryDelta; - ULONG ThreadCount; - ULONG Reserved1[6]; - LARGE_INTEGER CreateTime; - LARGE_INTEGER UserTime; - LARGE_INTEGER KernelTime; + ULONG NextEntryDelta; + ULONG ThreadCount; + ULONG Reserved1[6]; + LARGE_INTEGER CreateTime; + LARGE_INTEGER UserTime; + LARGE_INTEGER KernelTime; UNICODE_STRING ProcessName; - KPRIORITY BasePriority; - ULONG ProcessId; - ULONG InheritedFromProcessId; + KPRIORITY BasePriority; + ULONG ProcessId; + ULONG InheritedFromProcessId; }; /*--------------------------------------------------------------------------*/ /* Toolhelp32 API definitions. */ -#define TH32CS_SNAPPROCESS 0x00000002 +#define TH32CS_SNAPPROCESS 0x00000002 #if defined(_WIN64) typedef unsigned __int64 ProcessULONG_PTR; #else @@ -2369,19 +2187,18 @@ struct tagPROCESSENTRY32 DWORD th32ModuleID; DWORD cntThreads; DWORD th32ParentProcessID; - LONG pcPriClassBase; + LONG pcPriClassBase; DWORD dwFlags; char szExeFile[MAX_PATH]; }; /*--------------------------------------------------------------------------*/ /* Windows API function types. */ -typedef HANDLE (WINAPI* CreateToolhelp32SnapshotType)(DWORD, DWORD); -typedef BOOL (WINAPI* Process32FirstType)(HANDLE, LPPROCESSENTRY32); -typedef BOOL (WINAPI* Process32NextType)(HANDLE, LPPROCESSENTRY32); -typedef NTSTATUS (WINAPI* ZwQuerySystemInformationType)(ULONG, PVOID, - ULONG, PULONG); - +typedef HANDLE(WINAPI* CreateToolhelp32SnapshotType)(DWORD, DWORD); +typedef BOOL(WINAPI* Process32FirstType)(HANDLE, LPPROCESSENTRY32); +typedef BOOL(WINAPI* Process32NextType)(HANDLE, LPPROCESSENTRY32); +typedef NTSTATUS(WINAPI* ZwQuerySystemInformationType)(ULONG, PVOID, ULONG, + PULONG); /*--------------------------------------------------------------------------*/ static int kwsysProcess_List__New_NT4(kwsysProcess_List* self); @@ -2423,97 +2240,88 @@ static kwsysProcess_List* kwsysProcess_List_New(void) kwsysProcess_List* self; /* Allocate and initialize the list object. */ - if(!(self = (kwsysProcess_List*)malloc(sizeof(kwsysProcess_List)))) - { + if (!(self = (kwsysProcess_List*)malloc(sizeof(kwsysProcess_List)))) { return 0; - } + } memset(self, 0, sizeof(*self)); /* Select an implementation. */ ZeroMemory(&osv, sizeof(osv)); osv.dwOSVersionInfoSize = sizeof(osv); #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx -# pragma warning (push) -# ifdef __INTEL_COMPILER -# pragma warning (disable:1478) -# else -# pragma warning (disable:4996) -# endif +#pragma warning(push) +#ifdef __INTEL_COMPILER +#pragma warning(disable : 1478) +#else +#pragma warning(disable : 4996) +#endif #endif GetVersionEx(&osv); #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx -# pragma warning (pop) +#pragma warning(pop) #endif - self->NT4 = (osv.dwPlatformId == VER_PLATFORM_WIN32_NT && - osv.dwMajorVersion < 5)? 1:0; + self->NT4 = + (osv.dwPlatformId == VER_PLATFORM_WIN32_NT && osv.dwMajorVersion < 5) ? 1 + : 0; /* Initialize the selected implementation. */ - if(!(self->NT4? - kwsysProcess_List__New_NT4(self) : - kwsysProcess_List__New_Snapshot(self))) - { + if (!(self->NT4 ? kwsysProcess_List__New_NT4(self) + : kwsysProcess_List__New_Snapshot(self))) { kwsysProcess_List_Delete(self); return 0; - } + } /* Update to the current set of processes. */ - if(!kwsysProcess_List_Update(self)) - { + if (!kwsysProcess_List_Update(self)) { kwsysProcess_List_Delete(self); return 0; - } + } return self; } /*--------------------------------------------------------------------------*/ static void kwsysProcess_List_Delete(kwsysProcess_List* self) { - if(self) - { - if(self->NT4) - { + if (self) { + if (self->NT4) { kwsysProcess_List__Delete_NT4(self); - } - else - { + } else { kwsysProcess_List__Delete_Snapshot(self); - } - free(self); } + free(self); + } } /*--------------------------------------------------------------------------*/ static int kwsysProcess_List_Update(kwsysProcess_List* self) { - return self? (self->NT4? - kwsysProcess_List__Update_NT4(self) : - kwsysProcess_List__Update_Snapshot(self)) : 0; + return self ? (self->NT4 ? kwsysProcess_List__Update_NT4(self) + : kwsysProcess_List__Update_Snapshot(self)) + : 0; } /*--------------------------------------------------------------------------*/ static int kwsysProcess_List_GetCurrentProcessId(kwsysProcess_List* self) { - return self? (self->NT4? - kwsysProcess_List__GetProcessId_NT4(self) : - kwsysProcess_List__GetProcessId_Snapshot(self)) : -1; - + return self ? (self->NT4 ? kwsysProcess_List__GetProcessId_NT4(self) + : kwsysProcess_List__GetProcessId_Snapshot(self)) + : -1; } /*--------------------------------------------------------------------------*/ static int kwsysProcess_List_GetCurrentParentId(kwsysProcess_List* self) { - return self? (self->NT4? - kwsysProcess_List__GetParentId_NT4(self) : - kwsysProcess_List__GetParentId_Snapshot(self)) : -1; - + return self ? (self->NT4 ? kwsysProcess_List__GetParentId_NT4(self) + : kwsysProcess_List__GetParentId_Snapshot(self)) + : -1; } /*--------------------------------------------------------------------------*/ static int kwsysProcess_List_NextProcess(kwsysProcess_List* self) { - return (self? (self->NT4? - kwsysProcess_List__Next_NT4(self) : - kwsysProcess_List__Next_Snapshot(self)) : 0); + return (self ? (self->NT4 ? kwsysProcess_List__Next_NT4(self) + : kwsysProcess_List__Next_Snapshot(self)) + : 0); } /*--------------------------------------------------------------------------*/ @@ -2524,100 +2332,85 @@ static int kwsysProcess_List__New_NT4(kwsysProcess_List* self) reference count to the module so we do not need to close the handle. */ HMODULE hNT = GetModuleHandleW(L"ntdll.dll"); - if(hNT) - { + if (hNT) { /* Get pointers to the needed API functions. */ self->P_ZwQuerySystemInformation = - ((ZwQuerySystemInformationType) - GetProcAddress(hNT, "ZwQuerySystemInformation")); - } - if(!self->P_ZwQuerySystemInformation) - { + ((ZwQuerySystemInformationType)GetProcAddress( + hNT, "ZwQuerySystemInformation")); + } + if (!self->P_ZwQuerySystemInformation) { return 0; - } + } /* Allocate an initial process information buffer. */ self->BufferSize = 32768; self->Buffer = (char*)malloc(self->BufferSize); - return self->Buffer? 1:0; + return self->Buffer ? 1 : 0; } /*--------------------------------------------------------------------------*/ static void kwsysProcess_List__Delete_NT4(kwsysProcess_List* self) { /* Free the process information buffer. */ - if(self->Buffer) - { + if (self->Buffer) { free(self->Buffer); - } + } } /*--------------------------------------------------------------------------*/ static int kwsysProcess_List__Update_NT4(kwsysProcess_List* self) { self->CurrentInfo = 0; - for(;;) - { + for (;;) { /* Query number 5 is for system process list. */ NTSTATUS status = self->P_ZwQuerySystemInformation(5, self->Buffer, self->BufferSize, 0); - if(status == STATUS_INFO_LENGTH_MISMATCH) - { + if (status == STATUS_INFO_LENGTH_MISMATCH) { /* The query requires a bigger buffer. */ int newBufferSize = self->BufferSize * 2; char* newBuffer = (char*)malloc(newBufferSize); - if(newBuffer) - { + if (newBuffer) { free(self->Buffer); self->Buffer = newBuffer; self->BufferSize = newBufferSize; - } - else - { + } else { return 0; - } } - else if(status >= 0) - { + } else if (status >= 0) { /* The query succeeded. Initialize traversal of the process list. */ self->CurrentInfo = (PSYSTEM_PROCESS_INFORMATION)self->Buffer; return 1; - } - else - { + } else { /* The query failed. */ return 0; - } } + } } /*--------------------------------------------------------------------------*/ static int kwsysProcess_List__Next_NT4(kwsysProcess_List* self) { - if(self->CurrentInfo) - { - if(self->CurrentInfo->NextEntryDelta > 0) - { - self->CurrentInfo = ((PSYSTEM_PROCESS_INFORMATION) - ((char*)self->CurrentInfo + - self->CurrentInfo->NextEntryDelta)); + if (self->CurrentInfo) { + if (self->CurrentInfo->NextEntryDelta > 0) { + self->CurrentInfo = ((PSYSTEM_PROCESS_INFORMATION)( + (char*)self->CurrentInfo + self->CurrentInfo->NextEntryDelta)); return 1; - } - self->CurrentInfo = 0; } + self->CurrentInfo = 0; + } return 0; } /*--------------------------------------------------------------------------*/ static int kwsysProcess_List__GetProcessId_NT4(kwsysProcess_List* self) { - return self->CurrentInfo? self->CurrentInfo->ProcessId : -1; + return self->CurrentInfo ? self->CurrentInfo->ProcessId : -1; } /*--------------------------------------------------------------------------*/ static int kwsysProcess_List__GetParentId_NT4(kwsysProcess_List* self) { - return self->CurrentInfo? self->CurrentInfo->InheritedFromProcessId : -1; + return self->CurrentInfo ? self->CurrentInfo->InheritedFromProcessId : -1; } /*--------------------------------------------------------------------------*/ @@ -2628,92 +2421,83 @@ static int kwsysProcess_List__New_Snapshot(kwsysProcess_List* self) reference count to the module so we do not need to close the handle. */ HMODULE hKernel = GetModuleHandleW(L"kernel32.dll"); - if(hKernel) - { + if (hKernel) { self->P_CreateToolhelp32Snapshot = - ((CreateToolhelp32SnapshotType) - GetProcAddress(hKernel, "CreateToolhelp32Snapshot")); + ((CreateToolhelp32SnapshotType)GetProcAddress( + hKernel, "CreateToolhelp32Snapshot")); self->P_Process32First = - ((Process32FirstType) - GetProcAddress(hKernel, "Process32First")); + ((Process32FirstType)GetProcAddress(hKernel, "Process32First")); self->P_Process32Next = - ((Process32NextType) - GetProcAddress(hKernel, "Process32Next")); - } - return (self->P_CreateToolhelp32Snapshot && - self->P_Process32First && - self->P_Process32Next)? 1:0; + ((Process32NextType)GetProcAddress(hKernel, "Process32Next")); + } + return (self->P_CreateToolhelp32Snapshot && self->P_Process32First && + self->P_Process32Next) + ? 1 + : 0; } /*--------------------------------------------------------------------------*/ static void kwsysProcess_List__Delete_Snapshot(kwsysProcess_List* self) { - if(self->Snapshot) - { + if (self->Snapshot) { CloseHandle(self->Snapshot); - } + } } /*--------------------------------------------------------------------------*/ static int kwsysProcess_List__Update_Snapshot(kwsysProcess_List* self) { - if(self->Snapshot) - { + if (self->Snapshot) { CloseHandle(self->Snapshot); - } - if(!(self->Snapshot = - self->P_CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0))) - { + } + if (!(self->Snapshot = + self->P_CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0))) { return 0; - } + } ZeroMemory(&self->CurrentEntry, sizeof(self->CurrentEntry)); self->CurrentEntry.dwSize = sizeof(self->CurrentEntry); - if(!self->P_Process32First(self->Snapshot, &self->CurrentEntry)) - { + if (!self->P_Process32First(self->Snapshot, &self->CurrentEntry)) { CloseHandle(self->Snapshot); self->Snapshot = 0; return 0; - } + } return 1; } /*--------------------------------------------------------------------------*/ static int kwsysProcess_List__Next_Snapshot(kwsysProcess_List* self) { - if(self->Snapshot) - { - if(self->P_Process32Next(self->Snapshot, &self->CurrentEntry)) - { + if (self->Snapshot) { + if (self->P_Process32Next(self->Snapshot, &self->CurrentEntry)) { return 1; - } + } CloseHandle(self->Snapshot); self->Snapshot = 0; - } + } return 0; } /*--------------------------------------------------------------------------*/ static int kwsysProcess_List__GetProcessId_Snapshot(kwsysProcess_List* self) { - return self->Snapshot? self->CurrentEntry.th32ProcessID : -1; + return self->Snapshot ? self->CurrentEntry.th32ProcessID : -1; } /*--------------------------------------------------------------------------*/ static int kwsysProcess_List__GetParentId_Snapshot(kwsysProcess_List* self) { - return self->Snapshot? self->CurrentEntry.th32ParentProcessID : -1; + return self->Snapshot ? self->CurrentEntry.th32ParentProcessID : -1; } /*--------------------------------------------------------------------------*/ static void kwsysProcessKill(DWORD pid) { HANDLE h = OpenProcess(PROCESS_TERMINATE, 0, pid); - if(h) - { + if (h) { TerminateProcess(h, 255); WaitForSingleObject(h, INFINITE); CloseHandle(h); - } + } } /*--------------------------------------------------------------------------*/ @@ -2721,18 +2505,15 @@ static void kwsysProcessKillTree(int pid) { kwsysProcess_List* plist = kwsysProcess_List_New(); kwsysProcessKill(pid); - if(plist) - { - do - { - if(kwsysProcess_List_GetCurrentParentId(plist) == pid) - { + if (plist) { + do { + if (kwsysProcess_List_GetCurrentParentId(plist) == pid) { int ppid = kwsysProcess_List_GetCurrentProcessId(plist); kwsysProcessKillTree(ppid); - } - } while(kwsysProcess_List_NextProcess(plist)); + } + } while (kwsysProcess_List_NextProcess(plist)); kwsysProcess_List_Delete(plist); - } + } } /*--------------------------------------------------------------------------*/ @@ -2741,16 +2522,14 @@ static void kwsysProcessDisablePipeThreads(kwsysProcess* cp) int i; /* If data were just reported data, release the pipe's thread. */ - if(cp->CurrentIndex < KWSYSPE_PIPE_COUNT) - { + if (cp->CurrentIndex < KWSYSPE_PIPE_COUNT) { KWSYSPE_DEBUG((stderr, "releasing reader %d\n", cp->CurrentIndex)); ReleaseSemaphore(cp->Pipe[cp->CurrentIndex].Reader.Go, 1, 0); cp->CurrentIndex = KWSYSPE_PIPE_COUNT; - } + } /* Wakeup all reading threads that are not on closed pipes. */ - for(i=0; i < KWSYSPE_PIPE_COUNT; ++i) - { + for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) { /* The wakeup threads will write one byte to the pipe write ends. If there are no data in the pipe then this is enough to wakeup the reading threads. If there are already data in the pipe @@ -2762,16 +2541,14 @@ static void kwsysProcessDisablePipeThreads(kwsysProcess* cp) thread to call WriteFile. If it blocks, that is okay because it will unblock when we close the read end and break the pipe below. */ - if(cp->Pipe[i].Read) - { + if (cp->Pipe[i].Read) { KWSYSPE_DEBUG((stderr, "releasing waker %d\n", i)); ReleaseSemaphore(cp->Pipe[i].Waker.Go, 1, 0); - } } + } /* Tell pipe threads to reset until we run another process. */ - while(cp->PipesLeft > 0) - { + while (cp->PipesLeft > 0) { /* The waking threads will cause all reading threads to report. Wait for the next one and save its index. */ KWSYSPE_DEBUG((stderr, "waiting for reader\n")); @@ -2788,7 +2565,7 @@ static void kwsysProcessDisablePipeThreads(kwsysProcess* cp) /* Tell the reading thread we are done with the data. It will reset immediately because the pipe is closed. */ ReleaseSemaphore(cp->Pipe[cp->CurrentIndex].Reader.Go, 1, 0); - } + } } /*--------------------------------------------------------------------------*/ @@ -2827,18 +2604,16 @@ static kwsysProcessInstances kwsysProcesses; static int kwsysProcessesInitialize(void) { /* Initialize everything if not done already. */ - if(!kwsysProcesses.Initialized) - { + if (!kwsysProcesses.Initialized) { InitializeCriticalSection(&kwsysProcesses.Lock); /* Set up console ctrl handler. */ - if(!SetConsoleCtrlHandler(kwsysCtrlHandler, TRUE)) - { + if (!SetConsoleCtrlHandler(kwsysCtrlHandler, TRUE)) { return 0; - } + } kwsysProcesses.Initialized = 1; - } + } return 1; } @@ -2853,15 +2628,12 @@ static int kwsysTryEnterCreateProcessSection(void) handler are mutually exclusive. */ EnterCriticalSection(&kwsysProcesses.Lock); /* Indicate to the caller if they can create a process. */ - if(kwsysProcesses.Exiting) - { + if (kwsysProcesses.Exiting) { LeaveCriticalSection(&kwsysProcesses.Lock); return 0; - } - else - { + } else { return 1; - } + } } /*--------------------------------------------------------------------------*/ @@ -2880,41 +2652,35 @@ static void kwsysLeaveCreateProcessSection(void) static int kwsysProcessesAdd(HANDLE hProcess, DWORD dwProcessid, int newProcessGroup) { - if(!kwsysProcessesInitialize() || !hProcess || - hProcess == INVALID_HANDLE_VALUE) - { + if (!kwsysProcessesInitialize() || !hProcess || + hProcess == INVALID_HANDLE_VALUE) { return 0; - } + } /* Enter the critical section. */ EnterCriticalSection(&kwsysProcesses.Lock); /* Make sure there is enough space for the new process handle. */ - if(kwsysProcesses.Count == kwsysProcesses.Size) - { + if (kwsysProcesses.Count == kwsysProcesses.Size) { size_t newSize; - kwsysProcessInstance *newArray; + kwsysProcessInstance* newArray; /* Start with enough space for a small number of process handles and double the size each time more is needed. */ - newSize = kwsysProcesses.Size? kwsysProcesses.Size*2 : 4; + newSize = kwsysProcesses.Size ? kwsysProcesses.Size * 2 : 4; /* Try allocating the new block of memory. */ - if(newArray = (kwsysProcessInstance*)malloc( - newSize*sizeof(kwsysProcessInstance))) - { + if (newArray = (kwsysProcessInstance*)malloc( + newSize * sizeof(kwsysProcessInstance))) { /* Copy the old process handles to the new memory. */ - if(kwsysProcesses.Count > 0) - { + if (kwsysProcesses.Count > 0) { memcpy(newArray, kwsysProcesses.Processes, kwsysProcesses.Count * sizeof(kwsysProcessInstance)); - } } - else - { + } else { /* Failed to allocate memory for the new process handle set. */ LeaveCriticalSection(&kwsysProcesses.Lock); return 0; - } + } /* Free original array. */ free(kwsysProcesses.Processes); @@ -2922,7 +2688,7 @@ static int kwsysProcessesAdd(HANDLE hProcess, DWORD dwProcessid, /* Update original structure with new allocation. */ kwsysProcesses.Size = newSize; kwsysProcesses.Processes = newArray; - } + } /* Append the new process information to the set. */ kwsysProcesses.Processes[kwsysProcesses.Count].hProcess = hProcess; @@ -2942,38 +2708,32 @@ static void kwsysProcessesRemove(HANDLE hProcess) { size_t i; - if (!hProcess || hProcess == INVALID_HANDLE_VALUE) - { + if (!hProcess || hProcess == INVALID_HANDLE_VALUE) { return; - } + } EnterCriticalSection(&kwsysProcesses.Lock); /* Find the given process in the set. */ - for(i=0; i < kwsysProcesses.Count; ++i) - { - if(kwsysProcesses.Processes[i].hProcess == hProcess) - { + for (i = 0; i < kwsysProcesses.Count; ++i) { + if (kwsysProcesses.Processes[i].hProcess == hProcess) { break; - } } - if(i < kwsysProcesses.Count) - { + } + if (i < kwsysProcesses.Count) { /* Found it! Remove the process from the set. */ --kwsysProcesses.Count; - for(; i < kwsysProcesses.Count; ++i) - { - kwsysProcesses.Processes[i] = kwsysProcesses.Processes[i+1]; - } + for (; i < kwsysProcesses.Count; ++i) { + kwsysProcesses.Processes[i] = kwsysProcesses.Processes[i + 1]; + } /* If this was the last process, free the array. */ - if(kwsysProcesses.Count == 0) - { + if (kwsysProcesses.Count == 0) { kwsysProcesses.Size = 0; free(kwsysProcesses.Processes); kwsysProcesses.Processes = 0; - } } + } LeaveCriticalSection(&kwsysProcesses.Lock); } @@ -2991,25 +2751,21 @@ static BOOL WINAPI kwsysCtrlHandler(DWORD dwCtrlType) /* If some of our processes were created in a new process group, we must manually interrupt them. They won't otherwise receive a Ctrl+C/Break. */ - for(i=0; i < kwsysProcesses.Count; ++i) - { - if(kwsysProcesses.Processes[i].NewProcessGroup) - { + for (i = 0; i < kwsysProcesses.Count; ++i) { + if (kwsysProcesses.Processes[i].NewProcessGroup) { DWORD groupId = kwsysProcesses.Processes[i].dwProcessId; - if(groupId) - { + if (groupId) { GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, groupId); - } } } + } /* Wait for each child process to exit. This is the key step that prevents us from leaving several orphaned children processes running in the background when the user presses Ctrl+C. */ - for(i=0; i < kwsysProcesses.Count; ++i) - { + for (i = 0; i < kwsysProcesses.Count; ++i) { WaitForSingleObject(kwsysProcesses.Processes[i].hProcess, INFINITE); - } + } /* Leave critical section. */ LeaveCriticalSection(&kwsysProcesses.Lock); @@ -3021,10 +2777,9 @@ static BOOL WINAPI kwsysCtrlHandler(DWORD dwCtrlType) /*--------------------------------------------------------------------------*/ void kwsysProcess_ResetStartTime(kwsysProcess* cp) { - if(!cp) - { + if (!cp) { return; - } + } /* Reset start time. */ cp->StartTime = kwsysProcessTimeGetCurrent(); } |