2 * processes.c: Process handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002-2011 Novell, Inc.
8 * Copyright 2011 Xamarin Inc
19 #include <sys/types.h>
25 #include <sys/resource.h>
27 #ifdef HAVE_SYS_PARAM_H
28 #include <sys/param.h>
32 #ifdef HAVE_SYS_MKDEV_H
33 #include <sys/mkdev.h>
36 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
38 #include <TargetConditionals.h>
39 #include <sys/resource.h>
46 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
48 #include <sys/sysctl.h>
49 # if !defined(__OpenBSD__)
50 # include <sys/utsname.h>
54 #ifdef PLATFORM_SOLARIS
55 /* procfs.h cannot be included if this define is set, but it seems to work fine if it is undefined */
56 #if _FILE_OFFSET_BITS == 64
57 #undef _FILE_OFFSET_BITS
59 #define _FILE_OFFSET_BITS 64
66 #include <KernelKit.h>
69 #include <mono/io-layer/wapi.h>
70 #include <mono/io-layer/wapi-private.h>
71 #include <mono/io-layer/handles-private.h>
72 #include <mono/io-layer/misc-private.h>
73 #include <mono/io-layer/process-private.h>
74 #include <mono/io-layer/threads.h>
75 #include <mono/utils/strenc.h>
76 #include <mono/utils/mono-path.h>
77 #include <mono/io-layer/timefuncs-private.h>
78 #include <mono/utils/mono-time.h>
79 #include <mono/utils/mono-membar.h>
80 #include <mono/utils/mono-mutex.h>
81 #include <mono/utils/mono-signal-handler.h>
83 /* The process' environment strings */
84 #if defined(__APPLE__) && !defined (__arm__)
85 /* Apple defines this in crt_externs.h but doesn't provide that header for
86 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
87 * in fact exist on all implementations (so far)
89 gchar ***_NSGetEnviron(void);
90 #define environ (*_NSGetEnviron())
92 extern char **environ;
96 #define DEBUG(...) g_message(__VA_ARGS__)
97 #define DEBUG_ENABLED 1
102 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable);
103 static void process_close (gpointer handle, gpointer data);
104 static gboolean is_pid_valid (pid_t pid);
106 #if !defined(__OpenBSD__)
108 open_process_map (int pid, const char *mode);
111 struct _WapiHandleOps _wapi_process_ops = {
112 process_close, /* close_shared */
116 process_wait, /* special_wait */
121 static struct sigaction previous_chld_sa;
123 static mono_once_t process_sig_chld_once = MONO_ONCE_INIT;
124 static void process_add_sigchld_handler (void);
126 /* The signal-safe logic to use mono_processes goes like this:
127 * - The list must be safe to traverse for the signal handler at all times.
128 * It's safe to: prepend an entry (which is a single store to 'mono_processes'),
129 * unlink an entry (assuming the unlinked entry isn't freed and doesn't
130 * change its 'next' pointer so that it can still be traversed).
131 * When cleaning up we first unlink an entry, then we verify that
132 * the read lock isn't locked. Then we can free the entry, since
133 * we know that nobody is using the old version of the list (including
134 * the unlinked entry).
135 * We also need to lock when adding and cleaning up so that those two
136 * operations don't mess with eachother. (This lock is not used in the
139 static struct MonoProcess *mono_processes = NULL;
140 static volatile gint32 mono_processes_read_lock = 0;
141 static volatile gint32 mono_processes_cleaning_up = 0;
142 static mono_mutex_t mono_processes_mutex;
143 static void mono_processes_cleanup (void);
145 static mono_once_t process_current_once=MONO_ONCE_INIT;
146 static gpointer current_process=NULL;
147 static char *cli_launcher;
149 static mono_once_t process_ops_once=MONO_ONCE_INIT;
151 static void process_ops_init (void)
153 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
154 WAPI_HANDLE_CAP_WAIT |
155 WAPI_HANDLE_CAP_SPECIAL_WAIT);
159 /* Check if a pid is valid - i.e. if a process exists with this pid. */
160 static gboolean is_pid_valid (pid_t pid)
162 gboolean result = FALSE;
164 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
165 if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
167 #elif defined(__HAIKU__)
169 if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
172 gchar *dir = g_strdup_printf ("/proc/%d", pid);
173 if (!access (dir, F_OK))
181 static void process_set_defaults (struct _WapiHandle_process *process_handle)
183 /* These seem to be the defaults on w2k */
184 process_handle->min_working_set = 204800;
185 process_handle->max_working_set = 1413120;
187 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
191 len16 (const gunichar2 *str)
202 utf16_concat (const gunichar2 *first, ...)
209 va_start (args, first);
210 total += len16 (first);
211 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
216 ret = g_new (gunichar2, total + 1);
222 for (s = first; *s != 0; s++)
224 va_start (args, first);
225 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
228 for (p = s; *p != 0; p++)
236 #ifdef PLATFORM_MACOSX
238 /* 0 = no detection; -1 = not 10.5 or higher; 1 = 10.5 or higher */
239 static int osx_10_5_or_higher;
242 detect_osx_10_5_or_higher (void)
248 if (uname (&u) != 0){
249 osx_10_5_or_higher = 1;
257 osx_10_5_or_higher = -1;
259 osx_10_5_or_higher = 1;
263 is_macos_10_5_or_higher (void)
265 if (osx_10_5_or_higher == 0)
266 detect_osx_10_5_or_higher ();
268 return (osx_10_5_or_higher == 1);
272 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
273 static const gunichar2 *utf16_space = utf16_space_bytes;
274 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
275 static const gunichar2 *utf16_quote = utf16_quote_bytes;
280 print_utf16 (gunichar2 *str)
284 res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
285 g_print ("%s\n", res);
290 /* Implemented as just a wrapper around CreateProcess () */
291 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
294 WapiProcessInformation process_info;
298 /* w2k just segfaults here, but we can do better than
301 SetLastError (ERROR_INVALID_PARAMETER);
305 if (sei->lpFile == NULL) {
306 /* w2k returns TRUE for this, for some reason. */
310 /* Put both executable and parameters into the second argument
311 * to CreateProcess (), so it searches $PATH. The conversion
312 * into and back out of utf8 is because there is no
313 * g_strdup_printf () equivalent for gunichar2 :-(
315 args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
317 SetLastError (ERROR_INVALID_DATA);
320 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
321 CREATE_UNICODE_ENVIRONMENT, NULL,
322 sei->lpDirectory, NULL, &process_info);
325 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
329 static char *handler;
330 static gunichar2 *handler_utf16;
332 if (handler_utf16 == (gunichar2 *)-1)
335 #ifdef PLATFORM_MACOSX
336 handler = g_strdup ("/usr/bin/open");
339 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
340 * if that fails, try to use gnome-open, then kfmclient
342 handler = g_find_program_in_path ("xdg-open");
343 if (handler == NULL){
344 handler = g_find_program_in_path ("gnome-open");
345 if (handler == NULL){
346 handler = g_find_program_in_path ("kfmclient");
347 if (handler == NULL){
348 handler_utf16 = (gunichar2 *) -1;
351 /* kfmclient needs exec argument */
353 handler = g_strconcat (old, " exec",
360 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
363 /* Put quotes around the filename, in case it's a url
364 * that contains #'s (CreateProcess() calls
365 * g_shell_parse_argv(), which deliberately throws
366 * away anything after an unquoted #). Fixes bug
369 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
370 sei->lpFile, utf16_quote,
371 sei->lpParameters == NULL ? NULL : utf16_space,
372 sei->lpParameters, NULL);
374 SetLastError (ERROR_INVALID_DATA);
377 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
378 CREATE_UNICODE_ENVIRONMENT, NULL,
379 sei->lpDirectory, NULL, &process_info);
382 if (GetLastError () != ERROR_OUTOFMEMORY)
383 SetLastError (ERROR_INVALID_DATA);
386 /* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
387 CloseHandle (process_info.hProcess);
388 process_info.hProcess = NULL;
391 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
392 sei->hProcess = process_info.hProcess;
394 CloseHandle (process_info.hProcess);
401 is_managed_binary (const gchar *filename)
403 int original_errno = errno;
404 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
405 int file = open (filename, O_RDONLY | O_LARGEFILE);
407 int file = open (filename, O_RDONLY);
410 unsigned char buffer[8];
411 off_t file_size, optional_header_offset;
412 off_t pe_header_offset;
413 gboolean managed = FALSE;
415 guint32 first_word, second_word;
417 /* If we are unable to open the file, then we definitely
418 * can't say that it is managed. The child mono process
419 * probably wouldn't be able to open it anyway.
422 errno = original_errno;
426 /* Retrieve the length of the file for future sanity checks. */
427 file_size = lseek (file, 0, SEEK_END);
428 lseek (file, 0, SEEK_SET);
430 /* We know we need to read a header field at offset 60. */
434 num_read = read (file, buffer, 2);
436 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
439 new_offset = lseek (file, 60, SEEK_SET);
441 if (new_offset != 60)
444 num_read = read (file, buffer, 4);
448 pe_header_offset = buffer[0]
453 if (pe_header_offset + 24 > file_size)
456 new_offset = lseek (file, pe_header_offset, SEEK_SET);
458 if (new_offset != pe_header_offset)
461 num_read = read (file, buffer, 4);
463 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
467 * Verify that the header we want in the optional header data
468 * is present in this binary.
470 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
472 if (new_offset != pe_header_offset + 20)
475 num_read = read (file, buffer, 2);
477 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
480 /* Read the CLR header address and size fields. These will be
481 * zero if the binary is not managed.
483 optional_header_offset = pe_header_offset + 24;
484 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
486 if (new_offset != optional_header_offset + 208)
489 num_read = read (file, buffer, 8);
491 /* We are not concerned with endianness, only with
492 * whether it is zero or not.
494 first_word = *(guint32 *)&buffer[0];
495 second_word = *(guint32 *)&buffer[4];
497 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
504 errno = original_errno;
508 gboolean CreateProcessWithLogonW (const gunichar2 *username,
509 const gunichar2 *domain,
510 const gunichar2 *password,
511 const guint32 logonFlags,
512 const gunichar2 *appname,
513 const gunichar2 *cmdline,
514 guint32 create_flags,
516 const gunichar2 *cwd,
517 WapiStartupInfo *startup,
518 WapiProcessInformation *process_info)
520 /* FIXME: use user information */
521 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
525 is_executable (const char *prog)
528 if (access (prog, X_OK) != 0)
530 if (stat (prog, &buf))
532 if (S_ISREG (buf.st_mode))
538 switchDirectorySeparators(gchar *path)
540 size_t i, pathLength = strlen(path);
542 /* Turn all the slashes round the right way, except for \' */
543 /* There are probably other characters that need to be excluded as well. */
544 for (i = 0; i < pathLength; i++)
546 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' ) {
552 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
553 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
554 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
555 gboolean inherit_handles, guint32 create_flags,
556 gpointer new_environ, const gunichar2 *cwd,
557 WapiStartupInfo *startup,
558 WapiProcessInformation *process_info)
560 gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
561 guint32 i, env_count = 0;
562 gboolean ret = FALSE;
564 struct _WapiHandle_process process_handle = {0}, *process_handle_data;
566 int in_fd, out_fd, err_fd;
569 int startup_pipe [2] = {-1, -1};
571 struct MonoProcess *mono_process;
572 gboolean fork_failed = FALSE;
574 mono_once (&process_ops_once, process_ops_init);
575 mono_once (&process_sig_chld_once, process_add_sigchld_handler);
577 /* appname and cmdline specify the executable and its args:
579 * If appname is not NULL, it is the name of the executable.
580 * Otherwise the executable is the first token in cmdline.
582 * Executable searching:
584 * If appname is not NULL, it can specify the full path and
585 * file name, or else a partial name and the current directory
586 * will be used. There is no additional searching.
588 * If appname is NULL, the first whitespace-delimited token in
589 * cmdline is used. If the name does not contain a full
590 * directory path, the search sequence is:
592 * 1) The directory containing the current process
593 * 2) The current working directory
594 * 3) The windows system directory (Ignored)
595 * 4) The windows directory (Ignored)
598 * Just to make things more interesting, tokens can contain
599 * white space if they are surrounded by quotation marks. I'm
600 * beginning to understand just why windows apps are generally
601 * so crap, with an API like this :-(
603 if (appname != NULL) {
604 cmd = mono_unicode_to_external (appname);
606 DEBUG ("%s: unicode conversion returned NULL",
609 SetLastError (ERROR_PATH_NOT_FOUND);
613 switchDirectorySeparators(cmd);
616 if (cmdline != NULL) {
617 args = mono_unicode_to_external (cmdline);
619 DEBUG ("%s: unicode conversion returned NULL", __func__);
621 SetLastError (ERROR_PATH_NOT_FOUND);
627 dir = mono_unicode_to_external (cwd);
629 DEBUG ("%s: unicode conversion returned NULL", __func__);
631 SetLastError (ERROR_PATH_NOT_FOUND);
635 /* Turn all the slashes round the right way */
636 switchDirectorySeparators(dir);
640 /* We can't put off locating the executable any longer :-( */
643 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
644 /* Strip off the drive letter. I can't
645 * believe that CP/M holdover is still
648 g_memmove (cmd, cmd+2, strlen (cmd)-2);
649 cmd[strlen (cmd)-2] = '\0';
652 unquoted = g_shell_unquote (cmd, NULL);
653 if (unquoted[0] == '/') {
654 /* Assume full path given */
655 prog = g_strdup (unquoted);
657 /* Executable existing ? */
658 if (!is_executable (prog)) {
659 DEBUG ("%s: Couldn't find executable %s",
662 SetLastError (ERROR_FILE_NOT_FOUND);
666 /* Search for file named by cmd in the current
669 char *curdir = g_get_current_dir ();
671 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
674 /* And make sure it's executable */
675 if (!is_executable (prog)) {
676 DEBUG ("%s: Couldn't find executable %s",
679 SetLastError (ERROR_FILE_NOT_FOUND);
685 args_after_prog = args;
690 /* Dig out the first token from args, taking quotation
694 /* First, strip off all leading whitespace */
695 args = g_strchug (args);
697 /* args_after_prog points to the contents of args
698 * after token has been set (otherwise argv[0] is
701 args_after_prog = args;
703 /* Assume the opening quote will always be the first
706 if (args[0] == '\"' || args [0] == '\'') {
708 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
709 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
710 /* We found the first token */
711 token = g_strndup (args+1, i-1);
712 args_after_prog = g_strchug (args + i + 1);
714 /* Quotation mark appeared in the
715 * middle of the token. Just give the
716 * whole first token, quotes and all,
723 /* No quote mark, or malformed */
724 for (i = 0; args[i] != '\0'; i++) {
725 if (g_ascii_isspace (args[i])) {
726 token = g_strndup (args, i);
727 args_after_prog = args + i + 1;
733 if (token == NULL && args[0] != '\0') {
734 /* Must be just one token in the string */
735 token = g_strdup (args);
736 args_after_prog = NULL;
741 DEBUG ("%s: Couldn't find what to exec", __func__);
743 SetLastError (ERROR_PATH_NOT_FOUND);
747 /* Turn all the slashes round the right way. Only for
750 switchDirectorySeparators(token);
752 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
753 /* Strip off the drive letter. I can't
754 * believe that CP/M holdover is still
757 g_memmove (token, token+2, strlen (token)-2);
758 token[strlen (token)-2] = '\0';
761 if (token[0] == '/') {
762 /* Assume full path given */
763 prog = g_strdup (token);
765 /* Executable existing ? */
766 if (!is_executable (prog)) {
767 DEBUG ("%s: Couldn't find executable %s",
770 SetLastError (ERROR_FILE_NOT_FOUND);
775 char *curdir = g_get_current_dir ();
777 /* FIXME: Need to record the directory
778 * containing the current process, and check
779 * that for the new executable as the first
783 prog = g_strdup_printf ("%s/%s", curdir, token);
786 /* I assume X_OK is the criterion to use,
789 if (!is_executable (prog)) {
791 prog = g_find_program_in_path (token);
793 DEBUG ("%s: Couldn't find executable %s", __func__, token);
796 SetLastError (ERROR_FILE_NOT_FOUND);
805 DEBUG ("%s: Exec prog [%s] args [%s]", __func__, prog,
808 /* Check for CLR binaries; if found, we will try to invoke
809 * them using the same mono binary that started us.
811 if (is_managed_binary (prog)) {
812 gunichar2 *newapp = NULL, *newcmd;
816 newapp = mono_unicode_from_external (cli_launcher, &bytes_ignored);
818 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
820 if (newapp != NULL) {
821 if (appname != NULL) {
822 newcmd = utf16_concat (newapp, utf16_space,
823 appname, utf16_space,
826 newcmd = utf16_concat (newapp, utf16_space,
830 g_free ((gunichar2 *)newapp);
832 if (newcmd != NULL) {
833 ret = CreateProcess (NULL, newcmd,
837 create_flags, new_environ,
841 g_free ((gunichar2 *)newcmd);
848 if (args_after_prog != NULL && *args_after_prog) {
851 qprog = g_shell_quote (prog);
852 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
855 full_prog = g_shell_quote (prog);
858 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
860 g_message ("CreateProcess: %s\n", gerr->message);
866 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
867 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
868 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
869 err_fd = GPOINTER_TO_UINT (startup->hStdError);
871 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
872 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
873 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
876 g_strlcpy (process_handle.proc_name, prog,
877 _WAPI_PROC_NAME_MAX_LEN - 1);
879 process_set_defaults (&process_handle);
881 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
882 if (handle == _WAPI_HANDLE_INVALID) {
883 g_warning ("%s: error creating process handle", __func__);
886 SetLastError (ERROR_OUTOFMEMORY);
890 /* new_environ is a block of NULL-terminated strings, which
891 * is itself NULL-terminated. Of course, passing an array of
892 * string pointers would have made things too easy :-(
894 * If new_environ is not NULL it specifies the entire set of
895 * environment variables in the new process. Otherwise the
896 * new process inherits the same environment.
898 if (new_environ != NULL) {
899 gunichar2 *new_environp;
901 /* Count the number of strings */
902 for (new_environp = (gunichar2 *)new_environ; *new_environp;
905 while (*new_environp) {
910 /* +2: one for the process handle value, and the last
913 env_strings = g_new0 (gchar *, env_count + 2);
915 /* Copy each environ string into 'strings' turning it
916 * into utf8 (or the requested encoding) at the same
920 for (new_environp = (gunichar2 *)new_environ; *new_environp;
922 env_strings[env_count] = mono_unicode_to_external (new_environp);
924 while (*new_environp) {
929 for (i = 0; environ[i] != NULL; i++) {
933 /* +2: one for the process handle value, and the last
936 env_strings = g_new0 (gchar *, env_count + 2);
938 /* Copy each environ string into 'strings' turning it
939 * into utf8 (or the requested encoding) at the same
943 for (i = 0; environ[i] != NULL; i++) {
944 env_strings[env_count] = g_strdup (environ[i]);
948 /* pass process handle info to the child, so it doesn't have
949 * to do an expensive search over the whole list
951 if (env_strings != NULL) {
952 struct _WapiHandleUnshared *handle_data;
953 struct _WapiHandle_shared_ref *ref;
955 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
956 ref = &handle_data->u.shared;
958 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
961 /* Create a pipe to make sure the child doesn't exit before
962 * we can add the process to the linked list of mono_processes */
963 if (pipe (startup_pipe) == -1) {
964 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
965 * This is just for a very hard to hit race condition in the first place */
966 startup_pipe [0] = startup_pipe [1] = -1;
967 DEBUG ("%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
970 thr_ret = _wapi_handle_lock_shared_handles ();
971 g_assert (thr_ret == 0);
976 SetLastError (ERROR_OUTOFMEMORY);
980 } else if (pid == 0) {
983 if (startup_pipe [0] != -1) {
984 /* Wait until the parent has updated it's internal data */
985 ssize_t _i G_GNUC_UNUSED = read (startup_pipe [0], &dummy, 1);
986 DEBUG ("%s: child: parent has completed its setup", __func__);
987 close (startup_pipe [0]);
988 close (startup_pipe [1]);
991 /* should we detach from the process group? */
993 /* Connect stdin, stdout and stderr */
998 if (inherit_handles != TRUE) {
999 /* FIXME: do something here */
1002 /* Close all file descriptors */
1003 for (i = getdtablesize () - 1; i > 2; i--) {
1007 #ifdef DEBUG_ENABLED
1008 DEBUG ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1010 for (i = 0; argv[i] != NULL; i++) {
1011 g_message ("arg %d: [%s]", i, argv[i]);
1014 for (i = 0; env_strings[i] != NULL; i++) {
1015 g_message ("env %d: [%s]", i, env_strings[i]);
1020 if (dir != NULL && chdir (dir) == -1) {
1026 execve (argv[0], argv, env_strings);
1033 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1034 (gpointer *)&process_handle_data);
1036 g_warning ("%s: error looking up process handle %p", __func__,
1038 _wapi_handle_unref (handle);
1042 process_handle_data->id = pid;
1044 /* Add our mono_process into the linked list of mono_processes */
1045 mono_process = (struct MonoProcess *) g_malloc0 (sizeof (struct MonoProcess));
1046 mono_process->pid = pid;
1047 mono_process->handle_count = 1;
1048 if (MONO_SEM_INIT (&mono_process->exit_sem, 0) != 0) {
1049 /* If we can't create the exit semaphore, we just don't add anything
1050 * to our list of mono processes. Waiting on the process will return
1052 g_warning ("%s: could not create exit semaphore for process.", strerror (errno));
1053 g_free (mono_process);
1055 /* Keep the process handle artificially alive until the process
1056 * exits so that the information in the handle isn't lost. */
1057 _wapi_handle_ref (handle);
1058 mono_process->handle = handle;
1060 process_handle_data->self = _wapi_getpid ();
1061 process_handle_data->mono_process = mono_process;
1063 mono_mutex_lock (&mono_processes_mutex);
1064 mono_process->next = mono_processes;
1065 mono_processes = mono_process;
1066 mono_mutex_unlock (&mono_processes_mutex);
1069 if (process_info != NULL) {
1070 process_info->hProcess = handle;
1071 process_info->dwProcessId = pid;
1073 /* FIXME: we might need to handle the thread info some
1076 process_info->hThread = INVALID_HANDLE_VALUE;
1077 process_info->dwThreadId = 0;
1081 _wapi_handle_unlock_shared_handles ();
1084 _wapi_handle_unref (handle);
1086 if (startup_pipe [1] != -1) {
1087 /* Write 1 byte, doesn't matter what */
1088 ssize_t _i G_GNUC_UNUSED = write (startup_pipe [1], startup_pipe, 1);
1089 close (startup_pipe [0]);
1090 close (startup_pipe [1]);
1097 if (full_prog != NULL) {
1109 if(env_strings != NULL) {
1110 g_strfreev (env_strings);
1116 DEBUG ("%s: returning handle %p for pid %d", __func__, handle,
1119 /* Check if something needs to be cleaned up. */
1120 mono_processes_cleanup ();
1125 static void process_set_name (struct _WapiHandle_process *process_handle)
1127 gchar *progname, *utf8_progname, *slash;
1129 progname=g_get_prgname ();
1130 utf8_progname=mono_utf8_from_external (progname);
1132 DEBUG ("%s: using [%s] as prog name", __func__, progname);
1134 if(utf8_progname!=NULL) {
1135 slash=strrchr (utf8_progname, '/');
1137 g_strlcpy (process_handle->proc_name, slash+1,
1138 _WAPI_PROC_NAME_MAX_LEN - 1);
1140 g_strlcpy (process_handle->proc_name, utf8_progname,
1141 _WAPI_PROC_NAME_MAX_LEN - 1);
1144 g_free (utf8_progname);
1148 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
1150 #if !GLIB_CHECK_VERSION (2,4,0)
1151 #define g_setenv(a,b,c) setenv(a,b,c)
1152 #define g_unsetenv(a) unsetenv(a)
1155 static void process_set_current (void)
1157 pid_t pid = _wapi_getpid ();
1158 const char *handle_env;
1159 struct _WapiHandle_process process_handle = {0};
1161 mono_once (&process_ops_once, process_ops_init);
1163 handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1164 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1166 if (handle_env != NULL) {
1167 struct _WapiHandle_process *process_handlep;
1168 gchar *procname = NULL;
1171 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
1173 DEBUG ("%s: Found my process handle: %p (offset %d 0x%x)",
1174 __func__, current_process, atoi (handle_env),
1177 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
1178 (gpointer *)&process_handlep);
1180 /* This test will probably break on linuxthreads, but
1181 * that should be ancient history on all distros we
1184 if (process_handlep->id == pid) {
1185 procname = process_handlep->proc_name;
1186 if (!strcmp (procname, "mono")) {
1187 /* Set a better process name */
1188 DEBUG ("%s: Setting better process name", __func__);
1190 process_set_name (process_handlep);
1192 DEBUG ("%s: Leaving process name: %s", __func__, procname);
1198 /* Wrong pid, so drop this handle and fall through to
1201 _wapi_handle_unref (current_process);
1205 /* We get here if the handle wasn't specified in the
1206 * environment, or if the process ID was wrong, or if the
1207 * handle lookup failed (eg if the parent process forked and
1208 * quit immediately, and deleted the shared data before the
1209 * child got a chance to attach it.)
1212 DEBUG ("%s: Need to create my own process handle", __func__);
1214 process_handle.id = pid;
1216 process_set_defaults (&process_handle);
1217 process_set_name (&process_handle);
1219 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1221 if (current_process == _WAPI_HANDLE_INVALID) {
1222 g_warning ("%s: error creating process handle", __func__);
1227 gpointer _wapi_process_duplicate ()
1229 mono_once (&process_current_once, process_set_current);
1231 _wapi_handle_ref (current_process);
1233 return(current_process);
1236 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1237 gpointer GetCurrentProcess (void)
1239 mono_once (&process_current_once, process_set_current);
1241 return(_WAPI_PROCESS_CURRENT);
1244 guint32 GetProcessId (gpointer handle)
1246 struct _WapiHandle_process *process_handle;
1249 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1250 /* This is a pseudo handle */
1251 return(GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
1254 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1255 (gpointer *)&process_handle);
1257 SetLastError (ERROR_INVALID_HANDLE);
1261 return (process_handle->id);
1264 guint32 GetCurrentProcessId (void)
1266 mono_once (&process_current_once, process_set_current);
1268 return (GetProcessId (current_process));
1271 /* Returns the process id as a convenience to the functions that call this */
1272 static pid_t signal_process_if_gone (gpointer handle)
1274 struct _WapiHandle_process *process_handle;
1277 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
1279 /* Make sure the process is signalled if it has exited - if
1280 * the parent process didn't wait for it then it won't be
1282 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1283 (gpointer *)&process_handle);
1285 /* It's possible that the handle has vanished during
1286 * the _wapi_search_handle before it gets here, so
1287 * don't spam the console with warnings.
1289 /* g_warning ("%s: error looking up process handle %p",
1290 __func__, handle);*/
1295 DEBUG ("%s: looking at process %d", __func__, process_handle->id);
1297 if (kill (process_handle->id, 0) == -1 &&
1300 /* The process is dead, (EPERM tells us a new process
1301 * has that ID, but as it's owned by someone else it
1302 * can't be the one listed in our shared memory file)
1304 _wapi_shared_handle_set_signal_state (handle, TRUE);
1307 return (process_handle->id);
1311 static gboolean process_enum (gpointer handle, gpointer user_data)
1313 GArray *processes=user_data;
1314 pid_t pid = signal_process_if_gone (handle);
1321 /* Ignore processes that have already exited (ie they are signalled) */
1322 if (_wapi_handle_issignalled (handle) == FALSE) {
1323 DEBUG ("%s: process %d added to array", __func__, pid);
1325 /* This ensures that duplicates aren't returned (see
1326 * the comment above _wapi_search_handle () for why
1329 for (i = 0; i < processes->len; i++) {
1330 if (g_array_index (processes, pid_t, i) == pid) {
1331 /* We've already got this one, return
1332 * FALSE to keep searching
1338 g_array_append_val (processes, pid);
1341 /* Return false to keep searching */
1344 #endif /* UNUSED_CODE */
1346 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1349 pid_t checking_pid = signal_process_if_gone (handle);
1351 if (checking_pid == 0) {
1355 wanted_pid = GPOINTER_TO_UINT (user_data);
1357 /* It's possible to have more than one process handle with the
1358 * same pid, but only the one running process can be
1361 if (checking_pid == wanted_pid &&
1362 _wapi_handle_issignalled (handle) == FALSE) {
1363 /* If the handle is blown away in the window between
1364 * returning TRUE here and _wapi_search_handle pinging
1365 * the timestamp, the search will continue
1373 gboolean CloseProcess(gpointer handle)
1375 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1376 /* This is a pseudo handle */
1380 return CloseHandle (handle);
1384 * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1386 gpointer OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1388 /* Find the process handle that corresponds to pid */
1389 gpointer handle = NULL;
1391 mono_once (&process_current_once, process_set_current);
1393 DEBUG ("%s: looking for process %d", __func__, pid);
1395 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1396 process_open_compare,
1397 GUINT_TO_POINTER (pid), NULL, TRUE);
1399 if (is_pid_valid (pid)) {
1400 /* Return a pseudo handle for processes we
1401 * don't have handles for
1403 return GINT_TO_POINTER (_WAPI_PROCESS_UNHANDLED + pid);
1405 DEBUG ("%s: Can't find pid %d", __func__, pid);
1407 SetLastError (ERROR_PROC_NOT_FOUND);
1413 /* _wapi_search_handle () already added a ref */
1417 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1419 struct _WapiHandle_process *process_handle;
1423 mono_once (&process_current_once, process_set_current);
1429 pid = GPOINTER_TO_UINT (process) - _WAPI_PROCESS_UNHANDLED;
1430 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1431 /* This is a pseudo handle, so we don't know what the
1432 * exit code was, but we can check whether it's alive or not
1434 if (is_pid_valid (pid)) {
1435 *code = STILL_ACTIVE;
1442 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1443 (gpointer *)&process_handle);
1445 DEBUG ("%s: Can't find process %p", __func__, process);
1450 /* A process handle is only signalled if the process has exited
1451 * and has been waited for */
1453 /* Make sure any process exit has been noticed, before
1454 * checking if the process is signalled. Fixes bug 325463.
1456 process_wait (process, 0, TRUE);
1458 if (_wapi_handle_issignalled (process) == TRUE) {
1459 *code = process_handle->exitstatus;
1461 *code = STILL_ACTIVE;
1467 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1468 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1469 WapiFileTime *user_time)
1471 struct _WapiHandle_process *process_handle;
1473 gboolean ku_times_set = FALSE;
1475 mono_once (&process_current_once, process_set_current);
1477 if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1479 /* Not sure if w32 allows NULLs here or not */
1483 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1484 /* This is a pseudo handle, so just fail for now
1489 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1490 (gpointer *)&process_handle);
1492 DEBUG ("%s: Can't find process %p", __func__, process);
1497 *create_time=process_handle->create_time;
1499 /* A process handle is only signalled if the process has
1500 * exited. Otherwise exit_time isn't set
1502 if(_wapi_handle_issignalled (process)==TRUE) {
1503 *exit_time=process_handle->exit_time;
1506 #ifdef HAVE_GETRUSAGE
1507 if (process_handle->id == getpid ()) {
1508 struct rusage time_data;
1509 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1511 ku_times_set = TRUE;
1512 tick_val = (guint64)time_data.ru_utime.tv_sec * 10000000 + (guint64)time_data.ru_utime.tv_usec * 10;
1513 _wapi_guint64_to_filetime (tick_val, user_time);
1514 tick_val = (guint64)time_data.ru_stime.tv_sec * 10000000 + (guint64)time_data.ru_stime.tv_usec * 10;
1515 _wapi_guint64_to_filetime (tick_val, kernel_time);
1519 if (!ku_times_set) {
1520 memset (kernel_time, 0, sizeof (WapiFileTime));
1521 memset (user_time, 0, sizeof (WapiFileTime));
1529 gpointer address_start;
1530 gpointer address_end;
1532 gpointer address_offset;
1538 static void free_procmodule (WapiProcModule *mod)
1540 if (mod->perms != NULL) {
1541 g_free (mod->perms);
1543 if (mod->filename != NULL) {
1544 g_free (mod->filename);
1549 static gint find_procmodule (gconstpointer a, gconstpointer b)
1551 WapiProcModule *want = (WapiProcModule *)a;
1552 WapiProcModule *compare = (WapiProcModule *)b;
1554 if ((want->device == compare->device) &&
1555 (want->inode == compare->inode)) {
1562 #ifdef PLATFORM_MACOSX
1563 #include <mach-o/dyld.h>
1564 #include <mach-o/getsect.h>
1566 static GSList *load_modules (void)
1569 WapiProcModule *mod;
1570 uint32_t count = _dyld_image_count ();
1573 for (i = 0; i < count; i++) {
1574 #if SIZEOF_VOID_P == 8
1575 const struct mach_header_64 *hdr;
1576 const struct section_64 *sec;
1578 const struct mach_header *hdr;
1579 const struct section *sec;
1583 name = _dyld_get_image_name (i);
1584 #if SIZEOF_VOID_P == 8
1585 hdr = (const struct mach_header_64*)_dyld_get_image_header (i);
1586 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1588 hdr = _dyld_get_image_header (i);
1589 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1592 /* Some dynlibs do not have data sections on osx (#533893) */
1597 mod = g_new0 (WapiProcModule, 1);
1598 mod->address_start = GINT_TO_POINTER (sec->addr);
1599 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1600 mod->perms = g_strdup ("r--p");
1601 mod->address_offset = 0;
1602 mod->device = makedev (0, 0);
1603 mod->inode = (ino_t) i;
1604 mod->filename = g_strdup (name);
1606 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1607 ret = g_slist_prepend (ret, mod);
1609 free_procmodule (mod);
1613 ret = g_slist_reverse (ret);
1617 #elif defined(__OpenBSD__)
1619 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1621 if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1622 + sizeof (info->dlpi_phnum))
1625 struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1629 memcpy(cpy, info, sizeof(*info));
1631 g_ptr_array_add ((GPtrArray *)ptr, cpy);
1636 static GSList *load_modules (void)
1639 WapiProcModule *mod;
1640 GPtrArray *dlarray = g_ptr_array_new();
1643 if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1646 for (i = 0; i < dlarray->len; i++) {
1647 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1649 mod = g_new0 (WapiProcModule, 1);
1650 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1651 mod->address_end = (gpointer)(info->dlpi_addr +
1652 info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1653 mod->perms = g_strdup ("r--p");
1654 mod->address_offset = 0;
1655 mod->inode = (ino_t) i;
1656 mod->filename = g_strdup (info->dlpi_name);
1658 DEBUG ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1659 mod->inode, mod->filename, mod->address_start, mod->address_end);
1663 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1664 ret = g_slist_prepend (ret, mod);
1666 free_procmodule (mod);
1670 g_ptr_array_free (dlarray, TRUE);
1672 ret = g_slist_reverse (ret);
1676 #elif defined(__HAIKU__)
1678 static GSList *load_modules (void)
1681 WapiProcModule *mod;
1683 image_info imageInfo;
1685 while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
1686 mod = g_new0 (WapiProcModule, 1);
1687 mod->device = imageInfo.device;
1688 mod->inode = imageInfo.node;
1689 mod->filename = g_strdup (imageInfo.name);
1690 mod->address_start = MIN (imageInfo.text, imageInfo.data);
1691 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
1692 (uint8_t*)imageInfo.data + imageInfo.data_size);
1693 mod->perms = g_strdup ("r--p");
1694 mod->address_offset = 0;
1696 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1697 ret = g_slist_prepend (ret, mod);
1699 free_procmodule (mod);
1703 ret = g_slist_reverse (ret);
1708 static GSList *load_modules (FILE *fp)
1711 WapiProcModule *mod;
1712 gchar buf[MAXPATHLEN + 1], *p, *endp;
1713 gchar *start_start, *end_start, *prot_start, *offset_start;
1714 gchar *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1715 gpointer address_start, address_end, address_offset;
1716 guint32 maj_dev, min_dev;
1720 while (fgets (buf, sizeof(buf), fp)) {
1722 while (g_ascii_isspace (*p)) ++p;
1724 if (!g_ascii_isxdigit (*start_start)) {
1727 address_start = (gpointer)strtoul (start_start, &endp, 16);
1735 if (!g_ascii_isxdigit (*end_start)) {
1738 address_end = (gpointer)strtoul (end_start, &endp, 16);
1740 if (!g_ascii_isspace (*p)) {
1744 while (g_ascii_isspace (*p)) ++p;
1746 if (*prot_start != 'r' && *prot_start != '-') {
1749 memcpy (prot_buf, prot_start, 4);
1751 while (!g_ascii_isspace (*p)) ++p;
1753 while (g_ascii_isspace (*p)) ++p;
1755 if (!g_ascii_isxdigit (*offset_start)) {
1758 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1760 if (!g_ascii_isspace (*p)) {
1764 while(g_ascii_isspace (*p)) ++p;
1766 if (!g_ascii_isxdigit (*maj_dev_start)) {
1769 maj_dev = strtoul (maj_dev_start, &endp, 16);
1777 if (!g_ascii_isxdigit (*min_dev_start)) {
1780 min_dev = strtoul (min_dev_start, &endp, 16);
1782 if (!g_ascii_isspace (*p)) {
1786 while (g_ascii_isspace (*p)) ++p;
1788 if (!g_ascii_isxdigit (*inode_start)) {
1791 inode = (ino_t)strtol (inode_start, &endp, 10);
1793 if (!g_ascii_isspace (*p)) {
1797 device = makedev ((int)maj_dev, (int)min_dev);
1798 if ((device == 0) &&
1803 while(g_ascii_isspace (*p)) ++p;
1804 /* p now points to the filename */
1806 mod = g_new0 (WapiProcModule, 1);
1807 mod->address_start = address_start;
1808 mod->address_end = address_end;
1809 mod->perms = g_strdup (prot_buf);
1810 mod->address_offset = address_offset;
1811 mod->device = device;
1813 mod->filename = g_strdup (g_strstrip (p));
1815 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1816 ret = g_slist_prepend (ret, mod);
1818 free_procmodule (mod);
1822 ret = g_slist_reverse (ret);
1828 static gboolean match_procname_to_modulename (gchar *procname, gchar *modulename)
1830 char* lastsep = NULL;
1831 char* lastsep2 = NULL;
1834 gboolean result = FALSE;
1836 if (procname == NULL || modulename == NULL)
1839 pname = mono_path_resolve_symlinks (procname);
1840 mname = mono_path_resolve_symlinks (modulename);
1842 if (!strcmp (pname, mname))
1846 lastsep = strrchr (mname, '/');
1848 if (!strcmp (lastsep+1, pname))
1851 lastsep2 = strrchr (pname, '/');
1854 if (!strcmp (lastsep+1, lastsep2+1))
1857 if (!strcmp (mname, lastsep2+1))
1870 #if !defined(__OpenBSD__)
1872 open_process_map (int pid, const char *mode)
1875 const gchar *proc_path[] = {
1876 "/proc/%d/maps", /* GNU/Linux */
1877 "/proc/%d/map", /* FreeBSD */
1883 for (i = 0; fp == NULL && proc_path [i]; i++) {
1884 filename = g_strdup_printf (proc_path[i], pid);
1885 fp = fopen (filename, mode);
1893 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1894 guint32 size, guint32 *needed)
1896 struct _WapiHandle_process *process_handle;
1898 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
1901 GSList *mods = NULL;
1902 WapiProcModule *module;
1903 guint32 count, avail = size / sizeof(gpointer);
1906 gchar *proc_name = NULL;
1908 /* Store modules in an array of pointers (main module as
1909 * modules[0]), using the load address for each module as a
1910 * token. (Use 'NULL' as an alternative for the main module
1911 * so that the simple implementation can just return one item
1912 * for now.) Get the info from /proc/<pid>/maps on linux,
1913 * /proc/<pid>/map on FreeBSD, other systems will have to
1914 * implement /dev/kmem reading or whatever other horrid
1915 * technique is needed.
1917 if (size < sizeof(gpointer)) {
1921 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1922 /* This is a pseudo handle */
1923 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
1925 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1926 (gpointer *)&process_handle);
1928 DEBUG ("%s: Can't find process %p", __func__, process);
1932 pid = process_handle->id;
1933 proc_name = process_handle->proc_name;
1936 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
1938 mods = load_modules ();
1940 if ((fp = open_process_map (pid, "r")) == NULL) {
1941 /* No /proc/<pid>/maps so just return the main module
1945 *needed = sizeof(gpointer);
1947 mods = load_modules (fp);
1950 count = g_slist_length (mods);
1952 /* count + 1 to leave slot 0 for the main module */
1953 *needed = sizeof(gpointer) * (count + 1);
1955 /* Use the NULL shortcut, as the first line in
1956 * /proc/<pid>/maps isn't the executable, and we need
1957 * that first in the returned list. Check the module name
1958 * to see if it ends with the proc name and substitute
1959 * the first entry with it. FIXME if this turns out to
1963 for (i = 0; i < (avail - 1) && i < count; i++) {
1964 module = (WapiProcModule *)g_slist_nth_data (mods, i);
1965 if (modules[0] != NULL)
1966 modules[i] = module->address_start;
1967 else if (match_procname_to_modulename (proc_name, module->filename))
1968 modules[0] = module->address_start;
1970 modules[i + 1] = module->address_start;
1973 for (i = 0; i < count; i++) {
1974 free_procmodule (g_slist_nth_data (mods, i));
1976 g_slist_free (mods);
1982 static gchar *get_process_name_from_proc (pid_t pid)
1984 #if defined(__OpenBSD__)
1987 struct kinfo_proc *pi;
1988 #elif defined(PLATFORM_MACOSX)
1989 #if !(!defined (__mono_ppc__) && defined (TARGET_OSX))
1991 struct kinfo_proc *pi;
1992 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
1996 gchar *filename = NULL;
2001 #if defined(PLATFORM_SOLARIS)
2002 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
2003 if ((fp = fopen (filename, "r")) != NULL) {
2007 nread = fread (&info, sizeof (info), 1, fp);
2009 ret = g_strdup (info.pr_fname);
2015 #elif defined(PLATFORM_MACOSX)
2016 #if !defined (__mono_ppc__) && defined (TARGET_OSX)
2017 /* No proc name on OSX < 10.5 nor ppc nor iOS */
2018 memset (buf, '\0', sizeof(buf));
2019 proc_name (pid, buf, sizeof(buf));
2020 if (strlen (buf) > 0)
2021 ret = g_strdup (buf);
2023 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0)
2026 if ((pi = malloc(size)) == NULL)
2029 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
2030 if (errno == ENOMEM) {
2032 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__);
2037 if (strlen (pi->kp_proc.p_comm) > 0)
2038 ret = g_strdup (pi->kp_proc.p_comm);
2042 #elif defined(__OpenBSD__)
2044 mib [1] = KERN_PROC;
2045 mib [2] = KERN_PROC_PID;
2047 mib [4] = sizeof(struct kinfo_proc);
2051 if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0)
2054 if ((pi = malloc(size)) == NULL)
2057 mib[5] = (int)(size / sizeof(struct kinfo_proc));
2059 if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
2060 (size != sizeof (struct kinfo_proc))) {
2061 if (errno == ENOMEM) {
2068 if (strlen (pi->p_comm) > 0)
2069 ret = g_strdup (pi->p_comm);
2072 #elif defined(__HAIKU__)
2073 image_info imageInfo;
2076 if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
2077 ret = g_strdup (imageInfo.name);
2080 memset (buf, '\0', sizeof(buf));
2081 filename = g_strdup_printf ("/proc/%d/exe", pid);
2082 if (readlink (filename, buf, 255) > 0) {
2083 ret = g_strdup (buf);
2091 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
2092 if ((fp = fopen (filename, "r")) != NULL) {
2093 if (fgets (buf, 256, fp) != NULL) {
2094 ret = g_strdup (buf);
2105 filename = g_strdup_printf ("/proc/%d/stat", pid);
2106 if ((fp = fopen (filename, "r")) != NULL) {
2107 if (fgets (buf, 256, fp) != NULL) {
2110 start = strchr (buf, '(');
2111 if (start != NULL) {
2112 end = strchr (start + 1, ')');
2115 ret = g_strndup (start + 1,
2130 * wapi_process_get_path:
2132 * Return the full path of the executable of the process PID, or NULL if it cannot be determined.
2133 * Returns malloc-ed memory.
2136 wapi_process_get_path (pid_t pid)
2138 #if defined(PLATFORM_MACOSX) && !defined(__mono_ppc__) && defined(TARGET_OSX)
2139 gchar buf [PROC_PIDPATHINFO_MAXSIZE];
2142 res = proc_pidpath (pid, buf, sizeof (buf));
2145 if (buf [0] == '\0')
2147 return g_strdup (buf);
2149 return get_process_name_from_proc (pid);
2154 * wapi_process_set_cli_launcher:
2156 * Set the full path of the runtime executable used to launch managed exe's.
2159 wapi_process_set_cli_launcher (char *path)
2161 g_free (cli_launcher);
2162 cli_launcher = path ? g_strdup (path) : NULL;
2165 static guint32 get_module_name (gpointer process, gpointer module,
2166 gunichar2 *basename, guint32 size,
2169 struct _WapiHandle_process *process_handle;
2172 gunichar2 *procname;
2173 gchar *procname_ext = NULL;
2176 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2179 GSList *mods = NULL;
2180 WapiProcModule *found_module;
2183 gchar *proc_name = NULL;
2185 mono_once (&process_current_once, process_set_current);
2187 DEBUG ("%s: Getting module base name, process handle %p module %p",
2188 __func__, process, module);
2190 size = size*sizeof(gunichar2); /* adjust for unicode characters */
2192 if (basename == NULL || size == 0) {
2196 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2197 /* This is a pseudo handle */
2198 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2199 proc_name = get_process_name_from_proc (pid);
2201 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2202 (gpointer *)&process_handle);
2204 DEBUG ("%s: Can't find process %p", __func__,
2209 pid = process_handle->id;
2210 proc_name = g_strdup (process_handle->proc_name);
2213 /* Look up the address in /proc/<pid>/maps */
2214 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2216 mods = load_modules ();
2218 if ((fp = open_process_map (pid, "r")) == NULL) {
2219 if (errno == EACCES && module == NULL && base == TRUE) {
2220 procname_ext = get_process_name_from_proc (pid);
2222 /* No /proc/<pid>/maps, so just return failure
2229 mods = load_modules (fp);
2232 count = g_slist_length (mods);
2234 /* If module != NULL compare the address.
2235 * If module == NULL we are looking for the main module.
2236 * The best we can do for now check it the module name end with the process name.
2238 for (i = 0; i < count; i++) {
2239 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2240 if (procname_ext == NULL &&
2241 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2242 (module != NULL && found_module->address_start == module))) {
2244 procname_ext = g_path_get_basename (found_module->filename);
2246 procname_ext = g_strdup (found_module->filename);
2250 free_procmodule (found_module);
2253 if (procname_ext == NULL)
2255 /* If it's *still* null, we might have hit the
2256 * case where reading /proc/$pid/maps gives an
2257 * empty file for this user.
2259 procname_ext = get_process_name_from_proc (pid);
2262 g_slist_free (mods);
2266 if (procname_ext != NULL) {
2267 DEBUG ("%s: Process name is [%s]", __func__,
2270 procname = mono_unicode_from_external (procname_ext, &bytes);
2271 if (procname == NULL) {
2273 g_free (procname_ext);
2279 /* Add the terminator */
2283 DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2285 memcpy (basename, procname, size);
2287 DEBUG ("%s: Size %d larger than needed (%ld)",
2288 __func__, size, bytes);
2290 memcpy (basename, procname, bytes);
2294 g_free (procname_ext);
2302 guint32 GetModuleBaseName (gpointer process, gpointer module,
2303 gunichar2 *basename, guint32 size)
2305 return(get_module_name (process, module, basename, size, TRUE));
2308 guint32 GetModuleFileNameEx (gpointer process, gpointer module,
2309 gunichar2 *filename, guint32 size)
2311 return(get_module_name (process, module, filename, size, FALSE));
2314 gboolean GetModuleInformation (gpointer process, gpointer module,
2315 WapiModuleInfo *modinfo, guint32 size)
2317 struct _WapiHandle_process *process_handle;
2320 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2323 GSList *mods = NULL;
2324 WapiProcModule *found_module;
2327 gboolean ret = FALSE;
2328 gchar *proc_name = NULL;
2330 mono_once (&process_current_once, process_set_current);
2332 DEBUG ("%s: Getting module info, process handle %p module %p",
2333 __func__, process, module);
2335 if (modinfo == NULL || size < sizeof(WapiModuleInfo)) {
2339 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2340 /* This is a pseudo handle */
2341 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2342 proc_name = get_process_name_from_proc (pid);
2344 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2345 (gpointer *)&process_handle);
2347 DEBUG ("%s: Can't find process %p", __func__,
2352 pid = process_handle->id;
2353 proc_name = g_strdup (process_handle->proc_name);
2356 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2358 mods = load_modules ();
2360 /* Look up the address in /proc/<pid>/maps */
2361 if ((fp = open_process_map (pid, "r")) == NULL) {
2362 /* No /proc/<pid>/maps, so just return failure
2368 mods = load_modules (fp);
2371 count = g_slist_length (mods);
2373 /* If module != NULL compare the address.
2374 * If module == NULL we are looking for the main module.
2375 * The best we can do for now check it the module name end with the process name.
2377 for (i = 0; i < count; i++) {
2378 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2379 if ( ret == FALSE &&
2380 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2381 (module != NULL && found_module->address_start == module))) {
2382 modinfo->lpBaseOfDll = found_module->address_start;
2383 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2384 modinfo->EntryPoint = found_module->address_offset;
2388 free_procmodule (found_module);
2391 g_slist_free (mods);
2398 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2400 struct _WapiHandle_process *process_handle;
2403 mono_once (&process_current_once, process_set_current);
2405 if(min==NULL || max==NULL) {
2406 /* Not sure if w32 allows NULLs here or not */
2410 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2411 /* This is a pseudo handle, so just fail for now
2416 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2417 (gpointer *)&process_handle);
2419 DEBUG ("%s: Can't find process %p", __func__, process);
2424 *min=process_handle->min_working_set;
2425 *max=process_handle->max_working_set;
2430 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2432 struct _WapiHandle_process *process_handle;
2435 mono_once (&process_current_once, process_set_current);
2437 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2438 /* This is a pseudo handle, so just fail for now
2443 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2444 (gpointer *)&process_handle);
2446 DEBUG ("%s: Can't find process %p", __func__, process);
2451 process_handle->min_working_set=min;
2452 process_handle->max_working_set=max;
2459 TerminateProcess (gpointer process, gint32 exitCode)
2461 struct _WapiHandle_process *process_handle;
2467 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2468 /* This is a pseudo handle */
2469 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2471 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2472 (gpointer *) &process_handle);
2475 DEBUG ("%s: Can't find process %p", __func__,
2477 SetLastError (ERROR_INVALID_HANDLE);
2480 pid = process_handle->id;
2483 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2484 ret = kill (pid, signo);
2488 SetLastError (ERROR_INVALID_PARAMETER);
2491 SetLastError (ERROR_ACCESS_DENIED);
2494 SetLastError (ERROR_PROC_NOT_FOUND);
2497 SetLastError (ERROR_GEN_FAILURE);
2505 GetPriorityClass (gpointer process)
2507 #ifdef HAVE_GETPRIORITY
2508 struct _WapiHandle_process *process_handle;
2513 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2514 /* This is a pseudo handle */
2515 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2517 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2518 (gpointer *) &process_handle);
2521 SetLastError (ERROR_INVALID_HANDLE);
2524 pid = process_handle->id;
2528 ret = getpriority (PRIO_PROCESS, pid);
2529 if (ret == -1 && errno != 0) {
2533 SetLastError (ERROR_ACCESS_DENIED);
2536 SetLastError (ERROR_PROC_NOT_FOUND);
2539 SetLastError (ERROR_GEN_FAILURE);
2545 return NORMAL_PRIORITY_CLASS;
2547 return REALTIME_PRIORITY_CLASS;
2549 return HIGH_PRIORITY_CLASS;
2551 return ABOVE_NORMAL_PRIORITY_CLASS;
2553 return IDLE_PRIORITY_CLASS;
2555 return BELOW_NORMAL_PRIORITY_CLASS;
2557 return NORMAL_PRIORITY_CLASS;
2559 SetLastError (ERROR_NOT_SUPPORTED);
2565 SetPriorityClass (gpointer process, guint32 priority_class)
2567 #ifdef HAVE_SETPRIORITY
2568 struct _WapiHandle_process *process_handle;
2574 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2575 /* This is a pseudo handle */
2576 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2578 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2579 (gpointer *) &process_handle);
2582 SetLastError (ERROR_INVALID_HANDLE);
2585 pid = process_handle->id;
2588 switch (priority_class) {
2589 case IDLE_PRIORITY_CLASS:
2592 case BELOW_NORMAL_PRIORITY_CLASS:
2595 case NORMAL_PRIORITY_CLASS:
2598 case ABOVE_NORMAL_PRIORITY_CLASS:
2601 case HIGH_PRIORITY_CLASS:
2604 case REALTIME_PRIORITY_CLASS:
2608 SetLastError (ERROR_INVALID_PARAMETER);
2612 ret = setpriority (PRIO_PROCESS, pid, prio);
2617 SetLastError (ERROR_ACCESS_DENIED);
2620 SetLastError (ERROR_PROC_NOT_FOUND);
2623 SetLastError (ERROR_GEN_FAILURE);
2629 SetLastError (ERROR_NOT_SUPPORTED);
2635 mono_processes_cleanup (void)
2637 struct MonoProcess *mp;
2638 struct MonoProcess *prev = NULL;
2639 struct MonoProcess *candidate = NULL;
2640 gpointer unref_handle;
2643 DEBUG ("%s", __func__);
2645 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2646 if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
2649 mp = mono_processes;
2650 while (mp != NULL) {
2651 if (mp->pid == 0 && mp->handle != NULL) {
2652 /* This process has exited and we need to remove the artifical ref
2654 mono_mutex_lock (&mono_processes_mutex);
2655 unref_handle = mp->handle;
2657 mono_mutex_unlock (&mono_processes_mutex);
2659 _wapi_handle_unref (unref_handle);
2665 mp = mono_processes;
2667 while (mp != NULL) {
2668 if ((mp->handle_count == 0 && mp->pid == 0) || candidate != NULL) {
2670 _wapi_handle_spin (spin);
2674 /* We've found a candidate */
2675 mono_mutex_lock (&mono_processes_mutex);
2676 if (candidate == NULL) {
2678 if (mp == mono_processes) {
2679 mono_processes = mp->next;
2681 prev->next = mp->next;
2686 /* It's still safe to traverse the structure.*/
2687 mono_memory_barrier ();
2689 if (mono_processes_read_lock != 0) {
2690 /* The sigchld handler is watching us. Spin a bit and try again */
2693 } else if (spin >= 8) {
2694 /* Just give up for now */
2695 mono_mutex_unlock (&mono_processes_mutex);
2699 /* We've modified the list of processes, and we know the sigchld handler
2700 * isn't executing, so even if it executes at any moment, it'll see the
2701 * new version of the list. So now we can free the candidate. */
2702 DEBUG ("%s: freeing candidate %p", __func__, candidate);
2703 mp = candidate->next;
2704 MONO_SEM_DESTROY (&candidate->exit_sem);
2709 mono_mutex_unlock (&mono_processes_mutex);
2718 DEBUG ("%s done", __func__);
2720 InterlockedDecrement (&mono_processes_cleaning_up);
2724 process_close (gpointer handle, gpointer data)
2726 struct _WapiHandle_process *process_handle;
2728 DEBUG ("%s", __func__);
2730 process_handle = (struct _WapiHandle_process *) data;
2731 if (process_handle->mono_process && process_handle->self == _wapi_getpid ())
2732 InterlockedDecrement (&process_handle->mono_process->handle_count);
2733 mono_processes_cleanup ();
2737 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
2741 struct MonoProcess *p;
2744 fprintf (stdout, "SIG CHILD handler for pid: %i\n", info->si_pid);
2747 InterlockedIncrement (&mono_processes_read_lock);
2751 pid = waitpid (-1, &status, WNOHANG);
2752 } while (pid == -1 && errno == EINTR);
2758 fprintf (stdout, "child ended: %i", pid);
2762 if (p->pid == pid) {
2763 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2765 MONO_SEM_POST (&p->exit_sem);
2772 InterlockedDecrement (&mono_processes_read_lock);
2775 fprintf (stdout, "SIG CHILD handler: done looping.");
2781 static void process_add_sigchld_handler (void)
2784 struct sigaction sa;
2786 sa.sa_sigaction = mono_sigchld_signal_handler;
2787 sigemptyset (&sa.sa_mask);
2788 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2789 g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2790 DEBUG ("Added SIGCHLD handler");
2794 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2796 struct _WapiHandle_process *process_handle;
2802 struct MonoProcess *mp;
2804 gpointer current_thread;
2806 current_thread = wapi_get_current_thread_handle ();
2807 if (current_thread == NULL) {
2808 SetLastError (ERROR_INVALID_HANDLE);
2812 /* FIXME: We can now easily wait on processes that aren't our own children,
2813 * but WaitFor*Object won't call us for pseudo handles. */
2814 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2816 DEBUG ("%s (%p, %u)", __func__, handle, timeout);
2818 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS, (gpointer *)&process_handle);
2820 g_warning ("%s: error looking up process handle %p", __func__, handle);
2824 if (process_handle->exited) {
2825 /* We've already done this one */
2826 DEBUG ("%s (%p, %u): Process already exited", __func__, handle, timeout);
2827 return WAIT_OBJECT_0;
2830 pid = process_handle->id;
2832 DEBUG ("%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2834 /* We don't need to lock mono_processes here, the entry
2835 * has a handle_count > 0 which means it will not be freed. */
2836 mp = process_handle->mono_process;
2837 if (mp && process_handle->self != _wapi_getpid ()) {
2838 /* mono_process points to memory in another process' address space: we can't use it */
2842 start = mono_msec_ticks ();
2848 /* We have a semaphore we can wait on */
2849 if (timeout != INFINITE) {
2850 DEBUG ("%s (%p, %u): waiting on semaphore for %li ms...",
2851 __func__, handle, timeout, (timeout - (now - start)));
2853 ret = MONO_SEM_TIMEDWAIT_ALERTABLE (&mp->exit_sem, (timeout - (now - start)), alertable);
2855 DEBUG ("%s (%p, %u): waiting on semaphore forever...",
2856 __func__, handle, timeout);
2857 ret = MONO_SEM_WAIT_ALERTABLE (&mp->exit_sem, alertable);
2860 if (ret == -1 && errno != EINTR && errno != ETIMEDOUT) {
2861 DEBUG ("%s (%p, %u): sem_timedwait failure: %s",
2862 __func__, handle, timeout, g_strerror (errno));
2863 /* Should we return a failure here? */
2867 /* Success, process has exited */
2868 MONO_SEM_POST (&mp->exit_sem);
2872 /* We did not create this process, so we can't waidpid / sem_wait it.
2873 * We need to poll for the pid existence */
2874 DEBUG ("%s (%p, %u): polling on pid...", __func__, handle, timeout);
2875 if (!is_pid_valid (pid)) {
2876 /* Success, process has exited */
2882 DEBUG ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
2883 return WAIT_TIMEOUT;
2886 now = mono_msec_ticks ();
2887 if (now - start >= timeout) {
2888 DEBUG ("%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
2889 return WAIT_TIMEOUT;
2893 /* "timeout - (now - start)" will not underflow, since timeout is always >=0,
2894 * and we passed the check just above */
2895 _wapi_handle_spin (MIN (100, timeout - (now - start)));
2898 if (alertable && _wapi_thread_apc_pending (current_thread)) {
2899 DEBUG ("%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
2900 return WAIT_IO_COMPLETION;
2904 /* Process must have exited */
2905 DEBUG ("%s (%p, %u): Waited successfully", __func__, handle, timeout);
2907 ret = _wapi_handle_lock_shared_handles ();
2908 g_assert (ret == 0);
2910 status = mp ? mp->status : 0;
2911 if (WIFSIGNALED (status)) {
2912 process_handle->exitstatus = 128 + WTERMSIG (status);
2914 process_handle->exitstatus = WEXITSTATUS (status);
2916 _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
2918 process_handle->exited = TRUE;
2920 DEBUG ("%s (%p, %u): Setting pid %d signalled, exit status %d",
2921 __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
2923 _wapi_shared_handle_set_signal_state (handle, TRUE);
2925 _wapi_handle_unlock_shared_handles ();
2927 return WAIT_OBJECT_0;
2931 wapi_processes_cleanup (void)
2933 g_free (cli_launcher);