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 #include <sys/param.h>
30 #ifdef HAVE_SYS_MKDEV_H
31 #include <sys/mkdev.h>
34 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
36 #include <TargetConditionals.h>
37 #include <sys/resource.h>
44 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
46 #include <sys/sysctl.h>
47 # if !defined(__OpenBSD__)
48 # include <sys/utsname.h>
52 #ifdef PLATFORM_SOLARIS
53 /* procfs.h cannot be included if this define is set, but it seems to work fine if it is undefined */
54 #if _FILE_OFFSET_BITS == 64
55 #undef _FILE_OFFSET_BITS
57 #define _FILE_OFFSET_BITS 64
64 #include <KernelKit.h>
67 #include <mono/io-layer/wapi.h>
68 #include <mono/io-layer/wapi-private.h>
69 #include <mono/io-layer/handles-private.h>
70 #include <mono/io-layer/misc-private.h>
71 #include <mono/io-layer/process-private.h>
72 #include <mono/io-layer/threads.h>
73 #include <mono/utils/strenc.h>
74 #include <mono/utils/mono-path.h>
75 #include <mono/io-layer/timefuncs-private.h>
76 #include <mono/utils/mono-time.h>
77 #include <mono/utils/mono-membar.h>
78 #include <mono/utils/mono-mutex.h>
79 #include <mono/utils/mono-signal-handler.h>
81 /* The process' environment strings */
82 #if defined(__APPLE__) && !defined (__arm__)
83 /* Apple defines this in crt_externs.h but doesn't provide that header for
84 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
85 * in fact exist on all implementations (so far)
87 gchar ***_NSGetEnviron(void);
88 #define environ (*_NSGetEnviron())
90 extern char **environ;
94 #define DEBUG(...) g_message(__VA_ARGS__)
95 #define DEBUG_ENABLED 1
100 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable);
101 static void process_close (gpointer handle, gpointer data);
102 static gboolean is_pid_valid (pid_t pid);
104 #if !defined(__OpenBSD__)
106 open_process_map (int pid, const char *mode);
109 struct _WapiHandleOps _wapi_process_ops = {
110 process_close, /* close_shared */
114 process_wait, /* special_wait */
119 static struct sigaction previous_chld_sa;
121 static mono_once_t process_sig_chld_once = MONO_ONCE_INIT;
122 static void process_add_sigchld_handler (void);
124 /* The signal-safe logic to use mono_processes goes like this:
125 * - The list must be safe to traverse for the signal handler at all times.
126 * It's safe to: prepend an entry (which is a single store to 'mono_processes'),
127 * unlink an entry (assuming the unlinked entry isn't freed and doesn't
128 * change its 'next' pointer so that it can still be traversed).
129 * When cleaning up we first unlink an entry, then we verify that
130 * the read lock isn't locked. Then we can free the entry, since
131 * we know that nobody is using the old version of the list (including
132 * the unlinked entry).
133 * We also need to lock when adding and cleaning up so that those two
134 * operations don't mess with eachother. (This lock is not used in the
137 static struct MonoProcess *mono_processes = NULL;
138 static volatile gint32 mono_processes_read_lock = 0;
139 static volatile gint32 mono_processes_cleaning_up = 0;
140 static mono_mutex_t mono_processes_mutex;
141 static void mono_processes_cleanup (void);
143 static mono_once_t process_current_once=MONO_ONCE_INIT;
144 static gpointer current_process=NULL;
146 static mono_once_t process_ops_once=MONO_ONCE_INIT;
148 static void process_ops_init (void)
150 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
151 WAPI_HANDLE_CAP_WAIT |
152 WAPI_HANDLE_CAP_SPECIAL_WAIT);
156 /* Check if a pid is valid - i.e. if a process exists with this pid. */
157 static gboolean is_pid_valid (pid_t pid)
159 gboolean result = FALSE;
161 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
162 if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
164 #elif defined(__HAIKU__)
166 if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
169 gchar *dir = g_strdup_printf ("/proc/%d", pid);
170 if (!access (dir, F_OK))
178 static void process_set_defaults (struct _WapiHandle_process *process_handle)
180 /* These seem to be the defaults on w2k */
181 process_handle->min_working_set = 204800;
182 process_handle->max_working_set = 1413120;
184 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
188 len16 (const gunichar2 *str)
199 utf16_concat (const gunichar2 *first, ...)
206 va_start (args, first);
207 total += len16 (first);
208 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
213 ret = g_new (gunichar2, total + 1);
219 for (s = first; *s != 0; s++)
221 va_start (args, first);
222 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
225 for (p = s; *p != 0; p++)
233 #ifdef PLATFORM_MACOSX
235 /* 0 = no detection; -1 = not 10.5 or higher; 1 = 10.5 or higher */
236 static int osx_10_5_or_higher;
239 detect_osx_10_5_or_higher (void)
245 if (uname (&u) != 0){
246 osx_10_5_or_higher = 1;
254 osx_10_5_or_higher = -1;
256 osx_10_5_or_higher = 1;
260 is_macos_10_5_or_higher (void)
262 if (osx_10_5_or_higher == 0)
263 detect_osx_10_5_or_higher ();
265 return (osx_10_5_or_higher == 1);
269 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
270 static const gunichar2 *utf16_space = utf16_space_bytes;
271 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
272 static const gunichar2 *utf16_quote = utf16_quote_bytes;
277 print_utf16 (gunichar2 *str)
281 res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
282 g_print ("%s\n", res);
287 /* Implemented as just a wrapper around CreateProcess () */
288 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
291 WapiProcessInformation process_info;
295 /* w2k just segfaults here, but we can do better than
298 SetLastError (ERROR_INVALID_PARAMETER);
302 if (sei->lpFile == NULL) {
303 /* w2k returns TRUE for this, for some reason. */
307 /* Put both executable and parameters into the second argument
308 * to CreateProcess (), so it searches $PATH. The conversion
309 * into and back out of utf8 is because there is no
310 * g_strdup_printf () equivalent for gunichar2 :-(
312 args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
314 SetLastError (ERROR_INVALID_DATA);
317 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
318 CREATE_UNICODE_ENVIRONMENT, NULL,
319 sei->lpDirectory, NULL, &process_info);
322 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
326 static char *handler;
327 static gunichar2 *handler_utf16;
329 if (handler_utf16 == (gunichar2 *)-1)
332 #ifdef PLATFORM_MACOSX
333 if (is_macos_10_5_or_higher ())
334 handler = g_strdup ("/usr/bin/open -W");
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);
388 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
389 sei->hProcess = process_info.hProcess;
391 CloseHandle (process_info.hProcess);
398 is_managed_binary (const gchar *filename)
400 int original_errno = errno;
401 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
402 int file = open (filename, O_RDONLY | O_LARGEFILE);
404 int file = open (filename, O_RDONLY);
407 unsigned char buffer[8];
408 off_t file_size, optional_header_offset;
409 off_t pe_header_offset;
410 gboolean managed = FALSE;
412 guint32 first_word, second_word;
414 /* If we are unable to open the file, then we definitely
415 * can't say that it is managed. The child mono process
416 * probably wouldn't be able to open it anyway.
419 errno = original_errno;
423 /* Retrieve the length of the file for future sanity checks. */
424 file_size = lseek (file, 0, SEEK_END);
425 lseek (file, 0, SEEK_SET);
427 /* We know we need to read a header field at offset 60. */
431 num_read = read (file, buffer, 2);
433 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
436 new_offset = lseek (file, 60, SEEK_SET);
438 if (new_offset != 60)
441 num_read = read (file, buffer, 4);
445 pe_header_offset = buffer[0]
450 if (pe_header_offset + 24 > file_size)
453 new_offset = lseek (file, pe_header_offset, SEEK_SET);
455 if (new_offset != pe_header_offset)
458 num_read = read (file, buffer, 4);
460 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
464 * Verify that the header we want in the optional header data
465 * is present in this binary.
467 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
469 if (new_offset != pe_header_offset + 20)
472 num_read = read (file, buffer, 2);
474 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
477 /* Read the CLR header address and size fields. These will be
478 * zero if the binary is not managed.
480 optional_header_offset = pe_header_offset + 24;
481 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
483 if (new_offset != optional_header_offset + 208)
486 num_read = read (file, buffer, 8);
488 /* We are not concerned with endianness, only with
489 * whether it is zero or not.
491 first_word = *(guint32 *)&buffer[0];
492 second_word = *(guint32 *)&buffer[4];
494 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
501 errno = original_errno;
505 gboolean CreateProcessWithLogonW (const gunichar2 *username,
506 const gunichar2 *domain,
507 const gunichar2 *password,
508 const guint32 logonFlags,
509 const gunichar2 *appname,
510 const gunichar2 *cmdline,
511 guint32 create_flags,
513 const gunichar2 *cwd,
514 WapiStartupInfo *startup,
515 WapiProcessInformation *process_info)
517 /* FIXME: use user information */
518 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
522 is_executable (const char *prog)
525 if (access (prog, X_OK) != 0)
527 if (stat (prog, &buf))
529 if (S_ISREG (buf.st_mode))
535 switchDirectorySeparators(gchar *path)
537 size_t i, pathLength = strlen(path);
539 /* Turn all the slashes round the right way, except for \' */
540 /* There are probably other characters that need to be excluded as well. */
541 for (i = 0; i < pathLength; i++)
543 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' ) {
549 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
550 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
551 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
552 gboolean inherit_handles, guint32 create_flags,
553 gpointer new_environ, const gunichar2 *cwd,
554 WapiStartupInfo *startup,
555 WapiProcessInformation *process_info)
557 gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
558 guint32 i, env_count = 0;
559 gboolean ret = FALSE;
561 struct _WapiHandle_process process_handle = {0}, *process_handle_data;
563 int in_fd, out_fd, err_fd;
566 int startup_pipe [2] = {-1, -1};
568 struct MonoProcess *mono_process;
569 gboolean fork_failed = FALSE;
571 mono_once (&process_ops_once, process_ops_init);
572 mono_once (&process_sig_chld_once, process_add_sigchld_handler);
574 /* appname and cmdline specify the executable and its args:
576 * If appname is not NULL, it is the name of the executable.
577 * Otherwise the executable is the first token in cmdline.
579 * Executable searching:
581 * If appname is not NULL, it can specify the full path and
582 * file name, or else a partial name and the current directory
583 * will be used. There is no additional searching.
585 * If appname is NULL, the first whitespace-delimited token in
586 * cmdline is used. If the name does not contain a full
587 * directory path, the search sequence is:
589 * 1) The directory containing the current process
590 * 2) The current working directory
591 * 3) The windows system directory (Ignored)
592 * 4) The windows directory (Ignored)
595 * Just to make things more interesting, tokens can contain
596 * white space if they are surrounded by quotation marks. I'm
597 * beginning to understand just why windows apps are generally
598 * so crap, with an API like this :-(
600 if (appname != NULL) {
601 cmd = mono_unicode_to_external (appname);
603 DEBUG ("%s: unicode conversion returned NULL",
606 SetLastError (ERROR_PATH_NOT_FOUND);
610 switchDirectorySeparators(cmd);
613 if (cmdline != NULL) {
614 args = mono_unicode_to_external (cmdline);
616 DEBUG ("%s: unicode conversion returned NULL", __func__);
618 SetLastError (ERROR_PATH_NOT_FOUND);
624 dir = mono_unicode_to_external (cwd);
626 DEBUG ("%s: unicode conversion returned NULL", __func__);
628 SetLastError (ERROR_PATH_NOT_FOUND);
632 /* Turn all the slashes round the right way */
633 switchDirectorySeparators(dir);
637 /* We can't put off locating the executable any longer :-( */
640 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
641 /* Strip off the drive letter. I can't
642 * believe that CP/M holdover is still
645 g_memmove (cmd, cmd+2, strlen (cmd)-2);
646 cmd[strlen (cmd)-2] = '\0';
649 unquoted = g_shell_unquote (cmd, NULL);
650 if (unquoted[0] == '/') {
651 /* Assume full path given */
652 prog = g_strdup (unquoted);
654 /* Executable existing ? */
655 if (!is_executable (prog)) {
656 DEBUG ("%s: Couldn't find executable %s",
659 SetLastError (ERROR_FILE_NOT_FOUND);
663 /* Search for file named by cmd in the current
666 char *curdir = g_get_current_dir ();
668 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
671 /* And make sure it's executable */
672 if (!is_executable (prog)) {
673 DEBUG ("%s: Couldn't find executable %s",
676 SetLastError (ERROR_FILE_NOT_FOUND);
682 args_after_prog = args;
687 /* Dig out the first token from args, taking quotation
691 /* First, strip off all leading whitespace */
692 args = g_strchug (args);
694 /* args_after_prog points to the contents of args
695 * after token has been set (otherwise argv[0] is
698 args_after_prog = args;
700 /* Assume the opening quote will always be the first
703 if (args[0] == '\"' || args [0] == '\'') {
705 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
706 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
707 /* We found the first token */
708 token = g_strndup (args+1, i-1);
709 args_after_prog = g_strchug (args + i + 1);
711 /* Quotation mark appeared in the
712 * middle of the token. Just give the
713 * whole first token, quotes and all,
720 /* No quote mark, or malformed */
721 for (i = 0; args[i] != '\0'; i++) {
722 if (g_ascii_isspace (args[i])) {
723 token = g_strndup (args, i);
724 args_after_prog = args + i + 1;
730 if (token == NULL && args[0] != '\0') {
731 /* Must be just one token in the string */
732 token = g_strdup (args);
733 args_after_prog = NULL;
738 DEBUG ("%s: Couldn't find what to exec", __func__);
740 SetLastError (ERROR_PATH_NOT_FOUND);
744 /* Turn all the slashes round the right way. Only for
747 switchDirectorySeparators(token);
749 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
750 /* Strip off the drive letter. I can't
751 * believe that CP/M holdover is still
754 g_memmove (token, token+2, strlen (token)-2);
755 token[strlen (token)-2] = '\0';
758 if (token[0] == '/') {
759 /* Assume full path given */
760 prog = g_strdup (token);
762 /* Executable existing ? */
763 if (!is_executable (prog)) {
764 DEBUG ("%s: Couldn't find executable %s",
767 SetLastError (ERROR_FILE_NOT_FOUND);
772 char *curdir = g_get_current_dir ();
774 /* FIXME: Need to record the directory
775 * containing the current process, and check
776 * that for the new executable as the first
780 prog = g_strdup_printf ("%s/%s", curdir, token);
783 /* I assume X_OK is the criterion to use,
786 if (!is_executable (prog)) {
788 prog = g_find_program_in_path (token);
790 DEBUG ("%s: Couldn't find executable %s", __func__, token);
793 SetLastError (ERROR_FILE_NOT_FOUND);
802 DEBUG ("%s: Exec prog [%s] args [%s]", __func__, prog,
805 /* Check for CLR binaries; if found, we will try to invoke
806 * them using the same mono binary that started us.
808 if (is_managed_binary (prog)) {
809 gunichar2 *newapp, *newcmd;
812 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
814 if (newapp != NULL) {
815 if (appname != NULL) {
816 newcmd = utf16_concat (newapp, utf16_space,
817 appname, utf16_space,
820 newcmd = utf16_concat (newapp, utf16_space,
824 g_free ((gunichar2 *)newapp);
826 if (newcmd != NULL) {
827 ret = CreateProcess (NULL, newcmd,
831 create_flags, new_environ,
835 g_free ((gunichar2 *)newcmd);
842 if (args_after_prog != NULL && *args_after_prog) {
845 qprog = g_shell_quote (prog);
846 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
849 full_prog = g_shell_quote (prog);
852 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
854 g_message ("CreateProcess: %s\n", gerr->message);
860 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
861 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
862 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
863 err_fd = GPOINTER_TO_UINT (startup->hStdError);
865 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
866 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
867 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
870 g_strlcpy (process_handle.proc_name, prog,
871 _WAPI_PROC_NAME_MAX_LEN - 1);
873 process_set_defaults (&process_handle);
875 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
876 if (handle == _WAPI_HANDLE_INVALID) {
877 g_warning ("%s: error creating process handle", __func__);
880 SetLastError (ERROR_OUTOFMEMORY);
884 /* new_environ is a block of NULL-terminated strings, which
885 * is itself NULL-terminated. Of course, passing an array of
886 * string pointers would have made things too easy :-(
888 * If new_environ is not NULL it specifies the entire set of
889 * environment variables in the new process. Otherwise the
890 * new process inherits the same environment.
892 if (new_environ != NULL) {
893 gunichar2 *new_environp;
895 /* Count the number of strings */
896 for (new_environp = (gunichar2 *)new_environ; *new_environp;
899 while (*new_environp) {
904 /* +2: one for the process handle value, and the last
907 env_strings = g_new0 (gchar *, env_count + 2);
909 /* Copy each environ string into 'strings' turning it
910 * into utf8 (or the requested encoding) at the same
914 for (new_environp = (gunichar2 *)new_environ; *new_environp;
916 env_strings[env_count] = mono_unicode_to_external (new_environp);
918 while (*new_environp) {
923 for (i = 0; environ[i] != NULL; i++) {
927 /* +2: one for the process handle value, and the last
930 env_strings = g_new0 (gchar *, env_count + 2);
932 /* Copy each environ string into 'strings' turning it
933 * into utf8 (or the requested encoding) at the same
937 for (i = 0; environ[i] != NULL; i++) {
938 env_strings[env_count] = g_strdup (environ[i]);
942 /* pass process handle info to the child, so it doesn't have
943 * to do an expensive search over the whole list
945 if (env_strings != NULL) {
946 struct _WapiHandleUnshared *handle_data;
947 struct _WapiHandle_shared_ref *ref;
949 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
950 ref = &handle_data->u.shared;
952 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
955 /* Create a pipe to make sure the child doesn't exit before
956 * we can add the process to the linked list of mono_processes */
957 if (pipe (startup_pipe) == -1) {
958 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
959 * This is just for a very hard to hit race condition in the first place */
960 startup_pipe [0] = startup_pipe [1] = -1;
961 DEBUG ("%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
964 thr_ret = _wapi_handle_lock_shared_handles ();
965 g_assert (thr_ret == 0);
970 SetLastError (ERROR_OUTOFMEMORY);
974 } else if (pid == 0) {
977 if (startup_pipe [0] != -1) {
978 /* Wait until the parent has updated it's internal data */
979 ssize_t _i G_GNUC_UNUSED = read (startup_pipe [0], &dummy, 1);
980 DEBUG ("%s: child: parent has completed its setup", __func__);
981 close (startup_pipe [0]);
982 close (startup_pipe [1]);
985 /* should we detach from the process group? */
987 /* Connect stdin, stdout and stderr */
992 if (inherit_handles != TRUE) {
993 /* FIXME: do something here */
996 /* Close all file descriptors */
997 for (i = getdtablesize () - 1; i > 2; i--) {
1001 #ifdef DEBUG_ENABLED
1002 DEBUG ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1004 for (i = 0; argv[i] != NULL; i++) {
1005 g_message ("arg %d: [%s]", i, argv[i]);
1008 for (i = 0; env_strings[i] != NULL; i++) {
1009 g_message ("env %d: [%s]", i, env_strings[i]);
1014 if (dir != NULL && chdir (dir) == -1) {
1020 execve (argv[0], argv, env_strings);
1027 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1028 (gpointer *)&process_handle_data);
1030 g_warning ("%s: error looking up process handle %p", __func__,
1032 _wapi_handle_unref (handle);
1036 process_handle_data->id = pid;
1038 /* Add our mono_process into the linked list of mono_processes */
1039 mono_process = (struct MonoProcess *) g_malloc0 (sizeof (struct MonoProcess));
1040 mono_process->pid = pid;
1041 mono_process->handle_count = 1;
1042 if (MONO_SEM_INIT (&mono_process->exit_sem, 0) != 0) {
1043 /* If we can't create the exit semaphore, we just don't add anything
1044 * to our list of mono processes. Waiting on the process will return
1046 g_warning ("%s: could not create exit semaphore for process.", strerror (errno));
1047 g_free (mono_process);
1049 /* Keep the process handle artificially alive until the process
1050 * exits so that the information in the handle isn't lost. */
1051 _wapi_handle_ref (handle);
1052 mono_process->handle = handle;
1054 process_handle_data->self = _wapi_getpid ();
1055 process_handle_data->mono_process = mono_process;
1057 mono_mutex_lock (&mono_processes_mutex);
1058 mono_process->next = mono_processes;
1059 mono_processes = mono_process;
1060 mono_mutex_unlock (&mono_processes_mutex);
1063 if (process_info != NULL) {
1064 process_info->hProcess = handle;
1065 process_info->dwProcessId = pid;
1067 /* FIXME: we might need to handle the thread info some
1070 process_info->hThread = INVALID_HANDLE_VALUE;
1071 process_info->dwThreadId = 0;
1075 _wapi_handle_unlock_shared_handles ();
1078 _wapi_handle_unref (handle);
1080 if (startup_pipe [1] != -1) {
1081 /* Write 1 byte, doesn't matter what */
1082 ssize_t _i G_GNUC_UNUSED = write (startup_pipe [1], startup_pipe, 1);
1083 close (startup_pipe [0]);
1084 close (startup_pipe [1]);
1091 if (full_prog != NULL) {
1103 if(env_strings != NULL) {
1104 g_strfreev (env_strings);
1110 DEBUG ("%s: returning handle %p for pid %d", __func__, handle,
1113 /* Check if something needs to be cleaned up. */
1114 mono_processes_cleanup ();
1119 static void process_set_name (struct _WapiHandle_process *process_handle)
1121 gchar *progname, *utf8_progname, *slash;
1123 progname=g_get_prgname ();
1124 utf8_progname=mono_utf8_from_external (progname);
1126 DEBUG ("%s: using [%s] as prog name", __func__, progname);
1128 if(utf8_progname!=NULL) {
1129 slash=strrchr (utf8_progname, '/');
1131 g_strlcpy (process_handle->proc_name, slash+1,
1132 _WAPI_PROC_NAME_MAX_LEN - 1);
1134 g_strlcpy (process_handle->proc_name, utf8_progname,
1135 _WAPI_PROC_NAME_MAX_LEN - 1);
1138 g_free (utf8_progname);
1142 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
1144 #if !GLIB_CHECK_VERSION (2,4,0)
1145 #define g_setenv(a,b,c) setenv(a,b,c)
1146 #define g_unsetenv(a) unsetenv(a)
1149 static void process_set_current (void)
1151 pid_t pid = _wapi_getpid ();
1152 const char *handle_env;
1153 struct _WapiHandle_process process_handle = {0};
1155 mono_once (&process_ops_once, process_ops_init);
1157 handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1158 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1160 if (handle_env != NULL) {
1161 struct _WapiHandle_process *process_handlep;
1162 gchar *procname = NULL;
1165 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
1167 DEBUG ("%s: Found my process handle: %p (offset %d 0x%x)",
1168 __func__, current_process, atoi (handle_env),
1171 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
1172 (gpointer *)&process_handlep);
1174 /* This test will probably break on linuxthreads, but
1175 * that should be ancient history on all distros we
1178 if (process_handlep->id == pid) {
1179 procname = process_handlep->proc_name;
1180 if (!strcmp (procname, "mono")) {
1181 /* Set a better process name */
1182 DEBUG ("%s: Setting better process name", __func__);
1184 process_set_name (process_handlep);
1186 DEBUG ("%s: Leaving process name: %s", __func__, procname);
1192 /* Wrong pid, so drop this handle and fall through to
1195 _wapi_handle_unref (current_process);
1199 /* We get here if the handle wasn't specified in the
1200 * environment, or if the process ID was wrong, or if the
1201 * handle lookup failed (eg if the parent process forked and
1202 * quit immediately, and deleted the shared data before the
1203 * child got a chance to attach it.)
1206 DEBUG ("%s: Need to create my own process handle", __func__);
1208 process_handle.id = pid;
1210 process_set_defaults (&process_handle);
1211 process_set_name (&process_handle);
1213 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1215 if (current_process == _WAPI_HANDLE_INVALID) {
1216 g_warning ("%s: error creating process handle", __func__);
1221 gpointer _wapi_process_duplicate ()
1223 mono_once (&process_current_once, process_set_current);
1225 _wapi_handle_ref (current_process);
1227 return(current_process);
1230 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1231 gpointer GetCurrentProcess (void)
1233 mono_once (&process_current_once, process_set_current);
1235 return(_WAPI_PROCESS_CURRENT);
1238 guint32 GetProcessId (gpointer handle)
1240 struct _WapiHandle_process *process_handle;
1243 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1244 /* This is a pseudo handle */
1245 return(GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
1248 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1249 (gpointer *)&process_handle);
1251 SetLastError (ERROR_INVALID_HANDLE);
1255 return (process_handle->id);
1258 guint32 GetCurrentProcessId (void)
1260 mono_once (&process_current_once, process_set_current);
1262 return (GetProcessId (current_process));
1265 /* Returns the process id as a convenience to the functions that call this */
1266 static pid_t signal_process_if_gone (gpointer handle)
1268 struct _WapiHandle_process *process_handle;
1271 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
1273 /* Make sure the process is signalled if it has exited - if
1274 * the parent process didn't wait for it then it won't be
1276 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1277 (gpointer *)&process_handle);
1279 /* It's possible that the handle has vanished during
1280 * the _wapi_search_handle before it gets here, so
1281 * don't spam the console with warnings.
1283 /* g_warning ("%s: error looking up process handle %p",
1284 __func__, handle);*/
1289 DEBUG ("%s: looking at process %d", __func__, process_handle->id);
1291 if (kill (process_handle->id, 0) == -1 &&
1294 /* The process is dead, (EPERM tells us a new process
1295 * has that ID, but as it's owned by someone else it
1296 * can't be the one listed in our shared memory file)
1298 _wapi_shared_handle_set_signal_state (handle, TRUE);
1301 return (process_handle->id);
1305 static gboolean process_enum (gpointer handle, gpointer user_data)
1307 GArray *processes=user_data;
1308 pid_t pid = signal_process_if_gone (handle);
1315 /* Ignore processes that have already exited (ie they are signalled) */
1316 if (_wapi_handle_issignalled (handle) == FALSE) {
1317 DEBUG ("%s: process %d added to array", __func__, pid);
1319 /* This ensures that duplicates aren't returned (see
1320 * the comment above _wapi_search_handle () for why
1323 for (i = 0; i < processes->len; i++) {
1324 if (g_array_index (processes, pid_t, i) == pid) {
1325 /* We've already got this one, return
1326 * FALSE to keep searching
1332 g_array_append_val (processes, pid);
1335 /* Return false to keep searching */
1338 #endif /* UNUSED_CODE */
1340 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
1342 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1344 guint32 count, fit, i, j;
1347 size_t proclength, size;
1348 #if defined(__OpenBSD__)
1349 struct kinfo_proc2 *result;
1352 name[1] = KERN_PROC2;
1353 name[2] = KERN_PROC_ALL;
1355 name[4] = sizeof(struct kinfo_proc2);
1358 struct kinfo_proc *result;
1359 static const int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
1362 mono_once (&process_current_once, process_set_current);
1369 #if defined(__OpenBSD__)
1370 size = (sizeof(name) / sizeof(*name));
1372 size = (sizeof(name) / sizeof(*name)) - 1;
1374 err = sysctl ((int *)name, size, NULL, &proclength, NULL, 0);
1377 result = malloc (proclength);
1382 #if defined(__OpenBSD__)
1383 name[5] = (int)(proclength / sizeof(struct kinfo_proc2));
1386 err = sysctl ((int *) name, size, result, &proclength, NULL, 0);
1393 } while (err == 0 && !done);
1396 if (result != NULL) {
1403 #if defined(__OpenBSD__)
1404 count = proclength / sizeof(struct kinfo_proc2);
1406 count = proclength / sizeof(struct kinfo_proc);
1408 fit = len / sizeof(guint32);
1409 for (i = 0, j = 0; j< fit && i < count; i++) {
1410 #if defined(__OpenBSD__)
1411 pids [j++] = result [i].p_pid;
1413 if (result[i].kp_proc.p_pid > 0) /* Pid 0 not supported */
1414 pids [j++] = result [i].kp_proc.p_pid;
1419 *needed = j * sizeof(guint32);
1423 #elif defined(__HAIKU__)
1425 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1431 mono_once (&process_current_once, process_set_current);
1433 fit = len / sizeof (guint32);
1434 while (get_next_team_info (&cookie, &teamInfo) == B_OK && i < fit) {
1435 pids [i++] = teamInfo.team;
1437 *needed = i * sizeof (guint32);
1442 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1446 struct dirent *entry;
1448 mono_once (&process_current_once, process_set_current);
1450 dir = opendir ("/proc");
1456 fit = len / sizeof (guint32);
1457 while(i < fit && (entry = readdir (dir)) != NULL) {
1461 if (!isdigit (entry->d_name[0]))
1464 pid = (pid_t) strtol (entry->d_name, &endptr, 10);
1465 if (*endptr == '\0')
1466 pids [i++] = (guint32) pid;
1469 *needed = i * sizeof(guint32);
1475 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1478 pid_t checking_pid = signal_process_if_gone (handle);
1480 if (checking_pid == 0) {
1484 wanted_pid = GPOINTER_TO_UINT (user_data);
1486 /* It's possible to have more than one process handle with the
1487 * same pid, but only the one running process can be
1490 if (checking_pid == wanted_pid &&
1491 _wapi_handle_issignalled (handle) == FALSE) {
1492 /* If the handle is blown away in the window between
1493 * returning TRUE here and _wapi_search_handle pinging
1494 * the timestamp, the search will continue
1502 gboolean CloseProcess(gpointer handle)
1504 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1505 /* This is a pseudo handle */
1509 return CloseHandle (handle);
1513 * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1515 gpointer OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1517 /* Find the process handle that corresponds to pid */
1518 gpointer handle = NULL;
1520 mono_once (&process_current_once, process_set_current);
1522 DEBUG ("%s: looking for process %d", __func__, pid);
1524 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1525 process_open_compare,
1526 GUINT_TO_POINTER (pid), NULL, TRUE);
1528 if (is_pid_valid (pid)) {
1529 /* Return a pseudo handle for processes we
1530 * don't have handles for
1532 return GINT_TO_POINTER (_WAPI_PROCESS_UNHANDLED + pid);
1534 DEBUG ("%s: Can't find pid %d", __func__, pid);
1536 SetLastError (ERROR_PROC_NOT_FOUND);
1542 /* _wapi_search_handle () already added a ref */
1546 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1548 struct _WapiHandle_process *process_handle;
1552 mono_once (&process_current_once, process_set_current);
1558 pid = GPOINTER_TO_UINT (process) - _WAPI_PROCESS_UNHANDLED;
1559 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1560 /* This is a pseudo handle, so we don't know what the
1561 * exit code was, but we can check whether it's alive or not
1563 if (is_pid_valid (pid)) {
1564 *code = STILL_ACTIVE;
1571 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1572 (gpointer *)&process_handle);
1574 DEBUG ("%s: Can't find process %p", __func__, process);
1579 /* A process handle is only signalled if the process has exited
1580 * and has been waited for */
1582 /* Make sure any process exit has been noticed, before
1583 * checking if the process is signalled. Fixes bug 325463.
1585 process_wait (process, 0, TRUE);
1587 if (_wapi_handle_issignalled (process) == TRUE) {
1588 *code = process_handle->exitstatus;
1590 *code = STILL_ACTIVE;
1596 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1597 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1598 WapiFileTime *user_time)
1600 struct _WapiHandle_process *process_handle;
1602 gboolean ku_times_set = FALSE;
1604 mono_once (&process_current_once, process_set_current);
1606 if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1608 /* Not sure if w32 allows NULLs here or not */
1612 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1613 /* This is a pseudo handle, so just fail for now
1618 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1619 (gpointer *)&process_handle);
1621 DEBUG ("%s: Can't find process %p", __func__, process);
1626 *create_time=process_handle->create_time;
1628 /* A process handle is only signalled if the process has
1629 * exited. Otherwise exit_time isn't set
1631 if(_wapi_handle_issignalled (process)==TRUE) {
1632 *exit_time=process_handle->exit_time;
1635 #ifdef HAVE_GETRUSAGE
1636 if (process_handle->id == getpid ()) {
1637 struct rusage time_data;
1638 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1640 gint64 *tick_val_ptr;
1641 ku_times_set = TRUE;
1642 tick_val = time_data.ru_utime.tv_sec * 10000000 + time_data.ru_utime.tv_usec * 10;
1643 tick_val_ptr = (gint64*)user_time;
1644 *tick_val_ptr = tick_val;
1645 tick_val = time_data.ru_stime.tv_sec * 10000000 + time_data.ru_stime.tv_usec * 10;
1646 tick_val_ptr = (gint64*)kernel_time;
1647 *tick_val_ptr = tick_val;
1651 if (!ku_times_set) {
1652 memset (kernel_time, 0, sizeof (WapiFileTime));
1653 memset (user_time, 0, sizeof (WapiFileTime));
1661 gpointer address_start;
1662 gpointer address_end;
1664 gpointer address_offset;
1670 static void free_procmodule (WapiProcModule *mod)
1672 if (mod->perms != NULL) {
1673 g_free (mod->perms);
1675 if (mod->filename != NULL) {
1676 g_free (mod->filename);
1681 static gint find_procmodule (gconstpointer a, gconstpointer b)
1683 WapiProcModule *want = (WapiProcModule *)a;
1684 WapiProcModule *compare = (WapiProcModule *)b;
1686 if ((want->device == compare->device) &&
1687 (want->inode == compare->inode)) {
1694 #ifdef PLATFORM_MACOSX
1695 #include <mach-o/dyld.h>
1696 #include <mach-o/getsect.h>
1698 static GSList *load_modules (void)
1701 WapiProcModule *mod;
1702 uint32_t count = _dyld_image_count ();
1705 for (i = 0; i < count; i++) {
1706 #if SIZEOF_VOID_P == 8
1707 const struct mach_header_64 *hdr;
1708 const struct section_64 *sec;
1710 const struct mach_header *hdr;
1711 const struct section *sec;
1716 slide = _dyld_get_image_vmaddr_slide (i);
1717 name = _dyld_get_image_name (i);
1718 #if SIZEOF_VOID_P == 8
1719 hdr = (const struct mach_header_64*)_dyld_get_image_header (i);
1720 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1722 hdr = _dyld_get_image_header (i);
1723 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1726 /* Some dynlibs do not have data sections on osx (#533893) */
1731 mod = g_new0 (WapiProcModule, 1);
1732 mod->address_start = GINT_TO_POINTER (sec->addr);
1733 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1734 mod->perms = g_strdup ("r--p");
1735 mod->address_offset = 0;
1736 mod->device = makedev (0, 0);
1737 mod->inode = (ino_t) i;
1738 mod->filename = g_strdup (name);
1740 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1741 ret = g_slist_prepend (ret, mod);
1743 free_procmodule (mod);
1747 ret = g_slist_reverse (ret);
1751 #elif defined(__OpenBSD__)
1753 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1755 if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1756 + sizeof (info->dlpi_phnum))
1759 struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1763 memcpy(cpy, info, sizeof(*info));
1765 g_ptr_array_add ((GPtrArray *)ptr, cpy);
1770 static GSList *load_modules (void)
1773 WapiProcModule *mod;
1774 GPtrArray *dlarray = g_ptr_array_new();
1777 if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1780 for (i = 0; i < dlarray->len; i++) {
1781 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1783 mod = g_new0 (WapiProcModule, 1);
1784 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1785 mod->address_end = (gpointer)(info->dlpi_addr +
1786 info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1787 mod->perms = g_strdup ("r--p");
1788 mod->address_offset = 0;
1789 mod->inode = (ino_t) i;
1790 mod->filename = g_strdup (info->dlpi_name);
1792 DEBUG ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1793 mod->inode, mod->filename, mod->address_start, mod->address_end);
1797 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1798 ret = g_slist_prepend (ret, mod);
1800 free_procmodule (mod);
1804 g_ptr_array_free (dlarray, TRUE);
1806 ret = g_slist_reverse (ret);
1810 #elif defined(__HAIKU__)
1812 static GSList *load_modules (void)
1815 WapiProcModule *mod;
1817 image_info imageInfo;
1819 while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
1820 mod = g_new0 (WapiProcModule, 1);
1821 mod->device = imageInfo.device;
1822 mod->inode = imageInfo.node;
1823 mod->filename = g_strdup (imageInfo.name);
1824 mod->address_start = MIN (imageInfo.text, imageInfo.data);
1825 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
1826 (uint8_t*)imageInfo.data + imageInfo.data_size);
1827 mod->perms = g_strdup ("r--p");
1828 mod->address_offset = 0;
1830 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1831 ret = g_slist_prepend (ret, mod);
1833 free_procmodule (mod);
1837 ret = g_slist_reverse (ret);
1842 static GSList *load_modules (FILE *fp)
1845 WapiProcModule *mod;
1846 gchar buf[MAXPATHLEN + 1], *p, *endp;
1847 gchar *start_start, *end_start, *prot_start, *offset_start;
1848 gchar *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1849 gpointer address_start, address_end, address_offset;
1850 guint32 maj_dev, min_dev;
1854 while (fgets (buf, sizeof(buf), fp)) {
1856 while (g_ascii_isspace (*p)) ++p;
1858 if (!g_ascii_isxdigit (*start_start)) {
1861 address_start = (gpointer)strtoul (start_start, &endp, 16);
1869 if (!g_ascii_isxdigit (*end_start)) {
1872 address_end = (gpointer)strtoul (end_start, &endp, 16);
1874 if (!g_ascii_isspace (*p)) {
1878 while (g_ascii_isspace (*p)) ++p;
1880 if (*prot_start != 'r' && *prot_start != '-') {
1883 memcpy (prot_buf, prot_start, 4);
1885 while (!g_ascii_isspace (*p)) ++p;
1887 while (g_ascii_isspace (*p)) ++p;
1889 if (!g_ascii_isxdigit (*offset_start)) {
1892 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1894 if (!g_ascii_isspace (*p)) {
1898 while(g_ascii_isspace (*p)) ++p;
1900 if (!g_ascii_isxdigit (*maj_dev_start)) {
1903 maj_dev = strtoul (maj_dev_start, &endp, 16);
1911 if (!g_ascii_isxdigit (*min_dev_start)) {
1914 min_dev = strtoul (min_dev_start, &endp, 16);
1916 if (!g_ascii_isspace (*p)) {
1920 while (g_ascii_isspace (*p)) ++p;
1922 if (!g_ascii_isxdigit (*inode_start)) {
1925 inode = (ino_t)strtol (inode_start, &endp, 10);
1927 if (!g_ascii_isspace (*p)) {
1931 device = makedev ((int)maj_dev, (int)min_dev);
1932 if ((device == 0) &&
1937 while(g_ascii_isspace (*p)) ++p;
1938 /* p now points to the filename */
1940 mod = g_new0 (WapiProcModule, 1);
1941 mod->address_start = address_start;
1942 mod->address_end = address_end;
1943 mod->perms = g_strdup (prot_buf);
1944 mod->address_offset = address_offset;
1945 mod->device = device;
1947 mod->filename = g_strdup (g_strstrip (p));
1949 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1950 ret = g_slist_prepend (ret, mod);
1952 free_procmodule (mod);
1956 ret = g_slist_reverse (ret);
1962 static gboolean match_procname_to_modulename (gchar *procname, gchar *modulename)
1964 char* lastsep = NULL;
1965 char* lastsep2 = NULL;
1968 gboolean result = FALSE;
1970 if (procname == NULL || modulename == NULL)
1973 pname = mono_path_resolve_symlinks (procname);
1974 mname = mono_path_resolve_symlinks (modulename);
1976 if (!strcmp (pname, mname))
1980 lastsep = strrchr (mname, '/');
1982 if (!strcmp (lastsep+1, pname))
1985 lastsep2 = strrchr (pname, '/');
1988 if (!strcmp (lastsep+1, lastsep2+1))
1991 if (!strcmp (mname, lastsep2+1))
2004 #if !defined(__OpenBSD__)
2006 open_process_map (int pid, const char *mode)
2009 const gchar *proc_path[] = {
2010 "/proc/%d/maps", /* GNU/Linux */
2011 "/proc/%d/map", /* FreeBSD */
2017 for (i = 0; fp == NULL && proc_path [i]; i++) {
2018 filename = g_strdup_printf (proc_path[i], pid);
2019 fp = fopen (filename, mode);
2027 gboolean EnumProcessModules (gpointer process, gpointer *modules,
2028 guint32 size, guint32 *needed)
2030 struct _WapiHandle_process *process_handle;
2032 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2035 GSList *mods = NULL;
2036 WapiProcModule *module;
2037 guint32 count, avail = size / sizeof(gpointer);
2040 gchar *proc_name = NULL;
2042 /* Store modules in an array of pointers (main module as
2043 * modules[0]), using the load address for each module as a
2044 * token. (Use 'NULL' as an alternative for the main module
2045 * so that the simple implementation can just return one item
2046 * for now.) Get the info from /proc/<pid>/maps on linux,
2047 * /proc/<pid>/map on FreeBSD, other systems will have to
2048 * implement /dev/kmem reading or whatever other horrid
2049 * technique is needed.
2051 if (size < sizeof(gpointer)) {
2055 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2056 /* This is a pseudo handle */
2057 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2059 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2060 (gpointer *)&process_handle);
2062 DEBUG ("%s: Can't find process %p", __func__, process);
2066 pid = process_handle->id;
2067 proc_name = process_handle->proc_name;
2070 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2072 mods = load_modules ();
2074 if ((fp = open_process_map (pid, "r")) == NULL) {
2075 /* No /proc/<pid>/maps so just return the main module
2079 *needed = sizeof(gpointer);
2081 mods = load_modules (fp);
2084 count = g_slist_length (mods);
2086 /* count + 1 to leave slot 0 for the main module */
2087 *needed = sizeof(gpointer) * (count + 1);
2089 /* Use the NULL shortcut, as the first line in
2090 * /proc/<pid>/maps isn't the executable, and we need
2091 * that first in the returned list. Check the module name
2092 * to see if it ends with the proc name and substitute
2093 * the first entry with it. FIXME if this turns out to
2097 for (i = 0; i < (avail - 1) && i < count; i++) {
2098 module = (WapiProcModule *)g_slist_nth_data (mods, i);
2099 if (modules[0] != NULL)
2100 modules[i] = module->address_start;
2101 else if (match_procname_to_modulename (proc_name, module->filename))
2102 modules[0] = module->address_start;
2104 modules[i + 1] = module->address_start;
2107 for (i = 0; i < count; i++) {
2108 free_procmodule (g_slist_nth_data (mods, i));
2110 g_slist_free (mods);
2116 static gchar *get_process_name_from_proc (pid_t pid)
2118 #if defined(__OpenBSD__)
2121 struct kinfo_proc2 *pi;
2122 #elif defined(PLATFORM_MACOSX)
2123 #if !(!defined (__mono_ppc__) && defined (TARGET_OSX))
2125 struct kinfo_proc *pi;
2126 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
2130 gchar *filename = NULL;
2135 #if defined(PLATFORM_SOLARIS)
2136 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
2137 if ((fp = fopen (filename, "r")) != NULL) {
2141 nread = fread (&info, sizeof (info), 1, fp);
2143 ret = g_strdup (info.pr_fname);
2149 #elif defined(PLATFORM_MACOSX)
2150 #if !defined (__mono_ppc__) && defined (TARGET_OSX)
2151 /* No proc name on OSX < 10.5 nor ppc nor iOS */
2152 memset (buf, '\0', sizeof(buf));
2153 proc_name (pid, buf, sizeof(buf));
2154 if (strlen (buf) > 0)
2155 ret = g_strdup (buf);
2157 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0)
2160 if ((pi = malloc(size)) == NULL)
2163 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
2164 if (errno == ENOMEM) {
2166 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__);
2171 if (strlen (pi->kp_proc.p_comm) > 0)
2172 ret = g_strdup (pi->kp_proc.p_comm);
2176 #elif defined(__OpenBSD__)
2178 mib [1] = KERN_PROC2;
2179 mib [2] = KERN_PROC_PID;
2181 mib [4] = sizeof(struct kinfo_proc2);
2185 if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0)
2188 if ((pi = malloc(size)) == NULL)
2191 mib[5] = (int)(size / sizeof(struct kinfo_proc2));
2193 if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
2194 (size != sizeof (struct kinfo_proc2))) {
2195 if (errno == ENOMEM) {
2202 if (strlen (pi->p_comm) > 0)
2203 ret = g_strdup (pi->p_comm);
2206 #elif defined(__HAIKU__)
2207 image_info imageInfo;
2210 if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
2211 ret = g_strdup (imageInfo.name);
2214 memset (buf, '\0', sizeof(buf));
2215 filename = g_strdup_printf ("/proc/%d/exe", pid);
2216 if (readlink (filename, buf, 255) > 0) {
2217 ret = g_strdup (buf);
2225 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
2226 if ((fp = fopen (filename, "r")) != NULL) {
2227 if (fgets (buf, 256, fp) != NULL) {
2228 ret = g_strdup (buf);
2239 filename = g_strdup_printf ("/proc/%d/stat", pid);
2240 if ((fp = fopen (filename, "r")) != NULL) {
2241 if (fgets (buf, 256, fp) != NULL) {
2244 start = strchr (buf, '(');
2245 if (start != NULL) {
2246 end = strchr (start + 1, ')');
2249 ret = g_strndup (start + 1,
2263 static guint32 get_module_name (gpointer process, gpointer module,
2264 gunichar2 *basename, guint32 size,
2267 struct _WapiHandle_process *process_handle;
2270 gunichar2 *procname;
2271 gchar *procname_ext = NULL;
2274 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2277 GSList *mods = NULL;
2278 WapiProcModule *found_module;
2281 gchar *proc_name = NULL;
2283 mono_once (&process_current_once, process_set_current);
2285 DEBUG ("%s: Getting module base name, process handle %p module %p",
2286 __func__, process, module);
2288 size = size*sizeof(gunichar2); /* adjust for unicode characters */
2290 if (basename == NULL || size == 0) {
2294 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2295 /* This is a pseudo handle */
2296 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2297 proc_name = get_process_name_from_proc (pid);
2299 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2300 (gpointer *)&process_handle);
2302 DEBUG ("%s: Can't find process %p", __func__,
2307 pid = process_handle->id;
2308 proc_name = g_strdup (process_handle->proc_name);
2311 /* Look up the address in /proc/<pid>/maps */
2312 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2314 mods = load_modules ();
2316 if ((fp = open_process_map (pid, "r")) == NULL) {
2317 if (errno == EACCES && module == NULL && base == TRUE) {
2318 procname_ext = get_process_name_from_proc (pid);
2320 /* No /proc/<pid>/maps, so just return failure
2327 mods = load_modules (fp);
2330 count = g_slist_length (mods);
2332 /* If module != NULL compare the address.
2333 * If module == NULL we are looking for the main module.
2334 * The best we can do for now check it the module name end with the process name.
2336 for (i = 0; i < count; i++) {
2337 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2338 if (procname_ext == NULL &&
2339 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2340 (module != NULL && found_module->address_start == module))) {
2342 procname_ext = g_path_get_basename (found_module->filename);
2344 procname_ext = g_strdup (found_module->filename);
2348 free_procmodule (found_module);
2351 if (procname_ext == NULL)
2353 /* If it's *still* null, we might have hit the
2354 * case where reading /proc/$pid/maps gives an
2355 * empty file for this user.
2357 procname_ext = get_process_name_from_proc (pid);
2360 g_slist_free (mods);
2364 if (procname_ext != NULL) {
2365 DEBUG ("%s: Process name is [%s]", __func__,
2368 procname = mono_unicode_from_external (procname_ext, &bytes);
2369 if (procname == NULL) {
2371 g_free (procname_ext);
2377 /* Add the terminator */
2381 DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2383 memcpy (basename, procname, size);
2385 DEBUG ("%s: Size %d larger than needed (%ld)",
2386 __func__, size, bytes);
2388 memcpy (basename, procname, bytes);
2392 g_free (procname_ext);
2400 guint32 GetModuleBaseName (gpointer process, gpointer module,
2401 gunichar2 *basename, guint32 size)
2403 return(get_module_name (process, module, basename, size, TRUE));
2406 guint32 GetModuleFileNameEx (gpointer process, gpointer module,
2407 gunichar2 *filename, guint32 size)
2409 return(get_module_name (process, module, filename, size, FALSE));
2412 gboolean GetModuleInformation (gpointer process, gpointer module,
2413 WapiModuleInfo *modinfo, guint32 size)
2415 struct _WapiHandle_process *process_handle;
2418 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2421 GSList *mods = NULL;
2422 WapiProcModule *found_module;
2425 gboolean ret = FALSE;
2426 gchar *proc_name = NULL;
2428 mono_once (&process_current_once, process_set_current);
2430 DEBUG ("%s: Getting module info, process handle %p module %p",
2431 __func__, process, module);
2433 if (modinfo == NULL || size < sizeof(WapiModuleInfo)) {
2437 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2438 /* This is a pseudo handle */
2439 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2440 proc_name = get_process_name_from_proc (pid);
2442 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2443 (gpointer *)&process_handle);
2445 DEBUG ("%s: Can't find process %p", __func__,
2450 pid = process_handle->id;
2451 proc_name = g_strdup (process_handle->proc_name);
2454 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2456 mods = load_modules ();
2458 /* Look up the address in /proc/<pid>/maps */
2459 if ((fp = open_process_map (pid, "r")) == NULL) {
2460 /* No /proc/<pid>/maps, so just return failure
2466 mods = load_modules (fp);
2469 count = g_slist_length (mods);
2471 /* If module != NULL compare the address.
2472 * If module == NULL we are looking for the main module.
2473 * The best we can do for now check it the module name end with the process name.
2475 for (i = 0; i < count; i++) {
2476 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2477 if ( ret == FALSE &&
2478 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2479 (module != NULL && found_module->address_start == module))) {
2480 modinfo->lpBaseOfDll = found_module->address_start;
2481 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2482 modinfo->EntryPoint = found_module->address_offset;
2486 free_procmodule (found_module);
2489 g_slist_free (mods);
2496 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2498 struct _WapiHandle_process *process_handle;
2501 mono_once (&process_current_once, process_set_current);
2503 if(min==NULL || max==NULL) {
2504 /* Not sure if w32 allows NULLs here or not */
2508 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2509 /* This is a pseudo handle, so just fail for now
2514 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2515 (gpointer *)&process_handle);
2517 DEBUG ("%s: Can't find process %p", __func__, process);
2522 *min=process_handle->min_working_set;
2523 *max=process_handle->max_working_set;
2528 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2530 struct _WapiHandle_process *process_handle;
2533 mono_once (&process_current_once, process_set_current);
2535 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2536 /* This is a pseudo handle, so just fail for now
2541 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2542 (gpointer *)&process_handle);
2544 DEBUG ("%s: Can't find process %p", __func__, process);
2549 process_handle->min_working_set=min;
2550 process_handle->max_working_set=max;
2557 TerminateProcess (gpointer process, gint32 exitCode)
2559 struct _WapiHandle_process *process_handle;
2565 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2566 /* This is a pseudo handle */
2567 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2569 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2570 (gpointer *) &process_handle);
2573 DEBUG ("%s: Can't find process %p", __func__,
2575 SetLastError (ERROR_INVALID_HANDLE);
2578 pid = process_handle->id;
2581 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2582 ret = kill (pid, signo);
2586 SetLastError (ERROR_INVALID_PARAMETER);
2589 SetLastError (ERROR_ACCESS_DENIED);
2592 SetLastError (ERROR_PROC_NOT_FOUND);
2595 SetLastError (ERROR_GEN_FAILURE);
2603 GetPriorityClass (gpointer process)
2605 #ifdef HAVE_GETPRIORITY
2606 struct _WapiHandle_process *process_handle;
2611 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2612 /* This is a pseudo handle */
2613 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2615 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2616 (gpointer *) &process_handle);
2619 SetLastError (ERROR_INVALID_HANDLE);
2622 pid = process_handle->id;
2626 ret = getpriority (PRIO_PROCESS, pid);
2627 if (ret == -1 && errno != 0) {
2631 SetLastError (ERROR_ACCESS_DENIED);
2634 SetLastError (ERROR_PROC_NOT_FOUND);
2637 SetLastError (ERROR_GEN_FAILURE);
2643 return NORMAL_PRIORITY_CLASS;
2645 return REALTIME_PRIORITY_CLASS;
2647 return HIGH_PRIORITY_CLASS;
2649 return ABOVE_NORMAL_PRIORITY_CLASS;
2651 return IDLE_PRIORITY_CLASS;
2653 return BELOW_NORMAL_PRIORITY_CLASS;
2655 return NORMAL_PRIORITY_CLASS;
2657 SetLastError (ERROR_NOT_SUPPORTED);
2663 SetPriorityClass (gpointer process, guint32 priority_class)
2665 #ifdef HAVE_SETPRIORITY
2666 struct _WapiHandle_process *process_handle;
2672 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2673 /* This is a pseudo handle */
2674 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2676 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2677 (gpointer *) &process_handle);
2680 SetLastError (ERROR_INVALID_HANDLE);
2683 pid = process_handle->id;
2686 switch (priority_class) {
2687 case IDLE_PRIORITY_CLASS:
2690 case BELOW_NORMAL_PRIORITY_CLASS:
2693 case NORMAL_PRIORITY_CLASS:
2696 case ABOVE_NORMAL_PRIORITY_CLASS:
2699 case HIGH_PRIORITY_CLASS:
2702 case REALTIME_PRIORITY_CLASS:
2706 SetLastError (ERROR_INVALID_PARAMETER);
2710 ret = setpriority (PRIO_PROCESS, pid, prio);
2715 SetLastError (ERROR_ACCESS_DENIED);
2718 SetLastError (ERROR_PROC_NOT_FOUND);
2721 SetLastError (ERROR_GEN_FAILURE);
2727 SetLastError (ERROR_NOT_SUPPORTED);
2733 mono_processes_cleanup (void)
2735 struct MonoProcess *mp;
2736 struct MonoProcess *prev = NULL;
2737 struct MonoProcess *candidate = NULL;
2738 gpointer unref_handle;
2741 DEBUG ("%s", __func__);
2743 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2744 if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
2747 mp = mono_processes;
2748 while (mp != NULL) {
2749 if (mp->pid == 0 && mp->handle != NULL) {
2750 /* This process has exited and we need to remove the artifical ref
2752 mono_mutex_lock (&mono_processes_mutex);
2753 unref_handle = mp->handle;
2755 mono_mutex_unlock (&mono_processes_mutex);
2757 _wapi_handle_unref (unref_handle);
2763 mp = mono_processes;
2765 while (mp != NULL) {
2766 if ((mp->handle_count == 0 && mp->pid == 0) || candidate != NULL) {
2768 _wapi_handle_spin (spin);
2772 /* We've found a candidate */
2773 mono_mutex_lock (&mono_processes_mutex);
2774 if (candidate == NULL) {
2776 if (mp == mono_processes) {
2777 mono_processes = mp->next;
2779 prev->next = mp->next;
2784 /* It's still safe to traverse the structure.*/
2785 mono_memory_barrier ();
2787 if (mono_processes_read_lock != 0) {
2788 /* The sigchld handler is watching us. Spin a bit and try again */
2791 } else if (spin >= 8) {
2792 /* Just give up for now */
2793 mono_mutex_unlock (&mono_processes_mutex);
2797 /* We've modified the list of processes, and we know the sigchld handler
2798 * isn't executing, so even if it executes at any moment, it'll see the
2799 * new version of the list. So now we can free the candidate. */
2800 DEBUG ("%s: freeing candidate %p", __func__, candidate);
2801 mp = candidate->next;
2802 MONO_SEM_DESTROY (&candidate->exit_sem);
2807 mono_mutex_unlock (&mono_processes_mutex);
2816 DEBUG ("%s done", __func__);
2818 InterlockedDecrement (&mono_processes_cleaning_up);
2822 process_close (gpointer handle, gpointer data)
2824 struct _WapiHandle_process *process_handle;
2826 DEBUG ("%s", __func__);
2828 process_handle = (struct _WapiHandle_process *) data;
2829 if (process_handle->mono_process && process_handle->self == _wapi_getpid ())
2830 InterlockedDecrement (&process_handle->mono_process->handle_count);
2831 mono_processes_cleanup ();
2835 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
2839 struct MonoProcess *p;
2842 fprintf (stdout, "SIG CHILD handler for pid: %i\n", info->si_pid);
2845 InterlockedIncrement (&mono_processes_read_lock);
2849 pid = waitpid (-1, &status, WNOHANG);
2850 } while (pid == -1 && errno == EINTR);
2856 fprintf (stdout, "child ended: %i", pid);
2860 if (p->pid == pid) {
2861 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2863 MONO_SEM_POST (&p->exit_sem);
2870 InterlockedDecrement (&mono_processes_read_lock);
2873 fprintf (stdout, "SIG CHILD handler: done looping.");
2879 static void process_add_sigchld_handler (void)
2882 struct sigaction sa;
2884 sa.sa_sigaction = mono_sigchld_signal_handler;
2885 sigemptyset (&sa.sa_mask);
2886 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2887 g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2888 DEBUG ("Added SIGCHLD handler");
2892 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2894 struct _WapiHandle_process *process_handle;
2900 struct MonoProcess *mp;
2902 gpointer current_thread;
2904 current_thread = _wapi_thread_handle_from_id (pthread_self ());
2905 if (current_thread == NULL) {
2906 SetLastError (ERROR_INVALID_HANDLE);
2910 /* FIXME: We can now easily wait on processes that aren't our own children,
2911 * but WaitFor*Object won't call us for pseudo handles. */
2912 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2914 DEBUG ("%s (%p, %u)", __func__, handle, timeout);
2916 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS, (gpointer *)&process_handle);
2918 g_warning ("%s: error looking up process handle %p", __func__, handle);
2922 if (process_handle->exited) {
2923 /* We've already done this one */
2924 DEBUG ("%s (%p, %u): Process already exited", __func__, handle, timeout);
2925 return WAIT_OBJECT_0;
2928 pid = process_handle->id;
2930 DEBUG ("%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2932 /* We don't need to lock mono_processes here, the entry
2933 * has a handle_count > 0 which means it will not be freed. */
2934 mp = process_handle->mono_process;
2935 if (mp && process_handle->self != _wapi_getpid ()) {
2936 /* mono_process points to memory in another process' address space: we can't use it */
2940 start = mono_msec_ticks ();
2946 /* We have a semaphore we can wait on */
2947 if (timeout != INFINITE) {
2948 DEBUG ("%s (%p, %u): waiting on semaphore for %li ms...",
2949 __func__, handle, timeout, (timeout - (now - start)));
2951 ret = MONO_SEM_TIMEDWAIT_ALERTABLE (&mp->exit_sem, (timeout - (now - start)), alertable);
2953 DEBUG ("%s (%p, %u): waiting on semaphore forever...",
2954 __func__, handle, timeout);
2955 ret = MONO_SEM_WAIT_ALERTABLE (&mp->exit_sem, alertable);
2958 if (ret == -1 && errno != EINTR && errno != ETIMEDOUT) {
2959 DEBUG ("%s (%p, %u): sem_timedwait failure: %s",
2960 __func__, handle, timeout, g_strerror (errno));
2961 /* Should we return a failure here? */
2965 /* Success, process has exited */
2966 MONO_SEM_POST (&mp->exit_sem);
2970 /* We did not create this process, so we can't waidpid / sem_wait it.
2971 * We need to poll for the pid existence */
2972 DEBUG ("%s (%p, %u): polling on pid...", __func__, handle, timeout);
2973 if (!is_pid_valid (pid)) {
2974 /* Success, process has exited */
2980 DEBUG ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
2981 return WAIT_TIMEOUT;
2984 now = mono_msec_ticks ();
2985 if (now - start >= timeout) {
2986 DEBUG ("%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
2987 return WAIT_TIMEOUT;
2991 /* "timeout - (now - start)" will not underflow, since timeout is always >=0,
2992 * and we passed the check just above */
2993 _wapi_handle_spin (MIN (100, timeout - (now - start)));
2996 if (alertable && _wapi_thread_apc_pending (current_thread)) {
2997 DEBUG ("%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
2998 return WAIT_IO_COMPLETION;
3002 /* Process must have exited */
3003 DEBUG ("%s (%p, %u): Waited successfully", __func__, handle, timeout);
3005 ret = _wapi_handle_lock_shared_handles ();
3006 g_assert (ret == 0);
3008 status = mp ? mp->status : 0;
3009 if (WIFSIGNALED (status)) {
3010 process_handle->exitstatus = 128 + WTERMSIG (status);
3012 process_handle->exitstatus = WEXITSTATUS (status);
3014 _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
3016 process_handle->exited = TRUE;
3018 DEBUG ("%s (%p, %u): Setting pid %d signalled, exit status %d",
3019 __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
3021 _wapi_shared_handle_set_signal_state (handle, TRUE);
3023 _wapi_handle_unlock_shared_handles ();
3025 return WAIT_OBJECT_0;