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>
80 /* The process' environment strings */
81 #if defined(__APPLE__) && !defined (__arm__)
82 /* Apple defines this in crt_externs.h but doesn't provide that header for
83 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
84 * in fact exist on all implementations (so far)
86 gchar ***_NSGetEnviron(void);
87 #define environ (*_NSGetEnviron())
89 extern char **environ;
93 #define DEBUG(...) g_message(__VA_ARGS__)
94 #define DEBUG_ENABLED 1
99 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable);
100 static void process_close (gpointer handle, gpointer data);
101 static gboolean is_pid_valid (pid_t pid);
103 #if !defined(__OpenBSD__)
105 open_process_map (int pid, const char *mode);
108 struct _WapiHandleOps _wapi_process_ops = {
109 process_close, /* close_shared */
113 process_wait, /* special_wait */
118 static struct sigaction previous_chld_sa;
120 static mono_once_t process_sig_chld_once = MONO_ONCE_INIT;
121 static void process_add_sigchld_handler (void);
123 /* The signal-safe logic to use mono_processes goes like this:
124 * - The list must be safe to traverse for the signal handler at all times.
125 * It's safe to: prepend an entry (which is a single store to 'mono_processes'),
126 * unlink an entry (assuming the unlinked entry isn't freed and doesn't
127 * change its 'next' pointer so that it can still be traversed).
128 * When cleaning up we first unlink an entry, then we verify that
129 * the read lock isn't locked. Then we can free the entry, since
130 * we know that nobody is using the old version of the list (including
131 * the unlinked entry).
132 * We also need to lock when adding and cleaning up so that those two
133 * operations don't mess with eachother. (This lock is not used in the
136 static struct MonoProcess *mono_processes = NULL;
137 static volatile gint32 mono_processes_read_lock = 0;
138 static volatile gint32 mono_processes_cleaning_up = 0;
139 static mono_mutex_t mono_processes_mutex;
140 static void mono_processes_cleanup (void);
142 static mono_once_t process_current_once=MONO_ONCE_INIT;
143 static gpointer current_process=NULL;
145 static mono_once_t process_ops_once=MONO_ONCE_INIT;
147 static void process_ops_init (void)
149 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
150 WAPI_HANDLE_CAP_WAIT |
151 WAPI_HANDLE_CAP_SPECIAL_WAIT);
155 /* Check if a pid is valid - i.e. if a process exists with this pid. */
156 static gboolean is_pid_valid (pid_t pid)
158 gboolean result = FALSE;
160 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
161 if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
163 #elif defined(__HAIKU__)
165 if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
168 gchar *dir = g_strdup_printf ("/proc/%d", pid);
169 if (!access (dir, F_OK))
177 static void process_set_defaults (struct _WapiHandle_process *process_handle)
179 /* These seem to be the defaults on w2k */
180 process_handle->min_working_set = 204800;
181 process_handle->max_working_set = 1413120;
183 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
187 len16 (const gunichar2 *str)
198 utf16_concat (const gunichar2 *first, ...)
205 va_start (args, first);
206 total += len16 (first);
207 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
212 ret = g_new (gunichar2, total + 1);
218 for (s = first; *s != 0; s++)
220 va_start (args, first);
221 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
224 for (p = s; *p != 0; p++)
232 #ifdef PLATFORM_MACOSX
234 /* 0 = no detection; -1 = not 10.5 or higher; 1 = 10.5 or higher */
235 static int osx_10_5_or_higher;
238 detect_osx_10_5_or_higher (void)
244 if (uname (&u) != 0){
245 osx_10_5_or_higher = 1;
253 osx_10_5_or_higher = -1;
255 osx_10_5_or_higher = 1;
259 is_macos_10_5_or_higher (void)
261 if (osx_10_5_or_higher == 0)
262 detect_osx_10_5_or_higher ();
264 return (osx_10_5_or_higher == 1);
268 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
269 static const gunichar2 *utf16_space = utf16_space_bytes;
270 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
271 static const gunichar2 *utf16_quote = utf16_quote_bytes;
276 print_utf16 (gunichar2 *str)
280 res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
281 g_print ("%s\n", res);
286 /* Implemented as just a wrapper around CreateProcess () */
287 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
290 WapiProcessInformation process_info;
294 /* w2k just segfaults here, but we can do better than
297 SetLastError (ERROR_INVALID_PARAMETER);
301 if (sei->lpFile == NULL) {
302 /* w2k returns TRUE for this, for some reason. */
306 /* Put both executable and parameters into the second argument
307 * to CreateProcess (), so it searches $PATH. The conversion
308 * into and back out of utf8 is because there is no
309 * g_strdup_printf () equivalent for gunichar2 :-(
311 args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
313 SetLastError (ERROR_INVALID_DATA);
316 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
317 CREATE_UNICODE_ENVIRONMENT, NULL,
318 sei->lpDirectory, NULL, &process_info);
321 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
325 static char *handler;
326 static gunichar2 *handler_utf16;
328 if (handler_utf16 == (gunichar2 *)-1)
331 #ifdef PLATFORM_MACOSX
332 if (is_macos_10_5_or_higher ())
333 handler = g_strdup ("/usr/bin/open -W");
335 handler = g_strdup ("/usr/bin/open");
338 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
339 * if that fails, try to use gnome-open, then kfmclient
341 handler = g_find_program_in_path ("xdg-open");
342 if (handler == NULL){
343 handler = g_find_program_in_path ("gnome-open");
344 if (handler == NULL){
345 handler = g_find_program_in_path ("kfmclient");
346 if (handler == NULL){
347 handler_utf16 = (gunichar2 *) -1;
350 /* kfmclient needs exec argument */
352 handler = g_strconcat (old, " exec",
359 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
362 /* Put quotes around the filename, in case it's a url
363 * that contains #'s (CreateProcess() calls
364 * g_shell_parse_argv(), which deliberately throws
365 * away anything after an unquoted #). Fixes bug
368 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
369 sei->lpFile, utf16_quote,
370 sei->lpParameters == NULL ? NULL : utf16_space,
371 sei->lpParameters, NULL);
373 SetLastError (ERROR_INVALID_DATA);
376 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
377 CREATE_UNICODE_ENVIRONMENT, NULL,
378 sei->lpDirectory, NULL, &process_info);
381 if (GetLastError () != ERROR_OUTOFMEMORY)
382 SetLastError (ERROR_INVALID_DATA);
387 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
388 sei->hProcess = process_info.hProcess;
390 CloseHandle (process_info.hProcess);
397 is_managed_binary (const gchar *filename)
399 int original_errno = errno;
400 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
401 int file = open (filename, O_RDONLY | O_LARGEFILE);
403 int file = open (filename, O_RDONLY);
406 unsigned char buffer[8];
407 off_t file_size, optional_header_offset;
408 off_t pe_header_offset;
409 gboolean managed = FALSE;
411 guint32 first_word, second_word;
413 /* If we are unable to open the file, then we definitely
414 * can't say that it is managed. The child mono process
415 * probably wouldn't be able to open it anyway.
418 errno = original_errno;
422 /* Retrieve the length of the file for future sanity checks. */
423 file_size = lseek (file, 0, SEEK_END);
424 lseek (file, 0, SEEK_SET);
426 /* We know we need to read a header field at offset 60. */
430 num_read = read (file, buffer, 2);
432 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
435 new_offset = lseek (file, 60, SEEK_SET);
437 if (new_offset != 60)
440 num_read = read (file, buffer, 4);
444 pe_header_offset = buffer[0]
449 if (pe_header_offset + 24 > file_size)
452 new_offset = lseek (file, pe_header_offset, SEEK_SET);
454 if (new_offset != pe_header_offset)
457 num_read = read (file, buffer, 4);
459 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
463 * Verify that the header we want in the optional header data
464 * is present in this binary.
466 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
468 if (new_offset != pe_header_offset + 20)
471 num_read = read (file, buffer, 2);
473 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
476 /* Read the CLR header address and size fields. These will be
477 * zero if the binary is not managed.
479 optional_header_offset = pe_header_offset + 24;
480 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
482 if (new_offset != optional_header_offset + 208)
485 num_read = read (file, buffer, 8);
487 /* We are not concerned with endianness, only with
488 * whether it is zero or not.
490 first_word = *(guint32 *)&buffer[0];
491 second_word = *(guint32 *)&buffer[4];
493 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
500 errno = original_errno;
504 gboolean CreateProcessWithLogonW (const gunichar2 *username,
505 const gunichar2 *domain,
506 const gunichar2 *password,
507 const guint32 logonFlags,
508 const gunichar2 *appname,
509 const gunichar2 *cmdline,
510 guint32 create_flags,
512 const gunichar2 *cwd,
513 WapiStartupInfo *startup,
514 WapiProcessInformation *process_info)
516 /* FIXME: use user information */
517 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
521 is_executable (const char *prog)
524 if (access (prog, X_OK) != 0)
526 if (stat (prog, &buf))
528 if (S_ISREG (buf.st_mode))
534 switchDirectorySeparators(gchar *path)
536 size_t i, pathLength = strlen(path);
538 /* Turn all the slashes round the right way, except for \' */
539 /* There are probably other characters that need to be excluded as well. */
540 for (i = 0; i < pathLength; i++)
542 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' ) {
548 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
549 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
550 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
551 gboolean inherit_handles, guint32 create_flags,
552 gpointer new_environ, const gunichar2 *cwd,
553 WapiStartupInfo *startup,
554 WapiProcessInformation *process_info)
556 gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
557 guint32 i, env_count = 0;
558 gboolean ret = FALSE;
560 struct _WapiHandle_process process_handle = {0}, *process_handle_data;
562 int in_fd, out_fd, err_fd;
565 int startup_pipe [2] = {-1, -1};
567 struct MonoProcess *mono_process;
568 gboolean fork_failed = FALSE;
570 mono_once (&process_ops_once, process_ops_init);
571 mono_once (&process_sig_chld_once, process_add_sigchld_handler);
573 /* appname and cmdline specify the executable and its args:
575 * If appname is not NULL, it is the name of the executable.
576 * Otherwise the executable is the first token in cmdline.
578 * Executable searching:
580 * If appname is not NULL, it can specify the full path and
581 * file name, or else a partial name and the current directory
582 * will be used. There is no additional searching.
584 * If appname is NULL, the first whitespace-delimited token in
585 * cmdline is used. If the name does not contain a full
586 * directory path, the search sequence is:
588 * 1) The directory containing the current process
589 * 2) The current working directory
590 * 3) The windows system directory (Ignored)
591 * 4) The windows directory (Ignored)
594 * Just to make things more interesting, tokens can contain
595 * white space if they are surrounded by quotation marks. I'm
596 * beginning to understand just why windows apps are generally
597 * so crap, with an API like this :-(
599 if (appname != NULL) {
600 cmd = mono_unicode_to_external (appname);
602 DEBUG ("%s: unicode conversion returned NULL",
605 SetLastError (ERROR_PATH_NOT_FOUND);
609 switchDirectorySeparators(cmd);
612 if (cmdline != NULL) {
613 args = mono_unicode_to_external (cmdline);
615 DEBUG ("%s: unicode conversion returned NULL", __func__);
617 SetLastError (ERROR_PATH_NOT_FOUND);
623 dir = mono_unicode_to_external (cwd);
625 DEBUG ("%s: unicode conversion returned NULL", __func__);
627 SetLastError (ERROR_PATH_NOT_FOUND);
631 /* Turn all the slashes round the right way */
632 switchDirectorySeparators(dir);
636 /* We can't put off locating the executable any longer :-( */
639 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
640 /* Strip off the drive letter. I can't
641 * believe that CP/M holdover is still
644 g_memmove (cmd, cmd+2, strlen (cmd)-2);
645 cmd[strlen (cmd)-2] = '\0';
648 unquoted = g_shell_unquote (cmd, NULL);
649 if (unquoted[0] == '/') {
650 /* Assume full path given */
651 prog = g_strdup (unquoted);
653 /* Executable existing ? */
654 if (!is_executable (prog)) {
655 DEBUG ("%s: Couldn't find executable %s",
658 SetLastError (ERROR_FILE_NOT_FOUND);
662 /* Search for file named by cmd in the current
665 char *curdir = g_get_current_dir ();
667 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
670 /* And make sure it's executable */
671 if (!is_executable (prog)) {
672 DEBUG ("%s: Couldn't find executable %s",
675 SetLastError (ERROR_FILE_NOT_FOUND);
681 args_after_prog = args;
686 /* Dig out the first token from args, taking quotation
690 /* First, strip off all leading whitespace */
691 args = g_strchug (args);
693 /* args_after_prog points to the contents of args
694 * after token has been set (otherwise argv[0] is
697 args_after_prog = args;
699 /* Assume the opening quote will always be the first
702 if (args[0] == '\"' || args [0] == '\'') {
704 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
705 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
706 /* We found the first token */
707 token = g_strndup (args+1, i-1);
708 args_after_prog = g_strchug (args + i + 1);
710 /* Quotation mark appeared in the
711 * middle of the token. Just give the
712 * whole first token, quotes and all,
719 /* No quote mark, or malformed */
720 for (i = 0; args[i] != '\0'; i++) {
721 if (g_ascii_isspace (args[i])) {
722 token = g_strndup (args, i);
723 args_after_prog = args + i + 1;
729 if (token == NULL && args[0] != '\0') {
730 /* Must be just one token in the string */
731 token = g_strdup (args);
732 args_after_prog = NULL;
737 DEBUG ("%s: Couldn't find what to exec", __func__);
739 SetLastError (ERROR_PATH_NOT_FOUND);
743 /* Turn all the slashes round the right way. Only for
746 switchDirectorySeparators(token);
748 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
749 /* Strip off the drive letter. I can't
750 * believe that CP/M holdover is still
753 g_memmove (token, token+2, strlen (token)-2);
754 token[strlen (token)-2] = '\0';
757 if (token[0] == '/') {
758 /* Assume full path given */
759 prog = g_strdup (token);
761 /* Executable existing ? */
762 if (!is_executable (prog)) {
763 DEBUG ("%s: Couldn't find executable %s",
766 SetLastError (ERROR_FILE_NOT_FOUND);
771 char *curdir = g_get_current_dir ();
773 /* FIXME: Need to record the directory
774 * containing the current process, and check
775 * that for the new executable as the first
779 prog = g_strdup_printf ("%s/%s", curdir, token);
782 /* I assume X_OK is the criterion to use,
785 if (!is_executable (prog)) {
787 prog = g_find_program_in_path (token);
789 DEBUG ("%s: Couldn't find executable %s", __func__, token);
792 SetLastError (ERROR_FILE_NOT_FOUND);
801 DEBUG ("%s: Exec prog [%s] args [%s]", __func__, prog,
804 /* Check for CLR binaries; if found, we will try to invoke
805 * them using the same mono binary that started us.
807 if (is_managed_binary (prog)) {
808 gunichar2 *newapp, *newcmd;
811 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
813 if (newapp != NULL) {
814 if (appname != NULL) {
815 newcmd = utf16_concat (newapp, utf16_space,
816 appname, utf16_space,
819 newcmd = utf16_concat (newapp, utf16_space,
823 g_free ((gunichar2 *)newapp);
825 if (newcmd != NULL) {
826 ret = CreateProcess (NULL, newcmd,
830 create_flags, new_environ,
834 g_free ((gunichar2 *)newcmd);
841 if (args_after_prog != NULL && *args_after_prog) {
844 qprog = g_shell_quote (prog);
845 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
848 full_prog = g_shell_quote (prog);
851 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
853 g_message ("CreateProcess: %s\n", gerr->message);
859 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
860 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
861 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
862 err_fd = GPOINTER_TO_UINT (startup->hStdError);
864 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
865 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
866 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
869 g_strlcpy (process_handle.proc_name, prog,
870 _WAPI_PROC_NAME_MAX_LEN - 1);
872 process_set_defaults (&process_handle);
874 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
875 if (handle == _WAPI_HANDLE_INVALID) {
876 g_warning ("%s: error creating process handle", __func__);
879 SetLastError (ERROR_OUTOFMEMORY);
883 /* new_environ is a block of NULL-terminated strings, which
884 * is itself NULL-terminated. Of course, passing an array of
885 * string pointers would have made things too easy :-(
887 * If new_environ is not NULL it specifies the entire set of
888 * environment variables in the new process. Otherwise the
889 * new process inherits the same environment.
891 if (new_environ != NULL) {
892 gunichar2 *new_environp;
894 /* Count the number of strings */
895 for (new_environp = (gunichar2 *)new_environ; *new_environp;
898 while (*new_environp) {
903 /* +2: one for the process handle value, and the last
906 env_strings = g_new0 (gchar *, env_count + 2);
908 /* Copy each environ string into 'strings' turning it
909 * into utf8 (or the requested encoding) at the same
913 for (new_environp = (gunichar2 *)new_environ; *new_environp;
915 env_strings[env_count] = mono_unicode_to_external (new_environp);
917 while (*new_environp) {
922 for (i = 0; environ[i] != NULL; i++) {
926 /* +2: one for the process handle value, and the last
929 env_strings = g_new0 (gchar *, env_count + 2);
931 /* Copy each environ string into 'strings' turning it
932 * into utf8 (or the requested encoding) at the same
936 for (i = 0; environ[i] != NULL; i++) {
937 env_strings[env_count] = g_strdup (environ[i]);
941 /* pass process handle info to the child, so it doesn't have
942 * to do an expensive search over the whole list
944 if (env_strings != NULL) {
945 struct _WapiHandleUnshared *handle_data;
946 struct _WapiHandle_shared_ref *ref;
948 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
949 ref = &handle_data->u.shared;
951 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
954 /* Create a pipe to make sure the child doesn't exit before
955 * we can add the process to the linked list of mono_processes */
956 if (pipe (startup_pipe) == -1) {
957 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
958 * This is just for a very hard to hit race condition in the first place */
959 startup_pipe [0] = startup_pipe [1] = -1;
960 DEBUG ("%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
963 thr_ret = _wapi_handle_lock_shared_handles ();
964 g_assert (thr_ret == 0);
969 SetLastError (ERROR_OUTOFMEMORY);
973 } else if (pid == 0) {
976 if (startup_pipe [0] != -1) {
977 /* Wait until the parent has updated it's internal data */
978 ssize_t _i G_GNUC_UNUSED = read (startup_pipe [0], &dummy, 1);
979 DEBUG ("%s: child: parent has completed its setup", __func__);
980 close (startup_pipe [0]);
981 close (startup_pipe [1]);
984 /* should we detach from the process group? */
986 /* Connect stdin, stdout and stderr */
991 if (inherit_handles != TRUE) {
992 /* FIXME: do something here */
995 /* Close all file descriptors */
996 for (i = getdtablesize () - 1; i > 2; i--) {
1000 #ifdef DEBUG_ENABLED
1001 DEBUG ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1003 for (i = 0; argv[i] != NULL; i++) {
1004 g_message ("arg %d: [%s]", i, argv[i]);
1007 for (i = 0; env_strings[i] != NULL; i++) {
1008 g_message ("env %d: [%s]", i, env_strings[i]);
1013 if (dir != NULL && chdir (dir) == -1) {
1019 execve (argv[0], argv, env_strings);
1026 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1027 (gpointer *)&process_handle_data);
1029 g_warning ("%s: error looking up process handle %p", __func__,
1031 _wapi_handle_unref (handle);
1035 process_handle_data->id = pid;
1037 /* Add our mono_process into the linked list of mono_processes */
1038 mono_process = (struct MonoProcess *) g_malloc0 (sizeof (struct MonoProcess));
1039 mono_process->pid = pid;
1040 mono_process->handle_count = 1;
1041 if (MONO_SEM_INIT (&mono_process->exit_sem, 0) != 0) {
1042 /* If we can't create the exit semaphore, we just don't add anything
1043 * to our list of mono processes. Waiting on the process will return
1045 g_warning ("%s: could not create exit semaphore for process.", strerror (errno));
1046 g_free (mono_process);
1048 /* Keep the process handle artificially alive until the process
1049 * exits so that the information in the handle isn't lost. */
1050 _wapi_handle_ref (handle);
1051 mono_process->handle = handle;
1053 process_handle_data->self = _wapi_getpid ();
1054 process_handle_data->mono_process = mono_process;
1056 mono_mutex_lock (&mono_processes_mutex);
1057 mono_process->next = mono_processes;
1058 mono_processes = mono_process;
1059 mono_mutex_unlock (&mono_processes_mutex);
1062 if (process_info != NULL) {
1063 process_info->hProcess = handle;
1064 process_info->dwProcessId = pid;
1066 /* FIXME: we might need to handle the thread info some
1069 process_info->hThread = INVALID_HANDLE_VALUE;
1070 process_info->dwThreadId = 0;
1074 _wapi_handle_unlock_shared_handles ();
1077 _wapi_handle_unref (handle);
1079 if (startup_pipe [1] != -1) {
1080 /* Write 1 byte, doesn't matter what */
1081 ssize_t _i G_GNUC_UNUSED = write (startup_pipe [1], startup_pipe, 1);
1082 close (startup_pipe [0]);
1083 close (startup_pipe [1]);
1090 if (full_prog != NULL) {
1102 if(env_strings != NULL) {
1103 g_strfreev (env_strings);
1109 DEBUG ("%s: returning handle %p for pid %d", __func__, handle,
1112 /* Check if something needs to be cleaned up. */
1113 mono_processes_cleanup ();
1118 static void process_set_name (struct _WapiHandle_process *process_handle)
1120 gchar *progname, *utf8_progname, *slash;
1122 progname=g_get_prgname ();
1123 utf8_progname=mono_utf8_from_external (progname);
1125 DEBUG ("%s: using [%s] as prog name", __func__, progname);
1127 if(utf8_progname!=NULL) {
1128 slash=strrchr (utf8_progname, '/');
1130 g_strlcpy (process_handle->proc_name, slash+1,
1131 _WAPI_PROC_NAME_MAX_LEN - 1);
1133 g_strlcpy (process_handle->proc_name, utf8_progname,
1134 _WAPI_PROC_NAME_MAX_LEN - 1);
1137 g_free (utf8_progname);
1141 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
1143 #if !GLIB_CHECK_VERSION (2,4,0)
1144 #define g_setenv(a,b,c) setenv(a,b,c)
1145 #define g_unsetenv(a) unsetenv(a)
1148 static void process_set_current (void)
1150 pid_t pid = _wapi_getpid ();
1151 const char *handle_env;
1152 struct _WapiHandle_process process_handle = {0};
1154 mono_once (&process_ops_once, process_ops_init);
1156 handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1157 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1159 if (handle_env != NULL) {
1160 struct _WapiHandle_process *process_handlep;
1161 gchar *procname = NULL;
1164 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
1166 DEBUG ("%s: Found my process handle: %p (offset %d 0x%x)",
1167 __func__, current_process, atoi (handle_env),
1170 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
1171 (gpointer *)&process_handlep);
1173 /* This test will probably break on linuxthreads, but
1174 * that should be ancient history on all distros we
1177 if (process_handlep->id == pid) {
1178 procname = process_handlep->proc_name;
1179 if (!strcmp (procname, "mono")) {
1180 /* Set a better process name */
1181 DEBUG ("%s: Setting better process name", __func__);
1183 process_set_name (process_handlep);
1185 DEBUG ("%s: Leaving process name: %s", __func__, procname);
1191 /* Wrong pid, so drop this handle and fall through to
1194 _wapi_handle_unref (current_process);
1198 /* We get here if the handle wasn't specified in the
1199 * environment, or if the process ID was wrong, or if the
1200 * handle lookup failed (eg if the parent process forked and
1201 * quit immediately, and deleted the shared data before the
1202 * child got a chance to attach it.)
1205 DEBUG ("%s: Need to create my own process handle", __func__);
1207 process_handle.id = pid;
1209 process_set_defaults (&process_handle);
1210 process_set_name (&process_handle);
1212 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1214 if (current_process == _WAPI_HANDLE_INVALID) {
1215 g_warning ("%s: error creating process handle", __func__);
1220 gpointer _wapi_process_duplicate ()
1222 mono_once (&process_current_once, process_set_current);
1224 _wapi_handle_ref (current_process);
1226 return(current_process);
1229 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1230 gpointer GetCurrentProcess (void)
1232 mono_once (&process_current_once, process_set_current);
1234 return(_WAPI_PROCESS_CURRENT);
1237 guint32 GetProcessId (gpointer handle)
1239 struct _WapiHandle_process *process_handle;
1242 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1243 /* This is a pseudo handle */
1244 return(GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
1247 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1248 (gpointer *)&process_handle);
1250 SetLastError (ERROR_INVALID_HANDLE);
1254 return (process_handle->id);
1257 guint32 GetCurrentProcessId (void)
1259 mono_once (&process_current_once, process_set_current);
1261 return (GetProcessId (current_process));
1264 /* Returns the process id as a convenience to the functions that call this */
1265 static pid_t signal_process_if_gone (gpointer handle)
1267 struct _WapiHandle_process *process_handle;
1270 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
1272 /* Make sure the process is signalled if it has exited - if
1273 * the parent process didn't wait for it then it won't be
1275 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1276 (gpointer *)&process_handle);
1278 /* It's possible that the handle has vanished during
1279 * the _wapi_search_handle before it gets here, so
1280 * don't spam the console with warnings.
1282 /* g_warning ("%s: error looking up process handle %p",
1283 __func__, handle);*/
1288 DEBUG ("%s: looking at process %d", __func__, process_handle->id);
1290 if (kill (process_handle->id, 0) == -1 &&
1293 /* The process is dead, (EPERM tells us a new process
1294 * has that ID, but as it's owned by someone else it
1295 * can't be the one listed in our shared memory file)
1297 _wapi_shared_handle_set_signal_state (handle, TRUE);
1300 return (process_handle->id);
1304 static gboolean process_enum (gpointer handle, gpointer user_data)
1306 GArray *processes=user_data;
1307 pid_t pid = signal_process_if_gone (handle);
1314 /* Ignore processes that have already exited (ie they are signalled) */
1315 if (_wapi_handle_issignalled (handle) == FALSE) {
1316 DEBUG ("%s: process %d added to array", __func__, pid);
1318 /* This ensures that duplicates aren't returned (see
1319 * the comment above _wapi_search_handle () for why
1322 for (i = 0; i < processes->len; i++) {
1323 if (g_array_index (processes, pid_t, i) == pid) {
1324 /* We've already got this one, return
1325 * FALSE to keep searching
1331 g_array_append_val (processes, pid);
1334 /* Return false to keep searching */
1337 #endif /* UNUSED_CODE */
1339 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
1341 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1343 guint32 count, fit, i, j;
1346 size_t proclength, size;
1347 #if defined(__OpenBSD__)
1348 struct kinfo_proc2 *result;
1351 name[1] = KERN_PROC2;
1352 name[2] = KERN_PROC_ALL;
1354 name[4] = sizeof(struct kinfo_proc2);
1357 struct kinfo_proc *result;
1358 static const int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
1361 mono_once (&process_current_once, process_set_current);
1368 #if defined(__OpenBSD__)
1369 size = (sizeof(name) / sizeof(*name));
1371 size = (sizeof(name) / sizeof(*name)) - 1;
1373 err = sysctl ((int *)name, size, NULL, &proclength, NULL, 0);
1376 result = malloc (proclength);
1381 #if defined(__OpenBSD__)
1382 name[5] = (int)(proclength / sizeof(struct kinfo_proc2));
1385 err = sysctl ((int *) name, size, result, &proclength, NULL, 0);
1392 } while (err == 0 && !done);
1395 if (result != NULL) {
1402 #if defined(__OpenBSD__)
1403 count = proclength / sizeof(struct kinfo_proc2);
1405 count = proclength / sizeof(struct kinfo_proc);
1407 fit = len / sizeof(guint32);
1408 for (i = 0, j = 0; j< fit && i < count; i++) {
1409 #if defined(__OpenBSD__)
1410 pids [j++] = result [i].p_pid;
1412 if (result[i].kp_proc.p_pid > 0) /* Pid 0 not supported */
1413 pids [j++] = result [i].kp_proc.p_pid;
1418 *needed = j * sizeof(guint32);
1422 #elif defined(__HAIKU__)
1424 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1430 mono_once (&process_current_once, process_set_current);
1432 fit = len / sizeof (guint32);
1433 while (get_next_team_info (&cookie, &teamInfo) == B_OK && i < fit) {
1434 pids [i++] = teamInfo.team;
1436 *needed = i * sizeof (guint32);
1441 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1445 struct dirent *entry;
1447 mono_once (&process_current_once, process_set_current);
1449 dir = opendir ("/proc");
1455 fit = len / sizeof (guint32);
1456 while(i < fit && (entry = readdir (dir)) != NULL) {
1460 if (!isdigit (entry->d_name[0]))
1463 pid = (pid_t) strtol (entry->d_name, &endptr, 10);
1464 if (*endptr == '\0')
1465 pids [i++] = (guint32) pid;
1468 *needed = i * sizeof(guint32);
1474 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1477 pid_t checking_pid = signal_process_if_gone (handle);
1479 if (checking_pid == 0) {
1483 wanted_pid = GPOINTER_TO_UINT (user_data);
1485 /* It's possible to have more than one process handle with the
1486 * same pid, but only the one running process can be
1489 if (checking_pid == wanted_pid &&
1490 _wapi_handle_issignalled (handle) == FALSE) {
1491 /* If the handle is blown away in the window between
1492 * returning TRUE here and _wapi_search_handle pinging
1493 * the timestamp, the search will continue
1501 gboolean CloseProcess(gpointer handle)
1503 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1504 /* This is a pseudo handle */
1508 return CloseHandle (handle);
1512 * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1514 gpointer OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1516 /* Find the process handle that corresponds to pid */
1517 gpointer handle = NULL;
1519 mono_once (&process_current_once, process_set_current);
1521 DEBUG ("%s: looking for process %d", __func__, pid);
1523 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1524 process_open_compare,
1525 GUINT_TO_POINTER (pid), NULL, TRUE);
1527 if (is_pid_valid (pid)) {
1528 /* Return a pseudo handle for processes we
1529 * don't have handles for
1531 return GINT_TO_POINTER (_WAPI_PROCESS_UNHANDLED + pid);
1533 DEBUG ("%s: Can't find pid %d", __func__, pid);
1535 SetLastError (ERROR_PROC_NOT_FOUND);
1541 /* _wapi_search_handle () already added a ref */
1545 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1547 struct _WapiHandle_process *process_handle;
1551 mono_once (&process_current_once, process_set_current);
1557 pid = GPOINTER_TO_UINT (process) - _WAPI_PROCESS_UNHANDLED;
1558 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1559 /* This is a pseudo handle, so we don't know what the
1560 * exit code was, but we can check whether it's alive or not
1562 if (is_pid_valid (pid)) {
1563 *code = STILL_ACTIVE;
1570 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1571 (gpointer *)&process_handle);
1573 DEBUG ("%s: Can't find process %p", __func__, process);
1578 /* A process handle is only signalled if the process has exited
1579 * and has been waited for */
1581 /* Make sure any process exit has been noticed, before
1582 * checking if the process is signalled. Fixes bug 325463.
1584 process_wait (process, 0, TRUE);
1586 if (_wapi_handle_issignalled (process) == TRUE) {
1587 *code = process_handle->exitstatus;
1589 *code = STILL_ACTIVE;
1595 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1596 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1597 WapiFileTime *user_time)
1599 struct _WapiHandle_process *process_handle;
1601 gboolean ku_times_set = FALSE;
1603 mono_once (&process_current_once, process_set_current);
1605 if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1607 /* Not sure if w32 allows NULLs here or not */
1611 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1612 /* This is a pseudo handle, so just fail for now
1617 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1618 (gpointer *)&process_handle);
1620 DEBUG ("%s: Can't find process %p", __func__, process);
1625 *create_time=process_handle->create_time;
1627 /* A process handle is only signalled if the process has
1628 * exited. Otherwise exit_time isn't set
1630 if(_wapi_handle_issignalled (process)==TRUE) {
1631 *exit_time=process_handle->exit_time;
1634 #ifdef HAVE_GETRUSAGE
1635 if (process_handle->id == getpid ()) {
1636 struct rusage time_data;
1637 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1639 gint64 *tick_val_ptr;
1640 ku_times_set = TRUE;
1641 tick_val = time_data.ru_utime.tv_sec * 10000000 + time_data.ru_utime.tv_usec * 10;
1642 tick_val_ptr = (gint64*)user_time;
1643 *tick_val_ptr = tick_val;
1644 tick_val = time_data.ru_stime.tv_sec * 10000000 + time_data.ru_stime.tv_usec * 10;
1645 tick_val_ptr = (gint64*)kernel_time;
1646 *tick_val_ptr = tick_val;
1650 if (!ku_times_set) {
1651 memset (kernel_time, 0, sizeof (WapiFileTime));
1652 memset (user_time, 0, sizeof (WapiFileTime));
1660 gpointer address_start;
1661 gpointer address_end;
1663 gpointer address_offset;
1669 static void free_procmodule (WapiProcModule *mod)
1671 if (mod->perms != NULL) {
1672 g_free (mod->perms);
1674 if (mod->filename != NULL) {
1675 g_free (mod->filename);
1680 static gint find_procmodule (gconstpointer a, gconstpointer b)
1682 WapiProcModule *want = (WapiProcModule *)a;
1683 WapiProcModule *compare = (WapiProcModule *)b;
1685 if ((want->device == compare->device) &&
1686 (want->inode == compare->inode)) {
1693 #ifdef PLATFORM_MACOSX
1694 #include <mach-o/dyld.h>
1695 #include <mach-o/getsect.h>
1697 static GSList *load_modules (void)
1700 WapiProcModule *mod;
1701 uint32_t count = _dyld_image_count ();
1704 for (i = 0; i < count; i++) {
1705 #if SIZEOF_VOID_P == 8
1706 const struct mach_header_64 *hdr;
1707 const struct section_64 *sec;
1709 const struct mach_header *hdr;
1710 const struct section *sec;
1715 slide = _dyld_get_image_vmaddr_slide (i);
1716 name = _dyld_get_image_name (i);
1717 hdr = _dyld_get_image_header (i);
1718 #if SIZEOF_VOID_P == 8
1719 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1721 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1724 /* Some dynlibs do not have data sections on osx (#533893) */
1729 mod = g_new0 (WapiProcModule, 1);
1730 mod->address_start = GINT_TO_POINTER (sec->addr);
1731 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1732 mod->perms = g_strdup ("r--p");
1733 mod->address_offset = 0;
1734 mod->device = makedev (0, 0);
1735 mod->inode = (ino_t) i;
1736 mod->filename = g_strdup (name);
1738 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1739 ret = g_slist_prepend (ret, mod);
1741 free_procmodule (mod);
1745 ret = g_slist_reverse (ret);
1749 #elif defined(__OpenBSD__)
1751 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1753 if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1754 + sizeof (info->dlpi_phnum))
1757 struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1761 memcpy(cpy, info, sizeof(*info));
1763 g_ptr_array_add ((GPtrArray *)ptr, cpy);
1768 static GSList *load_modules (void)
1771 WapiProcModule *mod;
1772 GPtrArray *dlarray = g_ptr_array_new();
1775 if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1778 for (i = 0; i < dlarray->len; i++) {
1779 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1781 mod = g_new0 (WapiProcModule, 1);
1782 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1783 mod->address_end = (gpointer)(info->dlpi_addr +
1784 info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1785 mod->perms = g_strdup ("r--p");
1786 mod->address_offset = 0;
1787 mod->inode = (ino_t) i;
1788 mod->filename = g_strdup (info->dlpi_name);
1790 DEBUG ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1791 mod->inode, mod->filename, mod->address_start, mod->address_end);
1795 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1796 ret = g_slist_prepend (ret, mod);
1798 free_procmodule (mod);
1802 g_ptr_array_free (dlarray, TRUE);
1804 ret = g_slist_reverse (ret);
1808 #elif defined(__HAIKU__)
1810 static GSList *load_modules (void)
1813 WapiProcModule *mod;
1815 image_info imageInfo;
1817 while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
1818 mod = g_new0 (WapiProcModule, 1);
1819 mod->device = imageInfo.device;
1820 mod->inode = imageInfo.node;
1821 mod->filename = g_strdup (imageInfo.name);
1822 mod->address_start = MIN (imageInfo.text, imageInfo.data);
1823 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
1824 (uint8_t*)imageInfo.data + imageInfo.data_size);
1825 mod->perms = g_strdup ("r--p");
1826 mod->address_offset = 0;
1828 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1829 ret = g_slist_prepend (ret, mod);
1831 free_procmodule (mod);
1835 ret = g_slist_reverse (ret);
1840 static GSList *load_modules (FILE *fp)
1843 WapiProcModule *mod;
1844 gchar buf[MAXPATHLEN + 1], *p, *endp;
1845 gchar *start_start, *end_start, *prot_start, *offset_start;
1846 gchar *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1847 gpointer address_start, address_end, address_offset;
1848 guint32 maj_dev, min_dev;
1852 while (fgets (buf, sizeof(buf), fp)) {
1854 while (g_ascii_isspace (*p)) ++p;
1856 if (!g_ascii_isxdigit (*start_start)) {
1859 address_start = (gpointer)strtoul (start_start, &endp, 16);
1867 if (!g_ascii_isxdigit (*end_start)) {
1870 address_end = (gpointer)strtoul (end_start, &endp, 16);
1872 if (!g_ascii_isspace (*p)) {
1876 while (g_ascii_isspace (*p)) ++p;
1878 if (*prot_start != 'r' && *prot_start != '-') {
1881 memcpy (prot_buf, prot_start, 4);
1883 while (!g_ascii_isspace (*p)) ++p;
1885 while (g_ascii_isspace (*p)) ++p;
1887 if (!g_ascii_isxdigit (*offset_start)) {
1890 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1892 if (!g_ascii_isspace (*p)) {
1896 while(g_ascii_isspace (*p)) ++p;
1898 if (!g_ascii_isxdigit (*maj_dev_start)) {
1901 maj_dev = strtoul (maj_dev_start, &endp, 16);
1909 if (!g_ascii_isxdigit (*min_dev_start)) {
1912 min_dev = strtoul (min_dev_start, &endp, 16);
1914 if (!g_ascii_isspace (*p)) {
1918 while (g_ascii_isspace (*p)) ++p;
1920 if (!g_ascii_isxdigit (*inode_start)) {
1923 inode = (ino_t)strtol (inode_start, &endp, 10);
1925 if (!g_ascii_isspace (*p)) {
1929 device = makedev ((int)maj_dev, (int)min_dev);
1930 if ((device == 0) &&
1935 while(g_ascii_isspace (*p)) ++p;
1936 /* p now points to the filename */
1938 mod = g_new0 (WapiProcModule, 1);
1939 mod->address_start = address_start;
1940 mod->address_end = address_end;
1941 mod->perms = g_strdup (prot_buf);
1942 mod->address_offset = address_offset;
1943 mod->device = device;
1945 mod->filename = g_strdup (g_strstrip (p));
1947 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1948 ret = g_slist_prepend (ret, mod);
1950 free_procmodule (mod);
1954 ret = g_slist_reverse (ret);
1960 static gboolean match_procname_to_modulename (gchar *procname, gchar *modulename)
1962 char* lastsep = NULL;
1963 char* lastsep2 = NULL;
1966 gboolean result = FALSE;
1968 if (procname == NULL || modulename == NULL)
1971 pname = mono_path_resolve_symlinks (procname);
1972 mname = mono_path_resolve_symlinks (modulename);
1974 if (!strcmp (pname, mname))
1978 lastsep = strrchr (mname, '/');
1980 if (!strcmp (lastsep+1, pname))
1983 lastsep2 = strrchr (pname, '/');
1986 if (!strcmp (lastsep+1, lastsep2+1))
1989 if (!strcmp (mname, lastsep2+1))
2002 #if !defined(__OpenBSD__)
2004 open_process_map (int pid, const char *mode)
2007 const gchar *proc_path[] = {
2008 "/proc/%d/maps", /* GNU/Linux */
2009 "/proc/%d/map", /* FreeBSD */
2015 for (i = 0; fp == NULL && proc_path [i]; i++) {
2016 filename = g_strdup_printf (proc_path[i], pid);
2017 fp = fopen (filename, mode);
2025 gboolean EnumProcessModules (gpointer process, gpointer *modules,
2026 guint32 size, guint32 *needed)
2028 struct _WapiHandle_process *process_handle;
2030 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2033 GSList *mods = NULL;
2034 WapiProcModule *module;
2035 guint32 count, avail = size / sizeof(gpointer);
2038 gchar *proc_name = NULL;
2040 /* Store modules in an array of pointers (main module as
2041 * modules[0]), using the load address for each module as a
2042 * token. (Use 'NULL' as an alternative for the main module
2043 * so that the simple implementation can just return one item
2044 * for now.) Get the info from /proc/<pid>/maps on linux,
2045 * /proc/<pid>/map on FreeBSD, other systems will have to
2046 * implement /dev/kmem reading or whatever other horrid
2047 * technique is needed.
2049 if (size < sizeof(gpointer)) {
2053 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2054 /* This is a pseudo handle */
2055 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2057 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2058 (gpointer *)&process_handle);
2060 DEBUG ("%s: Can't find process %p", __func__, process);
2064 pid = process_handle->id;
2065 proc_name = process_handle->proc_name;
2068 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2070 mods = load_modules ();
2072 if ((fp = open_process_map (pid, "r")) == NULL) {
2073 /* No /proc/<pid>/maps so just return the main module
2077 *needed = sizeof(gpointer);
2079 mods = load_modules (fp);
2082 count = g_slist_length (mods);
2084 /* count + 1 to leave slot 0 for the main module */
2085 *needed = sizeof(gpointer) * (count + 1);
2087 /* Use the NULL shortcut, as the first line in
2088 * /proc/<pid>/maps isn't the executable, and we need
2089 * that first in the returned list. Check the module name
2090 * to see if it ends with the proc name and substitute
2091 * the first entry with it. FIXME if this turns out to
2095 for (i = 0; i < (avail - 1) && i < count; i++) {
2096 module = (WapiProcModule *)g_slist_nth_data (mods, i);
2097 if (modules[0] != NULL)
2098 modules[i] = module->address_start;
2099 else if (match_procname_to_modulename (proc_name, module->filename))
2100 modules[0] = module->address_start;
2102 modules[i + 1] = module->address_start;
2105 for (i = 0; i < count; i++) {
2106 free_procmodule (g_slist_nth_data (mods, i));
2108 g_slist_free (mods);
2114 static gchar *get_process_name_from_proc (pid_t pid)
2116 #if defined(__OpenBSD__)
2119 struct kinfo_proc2 *pi;
2120 #elif defined(PLATFORM_MACOSX)
2122 struct kinfo_proc *pi;
2123 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
2126 gchar *filename = NULL;
2131 #if defined(PLATFORM_SOLARIS)
2132 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
2133 if ((fp = fopen (filename, "r")) != NULL) {
2137 nread = fread (&info, sizeof (info), 1, fp);
2139 ret = g_strdup (info.pr_fname);
2145 #elif defined(PLATFORM_MACOSX)
2146 #if !defined (__mono_ppc__) && defined (TARGET_OSX)
2147 /* No proc name on OSX < 10.5 nor ppc nor iOS */
2148 memset (buf, '\0', sizeof(buf));
2149 proc_name (pid, buf, sizeof(buf));
2150 if (strlen (buf) > 0)
2151 ret = g_strdup (buf);
2153 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0)
2156 if ((pi = malloc(size)) == NULL)
2159 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
2160 if (errno == ENOMEM) {
2162 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__);
2167 if (strlen (pi->kp_proc.p_comm) > 0)
2168 ret = g_strdup (pi->kp_proc.p_comm);
2172 #elif defined(__OpenBSD__)
2174 mib [1] = KERN_PROC2;
2175 mib [2] = KERN_PROC_PID;
2177 mib [4] = sizeof(struct kinfo_proc2);
2181 if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0)
2184 if ((pi = malloc(size)) == NULL)
2187 mib[5] = (int)(size / sizeof(struct kinfo_proc2));
2189 if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
2190 (size != sizeof (struct kinfo_proc2))) {
2191 if (errno == ENOMEM) {
2198 if (strlen (pi->p_comm) > 0)
2199 ret = g_strdup (pi->p_comm);
2202 #elif defined(__HAIKU__)
2203 image_info imageInfo;
2206 if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
2207 ret = g_strdup (imageInfo.name);
2210 memset (buf, '\0', sizeof(buf));
2211 filename = g_strdup_printf ("/proc/%d/exe", pid);
2212 if (readlink (filename, buf, 255) > 0) {
2213 ret = g_strdup (buf);
2221 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
2222 if ((fp = fopen (filename, "r")) != NULL) {
2223 if (fgets (buf, 256, fp) != NULL) {
2224 ret = g_strdup (buf);
2235 filename = g_strdup_printf ("/proc/%d/stat", pid);
2236 if ((fp = fopen (filename, "r")) != NULL) {
2237 if (fgets (buf, 256, fp) != NULL) {
2240 start = strchr (buf, '(');
2241 if (start != NULL) {
2242 end = strchr (start + 1, ')');
2245 ret = g_strndup (start + 1,
2259 static guint32 get_module_name (gpointer process, gpointer module,
2260 gunichar2 *basename, guint32 size,
2263 struct _WapiHandle_process *process_handle;
2266 gunichar2 *procname;
2267 gchar *procname_ext = NULL;
2270 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2273 GSList *mods = NULL;
2274 WapiProcModule *found_module;
2277 gchar *proc_name = NULL;
2279 mono_once (&process_current_once, process_set_current);
2281 DEBUG ("%s: Getting module base name, process handle %p module %p",
2282 __func__, process, module);
2284 size = size*sizeof(gunichar2); /* adjust for unicode characters */
2286 if (basename == NULL || size == 0) {
2290 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2291 /* This is a pseudo handle */
2292 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2293 proc_name = get_process_name_from_proc (pid);
2295 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2296 (gpointer *)&process_handle);
2298 DEBUG ("%s: Can't find process %p", __func__,
2303 pid = process_handle->id;
2304 proc_name = g_strdup (process_handle->proc_name);
2307 /* Look up the address in /proc/<pid>/maps */
2308 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2310 mods = load_modules ();
2312 if ((fp = open_process_map (pid, "r")) == NULL) {
2313 if (errno == EACCES && module == NULL && base == TRUE) {
2314 procname_ext = get_process_name_from_proc (pid);
2316 /* No /proc/<pid>/maps, so just return failure
2323 mods = load_modules (fp);
2326 count = g_slist_length (mods);
2328 /* If module != NULL compare the address.
2329 * If module == NULL we are looking for the main module.
2330 * The best we can do for now check it the module name end with the process name.
2332 for (i = 0; i < count; i++) {
2333 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2334 if (procname_ext == NULL &&
2335 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2336 (module != NULL && found_module->address_start == module))) {
2338 procname_ext = g_path_get_basename (found_module->filename);
2340 procname_ext = g_strdup (found_module->filename);
2344 free_procmodule (found_module);
2347 if (procname_ext == NULL)
2349 /* If it's *still* null, we might have hit the
2350 * case where reading /proc/$pid/maps gives an
2351 * empty file for this user.
2353 procname_ext = get_process_name_from_proc (pid);
2356 g_slist_free (mods);
2360 if (procname_ext != NULL) {
2361 DEBUG ("%s: Process name is [%s]", __func__,
2364 procname = mono_unicode_from_external (procname_ext, &bytes);
2365 if (procname == NULL) {
2367 g_free (procname_ext);
2373 /* Add the terminator */
2377 DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2379 memcpy (basename, procname, size);
2381 DEBUG ("%s: Size %d larger than needed (%ld)",
2382 __func__, size, bytes);
2384 memcpy (basename, procname, bytes);
2388 g_free (procname_ext);
2396 guint32 GetModuleBaseName (gpointer process, gpointer module,
2397 gunichar2 *basename, guint32 size)
2399 return(get_module_name (process, module, basename, size, TRUE));
2402 guint32 GetModuleFileNameEx (gpointer process, gpointer module,
2403 gunichar2 *filename, guint32 size)
2405 return(get_module_name (process, module, filename, size, FALSE));
2408 gboolean GetModuleInformation (gpointer process, gpointer module,
2409 WapiModuleInfo *modinfo, guint32 size)
2411 struct _WapiHandle_process *process_handle;
2414 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2417 GSList *mods = NULL;
2418 WapiProcModule *found_module;
2421 gboolean ret = FALSE;
2422 gchar *proc_name = NULL;
2424 mono_once (&process_current_once, process_set_current);
2426 DEBUG ("%s: Getting module info, process handle %p module %p",
2427 __func__, process, module);
2429 if (modinfo == NULL || size < sizeof(WapiModuleInfo)) {
2433 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2434 /* This is a pseudo handle */
2435 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2436 proc_name = get_process_name_from_proc (pid);
2438 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2439 (gpointer *)&process_handle);
2441 DEBUG ("%s: Can't find process %p", __func__,
2446 pid = process_handle->id;
2447 proc_name = g_strdup (process_handle->proc_name);
2450 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2452 mods = load_modules ();
2454 /* Look up the address in /proc/<pid>/maps */
2455 if ((fp = open_process_map (pid, "r")) == NULL) {
2456 /* No /proc/<pid>/maps, so just return failure
2462 mods = load_modules (fp);
2465 count = g_slist_length (mods);
2467 /* If module != NULL compare the address.
2468 * If module == NULL we are looking for the main module.
2469 * The best we can do for now check it the module name end with the process name.
2471 for (i = 0; i < count; i++) {
2472 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2473 if ( ret == FALSE &&
2474 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2475 (module != NULL && found_module->address_start == module))) {
2476 modinfo->lpBaseOfDll = found_module->address_start;
2477 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2478 modinfo->EntryPoint = found_module->address_offset;
2482 free_procmodule (found_module);
2485 g_slist_free (mods);
2492 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2494 struct _WapiHandle_process *process_handle;
2497 mono_once (&process_current_once, process_set_current);
2499 if(min==NULL || max==NULL) {
2500 /* Not sure if w32 allows NULLs here or not */
2504 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2505 /* This is a pseudo handle, so just fail for now
2510 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2511 (gpointer *)&process_handle);
2513 DEBUG ("%s: Can't find process %p", __func__, process);
2518 *min=process_handle->min_working_set;
2519 *max=process_handle->max_working_set;
2524 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2526 struct _WapiHandle_process *process_handle;
2529 mono_once (&process_current_once, process_set_current);
2531 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2532 /* This is a pseudo handle, so just fail for now
2537 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2538 (gpointer *)&process_handle);
2540 DEBUG ("%s: Can't find process %p", __func__, process);
2545 process_handle->min_working_set=min;
2546 process_handle->max_working_set=max;
2553 TerminateProcess (gpointer process, gint32 exitCode)
2555 struct _WapiHandle_process *process_handle;
2561 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2562 /* This is a pseudo handle */
2563 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2565 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2566 (gpointer *) &process_handle);
2569 DEBUG ("%s: Can't find process %p", __func__,
2571 SetLastError (ERROR_INVALID_HANDLE);
2574 pid = process_handle->id;
2577 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2578 ret = kill (pid, signo);
2582 SetLastError (ERROR_INVALID_PARAMETER);
2585 SetLastError (ERROR_ACCESS_DENIED);
2588 SetLastError (ERROR_PROC_NOT_FOUND);
2591 SetLastError (ERROR_GEN_FAILURE);
2599 GetPriorityClass (gpointer process)
2601 #ifdef HAVE_GETPRIORITY
2602 struct _WapiHandle_process *process_handle;
2607 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2608 /* This is a pseudo handle */
2609 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2611 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2612 (gpointer *) &process_handle);
2615 SetLastError (ERROR_INVALID_HANDLE);
2618 pid = process_handle->id;
2622 ret = getpriority (PRIO_PROCESS, pid);
2623 if (ret == -1 && errno != 0) {
2627 SetLastError (ERROR_ACCESS_DENIED);
2630 SetLastError (ERROR_PROC_NOT_FOUND);
2633 SetLastError (ERROR_GEN_FAILURE);
2639 return NORMAL_PRIORITY_CLASS;
2641 return REALTIME_PRIORITY_CLASS;
2643 return HIGH_PRIORITY_CLASS;
2645 return ABOVE_NORMAL_PRIORITY_CLASS;
2647 return IDLE_PRIORITY_CLASS;
2649 return BELOW_NORMAL_PRIORITY_CLASS;
2651 return NORMAL_PRIORITY_CLASS;
2653 SetLastError (ERROR_NOT_SUPPORTED);
2659 SetPriorityClass (gpointer process, guint32 priority_class)
2661 #ifdef HAVE_SETPRIORITY
2662 struct _WapiHandle_process *process_handle;
2668 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2669 /* This is a pseudo handle */
2670 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2672 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2673 (gpointer *) &process_handle);
2676 SetLastError (ERROR_INVALID_HANDLE);
2679 pid = process_handle->id;
2682 switch (priority_class) {
2683 case IDLE_PRIORITY_CLASS:
2686 case BELOW_NORMAL_PRIORITY_CLASS:
2689 case NORMAL_PRIORITY_CLASS:
2692 case ABOVE_NORMAL_PRIORITY_CLASS:
2695 case HIGH_PRIORITY_CLASS:
2698 case REALTIME_PRIORITY_CLASS:
2702 SetLastError (ERROR_INVALID_PARAMETER);
2706 ret = setpriority (PRIO_PROCESS, pid, prio);
2711 SetLastError (ERROR_ACCESS_DENIED);
2714 SetLastError (ERROR_PROC_NOT_FOUND);
2717 SetLastError (ERROR_GEN_FAILURE);
2723 SetLastError (ERROR_NOT_SUPPORTED);
2729 mono_processes_cleanup (void)
2731 struct MonoProcess *mp;
2732 struct MonoProcess *prev = NULL;
2733 struct MonoProcess *candidate = NULL;
2734 gpointer unref_handle;
2737 DEBUG ("%s", __func__);
2739 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2740 if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
2743 mp = mono_processes;
2744 while (mp != NULL) {
2745 if (mp->pid == 0 && mp->handle != NULL) {
2746 /* This process has exited and we need to remove the artifical ref
2748 mono_mutex_lock (&mono_processes_mutex);
2749 unref_handle = mp->handle;
2751 mono_mutex_unlock (&mono_processes_mutex);
2753 _wapi_handle_unref (unref_handle);
2759 mp = mono_processes;
2761 while (mp != NULL) {
2762 if ((mp->handle_count == 0 && mp->pid == 0) || candidate != NULL) {
2764 _wapi_handle_spin (spin);
2768 /* We've found a candidate */
2769 mono_mutex_lock (&mono_processes_mutex);
2770 if (candidate == NULL) {
2772 if (mp == mono_processes) {
2773 mono_processes = mp->next;
2775 prev->next = mp->next;
2780 /* It's still safe to traverse the structure.*/
2781 mono_memory_barrier ();
2783 if (mono_processes_read_lock != 0) {
2784 /* The sigchld handler is watching us. Spin a bit and try again */
2787 } else if (spin >= 8) {
2788 /* Just give up for now */
2789 mono_mutex_unlock (&mono_processes_mutex);
2793 /* We've modified the list of processes, and we know the sigchld handler
2794 * isn't executing, so even if it executes at any moment, it'll see the
2795 * new version of the list. So now we can free the candidate. */
2796 DEBUG ("%s: freeing candidate %p", __func__, candidate);
2797 mp = candidate->next;
2798 MONO_SEM_DESTROY (&candidate->exit_sem);
2803 mono_mutex_unlock (&mono_processes_mutex);
2812 DEBUG ("%s done", __func__);
2814 InterlockedDecrement (&mono_processes_cleaning_up);
2818 process_close (gpointer handle, gpointer data)
2820 struct _WapiHandle_process *process_handle;
2822 DEBUG ("%s", __func__);
2824 process_handle = (struct _WapiHandle_process *) data;
2825 if (process_handle->mono_process && process_handle->self == _wapi_getpid ())
2826 InterlockedDecrement (&process_handle->mono_process->handle_count);
2827 mono_processes_cleanup ();
2832 mono_sigchld_signal_handler (int _dummy, siginfo_t *info, void *context)
2836 struct MonoProcess *p;
2839 fprintf (stdout, "SIG CHILD handler for pid: %i\n", info->si_pid);
2842 InterlockedIncrement (&mono_processes_read_lock);
2846 pid = waitpid (-1, &status, WNOHANG);
2847 } while (pid == -1 && errno == EINTR);
2853 fprintf (stdout, "child ended: %i", pid);
2857 if (p->pid == pid) {
2858 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2860 MONO_SEM_POST (&p->exit_sem);
2867 InterlockedDecrement (&mono_processes_read_lock);
2870 fprintf (stdout, "SIG CHILD handler: done looping.");
2875 static void process_add_sigchld_handler (void)
2878 struct sigaction sa;
2880 sa.sa_sigaction = mono_sigchld_signal_handler;
2881 sigemptyset (&sa.sa_mask);
2882 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2883 g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2884 DEBUG ("Added SIGCHLD handler");
2888 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2890 struct _WapiHandle_process *process_handle;
2896 struct MonoProcess *mp;
2898 gpointer current_thread;
2900 current_thread = _wapi_thread_handle_from_id (pthread_self ());
2901 if (current_thread == NULL) {
2902 SetLastError (ERROR_INVALID_HANDLE);
2906 /* FIXME: We can now easily wait on processes that aren't our own children,
2907 * but WaitFor*Object won't call us for pseudo handles. */
2908 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2910 DEBUG ("%s (%p, %u)", __func__, handle, timeout);
2912 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS, (gpointer *)&process_handle);
2914 g_warning ("%s: error looking up process handle %p", __func__, handle);
2918 if (process_handle->exited) {
2919 /* We've already done this one */
2920 DEBUG ("%s (%p, %u): Process already exited", __func__, handle, timeout);
2921 return WAIT_OBJECT_0;
2924 pid = process_handle->id;
2926 DEBUG ("%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2928 /* We don't need to lock mono_processes here, the entry
2929 * has a handle_count > 0 which means it will not be freed. */
2930 mp = process_handle->mono_process;
2931 if (mp && process_handle->self != _wapi_getpid ()) {
2932 /* mono_process points to memory in another process' address space: we can't use it */
2936 start = mono_msec_ticks ();
2942 /* We have a semaphore we can wait on */
2943 if (timeout != INFINITE) {
2944 DEBUG ("%s (%p, %u): waiting on semaphore for %li ms...",
2945 __func__, handle, timeout, (timeout - (now - start)));
2947 ret = MONO_SEM_TIMEDWAIT_ALERTABLE (&mp->exit_sem, (timeout - (now - start)), alertable);
2949 DEBUG ("%s (%p, %u): waiting on semaphore forever...",
2950 __func__, handle, timeout);
2951 ret = MONO_SEM_WAIT_ALERTABLE (&mp->exit_sem, alertable);
2954 if (ret == -1 && errno != EINTR && errno != ETIMEDOUT) {
2955 DEBUG ("%s (%p, %u): sem_timedwait failure: %s",
2956 __func__, handle, timeout, g_strerror (errno));
2957 /* Should we return a failure here? */
2961 /* Success, process has exited */
2962 MONO_SEM_POST (&mp->exit_sem);
2966 /* We did not create this process, so we can't waidpid / sem_wait it.
2967 * We need to poll for the pid existence */
2968 DEBUG ("%s (%p, %u): polling on pid...", __func__, handle, timeout);
2969 if (!is_pid_valid (pid)) {
2970 /* Success, process has exited */
2976 DEBUG ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
2977 return WAIT_TIMEOUT;
2980 now = mono_msec_ticks ();
2981 if (now - start >= timeout) {
2982 DEBUG ("%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
2983 return WAIT_TIMEOUT;
2987 /* "timeout - (now - start)" will not underflow, since timeout is always >=0,
2988 * and we passed the check just above */
2989 _wapi_handle_spin (MIN (100, timeout - (now - start)));
2992 if (alertable && _wapi_thread_apc_pending (current_thread)) {
2993 DEBUG ("%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
2994 return WAIT_IO_COMPLETION;
2998 /* Process must have exited */
2999 DEBUG ("%s (%p, %u): Waited successfully", __func__, handle, timeout);
3001 ret = _wapi_handle_lock_shared_handles ();
3002 g_assert (ret == 0);
3004 status = mp ? mp->status : 0;
3005 if (WIFSIGNALED (status)) {
3006 process_handle->exitstatus = 128 + WTERMSIG (status);
3008 process_handle->exitstatus = WEXITSTATUS (status);
3010 _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
3012 process_handle->exited = TRUE;
3014 DEBUG ("%s (%p, %u): Setting pid %d signalled, exit status %d",
3015 __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
3017 _wapi_shared_handle_set_signal_state (handle, TRUE);
3019 _wapi_handle_unlock_shared_handles ();
3021 return WAIT_OBJECT_0;