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/mono-mutex.h>
72 #include <mono/io-layer/process-private.h>
73 #include <mono/io-layer/threads.h>
74 #include <mono/utils/strenc.h>
75 #include <mono/utils/mono-path.h>
76 #include <mono/io-layer/timefuncs-private.h>
77 #include <mono/utils/mono-time.h>
78 #include <mono/utils/mono-membar.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 SetLastError (ERROR_INVALID_DATA);
386 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
387 sei->hProcess = process_info.hProcess;
389 CloseHandle (process_info.hProcess);
396 is_managed_binary (const gchar *filename)
398 int original_errno = errno;
399 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
400 int file = open (filename, O_RDONLY | O_LARGEFILE);
402 int file = open (filename, O_RDONLY);
405 unsigned char buffer[8];
406 off_t file_size, optional_header_offset;
407 off_t pe_header_offset;
408 gboolean managed = FALSE;
410 guint32 first_word, second_word;
412 /* If we are unable to open the file, then we definitely
413 * can't say that it is managed. The child mono process
414 * probably wouldn't be able to open it anyway.
417 errno = original_errno;
421 /* Retrieve the length of the file for future sanity checks. */
422 file_size = lseek (file, 0, SEEK_END);
423 lseek (file, 0, SEEK_SET);
425 /* We know we need to read a header field at offset 60. */
429 num_read = read (file, buffer, 2);
431 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
434 new_offset = lseek (file, 60, SEEK_SET);
436 if (new_offset != 60)
439 num_read = read (file, buffer, 4);
443 pe_header_offset = buffer[0]
448 if (pe_header_offset + 24 > file_size)
451 new_offset = lseek (file, pe_header_offset, SEEK_SET);
453 if (new_offset != pe_header_offset)
456 num_read = read (file, buffer, 4);
458 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
462 * Verify that the header we want in the optional header data
463 * is present in this binary.
465 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
467 if (new_offset != pe_header_offset + 20)
470 num_read = read (file, buffer, 2);
472 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
475 /* Read the CLR header address and size fields. These will be
476 * zero if the binary is not managed.
478 optional_header_offset = pe_header_offset + 24;
479 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
481 if (new_offset != optional_header_offset + 208)
484 num_read = read (file, buffer, 8);
486 /* We are not concerned with endianness, only with
487 * whether it is zero or not.
489 first_word = *(guint32 *)&buffer[0];
490 second_word = *(guint32 *)&buffer[4];
492 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
499 errno = original_errno;
503 gboolean CreateProcessWithLogonW (const gunichar2 *username,
504 const gunichar2 *domain,
505 const gunichar2 *password,
506 const guint32 logonFlags,
507 const gunichar2 *appname,
508 const gunichar2 *cmdline,
509 guint32 create_flags,
511 const gunichar2 *cwd,
512 WapiStartupInfo *startup,
513 WapiProcessInformation *process_info)
515 /* FIXME: use user information */
516 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
520 is_executable (const char *prog)
523 if (access (prog, X_OK) != 0)
525 if (stat (prog, &buf))
527 if (S_ISREG (buf.st_mode))
533 switchDirectorySeparators(gchar *path)
535 size_t i, pathLength = strlen(path);
537 /* Turn all the slashes round the right way, except for \' */
538 /* There are probably other characters that need to be excluded as well. */
539 for (i = 0; i < pathLength; i++)
541 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' ) {
547 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
548 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
549 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
550 gboolean inherit_handles, guint32 create_flags,
551 gpointer new_environ, const gunichar2 *cwd,
552 WapiStartupInfo *startup,
553 WapiProcessInformation *process_info)
555 gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
556 guint32 i, env_count = 0;
557 gboolean ret = FALSE;
559 struct _WapiHandle_process process_handle = {0}, *process_handle_data;
561 int in_fd, out_fd, err_fd;
564 int startup_pipe [2] = {-1, -1};
566 struct MonoProcess *mono_process;
568 mono_once (&process_ops_once, process_ops_init);
569 mono_once (&process_sig_chld_once, process_add_sigchld_handler);
571 /* appname and cmdline specify the executable and its args:
573 * If appname is not NULL, it is the name of the executable.
574 * Otherwise the executable is the first token in cmdline.
576 * Executable searching:
578 * If appname is not NULL, it can specify the full path and
579 * file name, or else a partial name and the current directory
580 * will be used. There is no additional searching.
582 * If appname is NULL, the first whitespace-delimited token in
583 * cmdline is used. If the name does not contain a full
584 * directory path, the search sequence is:
586 * 1) The directory containing the current process
587 * 2) The current working directory
588 * 3) The windows system directory (Ignored)
589 * 4) The windows directory (Ignored)
592 * Just to make things more interesting, tokens can contain
593 * white space if they are surrounded by quotation marks. I'm
594 * beginning to understand just why windows apps are generally
595 * so crap, with an API like this :-(
597 if (appname != NULL) {
598 cmd = mono_unicode_to_external (appname);
600 DEBUG ("%s: unicode conversion returned NULL",
603 SetLastError (ERROR_PATH_NOT_FOUND);
607 switchDirectorySeparators(cmd);
610 if (cmdline != NULL) {
611 args = mono_unicode_to_external (cmdline);
613 DEBUG ("%s: unicode conversion returned NULL", __func__);
615 SetLastError (ERROR_PATH_NOT_FOUND);
621 dir = mono_unicode_to_external (cwd);
623 DEBUG ("%s: unicode conversion returned NULL", __func__);
625 SetLastError (ERROR_PATH_NOT_FOUND);
629 /* Turn all the slashes round the right way */
630 switchDirectorySeparators(dir);
634 /* We can't put off locating the executable any longer :-( */
637 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
638 /* Strip off the drive letter. I can't
639 * believe that CP/M holdover is still
642 g_memmove (cmd, cmd+2, strlen (cmd)-2);
643 cmd[strlen (cmd)-2] = '\0';
646 unquoted = g_shell_unquote (cmd, NULL);
647 if (unquoted[0] == '/') {
648 /* Assume full path given */
649 prog = g_strdup (unquoted);
651 /* Executable existing ? */
652 if (!is_executable (prog)) {
653 DEBUG ("%s: Couldn't find executable %s",
656 SetLastError (ERROR_FILE_NOT_FOUND);
660 /* Search for file named by cmd in the current
663 char *curdir = g_get_current_dir ();
665 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
668 /* And make sure it's executable */
669 if (!is_executable (prog)) {
670 DEBUG ("%s: Couldn't find executable %s",
673 SetLastError (ERROR_FILE_NOT_FOUND);
679 args_after_prog = args;
684 /* Dig out the first token from args, taking quotation
688 /* First, strip off all leading whitespace */
689 args = g_strchug (args);
691 /* args_after_prog points to the contents of args
692 * after token has been set (otherwise argv[0] is
695 args_after_prog = args;
697 /* Assume the opening quote will always be the first
700 if (args[0] == '\"' || args [0] == '\'') {
702 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
703 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
704 /* We found the first token */
705 token = g_strndup (args+1, i-1);
706 args_after_prog = g_strchug (args + i + 1);
708 /* Quotation mark appeared in the
709 * middle of the token. Just give the
710 * whole first token, quotes and all,
717 /* No quote mark, or malformed */
718 for (i = 0; args[i] != '\0'; i++) {
719 if (g_ascii_isspace (args[i])) {
720 token = g_strndup (args, i);
721 args_after_prog = args + i + 1;
727 if (token == NULL && args[0] != '\0') {
728 /* Must be just one token in the string */
729 token = g_strdup (args);
730 args_after_prog = NULL;
735 DEBUG ("%s: Couldn't find what to exec", __func__);
737 SetLastError (ERROR_PATH_NOT_FOUND);
741 /* Turn all the slashes round the right way. Only for
744 switchDirectorySeparators(token);
746 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
747 /* Strip off the drive letter. I can't
748 * believe that CP/M holdover is still
751 g_memmove (token, token+2, strlen (token)-2);
752 token[strlen (token)-2] = '\0';
755 if (token[0] == '/') {
756 /* Assume full path given */
757 prog = g_strdup (token);
759 /* Executable existing ? */
760 if (!is_executable (prog)) {
761 DEBUG ("%s: Couldn't find executable %s",
764 SetLastError (ERROR_FILE_NOT_FOUND);
769 char *curdir = g_get_current_dir ();
771 /* FIXME: Need to record the directory
772 * containing the current process, and check
773 * that for the new executable as the first
777 prog = g_strdup_printf ("%s/%s", curdir, token);
780 /* I assume X_OK is the criterion to use,
783 if (!is_executable (prog)) {
785 prog = g_find_program_in_path (token);
787 DEBUG ("%s: Couldn't find executable %s", __func__, token);
790 SetLastError (ERROR_FILE_NOT_FOUND);
799 DEBUG ("%s: Exec prog [%s] args [%s]", __func__, prog,
802 /* Check for CLR binaries; if found, we will try to invoke
803 * them using the same mono binary that started us.
805 if (is_managed_binary (prog)) {
806 gunichar2 *newapp, *newcmd;
809 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
811 if (newapp != NULL) {
812 if (appname != NULL) {
813 newcmd = utf16_concat (newapp, utf16_space,
814 appname, utf16_space,
817 newcmd = utf16_concat (newapp, utf16_space,
821 g_free ((gunichar2 *)newapp);
823 if (newcmd != NULL) {
824 ret = CreateProcess (NULL, newcmd,
828 create_flags, new_environ,
832 g_free ((gunichar2 *)newcmd);
839 if (args_after_prog != NULL && *args_after_prog) {
842 qprog = g_shell_quote (prog);
843 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
846 full_prog = g_shell_quote (prog);
849 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
851 g_message ("CreateProcess: %s\n", gerr->message);
857 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
858 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
859 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
860 err_fd = GPOINTER_TO_UINT (startup->hStdError);
862 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
863 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
864 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
867 g_strlcpy (process_handle.proc_name, prog,
868 _WAPI_PROC_NAME_MAX_LEN - 1);
870 process_set_defaults (&process_handle);
872 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
873 if (handle == _WAPI_HANDLE_INVALID) {
874 g_warning ("%s: error creating process handle", __func__);
877 SetLastError (ERROR_OUTOFMEMORY);
881 /* new_environ is a block of NULL-terminated strings, which
882 * is itself NULL-terminated. Of course, passing an array of
883 * string pointers would have made things too easy :-(
885 * If new_environ is not NULL it specifies the entire set of
886 * environment variables in the new process. Otherwise the
887 * new process inherits the same environment.
889 if (new_environ != NULL) {
890 gunichar2 *new_environp;
892 /* Count the number of strings */
893 for (new_environp = (gunichar2 *)new_environ; *new_environp;
896 while (*new_environp) {
901 /* +2: one for the process handle value, and the last
904 env_strings = g_new0 (gchar *, env_count + 2);
906 /* Copy each environ string into 'strings' turning it
907 * into utf8 (or the requested encoding) at the same
911 for (new_environp = (gunichar2 *)new_environ; *new_environp;
913 env_strings[env_count] = mono_unicode_to_external (new_environp);
915 while (*new_environp) {
920 for (i = 0; environ[i] != NULL; i++) {
924 /* +2: one for the process handle value, and the last
927 env_strings = g_new0 (gchar *, env_count + 2);
929 /* Copy each environ string into 'strings' turning it
930 * into utf8 (or the requested encoding) at the same
934 for (i = 0; environ[i] != NULL; i++) {
935 env_strings[env_count] = g_strdup (environ[i]);
939 /* pass process handle info to the child, so it doesn't have
940 * to do an expensive search over the whole list
942 if (env_strings != NULL) {
943 struct _WapiHandleUnshared *handle_data;
944 struct _WapiHandle_shared_ref *ref;
946 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
947 ref = &handle_data->u.shared;
949 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
952 /* Create a pipe to make sure the child doesn't exit before
953 * we can add the process to the linked list of mono_processes */
954 if (pipe (startup_pipe) == -1) {
955 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
956 * This is just for a very hard to hit race condition in the first place */
957 startup_pipe [0] = startup_pipe [1] = -1;
958 DEBUG ("%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
961 thr_ret = _wapi_handle_lock_shared_handles ();
962 g_assert (thr_ret == 0);
967 SetLastError (ERROR_OUTOFMEMORY);
968 _wapi_handle_unref (handle);
970 } else if (pid == 0) {
973 if (startup_pipe [0] != -1) {
974 /* Wait until the parent has updated it's internal data */
975 read (startup_pipe [0], &dummy, 1);
976 DEBUG ("%s: child: parent has completed its setup", __func__);
977 close (startup_pipe [0]);
978 close (startup_pipe [1]);
981 /* should we detach from the process group? */
983 /* Connect stdin, stdout and stderr */
988 if (inherit_handles != TRUE) {
989 /* FIXME: do something here */
992 /* Close all file descriptors */
993 for (i = getdtablesize () - 1; i > 2; i--) {
998 DEBUG ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1000 for (i = 0; argv[i] != NULL; i++) {
1001 g_message ("arg %d: [%s]", i, argv[i]);
1004 for (i = 0; env_strings[i] != NULL; i++) {
1005 g_message ("env %d: [%s]", i, env_strings[i]);
1010 if (dir != NULL && chdir (dir) == -1) {
1016 execve (argv[0], argv, env_strings);
1023 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1024 (gpointer *)&process_handle_data);
1026 g_warning ("%s: error looking up process handle %p", __func__,
1028 _wapi_handle_unref (handle);
1032 process_handle_data->id = pid;
1034 /* Add our mono_process into the linked list of mono_processes */
1035 mono_process = (struct MonoProcess *) g_malloc0 (sizeof (struct MonoProcess));
1036 mono_process->pid = pid;
1037 mono_process->handle_count = 1;
1038 if (MONO_SEM_INIT (&mono_process->exit_sem, 0) != 0) {
1039 /* If we can't create the exit semaphore, we just don't add anything
1040 * to our list of mono processes. Waiting on the process will return
1042 g_warning ("%s: could not create exit semaphore for process.", strerror (errno));
1043 g_free (mono_process);
1045 /* Keep the process handle artificially alive until the process
1046 * exits so that the information in the handle isn't lost. */
1047 _wapi_handle_ref (handle);
1048 mono_process->handle = handle;
1050 process_handle_data->self = _wapi_getpid ();
1051 process_handle_data->mono_process = mono_process;
1053 mono_mutex_lock (&mono_processes_mutex);
1054 mono_process->next = mono_processes;
1055 mono_processes = mono_process;
1056 mono_mutex_unlock (&mono_processes_mutex);
1059 if (process_info != NULL) {
1060 process_info->hProcess = handle;
1061 process_info->dwProcessId = pid;
1063 /* FIXME: we might need to handle the thread info some
1066 process_info->hThread = INVALID_HANDLE_VALUE;
1067 process_info->dwThreadId = 0;
1071 _wapi_handle_unlock_shared_handles ();
1073 if (startup_pipe [1] != -1) {
1074 /* Write 1 byte, doesn't matter what */
1075 write (startup_pipe [1], startup_pipe, 1);
1076 close (startup_pipe [0]);
1077 close (startup_pipe [1]);
1084 if (full_prog != NULL) {
1096 if(env_strings != NULL) {
1097 g_strfreev (env_strings);
1103 DEBUG ("%s: returning handle %p for pid %d", __func__, handle,
1106 /* Check if something needs to be cleaned up. */
1107 mono_processes_cleanup ();
1112 static void process_set_name (struct _WapiHandle_process *process_handle)
1114 gchar *progname, *utf8_progname, *slash;
1116 progname=g_get_prgname ();
1117 utf8_progname=mono_utf8_from_external (progname);
1119 DEBUG ("%s: using [%s] as prog name", __func__, progname);
1121 if(utf8_progname!=NULL) {
1122 slash=strrchr (utf8_progname, '/');
1124 g_strlcpy (process_handle->proc_name, slash+1,
1125 _WAPI_PROC_NAME_MAX_LEN - 1);
1127 g_strlcpy (process_handle->proc_name, utf8_progname,
1128 _WAPI_PROC_NAME_MAX_LEN - 1);
1131 g_free (utf8_progname);
1135 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
1137 #if !GLIB_CHECK_VERSION (2,4,0)
1138 #define g_setenv(a,b,c) setenv(a,b,c)
1139 #define g_unsetenv(a) unsetenv(a)
1142 static void process_set_current (void)
1144 pid_t pid = _wapi_getpid ();
1145 const char *handle_env;
1146 struct _WapiHandle_process process_handle = {0};
1148 mono_once (&process_ops_once, process_ops_init);
1150 handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1151 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1153 if (handle_env != NULL) {
1154 struct _WapiHandle_process *process_handlep;
1155 gchar *procname = NULL;
1158 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
1160 DEBUG ("%s: Found my process handle: %p (offset %d 0x%x)",
1161 __func__, current_process, atoi (handle_env),
1164 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
1165 (gpointer *)&process_handlep);
1167 /* This test will probably break on linuxthreads, but
1168 * that should be ancient history on all distros we
1171 if (process_handlep->id == pid) {
1172 procname = process_handlep->proc_name;
1173 if (!strcmp (procname, "mono")) {
1174 /* Set a better process name */
1175 DEBUG ("%s: Setting better process name", __func__);
1177 process_set_name (process_handlep);
1179 DEBUG ("%s: Leaving process name: %s", __func__, procname);
1185 /* Wrong pid, so drop this handle and fall through to
1188 _wapi_handle_unref (current_process);
1192 /* We get here if the handle wasn't specified in the
1193 * environment, or if the process ID was wrong, or if the
1194 * handle lookup failed (eg if the parent process forked and
1195 * quit immediately, and deleted the shared data before the
1196 * child got a chance to attach it.)
1199 DEBUG ("%s: Need to create my own process handle", __func__);
1201 process_handle.id = pid;
1203 process_set_defaults (&process_handle);
1204 process_set_name (&process_handle);
1206 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1208 if (current_process == _WAPI_HANDLE_INVALID) {
1209 g_warning ("%s: error creating process handle", __func__);
1214 gpointer _wapi_process_duplicate ()
1216 mono_once (&process_current_once, process_set_current);
1218 _wapi_handle_ref (current_process);
1220 return(current_process);
1223 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1224 gpointer GetCurrentProcess (void)
1226 mono_once (&process_current_once, process_set_current);
1228 return(_WAPI_PROCESS_CURRENT);
1231 guint32 GetProcessId (gpointer handle)
1233 struct _WapiHandle_process *process_handle;
1236 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1237 /* This is a pseudo handle */
1238 return(GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
1241 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1242 (gpointer *)&process_handle);
1244 SetLastError (ERROR_INVALID_HANDLE);
1248 return (process_handle->id);
1251 guint32 GetCurrentProcessId (void)
1253 mono_once (&process_current_once, process_set_current);
1255 return (GetProcessId (current_process));
1258 /* Returns the process id as a convenience to the functions that call this */
1259 static pid_t signal_process_if_gone (gpointer handle)
1261 struct _WapiHandle_process *process_handle;
1264 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
1266 /* Make sure the process is signalled if it has exited - if
1267 * the parent process didn't wait for it then it won't be
1269 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1270 (gpointer *)&process_handle);
1272 /* It's possible that the handle has vanished during
1273 * the _wapi_search_handle before it gets here, so
1274 * don't spam the console with warnings.
1276 /* g_warning ("%s: error looking up process handle %p",
1277 __func__, handle);*/
1282 DEBUG ("%s: looking at process %d", __func__, process_handle->id);
1284 if (kill (process_handle->id, 0) == -1 &&
1287 /* The process is dead, (EPERM tells us a new process
1288 * has that ID, but as it's owned by someone else it
1289 * can't be the one listed in our shared memory file)
1291 _wapi_shared_handle_set_signal_state (handle, TRUE);
1294 return (process_handle->id);
1298 static gboolean process_enum (gpointer handle, gpointer user_data)
1300 GArray *processes=user_data;
1301 pid_t pid = signal_process_if_gone (handle);
1308 /* Ignore processes that have already exited (ie they are signalled) */
1309 if (_wapi_handle_issignalled (handle) == FALSE) {
1310 DEBUG ("%s: process %d added to array", __func__, pid);
1312 /* This ensures that duplicates aren't returned (see
1313 * the comment above _wapi_search_handle () for why
1316 for (i = 0; i < processes->len; i++) {
1317 if (g_array_index (processes, pid_t, i) == pid) {
1318 /* We've already got this one, return
1319 * FALSE to keep searching
1325 g_array_append_val (processes, pid);
1328 /* Return false to keep searching */
1331 #endif /* UNUSED_CODE */
1333 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
1335 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1337 guint32 count, fit, i, j;
1340 size_t proclength, size;
1341 #if defined(__OpenBSD__)
1342 struct kinfo_proc2 *result;
1345 name[1] = KERN_PROC2;
1346 name[2] = KERN_PROC_ALL;
1348 name[4] = sizeof(struct kinfo_proc2);
1351 struct kinfo_proc *result;
1352 static const int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
1355 mono_once (&process_current_once, process_set_current);
1362 #if defined(__OpenBSD__)
1363 size = (sizeof(name) / sizeof(*name));
1365 size = (sizeof(name) / sizeof(*name)) - 1;
1367 err = sysctl ((int *)name, size, NULL, &proclength, NULL, 0);
1370 result = malloc (proclength);
1375 #if defined(__OpenBSD__)
1376 name[5] = (int)(proclength / sizeof(struct kinfo_proc2));
1379 err = sysctl ((int *) name, size, result, &proclength, NULL, 0);
1386 } while (err == 0 && !done);
1389 if (result != NULL) {
1396 #if defined(__OpenBSD__)
1397 count = proclength / sizeof(struct kinfo_proc2);
1399 count = proclength / sizeof(struct kinfo_proc);
1401 fit = len / sizeof(guint32);
1402 for (i = 0, j = 0; j< fit && i < count; i++) {
1403 #if defined(__OpenBSD__)
1404 pids [j++] = result [i].p_pid;
1406 if (result[i].kp_proc.p_pid > 0) /* Pid 0 not supported */
1407 pids [j++] = result [i].kp_proc.p_pid;
1412 *needed = j * sizeof(guint32);
1416 #elif defined(__HAIKU__)
1418 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1424 mono_once (&process_current_once, process_set_current);
1426 fit = len / sizeof (guint32);
1427 while (get_next_team_info (&cookie, &teamInfo) == B_OK && i < fit) {
1428 pids [i++] = teamInfo.team;
1430 *needed = i * sizeof (guint32);
1435 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1439 struct dirent *entry;
1441 mono_once (&process_current_once, process_set_current);
1443 dir = opendir ("/proc");
1449 fit = len / sizeof (guint32);
1450 while(i < fit && (entry = readdir (dir)) != NULL) {
1454 if (!isdigit (entry->d_name[0]))
1457 pid = (pid_t) strtol (entry->d_name, &endptr, 10);
1458 if (*endptr == '\0')
1459 pids [i++] = (guint32) pid;
1462 *needed = i * sizeof(guint32);
1468 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1471 pid_t checking_pid = signal_process_if_gone (handle);
1473 if (checking_pid == 0) {
1477 wanted_pid = GPOINTER_TO_UINT (user_data);
1479 /* It's possible to have more than one process handle with the
1480 * same pid, but only the one running process can be
1483 if (checking_pid == wanted_pid &&
1484 _wapi_handle_issignalled (handle) == FALSE) {
1485 /* If the handle is blown away in the window between
1486 * returning TRUE here and _wapi_search_handle pinging
1487 * the timestamp, the search will continue
1495 gboolean CloseProcess(gpointer handle)
1497 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1498 /* This is a pseudo handle */
1502 return CloseHandle (handle);
1506 * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1508 gpointer OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1510 /* Find the process handle that corresponds to pid */
1511 gpointer handle = NULL;
1513 mono_once (&process_current_once, process_set_current);
1515 DEBUG ("%s: looking for process %d", __func__, pid);
1517 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1518 process_open_compare,
1519 GUINT_TO_POINTER (pid), NULL, TRUE);
1521 if (is_pid_valid (pid)) {
1522 /* Return a pseudo handle for processes we
1523 * don't have handles for
1525 return GINT_TO_POINTER (_WAPI_PROCESS_UNHANDLED + pid);
1527 DEBUG ("%s: Can't find pid %d", __func__, pid);
1529 SetLastError (ERROR_PROC_NOT_FOUND);
1535 /* _wapi_search_handle () already added a ref */
1539 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1541 struct _WapiHandle_process *process_handle;
1545 mono_once (&process_current_once, process_set_current);
1551 pid = GPOINTER_TO_UINT (process) - _WAPI_PROCESS_UNHANDLED;
1552 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1553 /* This is a pseudo handle, so we don't know what the
1554 * exit code was, but we can check whether it's alive or not
1556 if (is_pid_valid (pid)) {
1557 *code = STILL_ACTIVE;
1564 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1565 (gpointer *)&process_handle);
1567 DEBUG ("%s: Can't find process %p", __func__, process);
1572 /* A process handle is only signalled if the process has exited
1573 * and has been waited for */
1575 /* Make sure any process exit has been noticed, before
1576 * checking if the process is signalled. Fixes bug 325463.
1578 process_wait (process, 0, TRUE);
1580 if (_wapi_handle_issignalled (process) == TRUE) {
1581 *code = process_handle->exitstatus;
1583 *code = STILL_ACTIVE;
1589 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1590 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1591 WapiFileTime *user_time)
1593 struct _WapiHandle_process *process_handle;
1595 gboolean ku_times_set = FALSE;
1597 mono_once (&process_current_once, process_set_current);
1599 if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1601 /* Not sure if w32 allows NULLs here or not */
1605 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1606 /* This is a pseudo handle, so just fail for now
1611 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1612 (gpointer *)&process_handle);
1614 DEBUG ("%s: Can't find process %p", __func__, process);
1619 *create_time=process_handle->create_time;
1621 /* A process handle is only signalled if the process has
1622 * exited. Otherwise exit_time isn't set
1624 if(_wapi_handle_issignalled (process)==TRUE) {
1625 *exit_time=process_handle->exit_time;
1628 #ifdef HAVE_GETRUSAGE
1629 if (process_handle->id == getpid ()) {
1630 struct rusage time_data;
1631 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1633 gint64 *tick_val_ptr;
1634 ku_times_set = TRUE;
1635 tick_val = time_data.ru_utime.tv_sec * 10000000 + time_data.ru_utime.tv_usec * 10;
1636 tick_val_ptr = (gint64*)user_time;
1637 *tick_val_ptr = tick_val;
1638 tick_val = time_data.ru_stime.tv_sec * 10000000 + time_data.ru_stime.tv_usec * 10;
1639 tick_val_ptr = (gint64*)kernel_time;
1640 *tick_val_ptr = tick_val;
1644 if (!ku_times_set) {
1645 memset (kernel_time, 0, sizeof (WapiFileTime));
1646 memset (user_time, 0, sizeof (WapiFileTime));
1654 gpointer address_start;
1655 gpointer address_end;
1657 gpointer address_offset;
1663 static void free_procmodule (WapiProcModule *mod)
1665 if (mod->perms != NULL) {
1666 g_free (mod->perms);
1668 if (mod->filename != NULL) {
1669 g_free (mod->filename);
1674 static gint find_procmodule (gconstpointer a, gconstpointer b)
1676 WapiProcModule *want = (WapiProcModule *)a;
1677 WapiProcModule *compare = (WapiProcModule *)b;
1679 if ((want->device == compare->device) &&
1680 (want->inode == compare->inode)) {
1687 #ifdef PLATFORM_MACOSX
1688 #include <mach-o/dyld.h>
1689 #include <mach-o/getsect.h>
1691 static GSList *load_modules (void)
1694 WapiProcModule *mod;
1695 uint32_t count = _dyld_image_count ();
1698 for (i = 0; i < count; i++) {
1699 #if SIZEOF_VOID_P == 8
1700 const struct mach_header_64 *hdr;
1701 const struct section_64 *sec;
1703 const struct mach_header *hdr;
1704 const struct section *sec;
1709 slide = _dyld_get_image_vmaddr_slide (i);
1710 name = _dyld_get_image_name (i);
1711 hdr = _dyld_get_image_header (i);
1712 #if SIZEOF_VOID_P == 8
1713 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1715 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1718 /* Some dynlibs do not have data sections on osx (#533893) */
1723 mod = g_new0 (WapiProcModule, 1);
1724 mod->address_start = GINT_TO_POINTER (sec->addr);
1725 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1726 mod->perms = g_strdup ("r--p");
1727 mod->address_offset = 0;
1728 mod->device = makedev (0, 0);
1729 mod->inode = (ino_t) i;
1730 mod->filename = g_strdup (name);
1732 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1733 ret = g_slist_prepend (ret, mod);
1735 free_procmodule (mod);
1739 ret = g_slist_reverse (ret);
1743 #elif defined(__OpenBSD__)
1745 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1747 if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1748 + sizeof (info->dlpi_phnum))
1751 struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1755 memcpy(cpy, info, sizeof(*info));
1757 g_ptr_array_add ((GPtrArray *)ptr, cpy);
1762 static GSList *load_modules (void)
1765 WapiProcModule *mod;
1766 GPtrArray *dlarray = g_ptr_array_new();
1769 if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1772 for (i = 0; i < dlarray->len; i++) {
1773 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1775 mod = g_new0 (WapiProcModule, 1);
1776 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1777 mod->address_end = (gpointer)(info->dlpi_addr +
1778 info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1779 mod->perms = g_strdup ("r--p");
1780 mod->address_offset = 0;
1781 mod->inode = (ino_t) i;
1782 mod->filename = g_strdup (info->dlpi_name);
1784 DEBUG ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1785 mod->inode, mod->filename, mod->address_start, mod->address_end);
1789 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1790 ret = g_slist_prepend (ret, mod);
1792 free_procmodule (mod);
1796 g_ptr_array_free (dlarray, TRUE);
1798 ret = g_slist_reverse (ret);
1802 #elif defined(__HAIKU__)
1804 static GSList *load_modules (void)
1807 WapiProcModule *mod;
1809 image_info imageInfo;
1811 while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
1812 mod = g_new0 (WapiProcModule, 1);
1813 mod->device = imageInfo.device;
1814 mod->inode = imageInfo.node;
1815 mod->filename = g_strdup (imageInfo.name);
1816 mod->address_start = MIN (imageInfo.text, imageInfo.data);
1817 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
1818 (uint8_t*)imageInfo.data + imageInfo.data_size);
1819 mod->perms = g_strdup ("r--p");
1820 mod->address_offset = 0;
1822 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1823 ret = g_slist_prepend (ret, mod);
1825 free_procmodule (mod);
1829 ret = g_slist_reverse (ret);
1834 static GSList *load_modules (FILE *fp)
1837 WapiProcModule *mod;
1838 gchar buf[MAXPATHLEN + 1], *p, *endp;
1839 gchar *start_start, *end_start, *prot_start, *offset_start;
1840 gchar *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1841 gpointer address_start, address_end, address_offset;
1842 guint32 maj_dev, min_dev;
1846 while (fgets (buf, sizeof(buf), fp)) {
1848 while (g_ascii_isspace (*p)) ++p;
1850 if (!g_ascii_isxdigit (*start_start)) {
1853 address_start = (gpointer)strtoul (start_start, &endp, 16);
1861 if (!g_ascii_isxdigit (*end_start)) {
1864 address_end = (gpointer)strtoul (end_start, &endp, 16);
1866 if (!g_ascii_isspace (*p)) {
1870 while (g_ascii_isspace (*p)) ++p;
1872 if (*prot_start != 'r' && *prot_start != '-') {
1875 memcpy (prot_buf, prot_start, 4);
1877 while (!g_ascii_isspace (*p)) ++p;
1879 while (g_ascii_isspace (*p)) ++p;
1881 if (!g_ascii_isxdigit (*offset_start)) {
1884 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1886 if (!g_ascii_isspace (*p)) {
1890 while(g_ascii_isspace (*p)) ++p;
1892 if (!g_ascii_isxdigit (*maj_dev_start)) {
1895 maj_dev = strtoul (maj_dev_start, &endp, 16);
1903 if (!g_ascii_isxdigit (*min_dev_start)) {
1906 min_dev = strtoul (min_dev_start, &endp, 16);
1908 if (!g_ascii_isspace (*p)) {
1912 while (g_ascii_isspace (*p)) ++p;
1914 if (!g_ascii_isxdigit (*inode_start)) {
1917 inode = (ino_t)strtol (inode_start, &endp, 10);
1919 if (!g_ascii_isspace (*p)) {
1923 device = makedev ((int)maj_dev, (int)min_dev);
1924 if ((device == 0) &&
1929 while(g_ascii_isspace (*p)) ++p;
1930 /* p now points to the filename */
1932 mod = g_new0 (WapiProcModule, 1);
1933 mod->address_start = address_start;
1934 mod->address_end = address_end;
1935 mod->perms = g_strdup (prot_buf);
1936 mod->address_offset = address_offset;
1937 mod->device = device;
1939 mod->filename = g_strdup (g_strstrip (p));
1941 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1942 ret = g_slist_prepend (ret, mod);
1944 free_procmodule (mod);
1948 ret = g_slist_reverse (ret);
1954 static gboolean match_procname_to_modulename (gchar *procname, gchar *modulename)
1956 char* lastsep = NULL;
1957 char* lastsep2 = NULL;
1960 gboolean result = FALSE;
1962 if (procname == NULL || modulename == NULL)
1965 pname = mono_path_resolve_symlinks (procname);
1966 mname = mono_path_resolve_symlinks (modulename);
1968 if (!strcmp (pname, mname))
1972 lastsep = strrchr (mname, '/');
1974 if (!strcmp (lastsep+1, pname))
1977 lastsep2 = strrchr (pname, '/');
1980 if (!strcmp (lastsep+1, lastsep2+1))
1983 if (!strcmp (mname, lastsep2+1))
1996 #if !defined(__OpenBSD__)
1998 open_process_map (int pid, const char *mode)
2001 const gchar *proc_path[] = {
2002 "/proc/%d/maps", /* GNU/Linux */
2003 "/proc/%d/map", /* FreeBSD */
2009 for (i = 0; fp == NULL && proc_path [i]; i++) {
2010 filename = g_strdup_printf (proc_path[i], pid);
2011 fp = fopen (filename, mode);
2019 gboolean EnumProcessModules (gpointer process, gpointer *modules,
2020 guint32 size, guint32 *needed)
2022 struct _WapiHandle_process *process_handle;
2024 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2027 GSList *mods = NULL;
2028 WapiProcModule *module;
2029 guint32 count, avail = size / sizeof(gpointer);
2032 gchar *proc_name = NULL;
2034 /* Store modules in an array of pointers (main module as
2035 * modules[0]), using the load address for each module as a
2036 * token. (Use 'NULL' as an alternative for the main module
2037 * so that the simple implementation can just return one item
2038 * for now.) Get the info from /proc/<pid>/maps on linux,
2039 * /proc/<pid>/map on FreeBSD, other systems will have to
2040 * implement /dev/kmem reading or whatever other horrid
2041 * technique is needed.
2043 if (size < sizeof(gpointer)) {
2047 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2048 /* This is a pseudo handle */
2049 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2051 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2052 (gpointer *)&process_handle);
2054 DEBUG ("%s: Can't find process %p", __func__, process);
2058 pid = process_handle->id;
2059 proc_name = process_handle->proc_name;
2062 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2064 mods = load_modules ();
2066 if ((fp = open_process_map (pid, "r")) == NULL) {
2067 /* No /proc/<pid>/maps so just return the main module
2071 *needed = sizeof(gpointer);
2073 mods = load_modules (fp);
2076 count = g_slist_length (mods);
2078 /* count + 1 to leave slot 0 for the main module */
2079 *needed = sizeof(gpointer) * (count + 1);
2081 /* Use the NULL shortcut, as the first line in
2082 * /proc/<pid>/maps isn't the executable, and we need
2083 * that first in the returned list. Check the module name
2084 * to see if it ends with the proc name and substitute
2085 * the first entry with it. FIXME if this turns out to
2089 for (i = 0; i < (avail - 1) && i < count; i++) {
2090 module = (WapiProcModule *)g_slist_nth_data (mods, i);
2091 if (modules[0] != NULL)
2092 modules[i] = module->address_start;
2093 else if (match_procname_to_modulename (proc_name, module->filename))
2094 modules[0] = module->address_start;
2096 modules[i + 1] = module->address_start;
2099 for (i = 0; i < count; i++) {
2100 free_procmodule (g_slist_nth_data (mods, i));
2102 g_slist_free (mods);
2108 static gchar *get_process_name_from_proc (pid_t pid)
2110 #if defined(__OpenBSD__)
2113 struct kinfo_proc2 *pi;
2114 #elif defined(PLATFORM_MACOSX)
2116 struct kinfo_proc *pi;
2117 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
2120 gchar *filename = NULL;
2125 #if defined(PLATFORM_SOLARIS)
2126 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
2127 if ((fp = fopen (filename, "r")) != NULL) {
2131 nread = fread (&info, sizeof (info), 1, fp);
2133 ret = g_strdup (info.pr_fname);
2139 #elif defined(PLATFORM_MACOSX)
2140 #if !defined (__mono_ppc__) && defined (TARGET_OSX)
2141 /* No proc name on OSX < 10.5 nor ppc nor iOS */
2142 memset (buf, '\0', sizeof(buf));
2143 proc_name (pid, buf, sizeof(buf));
2144 if (strlen (buf) > 0)
2145 ret = g_strdup (buf);
2147 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0)
2150 if ((pi = malloc(size)) == NULL)
2153 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
2154 if (errno == ENOMEM) {
2156 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__);
2161 if (strlen (pi->kp_proc.p_comm) > 0)
2162 ret = g_strdup (pi->kp_proc.p_comm);
2166 #elif defined(__OpenBSD__)
2168 mib [1] = KERN_PROC2;
2169 mib [2] = KERN_PROC_PID;
2171 mib [4] = sizeof(struct kinfo_proc2);
2175 if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0)
2178 if ((pi = malloc(size)) == NULL)
2181 mib[5] = (int)(size / sizeof(struct kinfo_proc2));
2183 if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
2184 (size != sizeof (struct kinfo_proc2))) {
2185 if (errno == ENOMEM) {
2192 if (strlen (pi->p_comm) > 0)
2193 ret = g_strdup (pi->p_comm);
2196 #elif defined(__HAIKU__)
2197 image_info imageInfo;
2200 if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
2201 ret = g_strdup (imageInfo.name);
2204 memset (buf, '\0', sizeof(buf));
2205 filename = g_strdup_printf ("/proc/%d/exe", pid);
2206 if (readlink (filename, buf, 255) > 0) {
2207 ret = g_strdup (buf);
2215 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
2216 if ((fp = fopen (filename, "r")) != NULL) {
2217 if (fgets (buf, 256, fp) != NULL) {
2218 ret = g_strdup (buf);
2229 filename = g_strdup_printf ("/proc/%d/stat", pid);
2230 if ((fp = fopen (filename, "r")) != NULL) {
2231 if (fgets (buf, 256, fp) != NULL) {
2234 start = strchr (buf, '(');
2235 if (start != NULL) {
2236 end = strchr (start + 1, ')');
2239 ret = g_strndup (start + 1,
2253 static guint32 get_module_name (gpointer process, gpointer module,
2254 gunichar2 *basename, guint32 size,
2257 struct _WapiHandle_process *process_handle;
2260 gunichar2 *procname;
2261 gchar *procname_ext = NULL;
2264 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2267 GSList *mods = NULL;
2268 WapiProcModule *found_module;
2271 gchar *proc_name = NULL;
2273 mono_once (&process_current_once, process_set_current);
2275 DEBUG ("%s: Getting module base name, process handle %p module %p",
2276 __func__, process, module);
2278 size = size*sizeof(gunichar2); /* adjust for unicode characters */
2280 if (basename == NULL || size == 0) {
2284 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2285 /* This is a pseudo handle */
2286 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2287 proc_name = get_process_name_from_proc (pid);
2289 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2290 (gpointer *)&process_handle);
2292 DEBUG ("%s: Can't find process %p", __func__,
2297 pid = process_handle->id;
2298 proc_name = g_strdup (process_handle->proc_name);
2301 /* Look up the address in /proc/<pid>/maps */
2302 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2304 mods = load_modules ();
2306 if ((fp = open_process_map (pid, "r")) == NULL) {
2307 if (errno == EACCES && module == NULL && base == TRUE) {
2308 procname_ext = get_process_name_from_proc (pid);
2310 /* No /proc/<pid>/maps, so just return failure
2317 mods = load_modules (fp);
2320 count = g_slist_length (mods);
2322 /* If module != NULL compare the address.
2323 * If module == NULL we are looking for the main module.
2324 * The best we can do for now check it the module name end with the process name.
2326 for (i = 0; i < count; i++) {
2327 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2328 if (procname_ext == NULL &&
2329 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2330 (module != NULL && found_module->address_start == module))) {
2332 procname_ext = g_path_get_basename (found_module->filename);
2334 procname_ext = g_strdup (found_module->filename);
2338 free_procmodule (found_module);
2341 if (procname_ext == NULL)
2343 /* If it's *still* null, we might have hit the
2344 * case where reading /proc/$pid/maps gives an
2345 * empty file for this user.
2347 procname_ext = get_process_name_from_proc (pid);
2350 g_slist_free (mods);
2354 if (procname_ext != NULL) {
2355 DEBUG ("%s: Process name is [%s]", __func__,
2358 procname = mono_unicode_from_external (procname_ext, &bytes);
2359 if (procname == NULL) {
2361 g_free (procname_ext);
2367 /* Add the terminator */
2371 DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2373 memcpy (basename, procname, size);
2375 DEBUG ("%s: Size %d larger than needed (%ld)",
2376 __func__, size, bytes);
2378 memcpy (basename, procname, bytes);
2382 g_free (procname_ext);
2390 guint32 GetModuleBaseName (gpointer process, gpointer module,
2391 gunichar2 *basename, guint32 size)
2393 return(get_module_name (process, module, basename, size, TRUE));
2396 guint32 GetModuleFileNameEx (gpointer process, gpointer module,
2397 gunichar2 *filename, guint32 size)
2399 return(get_module_name (process, module, filename, size, FALSE));
2402 gboolean GetModuleInformation (gpointer process, gpointer module,
2403 WapiModuleInfo *modinfo, guint32 size)
2405 struct _WapiHandle_process *process_handle;
2408 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2411 GSList *mods = NULL;
2412 WapiProcModule *found_module;
2415 gboolean ret = FALSE;
2416 gchar *proc_name = NULL;
2418 mono_once (&process_current_once, process_set_current);
2420 DEBUG ("%s: Getting module info, process handle %p module %p",
2421 __func__, process, module);
2423 if (modinfo == NULL || size < sizeof(WapiModuleInfo)) {
2427 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2428 /* This is a pseudo handle */
2429 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2430 proc_name = get_process_name_from_proc (pid);
2432 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2433 (gpointer *)&process_handle);
2435 DEBUG ("%s: Can't find process %p", __func__,
2440 pid = process_handle->id;
2441 proc_name = g_strdup (process_handle->proc_name);
2444 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2446 mods = load_modules ();
2448 /* Look up the address in /proc/<pid>/maps */
2449 if ((fp = open_process_map (pid, "r")) == NULL) {
2450 /* No /proc/<pid>/maps, so just return failure
2456 mods = load_modules (fp);
2459 count = g_slist_length (mods);
2461 /* If module != NULL compare the address.
2462 * If module == NULL we are looking for the main module.
2463 * The best we can do for now check it the module name end with the process name.
2465 for (i = 0; i < count; i++) {
2466 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2467 if ( ret == FALSE &&
2468 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2469 (module != NULL && found_module->address_start == module))) {
2470 modinfo->lpBaseOfDll = found_module->address_start;
2471 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2472 modinfo->EntryPoint = found_module->address_offset;
2476 free_procmodule (found_module);
2479 g_slist_free (mods);
2486 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2488 struct _WapiHandle_process *process_handle;
2491 mono_once (&process_current_once, process_set_current);
2493 if(min==NULL || max==NULL) {
2494 /* Not sure if w32 allows NULLs here or not */
2498 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2499 /* This is a pseudo handle, so just fail for now
2504 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2505 (gpointer *)&process_handle);
2507 DEBUG ("%s: Can't find process %p", __func__, process);
2512 *min=process_handle->min_working_set;
2513 *max=process_handle->max_working_set;
2518 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2520 struct _WapiHandle_process *process_handle;
2523 mono_once (&process_current_once, process_set_current);
2525 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2526 /* This is a pseudo handle, so just fail for now
2531 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2532 (gpointer *)&process_handle);
2534 DEBUG ("%s: Can't find process %p", __func__, process);
2539 process_handle->min_working_set=min;
2540 process_handle->max_working_set=max;
2547 TerminateProcess (gpointer process, gint32 exitCode)
2549 struct _WapiHandle_process *process_handle;
2555 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2556 /* This is a pseudo handle */
2557 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2559 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2560 (gpointer *) &process_handle);
2563 DEBUG ("%s: Can't find process %p", __func__,
2565 SetLastError (ERROR_INVALID_HANDLE);
2568 pid = process_handle->id;
2571 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2572 ret = kill (pid, signo);
2576 SetLastError (ERROR_INVALID_PARAMETER);
2579 SetLastError (ERROR_ACCESS_DENIED);
2582 SetLastError (ERROR_PROC_NOT_FOUND);
2585 SetLastError (ERROR_GEN_FAILURE);
2593 GetPriorityClass (gpointer process)
2595 #ifdef HAVE_GETPRIORITY
2596 struct _WapiHandle_process *process_handle;
2601 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2602 /* This is a pseudo handle */
2603 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2605 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2606 (gpointer *) &process_handle);
2609 SetLastError (ERROR_INVALID_HANDLE);
2612 pid = process_handle->id;
2616 ret = getpriority (PRIO_PROCESS, pid);
2617 if (ret == -1 && errno != 0) {
2621 SetLastError (ERROR_ACCESS_DENIED);
2624 SetLastError (ERROR_PROC_NOT_FOUND);
2627 SetLastError (ERROR_GEN_FAILURE);
2633 return NORMAL_PRIORITY_CLASS;
2635 return REALTIME_PRIORITY_CLASS;
2637 return HIGH_PRIORITY_CLASS;
2639 return ABOVE_NORMAL_PRIORITY_CLASS;
2641 return IDLE_PRIORITY_CLASS;
2643 return BELOW_NORMAL_PRIORITY_CLASS;
2645 return NORMAL_PRIORITY_CLASS;
2647 SetLastError (ERROR_NOT_SUPPORTED);
2653 SetPriorityClass (gpointer process, guint32 priority_class)
2655 #ifdef HAVE_SETPRIORITY
2656 struct _WapiHandle_process *process_handle;
2662 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2663 /* This is a pseudo handle */
2664 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2666 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2667 (gpointer *) &process_handle);
2670 SetLastError (ERROR_INVALID_HANDLE);
2673 pid = process_handle->id;
2676 switch (priority_class) {
2677 case IDLE_PRIORITY_CLASS:
2680 case BELOW_NORMAL_PRIORITY_CLASS:
2683 case NORMAL_PRIORITY_CLASS:
2686 case ABOVE_NORMAL_PRIORITY_CLASS:
2689 case HIGH_PRIORITY_CLASS:
2692 case REALTIME_PRIORITY_CLASS:
2696 SetLastError (ERROR_INVALID_PARAMETER);
2700 ret = setpriority (PRIO_PROCESS, pid, prio);
2705 SetLastError (ERROR_ACCESS_DENIED);
2708 SetLastError (ERROR_PROC_NOT_FOUND);
2711 SetLastError (ERROR_GEN_FAILURE);
2717 SetLastError (ERROR_NOT_SUPPORTED);
2723 mono_processes_cleanup (void)
2725 struct MonoProcess *mp;
2726 struct MonoProcess *prev = NULL;
2727 struct MonoProcess *candidate = NULL;
2728 gpointer unref_handle;
2731 DEBUG ("%s", __func__);
2733 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2734 if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
2737 mp = mono_processes;
2738 while (mp != NULL) {
2739 if (mp->pid == 0 && mp->handle != NULL) {
2740 /* This process has exited and we need to remove the artifical ref
2742 mono_mutex_lock (&mono_processes_mutex);
2743 unref_handle = mp->handle;
2745 mono_mutex_unlock (&mono_processes_mutex);
2747 _wapi_handle_unref (unref_handle);
2753 mp = mono_processes;
2755 while (mp != NULL) {
2756 if ((mp->handle_count == 0 && mp->pid == 0) || candidate != NULL) {
2758 _wapi_handle_spin (spin);
2762 /* We've found a candidate */
2763 mono_mutex_lock (&mono_processes_mutex);
2764 if (candidate == NULL) {
2766 if (mp == mono_processes) {
2767 mono_processes = mp->next;
2769 prev->next = mp->next;
2774 /* It's still safe to traverse the structure.*/
2775 mono_memory_barrier ();
2777 if (mono_processes_read_lock != 0) {
2778 /* The sigchld handler is watching us. Spin a bit and try again */
2781 } else if (spin >= 8) {
2782 /* Just give up for now */
2783 mono_mutex_unlock (&mono_processes_mutex);
2787 /* We've modified the list of processes, and we know the sigchld handler
2788 * isn't executing, so even if it executes at any moment, it'll see the
2789 * new version of the list. So now we can free the candidate. */
2790 DEBUG ("%s: freeing candidate %p", __func__, candidate);
2791 mp = candidate->next;
2792 MONO_SEM_DESTROY (&candidate->exit_sem);
2797 mono_mutex_unlock (&mono_processes_mutex);
2806 DEBUG ("%s done", __func__);
2808 InterlockedDecrement (&mono_processes_cleaning_up);
2812 process_close (gpointer handle, gpointer data)
2814 struct _WapiHandle_process *process_handle;
2816 DEBUG ("%s", __func__);
2818 process_handle = (struct _WapiHandle_process *) data;
2819 if (process_handle->mono_process && process_handle->self == _wapi_getpid ())
2820 InterlockedDecrement (&process_handle->mono_process->handle_count);
2821 mono_processes_cleanup ();
2826 mono_sigchld_signal_handler (int _dummy, siginfo_t *info, void *context)
2830 struct MonoProcess *p;
2833 fprintf (stdout, "SIG CHILD handler for pid: %i\n", info->si_pid);
2836 InterlockedIncrement (&mono_processes_read_lock);
2840 pid = waitpid (-1, &status, WNOHANG);
2841 } while (pid == -1 && errno == EINTR);
2847 fprintf (stdout, "child ended: %i", pid);
2851 if (p->pid == pid) {
2852 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2854 MONO_SEM_POST (&p->exit_sem);
2861 InterlockedDecrement (&mono_processes_read_lock);
2864 fprintf (stdout, "SIG CHILD handler: done looping.");
2869 static void process_add_sigchld_handler (void)
2872 struct sigaction sa;
2874 sa.sa_sigaction = mono_sigchld_signal_handler;
2875 sigemptyset (&sa.sa_mask);
2876 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2877 g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2878 DEBUG ("Added SIGCHLD handler");
2882 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2884 struct _WapiHandle_process *process_handle;
2890 struct MonoProcess *mp;
2892 gpointer current_thread;
2894 current_thread = _wapi_thread_handle_from_id (pthread_self ());
2895 if (current_thread == NULL) {
2896 SetLastError (ERROR_INVALID_HANDLE);
2900 /* FIXME: We can now easily wait on processes that aren't our own children,
2901 * but WaitFor*Object won't call us for pseudo handles. */
2902 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2904 DEBUG ("%s (%p, %u)", __func__, handle, timeout);
2906 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS, (gpointer *)&process_handle);
2908 g_warning ("%s: error looking up process handle %p", __func__, handle);
2912 if (process_handle->exited) {
2913 /* We've already done this one */
2914 DEBUG ("%s (%p, %u): Process already exited", __func__, handle, timeout);
2915 return WAIT_OBJECT_0;
2918 pid = process_handle->id;
2920 DEBUG ("%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2922 /* We don't need to lock mono_processes here, the entry
2923 * has a handle_count > 0 which means it will not be freed. */
2924 mp = process_handle->mono_process;
2925 if (mp && process_handle->self != _wapi_getpid ()) {
2926 /* mono_process points to memory in another process' address space: we can't use it */
2930 start = mono_msec_ticks ();
2936 /* We have a semaphore we can wait on */
2937 if (timeout != INFINITE) {
2938 DEBUG ("%s (%p, %u): waiting on semaphore for %li ms...",
2939 __func__, handle, timeout, (timeout - (now - start)));
2941 ret = MONO_SEM_TIMEDWAIT_ALERTABLE (&mp->exit_sem, (timeout - (now - start)), alertable);
2943 DEBUG ("%s (%p, %u): waiting on semaphore forever...",
2944 __func__, handle, timeout);
2945 ret = MONO_SEM_WAIT_ALERTABLE (&mp->exit_sem, alertable);
2948 if (ret == -1 && errno != EINTR && errno != ETIMEDOUT) {
2949 DEBUG ("%s (%p, %u): sem_timedwait failure: %s",
2950 __func__, handle, timeout, g_strerror (errno));
2951 /* Should we return a failure here? */
2955 /* Success, process has exited */
2956 MONO_SEM_POST (&mp->exit_sem);
2960 /* We did not create this process, so we can't waidpid / sem_wait it.
2961 * We need to poll for the pid existence */
2962 DEBUG ("%s (%p, %u): polling on pid...", __func__, handle, timeout);
2963 if (!is_pid_valid (pid)) {
2964 /* Success, process has exited */
2970 DEBUG ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
2971 return WAIT_TIMEOUT;
2974 now = mono_msec_ticks ();
2975 if (now - start >= timeout) {
2976 DEBUG ("%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
2977 return WAIT_TIMEOUT;
2981 /* "timeout - (now - start)" will not underflow, since timeout is always >=0,
2982 * and we passed the check just above */
2983 _wapi_handle_spin (MIN (100, timeout - (now - start)));
2986 if (alertable && _wapi_thread_apc_pending (current_thread)) {
2987 DEBUG ("%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
2988 return WAIT_IO_COMPLETION;
2992 /* Process must have exited */
2993 DEBUG ("%s (%p, %u): Waited successfully", __func__, handle, timeout);
2995 ret = _wapi_handle_lock_shared_handles ();
2996 g_assert (ret == 0);
2998 status = mp ? mp->status : 0;
2999 if (WIFSIGNALED (status)) {
3000 process_handle->exitstatus = 128 + WTERMSIG (status);
3002 process_handle->exitstatus = WEXITSTATUS (status);
3004 _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
3006 process_handle->exited = TRUE;
3008 DEBUG ("%s (%p, %u): Setting pid %d signalled, exit status %d",
3009 __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
3011 _wapi_shared_handle_set_signal_state (handle, TRUE);
3013 _wapi_handle_unlock_shared_handles ();
3015 return WAIT_OBJECT_0;