summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/kwsys/.gitattributes16
-rw-r--r--src/kwsys/CMakeLists.txt20
-rw-r--r--src/kwsys/CONTRIBUTING.rst35
-rw-r--r--src/kwsys/CTestCustom.cmake.in15
-rw-r--r--src/kwsys/EncodingC.c18
-rw-r--r--src/kwsys/Process.h.in138
-rw-r--r--src/kwsys/ProcessUNIX.c707
-rw-r--r--src/kwsys/ProcessWin32.c1103
-rw-r--r--src/kwsys/README.txt2
-rw-r--r--src/kwsys/System.c585
-rw-r--r--src/kwsys/System.h.in98
-rw-r--r--src/kwsys/kwsysPlatformTestsCXX.cxx17
12 files changed, 1395 insertions, 1359 deletions
diff --git a/src/kwsys/.gitattributes b/src/kwsys/.gitattributes
new file mode 100644
index 0000000..248786e
--- /dev/null
+++ b/src/kwsys/.gitattributes
@@ -0,0 +1,16 @@
+.git* export-ignore
+.gitattributes -export-ignore
+
+/GitSetup export-ignore
+/SetupForDevelopment.sh export-ignore eol=lf
+
+/CONTRIBUTING.rst conflict-marker-size=78
+
+*.c whitespace=tab-in-indent,no-lf-at-eof
+*.h whitespace=tab-in-indent,no-lf-at-eof
+*.h.in whitespace=tab-in-indent,no-lf-at-eof
+*.cxx whitespace=tab-in-indent,no-lf-at-eof
+*.hxx whitespace=tab-in-indent,no-lf-at-eof
+*.hxx.in whitespace=tab-in-indent,no-lf-at-eof
+*.txt whitespace=tab-in-indent,no-lf-at-eof
+*.cmake whitespace=tab-in-indent,no-lf-at-eof
diff --git a/src/kwsys/CMakeLists.txt b/src/kwsys/CMakeLists.txt
index 7c1b0b0..9b26553 100644
--- a/src/kwsys/CMakeLists.txt
+++ b/src/kwsys/CMakeLists.txt
@@ -88,6 +88,9 @@ CMAKE_MINIMUM_REQUIRED(VERSION 2.6.3 FATAL_ERROR)
IF(POLICY CMP0025)
CMAKE_POLICY(SET CMP0025 NEW)
ENDIF()
+IF(POLICY CMP0056)
+ CMAKE_POLICY(SET CMP0056 NEW)
+ENDIF()
#-----------------------------------------------------------------------------
# If a namespace is not specified, use "kwsys" and enable testing.
@@ -787,6 +790,15 @@ IF(KWSYS_USE_SystemInformation)
SET_PROPERTY(SOURCE SystemInformation.cxx APPEND PROPERTY
COMPILE_DEFINITIONS KWSYS_BUILD_SHARED=1)
ENDIF()
+
+ IF(UNIX AND NOT CYGWIN)
+ KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_GETLOADAVG
+ "Checking whether CXX compiler has getloadavg" DIRECT)
+ IF(KWSYS_CXX_HAS_GETLOADAVG)
+ SET_PROPERTY(SOURCE SystemInformation.cxx APPEND PROPERTY
+ COMPILE_DEFINITIONS KWSYS_CXX_HAS_GETLOADAVG=1)
+ ENDIF()
+ ENDIF()
ENDIF()
#-----------------------------------------------------------------------------
@@ -1068,7 +1080,7 @@ IF(KWSYS_ENABLE_C AND KWSYS_C_SRCS)
# Apply user-defined target properties to the library.
IF(KWSYS_PROPERTIES_C)
- SET_TARGET_PROPERTIES(${KWSYS_NAMESPACE} PROPERTIES
+ SET_TARGET_PROPERTIES(${KWSYS_NAMESPACE}_c PROPERTIES
${KWSYS_PROPERTIES_C}
)
ENDIF()
@@ -1234,7 +1246,7 @@ IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR)
IF(NOT CYGWIN)
SET(KWSYS_TEST_PROCESS_7 7)
ENDIF()
- FOREACH(n 1 2 3 4 5 6 ${KWSYS_TEST_PROCESS_7})
+ FOREACH(n 1 2 3 4 5 6 ${KWSYS_TEST_PROCESS_7} 9 10)
ADD_TEST(kwsys.testProcess-${n} ${EXEC_DIR}/${KWSYS_NAMESPACE}TestProcess ${n})
SET_PROPERTY(TEST kwsys.testProcess-${n} PROPERTY LABELS ${KWSYS_LABELS_TEST})
SET_TESTS_PROPERTIES(kwsys.testProcess-${n} PROPERTIES TIMEOUT 120)
@@ -1267,6 +1279,10 @@ IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR)
MESSAGE(STATUS "GET_TEST_PROPERTY returned: ${wfv}")
ENDIF()
+ # Set up ctest custom configuration file.
+ CONFIGURE_FILE(${PROJECT_SOURCE_DIR}/CTestCustom.cmake.in
+ ${PROJECT_BINARY_DIR}/CTestCustom.cmake @ONLY)
+
# Suppress known consistent failures on buggy systems.
IF(KWSYS_TEST_BOGUS_FAILURES)
SET_TESTS_PROPERTIES(${KWSYS_TEST_BOGUS_FAILURES} PROPERTIES WILL_FAIL ON)
diff --git a/src/kwsys/CONTRIBUTING.rst b/src/kwsys/CONTRIBUTING.rst
new file mode 100644
index 0000000..960eea4
--- /dev/null
+++ b/src/kwsys/CONTRIBUTING.rst
@@ -0,0 +1,35 @@
+Contributing to KWSys
+*********************
+
+Overview
+========
+
+KWSys is kept in its own Git repository and shared by several projects
+via copies in their source trees. Changes to KWSys should not be made
+directly in a host project, except perhaps in maintenance branches.
+
+Please visit
+
+ http://public.kitware.com/Wiki/KWSys/Git
+
+to contribute changes directly to KWSys upstream. Once changes are
+reviewed, tested, and integrated there then the copies of KWSys within
+dependent projects can be updated to get the changes.
+
+Issues
+======
+
+KWSys has no independent issue tracker. After encountering an issue
+(bug) please try to submit a patch using the above instructions.
+Otherwise please report the issue to the tracker for the project that
+hosts the copy of KWSys in which the problem was found.
+
+License
+=======
+
+We do not require any formal copyright assignment or contributor license
+agreement. Any contributions intentionally sent upstream are presumed
+to be offered under terms of the OSI-approved BSD 3-clause License.
+See `Copyright.txt`_ for details.
+
+.. _`Copyright.txt`: Copyright.txt
diff --git a/src/kwsys/CTestCustom.cmake.in b/src/kwsys/CTestCustom.cmake.in
new file mode 100644
index 0000000..d6f802e
--- /dev/null
+++ b/src/kwsys/CTestCustom.cmake.in
@@ -0,0 +1,15 @@
+# kwsys.testProcess-10 involves sending SIGINT to a child process, which then
+# exits abnormally via a call to _exit(). (On Windows, a call to ExitProcess).
+# Naturally, this results in plenty of memory being "leaked" by this child
+# process - the memory check results are not meaningful in this case.
+#
+# kwsys.testProcess-9 also tests sending SIGINT to a child process. However,
+# normal operation of that test involves the child process timing out, and the
+# host process kills (SIGKILL) it as a result. Since it was SIGKILL'ed, the
+# resulting memory leaks are not logged by valgrind anyway. Therefore, we
+# don't have to exclude it.
+
+set(CTEST_CUSTOM_MEMCHECK_IGNORE
+ ${CTEST_CUSTOM_MEMCHECK_IGNORE}
+ kwsys.testProcess-10
+ )
diff --git a/src/kwsys/EncodingC.c b/src/kwsys/EncodingC.c
index cda78e2..32b9bff 100644
--- a/src/kwsys/EncodingC.c
+++ b/src/kwsys/EncodingC.c
@@ -44,9 +44,12 @@ wchar_t* kwsysEncoding_DupToWide(const char* str)
size_t length = kwsysEncoding_mbstowcs(NULL, str, 0) + 1;
if(length > 0)
{
- ret = malloc((length)*sizeof(wchar_t));
- ret[0] = 0;
- kwsysEncoding_mbstowcs(ret, str, length);
+ ret = (wchar_t*)malloc((length)*sizeof(wchar_t));
+ if(ret)
+ {
+ ret[0] = 0;
+ kwsysEncoding_mbstowcs(ret, str, length);
+ }
}
return ret;
}
@@ -71,9 +74,12 @@ char* kwsysEncoding_DupToNarrow(const wchar_t* str)
size_t length = kwsysEncoding_wcstombs(0, str, 0) + 1;
if(length > 0)
{
- ret = malloc(length);
- ret[0] = 0;
- kwsysEncoding_wcstombs(ret, str, length);
+ ret = (char*)malloc(length);
+ if(ret)
+ {
+ ret[0] = 0;
+ kwsysEncoding_wcstombs(ret, str, length);
+ }
}
return ret;
}
diff --git a/src/kwsys/Process.h.in b/src/kwsys/Process.h.in
index c5995ea..c5ebc97 100644
--- a/src/kwsys/Process.h.in
+++ b/src/kwsys/Process.h.in
@@ -23,57 +23,60 @@
# define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
#endif
#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
-# define kwsysProcess kwsys_ns(Process)
-# define kwsysProcess_s kwsys_ns(Process_s)
-# define kwsysProcess_New kwsys_ns(Process_New)
-# define kwsysProcess_Delete kwsys_ns(Process_Delete)
-# define kwsysProcess_SetCommand kwsys_ns(Process_SetCommand)
-# define kwsysProcess_AddCommand kwsys_ns(Process_AddCommand)
-# define kwsysProcess_SetTimeout kwsys_ns(Process_SetTimeout)
-# define kwsysProcess_SetWorkingDirectory kwsys_ns(Process_SetWorkingDirectory)
-# define kwsysProcess_SetPipeFile kwsys_ns(Process_SetPipeFile)
-# define kwsysProcess_SetPipeNative kwsys_ns(Process_SetPipeNative)
-# define kwsysProcess_SetPipeShared kwsys_ns(Process_SetPipeShared)
-# define kwsysProcess_Option_Detach kwsys_ns(Process_Option_Detach)
-# define kwsysProcess_Option_HideWindow kwsys_ns(Process_Option_HideWindow)
-# define kwsysProcess_Option_Verbatim kwsys_ns(Process_Option_Verbatim)
-# define kwsysProcess_GetOption kwsys_ns(Process_GetOption)
-# define kwsysProcess_SetOption kwsys_ns(Process_SetOption)
-# define kwsysProcess_Option_e kwsys_ns(Process_Option_e)
-# define kwsysProcess_State_Starting kwsys_ns(Process_State_Starting)
-# define kwsysProcess_State_Error kwsys_ns(Process_State_Error)
-# define kwsysProcess_State_Exception kwsys_ns(Process_State_Exception)
-# define kwsysProcess_State_Executing kwsys_ns(Process_State_Executing)
-# define kwsysProcess_State_Exited kwsys_ns(Process_State_Exited)
-# define kwsysProcess_State_Expired kwsys_ns(Process_State_Expired)
-# define kwsysProcess_State_Killed kwsys_ns(Process_State_Killed)
-# define kwsysProcess_State_Disowned kwsys_ns(Process_State_Disowned)
-# define kwsysProcess_GetState kwsys_ns(Process_GetState)
-# define kwsysProcess_State_e kwsys_ns(Process_State_e)
-# define kwsysProcess_Exception_None kwsys_ns(Process_Exception_None)
-# define kwsysProcess_Exception_Fault kwsys_ns(Process_Exception_Fault)
-# define kwsysProcess_Exception_Illegal kwsys_ns(Process_Exception_Illegal)
-# define kwsysProcess_Exception_Interrupt kwsys_ns(Process_Exception_Interrupt)
-# define kwsysProcess_Exception_Numerical kwsys_ns(Process_Exception_Numerical)
-# define kwsysProcess_Exception_Other kwsys_ns(Process_Exception_Other)
-# define kwsysProcess_GetExitException kwsys_ns(Process_GetExitException)
-# define kwsysProcess_Exception_e kwsys_ns(Process_Exception_e)
-# define kwsysProcess_GetExitCode kwsys_ns(Process_GetExitCode)
-# define kwsysProcess_GetExitValue kwsys_ns(Process_GetExitValue)
-# define kwsysProcess_GetErrorString kwsys_ns(Process_GetErrorString)
-# define kwsysProcess_GetExceptionString kwsys_ns(Process_GetExceptionString)
-# define kwsysProcess_Execute kwsys_ns(Process_Execute)
-# define kwsysProcess_Disown kwsys_ns(Process_Disown)
-# define kwsysProcess_WaitForData kwsys_ns(Process_WaitForData)
-# define kwsysProcess_Pipes_e kwsys_ns(Process_Pipes_e)
-# define kwsysProcess_Pipe_None kwsys_ns(Process_Pipe_None)
-# define kwsysProcess_Pipe_STDIN kwsys_ns(Process_Pipe_STDIN)
-# define kwsysProcess_Pipe_STDOUT kwsys_ns(Process_Pipe_STDOUT)
-# define kwsysProcess_Pipe_STDERR kwsys_ns(Process_Pipe_STDERR)
-# define kwsysProcess_Pipe_Timeout kwsys_ns(Process_Pipe_Timeout)
-# define kwsysProcess_Pipe_Handle kwsys_ns(Process_Pipe_Handle)
-# define kwsysProcess_WaitForExit kwsys_ns(Process_WaitForExit)
-# define kwsysProcess_Kill kwsys_ns(Process_Kill)
+# define kwsysProcess kwsys_ns(Process)
+# define kwsysProcess_s kwsys_ns(Process_s)
+# define kwsysProcess_New kwsys_ns(Process_New)
+# define kwsysProcess_Delete kwsys_ns(Process_Delete)
+# define kwsysProcess_SetCommand kwsys_ns(Process_SetCommand)
+# define kwsysProcess_AddCommand kwsys_ns(Process_AddCommand)
+# define kwsysProcess_SetTimeout kwsys_ns(Process_SetTimeout)
+# define kwsysProcess_SetWorkingDirectory kwsys_ns(Process_SetWorkingDirectory)
+# define kwsysProcess_SetPipeFile kwsys_ns(Process_SetPipeFile)
+# define kwsysProcess_SetPipeNative kwsys_ns(Process_SetPipeNative)
+# define kwsysProcess_SetPipeShared kwsys_ns(Process_SetPipeShared)
+# define kwsysProcess_Option_Detach kwsys_ns(Process_Option_Detach)
+# define kwsysProcess_Option_HideWindow kwsys_ns(Process_Option_HideWindow)
+# define kwsysProcess_Option_MergeOutput kwsys_ns(Process_Option_MergeOutput)
+# define kwsysProcess_Option_Verbatim kwsys_ns(Process_Option_Verbatim)
+# define kwsysProcess_Option_CreateProcessGroup kwsys_ns(Process_Option_CreateProcessGroup)
+# define kwsysProcess_GetOption kwsys_ns(Process_GetOption)
+# define kwsysProcess_SetOption kwsys_ns(Process_SetOption)
+# define kwsysProcess_Option_e kwsys_ns(Process_Option_e)
+# define kwsysProcess_State_Starting kwsys_ns(Process_State_Starting)
+# define kwsysProcess_State_Error kwsys_ns(Process_State_Error)
+# define kwsysProcess_State_Exception kwsys_ns(Process_State_Exception)
+# define kwsysProcess_State_Executing kwsys_ns(Process_State_Executing)
+# define kwsysProcess_State_Exited kwsys_ns(Process_State_Exited)
+# define kwsysProcess_State_Expired kwsys_ns(Process_State_Expired)
+# define kwsysProcess_State_Killed kwsys_ns(Process_State_Killed)
+# define kwsysProcess_State_Disowned kwsys_ns(Process_State_Disowned)
+# define kwsysProcess_GetState kwsys_ns(Process_GetState)
+# define kwsysProcess_State_e kwsys_ns(Process_State_e)
+# define kwsysProcess_Exception_None kwsys_ns(Process_Exception_None)
+# define kwsysProcess_Exception_Fault kwsys_ns(Process_Exception_Fault)
+# define kwsysProcess_Exception_Illegal kwsys_ns(Process_Exception_Illegal)
+# define kwsysProcess_Exception_Interrupt kwsys_ns(Process_Exception_Interrupt)
+# define kwsysProcess_Exception_Numerical kwsys_ns(Process_Exception_Numerical)
+# define kwsysProcess_Exception_Other kwsys_ns(Process_Exception_Other)
+# define kwsysProcess_GetExitException kwsys_ns(Process_GetExitException)
+# define kwsysProcess_Exception_e kwsys_ns(Process_Exception_e)
+# define kwsysProcess_GetExitCode kwsys_ns(Process_GetExitCode)
+# define kwsysProcess_GetExitValue kwsys_ns(Process_GetExitValue)
+# define kwsysProcess_GetErrorString kwsys_ns(Process_GetErrorString)
+# define kwsysProcess_GetExceptionString kwsys_ns(Process_GetExceptionString)
+# define kwsysProcess_Execute kwsys_ns(Process_Execute)
+# define kwsysProcess_Disown kwsys_ns(Process_Disown)
+# define kwsysProcess_WaitForData kwsys_ns(Process_WaitForData)
+# define kwsysProcess_Pipes_e kwsys_ns(Process_Pipes_e)
+# define kwsysProcess_Pipe_None kwsys_ns(Process_Pipe_None)
+# define kwsysProcess_Pipe_STDIN kwsys_ns(Process_Pipe_STDIN)
+# define kwsysProcess_Pipe_STDOUT kwsys_ns(Process_Pipe_STDOUT)
+# define kwsysProcess_Pipe_STDERR kwsys_ns(Process_Pipe_STDERR)
+# define kwsysProcess_Pipe_Timeout kwsys_ns(Process_Pipe_Timeout)
+# define kwsysProcess_Pipe_Handle kwsys_ns(Process_Pipe_Handle)
+# define kwsysProcess_WaitForExit kwsys_ns(Process_WaitForExit)
+# define kwsysProcess_Interrupt kwsys_ns(Process_Interrupt)
+# define kwsysProcess_Kill kwsys_ns(Process_Kill)
#endif
#if defined(__cplusplus)
@@ -186,12 +189,27 @@ kwsysEXPORT void kwsysProcess_SetPipeNative(kwsysProcess* cp, int pipe,
* 0 = No (default)
* 1 = Yes
*
+ * kwsysProcess_Option_MergeOutput = Whether to merge stdout/stderr.
+ * No content will be returned as stderr.
+ * Any actual stderr will be on stdout.
+ * 0 = No (default)
+ * 1 = Yes
+ *
* kwsysProcess_Option_Verbatim = Whether SetCommand and AddCommand
* should treat the first argument
* as a verbatim command line
* and ignore the rest of the arguments.
* 0 = No (default)
* 1 = Yes
+ *
+ * kwsysProcess_Option_CreateProcessGroup = Whether to place the process in a
+ * new process group. This is
+ * useful if you want to send Ctrl+C
+ * to the process. On UNIX, also
+ * places the process in a new
+ * session.
+ * 0 = No (default)
+ * 1 = Yes
*/
kwsysEXPORT int kwsysProcess_GetOption(kwsysProcess* cp, int optionId);
kwsysEXPORT void kwsysProcess_SetOption(kwsysProcess* cp, int optionId,
@@ -200,7 +218,9 @@ enum kwsysProcess_Option_e
{
kwsysProcess_Option_HideWindow,
kwsysProcess_Option_Detach,
- kwsysProcess_Option_Verbatim
+ kwsysProcess_Option_MergeOutput,
+ kwsysProcess_Option_Verbatim,
+ kwsysProcess_Option_CreateProcessGroup
};
/**
@@ -355,6 +375,17 @@ enum kwsysProcess_Pipes_e
kwsysEXPORT int kwsysProcess_WaitForExit(kwsysProcess* cp, double* timeout);
/**
+ * Interrupt the process group for the child process that is currently
+ * running by sending it the appropriate operating-system specific signal.
+ * The caller should call WaitForExit after this returns to wait for the
+ * child to terminate.
+ *
+ * WARNING: If you didn't specify kwsysProcess_Option_CreateProcessGroup,
+ * you will interrupt your own process group.
+ */
+kwsysEXPORT void kwsysProcess_Interrupt(kwsysProcess* cp);
+
+/**
* Forcefully terminate the child process that is currently running.
* The caller should call WaitForExit after this returns to wait for
* the child to terminate.
@@ -384,7 +415,9 @@ kwsysEXPORT void kwsysProcess_Kill(kwsysProcess* cp);
# undef kwsysProcess_SetPipeShared
# undef kwsysProcess_Option_Detach
# undef kwsysProcess_Option_HideWindow
+# undef kwsysProcess_Option_MergeOutput
# undef kwsysProcess_Option_Verbatim
+# undef kwsysProcess_Option_CreateProcessGroup
# undef kwsysProcess_GetOption
# undef kwsysProcess_SetOption
# undef kwsysProcess_Option_e
@@ -421,6 +454,7 @@ kwsysEXPORT void kwsysProcess_Kill(kwsysProcess* cp);
# undef kwsysProcess_Pipe_Timeout
# undef kwsysProcess_Pipe_Handle
# undef kwsysProcess_WaitForExit
+# undef kwsysProcess_Interrupt
# undef kwsysProcess_Kill
# endif
#endif
diff --git a/src/kwsys/ProcessUNIX.c b/src/kwsys/ProcessUNIX.c
index ca9d424..6d9b109 100644
--- a/src/kwsys/ProcessUNIX.c
+++ b/src/kwsys/ProcessUNIX.c
@@ -88,7 +88,7 @@ typedef ssize_t kwsysProcess_ssize_t;
typedef int kwsysProcess_ssize_t;
#endif
-#if defined(__BEOS__) && !defined(__ZETA__)
+#if defined(__BEOS__) && !defined(__ZETA__)
/* BeOS 5 doesn't have usleep(), but it has snooze(), which is identical. */
# include <be/kernel/OS.h>
static inline void kwsysProcess_usleep(unsigned int msec)
@@ -151,13 +151,14 @@ typedef struct kwsysProcessCreateInformation_s
} kwsysProcessCreateInformation;
/*--------------------------------------------------------------------------*/
+static void kwsysProcessVolatileFree(volatile void* p);
static int kwsysProcessInitialize(kwsysProcess* cp);
static void kwsysProcessCleanup(kwsysProcess* cp, int error);
static void kwsysProcessCleanupDescriptor(int* pfd);
static void kwsysProcessClosePipes(kwsysProcess* cp);
static int kwsysProcessSetNonBlocking(int fd);
static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
- kwsysProcessCreateInformation* si, int* readEnd);
+ kwsysProcessCreateInformation* si);
static void kwsysProcessDestroy(kwsysProcess* cp);
static int kwsysProcessSetupOutputPipeFile(int* p, const char* name);
static int kwsysProcessSetupOutputPipeNative(int* p, int des[2]);
@@ -197,20 +198,26 @@ struct kwsysProcess_s
{
/* The command lines to execute. */
char*** Commands;
- int NumberOfCommands;
+ volatile int NumberOfCommands;
/* Descriptors for the read ends of the child's output pipes and
the signal pipe. */
int PipeReadEnds[KWSYSPE_PIPE_COUNT];
+ /* Descriptors for the child's ends of the pipes.
+ Used temporarily during process creation. */
+ int PipeChildStd[3];
+
/* Write descriptor for child termination signal pipe. */
int SignalPipe;
/* Buffer for pipe data. */
char PipeBuffer[KWSYSPE_PIPE_BUFFER_SIZE];
- /* Process IDs returned by the calls to fork. */
- pid_t* ForkPIDs;
+ /* Process IDs returned by the calls to fork. Everything is volatile
+ because the signal handler accesses them. You must be very careful
+ when reaping PIDs or modifying this array to avoid race conditions. */
+ volatile pid_t* volatile ForkPIDs;
/* Flag for whether the children were terminated by a faild select. */
int SelectError;
@@ -230,6 +237,12 @@ struct kwsysProcess_s
/* Whether to treat command lines as verbatim. */
int Verbatim;
+ /* Whether to merge stdout/stderr of the child. */
+ int MergeOutput;
+
+ /* Whether to create the process in a new process group. */
+ volatile sig_atomic_t CreateProcessGroup;
+
/* Time at which the child started. Negative for no timeout. */
kwsysProcessTime StartTime;
@@ -250,8 +263,9 @@ struct kwsysProcess_s
/* The number of children still executing. */
int CommandsLeft;
- /* The current status of the child process. */
- int State;
+ /* The current status of the child process. Must be atomic because
+ the signal handler checks this to avoid a race. */
+ volatile sig_atomic_t State;
/* The exceptional behavior that terminated the child process, if
* any. */
@@ -264,7 +278,7 @@ struct kwsysProcess_s
int ExitValue;
/* Whether the process was killed. */
- int Killed;
+ volatile sig_atomic_t Killed;
/* Buffer for error message in case of failure. */
char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE+1];
@@ -547,7 +561,7 @@ int kwsysProcess_SetPipeFile(kwsysProcess* cp, int prPipe, const char* file)
}
if(file)
{
- *pfile = malloc(strlen(file)+1);
+ *pfile = (char*)malloc(strlen(file)+1);
if(!*pfile)
{
return 0;
@@ -640,7 +654,10 @@ int kwsysProcess_GetOption(kwsysProcess* cp, int optionId)
switch(optionId)
{
case kwsysProcess_Option_Detach: return cp->OptionDetach;
+ case kwsysProcess_Option_MergeOutput: return cp->MergeOutput;
case kwsysProcess_Option_Verbatim: return cp->Verbatim;
+ case kwsysProcess_Option_CreateProcessGroup:
+ return cp->CreateProcessGroup;
default: return 0;
}
}
@@ -656,7 +673,10 @@ void kwsysProcess_SetOption(kwsysProcess* cp, int optionId, int value)
switch(optionId)
{
case kwsysProcess_Option_Detach: cp->OptionDetach = 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;
}
}
@@ -717,7 +737,6 @@ const char* kwsysProcess_GetExceptionString(kwsysProcess* cp)
void kwsysProcess_Execute(kwsysProcess* cp)
{
int i;
- kwsysProcessCreateInformation si = {-1, -1, -1, {-1, -1}};
/* Do not execute a second copy simultaneously. */
if(!cp || cp->State == kwsysProcess_State_Executing)
@@ -785,7 +804,50 @@ void kwsysProcess_Execute(kwsysProcess* cp)
}
}
- /* Setup the stderr pipe to be shared by all processes. */
+ /* Setup the stdin pipe for the first process. */
+ if(cp->PipeFileSTDIN)
+ {
+ /* Open a file for the child's stdin to read. */
+ cp->PipeChildStd[0] = open(cp->PipeFileSTDIN, O_RDONLY);
+ if(cp->PipeChildStd[0] < 0)
+ {
+ kwsysProcessCleanup(cp, 1);
+ return;
+ }
+
+ /* Set close-on-exec flag on the pipe's end. */
+ if(fcntl(cp->PipeChildStd[0], F_SETFD, FD_CLOEXEC) < 0)
+ {
+ kwsysProcessCleanup(cp, 1);
+ return;
+ }
+ }
+ else if(cp->PipeSharedSTDIN)
+ {
+ cp->PipeChildStd[0] = 0;
+ }
+ else if(cp->PipeNativeSTDIN[0] >= 0)
+ {
+ cp->PipeChildStd[0] = cp->PipeNativeSTDIN[0];
+
+ /* Set close-on-exec flag on the pipe's ends. The read end will
+ be dup2-ed into the stdin descriptor after the fork but before
+ the exec. */
+ if((fcntl(cp->PipeNativeSTDIN[0], F_SETFD, FD_CLOEXEC) < 0) ||
+ (fcntl(cp->PipeNativeSTDIN[1], F_SETFD, FD_CLOEXEC) < 0))
+ {
+ kwsysProcessCleanup(cp, 1);
+ return;
+ }
+ }
+ else
+ {
+ cp->PipeChildStd[0] = -1;
+ }
+
+ /* Create the output pipe for the last process.
+ We always create this so the pipe can be passed to select even if
+ it will report closed immediately. */
{
/* Create the pipe. */
int p[2];
@@ -796,15 +858,14 @@ void kwsysProcess_Execute(kwsysProcess* cp)
}
/* Store the pipe. */
- cp->PipeReadEnds[KWSYSPE_PIPE_STDERR] = p[0];
- si.StdErr = p[1];
+ cp->PipeReadEnds[KWSYSPE_PIPE_STDOUT] = p[0];
+ cp->PipeChildStd[1] = p[1];
/* Set close-on-exec flag on the pipe's ends. */
if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
(fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
{
kwsysProcessCleanup(cp, 1);
- kwsysProcessCleanupDescriptor(&si.StdErr);
return;
}
@@ -813,41 +874,93 @@ void kwsysProcess_Execute(kwsysProcess* cp)
if(!kwsysProcessSetNonBlocking(p[0]))
{
kwsysProcessCleanup(cp, 1);
- kwsysProcessCleanupDescriptor(&si.StdErr);
return;
}
}
- /* Replace the stderr pipe with a file if requested. In this case
- the select call will report that stderr is closed immediately. */
- if(cp->PipeFileSTDERR)
+ if (cp->PipeFileSTDOUT)
{
- if(!kwsysProcessSetupOutputPipeFile(&si.StdErr, cp->PipeFileSTDERR))
+ /* Use a file for stdout. */
+ if(!kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[1],
+ cp->PipeFileSTDOUT))
{
kwsysProcessCleanup(cp, 1);
- kwsysProcessCleanupDescriptor(&si.StdErr);
return;
}
}
+ else if (cp->PipeSharedSTDOUT)
+ {
+ /* Use the parent stdout. */
+ kwsysProcessCleanupDescriptor(&cp->PipeChildStd[1]);
+ cp->PipeChildStd[1] = 1;
+ }
+ else if (cp->PipeNativeSTDOUT[1] >= 0)
+ {
+ /* Use the given descriptor for stdout. */
+ if(!kwsysProcessSetupOutputPipeNative(&cp->PipeChildStd[1],
+ cp->PipeNativeSTDOUT))
+ {
+ kwsysProcessCleanup(cp, 1);
+ return;
+ }
+ }
+
+ /* Create stderr pipe to be shared by all processes in the pipeline.
+ We always create this so the pipe can be passed to select even if
+ it will report closed immediately. */
+ {
+ /* Create the pipe. */
+ int p[2];
+ if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0)
+ {
+ kwsysProcessCleanup(cp, 1);
+ return;
+ }
+
+ /* Store the pipe. */
+ cp->PipeReadEnds[KWSYSPE_PIPE_STDERR] = p[0];
+ cp->PipeChildStd[2] = p[1];
- /* Replace the stderr pipe with the parent's if requested. In this
- case the select call will report that stderr is closed
- immediately. */
- if(cp->PipeSharedSTDERR)
+ /* Set close-on-exec flag on the pipe's ends. */
+ if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
+ (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
{
- kwsysProcessCleanupDescriptor(&si.StdErr);
- si.StdErr = 2;
+ kwsysProcessCleanup(cp, 1);
+ return;
}
- /* Replace the stderr pipe with the native pipe provided if any. In
- this case the select call will report that stderr is closed
- immediately. */
- if(cp->PipeNativeSTDERR[1] >= 0)
+ /* Set to non-blocking in case select lies, or for the polling
+ implementation. */
+ if(!kwsysProcessSetNonBlocking(p[0]))
{
- if(!kwsysProcessSetupOutputPipeNative(&si.StdErr, cp->PipeNativeSTDERR))
+ kwsysProcessCleanup(cp, 1);
+ return;
+ }
+ }
+
+ if (cp->PipeFileSTDERR)
+ {
+ /* Use a file for stderr. */
+ if(!kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[2],
+ cp->PipeFileSTDERR))
+ {
+ kwsysProcessCleanup(cp, 1);
+ return;
+ }
+ }
+ else if (cp->PipeSharedSTDERR)
+ {
+ /* Use the parent stderr. */
+ kwsysProcessCleanupDescriptor(&cp->PipeChildStd[2]);
+ cp->PipeChildStd[2] = 2;
+ }
+ else if (cp->PipeNativeSTDERR[1] >= 0)
+ {
+ /* Use the given handle for stderr. */
+ if(!kwsysProcessSetupOutputPipeNative(&cp->PipeChildStd[2],
+ cp->PipeNativeSTDERR))
{
kwsysProcessCleanup(cp, 1);
- kwsysProcessCleanupDescriptor(&si.StdErr);
return;
}
}
@@ -859,54 +972,85 @@ void kwsysProcess_Execute(kwsysProcess* cp)
/* Create the pipeline of processes. */
{
- int readEnd = -1;
- int failed = 0;
+ kwsysProcessCreateInformation si = {-1, -1, -1, {-1, -1}};
+ int nextStdIn = cp->PipeChildStd[0];
for(i=0; i < cp->NumberOfCommands; ++i)
{
- if(!kwsysProcessCreate(cp, i, &si, &readEnd))
- {
- failed = 1;
- }
-
- /* Set the output pipe of the last process to be non-blocking in
- case select lies, or for the polling implementation. */
- if(i == (cp->NumberOfCommands-1) && !kwsysProcessSetNonBlocking(readEnd))
+ /* Setup the process's pipes. */
+ si.StdIn = nextStdIn;
+ if (i == cp->NumberOfCommands-1)
{
- failed = 1;
+ nextStdIn = -1;
+ si.StdOut = cp->PipeChildStd[1];
}
-
- if(failed)
+ else
{
- kwsysProcessCleanup(cp, 1);
-
- /* Release resources that may have been allocated for this
- process before an error occurred. */
- kwsysProcessCleanupDescriptor(&readEnd);
- if(si.StdIn != 0)
- {
- kwsysProcessCleanupDescriptor(&si.StdIn);
- }
- if(si.StdOut != 1)
+ /* Create a pipe to sit between the children. */
+ int p[2] = {-1,-1};
+ if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0)
{
- kwsysProcessCleanupDescriptor(&si.StdOut);
+ if (nextStdIn != cp->PipeChildStd[0])
+ {
+ kwsysProcessCleanupDescriptor(&nextStdIn);
+ }
+ kwsysProcessCleanup(cp, 1);
+ return;
}
- if(si.StdErr != 2)
+
+ /* Set close-on-exec flag on the pipe's ends. */
+ if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
+ (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
{
- kwsysProcessCleanupDescriptor(&si.StdErr);
+ close(p[0]);
+ close(p[1]);
+ if (nextStdIn != cp->PipeChildStd[0])
+ {
+ kwsysProcessCleanupDescriptor(&nextStdIn);
+ }
+ kwsysProcessCleanup(cp, 1);
+ return;
}
+ nextStdIn = p[0];
+ si.StdOut = p[1];
+ }
+ si.StdErr = cp->MergeOutput? cp->PipeChildStd[1] : cp->PipeChildStd[2];
+
+ {
+ int res = kwsysProcessCreate(cp, i, &si);
+
+ /* Close our copies of pipes used between children. */
+ if (si.StdIn != cp->PipeChildStd[0])
+ {
+ kwsysProcessCleanupDescriptor(&si.StdIn);
+ }
+ if (si.StdOut != cp->PipeChildStd[1])
+ {
+ kwsysProcessCleanupDescriptor(&si.StdOut);
+ }
+ if (si.StdErr != cp->PipeChildStd[2] && !cp->MergeOutput)
+ {
+ kwsysProcessCleanupDescriptor(&si.StdErr);
+ }
+
+ if(!res)
+ {
kwsysProcessCleanupDescriptor(&si.ErrorPipe[0]);
kwsysProcessCleanupDescriptor(&si.ErrorPipe[1]);
+ if (nextStdIn != cp->PipeChildStd[0])
+ {
+ kwsysProcessCleanupDescriptor(&nextStdIn);
+ }
+ kwsysProcessCleanup(cp, 1);
return;
}
}
- /* Save a handle to the output pipe for the last process. */
- cp->PipeReadEnds[KWSYSPE_PIPE_STDOUT] = readEnd;
+ }
}
- /* The parent process does not need the output pipe write ends. */
- if(si.StdErr != 2)
+ /* The parent process does not need the child's pipe ends. */
+ for (i=0; i < 3; ++i)
{
- kwsysProcessCleanupDescriptor(&si.StdErr);
+ kwsysProcessCleanupDescriptor(&cp->PipeChildStd[i]);
}
/* Restore the working directory. */
@@ -1357,6 +1501,45 @@ int kwsysProcess_WaitForExit(kwsysProcess* cp, double* userTimeout)
}
/*--------------------------------------------------------------------------*/
+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)
+ {
+ return;
+ }
+
+ /* Interrupt the children. */
+ if (cp->CreateProcessGroup)
+ {
+ if(cp->ForkPIDs)
+ {
+ for(i=0; i < cp->NumberOfCommands; ++i)
+ {
+ /* Make sure the PID is still valid. */
+ if(cp->ForkPIDs[i])
+ {
+ /* The user created a process group for this process. The group ID
+ is the process ID for the original process in the group. */
+ kill(-cp->ForkPIDs[i], SIGINT);
+ }
+ }
+ }
+ }
+ else
+ {
+ /* No process group was created. Kill our own process group.
+ NOTE: While one could argue that we could call kill(cp->ForkPIDs[i],
+ SIGINT) as a way to still interrupt the process even though it's not in
+ a special group, this is not an option on Windows. Therefore, we kill
+ the current process group for consistency with Windows. */
+ kill(0, SIGINT);
+ }
+}
+
+/*--------------------------------------------------------------------------*/
void kwsysProcess_Kill(kwsysProcess* cp)
{
int i;
@@ -1406,14 +1589,36 @@ void kwsysProcess_Kill(kwsysProcess* cp)
}
/*--------------------------------------------------------------------------*/
+/* Call the free() function with a pointer to volatile without causing
+ compiler warnings. */
+static void kwsysProcessVolatileFree(volatile void* p)
+{
+ /* clang has made it impossible to free memory that points to volatile
+ without first using special pragmas to disable a warning... */
+#if defined(__clang__)
+# pragma clang diagnostic push
+# pragma clang diagnostic ignored "-Wcast-qual"
+#endif
+ free((void*)p); /* The cast will silence most compilers, but not clang. */
+#if defined(__clang__)
+# pragma clang diagnostic pop
+#endif
+}
+
+/*--------------------------------------------------------------------------*/
/* Initialize a process control structure for kwsysProcess_Execute. */
static int kwsysProcessInitialize(kwsysProcess* cp)
{
int i;
+ volatile pid_t* oldForkPIDs;
for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
{
cp->PipeReadEnds[i] = -1;
}
+ for(i=0; i < 3; ++i)
+ {
+ cp->PipeChildStd[i] = -1;
+ }
cp->SignalPipe = -1;
cp->SelectError = 0;
cp->StartTime.tv_sec = -1;
@@ -1434,16 +1639,21 @@ static int kwsysProcessInitialize(kwsysProcess* cp)
cp->ErrorMessage[0] = 0;
strcpy(cp->ExitExceptionString, "No exception");
- if(cp->ForkPIDs)
+ oldForkPIDs = cp->ForkPIDs;
+ cp->ForkPIDs = (volatile pid_t*)malloc(
+ sizeof(volatile pid_t)*(size_t)(cp->NumberOfCommands));
+ if(oldForkPIDs)
{
- free(cp->ForkPIDs);
+ kwsysProcessVolatileFree(oldForkPIDs);
}
- cp->ForkPIDs = (pid_t*)malloc(sizeof(pid_t)*(size_t)(cp->NumberOfCommands));
if(!cp->ForkPIDs)
{
return 0;
}
- memset(cp->ForkPIDs, 0, sizeof(pid_t)*(size_t)(cp->NumberOfCommands));
+ for(i=0; i < cp->NumberOfCommands; ++i)
+ {
+ cp->ForkPIDs[i] = 0; /* can't use memset due to volatile */
+ }
if(cp->CommandExitCodes)
{
@@ -1468,7 +1678,7 @@ static int kwsysProcessInitialize(kwsysProcess* cp)
cp->RealWorkingDirectoryLength = 4096;
#endif
cp->RealWorkingDirectory =
- malloc((size_t)(cp->RealWorkingDirectoryLength));
+ (char*)malloc((size_t)(cp->RealWorkingDirectoryLength));
if(!cp->RealWorkingDirectory)
{
return 0;
@@ -1534,7 +1744,7 @@ static void kwsysProcessCleanup(kwsysProcess* cp, int error)
/* Free memory. */
if(cp->ForkPIDs)
{
- free(cp->ForkPIDs);
+ kwsysProcessVolatileFree(cp->ForkPIDs);
cp->ForkPIDs = 0;
}
if(cp->RealWorkingDirectory)
@@ -1548,13 +1758,17 @@ static void kwsysProcessCleanup(kwsysProcess* cp, int error)
{
kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
}
+ for(i=0; i < 3; ++i)
+ {
+ kwsysProcessCleanupDescriptor(&cp->PipeChildStd[i]);
+ }
}
/*--------------------------------------------------------------------------*/
/* Close the given file descriptor if it is open. Reset its value to -1. */
static void kwsysProcessCleanupDescriptor(int* pfd)
{
- if(pfd && *pfd >= 0)
+ if(pfd && *pfd > 2)
{
/* Keep trying to close until it is not interrupted by a
* signal. */
@@ -1615,109 +1829,51 @@ int decc$set_child_standard_streams(int fd1, int fd2, int fd3);
/*--------------------------------------------------------------------------*/
static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
- kwsysProcessCreateInformation* si, int* readEnd)
+ kwsysProcessCreateInformation* si)
{
- /* Setup the process's stdin. */
- if(prIndex > 0)
- {
- si->StdIn = *readEnd;
- *readEnd = 0;
- }
- else if(cp->PipeFileSTDIN)
- {
- /* Open a file for the child's stdin to read. */
- si->StdIn = open(cp->PipeFileSTDIN, O_RDONLY);
- if(si->StdIn < 0)
- {
- return 0;
- }
-
- /* Set close-on-exec flag on the pipe's end. */
- if(fcntl(si->StdIn, F_SETFD, FD_CLOEXEC) < 0)
- {
- return 0;
- }
- }
- else if(cp->PipeSharedSTDIN)
- {
- si->StdIn = 0;
- }
- else if(cp->PipeNativeSTDIN[0] >= 0)
- {
- si->StdIn = cp->PipeNativeSTDIN[0];
+ sigset_t mask, old_mask;
+ int pgidPipe[2];
+ char tmp;
+ ssize_t readRes;
- /* Set close-on-exec flag on the pipe's ends. The read end will
- be dup2-ed into the stdin descriptor after the fork but before
- the exec. */
- if((fcntl(cp->PipeNativeSTDIN[0], F_SETFD, FD_CLOEXEC) < 0) ||
- (fcntl(cp->PipeNativeSTDIN[1], F_SETFD, FD_CLOEXEC) < 0))
- {
- return 0;
- }
- }
- else
- {
- si->StdIn = -1;
- }
-
- /* Setup the process's stdout. */
- {
- /* Create the pipe. */
- int p[2];
- if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0)
+ /* Create the error reporting pipe. */
+ if(pipe(si->ErrorPipe) < 0)
{
return 0;
}
- *readEnd = p[0];
- si->StdOut = p[1];
- /* Set close-on-exec flag on the pipe's ends. */
- if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
- (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
+ /* Create a pipe for detecting that the child process has created a process
+ group and session. */
+ if(pipe(pgidPipe) < 0)
{
+ kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
+ kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
return 0;
}
- }
- /* Replace the stdout pipe with a file if requested. In this case
- the select call will report that stdout is closed immediately. */
- if(prIndex == cp->NumberOfCommands-1 && cp->PipeFileSTDOUT)
- {
- if(!kwsysProcessSetupOutputPipeFile(&si->StdOut, cp->PipeFileSTDOUT))
- {
- return 0;
- }
- }
-
- /* Replace the stdout pipe with the parent's if requested. In this
- case the select call will report that stderr is closed
- immediately. */
- if(prIndex == cp->NumberOfCommands-1 && cp->PipeSharedSTDOUT)
- {
- kwsysProcessCleanupDescriptor(&si->StdOut);
- si->StdOut = 1;
- }
-
- /* Replace the stdout pipe with the native pipe provided if any. In
- this case the select call will report that stdout is closed
- immediately. */
- if(prIndex == cp->NumberOfCommands-1 && cp->PipeNativeSTDOUT[1] >= 0)
- {
- if(!kwsysProcessSetupOutputPipeNative(&si->StdOut, cp->PipeNativeSTDOUT))
- {
- return 0;
- }
- }
-
- /* Create the error reporting pipe. */
- if(pipe(si->ErrorPipe) < 0)
+ /* Set close-on-exec flag on the pipe's write end. */
+ if(fcntl(si->ErrorPipe[1], F_SETFD, FD_CLOEXEC) < 0 ||
+ fcntl(pgidPipe[1], F_SETFD, FD_CLOEXEC) < 0)
{
+ kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
+ kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
+ kwsysProcessCleanupDescriptor(&pgidPipe[0]);
+ kwsysProcessCleanupDescriptor(&pgidPipe[1]);
return 0;
}
- /* Set close-on-exec flag on the error pipe's write end. */
- if(fcntl(si->ErrorPipe[1], F_SETFD, FD_CLOEXEC) < 0)
+ /* Block SIGINT / SIGTERM while we start. The purpose is so that our signal
+ handler doesn't get called from the child process after the fork and
+ before the exec, and subsequently start kill()'ing PIDs from ForkPIDs. */
+ sigemptyset(&mask);
+ sigaddset(&mask, SIGINT);
+ sigaddset(&mask, SIGTERM);
+ if(sigprocmask(SIG_BLOCK, &mask, &old_mask) < 0)
{
+ kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
+ kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
+ kwsysProcessCleanupDescriptor(&pgidPipe[0]);
+ kwsysProcessCleanupDescriptor(&pgidPipe[1]);
return 0;
}
@@ -1725,13 +1881,19 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
#if defined(__VMS)
/* VMS needs vfork and execvp to be in the same function because
they use setjmp/longjmp to run the child startup code in the
- parent! TODO: OptionDetach. */
+ parent! TODO: OptionDetach. Also
+ TODO: CreateProcessGroup. */
cp->ForkPIDs[prIndex] = vfork();
#else
cp->ForkPIDs[prIndex] = kwsysProcessFork(cp, si);
#endif
if(cp->ForkPIDs[prIndex] < 0)
{
+ sigprocmask(SIG_SETMASK, &old_mask, 0);
+ kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
+ kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
+ kwsysProcessCleanupDescriptor(&pgidPipe[0]);
+ kwsysProcessCleanupDescriptor(&pgidPipe[1]);
return 0;
}
@@ -1741,8 +1903,10 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
/* Specify standard pipes for child process. */
decc$set_child_standard_streams(si->StdIn, si->StdOut, si->StdErr);
#else
- /* Close the read end of the error reporting pipe. */
+ /* Close the read end of the error reporting / process group
+ setup pipe. */
close(si->ErrorPipe[0]);
+ close(pgidPipe[0]);
/* Setup the stdin, stdout, and stderr pipes. */
if(si->StdIn > 0)
@@ -1770,11 +1934,25 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
/* Restore all default signal handlers. */
kwsysProcessRestoreDefaultSignalHandlers();
+
+ /* Now that we have restored default signal handling and created the
+ process group, restore mask. */
+ sigprocmask(SIG_SETMASK, &old_mask, 0);
+
+ /* Create new process group. We use setsid instead of setpgid to avoid
+ the child getting hung up on signals like SIGTTOU. (In the real world,
+ this has been observed where "git svn" ends up calling the "resize"
+ program which opens /dev/tty. */
+ if(cp->CreateProcessGroup && setsid() < 0)
+ {
+ kwsysProcessChildErrorExit(si->ErrorPipe[1]);
+ }
#endif
/* Execute the real process. If successful, this does not return. */
execvp(cp->Commands[prIndex][0], cp->Commands[prIndex]);
/* TODO: What does VMS do if the child fails to start? */
+ /* TODO: On VMS, how do we put the process in a new group? */
/* Failure. Report error to parent and terminate. */
kwsysProcessChildErrorExit(si->ErrorPipe[1]);
@@ -1785,12 +1963,34 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
decc$set_child_standard_streams(0, 1, 2);
#endif
+ /* We are done with the error reporting pipe and process group setup pipe
+ write end. */
+ kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
+ kwsysProcessCleanupDescriptor(&pgidPipe[1]);
+
+ /* Make sure the child is in the process group before we proceed. This
+ avoids race conditions with calls to the kill function that we make for
+ signalling process groups. */
+ while((readRes = read(pgidPipe[0], &tmp, 1)) > 0);
+ if(readRes < 0)
+ {
+ sigprocmask(SIG_SETMASK, &old_mask, 0);
+ kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
+ kwsysProcessCleanupDescriptor(&pgidPipe[0]);
+ return 0;
+ }
+ kwsysProcessCleanupDescriptor(&pgidPipe[0]);
+
+ /* Unmask signals. */
+ if(sigprocmask(SIG_SETMASK, &old_mask, 0) < 0)
+ {
+ kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
+ return 0;
+ }
+
/* A child has been created. */
++cp->CommandsLeft;
- /* We are done with the error reporting pipe write end. */
- kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
-
/* Block until the child's exec call succeeds and closes the error
pipe or writes data to the pipe to report an error. */
{
@@ -1819,19 +2019,6 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
}
}
- /* Successfully created this child process. */
- if(prIndex > 0 || si->StdIn > 0)
- {
- /* The parent process does not need the input pipe read end. */
- kwsysProcessCleanupDescriptor(&si->StdIn);
- }
-
- /* The parent process does not need the output pipe write ends. */
- if(si->StdOut != 1)
- {
- kwsysProcessCleanupDescriptor(&si->StdOut);
- }
-
return 1;
}
@@ -1841,6 +2028,17 @@ static void kwsysProcessDestroy(kwsysProcess* cp)
/* A child process has terminated. Reap it if it is one handled by
this object. */
int i;
+ /* Temporarily disable signals that access ForkPIDs. We don't want them to
+ read a reaped PID, and writes to ForkPIDs are not atomic. */
+ sigset_t mask, old_mask;
+ sigemptyset(&mask);
+ sigaddset(&mask, SIGINT);
+ sigaddset(&mask, SIGTERM);
+ if(sigprocmask(SIG_BLOCK, &mask, &old_mask) < 0)
+ {
+ return;
+ }
+
for(i=0; i < cp->NumberOfCommands; ++i)
{
if(cp->ForkPIDs[i])
@@ -1874,6 +2072,9 @@ static void kwsysProcessDestroy(kwsysProcess* cp)
}
}
}
+
+ /* Re-enable signals. */
+ sigprocmask(SIG_SETMASK, &old_mask, 0);
}
/*--------------------------------------------------------------------------*/
@@ -1902,7 +2103,7 @@ static int kwsysProcessSetupOutputPipeFile(int* p, const char* name)
/* Assign the replacement descriptor. */
*p = fout;
- return 1;
+ return 1;
}
/*--------------------------------------------------------------------------*/
@@ -2546,19 +2747,23 @@ typedef struct kwsysProcessInstances_s
} kwsysProcessInstances;
static kwsysProcessInstances kwsysProcesses;
-/* The old SIGCHLD handler. */
+/* The old SIGCHLD / SIGINT / SIGTERM handlers. */
static struct sigaction kwsysProcessesOldSigChldAction;
+static struct sigaction kwsysProcessesOldSigIntAction;
+static struct sigaction kwsysProcessesOldSigTermAction;
/*--------------------------------------------------------------------------*/
static void kwsysProcessesUpdate(kwsysProcessInstances* newProcesses)
{
- /* Block SIGCHLD while we update the set of pipes to check.
+ /* Block signals while we update the set of pipes to check.
TODO: sigprocmask is undefined for threaded apps. See
pthread_sigmask. */
sigset_t newset;
sigset_t oldset;
sigemptyset(&newset);
sigaddset(&newset, SIGCHLD);
+ sigaddset(&newset, SIGINT);
+ sigaddset(&newset, SIGTERM);
sigprocmask(SIG_BLOCK, &newset, &oldset);
/* Store the new set in that seen by the signal handler. */
@@ -2650,21 +2855,36 @@ static int kwsysProcessesAdd(kwsysProcess* cp)
{
/* Install our handler for SIGCHLD. Repeat call until it is not
interrupted. */
- struct sigaction newSigChldAction;
- memset(&newSigChldAction, 0, sizeof(struct sigaction));
+ struct sigaction newSigAction;
+ memset(&newSigAction, 0, sizeof(struct sigaction));
#if KWSYSPE_USE_SIGINFO
- newSigChldAction.sa_sigaction = kwsysProcessesSignalHandler;
- newSigChldAction.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
+ newSigAction.sa_sigaction = kwsysProcessesSignalHandler;
+ newSigAction.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
# ifdef SA_RESTART
- newSigChldAction.sa_flags |= SA_RESTART;
+ newSigAction.sa_flags |= SA_RESTART;
# endif
#else
- newSigChldAction.sa_handler = kwsysProcessesSignalHandler;
- newSigChldAction.sa_flags = SA_NOCLDSTOP;
+ newSigAction.sa_handler = kwsysProcessesSignalHandler;
+ newSigAction.sa_flags = SA_NOCLDSTOP;
#endif
- while((sigaction(SIGCHLD, &newSigChldAction,
+ sigemptyset(&newSigAction.sa_mask);
+ while((sigaction(SIGCHLD, &newSigAction,
&kwsysProcessesOldSigChldAction) < 0) &&
(errno == EINTR));
+
+ /* Install our handler for SIGINT / SIGTERM. Repeat call until
+ it is not interrupted. */
+ sigemptyset(&newSigAction.sa_mask);
+ sigaddset(&newSigAction.sa_mask, SIGTERM);
+ while((sigaction(SIGINT, &newSigAction,
+ &kwsysProcessesOldSigIntAction) < 0) &&
+ (errno == EINTR));
+
+ sigemptyset(&newSigAction.sa_mask);
+ sigaddset(&newSigAction.sa_mask, SIGINT);
+ while((sigaction(SIGTERM, &newSigAction,
+ &kwsysProcessesOldSigIntAction) < 0) &&
+ (errno == EINTR));
}
}
@@ -2698,10 +2918,14 @@ static void kwsysProcessesRemove(kwsysProcess* cp)
/* If this was the last process, disable the signal handler. */
if(newProcesses.Count == 0)
{
- /* Restore the SIGCHLD handler. Repeat call until it is not
+ /* Restore the signal handlers. Repeat call until it is not
interrupted. */
while((sigaction(SIGCHLD, &kwsysProcessesOldSigChldAction, 0) < 0) &&
(errno == EINTR));
+ while((sigaction(SIGINT, &kwsysProcessesOldSigIntAction, 0) < 0) &&
+ (errno == EINTR));
+ while((sigaction(SIGTERM, &kwsysProcessesOldSigTermAction, 0) < 0) &&
+ (errno == EINTR));
/* Free the table of process pointers since it is now empty.
This is safe because the signal handler has been removed. */
@@ -2727,39 +2951,108 @@ static void kwsysProcessesSignalHandler(int signum
#endif
)
{
- (void)signum;
+ int i, j, procStatus, old_errno = errno;
#if KWSYSPE_USE_SIGINFO
(void)info;
(void)ucontext;
#endif
/* Signal all process objects that a child has terminated. */
- {
- int i;
- for(i=0; i < kwsysProcesses.Count; ++i)
+ switch(signum)
{
- /* Set the pipe in a signalled state. */
- char buf = 1;
- kwsysProcess* cp = kwsysProcesses.Processes[i];
- kwsysProcess_ssize_t status=
- read(cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL], &buf, 1);
- (void)status;
- status=write(cp->SignalPipe, &buf, 1);
- (void)status;
+ case SIGCHLD:
+ for(i=0; i < kwsysProcesses.Count; ++i)
+ {
+ /* Set the pipe in a signalled state. */
+ char buf = 1;
+ kwsysProcess* cp = kwsysProcesses.Processes[i];
+ kwsysProcess_ssize_t pipeStatus=
+ read(cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL], &buf, 1);
+ (void)pipeStatus;
+ pipeStatus=write(cp->SignalPipe, &buf, 1);
+ (void)pipeStatus;
+ }
+ break;
+ case SIGINT:
+ case SIGTERM:
+ /* Signal child processes that are running in new process groups. */
+ for(i=0; i < kwsysProcesses.Count; ++i)
+ {
+ kwsysProcess* cp = kwsysProcesses.Processes[i];
+ /* Check Killed to avoid data race condition when killing.
+ Check State to avoid data race condition in kwsysProcessCleanup
+ when there is an error (it leaves a reaped PID). */
+ if(cp->CreateProcessGroup && !cp->Killed &&
+ cp->State != kwsysProcess_State_Error && cp->ForkPIDs)
+ {
+ for(j=0; j < cp->NumberOfCommands; ++j)
+ {
+ /* Make sure the PID is still valid. */
+ if(cp->ForkPIDs[j])
+ {
+ /* The user created a process group for this process. The group ID
+ is the process ID for the original process in the group. */
+ kill(-cp->ForkPIDs[j], SIGINT);
+ }
+ }
+ }
+ }
+
+ /* Wait for all processes to terminate. */
+ while(wait(&procStatus) >= 0 || errno != ECHILD)
+ {
+ }
+
+ /* Terminate the process, which is now in an inconsistent state
+ because we reaped all the PIDs that it may have been reaping
+ or may have reaped in the future. Reraise the signal so that
+ the proper exit code is returned. */
+ {
+ /* Install default signal handler. */
+ struct sigaction defSigAction;
+ sigset_t unblockSet;
+ memset(&defSigAction, 0, sizeof(defSigAction));
+ defSigAction.sa_handler = SIG_DFL;
+ sigemptyset(&defSigAction.sa_mask);
+ while((sigaction(signum, &defSigAction, 0) < 0) &&
+ (errno == EINTR));
+ /* Unmask the signal. */
+ sigemptyset(&unblockSet);
+ sigaddset(&unblockSet, signum);
+ sigprocmask(SIG_UNBLOCK, &unblockSet, 0);
+ /* Raise the signal again. */
+ raise(signum);
+ /* We shouldn't get here... but if we do... */
+ _exit(1);
+ }
+ /* break omitted to silence unreachable code clang compiler warning. */
}
- }
#if !KWSYSPE_USE_SIGINFO
- /* Re-Install our handler for SIGCHLD. Repeat call until it is not
- interrupted. */
+ /* Re-Install our handler. Repeat call until it is not interrupted. */
{
- struct sigaction newSigChldAction;
- memset(&newSigChldAction, 0, sizeof(struct sigaction));
+ struct sigaction newSigAction;
+ struct sigaction &oldSigAction;
+ memset(&newSigAction, 0, sizeof(struct sigaction));
newSigChldAction.sa_handler = kwsysProcessesSignalHandler;
newSigChldAction.sa_flags = SA_NOCLDSTOP;
- while((sigaction(SIGCHLD, &newSigChldAction,
- &kwsysProcessesOldSigChldAction) < 0) &&
+ sigemptyset(&newSigAction.sa_mask);
+ switch(signum)
+ {
+ case SIGCHLD: oldSigAction = &kwsysProcessesOldSigChldAction; break;
+ case SIGINT:
+ sigaddset(&newSigAction.sa_mask, SIGTERM);
+ oldSigAction = &kwsysProcessesOldSigIntAction; break;
+ case SIGTERM:
+ sigaddset(&newSigAction.sa_mask, SIGINT);
+ oldSigAction = &kwsysProcessesOldSigTermAction; break;
+ default: return 0;
+ }
+ while((sigaction(signum, &newSigAction,
+ oldSigAction) < 0) &&
(errno == EINTR));
}
#endif
+
+ errno = old_errno;
}
diff --git a/src/kwsys/ProcessWin32.c b/src/kwsys/ProcessWin32.c
index ef71f26..1f8749f 100644
--- a/src/kwsys/ProcessWin32.c
+++ b/src/kwsys/ProcessWin32.c
@@ -11,14 +11,12 @@
============================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Process.h)
-#include KWSYS_HEADER(System.h)
#include KWSYS_HEADER(Encoding.h)
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
# include "Process.h.in"
-# include "System.h.in"
# include "Encoding_c.h.in"
#endif
@@ -94,6 +92,11 @@ typedef struct kwsysProcessCreateInformation_s
{
/* Windows child startup control data. */
STARTUPINFOW StartupInfo;
+
+ /* Original handles before making inherited duplicates. */
+ HANDLE hStdInput;
+ HANDLE hStdOutput;
+ HANDLE hStdError;
} kwsysProcessCreateInformation;
@@ -106,23 +109,16 @@ static DWORD WINAPI kwsysProcessPipeThreadWake(LPVOID ptd);
static void kwsysProcessPipeThreadWakePipe(kwsysProcess* cp,
kwsysProcessPipeData* td);
static int kwsysProcessInitialize(kwsysProcess* cp);
-static int kwsysProcessCreate(kwsysProcess* cp, int index,
- kwsysProcessCreateInformation* si,
- PHANDLE readEnd);
+static DWORD kwsysProcessCreate(kwsysProcess* cp, int index,
+ kwsysProcessCreateInformation* si);
static void kwsysProcessDestroy(kwsysProcess* cp, int event);
-static int kwsysProcessSetupOutputPipeFile(PHANDLE handle, const char* name);
-static int kwsysProcessSetupSharedPipe(DWORD nStdHandle, PHANDLE handle);
-static int kwsysProcessSetupPipeNative(PHANDLE handle, HANDLE p[2],
- int isWrite);
+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);
-static void kwsysProcessCleanupHandleSafe(PHANDLE h, DWORD nStdHandle);
-static void kwsysProcessCleanup(kwsysProcess* cp, int error);
+static void kwsysProcessCleanup(kwsysProcess* cp, DWORD error);
static void kwsysProcessCleanErrorMessage(kwsysProcess* cp);
-static int kwsysProcessComputeCommandLength(kwsysProcess* cp,
- char const* const* command);
-static void kwsysProcessComputeCommandLine(kwsysProcess* cp,
- char const* const* command,
- char* cmd);
static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
kwsysProcessTime* timeoutTime);
static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
@@ -138,6 +134,13 @@ static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProc
static void kwsysProcessSetExitException(kwsysProcess* cp, int code);
static void kwsysProcessKillTree(int pid);
static void kwsysProcessDisablePipeThreads(kwsysProcess* cp);
+static int kwsysProcessesInitialize(void);
+static int kwsysTryEnterCreateProcessSection(void);
+static void kwsysLeaveCreateProcessSection(void);
+static int kwsysProcessesAdd(HANDLE hProcess, DWORD dwProcessId,
+ int newProcessGroup);
+static void kwsysProcessesRemove(HANDLE hProcess);
+static BOOL WINAPI kwsysCtrlHandler(DWORD dwCtrlType);
/*--------------------------------------------------------------------------*/
/* A structure containing synchronization data for each thread. */
@@ -224,6 +227,12 @@ struct kwsysProcess_s
/* Whether to treat command lines as verbatim. */
int Verbatim;
+ /* Whether to merge stdout/stderr of the child. */
+ int MergeOutput;
+
+ /* Whether to create the process in a new process group. */
+ int CreateProcessGroup;
+
/* Mutex to protect the shared index used by threads to report data. */
HANDLE SharedIndexMutex;
@@ -306,6 +315,10 @@ struct kwsysProcess_s
/* Real working directory of our own process. */
DWORD RealWorkingDirectoryLength;
wchar_t* RealWorkingDirectory;
+
+ /* Own handles for the child's ends of the pipes in the parent process.
+ Used temporarily during process creation. */
+ HANDLE PipeChildStd[3];
};
/*--------------------------------------------------------------------------*/
@@ -319,6 +332,16 @@ kwsysProcess* kwsysProcess_New(void)
/* Windows version number data. */
OSVERSIONINFO osv;
+ /* Initialize list of processes before we get any farther. It's especially
+ important that the console Ctrl handler be added BEFORE starting the
+ 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())
+ {
+ return 0;
+ }
+
/* Allocate a process control structure. */
cp = (kwsysProcess*)malloc(sizeof(kwsysProcess));
if(!cp)
@@ -340,7 +363,11 @@ kwsysProcess* kwsysProcess_New(void)
osv.dwOSVersionInfoSize = sizeof(osv);
#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
# pragma warning (push)
-# pragma warning (disable:4996)
+# ifdef __INTEL_COMPILER
+# pragma warning (disable:1478)
+# else
+# pragma warning (disable:4996)
+# endif
#endif
GetVersionEx(&osv);
#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
@@ -442,6 +469,10 @@ kwsysProcess* kwsysProcess_New(void)
return 0;
}
}
+ for(i=0; i < 3; ++i)
+ {
+ cp->PipeChildStd[i] = INVALID_HANDLE_VALUE;
+ }
return cp;
}
@@ -585,37 +616,69 @@ int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
}
}
- /* We need to construct a single string representing the command
- and its arguments. We will surround each argument containing
- spaces with double-quotes. Inside a double-quoted argument, we
- need to escape double-quotes and all backslashes before them.
- We also need to escape backslashes at the end of an argument
- because they come before the closing double-quote for the
- argument. */
- {
- /* First determine the length of the final string. */
- int length = kwsysProcessComputeCommandLength(cp, command);
-
- /* Allocate enough space for the command. We do not need an extra
- byte for the terminating null because we allocated a space for
- the first argument that we will not use. */
- char* new_cmd = malloc(length);
- if(!new_cmd)
+ if (cp->Verbatim)
{
- /* Out of memory. */
+ /* Copy the verbatim command line into the buffer. */
+ newCommands[cp->NumberOfCommands] = kwsysEncoding_DupToWide(*command);
+ }
+ 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)
+ {
+ 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 == '\\')
+ {
+ ++slashes;
+ }
+ else
+ {
+ if (*c == '"')
+ {
+ // Add n+1 backslashes to total 2n+1 before internal '"'.
+ while(slashes-- >= 0 && out != end) { *out++ = '\\'; }
+ }
+ slashes = 0;
+ }
+ 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++ = '"'; }
+ }
+ }
+ if(out != end)
+ {
+ *out = '\0';
+ newCommands[cp->NumberOfCommands] = kwsysEncoding_DupToWide(buffer);
+ }
+ else
+ {
+ newCommands[cp->NumberOfCommands] = 0;
+ }
+ }
+ if (!newCommands[cp->NumberOfCommands])
+ {
+ /* Out of memory or command line too long. */
free(newCommands);
return 0;
}
- /* Construct the command line in the allocated buffer. */
- kwsysProcessComputeCommandLine(cp, command,
- new_cmd);
-
- newCommands[cp->NumberOfCommands] = kwsysEncoding_DupToWide(new_cmd);
- free(new_cmd);
- }
-
-
/* Save the new array of commands. */
free(cp->Commands);
cp->Commands = newCommands;
@@ -792,7 +855,10 @@ int kwsysProcess_GetOption(kwsysProcess* cp, int 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;
}
}
@@ -809,7 +875,10 @@ void kwsysProcess_SetOption(kwsysProcess* cp, int optionId, int value)
{
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;
}
}
@@ -871,9 +940,6 @@ void kwsysProcess_Execute(kwsysProcess* cp)
{
int i;
- /* Child startup control data. */
- kwsysProcessCreateInformation si;
-
/* Do not execute a second time. */
if(!cp || cp->State == kwsysProcess_State_Executing)
{
@@ -904,123 +970,222 @@ void kwsysProcess_Execute(kwsysProcess* cp)
if(!GetCurrentDirectoryW(cp->RealWorkingDirectoryLength,
cp->RealWorkingDirectory))
{
- kwsysProcessCleanup(cp, 1);
+ kwsysProcessCleanup(cp, GetLastError());
return;
}
SetCurrentDirectoryW(cp->WorkingDirectory);
}
- /* 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;
- /* Create stderr pipe to be shared by all processes in the pipeline.
- Neither end is directly inherited. */
- if(!CreatePipe(&cp->Pipe[KWSYSPE_PIPE_STDERR].Read,
- &cp->Pipe[KWSYSPE_PIPE_STDERR].Write, 0, 0))
+ /* Setup the stdin pipe for the first process. */
+ if(cp->PipeFileSTDIN)
{
- kwsysProcessCleanup(cp, 1);
- return;
+ /* 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);
+ error = GetLastError(); /* Check now in case free changes this. */
+ free(wstdin);
+ if(cp->PipeChildStd[0] == INVALID_HANDLE_VALUE)
+ {
+ kwsysProcessCleanup(cp, error);
+ return;
+ }
+ }
+ else if(cp->PipeSharedSTDIN)
+ {
+ /* Share this process's stdin with the child. */
+ kwsysProcessSetupSharedPipe(STD_INPUT_HANDLE, &cp->PipeChildStd[0]);
+ }
+ else if(cp->PipeNativeSTDIN[0])
+ {
+ /* Use the provided native pipe. */
+ kwsysProcessSetupPipeNative(cp->PipeNativeSTDIN[0], &cp->PipeChildStd[0]);
+ }
+ else
+ {
+ /* Explicitly give the child no stdin. */
+ cp->PipeChildStd[0] = INVALID_HANDLE_VALUE;
}
- /* Create an inherited duplicate of the write end, but do not
- close the non-inherited version. We need to keep it open
- to use in waking up the pipe threads. */
- if(!DuplicateHandle(GetCurrentProcess(), cp->Pipe[KWSYSPE_PIPE_STDERR].Write,
- GetCurrentProcess(), &si.StartupInfo.hStdError,
- 0, TRUE, DUPLICATE_SAME_ACCESS))
+ /* 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))
{
- kwsysProcessCleanup(cp, 1);
- kwsysProcessCleanupHandle(&si.StartupInfo.hStdError);
+ kwsysProcessCleanup(cp, GetLastError());
return;
}
- /* Replace the stderr pipe with a file if requested. In this case
- the pipe thread will still run but never report data. */
- if(cp->PipeFileSTDERR)
+ if(cp->PipeFileSTDOUT)
{
- if(!kwsysProcessSetupOutputPipeFile(&si.StartupInfo.hStdError,
- cp->PipeFileSTDERR))
+ /* Use a file for stdout. */
+ DWORD error = kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[1],
+ cp->PipeFileSTDOUT);
+ if(error)
{
- kwsysProcessCleanup(cp, 1);
- kwsysProcessCleanupHandle(&si.StartupInfo.hStdError);
+ kwsysProcessCleanup(cp, error);
return;
}
}
-
- /* Replace the stderr pipe with the parent process's if requested.
- In this case the pipe thread will still run but never report
- data. */
- if(cp->PipeSharedSTDERR)
+ else if(cp->PipeSharedSTDOUT)
+ {
+ /* Use the parent stdout. */
+ kwsysProcessSetupSharedPipe(STD_OUTPUT_HANDLE, &cp->PipeChildStd[1]);
+ }
+ else if(cp->PipeNativeSTDOUT[1])
{
- if(!kwsysProcessSetupSharedPipe(STD_ERROR_HANDLE,
- &si.StartupInfo.hStdError))
+ /* Use the given handle for stdout. */
+ kwsysProcessSetupPipeNative(cp->PipeNativeSTDOUT[1], &cp->PipeChildStd[1]);
+ }
+ 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))
{
- kwsysProcessCleanup(cp, 1);
- kwsysProcessCleanupHandleSafe(&si.StartupInfo.hStdError,
- STD_ERROR_HANDLE);
+ kwsysProcessCleanup(cp, GetLastError());
return;
}
}
- /* Replace the stderr pipe with the native pipe provided if any. In
- this case the pipe thread will still run but never report
- data. */
- if(cp->PipeNativeSTDERR[1])
+ /* 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(!kwsysProcessSetupPipeNative(&si.StartupInfo.hStdError,
- cp->PipeNativeSTDERR, 1))
+ kwsysProcessCleanup(cp, GetLastError());
+ return;
+ }
+
+ if(cp->PipeFileSTDERR)
+ {
+ /* Use a file for stderr. */
+ DWORD error = kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[2],
+ cp->PipeFileSTDERR);
+ if(error)
{
- kwsysProcessCleanup(cp, 1);
- kwsysProcessCleanupHandleSafe(&si.StartupInfo.hStdError,
- STD_ERROR_HANDLE);
+ kwsysProcessCleanup(cp, error);
+ return;
+ }
+ }
+ else if(cp->PipeSharedSTDERR)
+ {
+ /* Use the parent stderr. */
+ kwsysProcessSetupSharedPipe(STD_ERROR_HANDLE, &cp->PipeChildStd[2]);
+ }
+ else if(cp->PipeNativeSTDERR[1])
+ {
+ /* Use the given handle for stderr. */
+ kwsysProcessSetupPipeNative(cp->PipeNativeSTDERR[1], &cp->PipeChildStd[2]);
+ }
+ 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))
+ {
+ kwsysProcessCleanup(cp, GetLastError());
return;
}
}
/* Create the pipeline of processes. */
{
- HANDLE readEnd = 0;
+ /* 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)
{
- if(kwsysProcessCreate(cp, i, &si, &readEnd))
+ /* 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;
+ }
+ nextStdInput = p[0];
+ si.hStdOutput = p[1];
+ }
+ si.hStdError = cp->MergeOutput? cp->PipeChildStd[1] : cp->PipeChildStd[2];
+
+ {
+ 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
{
- kwsysProcessCleanup(cp, 1);
-
- /* Release resources that may have been allocated for this
- process before an error occurred. */
- kwsysProcessCleanupHandle(&readEnd);
- kwsysProcessCleanupHandleSafe(&si.StartupInfo.hStdInput,
- STD_INPUT_HANDLE);
- kwsysProcessCleanupHandleSafe(&si.StartupInfo.hStdOutput,
- STD_OUTPUT_HANDLE);
- kwsysProcessCleanupHandleSafe(&si.StartupInfo.hStdError,
- STD_ERROR_HANDLE);
+ if (nextStdInput != cp->PipeChildStd[0])
+ {
+ kwsysProcessCleanupHandle(&nextStdInput);
+ }
+ kwsysProcessCleanup(cp, error);
return;
}
}
-
- /* Save a handle to the output pipe for the last process. */
- cp->Pipe[KWSYSPE_PIPE_STDOUT].Read = readEnd;
+ }
}
- /* Close the inherited handles to the stderr pipe shared by all
- processes in the pipeline. The stdout and stdin pipes are not
- shared among all children and are therefore closed by
- kwsysProcessCreate after each child is created. */
- kwsysProcessCleanupHandleSafe(&si.StartupInfo.hStdError, STD_ERROR_HANDLE);
+ /* The parent process does not need the child's pipe ends. */
+ for (i=0; i < 3; ++i)
+ {
+ kwsysProcessCleanupHandle(&cp->PipeChildStd[i]);
+ }
/* Restore the working directory. */
if(cp->RealWorkingDirectory)
@@ -1325,6 +1490,52 @@ int kwsysProcess_WaitForExit(kwsysProcess* cp, double* userTimeout)
}
/*--------------------------------------------------------------------------*/
+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)
+ {
+ KWSYSPE_DEBUG((stderr, "interrupt: child not executing\n"));
+ return;
+ }
+
+ /* Skip actually interrupting the child if it has already 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)
+ {
+ /* Make sure the process handle isn't closed (e.g. from disowning). */
+ 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
+ {
+ /* No process group was created. Kill our own process group... */
+ GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, 0);
+ }
+}
+
+/*--------------------------------------------------------------------------*/
void kwsysProcess_Kill(kwsysProcess* cp)
{
int i;
@@ -1352,7 +1563,8 @@ void kwsysProcess_Kill(kwsysProcess* cp)
for(i=0; i < cp->NumberOfCommands; ++i)
{
kwsysProcessKillTree(cp->ProcessInformation[i].dwProcessId);
- // close the handle if we kill it
+ /* Remove from global list of processes and close handles. */
+ kwsysProcessesRemove(cp->ProcessInformation[i].hProcess);
kwsysProcessCleanupHandle(&cp->ProcessInformation[i].hThread);
kwsysProcessCleanupHandle(&cp->ProcessInformation[i].hProcess);
}
@@ -1539,162 +1751,129 @@ int kwsysProcessInitialize(kwsysProcess* cp)
}
}
}
+ {
+ int i;
+ for (i=0; i < 3; ++i)
+ {
+ cp->PipeChildStd[i] = INVALID_HANDLE_VALUE;
+ }
+ }
return 1;
}
/*--------------------------------------------------------------------------*/
-int kwsysProcessCreate(kwsysProcess* cp, int index,
- kwsysProcessCreateInformation* si,
- PHANDLE readEnd)
+static DWORD kwsysProcessCreateChildHandle(PHANDLE out, HANDLE in, int isStdIn)
{
- /* Setup the process's stdin. */
- if(*readEnd)
- {
- /* Create an inherited duplicate of the read end from the output
- pipe of the previous process. This also closes the
- non-inherited version. */
- if(!DuplicateHandle(GetCurrentProcess(), *readEnd,
- GetCurrentProcess(), readEnd,
- 0, TRUE, (DUPLICATE_CLOSE_SOURCE |
- DUPLICATE_SAME_ACCESS)))
- {
- return 0;
- }
- si->StartupInfo.hStdInput = *readEnd;
+ DWORD flags;
- /* This function is done with this handle. */
- *readEnd = 0;
- }
- else if(cp->PipeFileSTDIN)
+ /* Check whether the handle is valid for this process. */
+ if (in != INVALID_HANDLE_VALUE && GetHandleInformation(in, &flags))
{
- /* Create a handle to read a file for stdin. */
- wchar_t* wstdin = kwsysEncoding_DupToWide(cp->PipeFileSTDIN);
- HANDLE fin = CreateFileW(wstdin, GENERIC_READ|GENERIC_WRITE,
- FILE_SHARE_READ|FILE_SHARE_WRITE,
- 0, OPEN_EXISTING, 0, 0);
- free(wstdin);
- if(fin == INVALID_HANDLE_VALUE)
+ /* Use the handle as-is if it is already inherited. */
+ if (flags & HANDLE_FLAG_INHERIT)
{
- return 0;
- }
- /* Create an inherited duplicate of the handle. This also closes
- the non-inherited version. */
- if(!DuplicateHandle(GetCurrentProcess(), fin,
- GetCurrentProcess(), &fin,
- 0, TRUE, (DUPLICATE_CLOSE_SOURCE |
- DUPLICATE_SAME_ACCESS)))
- {
- return 0;
+ *out = in;
+ return ERROR_SUCCESS;
}
- si->StartupInfo.hStdInput = fin;
- }
- else if(cp->PipeSharedSTDIN)
- {
- /* Share this process's stdin with the child. */
- if(!kwsysProcessSetupSharedPipe(STD_INPUT_HANDLE,
- &si->StartupInfo.hStdInput))
+
+ /* Create an inherited copy of this handle. */
+ if (DuplicateHandle(GetCurrentProcess(), in, GetCurrentProcess(), out,
+ 0, TRUE, DUPLICATE_SAME_ACCESS))
{
- return 0;
+ return ERROR_SUCCESS;
}
- }
- else if(cp->PipeNativeSTDIN[0])
- {
- /* Use the provided native pipe. */
- if(!kwsysProcessSetupPipeNative(&si->StartupInfo.hStdInput,
- cp->PipeNativeSTDIN, 0))
+ else
{
- return 0;
+ return GetLastError();
}
}
else
{
- /* Explicitly give the child no stdin. */
- si->StartupInfo.hStdInput = INVALID_HANDLE_VALUE;
+ /* 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. */
+ SECURITY_ATTRIBUTES sa;
+ 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);
+ return (*out != INVALID_HANDLE_VALUE) ? ERROR_SUCCESS : GetLastError();
}
+}
- /* Setup the process's stdout. */
- {
- DWORD maybeClose = DUPLICATE_CLOSE_SOURCE;
- HANDLE writeEnd;
+/*--------------------------------------------------------------------------*/
+DWORD kwsysProcessCreate(kwsysProcess* cp, int index,
+ kwsysProcessCreateInformation* si)
+{
+ DWORD creationFlags;
+ DWORD error = ERROR_SUCCESS;
- /* Create the output pipe for this process. Neither end is directly
- inherited. */
- if(!CreatePipe(readEnd, &writeEnd, 0, 0))
+ /* Check if we are currently exiting. */
+ if (!kwsysTryEnterCreateProcessSection())
{
- return 0;
+ /* 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 an inherited duplicate of the write end. Close the
- non-inherited version unless this is the last process. Save the
- non-inherited write end of the last process. */
- if(index == cp->NumberOfCommands-1)
+ /* 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)
{
- cp->Pipe[KWSYSPE_PIPE_STDOUT].Write = writeEnd;
- maybeClose = 0;
+ creationFlags |= CREATE_NEW_PROCESS_GROUP;
}
- if(!DuplicateHandle(GetCurrentProcess(), writeEnd,
- GetCurrentProcess(), &writeEnd,
- 0, TRUE, (maybeClose | DUPLICATE_SAME_ACCESS)))
- {
- return 0;
- }
- si->StartupInfo.hStdOutput = writeEnd;
- }
- /* Replace the stdout pipe with a file if requested. In this case
- the pipe thread will still run but never report data. */
- if(index == cp->NumberOfCommands-1 && cp->PipeFileSTDOUT)
+ /* 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()));
+
+ /* Close the inherited copies of the handles. */
+ if (si->StartupInfo.hStdInput != si->hStdInput)
{
- if(!kwsysProcessSetupOutputPipeFile(&si->StartupInfo.hStdOutput,
- cp->PipeFileSTDOUT))
- {
- return 0;
- }
+ kwsysProcessCleanupHandle(&si->StartupInfo.hStdInput);
}
-
- /* Replace the stdout pipe of the last child with the parent
- process's if requested. In this case the pipe thread will still
- run but never report data. */
- if(index == cp->NumberOfCommands-1 && cp->PipeSharedSTDOUT)
+ if (si->StartupInfo.hStdOutput != si->hStdOutput)
{
- if(!kwsysProcessSetupSharedPipe(STD_OUTPUT_HANDLE,
- &si->StartupInfo.hStdOutput))
- {
- return 0;
- }
+ kwsysProcessCleanupHandle(&si->StartupInfo.hStdOutput);
}
-
- /* Replace the stdout pipe with the native pipe provided if any. In
- this case the pipe thread will still run but never report
- data. */
- if(index == cp->NumberOfCommands-1 && cp->PipeNativeSTDOUT[1])
+ if (si->StartupInfo.hStdError != si->hStdError)
{
- if(!kwsysProcessSetupPipeNative(&si->StartupInfo.hStdOutput,
- cp->PipeNativeSTDOUT, 1))
- {
- return 0;
- }
+ kwsysProcessCleanupHandle(&si->StartupInfo.hStdError);
}
- /* Create the child in a suspended state so we can wait until all
- children have been created before running any one. */
- if(!CreateProcessW(0, cp->Commands[index], 0, 0, TRUE, CREATE_SUSPENDED, 0,
- 0, &si->StartupInfo, &cp->ProcessInformation[index]))
+ /* Add the process to the global list of processes. */
+ if (!error &&
+ !kwsysProcessesAdd(cp->ProcessInformation[index].hProcess,
+ cp->ProcessInformation[index].dwProcessId, cp->CreateProcessGroup))
{
- return 0;
+ /* This failed for some reason. Kill the suspended process. */
+ TerminateProcess(cp->ProcessInformation[index].hProcess, 1);
+ /* And clean up... */
+ kwsysProcessCleanupHandle(&cp->ProcessInformation[index].hProcess);
+ kwsysProcessCleanupHandle(&cp->ProcessInformation[index].hThread);
+ strcpy(cp->ErrorMessage, "kwsysProcessesAdd function failed");
+ error = ERROR_NOT_ENOUGH_MEMORY; /* Most likely reason. */
}
- /* Successfully created this child process. Close the current
- process's copies of the inherited stdout and stdin handles. The
- stderr handle is shared among all children and is closed by
- kwsysProcess_Execute after all children have been created. */
- kwsysProcessCleanupHandleSafe(&si->StartupInfo.hStdInput,
- STD_INPUT_HANDLE);
- kwsysProcessCleanupHandleSafe(&si->StartupInfo.hStdOutput,
- STD_OUTPUT_HANDLE);
-
- return 1;
+ /* If the console Ctrl handler is waiting for us, this will release it... */
+ kwsysLeaveCreateProcessSection();
+ return error;
}
/*--------------------------------------------------------------------------*/
@@ -1716,6 +1895,9 @@ void kwsysProcessDestroy(kwsysProcess* cp, int event)
GetExitCodeProcess(cp->ProcessInformation[index].hProcess,
&cp->CommandExitCodes[index]);
+ /* Remove from global list of processes. */
+ kwsysProcessesRemove(cp->ProcessInformation[index].hProcess);
+
/* Close the process handle for the terminated process. */
kwsysProcessCleanupHandle(&cp->ProcessInformation[index].hProcess);
@@ -1750,125 +1932,51 @@ void kwsysProcessDestroy(kwsysProcess* cp, int event)
}
/*--------------------------------------------------------------------------*/
-int kwsysProcessSetupOutputPipeFile(PHANDLE phandle, const char* name)
+DWORD kwsysProcessSetupOutputPipeFile(PHANDLE phandle, const char* name)
{
HANDLE fout;
wchar_t* wname;
+ DWORD error;
if(!name)
{
- return 1;
+ return ERROR_INVALID_PARAMETER;
}
- /* Close the existing inherited handle. */
+ /* 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);
+ error = GetLastError();
free(wname);
if(fout == INVALID_HANDLE_VALUE)
{
- return 0;
- }
-
- /* Create an inherited duplicate of the handle. This also closes
- the non-inherited version. */
- if(!DuplicateHandle(GetCurrentProcess(), fout,
- GetCurrentProcess(), &fout,
- 0, TRUE, (DUPLICATE_CLOSE_SOURCE |
- DUPLICATE_SAME_ACCESS)))
- {
- return 0;
+ return error;
}
/* Assign the replacement handle. */
*phandle = fout;
- return 1;
+ return ERROR_SUCCESS;
}
/*--------------------------------------------------------------------------*/
-int kwsysProcessSetupSharedPipe(DWORD nStdHandle, PHANDLE handle)
+void kwsysProcessSetupSharedPipe(DWORD nStdHandle, PHANDLE handle)
{
- /* Check whether the handle to be shared is already inherited. */
- DWORD flags;
- int inherited = 0;
- if(GetHandleInformation(GetStdHandle(nStdHandle), &flags) &&
- (flags & HANDLE_FLAG_INHERIT))
- {
- inherited = 1;
- }
-
- /* Cleanup the previous handle. */
+ /* Close the existing handle. */
kwsysProcessCleanupHandle(handle);
-
- /* If the standard handle is not inherited then duplicate it to
- create an inherited copy. Do not close the original handle when
- duplicating! */
- if(inherited)
- {
- *handle = GetStdHandle(nStdHandle);
- return 1;
- }
- else if(DuplicateHandle(GetCurrentProcess(), GetStdHandle(nStdHandle),
- GetCurrentProcess(), handle,
- 0, TRUE, DUPLICATE_SAME_ACCESS))
- {
- return 1;
- }
- else
- {
- /* The given standard handle is not valid for this process. Some
- child processes may break if they do not have a valid standard
- pipe, so give the child an empty pipe. For the stdin pipe we
- want to close the write end and give the read end to the child.
- For stdout and stderr we want to close the read end and give
- the write end to the child. */
- int child_end = (nStdHandle == STD_INPUT_HANDLE)? 0:1;
- int parent_end = (nStdHandle == STD_INPUT_HANDLE)? 1:0;
- HANDLE emptyPipe[2];
- if(!CreatePipe(&emptyPipe[0], &emptyPipe[1], 0, 0))
- {
- return 0;
- }
-
- /* Close the non-inherited end so the pipe will be broken
- immediately. */
- CloseHandle(emptyPipe[parent_end]);
-
- /* Create an inherited duplicate of the handle. This also
- closes the non-inherited version. */
- if(!DuplicateHandle(GetCurrentProcess(), emptyPipe[child_end],
- GetCurrentProcess(), &emptyPipe[child_end],
- 0, TRUE, (DUPLICATE_CLOSE_SOURCE |
- DUPLICATE_SAME_ACCESS)))
- {
- return 0;
- }
-
- /* Give the inherited handle to the child. */
- *handle = emptyPipe[child_end];
- return 1;
- }
+ /* Store the new standard handle. */
+ *handle = GetStdHandle(nStdHandle);
}
/*--------------------------------------------------------------------------*/
-int kwsysProcessSetupPipeNative(PHANDLE handle, HANDLE p[2], int isWrite)
+void kwsysProcessSetupPipeNative(HANDLE native, PHANDLE handle)
{
- /* Close the existing inherited handle. */
+ /* Close the existing handle. */
kwsysProcessCleanupHandle(handle);
-
- /* Create an inherited duplicate of the handle. This also closes
- the non-inherited version. */
- if(!DuplicateHandle(GetCurrentProcess(), p[isWrite? 1:0],
- GetCurrentProcess(), handle,
- 0, TRUE, (DUPLICATE_CLOSE_SOURCE |
- DUPLICATE_SAME_ACCESS)))
- {
- return 0;
- }
-
- return 1;
+ /* Store the new given handle. */
+ *handle = native;
}
/*--------------------------------------------------------------------------*/
@@ -1876,30 +1984,20 @@ int kwsysProcessSetupPipeNative(PHANDLE handle, HANDLE p[2], int isWrite)
/* Close the given handle if it is open. Reset its value to 0. */
void kwsysProcessCleanupHandle(PHANDLE h)
{
- if(h && *h)
- {
- CloseHandle(*h);
- *h = 0;
- }
-}
-
-/*--------------------------------------------------------------------------*/
-
-/* Close the given handle if it is open and not a standard handle.
- Reset its value to 0. */
-void kwsysProcessCleanupHandleSafe(PHANDLE h, DWORD nStdHandle)
-{
- if(h && *h && (*h != GetStdHandle(nStdHandle)))
+ 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 = 0;
+ *h = INVALID_HANDLE_VALUE;
}
}
/*--------------------------------------------------------------------------*/
/* Close all handles created by kwsysProcess_Execute. */
-void kwsysProcessCleanup(kwsysProcess* cp, int error)
+void kwsysProcessCleanup(kwsysProcess* cp, DWORD error)
{
int i;
/* If this is an error case, report the error. */
@@ -1909,21 +2007,27 @@ void kwsysProcessCleanup(kwsysProcess* cp, int error)
if(cp->ErrorMessage[0] == 0)
{
/* Format the error message. */
- DWORD original = GetLastError();
wchar_t err_msg[KWSYSPE_PIPE_BUFFER_SIZE];
DWORD length = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS, 0, original,
+ FORMAT_MESSAGE_IGNORE_INSERTS, 0, error,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
err_msg, KWSYSPE_PIPE_BUFFER_SIZE, 0);
- WideCharToMultiByte(CP_UTF8, 0, err_msg, -1, cp->ErrorMessage,
- KWSYSPE_PIPE_BUFFER_SIZE, NULL, NULL);
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",
- original, GetLastError());
+ error, GetLastError());
+ }
+ 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());
}
}
@@ -1946,6 +2050,8 @@ void kwsysProcessCleanup(kwsysProcess* cp, int error)
}
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);
}
@@ -1982,6 +2088,10 @@ void kwsysProcessCleanup(kwsysProcess* cp, int error)
kwsysProcessCleanupHandle(&cp->Pipe[i].Read);
cp->Pipe[i].Closed = 0;
}
+ for(i=0; i < 3; ++i)
+ {
+ kwsysProcessCleanupHandle(&cp->PipeChildStd[i]);
+ }
}
/*--------------------------------------------------------------------------*/
@@ -2006,66 +2116,6 @@ void kwsysProcessCleanErrorMessage(kwsysProcess* cp)
}
/*--------------------------------------------------------------------------*/
-int kwsysProcessComputeCommandLength(kwsysProcess* cp,
- char const* const* command)
-{
- int length = 0;
- if(cp->Verbatim)
- {
- /* Treat the first argument as a verbatim command line. Use its
- length directly and add space for the null-terminator. */
- length = (int)strlen(*command)+1;
- }
- else
- {
- /* Compute the length of the command line when it is converted to
- a single string. Space for the null-terminator is allocated by
- the whitespace character allocated for the first argument that
- will not be used. */
- char const* const* arg;
- for(arg = command; *arg; ++arg)
- {
- /* Add the length of this argument. It already includes room
- for a separating space or terminating null. */
- length += kwsysSystem_Shell_GetArgumentSizeForWindows(*arg, 0);
- }
- }
-
- return length;
-}
-
-/*--------------------------------------------------------------------------*/
-void kwsysProcessComputeCommandLine(kwsysProcess* cp,
- char const* const* command,
- char* cmd)
-{
- if(cp->Verbatim)
- {
- /* Copy the verbatim command line into the buffer. */
- strcpy(cmd, *command);
- }
- else
- {
- /* Construct the command line in the allocated buffer. */
- char const* const* arg;
- for(arg = command; *arg; ++arg)
- {
- /* Add the separating space if this is not the first argument. */
- if(arg != command)
- {
- *cmd++ = ' ';
- }
-
- /* Add the current argument. */
- cmd = kwsysSystem_Shell_GetArgumentForWindows(*arg, cmd, 0);
- }
-
- /* Add the terminating null character to the command line. */
- *cmd = 0;
- }
-}
-
-/*--------------------------------------------------------------------------*/
/* Get the time at which either the process or user timeout will
expire. Returns 1 if the user timeout is first, and 0 otherwise. */
int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
@@ -2382,7 +2432,11 @@ static kwsysProcess_List* kwsysProcess_List_New(void)
osv.dwOSVersionInfoSize = sizeof(osv);
#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
# pragma warning (push)
-# pragma warning (disable:4996)
+# ifdef __INTEL_COMPILER
+# pragma warning (disable:1478)
+# else
+# pragma warning (disable:4996)
+# endif
#endif
GetVersionEx(&osv);
#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
@@ -2734,3 +2788,230 @@ static void kwsysProcessDisablePipeThreads(kwsysProcess* cp)
ReleaseSemaphore(cp->Pipe[cp->CurrentIndex].Reader.Go, 1, 0);
}
}
+
+/*--------------------------------------------------------------------------*/
+/* Global set of executing processes for use by the Ctrl handler.
+ This global instance will be zero-initialized by the compiler.
+
+ Note that the console Ctrl handler runs on a background thread and so
+ everything it does must be thread safe. Here, we track the hProcess
+ HANDLEs directly instead of kwsysProcess instances, so that we don't have
+ to make kwsysProcess thread safe. */
+typedef struct kwsysProcessInstance_s
+{
+ HANDLE hProcess;
+ DWORD dwProcessId;
+ int NewProcessGroup; /* Whether the process was created in a new group. */
+} kwsysProcessInstance;
+
+typedef struct kwsysProcessInstances_s
+{
+ /* Whether we have initialized key fields below, like critical sections. */
+ int Initialized;
+
+ /* Ctrl handler runs on a different thread, so we must sync access. */
+ CRITICAL_SECTION Lock;
+
+ int Exiting;
+ size_t Count;
+ size_t Size;
+ kwsysProcessInstance* Processes;
+} kwsysProcessInstances;
+static kwsysProcessInstances kwsysProcesses;
+
+/*--------------------------------------------------------------------------*/
+/* Initialize critial section and set up console Ctrl handler. You MUST call
+ this before using any other kwsysProcesses* functions below. */
+static int kwsysProcessesInitialize(void)
+{
+ /* Initialize everything if not done already. */
+ if(!kwsysProcesses.Initialized)
+ {
+ InitializeCriticalSection(&kwsysProcesses.Lock);
+
+ /* Set up console ctrl handler. */
+ if(!SetConsoleCtrlHandler(kwsysCtrlHandler, TRUE))
+ {
+ return 0;
+ }
+
+ kwsysProcesses.Initialized = 1;
+ }
+ return 1;
+}
+
+/*--------------------------------------------------------------------------*/
+/* The Ctrl handler waits on the global list of processes. To prevent an
+ orphaned process, do not create a new process if the Ctrl handler is
+ already running. Do so by using this function to check if it is ok to
+ create a process. */
+static int kwsysTryEnterCreateProcessSection(void)
+{
+ /* Enter main critical section; this means creating a process and the Ctrl
+ handler are mutually exclusive. */
+ EnterCriticalSection(&kwsysProcesses.Lock);
+ /* Indicate to the caller if they can create a process. */
+ if(kwsysProcesses.Exiting)
+ {
+ LeaveCriticalSection(&kwsysProcesses.Lock);
+ return 0;
+ }
+ else
+ {
+ return 1;
+ }
+}
+
+/*--------------------------------------------------------------------------*/
+/* Matching function on successful kwsysTryEnterCreateProcessSection return.
+ Make sure you called kwsysProcessesAdd if applicable before calling this.*/
+static void kwsysLeaveCreateProcessSection(void)
+{
+ LeaveCriticalSection(&kwsysProcesses.Lock);
+}
+
+/*--------------------------------------------------------------------------*/
+/* Add new process to global process list. The Ctrl handler will wait for
+ the process to exit before it returns. Do not close the process handle
+ until after calling kwsysProcessesRemove. The newProcessGroup parameter
+ must be set if the process was created with CREATE_NEW_PROCESS_GROUP. */
+static int kwsysProcessesAdd(HANDLE hProcess, DWORD dwProcessid,
+ int newProcessGroup)
+{
+ 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)
+ {
+ size_t newSize;
+ 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;
+
+ /* Try allocating the new block of memory. */
+ if(newArray = (kwsysProcessInstance*)malloc(
+ newSize*sizeof(kwsysProcessInstance)))
+ {
+ /* Copy the old process handles to the new memory. */
+ if(kwsysProcesses.Count > 0)
+ {
+ memcpy(newArray, kwsysProcesses.Processes,
+ kwsysProcesses.Count * sizeof(kwsysProcessInstance));
+ }
+ }
+ else
+ {
+ /* Failed to allocate memory for the new process handle set. */
+ LeaveCriticalSection(&kwsysProcesses.Lock);
+ return 0;
+ }
+
+ /* Free original array. */
+ free(kwsysProcesses.Processes);
+
+ /* 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;
+ kwsysProcesses.Processes[kwsysProcesses.Count].dwProcessId = dwProcessid;
+ kwsysProcesses.Processes[kwsysProcesses.Count++].NewProcessGroup =
+ newProcessGroup;
+
+ /* Leave critical section and return success. */
+ LeaveCriticalSection(&kwsysProcesses.Lock);
+
+ return 1;
+}
+
+/*--------------------------------------------------------------------------*/
+/* Removes process to global process list. */
+static void kwsysProcessesRemove(HANDLE hProcess)
+{
+ size_t i;
+
+ 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)
+ {
+ break;
+ }
+ }
+ 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];
+ }
+
+ /* If this was the last process, free the array. */
+ if(kwsysProcesses.Count == 0)
+ {
+ kwsysProcesses.Size = 0;
+ free(kwsysProcesses.Processes);
+ kwsysProcesses.Processes = 0;
+ }
+ }
+
+ LeaveCriticalSection(&kwsysProcesses.Lock);
+}
+
+/*--------------------------------------------------------------------------*/
+static BOOL WINAPI kwsysCtrlHandler(DWORD dwCtrlType)
+{
+ size_t i;
+ (void)dwCtrlType;
+ /* Enter critical section. */
+ EnterCriticalSection(&kwsysProcesses.Lock);
+
+ /* Set flag indicating that we are exiting. */
+ kwsysProcesses.Exiting = 1;
+
+ /* 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)
+ {
+ DWORD groupId = kwsysProcesses.Processes[i].dwProcessId;
+ 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)
+ {
+ WaitForSingleObject(kwsysProcesses.Processes[i].hProcess, INFINITE);
+ }
+
+ /* Leave critical section. */
+ LeaveCriticalSection(&kwsysProcesses.Lock);
+
+ /* Continue on to default Ctrl handler (which calls ExitProcess). */
+ return FALSE;
+}
diff --git a/src/kwsys/README.txt b/src/kwsys/README.txt
index ba03f8d..b8191f7 100644
--- a/src/kwsys/README.txt
+++ b/src/kwsys/README.txt
@@ -8,3 +8,5 @@ details.
You are probably reading this file in the source tree of a surrounding
project. In that case, see "../README.kwsys" for details of using
KWSys in your project.
+
+See CONTRIBUTING.rst for instructions to contribute KWSys changes.
diff --git a/src/kwsys/System.c b/src/kwsys/System.c
index 1ee26fa..ccc7e81 100644
--- a/src/kwsys/System.c
+++ b/src/kwsys/System.c
@@ -20,8 +20,8 @@
#include <stddef.h> /* ptrdiff_t */
#include <stdlib.h> /* malloc, free */
-#include <string.h> /* strlen */
-#include <ctype.h> /* isalpha */
+#include <string.h> /* memcpy */
+#include <ctype.h> /* isspace */
#include <stdio.h>
@@ -31,587 +31,6 @@ typedef ptrdiff_t kwsysSystem_ptrdiff_t;
typedef int kwsysSystem_ptrdiff_t;
#endif
-/*
-
-Notes:
-
-Make variable replacements open a can of worms. Sometimes they should
-be quoted and sometimes not. Sometimes their replacement values are
-already quoted.
-
-VS variables cause problems. In order to pass the referenced value
-with spaces the reference must be quoted. If the variable value ends
-in a backslash then it will escape the ending quote! In order to make
-the ending backslash appear we need this:
-
- "$(InputDir)\"
-
-However if there is not a trailing backslash then this will put a
-quote in the value so we need:
-
- "$(InputDir)"
-
-Make variable references are platform specific so we should probably
-just NOT quote them and let the listfile author deal with it.
-
-*/
-
-/*
-TODO: For windows echo:
-
-To display a pipe (|) or redirection character (< or >) when using the
-echo command, use a caret character immediately before the pipe or
-redirection character (for example, ^>, ^<, or ^| ). If you need to
-use the caret character itself (^), use two in a row (^^).
-*/
-
-/*--------------------------------------------------------------------------*/
-static int kwsysSystem_Shell__CharIsWhitespace(char c)
-{
- return ((c == ' ') || (c == '\t'));
-}
-
-/*--------------------------------------------------------------------------*/
-static int kwsysSystem_Shell__CharNeedsQuotesOnUnix(char c)
-{
- return ((c == '\'') || (c == '`') || (c == ';') || (c == '#') ||
- (c == '&') || (c == '$') || (c == '(') || (c == ')') ||
- (c == '~') || (c == '<') || (c == '>') || (c == '|') ||
- (c == '*') || (c == '^') || (c == '\\'));
-}
-
-/*--------------------------------------------------------------------------*/
-static int kwsysSystem_Shell__CharNeedsQuotesOnWindows(char c)
-{
- return ((c == '\'') || (c == '#') || (c == '&') ||
- (c == '<') || (c == '>') || (c == '|') || (c == '^'));
-}
-
-/*--------------------------------------------------------------------------*/
-static int kwsysSystem_Shell__CharNeedsQuotes(char c, int isUnix, int flags)
-{
- /* On Windows the built-in command shell echo never needs quotes. */
- if(!isUnix && (flags & kwsysSystem_Shell_Flag_EchoWindows))
- {
- return 0;
- }
-
- /* On all platforms quotes are needed to preserve whitespace. */
- if(kwsysSystem_Shell__CharIsWhitespace(c))
- {
- return 1;
- }
-
- if(isUnix)
- {
- /* On UNIX several special characters need quotes to preserve them. */
- if(kwsysSystem_Shell__CharNeedsQuotesOnUnix(c))
- {
- return 1;
- }
- }
- else
- {
- /* On Windows several special characters need quotes to preserve them. */
- if(kwsysSystem_Shell__CharNeedsQuotesOnWindows(c))
- {
- return 1;
- }
- }
- return 0;
-}
-
-/*--------------------------------------------------------------------------*/
-static int kwsysSystem_Shell__CharIsMakeVariableName(char c)
-{
- return c && (c == '_' || isalpha(((int)c)));
-}
-
-/*--------------------------------------------------------------------------*/
-static const char* kwsysSystem_Shell__SkipMakeVariables(const char* c)
-{
- while(*c == '$' && *(c+1) == '(')
- {
- const char* skip = c+2;
- while(kwsysSystem_Shell__CharIsMakeVariableName(*skip))
- {
- ++skip;
- }
- if(*skip == ')')
- {
- c = skip+1;
- }
- else
- {
- break;
- }
- }
- return c;
-}
-
-/*
-Allowing make variable replacements opens a can of worms. Sometimes
-they should be quoted and sometimes not. Sometimes their replacement
-values are already quoted or contain escapes.
-
-Some Visual Studio variables cause problems. In order to pass the
-referenced value with spaces the reference must be quoted. If the
-variable value ends in a backslash then it will escape the ending
-quote! In order to make the ending backslash appear we need this:
-
- "$(InputDir)\"
-
-However if there is not a trailing backslash then this will put a
-quote in the value so we need:
-
- "$(InputDir)"
-
-This macro decides whether we quote an argument just because it
-contains a make variable reference. This should be replaced with a
-flag later when we understand applications of this better.
-*/
-#define KWSYS_SYSTEM_SHELL_QUOTE_MAKE_VARIABLES 0
-
-/*--------------------------------------------------------------------------*/
-static int kwsysSystem_Shell__ArgumentNeedsQuotes(const char* in, int isUnix,
- int flags)
-{
- /* The empty string needs quotes. */
- if(!*in)
- {
- return 1;
- }
-
- /* Scan the string for characters that require quoting. */
- {
- const char* c;
- for(c=in; *c; ++c)
- {
- /* Look for $(MAKEVAR) syntax if requested. */
- if(flags & kwsysSystem_Shell_Flag_AllowMakeVariables)
- {
-#if KWSYS_SYSTEM_SHELL_QUOTE_MAKE_VARIABLES
- const char* skip = kwsysSystem_Shell__SkipMakeVariables(c);
- if(skip != c)
- {
- /* We need to quote make variable references to preserve the
- string with contents substituted in its place. */
- return 1;
- }
-#else
- /* Skip over the make variable references if any are present. */
- c = kwsysSystem_Shell__SkipMakeVariables(c);
-
- /* Stop if we have reached the end of the string. */
- if(!*c)
- {
- break;
- }
-#endif
- }
-
- /* Check whether this character needs quotes. */
- if(kwsysSystem_Shell__CharNeedsQuotes(*c, isUnix, flags))
- {
- return 1;
- }
- }
- }
-
- /* On Windows some single character arguments need quotes. */
- if(!isUnix && *in && !*(in+1))
- {
- char c = *in;
- if((c == '?') || (c == '&') || (c == '^') || (c == '|') || (c == '#'))
- {
- return 1;
- }
- }
-
- return 0;
-}
-
-/*--------------------------------------------------------------------------*/
-static int kwsysSystem_Shell__GetArgumentSize(const char* in,
- int isUnix, int flags)
-{
- /* Start with the length of the original argument, plus one for
- either a terminating null or a separating space. */
- int size = (int)strlen(in) + 1;
-
- /* String iterator. */
- const char* c;
-
- /* Keep track of how many backslashes have been encountered in a row. */
- int windows_backslashes = 0;
-
- /* Scan the string for characters that require escaping or quoting. */
- for(c=in; *c; ++c)
- {
- /* Look for $(MAKEVAR) syntax if requested. */
- if(flags & kwsysSystem_Shell_Flag_AllowMakeVariables)
- {
- /* Skip over the make variable references if any are present. */
- c = kwsysSystem_Shell__SkipMakeVariables(c);
-
- /* Stop if we have reached the end of the string. */
- if(!*c)
- {
- break;
- }
- }
-
- /* Check whether this character needs escaping for the shell. */
- if(isUnix)
- {
- /* On Unix a few special characters need escaping even inside a
- quoted argument. */
- if(*c == '\\' || *c == '"' || *c == '`' || *c == '$')
- {
- /* This character needs a backslash to escape it. */
- ++size;
- }
- }
- else if(flags & kwsysSystem_Shell_Flag_EchoWindows)
- {
- /* On Windows the built-in command shell echo never needs escaping. */
- }
- else
- {
- /* On Windows only backslashes and double-quotes need escaping. */
- if(*c == '\\')
- {
- /* Found a backslash. It may need to be escaped later. */
- ++windows_backslashes;
- }
- else if(*c == '"')
- {
- /* Found a double-quote. We need to escape it and all
- immediately preceding backslashes. */
- size += windows_backslashes + 1;
- windows_backslashes = 0;
- }
- else
- {
- /* Found another character. This eliminates the possibility
- that any immediately preceding backslashes will be
- escaped. */
- windows_backslashes = 0;
- }
- }
-
- /* Check whether this character needs escaping for a make tool. */
- if(*c == '$')
- {
- if(flags & kwsysSystem_Shell_Flag_Make)
- {
- /* In Makefiles a dollar is written $$ so we need one extra
- character. */
- ++size;
- }
- else if(flags & kwsysSystem_Shell_Flag_VSIDE)
- {
- /* In a VS IDE a dollar is written "$" so we need two extra
- characters. */
- size += 2;
- }
- }
- else if(*c == '#')
- {
- if((flags & kwsysSystem_Shell_Flag_Make) &&
- (flags & kwsysSystem_Shell_Flag_WatcomWMake))
- {
- /* In Watcom WMake makefiles a pound is written $# so we need
- one extra character. */
- ++size;
- }
- }
- else if(*c == '%')
- {
- if((flags & kwsysSystem_Shell_Flag_VSIDE) ||
- ((flags & kwsysSystem_Shell_Flag_Make) &&
- ((flags & kwsysSystem_Shell_Flag_MinGWMake) ||
- (flags & kwsysSystem_Shell_Flag_NMake))))
- {
- /* In the VS IDE, NMake, or MinGW make a percent is written %%
- so we need one extra characters. */
- size += 1;
- }
- }
- else if(*c == ';')
- {
- if(flags & kwsysSystem_Shell_Flag_VSIDE)
- {
- /* In a VS IDE a semicolon is written ";" so we need two extra
- characters. */
- size += 2;
- }
- }
- }
-
- /* Check whether the argument needs surrounding quotes. */
- if(kwsysSystem_Shell__ArgumentNeedsQuotes(in, isUnix, flags))
- {
- /* Surrounding quotes are needed. Allocate space for them. */
- if((flags & kwsysSystem_Shell_Flag_WatcomQuote) && (isUnix))
- {
- size += 2;
- }
- size += 2;
-
- /* We must escape all ending backslashes when quoting on windows. */
- size += windows_backslashes;
- }
-
- return size;
-}
-
-/*--------------------------------------------------------------------------*/
-static char* kwsysSystem_Shell__GetArgument(const char* in, char* out,
- int isUnix, int flags)
-{
- /* String iterator. */
- const char* c;
-
- /* Keep track of how many backslashes have been encountered in a row. */
- int windows_backslashes = 0;
-
- /* Whether the argument must be quoted. */
- int needQuotes = kwsysSystem_Shell__ArgumentNeedsQuotes(in, isUnix, flags);
- if(needQuotes)
- {
- /* Add the opening quote for this argument. */
- if(flags & kwsysSystem_Shell_Flag_WatcomQuote)
- {
- if(isUnix)
- {
- *out++ = '"';
- }
- *out++ = '\'';
- }
- else
- {
- *out++ = '"';
- }
- }
-
- /* Scan the string for characters that require escaping or quoting. */
- for(c=in; *c; ++c)
- {
- /* Look for $(MAKEVAR) syntax if requested. */
- if(flags & kwsysSystem_Shell_Flag_AllowMakeVariables)
- {
- const char* skip = kwsysSystem_Shell__SkipMakeVariables(c);
- if(skip != c)
- {
- /* Copy to the end of the make variable references. */
- while(c != skip)
- {
- *out++ = *c++;
- }
-
- /* The make variable reference eliminates any escaping needed
- for preceding backslashes. */
- windows_backslashes = 0;
-
- /* Stop if we have reached the end of the string. */
- if(!*c)
- {
- break;
- }
- }
- }
-
- /* Check whether this character needs escaping for the shell. */
- if(isUnix)
- {
- /* On Unix a few special characters need escaping even inside a
- quoted argument. */
- if(*c == '\\' || *c == '"' || *c == '`' || *c == '$')
- {
- /* This character needs a backslash to escape it. */
- *out++ = '\\';
- }
- }
- else if(flags & kwsysSystem_Shell_Flag_EchoWindows)
- {
- /* On Windows the built-in command shell echo never needs escaping. */
- }
- else
- {
- /* On Windows only backslashes and double-quotes need escaping. */
- if(*c == '\\')
- {
- /* Found a backslash. It may need to be escaped later. */
- ++windows_backslashes;
- }
- else if(*c == '"')
- {
- /* Found a double-quote. Escape all immediately preceding
- backslashes. */
- while(windows_backslashes > 0)
- {
- --windows_backslashes;
- *out++ = '\\';
- }
-
- /* Add the backslash to escape the double-quote. */
- *out++ = '\\';
- }
- else
- {
- /* We encountered a normal character. This eliminates any
- escaping needed for preceding backslashes. */
- windows_backslashes = 0;
- }
- }
-
- /* Check whether this character needs escaping for a make tool. */
- if(*c == '$')
- {
- if(flags & kwsysSystem_Shell_Flag_Make)
- {
- /* In Makefiles a dollar is written $$. The make tool will
- replace it with just $ before passing it to the shell. */
- *out++ = '$';
- *out++ = '$';
- }
- else if(flags & kwsysSystem_Shell_Flag_VSIDE)
- {
- /* In a VS IDE a dollar is written "$". If this is written in
- an un-quoted argument it starts a quoted segment, inserts
- the $ and ends the segment. If it is written in a quoted
- argument it ends quoting, inserts the $ and restarts
- quoting. Either way the $ is isolated from surrounding
- text to avoid looking like a variable reference. */
- *out++ = '"';
- *out++ = '$';
- *out++ = '"';
- }
- else
- {
- /* Otherwise a dollar is written just $. */
- *out++ = '$';
- }
- }
- else if(*c == '#')
- {
- if((flags & kwsysSystem_Shell_Flag_Make) &&
- (flags & kwsysSystem_Shell_Flag_WatcomWMake))
- {
- /* In Watcom WMake makefiles a pound is written $#. The make
- tool will replace it with just # before passing it to the
- shell. */
- *out++ = '$';
- *out++ = '#';
- }
- else
- {
- /* Otherwise a pound is written just #. */
- *out++ = '#';
- }
- }
- else if(*c == '%')
- {
- if((flags & kwsysSystem_Shell_Flag_VSIDE) ||
- ((flags & kwsysSystem_Shell_Flag_Make) &&
- ((flags & kwsysSystem_Shell_Flag_MinGWMake) ||
- (flags & kwsysSystem_Shell_Flag_NMake))))
- {
- /* In the VS IDE, NMake, or MinGW make a percent is written %%. */
- *out++ = '%';
- *out++ = '%';
- }
- else
- {
- /* Otherwise a percent is written just %. */
- *out++ = '%';
- }
- }
- else if(*c == ';')
- {
- if(flags & kwsysSystem_Shell_Flag_VSIDE)
- {
- /* In a VS IDE a semicolon is written ";". If this is written
- in an un-quoted argument it starts a quoted segment,
- inserts the ; and ends the segment. If it is written in a
- quoted argument it ends quoting, inserts the ; and restarts
- quoting. Either way the ; is isolated. */
- *out++ = '"';
- *out++ = ';';
- *out++ = '"';
- }
- else
- {
- /* Otherwise a semicolon is written just ;. */
- *out++ = ';';
- }
- }
- else
- {
- /* Store this character. */
- *out++ = *c;
- }
- }
-
- if(needQuotes)
- {
- /* Add enough backslashes to escape any trailing ones. */
- while(windows_backslashes > 0)
- {
- --windows_backslashes;
- *out++ = '\\';
- }
-
- /* Add the closing quote for this argument. */
- if(flags & kwsysSystem_Shell_Flag_WatcomQuote)
- {
- *out++ = '\'';
- if(isUnix)
- {
- *out++ = '"';
- }
- }
- else
- {
- *out++ = '"';
- }
- }
-
- /* Store a terminating null without incrementing. */
- *out = 0;
-
- return out;
-}
-
-/*--------------------------------------------------------------------------*/
-char* kwsysSystem_Shell_GetArgumentForWindows(const char* in,
- char* out,
- int flags)
-{
- return kwsysSystem_Shell__GetArgument(in, out, 0, flags);
-}
-
-/*--------------------------------------------------------------------------*/
-char* kwsysSystem_Shell_GetArgumentForUnix(const char* in,
- char* out,
- int flags)
-{
- return kwsysSystem_Shell__GetArgument(in, out, 1, flags);
-}
-
-/*--------------------------------------------------------------------------*/
-int kwsysSystem_Shell_GetArgumentSizeForWindows(const char* in, int flags)
-{
- return kwsysSystem_Shell__GetArgumentSize(in, 0, flags);
-}
-
-/*--------------------------------------------------------------------------*/
-int kwsysSystem_Shell_GetArgumentSizeForUnix(const char* in, int flags)
-{
- return kwsysSystem_Shell__GetArgumentSize(in, 1, flags);
-}
-
/*--------------------------------------------------------------------------*/
static int kwsysSystem__AppendByte(char* local,
char** begin, char** end,
diff --git a/src/kwsys/System.h.in b/src/kwsys/System.h.in
index f21bf0d..3f3d3f4 100644
--- a/src/kwsys/System.h.in
+++ b/src/kwsys/System.h.in
@@ -24,28 +24,6 @@
#endif
#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# define kwsysSystem_Parse_CommandForUnix kwsys_ns(System_Parse_CommandForUnix)
-# define kwsysSystem_Shell_GetArgumentForWindows kwsys_ns(System_Shell_GetArgumentForWindows)
-# define kwsysSystem_Shell_GetArgumentForUnix kwsys_ns(System_Shell_GetArgumentForUnix)
-# define kwsysSystem_Shell_GetArgumentSizeForWindows kwsys_ns(System_Shell_GetArgumentSizeForWindows)
-# define kwsysSystem_Shell_GetArgumentSizeForUnix kwsys_ns(System_Shell_GetArgumentSizeForUnix)
-# define kwsysSystem_Shell_Flag_e kwsys_ns(System_Shell_Flag_e)
-# define kwsysSystem_Shell_Flag_Make kwsys_ns(System_Shell_Flag_Make)
-# define kwsysSystem_Shell_Flag_VSIDE kwsys_ns(System_Shell_Flag_VSIDE)
-# define kwsysSystem_Shell_Flag_EchoWindows kwsys_ns(System_Shell_Flag_EchoWindows)
-# define kwsysSystem_Shell_Flag_WatcomWMake kwsys_ns(System_Shell_Flag_WatcomWMake)
-# define kwsysSystem_Shell_Flag_MinGWMake kwsys_ns(System_Shell_Flag_MinGWMake)
-# define kwsysSystem_Shell_Flag_NMake kwsys_ns(System_Shell_Flag_NMake)
-# define kwsysSystem_Shell_Flag_AllowMakeVariables kwsys_ns(System_Shell_Flag_AllowMakeVariables)
-# define kwsysSystem_Shell_Flag_WatcomQuote kwsys_ns(System_Shell_Flag_WatcomQuote)
-#endif
-
-#ifdef __VMS
-#define @KWSYS_NAMESPACE@System_Shell_GetArgumentForUnix \
- @KWSYS_NAMESPACE@System_Shell_UnixGA
-#define @KWSYS_NAMESPACE@System_Shell_GetArgumentSizeForUnix \
- @KWSYS_NAMESPACE@System_Shell_UnixGAS
-#define @KWSYS_NAMESPACE@System_Shell_GetArgumentForWindows \
- @KWSYS_NAMESPACE@System_Shell_WindowsGA
#endif
#if defined(__cplusplus)
@@ -54,69 +32,6 @@ extern "C"
#endif
/**
- * Transform the given command line argument for use in a Windows or
- * Unix shell. Returns a pointer to the end of the command line
- * argument in the provided output buffer. Flags may be passed to
- * modify the generated quoting and escape sequences to work under
- * alternative environments.
- */
-kwsysEXPORT char* kwsysSystem_Shell_GetArgumentForWindows(const char* in,
- char* out,
- int flags);
-kwsysEXPORT char* kwsysSystem_Shell_GetArgumentForUnix(const char* in,
- char* out,
- int flags);
-
-/**
- * Compute the size of the buffer required to store the output from
- * kwsysSystem_Shell_GetArgumentForWindows or
- * kwsysSystem_Shell_GetArgumentForUnix. The flags passed must be
- * identical between the two calls.
- */
-kwsysEXPORT int kwsysSystem_Shell_GetArgumentSizeForWindows(const char* in,
- int flags);
-kwsysEXPORT int kwsysSystem_Shell_GetArgumentSizeForUnix(const char* in,
- int flags);
-
-/**
- * Flags to pass to kwsysSystem_Shell_GetArgumentForWindows or
- * kwsysSystem_Shell_GetArgumentForUnix. These modify the generated
- * quoting and escape sequences to work under alternative
- * environments.
- */
-enum kwsysSystem_Shell_Flag_e
-{
- /** The target shell is in a makefile. */
- kwsysSystem_Shell_Flag_Make = (1<<0),
-
- /** The target shell is in a VS project file. Do not use with
- Shell_Flag_Make. */
- kwsysSystem_Shell_Flag_VSIDE = (1<<1),
-
- /** In a windows shell the argument is being passed to "echo". */
- kwsysSystem_Shell_Flag_EchoWindows = (1<<2),
-
- /** The target shell is in a Watcom WMake makefile. */
- kwsysSystem_Shell_Flag_WatcomWMake = (1<<3),
-
- /** The target shell is in a MinGW Make makefile. */
- kwsysSystem_Shell_Flag_MinGWMake = (1<<4),
-
- /** The target shell is in a NMake makefile. */
- kwsysSystem_Shell_Flag_NMake = (1<<5),
-
- /** Make variable reference syntax $(MAKEVAR) should not be escaped
- to allow a build tool to replace it. Replacement values
- containing spaces, quotes, backslashes, or other
- non-alphanumeric characters that have significance to some makes
- or shells produce undefined behavior. */
- kwsysSystem_Shell_Flag_AllowMakeVariables = (1<<6),
-
- /** The target shell quoting uses extra single Quotes for Watcom tools. */
- kwsysSystem_Shell_Flag_WatcomQuote = (1<<7)
-};
-
-/**
* Parse a unix-style command line string into separate arguments.
*
* On success, returns a pointer to an array of pointers to individual
@@ -148,19 +63,6 @@ kwsysEXPORT char** kwsysSystem_Parse_CommandForUnix(const char* command,
# undef kwsysEXPORT
# if !defined(KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# undef kwsysSystem_Parse_CommandForUnix
-# undef kwsysSystem_Shell_GetArgumentForWindows
-# undef kwsysSystem_Shell_GetArgumentForUnix
-# undef kwsysSystem_Shell_GetArgumentSizeForWindows
-# undef kwsysSystem_Shell_GetArgumentSizeForUnix
-# undef kwsysSystem_Shell_Flag_e
-# undef kwsysSystem_Shell_Flag_Make
-# undef kwsysSystem_Shell_Flag_VSIDE
-# undef kwsysSystem_Shell_Flag_EchoWindows
-# undef kwsysSystem_Shell_Flag_WatcomWMake
-# undef kwsysSystem_Shell_Flag_MinGWMake
-# undef kwsysSystem_Shell_Flag_NMake
-# undef kwsysSystem_Shell_Flag_AllowMakeVariables
-# undef kwsysSystem_Shell_Flag_WatcomQuote
# endif
#endif
diff --git a/src/kwsys/kwsysPlatformTestsCXX.cxx b/src/kwsys/kwsysPlatformTestsCXX.cxx
index 3f947f3..1596fe4 100644
--- a/src/kwsys/kwsysPlatformTestsCXX.cxx
+++ b/src/kwsys/kwsysPlatformTestsCXX.cxx
@@ -452,6 +452,19 @@ int main()
}
#endif
+#ifdef TEST_KWSYS_CXX_HAS_GETLOADAVG
+// Match feature definitions from SystemInformation.cxx
+#if (defined(__GNUC__) || defined(__PGI)) && !defined(_GNU_SOURCE)
+# define _GNU_SOURCE
+#endif
+#include <stdlib.h>
+int main()
+{
+ double loadavg[3] = { 0.0, 0.0, 0.0 };
+ return getloadavg(loadavg, 3);
+}
+#endif
+
#ifdef TEST_KWSYS_CXX_HAS_RLIMIT64
# if defined(KWSYS_HAS_LFS)
# define _LARGEFILE_SOURCE
@@ -548,6 +561,10 @@ int main()
#if (defined(__GNUC__) || defined(__PGI)) && !defined(_GNU_SOURCE)
# define _GNU_SOURCE
#endif
+#if defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5130 \
+ && __linux && __SUNPRO_CC_COMPAT == 'G'
+# include <iostream>
+#endif
#include <cxxabi.h>
int main()
{