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 <sys/resource.h>
43 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
45 #include <sys/sysctl.h>
46 # if !defined(__OpenBSD__)
47 # include <sys/utsname.h>
51 #ifdef PLATFORM_SOLARIS
52 /* procfs.h cannot be included if this define is set, but it seems to work fine if it is undefined */
53 #if _FILE_OFFSET_BITS == 64
54 #undef _FILE_OFFSET_BITS
56 #define _FILE_OFFSET_BITS 64
63 #include <KernelKit.h>
66 #include <mono/io-layer/wapi.h>
67 #include <mono/io-layer/wapi-private.h>
68 #include <mono/io-layer/handles-private.h>
69 #include <mono/io-layer/misc-private.h>
70 #include <mono/io-layer/mono-mutex.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>
79 /* The process' environment strings */
80 #if defined(__APPLE__) && !defined (__arm__)
81 /* Apple defines this in crt_externs.h but doesn't provide that header for
82 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
83 * in fact exist on all implementations (so far)
85 gchar ***_NSGetEnviron(void);
86 #define environ (*_NSGetEnviron())
88 extern char **environ;
92 #define DEBUG(...) g_message(__VA_ARGS__)
93 #define DEBUG_ENABLED 1
98 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable);
99 static void process_close (gpointer handle, gpointer data);
100 static gboolean is_pid_valid (pid_t pid);
102 #if !defined(__OpenBSD__)
104 open_process_map (int pid, const char *mode);
107 struct _WapiHandleOps _wapi_process_ops = {
108 process_close, /* close_shared */
112 process_wait, /* special_wait */
117 static struct sigaction previous_chld_sa;
119 static mono_once_t process_sig_chld_once = MONO_ONCE_INIT;
120 static void process_add_sigchld_handler (void);
122 /* The signal-safe logic to use mono_processes goes like this:
123 * - The list must be safe to traverse for the signal handler at all times.
124 * It's safe to: prepend an entry (which is a single store to 'mono_processes'),
125 * unlink an entry (assuming the unlinked entry isn't freed and doesn't
126 * change its 'next' pointer so that it can still be traversed).
127 * When cleaning up we first unlink an entry, then we verify that
128 * the read lock isn't locked. Then we can free the entry, since
129 * we know that nobody is using the old version of the list (including
130 * the unlinked entry).
131 * We also need to lock when adding and cleaning up so that those two
132 * operations don't mess with eachother. (This lock is not used in the
135 static struct MonoProcess *mono_processes = NULL;
136 static volatile gint32 mono_processes_read_lock = 0;
137 static volatile gint32 mono_processes_cleaning_up = 0;
138 static mono_mutex_t mono_processes_mutex;
139 static void mono_processes_cleanup (void);
141 static mono_once_t process_current_once=MONO_ONCE_INIT;
142 static gpointer current_process=NULL;
144 static mono_once_t process_ops_once=MONO_ONCE_INIT;
146 static void process_ops_init (void)
148 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
149 WAPI_HANDLE_CAP_WAIT |
150 WAPI_HANDLE_CAP_SPECIAL_WAIT);
154 /* Check if a pid is valid - i.e. if a process exists with this pid. */
155 static gboolean is_pid_valid (pid_t pid)
157 gboolean result = FALSE;
159 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
160 if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
162 #elif defined(__HAIKU__)
164 if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
167 gchar *dir = g_strdup_printf ("/proc/%d", pid);
168 if (!access (dir, F_OK))
176 static void process_set_defaults (struct _WapiHandle_process *process_handle)
178 /* These seem to be the defaults on w2k */
179 process_handle->min_working_set = 204800;
180 process_handle->max_working_set = 1413120;
182 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
186 len16 (const gunichar2 *str)
197 utf16_concat (const gunichar2 *first, ...)
204 va_start (args, first);
205 total += len16 (first);
206 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
211 ret = g_new (gunichar2, total + 1);
217 for (s = first; *s != 0; s++)
219 va_start (args, first);
220 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
223 for (p = s; *p != 0; p++)
231 #ifdef PLATFORM_MACOSX
233 /* 0 = no detection; -1 = not 10.5 or higher; 1 = 10.5 or higher */
234 static int osx_10_5_or_higher;
237 detect_osx_10_5_or_higher (void)
243 if (uname (&u) != 0){
244 osx_10_5_or_higher = 1;
252 osx_10_5_or_higher = -1;
254 osx_10_5_or_higher = 1;
258 is_macos_10_5_or_higher (void)
260 if (osx_10_5_or_higher == 0)
261 detect_osx_10_5_or_higher ();
263 return (osx_10_5_or_higher == 1);
267 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
268 static const gunichar2 *utf16_space = utf16_space_bytes;
269 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
270 static const gunichar2 *utf16_quote = utf16_quote_bytes;
275 print_utf16 (gunichar2 *str)
279 res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
280 g_print ("%s\n", res);
285 /* Implemented as just a wrapper around CreateProcess () */
286 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
289 WapiProcessInformation process_info;
293 /* w2k just segfaults here, but we can do better than
296 SetLastError (ERROR_INVALID_PARAMETER);
300 if (sei->lpFile == NULL) {
301 /* w2k returns TRUE for this, for some reason. */
305 /* Put both executable and parameters into the second argument
306 * to CreateProcess (), so it searches $PATH. The conversion
307 * into and back out of utf8 is because there is no
308 * g_strdup_printf () equivalent for gunichar2 :-(
310 args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
312 SetLastError (ERROR_INVALID_DATA);
315 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
316 CREATE_UNICODE_ENVIRONMENT, NULL,
317 sei->lpDirectory, NULL, &process_info);
320 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
324 static char *handler;
325 static gunichar2 *handler_utf16;
327 if (handler_utf16 == (gunichar2 *)-1)
330 #ifdef PLATFORM_MACOSX
331 if (is_macos_10_5_or_higher ())
332 handler = g_strdup ("/usr/bin/open -W");
334 handler = g_strdup ("/usr/bin/open");
337 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
338 * if that fails, try to use gnome-open, then kfmclient
340 handler = g_find_program_in_path ("xdg-open");
341 if (handler == NULL){
342 handler = g_find_program_in_path ("gnome-open");
343 if (handler == NULL){
344 handler = g_find_program_in_path ("kfmclient");
345 if (handler == NULL){
346 handler_utf16 = (gunichar2 *) -1;
349 /* kfmclient needs exec argument */
351 handler = g_strconcat (old, " exec",
358 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
361 /* Put quotes around the filename, in case it's a url
362 * that contains #'s (CreateProcess() calls
363 * g_shell_parse_argv(), which deliberately throws
364 * away anything after an unquoted #). Fixes bug
367 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
368 sei->lpFile, utf16_quote,
369 sei->lpParameters == NULL ? NULL : utf16_space,
370 sei->lpParameters, NULL);
372 SetLastError (ERROR_INVALID_DATA);
375 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
376 CREATE_UNICODE_ENVIRONMENT, NULL,
377 sei->lpDirectory, NULL, &process_info);
380 SetLastError (ERROR_INVALID_DATA);
385 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
386 sei->hProcess = process_info.hProcess;
388 CloseHandle (process_info.hProcess);
395 is_managed_binary (const gchar *filename)
397 int original_errno = errno;
398 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
399 int file = open (filename, O_RDONLY | O_LARGEFILE);
401 int file = open (filename, O_RDONLY);
404 unsigned char buffer[8];
405 off_t file_size, optional_header_offset;
406 off_t pe_header_offset;
407 gboolean managed = FALSE;
409 guint32 first_word, second_word;
411 /* If we are unable to open the file, then we definitely
412 * can't say that it is managed. The child mono process
413 * probably wouldn't be able to open it anyway.
416 errno = original_errno;
420 /* Retrieve the length of the file for future sanity checks. */
421 file_size = lseek (file, 0, SEEK_END);
422 lseek (file, 0, SEEK_SET);
424 /* We know we need to read a header field at offset 60. */
428 num_read = read (file, buffer, 2);
430 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
433 new_offset = lseek (file, 60, SEEK_SET);
435 if (new_offset != 60)
438 num_read = read (file, buffer, 4);
442 pe_header_offset = buffer[0]
447 if (pe_header_offset + 24 > file_size)
450 new_offset = lseek (file, pe_header_offset, SEEK_SET);
452 if (new_offset != pe_header_offset)
455 num_read = read (file, buffer, 4);
457 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
461 * Verify that the header we want in the optional header data
462 * is present in this binary.
464 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
466 if (new_offset != pe_header_offset + 20)
469 num_read = read (file, buffer, 2);
471 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
474 /* Read the CLR header address and size fields. These will be
475 * zero if the binary is not managed.
477 optional_header_offset = pe_header_offset + 24;
478 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
480 if (new_offset != optional_header_offset + 208)
483 num_read = read (file, buffer, 8);
485 /* We are not concerned with endianness, only with
486 * whether it is zero or not.
488 first_word = *(guint32 *)&buffer[0];
489 second_word = *(guint32 *)&buffer[4];
491 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
498 errno = original_errno;
502 gboolean CreateProcessWithLogonW (const gunichar2 *username,
503 const gunichar2 *domain,
504 const gunichar2 *password,
505 const guint32 logonFlags,
506 const gunichar2 *appname,
507 const gunichar2 *cmdline,
508 guint32 create_flags,
510 const gunichar2 *cwd,
511 WapiStartupInfo *startup,
512 WapiProcessInformation *process_info)
514 /* FIXME: use user information */
515 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
519 is_executable (const char *prog)
522 if (access (prog, X_OK) != 0)
524 if (stat (prog, &buf))
526 if (S_ISREG (buf.st_mode))
532 switchDirectorySeparators(gchar *path)
534 size_t i, pathLength = strlen(path);
536 /* Turn all the slashes round the right way, except for \' */
537 /* There are probably other characters that need to be excluded as well. */
538 for (i = 0; i < pathLength; i++)
540 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' ) {
546 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
547 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
548 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
549 gboolean inherit_handles, guint32 create_flags,
550 gpointer new_environ, const gunichar2 *cwd,
551 WapiStartupInfo *startup,
552 WapiProcessInformation *process_info)
554 gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
555 guint32 i, env_count = 0;
556 gboolean ret = FALSE;
558 struct _WapiHandle_process process_handle = {0}, *process_handle_data;
560 int in_fd, out_fd, err_fd;
563 int startup_pipe [2] = {-1, -1};
565 struct MonoProcess *mono_process;
567 mono_once (&process_ops_once, process_ops_init);
568 mono_once (&process_sig_chld_once, process_add_sigchld_handler);
570 /* appname and cmdline specify the executable and its args:
572 * If appname is not NULL, it is the name of the executable.
573 * Otherwise the executable is the first token in cmdline.
575 * Executable searching:
577 * If appname is not NULL, it can specify the full path and
578 * file name, or else a partial name and the current directory
579 * will be used. There is no additional searching.
581 * If appname is NULL, the first whitespace-delimited token in
582 * cmdline is used. If the name does not contain a full
583 * directory path, the search sequence is:
585 * 1) The directory containing the current process
586 * 2) The current working directory
587 * 3) The windows system directory (Ignored)
588 * 4) The windows directory (Ignored)
591 * Just to make things more interesting, tokens can contain
592 * white space if they are surrounded by quotation marks. I'm
593 * beginning to understand just why windows apps are generally
594 * so crap, with an API like this :-(
596 if (appname != NULL) {
597 cmd = mono_unicode_to_external (appname);
599 DEBUG ("%s: unicode conversion returned NULL",
602 SetLastError (ERROR_PATH_NOT_FOUND);
606 switchDirectorySeparators(cmd);
609 if (cmdline != NULL) {
610 args = mono_unicode_to_external (cmdline);
612 DEBUG ("%s: unicode conversion returned NULL", __func__);
614 SetLastError (ERROR_PATH_NOT_FOUND);
620 dir = mono_unicode_to_external (cwd);
622 DEBUG ("%s: unicode conversion returned NULL", __func__);
624 SetLastError (ERROR_PATH_NOT_FOUND);
628 /* Turn all the slashes round the right way */
629 switchDirectorySeparators(dir);
633 /* We can't put off locating the executable any longer :-( */
636 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
637 /* Strip off the drive letter. I can't
638 * believe that CP/M holdover is still
641 g_memmove (cmd, cmd+2, strlen (cmd)-2);
642 cmd[strlen (cmd)-2] = '\0';
645 unquoted = g_shell_unquote (cmd, NULL);
646 if (unquoted[0] == '/') {
647 /* Assume full path given */
648 prog = g_strdup (unquoted);
650 /* Executable existing ? */
651 if (!is_executable (prog)) {
652 DEBUG ("%s: Couldn't find executable %s",
655 SetLastError (ERROR_FILE_NOT_FOUND);
659 /* Search for file named by cmd in the current
662 char *curdir = g_get_current_dir ();
664 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
667 /* And make sure it's executable */
668 if (!is_executable (prog)) {
669 DEBUG ("%s: Couldn't find executable %s",
672 SetLastError (ERROR_FILE_NOT_FOUND);
678 args_after_prog = args;
683 /* Dig out the first token from args, taking quotation
687 /* First, strip off all leading whitespace */
688 args = g_strchug (args);
690 /* args_after_prog points to the contents of args
691 * after token has been set (otherwise argv[0] is
694 args_after_prog = args;
696 /* Assume the opening quote will always be the first
699 if (args[0] == '\"' || args [0] == '\'') {
701 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
702 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
703 /* We found the first token */
704 token = g_strndup (args+1, i-1);
705 args_after_prog = g_strchug (args + i + 1);
707 /* Quotation mark appeared in the
708 * middle of the token. Just give the
709 * whole first token, quotes and all,
716 /* No quote mark, or malformed */
717 for (i = 0; args[i] != '\0'; i++) {
718 if (g_ascii_isspace (args[i])) {
719 token = g_strndup (args, i);
720 args_after_prog = args + i + 1;
726 if (token == NULL && args[0] != '\0') {
727 /* Must be just one token in the string */
728 token = g_strdup (args);
729 args_after_prog = NULL;
734 DEBUG ("%s: Couldn't find what to exec", __func__);
736 SetLastError (ERROR_PATH_NOT_FOUND);
740 /* Turn all the slashes round the right way. Only for
743 switchDirectorySeparators(token);
745 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
746 /* Strip off the drive letter. I can't
747 * believe that CP/M holdover is still
750 g_memmove (token, token+2, strlen (token)-2);
751 token[strlen (token)-2] = '\0';
754 if (token[0] == '/') {
755 /* Assume full path given */
756 prog = g_strdup (token);
758 /* Executable existing ? */
759 if (!is_executable (prog)) {
760 DEBUG ("%s: Couldn't find executable %s",
763 SetLastError (ERROR_FILE_NOT_FOUND);
768 char *curdir = g_get_current_dir ();
770 /* FIXME: Need to record the directory
771 * containing the current process, and check
772 * that for the new executable as the first
776 prog = g_strdup_printf ("%s/%s", curdir, token);
779 /* I assume X_OK is the criterion to use,
782 if (!is_executable (prog)) {
784 prog = g_find_program_in_path (token);
786 DEBUG ("%s: Couldn't find executable %s", __func__, token);
789 SetLastError (ERROR_FILE_NOT_FOUND);
798 DEBUG ("%s: Exec prog [%s] args [%s]", __func__, prog,
801 /* Check for CLR binaries; if found, we will try to invoke
802 * them using the same mono binary that started us.
804 if (is_managed_binary (prog)) {
805 gunichar2 *newapp, *newcmd;
808 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
810 if (newapp != NULL) {
811 if (appname != NULL) {
812 newcmd = utf16_concat (newapp, utf16_space,
813 appname, utf16_space,
816 newcmd = utf16_concat (newapp, utf16_space,
820 g_free ((gunichar2 *)newapp);
822 if (newcmd != NULL) {
823 ret = CreateProcess (NULL, newcmd,
827 create_flags, new_environ,
831 g_free ((gunichar2 *)newcmd);
838 if (args_after_prog != NULL && *args_after_prog) {
841 qprog = g_shell_quote (prog);
842 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
845 full_prog = g_shell_quote (prog);
848 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
850 g_message ("CreateProcess: %s\n", gerr->message);
856 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
857 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
858 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
859 err_fd = GPOINTER_TO_UINT (startup->hStdError);
861 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
862 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
863 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
866 g_strlcpy (process_handle.proc_name, prog,
867 _WAPI_PROC_NAME_MAX_LEN - 1);
869 process_set_defaults (&process_handle);
871 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
872 if (handle == _WAPI_HANDLE_INVALID) {
873 g_warning ("%s: error creating process handle", __func__);
876 SetLastError (ERROR_OUTOFMEMORY);
880 /* new_environ is a block of NULL-terminated strings, which
881 * is itself NULL-terminated. Of course, passing an array of
882 * string pointers would have made things too easy :-(
884 * If new_environ is not NULL it specifies the entire set of
885 * environment variables in the new process. Otherwise the
886 * new process inherits the same environment.
888 if (new_environ != NULL) {
889 gunichar2 *new_environp;
891 /* Count the number of strings */
892 for (new_environp = (gunichar2 *)new_environ; *new_environp;
895 while (*new_environp) {
900 /* +2: one for the process handle value, and the last
903 env_strings = g_new0 (gchar *, env_count + 2);
905 /* Copy each environ string into 'strings' turning it
906 * into utf8 (or the requested encoding) at the same
910 for (new_environp = (gunichar2 *)new_environ; *new_environp;
912 env_strings[env_count] = mono_unicode_to_external (new_environp);
914 while (*new_environp) {
919 for (i = 0; environ[i] != NULL; i++) {
923 /* +2: one for the process handle value, and the last
926 env_strings = g_new0 (gchar *, env_count + 2);
928 /* Copy each environ string into 'strings' turning it
929 * into utf8 (or the requested encoding) at the same
933 for (i = 0; environ[i] != NULL; i++) {
934 env_strings[env_count] = g_strdup (environ[i]);
938 /* pass process handle info to the child, so it doesn't have
939 * to do an expensive search over the whole list
941 if (env_strings != NULL) {
942 struct _WapiHandleUnshared *handle_data;
943 struct _WapiHandle_shared_ref *ref;
945 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
946 ref = &handle_data->u.shared;
948 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
951 /* Create a pipe to make sure the child doesn't exit before
952 * we can add the process to the linked list of mono_processes */
953 if (pipe (startup_pipe) == -1) {
954 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
955 * This is just for a very hard to hit race condition in the first place */
956 startup_pipe [0] = startup_pipe [1] = -1;
957 DEBUG ("%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
960 thr_ret = _wapi_handle_lock_shared_handles ();
961 g_assert (thr_ret == 0);
966 SetLastError (ERROR_OUTOFMEMORY);
967 _wapi_handle_unref (handle);
969 } else if (pid == 0) {
972 if (startup_pipe [0] != -1) {
973 /* Wait until the parent has updated it's internal data */
974 read (startup_pipe [0], &dummy, 1);
975 DEBUG ("%s: child: parent has completed its setup", __func__);
976 close (startup_pipe [0]);
977 close (startup_pipe [1]);
980 /* should we detach from the process group? */
982 /* Connect stdin, stdout and stderr */
987 if (inherit_handles != TRUE) {
988 /* FIXME: do something here */
991 /* Close all file descriptors */
992 for (i = getdtablesize () - 1; i > 2; i--) {
997 DEBUG ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
999 for (i = 0; argv[i] != NULL; i++) {
1000 g_message ("arg %d: [%s]", i, argv[i]);
1003 for (i = 0; env_strings[i] != NULL; i++) {
1004 g_message ("env %d: [%s]", i, env_strings[i]);
1009 if (dir != NULL && chdir (dir) == -1) {
1015 execve (argv[0], argv, env_strings);
1022 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1023 (gpointer *)&process_handle_data);
1025 g_warning ("%s: error looking up process handle %p", __func__,
1027 _wapi_handle_unref (handle);
1031 process_handle_data->id = pid;
1033 /* Add our mono_process into the linked list of mono_processes */
1034 mono_process = (struct MonoProcess *) g_malloc0 (sizeof (struct MonoProcess));
1035 mono_process->pid = pid;
1036 mono_process->handle_count = 1;
1037 if (MONO_SEM_INIT (&mono_process->exit_sem, 0) != 0) {
1038 /* If we can't create the exit semaphore, we just don't add anything
1039 * to our list of mono processes. Waiting on the process will return
1041 g_warning ("%s: could not create exit semaphore for process.", strerror (errno));
1042 g_free (mono_process);
1044 /* Keep the process handle artificially alive until the process
1045 * exits so that the information in the handle isn't lost. */
1046 _wapi_handle_ref (handle);
1047 mono_process->handle = handle;
1049 process_handle_data->self = _wapi_getpid ();
1050 process_handle_data->mono_process = mono_process;
1052 mono_mutex_lock (&mono_processes_mutex);
1053 mono_process->next = mono_processes;
1054 mono_processes = mono_process;
1055 mono_mutex_unlock (&mono_processes_mutex);
1058 if (process_info != NULL) {
1059 process_info->hProcess = handle;
1060 process_info->dwProcessId = pid;
1062 /* FIXME: we might need to handle the thread info some
1065 process_info->hThread = INVALID_HANDLE_VALUE;
1066 process_info->dwThreadId = 0;
1070 _wapi_handle_unlock_shared_handles ();
1072 if (startup_pipe [1] != -1) {
1073 /* Write 1 byte, doesn't matter what */
1074 write (startup_pipe [1], startup_pipe, 1);
1075 close (startup_pipe [0]);
1076 close (startup_pipe [1]);
1083 if (full_prog != NULL) {
1095 if(env_strings != NULL) {
1096 g_strfreev (env_strings);
1102 DEBUG ("%s: returning handle %p for pid %d", __func__, handle,
1105 /* Check if something needs to be cleaned up. */
1106 mono_processes_cleanup ();
1111 static void process_set_name (struct _WapiHandle_process *process_handle)
1113 gchar *progname, *utf8_progname, *slash;
1115 progname=g_get_prgname ();
1116 utf8_progname=mono_utf8_from_external (progname);
1118 DEBUG ("%s: using [%s] as prog name", __func__, progname);
1120 if(utf8_progname!=NULL) {
1121 slash=strrchr (utf8_progname, '/');
1123 g_strlcpy (process_handle->proc_name, slash+1,
1124 _WAPI_PROC_NAME_MAX_LEN - 1);
1126 g_strlcpy (process_handle->proc_name, utf8_progname,
1127 _WAPI_PROC_NAME_MAX_LEN - 1);
1130 g_free (utf8_progname);
1134 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
1136 #if !GLIB_CHECK_VERSION (2,4,0)
1137 #define g_setenv(a,b,c) setenv(a,b,c)
1138 #define g_unsetenv(a) unsetenv(a)
1141 static void process_set_current (void)
1143 pid_t pid = _wapi_getpid ();
1144 const char *handle_env;
1145 struct _WapiHandle_process process_handle = {0};
1147 mono_once (&process_ops_once, process_ops_init);
1149 handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1150 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1152 if (handle_env != NULL) {
1153 struct _WapiHandle_process *process_handlep;
1154 gchar *procname = NULL;
1157 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
1159 DEBUG ("%s: Found my process handle: %p (offset %d 0x%x)",
1160 __func__, current_process, atoi (handle_env),
1163 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
1164 (gpointer *)&process_handlep);
1166 /* This test will probably break on linuxthreads, but
1167 * that should be ancient history on all distros we
1170 if (process_handlep->id == pid) {
1171 procname = process_handlep->proc_name;
1172 if (!strcmp (procname, "mono")) {
1173 /* Set a better process name */
1174 DEBUG ("%s: Setting better process name", __func__);
1176 process_set_name (process_handlep);
1178 DEBUG ("%s: Leaving process name: %s", __func__, procname);
1184 /* Wrong pid, so drop this handle and fall through to
1187 _wapi_handle_unref (current_process);
1191 /* We get here if the handle wasn't specified in the
1192 * environment, or if the process ID was wrong, or if the
1193 * handle lookup failed (eg if the parent process forked and
1194 * quit immediately, and deleted the shared data before the
1195 * child got a chance to attach it.)
1198 DEBUG ("%s: Need to create my own process handle", __func__);
1200 process_handle.id = pid;
1202 process_set_defaults (&process_handle);
1203 process_set_name (&process_handle);
1205 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1207 if (current_process == _WAPI_HANDLE_INVALID) {
1208 g_warning ("%s: error creating process handle", __func__);
1213 gpointer _wapi_process_duplicate ()
1215 mono_once (&process_current_once, process_set_current);
1217 _wapi_handle_ref (current_process);
1219 return(current_process);
1222 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1223 gpointer GetCurrentProcess (void)
1225 mono_once (&process_current_once, process_set_current);
1227 return(_WAPI_PROCESS_CURRENT);
1230 guint32 GetProcessId (gpointer handle)
1232 struct _WapiHandle_process *process_handle;
1235 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1236 /* This is a pseudo handle */
1237 return(GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
1240 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1241 (gpointer *)&process_handle);
1243 SetLastError (ERROR_INVALID_HANDLE);
1247 return (process_handle->id);
1250 guint32 GetCurrentProcessId (void)
1252 mono_once (&process_current_once, process_set_current);
1254 return (GetProcessId (current_process));
1257 /* Returns the process id as a convenience to the functions that call this */
1258 static pid_t signal_process_if_gone (gpointer handle)
1260 struct _WapiHandle_process *process_handle;
1263 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
1265 /* Make sure the process is signalled if it has exited - if
1266 * the parent process didn't wait for it then it won't be
1268 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1269 (gpointer *)&process_handle);
1271 /* It's possible that the handle has vanished during
1272 * the _wapi_search_handle before it gets here, so
1273 * don't spam the console with warnings.
1275 /* g_warning ("%s: error looking up process handle %p",
1276 __func__, handle);*/
1281 DEBUG ("%s: looking at process %d", __func__, process_handle->id);
1283 if (kill (process_handle->id, 0) == -1 &&
1286 /* The process is dead, (EPERM tells us a new process
1287 * has that ID, but as it's owned by someone else it
1288 * can't be the one listed in our shared memory file)
1290 _wapi_shared_handle_set_signal_state (handle, TRUE);
1293 return (process_handle->id);
1297 static gboolean process_enum (gpointer handle, gpointer user_data)
1299 GArray *processes=user_data;
1300 pid_t pid = signal_process_if_gone (handle);
1307 /* Ignore processes that have already exited (ie they are signalled) */
1308 if (_wapi_handle_issignalled (handle) == FALSE) {
1309 DEBUG ("%s: process %d added to array", __func__, pid);
1311 /* This ensures that duplicates aren't returned (see
1312 * the comment above _wapi_search_handle () for why
1315 for (i = 0; i < processes->len; i++) {
1316 if (g_array_index (processes, pid_t, i) == pid) {
1317 /* We've already got this one, return
1318 * FALSE to keep searching
1324 g_array_append_val (processes, pid);
1327 /* Return false to keep searching */
1330 #endif /* UNUSED_CODE */
1332 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
1334 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1336 guint32 count, fit, i, j;
1339 size_t proclength, size;
1340 #if defined(__OpenBSD__)
1341 struct kinfo_proc2 *result;
1344 name[1] = KERN_PROC2;
1345 name[2] = KERN_PROC_ALL;
1347 name[4] = sizeof(struct kinfo_proc2);
1350 struct kinfo_proc *result;
1351 static const int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
1354 mono_once (&process_current_once, process_set_current);
1361 #if defined(__OpenBSD__)
1362 size = (sizeof(name) / sizeof(*name));
1364 size = (sizeof(name) / sizeof(*name)) - 1;
1366 err = sysctl ((int *)name, size, NULL, &proclength, NULL, 0);
1369 result = malloc (proclength);
1374 #if defined(__OpenBSD__)
1375 name[5] = (int)(proclength / sizeof(struct kinfo_proc2));
1378 err = sysctl ((int *) name, size, result, &proclength, NULL, 0);
1385 } while (err == 0 && !done);
1388 if (result != NULL) {
1395 #if defined(__OpenBSD__)
1396 count = proclength / sizeof(struct kinfo_proc2);
1398 count = proclength / sizeof(struct kinfo_proc);
1400 fit = len / sizeof(guint32);
1401 for (i = 0, j = 0; j< fit && i < count; i++) {
1402 #if defined(__OpenBSD__)
1403 pids [j++] = result [i].p_pid;
1405 if (result[i].kp_proc.p_pid > 0) /* Pid 0 not supported */
1406 pids [j++] = result [i].kp_proc.p_pid;
1411 *needed = j * sizeof(guint32);
1415 #elif defined(__HAIKU__)
1417 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1423 mono_once (&process_current_once, process_set_current);
1425 fit = len / sizeof (guint32);
1426 while (get_next_team_info (&cookie, &teamInfo) == B_OK && i < fit) {
1427 pids [i++] = teamInfo.team;
1429 *needed = i * sizeof (guint32);
1434 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1438 struct dirent *entry;
1440 mono_once (&process_current_once, process_set_current);
1442 dir = opendir ("/proc");
1448 fit = len / sizeof (guint32);
1449 while(i < fit && (entry = readdir (dir)) != NULL) {
1453 if (!isdigit (entry->d_name[0]))
1456 pid = (pid_t) strtol (entry->d_name, &endptr, 10);
1457 if (*endptr == '\0')
1458 pids [i++] = (guint32) pid;
1461 *needed = i * sizeof(guint32);
1467 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1470 pid_t checking_pid = signal_process_if_gone (handle);
1472 if (checking_pid == 0) {
1476 wanted_pid = GPOINTER_TO_UINT (user_data);
1478 /* It's possible to have more than one process handle with the
1479 * same pid, but only the one running process can be
1482 if (checking_pid == wanted_pid &&
1483 _wapi_handle_issignalled (handle) == FALSE) {
1484 /* If the handle is blown away in the window between
1485 * returning TRUE here and _wapi_search_handle pinging
1486 * the timestamp, the search will continue
1494 gboolean CloseProcess(gpointer handle)
1496 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1497 /* This is a pseudo handle */
1501 return CloseHandle (handle);
1505 * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1507 gpointer OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1509 /* Find the process handle that corresponds to pid */
1510 gpointer handle = NULL;
1512 mono_once (&process_current_once, process_set_current);
1514 DEBUG ("%s: looking for process %d", __func__, pid);
1516 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1517 process_open_compare,
1518 GUINT_TO_POINTER (pid), NULL, TRUE);
1520 if (is_pid_valid (pid)) {
1521 /* Return a pseudo handle for processes we
1522 * don't have handles for
1524 return GINT_TO_POINTER (_WAPI_PROCESS_UNHANDLED + pid);
1526 DEBUG ("%s: Can't find pid %d", __func__, pid);
1528 SetLastError (ERROR_PROC_NOT_FOUND);
1534 /* _wapi_search_handle () already added a ref */
1538 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1540 struct _WapiHandle_process *process_handle;
1544 mono_once (&process_current_once, process_set_current);
1550 pid = GPOINTER_TO_UINT (process) - _WAPI_PROCESS_UNHANDLED;
1551 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1552 /* This is a pseudo handle, so we don't know what the
1553 * exit code was, but we can check whether it's alive or not
1555 if (is_pid_valid (pid)) {
1556 *code = STILL_ACTIVE;
1563 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1564 (gpointer *)&process_handle);
1566 DEBUG ("%s: Can't find process %p", __func__, process);
1571 /* A process handle is only signalled if the process has exited
1572 * and has been waited for */
1574 /* Make sure any process exit has been noticed, before
1575 * checking if the process is signalled. Fixes bug 325463.
1577 process_wait (process, 0, TRUE);
1579 if (_wapi_handle_issignalled (process) == TRUE) {
1580 *code = process_handle->exitstatus;
1582 *code = STILL_ACTIVE;
1588 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1589 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1590 WapiFileTime *user_time)
1592 struct _WapiHandle_process *process_handle;
1594 gboolean ku_times_set = FALSE;
1596 mono_once (&process_current_once, process_set_current);
1598 if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1600 /* Not sure if w32 allows NULLs here or not */
1604 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1605 /* This is a pseudo handle, so just fail for now
1610 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1611 (gpointer *)&process_handle);
1613 DEBUG ("%s: Can't find process %p", __func__, process);
1618 *create_time=process_handle->create_time;
1620 /* A process handle is only signalled if the process has
1621 * exited. Otherwise exit_time isn't set
1623 if(_wapi_handle_issignalled (process)==TRUE) {
1624 *exit_time=process_handle->exit_time;
1627 #ifdef HAVE_GETRUSAGE
1628 if (process_handle->id == getpid ()) {
1629 struct rusage time_data;
1630 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1632 gint64 *tick_val_ptr;
1633 ku_times_set = TRUE;
1634 tick_val = time_data.ru_utime.tv_sec * 10000000 + time_data.ru_utime.tv_usec * 10;
1635 tick_val_ptr = (gint64*)user_time;
1636 *tick_val_ptr = tick_val;
1637 tick_val = time_data.ru_stime.tv_sec * 10000000 + time_data.ru_stime.tv_usec * 10;
1638 tick_val_ptr = (gint64*)kernel_time;
1639 *tick_val_ptr = tick_val;
1643 if (!ku_times_set) {
1644 memset (kernel_time, 0, sizeof (WapiFileTime));
1645 memset (user_time, 0, sizeof (WapiFileTime));
1653 gpointer address_start;
1654 gpointer address_end;
1656 gpointer address_offset;
1662 static void free_procmodule (WapiProcModule *mod)
1664 if (mod->perms != NULL) {
1665 g_free (mod->perms);
1667 if (mod->filename != NULL) {
1668 g_free (mod->filename);
1673 static gint find_procmodule (gconstpointer a, gconstpointer b)
1675 WapiProcModule *want = (WapiProcModule *)a;
1676 WapiProcModule *compare = (WapiProcModule *)b;
1678 if ((want->device == compare->device) &&
1679 (want->inode == compare->inode)) {
1686 #ifdef PLATFORM_MACOSX
1687 #include <mach-o/dyld.h>
1688 #include <mach-o/getsect.h>
1690 static GSList *load_modules (void)
1693 WapiProcModule *mod;
1694 uint32_t count = _dyld_image_count ();
1697 for (i = 0; i < count; i++) {
1698 #if SIZEOF_VOID_P == 8
1699 const struct mach_header_64 *hdr;
1700 const struct section_64 *sec;
1702 const struct mach_header *hdr;
1703 const struct section *sec;
1708 slide = _dyld_get_image_vmaddr_slide (i);
1709 name = _dyld_get_image_name (i);
1710 hdr = _dyld_get_image_header (i);
1711 #if SIZEOF_VOID_P == 8
1712 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1714 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1717 /* Some dynlibs do not have data sections on osx (#533893) */
1722 mod = g_new0 (WapiProcModule, 1);
1723 mod->address_start = GINT_TO_POINTER (sec->addr);
1724 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1725 mod->perms = g_strdup ("r--p");
1726 mod->address_offset = 0;
1727 mod->device = makedev (0, 0);
1728 mod->inode = (ino_t) i;
1729 mod->filename = g_strdup (name);
1731 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1732 ret = g_slist_prepend (ret, mod);
1734 free_procmodule (mod);
1738 ret = g_slist_reverse (ret);
1742 #elif defined(__OpenBSD__)
1744 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1746 if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1747 + sizeof (info->dlpi_phnum))
1750 struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1754 memcpy(cpy, info, sizeof(*info));
1756 g_ptr_array_add ((GPtrArray *)ptr, cpy);
1761 static GSList *load_modules (void)
1764 WapiProcModule *mod;
1765 GPtrArray *dlarray = g_ptr_array_new();
1768 if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1771 for (i = 0; i < dlarray->len; i++) {
1772 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1774 mod = g_new0 (WapiProcModule, 1);
1775 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1776 mod->address_end = (gpointer)(info->dlpi_addr +
1777 info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1778 mod->perms = g_strdup ("r--p");
1779 mod->address_offset = 0;
1780 mod->inode = (ino_t) i;
1781 mod->filename = g_strdup (info->dlpi_name);
1783 DEBUG ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1784 mod->inode, mod->filename, mod->address_start, mod->address_end);
1788 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1789 ret = g_slist_prepend (ret, mod);
1791 free_procmodule (mod);
1795 g_ptr_array_free (dlarray, TRUE);
1797 ret = g_slist_reverse (ret);
1801 #elif defined(__HAIKU__)
1803 static GSList *load_modules (void)
1806 WapiProcModule *mod;
1808 image_info imageInfo;
1810 while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
1811 mod = g_new0 (WapiProcModule, 1);
1812 mod->device = imageInfo.device;
1813 mod->inode = imageInfo.node;
1814 mod->filename = g_strdup (imageInfo.name);
1815 mod->address_start = MIN (imageInfo.text, imageInfo.data);
1816 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
1817 (uint8_t*)imageInfo.data + imageInfo.data_size);
1818 mod->perms = g_strdup ("r--p");
1819 mod->address_offset = 0;
1821 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1822 ret = g_slist_prepend (ret, mod);
1824 free_procmodule (mod);
1828 ret = g_slist_reverse (ret);
1833 static GSList *load_modules (FILE *fp)
1836 WapiProcModule *mod;
1837 gchar buf[MAXPATHLEN + 1], *p, *endp;
1838 gchar *start_start, *end_start, *prot_start, *offset_start;
1839 gchar *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1840 gpointer address_start, address_end, address_offset;
1841 guint32 maj_dev, min_dev;
1845 while (fgets (buf, sizeof(buf), fp)) {
1847 while (g_ascii_isspace (*p)) ++p;
1849 if (!g_ascii_isxdigit (*start_start)) {
1852 address_start = (gpointer)strtoul (start_start, &endp, 16);
1860 if (!g_ascii_isxdigit (*end_start)) {
1863 address_end = (gpointer)strtoul (end_start, &endp, 16);
1865 if (!g_ascii_isspace (*p)) {
1869 while (g_ascii_isspace (*p)) ++p;
1871 if (*prot_start != 'r' && *prot_start != '-') {
1874 memcpy (prot_buf, prot_start, 4);
1876 while (!g_ascii_isspace (*p)) ++p;
1878 while (g_ascii_isspace (*p)) ++p;
1880 if (!g_ascii_isxdigit (*offset_start)) {
1883 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1885 if (!g_ascii_isspace (*p)) {
1889 while(g_ascii_isspace (*p)) ++p;
1891 if (!g_ascii_isxdigit (*maj_dev_start)) {
1894 maj_dev = strtoul (maj_dev_start, &endp, 16);
1902 if (!g_ascii_isxdigit (*min_dev_start)) {
1905 min_dev = strtoul (min_dev_start, &endp, 16);
1907 if (!g_ascii_isspace (*p)) {
1911 while (g_ascii_isspace (*p)) ++p;
1913 if (!g_ascii_isxdigit (*inode_start)) {
1916 inode = (ino_t)strtol (inode_start, &endp, 10);
1918 if (!g_ascii_isspace (*p)) {
1922 device = makedev ((int)maj_dev, (int)min_dev);
1923 if ((device == 0) &&
1928 while(g_ascii_isspace (*p)) ++p;
1929 /* p now points to the filename */
1931 mod = g_new0 (WapiProcModule, 1);
1932 mod->address_start = address_start;
1933 mod->address_end = address_end;
1934 mod->perms = g_strdup (prot_buf);
1935 mod->address_offset = address_offset;
1936 mod->device = device;
1938 mod->filename = g_strdup (g_strstrip (p));
1940 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1941 ret = g_slist_prepend (ret, mod);
1943 free_procmodule (mod);
1947 ret = g_slist_reverse (ret);
1953 static gboolean match_procname_to_modulename (gchar *procname, gchar *modulename)
1955 char* lastsep = NULL;
1956 char* lastsep2 = NULL;
1959 gboolean result = FALSE;
1961 if (procname == NULL || modulename == NULL)
1964 pname = mono_path_resolve_symlinks (procname);
1965 mname = mono_path_resolve_symlinks (modulename);
1967 if (!strcmp (pname, mname))
1971 lastsep = strrchr (mname, '/');
1973 if (!strcmp (lastsep+1, pname))
1976 lastsep2 = strrchr (pname, '/');
1979 if (!strcmp (lastsep+1, lastsep2+1))
1982 if (!strcmp (mname, lastsep2+1))
1995 #if !defined(__OpenBSD__)
1997 open_process_map (int pid, const char *mode)
2000 const gchar *proc_path[] = {
2001 "/proc/%d/maps", /* GNU/Linux */
2002 "/proc/%d/map", /* FreeBSD */
2008 for (i = 0; fp == NULL && proc_path [i]; i++) {
2009 filename = g_strdup_printf (proc_path[i], pid);
2010 fp = fopen (filename, mode);
2018 gboolean EnumProcessModules (gpointer process, gpointer *modules,
2019 guint32 size, guint32 *needed)
2021 struct _WapiHandle_process *process_handle;
2023 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2026 GSList *mods = NULL;
2027 WapiProcModule *module;
2028 guint32 count, avail = size / sizeof(gpointer);
2031 gchar *proc_name = NULL;
2033 /* Store modules in an array of pointers (main module as
2034 * modules[0]), using the load address for each module as a
2035 * token. (Use 'NULL' as an alternative for the main module
2036 * so that the simple implementation can just return one item
2037 * for now.) Get the info from /proc/<pid>/maps on linux,
2038 * /proc/<pid>/map on FreeBSD, other systems will have to
2039 * implement /dev/kmem reading or whatever other horrid
2040 * technique is needed.
2042 if (size < sizeof(gpointer)) {
2046 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2047 /* This is a pseudo handle */
2048 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2050 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2051 (gpointer *)&process_handle);
2053 DEBUG ("%s: Can't find process %p", __func__, process);
2057 pid = process_handle->id;
2058 proc_name = process_handle->proc_name;
2061 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2063 mods = load_modules ();
2065 if ((fp = open_process_map (pid, "r")) == NULL) {
2066 /* No /proc/<pid>/maps so just return the main module
2070 *needed = sizeof(gpointer);
2072 mods = load_modules (fp);
2075 count = g_slist_length (mods);
2077 /* count + 1 to leave slot 0 for the main module */
2078 *needed = sizeof(gpointer) * (count + 1);
2080 /* Use the NULL shortcut, as the first line in
2081 * /proc/<pid>/maps isn't the executable, and we need
2082 * that first in the returned list. Check the module name
2083 * to see if it ends with the proc name and substitute
2084 * the first entry with it. FIXME if this turns out to
2088 for (i = 0; i < (avail - 1) && i < count; i++) {
2089 module = (WapiProcModule *)g_slist_nth_data (mods, i);
2090 if (modules[0] != NULL)
2091 modules[i] = module->address_start;
2092 else if (match_procname_to_modulename (proc_name, module->filename))
2093 modules[0] = module->address_start;
2095 modules[i + 1] = module->address_start;
2098 for (i = 0; i < count; i++) {
2099 free_procmodule (g_slist_nth_data (mods, i));
2101 g_slist_free (mods);
2107 static gchar *get_process_name_from_proc (pid_t pid)
2109 #if defined(__OpenBSD__)
2112 struct kinfo_proc2 *pi;
2113 #elif defined(PLATFORM_MACOSX)
2115 struct kinfo_proc *pi;
2116 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
2119 gchar *filename = NULL;
2124 #if defined(PLATFORM_SOLARIS)
2125 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
2126 if ((fp = fopen (filename, "r")) != NULL) {
2130 nread = fread (&info, sizeof (info), 1, fp);
2132 ret = g_strdup (info.pr_fname);
2138 #elif defined(PLATFORM_MACOSX)
2139 #if (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5) && !defined (__mono_ppc__) && !defined(__arm__)
2140 /* No proc name on OSX < 10.5 nor ppc nor iOS */
2141 memset (buf, '\0', sizeof(buf));
2142 proc_name (pid, buf, sizeof(buf));
2143 if (strlen (buf) > 0)
2144 ret = g_strdup (buf);
2146 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0)
2149 if ((pi = malloc(size)) == NULL)
2152 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
2153 if (errno == ENOMEM) {
2155 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__);
2160 if (strlen (pi->kp_proc.p_comm) > 0)
2161 ret = g_strdup (pi->kp_proc.p_comm);
2165 #elif defined(__OpenBSD__)
2167 mib [1] = KERN_PROC2;
2168 mib [2] = KERN_PROC_PID;
2170 mib [4] = sizeof(struct kinfo_proc2);
2174 if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0)
2177 if ((pi = malloc(size)) == NULL)
2180 mib[5] = (int)(size / sizeof(struct kinfo_proc2));
2182 if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
2183 (size != sizeof (struct kinfo_proc2))) {
2184 if (errno == ENOMEM) {
2191 if (strlen (pi->p_comm) > 0)
2192 ret = g_strdup (pi->p_comm);
2195 #elif defined(__HAIKU__)
2196 image_info imageInfo;
2199 if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
2200 ret = g_strdup (imageInfo.name);
2203 memset (buf, '\0', sizeof(buf));
2204 filename = g_strdup_printf ("/proc/%d/exe", pid);
2205 if (readlink (filename, buf, 255) > 0) {
2206 ret = g_strdup (buf);
2214 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
2215 if ((fp = fopen (filename, "r")) != NULL) {
2216 if (fgets (buf, 256, fp) != NULL) {
2217 ret = g_strdup (buf);
2228 filename = g_strdup_printf ("/proc/%d/stat", pid);
2229 if ((fp = fopen (filename, "r")) != NULL) {
2230 if (fgets (buf, 256, fp) != NULL) {
2233 start = strchr (buf, '(');
2234 if (start != NULL) {
2235 end = strchr (start + 1, ')');
2238 ret = g_strndup (start + 1,
2252 static guint32 get_module_name (gpointer process, gpointer module,
2253 gunichar2 *basename, guint32 size,
2256 struct _WapiHandle_process *process_handle;
2259 gunichar2 *procname;
2260 gchar *procname_ext = NULL;
2263 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2266 GSList *mods = NULL;
2267 WapiProcModule *found_module;
2270 gchar *proc_name = NULL;
2272 mono_once (&process_current_once, process_set_current);
2274 DEBUG ("%s: Getting module base name, process handle %p module %p",
2275 __func__, process, module);
2277 size = size*sizeof(gunichar2); /* adjust for unicode characters */
2279 if (basename == NULL || size == 0) {
2283 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2284 /* This is a pseudo handle */
2285 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2286 proc_name = get_process_name_from_proc (pid);
2288 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2289 (gpointer *)&process_handle);
2291 DEBUG ("%s: Can't find process %p", __func__,
2296 pid = process_handle->id;
2297 proc_name = g_strdup (process_handle->proc_name);
2300 /* Look up the address in /proc/<pid>/maps */
2301 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2303 mods = load_modules ();
2305 if ((fp = open_process_map (pid, "r")) == NULL) {
2306 if (errno == EACCES && module == NULL && base == TRUE) {
2307 procname_ext = get_process_name_from_proc (pid);
2309 /* No /proc/<pid>/maps, so just return failure
2316 mods = load_modules (fp);
2319 count = g_slist_length (mods);
2321 /* If module != NULL compare the address.
2322 * If module == NULL we are looking for the main module.
2323 * The best we can do for now check it the module name end with the process name.
2325 for (i = 0; i < count; i++) {
2326 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2327 if (procname_ext == NULL &&
2328 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2329 (module != NULL && found_module->address_start == module))) {
2331 procname_ext = g_path_get_basename (found_module->filename);
2333 procname_ext = g_strdup (found_module->filename);
2337 free_procmodule (found_module);
2340 if (procname_ext == NULL)
2342 /* If it's *still* null, we might have hit the
2343 * case where reading /proc/$pid/maps gives an
2344 * empty file for this user.
2346 procname_ext = get_process_name_from_proc (pid);
2349 g_slist_free (mods);
2353 if (procname_ext != NULL) {
2354 DEBUG ("%s: Process name is [%s]", __func__,
2357 procname = mono_unicode_from_external (procname_ext, &bytes);
2358 if (procname == NULL) {
2360 g_free (procname_ext);
2366 /* Add the terminator */
2370 DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2372 memcpy (basename, procname, size);
2374 DEBUG ("%s: Size %d larger than needed (%ld)",
2375 __func__, size, bytes);
2377 memcpy (basename, procname, bytes);
2381 g_free (procname_ext);
2389 guint32 GetModuleBaseName (gpointer process, gpointer module,
2390 gunichar2 *basename, guint32 size)
2392 return(get_module_name (process, module, basename, size, TRUE));
2395 guint32 GetModuleFileNameEx (gpointer process, gpointer module,
2396 gunichar2 *filename, guint32 size)
2398 return(get_module_name (process, module, filename, size, FALSE));
2401 gboolean GetModuleInformation (gpointer process, gpointer module,
2402 WapiModuleInfo *modinfo, guint32 size)
2404 struct _WapiHandle_process *process_handle;
2407 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2410 GSList *mods = NULL;
2411 WapiProcModule *found_module;
2414 gboolean ret = FALSE;
2415 gchar *proc_name = NULL;
2417 mono_once (&process_current_once, process_set_current);
2419 DEBUG ("%s: Getting module info, process handle %p module %p",
2420 __func__, process, module);
2422 if (modinfo == NULL || size < sizeof(WapiModuleInfo)) {
2426 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2427 /* This is a pseudo handle */
2428 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2429 proc_name = get_process_name_from_proc (pid);
2431 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2432 (gpointer *)&process_handle);
2434 DEBUG ("%s: Can't find process %p", __func__,
2439 pid = process_handle->id;
2440 proc_name = g_strdup (process_handle->proc_name);
2443 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2445 mods = load_modules ();
2447 /* Look up the address in /proc/<pid>/maps */
2448 if ((fp = open_process_map (pid, "r")) == NULL) {
2449 /* No /proc/<pid>/maps, so just return failure
2455 mods = load_modules (fp);
2458 count = g_slist_length (mods);
2460 /* If module != NULL compare the address.
2461 * If module == NULL we are looking for the main module.
2462 * The best we can do for now check it the module name end with the process name.
2464 for (i = 0; i < count; i++) {
2465 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2466 if ( ret == FALSE &&
2467 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2468 (module != NULL && found_module->address_start == module))) {
2469 modinfo->lpBaseOfDll = found_module->address_start;
2470 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2471 modinfo->EntryPoint = found_module->address_offset;
2475 free_procmodule (found_module);
2478 g_slist_free (mods);
2485 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2487 struct _WapiHandle_process *process_handle;
2490 mono_once (&process_current_once, process_set_current);
2492 if(min==NULL || max==NULL) {
2493 /* Not sure if w32 allows NULLs here or not */
2497 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2498 /* This is a pseudo handle, so just fail for now
2503 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2504 (gpointer *)&process_handle);
2506 DEBUG ("%s: Can't find process %p", __func__, process);
2511 *min=process_handle->min_working_set;
2512 *max=process_handle->max_working_set;
2517 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2519 struct _WapiHandle_process *process_handle;
2522 mono_once (&process_current_once, process_set_current);
2524 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2525 /* This is a pseudo handle, so just fail for now
2530 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2531 (gpointer *)&process_handle);
2533 DEBUG ("%s: Can't find process %p", __func__, process);
2538 process_handle->min_working_set=min;
2539 process_handle->max_working_set=max;
2546 TerminateProcess (gpointer process, gint32 exitCode)
2548 struct _WapiHandle_process *process_handle;
2554 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2555 /* This is a pseudo handle */
2556 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2558 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2559 (gpointer *) &process_handle);
2562 DEBUG ("%s: Can't find process %p", __func__,
2564 SetLastError (ERROR_INVALID_HANDLE);
2567 pid = process_handle->id;
2570 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2571 ret = kill (pid, signo);
2575 SetLastError (ERROR_INVALID_PARAMETER);
2578 SetLastError (ERROR_ACCESS_DENIED);
2581 SetLastError (ERROR_PROC_NOT_FOUND);
2584 SetLastError (ERROR_GEN_FAILURE);
2592 GetPriorityClass (gpointer process)
2594 #ifdef HAVE_GETPRIORITY
2595 struct _WapiHandle_process *process_handle;
2600 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2601 /* This is a pseudo handle */
2602 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2604 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2605 (gpointer *) &process_handle);
2608 SetLastError (ERROR_INVALID_HANDLE);
2611 pid = process_handle->id;
2615 ret = getpriority (PRIO_PROCESS, pid);
2616 if (ret == -1 && errno != 0) {
2620 SetLastError (ERROR_ACCESS_DENIED);
2623 SetLastError (ERROR_PROC_NOT_FOUND);
2626 SetLastError (ERROR_GEN_FAILURE);
2632 return NORMAL_PRIORITY_CLASS;
2634 return REALTIME_PRIORITY_CLASS;
2636 return HIGH_PRIORITY_CLASS;
2638 return ABOVE_NORMAL_PRIORITY_CLASS;
2640 return IDLE_PRIORITY_CLASS;
2642 return BELOW_NORMAL_PRIORITY_CLASS;
2644 return NORMAL_PRIORITY_CLASS;
2646 SetLastError (ERROR_NOT_SUPPORTED);
2652 SetPriorityClass (gpointer process, guint32 priority_class)
2654 #ifdef HAVE_SETPRIORITY
2655 struct _WapiHandle_process *process_handle;
2661 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2662 /* This is a pseudo handle */
2663 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2665 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2666 (gpointer *) &process_handle);
2669 SetLastError (ERROR_INVALID_HANDLE);
2672 pid = process_handle->id;
2675 switch (priority_class) {
2676 case IDLE_PRIORITY_CLASS:
2679 case BELOW_NORMAL_PRIORITY_CLASS:
2682 case NORMAL_PRIORITY_CLASS:
2685 case ABOVE_NORMAL_PRIORITY_CLASS:
2688 case HIGH_PRIORITY_CLASS:
2691 case REALTIME_PRIORITY_CLASS:
2695 SetLastError (ERROR_INVALID_PARAMETER);
2699 ret = setpriority (PRIO_PROCESS, pid, prio);
2704 SetLastError (ERROR_ACCESS_DENIED);
2707 SetLastError (ERROR_PROC_NOT_FOUND);
2710 SetLastError (ERROR_GEN_FAILURE);
2716 SetLastError (ERROR_NOT_SUPPORTED);
2722 mono_processes_cleanup (void)
2724 struct MonoProcess *mp;
2725 struct MonoProcess *prev = NULL;
2726 struct MonoProcess *candidate = NULL;
2727 gpointer unref_handle;
2730 DEBUG ("%s", __func__);
2732 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2733 if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
2736 mp = mono_processes;
2737 while (mp != NULL) {
2738 if (mp->pid == 0 && mp->handle != NULL) {
2739 /* This process has exited and we need to remove the artifical ref
2741 mono_mutex_lock (&mono_processes_mutex);
2742 unref_handle = mp->handle;
2744 mono_mutex_unlock (&mono_processes_mutex);
2746 _wapi_handle_unref (unref_handle);
2752 mp = mono_processes;
2754 while (mp != NULL) {
2755 if ((mp->handle_count == 0 && mp->pid == 0) || candidate != NULL) {
2757 _wapi_handle_spin (spin);
2761 /* We've found a candidate */
2762 mono_mutex_lock (&mono_processes_mutex);
2763 if (candidate == NULL) {
2765 if (mp == mono_processes) {
2766 mono_processes = mp->next;
2768 prev->next = mp->next;
2773 /* It's still safe to traverse the structure.*/
2774 mono_memory_barrier ();
2776 if (mono_processes_read_lock != 0) {
2777 /* The sigchld handler is watching us. Spin a bit and try again */
2780 } else if (spin >= 8) {
2781 /* Just give up for now */
2782 mono_mutex_unlock (&mono_processes_mutex);
2786 /* We've modified the list of processes, and we know the sigchld handler
2787 * isn't executing, so even if it executes at any moment, it'll see the
2788 * new version of the list. So now we can free the candidate. */
2789 DEBUG ("%s: freeing candidate %p", __func__, candidate);
2790 mp = candidate->next;
2791 MONO_SEM_DESTROY (&candidate->exit_sem);
2796 mono_mutex_unlock (&mono_processes_mutex);
2805 DEBUG ("%s done", __func__);
2807 InterlockedDecrement (&mono_processes_cleaning_up);
2811 process_close (gpointer handle, gpointer data)
2813 struct _WapiHandle_process *process_handle;
2815 DEBUG ("%s", __func__);
2817 process_handle = (struct _WapiHandle_process *) data;
2818 if (process_handle->mono_process && process_handle->self == _wapi_getpid ())
2819 InterlockedDecrement (&process_handle->mono_process->handle_count);
2820 mono_processes_cleanup ();
2825 mono_sigchld_signal_handler (int _dummy, siginfo_t *info, void *context)
2829 struct MonoProcess *p;
2832 fprintf (stdout, "SIG CHILD handler for pid: %i\n", info->si_pid);
2835 InterlockedIncrement (&mono_processes_read_lock);
2839 pid = waitpid (-1, &status, WNOHANG);
2840 } while (pid == -1 && errno == EINTR);
2846 fprintf (stdout, "child ended: %i", pid);
2850 if (p->pid == pid) {
2851 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2853 MONO_SEM_POST (&p->exit_sem);
2860 InterlockedDecrement (&mono_processes_read_lock);
2863 fprintf (stdout, "SIG CHILD handler: done looping.");
2868 static void process_add_sigchld_handler (void)
2871 struct sigaction sa;
2873 sa.sa_sigaction = mono_sigchld_signal_handler;
2874 sigemptyset (&sa.sa_mask);
2875 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2876 g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2877 DEBUG ("Added SIGCHLD handler");
2881 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2883 struct _WapiHandle_process *process_handle;
2889 struct MonoProcess *mp;
2891 gpointer current_thread;
2893 current_thread = _wapi_thread_handle_from_id (pthread_self ());
2894 if (current_thread == NULL) {
2895 SetLastError (ERROR_INVALID_HANDLE);
2899 /* FIXME: We can now easily wait on processes that aren't our own children,
2900 * but WaitFor*Object won't call us for pseudo handles. */
2901 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2903 DEBUG ("%s (%p, %u)", __func__, handle, timeout);
2905 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS, (gpointer *)&process_handle);
2907 g_warning ("%s: error looking up process handle %p", __func__, handle);
2911 if (process_handle->exited) {
2912 /* We've already done this one */
2913 DEBUG ("%s (%p, %u): Process already exited", __func__, handle, timeout);
2914 return WAIT_OBJECT_0;
2917 pid = process_handle->id;
2919 DEBUG ("%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2921 /* We don't need to lock mono_processes here, the entry
2922 * has a handle_count > 0 which means it will not be freed. */
2923 mp = process_handle->mono_process;
2924 if (mp && process_handle->self != _wapi_getpid ()) {
2925 /* mono_process points to memory in another process' address space: we can't use it */
2929 start = mono_msec_ticks ();
2935 /* We have a semaphore we can wait on */
2936 if (timeout != INFINITE) {
2937 DEBUG ("%s (%p, %u): waiting on semaphore for %li ms...",
2938 __func__, handle, timeout, (timeout - (now - start)));
2940 ret = MONO_SEM_TIMEDWAIT_ALERTABLE (&mp->exit_sem, (timeout - (now - start)), alertable);
2942 DEBUG ("%s (%p, %u): waiting on semaphore forever...",
2943 __func__, handle, timeout);
2944 ret = MONO_SEM_WAIT_ALERTABLE (&mp->exit_sem, alertable);
2947 if (ret == -1 && errno != EINTR && errno != ETIMEDOUT) {
2948 DEBUG ("%s (%p, %u): sem_timedwait failure: %s",
2949 __func__, handle, timeout, g_strerror (errno));
2950 /* Should we return a failure here? */
2954 /* Success, process has exited */
2955 MONO_SEM_POST (&mp->exit_sem);
2959 /* We did not create this process, so we can't waidpid / sem_wait it.
2960 * We need to poll for the pid existence */
2961 DEBUG ("%s (%p, %u): polling on pid...", __func__, handle, timeout);
2962 if (!is_pid_valid (pid)) {
2963 /* Success, process has exited */
2969 DEBUG ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
2970 return WAIT_TIMEOUT;
2973 now = mono_msec_ticks ();
2974 if (now - start >= timeout) {
2975 DEBUG ("%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
2976 return WAIT_TIMEOUT;
2980 /* "timeout - (now - start)" will not underflow, since timeout is always >=0,
2981 * and we passed the check just above */
2982 _wapi_handle_spin (MIN (100, timeout - (now - start)));
2985 if (alertable && _wapi_thread_apc_pending (current_thread)) {
2986 DEBUG ("%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
2987 return WAIT_IO_COMPLETION;
2991 /* Process must have exited */
2992 DEBUG ("%s (%p, %u): Waited successfully", __func__, handle, timeout);
2994 ret = _wapi_handle_lock_shared_handles ();
2995 g_assert (ret == 0);
2997 status = mp ? mp->status : 0;
2998 if (WIFSIGNALED (status)) {
2999 process_handle->exitstatus = 128 + WTERMSIG (status);
3001 process_handle->exitstatus = WEXITSTATUS (status);
3003 _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
3005 process_handle->exited = TRUE;
3007 DEBUG ("%s (%p, %u): Setting pid %d signalled, exit status %d",
3008 __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
3010 _wapi_shared_handle_set_signal_state (handle, TRUE);
3012 _wapi_handle_unlock_shared_handles ();
3014 return WAIT_OBJECT_0;