2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
10 #include <afsconfig.h>
11 #include <afs/param.h>
23 #include <afs/errmap_nt.h>
24 #include <afs/secutil_nt.h>
27 #include "pmgtprivate.h"
31 /* Signal disposition table and associated definitions and locks */
34 struct sigaction action; /* signal action information */
37 static sigtable_entry_t signalTable[NSIG]; /* signal table; slot 0 unused */
38 static pthread_mutex_t signalTableLock; /* lock protects signalTable */
40 /* Global signal block lock; all signal handlers are serialized for now */
41 static pthread_mutex_t signalBlockLock;
43 /* Named pipe prefix for sending signals */
44 #define PMGT_SIGNAL_PIPE_PREFIX "\\\\.\\pipe\\TransarcAfsSignalPipe"
46 /* Macro to test process exit status for an uncaught exception */
47 #define PMGT_IS_EXPSTATUS(status) (((status) & 0xF0000000) == 0xC0000000)
51 /* Child process table and associated definitions and locks */
54 HANDLE p_handle; /* process handle (NULL if table entry not valid) */
55 BOOL p_reserved; /* table entry is reserved for spawn */
56 DWORD p_id; /* process id */
57 BOOL p_terminated; /* process terminated; status available/valid */
58 DWORD p_status; /* status of terminated process */
61 /* Max number of active child processes supported */
62 #define PMGT_CHILD_MAX 100
64 static proctable_entry_t procTable[PMGT_CHILD_MAX]; /* child process table */
65 static int procEntryCount; /* count of valid entries in procTable */
66 static int procTermCount; /* count of terminated entries in procTable */
68 /* lock protects procTable, procEntryCount, and procTermCount */
69 static pthread_mutex_t procTableLock;
71 /* Named shared memory prefix for passing a data buffer to a child process */
72 #define PMGT_DATA_MEM_PREFIX "TransarcAfsSpawnDataMemory"
74 /* Named event prefix for indicating that a data buffer has been read */
75 #define PMGT_DATA_EVENT_PREFIX "TransarcAfsSpawnDataEvent"
77 /* event signals termination of a child process */
78 static pthread_cond_t childTermEvent;
81 /* Exported data values */
83 void *pmgt_spawnData = NULL;
84 size_t pmgt_spawnDataLen = 0;
87 /* General definitions */
89 #define DWORD_OF_ONES ((DWORD)0xFFFFFFFF) /* a common Win32 failure code */
96 /* ----------------- Signals ---------------- */
100 * SignalIsDefined() -- Determine if an integer value corresponds to a
101 * signal value defined for this platform.
104 SignalIsDefined(int signo)
108 if (signo >= 1 && signo <= (NSIG - 1)) {
109 /* value is in valid range; check specifics */
133 * DefaultActionHandler() -- Execute the default action for the given signal.
136 DefaultActionHandler(int signo)
144 /* default action is "exit" */
145 ExitProcess(PMGT_SIGSTATUS_ENCODE(signo));
151 /* default action is "core" */
152 /* Best we can do is to raise an exception that can be caught by
153 * Dr. Watson, which can in turn generate a crash dump file.
154 * The default exception handler will call ExitProcess() with
155 * our application-specific exception code.
157 RaiseException((DWORD) PMGT_SIGSTATUS_ENCODE(signo),
158 EXCEPTION_NONCONTINUABLE, 0, NULL);
163 /* default action is "ignore" */
166 /* default action is "stop" */
167 /* No good way to implement this from inside a process so ignore */
170 /* no default action for specified signal value; just ignore */
177 * ProcessSignal() -- Execute the specified or default handler for the given
178 * signal; reset the signal's disposition to SIG_DFL if necessary.
179 * If the signal's disposition is SIG_IGN then no processing takes place.
181 * ASSUMPTIONS: signo is valid (i.e., SignalIsDefined(signo) is TRUE).
184 ProcessSignal(int signo)
186 struct sigaction sigEntry;
188 if (signo != SIGKILL) {
189 /* serialize signals, but never block processing of SIGKILL */
190 (void)pthread_mutex_lock(&signalBlockLock);
193 /* fetch disposition of signo, updating it if necessary */
195 (void)pthread_mutex_lock(&signalTableLock);
196 sigEntry = signalTable[signo].action;
198 if ((sigEntry.sa_handler != SIG_IGN) && (sigEntry.sa_flags & SA_RESETHAND)
199 && (signo != SIGILL)) {
200 signalTable[signo].action.sa_handler = SIG_DFL;
202 (void)pthread_mutex_unlock(&signalTableLock);
204 /* execute handler */
206 if (sigEntry.sa_handler != SIG_IGN) {
207 if (sigEntry.sa_handler == SIG_DFL) {
208 sigEntry.sa_handler = DefaultActionHandler;
210 (*sigEntry.sa_handler) (signo);
213 if (signo != SIGKILL) {
214 (void)pthread_mutex_unlock(&signalBlockLock);
220 * RemoteSignalThread() -- Thread spawned to process remote signal.
222 * Param must be the signal number.
225 RemoteSignalThread(LPVOID param)
227 int signo = (int)(intptr_t)param;
230 if (SignalIsDefined(signo)) {
232 ProcessSignal(signo);
233 } else if (signo != 0) {
234 /* invalid signal value */
242 * RemoteSignalListenerThread() -- Thread spawned to receive and process
243 * remotely generated signals; never returns.
245 * Param must be a handle for a duplex server message pipe in blocking
249 RemoteSignalListenerThread(LPVOID param)
251 HANDLE sigPipeHandle = (HANDLE) param;
252 HMODULE hLib = LoadLibrary("AFSPROCMGMT.DLL");
255 /* wait for pipe client to connect */
257 if ((ConnectNamedPipe(sigPipeHandle, NULL))
258 || (GetLastError() == ERROR_PIPE_CONNECTED)) {
259 /* client connected; read signal value */
264 (sigPipeHandle, &signo, sizeof(signo), &bytesXfered, NULL))
265 && (bytesXfered == sizeof(signo))) {
266 HANDLE sigThreadHandle;
269 /* ACK signal to release sender */
270 (void)WriteFile(sigPipeHandle, &signo, sizeof(signo),
273 /* spawn thread to process signal; we do this so that
274 * we can always process a SIGKILL even if a signal handler
275 * invoked earlier fails to return (blocked/spinning).
277 sigThreadHandle = CreateThread(NULL, /* default security attr. */
278 0, /* default stack size */
279 RemoteSignalThread, (LPVOID) (intptr_t)signo, /* thread argument */
280 0, /* creation flags */
281 &sigThreadId); /* thread id */
283 if (sigThreadHandle != NULL) {
284 (void)CloseHandle(sigThreadHandle);
287 /* nothing to do if ReadFile, WriteFile or CreateThread fails. */
290 /* connect failed; this should never happen */
291 Sleep(2000); /* sleep 2 seconds to avoid tight loop */
294 (void)DisconnectNamedPipe(sigPipeHandle);
307 * pmgt_SigactionSet() -- Examine and/or specify the action for a given
308 * signal (Unix sigaction() semantics).
311 pmgt_SigactionSet(int signo, const struct sigaction *actionP,
312 struct sigaction *old_actionP)
314 /* validate arguments */
316 if (!SignalIsDefined(signo) || signo == SIGKILL) {
317 /* invalid signal value or signal can't be caught/ignored */
322 if (actionP && actionP->sa_handler == SIG_ERR) {
323 /* invalid signal disposition */
328 /* fetch and/or set disposition of signo */
330 (void)pthread_mutex_lock(&signalTableLock);
333 *old_actionP = signalTable[signo].action;
337 signalTable[signo].action = *actionP;
340 (void)pthread_mutex_unlock(&signalTableLock);
347 * pmgt_SignalSet() -- Specify the disposition for a given signal
348 * value (Unix signal() semantics).
350 void (__cdecl * pmgt_SignalSet(int signo, void (__cdecl * dispP) (int))) (int) {
351 struct sigaction newAction, oldAction;
353 /* construct action to request Unix signal() semantics */
355 newAction.sa_handler = dispP;
356 sigemptyset(&newAction.sa_mask);
357 newAction.sa_flags = SA_RESETHAND;
359 if (!pmgt_SigactionSet(signo, &newAction, &oldAction)) {
360 /* successfully set new signal action */
361 return oldAction.sa_handler;
363 /* failed to set signal action; errno will have been set */
370 * pmgt_SignalRaiseLocal() -- Raise a signal in this process (C raise()
374 pmgt_SignalRaiseLocal(int signo)
378 /* Process signal directly in the context of the calling thread.
379 * This is the same as if the signal had been raised in this process
380 * and this thread chosen to execute the handler.
383 if (SignalIsDefined(signo)) {
385 ProcessSignal(signo);
386 } else if (signo != 0) {
387 /* invalid signal value */
396 * pmgt_SignalRaiseLocalByName() -- Raise a signal in this process where
397 * the signal is specified by name (C raise() semantics).
399 * Upon successful completion, *libSigno is set to the process management
400 * library's constant value for signame.
402 * Note: exists to implement the native-signal redirector (redirect_nt.c),
403 * which can't include procmgmt.h and hence can't get the SIG* decls.
406 pmgt_SignalRaiseLocalByName(const char *signame, int *libSigno)
411 if (!strcmp(signame, "SIGHUP")) {
413 } else if (!strcmp(signame, "SIGINT")) {
415 } else if (!strcmp(signame, "SIGQUIT")) {
417 } else if (!strcmp(signame, "SIGILL")) {
419 } else if (!strcmp(signame, "SIGABRT")) {
421 } else if (!strcmp(signame, "SIGFPE")) {
423 } else if (!strcmp(signame, "SIGKILL")) {
425 } else if (!strcmp(signame, "SIGSEGV")) {
427 } else if (!strcmp(signame, "SIGTERM")) {
429 } else if (!strcmp(signame, "SIGUSR1")) {
431 } else if (!strcmp(signame, "SIGUSR2")) {
433 } else if (!strcmp(signame, "SIGCLD")) {
435 } else if (!strcmp(signame, "SIGCHLD")) {
437 } else if (!strcmp(signame, "SIGTSTP")) {
440 /* unknown signal name */
447 rc = pmgt_SignalRaiseLocal(signo);
454 * pmgt_SignalRaiseRemote() -- Raise a signal in the specified process (Unix
457 * Note: only supports sending signal to a specific (single) process.
460 pmgt_SignalRaiseRemote(pid_t pid, int signo)
463 char sigPipeName[sizeof(PMGT_SIGNAL_PIPE_PREFIX) + 20];
468 /* validate arguments */
470 if ((pid <= (pid_t) 0) || (!SignalIsDefined(signo) && signo != 0)) {
471 /* invalid pid or signo */
476 /* optimize for the "this process" case */
478 if (pid == (pid_t) GetCurrentProcessId()) {
479 return pmgt_SignalRaiseLocal(signo);
482 /* send signal to process via named pipe */
484 sprintf(sigPipeName, "%s%d", PMGT_SIGNAL_PIPE_PREFIX, (int)pid);
486 fsuccess = CallNamedPipe(sigPipeName, /* process pid's signal pipe */
487 &signo, /* data written to pipe */
488 sizeof(signo), /* size of data to write */
489 &signoACK, /* data read from pipe */
490 sizeof(signoACK), /* size of data read buffer */
491 &ackBytesRead, /* number of bytes actually read */
492 5 * 1000); /* 5 second timeout */
495 /* failed to send signal via named pipe */
498 if (signo == SIGKILL) {
499 /* could be a non-AFS process, which might still be kill-able */
503 OpenProcess(PROCESS_TERMINATE, FALSE, (DWORD) pid)) {
505 (procHandle, PMGT_SIGSTATUS_ENCODE(SIGKILL))) {
506 /* successfully killed process */
509 errno = nterr_nt2unix(GetLastError(), EPERM);
511 (void)CloseHandle(procHandle);
513 if (GetLastError() == ERROR_INVALID_PARAMETER) {
515 } else if (GetLastError() == ERROR_ACCESS_DENIED) {
518 errno = nterr_nt2unix(GetLastError(), EPERM);
522 /* couldn't open pipe so can't send (non-SIGKILL) signal */
523 errno = nterr_nt2unix(GetLastError(), EPERM);
533 /* ----------------- Processes ---------------- */
537 * StringArrayToString() -- convert a null-terminated array of strings,
538 * such as argv, into a single string of space-separated elements
539 * with each element quoted (in case it contains space characters
540 * or is of zero length).
543 StringArrayToString(char *strArray[])
549 for (strCount = 0; strArray[strCount] != NULL; strCount++) {
550 /* sum all string lengths */
551 byteCount += (int)strlen(strArray[strCount]);
554 /* put all strings into buffer; guarantee buffer is at least one char */
555 buffer = (char *)malloc(byteCount + (strCount * 3) /* quotes+space */ +1);
556 if (buffer != NULL) {
561 for (i = 0; i < strCount; i++) {
562 char *bufp = buffer + strlen(buffer);
564 if (i == strCount - 1) {
565 /* last string; no trailing space */
566 sprintf(bufp, "\"%s\"", strArray[i]);
568 sprintf(bufp, "\"%s\" ", strArray[i]);
578 * StringArrayToMultiString() -- convert a null-terminated array of strings,
579 * such as envp, into a multistring.
582 StringArrayToMultiString(char *strArray[])
588 for (strCount = 0; strArray[strCount] != NULL; strCount++) {
589 /* sum all string lengths */
590 byteCount += strlen(strArray[strCount]);
593 /* put all strings into buffer; guarantee buffer is at least two chars */
594 buffer = (char *)malloc(byteCount + strCount + 2);
595 if (buffer != NULL) {
596 if (byteCount == 0) {
603 for (i = 0; i < strCount; i++) {
604 int strLen = strlen(strArray[i]);
607 /* can not embed zero length string in a multistring */
608 strcpy(bufp, strArray[i]);
612 *bufp = '\0'; /* terminate multistring */
622 * ComputeWaitStatus() -- Compute an appropriate wait status value from
623 * a given process termination (exit) code.
626 ComputeWaitStatus(DWORD exitStatus)
630 if (PMGT_IS_SIGSTATUS(exitStatus)) {
631 /* child terminated due to an unhandled signal */
632 int signo = PMGT_SIGSTATUS_DECODE(exitStatus);
633 waitStatus = WSIGNALED_ENCODE(signo);
634 } else if (PMGT_IS_EXPSTATUS(exitStatus)) {
635 /* child terminated due to an uncaught exception */
638 switch (exitStatus) {
639 case EXCEPTION_FLT_DENORMAL_OPERAND:
640 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
641 case EXCEPTION_FLT_INEXACT_RESULT:
642 case EXCEPTION_FLT_INVALID_OPERATION:
643 case EXCEPTION_FLT_OVERFLOW:
644 case EXCEPTION_FLT_STACK_CHECK:
645 case EXCEPTION_FLT_UNDERFLOW:
646 case EXCEPTION_INT_DIVIDE_BY_ZERO:
647 case EXCEPTION_INT_OVERFLOW:
650 case EXCEPTION_PRIV_INSTRUCTION:
651 case EXCEPTION_ILLEGAL_INSTRUCTION:
661 waitStatus = WSIGNALED_ENCODE(signo);
663 /* child terminated normally */
664 waitStatus = WEXITED_ENCODE(exitStatus);
673 * CreateChildDataBuffer() -- Create and fill a named data buffer to pass to
674 * a child process, along with a corresponding buffer read event.
676 * ASSUMPTIONS: child process is linked with this process management library;
677 * otherwise no data transfer will take place.
680 CreateChildDataBuffer(DWORD pid, /* child pid */
681 void *datap, /* data to place in buffer */
682 size_t dataLen, /* size of data in bytes */
683 HANDLE * bufMemHandlep, /* buffer memory handle */
684 HANDLE * bufEventHandlep)
685 { /* buffer read event handle */
686 BOOL fsuccess = FALSE;
687 DWORD bufMemSize = dataLen + (DWORD)sizeof(size_t);
688 char bufMemName[sizeof(PMGT_DATA_MEM_PREFIX) + 20];
689 char bufEventName[sizeof(PMGT_DATA_EVENT_PREFIX) + 20];
691 sprintf(bufMemName, "%s%d", PMGT_DATA_MEM_PREFIX, (int)pid);
692 sprintf(bufEventName, "%s%d", PMGT_DATA_EVENT_PREFIX, (int)pid);
694 /* Create and initialize named shared memory and named event */
696 *bufMemHandlep = CreateFileMapping(INVALID_HANDLE_VALUE, /* page-file backed */
697 NULL, PAGE_READWRITE, 0, bufMemSize,
700 if (*bufMemHandlep != NULL) {
704 MapViewOfFile(*bufMemHandlep, FILE_MAP_WRITE, 0, 0, bufMemSize);
706 if (bufMemp != NULL) {
707 /* copy data into shared memory, prefixed with data size */
708 size_t *memp = (size_t *) bufMemp;
711 memcpy((void *)memp, datap, dataLen);
713 if (UnmapViewOfFile(bufMemp)) {
714 /* create buffer read event */
716 CreateEvent(NULL, FALSE /* manual reset */ ,
717 FALSE /* initial state */ ,
719 if (*bufEventHandlep != NULL) {
726 (void)CloseHandle(*bufMemHandlep);
731 *bufMemHandlep = *bufEventHandlep = NULL;
739 * ReadChildDataBuffer() -- Read data buffer passed to child from parent,
740 * if any, and place in allocated storage.
743 ReadChildDataBuffer(void **datap, /* allocated data buffer */
745 { /* size of data buffer returned */
746 BOOL fsuccess = FALSE;
747 char bufMemName[sizeof(PMGT_DATA_MEM_PREFIX) + 20];
748 char bufEventName[sizeof(PMGT_DATA_EVENT_PREFIX) + 20];
749 HANDLE bufMemHandle, bufEventHandle;
751 sprintf(bufMemName, "%s%d", PMGT_DATA_MEM_PREFIX,
752 (int)GetCurrentProcessId());
753 sprintf(bufEventName, "%s%d", PMGT_DATA_EVENT_PREFIX,
754 (int)GetCurrentProcessId());
756 /* Attempt to open named event and named shared memory */
758 bufEventHandle = OpenEvent(EVENT_MODIFY_STATE, FALSE, bufEventName);
760 if (bufEventHandle != NULL) {
761 bufMemHandle = OpenFileMapping(FILE_MAP_READ, FALSE, bufMemName);
763 if (bufMemHandle != NULL) {
766 bufMemp = MapViewOfFile(bufMemHandle, FILE_MAP_READ, 0, 0, 0);
768 if (bufMemp != NULL) {
769 /* read data size and data from shared memory */
770 size_t *memp = (size_t *) bufMemp;
773 *datap = (void *)malloc(*dataLen);
775 if (*datap != NULL) {
776 memcpy(*datap, (void *)memp, *dataLen);
779 (void)UnmapViewOfFile(bufMemp);
782 (void)CloseHandle(bufMemHandle);
785 (void)SetEvent(bufEventHandle);
786 (void)CloseHandle(bufEventHandle);
799 * ChildMonitorThread() -- Thread spawned to monitor status of child process.
801 * Param must be index into child process table.
804 ChildMonitorThread(LPVOID param)
806 int tidx = (int)(intptr_t)param;
807 HANDLE childProcHandle;
811 /* retrieve handle for child process from process table and duplicate */
813 (void)pthread_mutex_lock(&procTableLock);
815 fsuccess = DuplicateHandle(GetCurrentProcess(), /* source process handle */
816 procTable[tidx].p_handle, /* source handle to dup */
817 GetCurrentProcess(), /* target process handle */
818 &childProcHandle, /* target handle (duplicate) */
819 0, /* access (ignored here) */
820 FALSE, /* not inheritable */
821 DUPLICATE_SAME_ACCESS);
823 (void)pthread_mutex_unlock(&procTableLock);
826 /* wait for child process to terminate */
828 if (WaitForSingleObject(childProcHandle, INFINITE) == WAIT_OBJECT_0) {
829 /* child process terminated; mark in table and signal event */
830 (void)pthread_mutex_lock(&procTableLock);
832 procTable[tidx].p_terminated = TRUE;
833 (void)GetExitCodeProcess(childProcHandle,
834 &procTable[tidx].p_status);
837 (void)pthread_mutex_unlock(&procTableLock);
839 (void)pthread_cond_broadcast(&childTermEvent);
841 /* process/raise SIGCHLD; do last in case handler never returns */
842 ProcessSignal(SIGCHLD);
846 (void)CloseHandle(childProcHandle);
849 /* note: nothing can be done if DuplicateHandle() or WaitForSingleObject()
850 * fail; however, this should never happen.
858 * pmgt_ProcessSpawnVEB() -- Spawn a process (Unix fork()/execve() semantics)
860 * Returns pid of the child process ((pid_t)-1 on failure with errno set).
862 * Notes: A senvp value of NULL results in Unix fork()/execv() semantics.
863 * Open files are not inherited; child's stdin, stdout, and stderr
864 * are set to parent's console.
865 * If spath does not specify a filename extension ".exe" is used.
866 * If sdatap is not NULL, and sdatalen > 0, data is passed to child.
867 * The spath and sargv[] strings must not contain quote chars (").
869 * ASSUMPTIONS: sargv[0] is the same as spath (or its last component).
872 pmgt_ProcessSpawnVEB(const char *spath, char *sargv[], char *senvp[],
873 void *sdatap, size_t sdatalen)
876 char *pathbuf, *argbuf, *envbuf;
877 char pathext[_MAX_EXT];
878 STARTUPINFO startInfo;
879 PROCESS_INFORMATION procInfo;
880 HANDLE monitorHandle = NULL;
881 HANDLE bufMemHandle, bufEventHandle;
882 DWORD monitorId, createFlags;
883 BOOL passingBuffer = (sdatap != NULL && sdatalen > 0);
887 /* verify arguments */
888 if (!spath || !sargv) {
891 } else if (*spath == '\0') {
896 /* create path with .exe extension if no filename extension supplied */
897 if (!(pathbuf = (char *)malloc(strlen(spath) + 5 /* .exe */ ))) {
899 return ((pid_t) - 1);
901 strcpy(pathbuf, spath);
903 _splitpath(pathbuf, NULL, NULL, NULL, pathext);
904 if (*pathext == '\0') {
905 /* no filename extension supplied for spath; .exe is assumed */
906 strcat(pathbuf, ".exe");
909 /* create command line argument string */
910 argbuf = StringArrayToString(sargv);
915 return ((pid_t) - 1);
918 /* create environment variable block (multistring) */
920 /* use environment variables provided */
921 envbuf = StringArrayToMultiString(senvp);
927 return ((pid_t) - 1);
930 /* use default environment variables */
934 /* set process creation flags */
935 createFlags = CREATE_SUSPENDED | NORMAL_PRIORITY_CLASS;
937 if (getenv(PMGT_SPAWN_DETACHED_ENV_NAME) != NULL) {
938 createFlags |= DETACHED_PROCESS;
941 /* clear start-up info; use defaults */
942 memset((void *)&startInfo, 0, sizeof(startInfo));
943 startInfo.cb = sizeof(startInfo);
945 /* perform the following as a logically atomic unit:
946 * 1) allocate a process table entry
947 * 2) spawn child process (suspended)
948 * 3) create data buffer to pass (optional)
949 * 4) initialize process table entry
950 * 5) start child watcher thread
951 * 6) resume spawned child process
954 (void)pthread_mutex_lock(&procTableLock);
956 for (tidx = 0; tidx < PMGT_CHILD_MAX; tidx++) {
957 if (procTable[tidx].p_handle == NULL
958 && procTable[tidx].p_reserved == FALSE) {
959 procTable[tidx].p_reserved = TRUE;
963 (void)pthread_mutex_unlock(&procTableLock);
965 if (tidx >= PMGT_CHILD_MAX) {
966 /* no space left in process table */
975 fsuccess = CreateProcess(pathbuf, /* executable path */
976 argbuf, /* command line argument string */
977 NULL, /* default process security attr */
978 NULL, /* default thread security attr */
979 FALSE, /* do NOT inherit handles */
980 createFlags, /* creation control flags */
981 envbuf, /* environment variable block */
982 NULL, /* current directory is that of parent */
983 &startInfo, /* startup info block */
986 lasterror = GetLastError();
992 /* failed to spawn process */
993 errno = nterr_nt2unix(lasterror, ENOENT);
995 (void)pthread_mutex_lock(&procTableLock);
996 procTable[tidx].p_reserved = FALSE; /* mark entry as not reserved */
997 (void)pthread_mutex_unlock(&procTableLock);
1002 if (passingBuffer) {
1003 /* create named data buffer and read event for child */
1005 CreateChildDataBuffer(procInfo.dwProcessId, sdatap, sdatalen,
1006 &bufMemHandle, &bufEventHandle);
1008 (void)pthread_mutex_lock(&procTableLock);
1009 procTable[tidx].p_reserved = FALSE; /* mark entry not reserved */
1010 (void)pthread_mutex_unlock(&procTableLock);
1012 (void)TerminateProcess(procInfo.hProcess,
1013 PMGT_SIGSTATUS_ENCODE(SIGKILL));
1014 (void)CloseHandle(procInfo.hThread);
1015 (void)CloseHandle(procInfo.hProcess);
1022 (void)pthread_mutex_lock(&procTableLock);
1024 procTable[tidx].p_handle = procInfo.hProcess;
1025 procTable[tidx].p_id = procInfo.dwProcessId;
1026 procTable[tidx].p_terminated = FALSE;
1030 /* Note: must hold procTableLock during monitor thread creation so
1031 * that if creation fails we can clean up process table before another
1032 * thread has a chance to see this procTable entry. Continue to hold
1033 * procTableLock while resuming child process, since the procTable
1034 * entry contains a copy of the child process handle which we might use.
1036 monitorHandle = CreateThread(NULL, /* default security attr. */
1037 0, /* default stack size */
1038 ChildMonitorThread, (LPVOID)(intptr_t) tidx, /* thread argument */
1039 0, /* creation flags */
1040 &monitorId); /* thread id */
1042 if (monitorHandle == NULL) {
1043 /* failed to start child monitor thread */
1044 procTable[tidx].p_handle = NULL; /* invalidate table entry */
1045 procTable[tidx].p_reserved = FALSE; /* mark entry as not reserved */
1048 (void)pthread_mutex_unlock(&procTableLock);
1050 (void)TerminateProcess(procInfo.hProcess,
1051 PMGT_SIGSTATUS_ENCODE(SIGKILL));
1052 (void)CloseHandle(procInfo.hThread);
1053 (void)CloseHandle(procInfo.hProcess);
1055 if (passingBuffer) {
1056 (void)CloseHandle(bufMemHandle);
1057 (void)CloseHandle(bufEventHandle);
1064 /* Resume child process, which was created suspended to implement spawn
1065 * atomically. If resumption fails, which it never should, terminate
1066 * the child process with a status of SIGKILL. Spawn still succeeds and
1067 * the net result is the same as if the child process received a spurious
1068 * SIGKILL signal; the child monitor thread will then handle this.
1070 if (ResumeThread(procInfo.hThread) == DWORD_OF_ONES) {
1071 (void)TerminateProcess(procInfo.hProcess,
1072 PMGT_SIGSTATUS_ENCODE(SIGKILL));
1074 if (passingBuffer) {
1075 /* child will never read data buffer */
1076 (void)SetEvent(bufEventHandle);
1080 (void)pthread_mutex_unlock(&procTableLock);
1082 (void)CloseHandle(procInfo.hThread);
1083 (void)CloseHandle(monitorHandle);
1085 /* After spawn returns, signals can not be sent to the new child process
1086 * until that child initializes its signal-receiving mechanism (assuming
1087 * the child is linked with this library). Shorten (but sadly don't
1088 * eliminate) this window of opportunity for failure by yielding this
1089 * thread's time slice.
1091 (void)SwitchToThread();
1093 /* If passing a data buffer to child, wait until child reads buffer
1094 * before closing handles and thus freeing resources; if don't wait
1095 * then parent can not safely exit immediately after returning from
1096 * this call (hence why wait is not done in a background thread).
1098 if (passingBuffer) {
1099 WaitForSingleObject(bufEventHandle, 10000);
1100 /* note: if wait times out, child may not get to read buffer */
1101 (void)CloseHandle(bufMemHandle);
1102 (void)CloseHandle(bufEventHandle);
1105 return (pid_t) procInfo.dwProcessId;
1111 * pmgt_ProcessWaitPid() -- Wait for child process status; i.e., wait
1112 * for child to terminate (Unix waitpid() semantics).
1114 * Note: does not support waiting for process in group (i.e., pid
1115 * equals (pid_t)0 or pid is less than (pid_t)-1.
1118 pmgt_ProcessWaitPid(pid_t pid, int *statusP, int options)
1122 BOOL statusFound = FALSE;
1125 /* validate arguments */
1126 if (pid < (pid_t) - 1 || pid == (pid_t) 0) {
1131 /* determine how long caller is willing to wait for child */
1133 waitTime = (options & WNOHANG) ? 0 : INFINITE;
1135 /* get child status */
1137 (void)pthread_mutex_lock(&procTableLock);
1140 BOOL waitForChild = FALSE;
1142 if (procEntryCount == 0) {
1143 /* no child processes */
1147 /* determine if status is available for specified child id */
1149 if (pid == (pid_t) - 1) {
1150 /* CASE 1: pid matches any child id */
1152 if (procTermCount == 0) {
1153 /* status not available for any child ... */
1154 if (waitTime == 0) {
1155 /* ... and caller is not willing to wait */
1158 /* ... but caller is willing to wait */
1159 waitForChild = TRUE;
1162 /* status available for some child; locate table entry */
1163 for (tidx = 0; tidx < PMGT_CHILD_MAX; tidx++) {
1164 if (procTable[tidx].p_handle != NULL
1165 && procTable[tidx].p_terminated == TRUE) {
1172 /* should never happen; indicates a bug */
1173 errno = EINTR; /* plausible lie for failure */
1179 /* CASE 2: pid must match a specific child id */
1181 /* locate table entry */
1182 for (tidx = 0; tidx < PMGT_CHILD_MAX; tidx++) {
1183 if (procTable[tidx].p_handle != NULL
1184 && procTable[tidx].p_id == (DWORD) pid) {
1189 if (tidx >= PMGT_CHILD_MAX) {
1190 /* pid does not match any child id */
1193 } else if (procTable[tidx].p_terminated == FALSE) {
1194 /* status not available for specified child ... */
1195 if (waitTime == 0) {
1196 /* ... and caller is not willing to wait */
1199 /* ... but caller is willing to wait */
1200 waitForChild = TRUE;
1203 /* status is available for specified child */
1210 (void)pthread_cond_wait(&childTermEvent, &procTableLock);
1217 /* child status available */
1219 *statusP = ComputeWaitStatus(procTable[tidx].p_status);
1221 rc = (pid_t) procTable[tidx].p_id;
1223 /* clean up process table */
1224 (void)CloseHandle(procTable[tidx].p_handle);
1225 procTable[tidx].p_handle = NULL;
1226 procTable[tidx].p_reserved = FALSE;
1232 (void)pthread_mutex_unlock(&procTableLock);
1241 /* ----------------- General ---------------- */
1246 * PmgtLibraryInitialize() -- Initialize process management library.
1249 PmgtLibraryInitialize(void)
1252 HANDLE sigPipeHandle;
1253 char sigPipeName[sizeof(PMGT_SIGNAL_PIPE_PREFIX) + 20];
1254 HANDLE sigListenerHandle;
1255 DWORD sigListenerId;
1257 /* initialize mutex locks and condition variables */
1259 if ((rc = pthread_mutex_init(&signalTableLock, NULL))
1260 || (rc = pthread_mutex_init(&signalBlockLock, NULL))
1261 || (rc = pthread_mutex_init(&procTableLock, NULL))
1262 || (rc = pthread_cond_init(&childTermEvent, NULL))) {
1267 /* initialize signal disposition table */
1269 for (i = 0; i < NSIG; i++) {
1270 if (SignalIsDefined(i)) {
1271 /* initialize to default action for defined signals */
1272 signalTable[i].action.sa_handler = SIG_DFL;
1273 sigemptyset(&signalTable[i].action.sa_mask);
1274 signalTable[i].action.sa_flags = 0;
1276 /* initialize to ignore for undefined signals */
1277 signalTable[i].action.sa_handler = SIG_IGN;
1281 /* initialize child process table */
1283 for (i = 0; i < PMGT_CHILD_MAX; i++) {
1284 procTable[i].p_handle = NULL;
1285 procTable[i].p_reserved = FALSE;
1290 /* retrieve data buffer passed from parent in spawn, if any */
1292 if (!ReadChildDataBuffer(&pmgt_spawnData, &pmgt_spawnDataLen)) {
1293 pmgt_spawnData = NULL;
1294 pmgt_spawnDataLen = 0;
1297 /* create named pipe for delivering signals to this process */
1299 sprintf(sigPipeName, "%s%d", PMGT_SIGNAL_PIPE_PREFIX,
1300 (int)GetCurrentProcessId());
1302 sigPipeHandle = CreateNamedPipe(sigPipeName, /* pipe for this process */
1303 PIPE_ACCESS_DUPLEX | /* full duplex pipe */
1304 WRITE_DAC, /* DACL write access */
1305 PIPE_TYPE_MESSAGE | /* message type pipe */
1306 PIPE_READMODE_MESSAGE | /* message read-mode */
1307 PIPE_WAIT, /* blocking mode */
1308 1, /* max of 1 pipe instance */
1309 64, /* output buffer size (advisory) */
1310 64, /* input buffer size (advisory) */
1311 1000, /* 1 sec default client timeout */
1312 NULL); /* default security attr. */
1314 if (sigPipeHandle == INVALID_HANDLE_VALUE) {
1315 /* failed to create signal pipe */
1316 errno = nterr_nt2unix(GetLastError(), EIO);
1320 /* add entry to signal pipe ACL granting local Administrators R/W access */
1322 (void)ObjectDaclEntryAdd(sigPipeHandle, SE_KERNEL_OBJECT,
1323 LocalAdministratorsGroup,
1324 GENERIC_READ | GENERIC_WRITE, GRANT_ACCESS,
1327 /* start signal pipe listener thread */
1329 sigListenerHandle = CreateThread(NULL, /* default security attr. */
1330 0, /* default stack size */
1331 RemoteSignalListenerThread, (LPVOID) sigPipeHandle, /* thread argument */
1332 0, /* creation flags */
1333 &sigListenerId); /* thread id */
1335 if (sigListenerHandle != NULL) {
1336 /* listener thread started; bump priority */
1337 (void)SetThreadPriority(sigListenerHandle, THREAD_PRIORITY_HIGHEST);
1338 (void)CloseHandle(sigListenerHandle);
1340 /* failed to start listener thread */
1342 (void)CloseHandle(sigPipeHandle);
1346 /* redirect native NT signals into this process management library */
1348 if (pmgt_RedirectNativeSignals()) {
1349 /* errno set by called function */
1358 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
1359 * function in the MSVC runtime DLL (msvcrt.dll).
1361 * Note: the system serializes calls to this function.
1364 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
1365 DWORD reason, /* reason function is being called */
1367 { /* reserved for future use */
1369 case DLL_PROCESS_ATTACH:
1370 /* library is being attached to a process */
1371 if (PmgtLibraryInitialize()) {
1372 /* failed to initialize library */
1376 /* disable thread attach/detach notifications */
1377 (void)DisableThreadLibraryCalls(dllInstHandle);
1379 case DLL_PROCESS_DETACH:
1380 pmgt_RestoreNativeSignals();