2 * processes.c: Process handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002-2011 Novell, Inc.
8 * Copyright 2011 Xamarin Inc
19 #include <sys/types.h>
25 #include <sys/resource.h>
27 #ifdef HAVE_SYS_PARAM_H
28 #include <sys/param.h>
32 #ifdef HAVE_SYS_MKDEV_H
33 #include <sys/mkdev.h>
36 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
38 #include <TargetConditionals.h>
39 #include <sys/resource.h>
46 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
48 #include <sys/sysctl.h>
49 # if !defined(__OpenBSD__)
50 # include <sys/utsname.h>
54 #ifdef PLATFORM_SOLARIS
55 /* procfs.h cannot be included if this define is set, but it seems to work fine if it is undefined */
56 #if _FILE_OFFSET_BITS == 64
57 #undef _FILE_OFFSET_BITS
59 #define _FILE_OFFSET_BITS 64
66 #include <KernelKit.h>
69 #include <mono/io-layer/wapi.h>
70 #include <mono/io-layer/wapi-private.h>
71 #include <mono/io-layer/handles-private.h>
72 #include <mono/io-layer/misc-private.h>
73 #include <mono/io-layer/process-private.h>
74 #include <mono/io-layer/threads.h>
75 #include <mono/utils/strenc.h>
76 #include <mono/utils/mono-path.h>
77 #include <mono/io-layer/timefuncs-private.h>
78 #include <mono/utils/mono-time.h>
79 #include <mono/utils/mono-membar.h>
80 #include <mono/utils/mono-mutex.h>
81 #include <mono/utils/mono-signal-handler.h>
83 /* The process' environment strings */
84 #if defined(__APPLE__) && !defined (__arm__)
85 /* Apple defines this in crt_externs.h but doesn't provide that header for
86 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
87 * in fact exist on all implementations (so far)
89 gchar ***_NSGetEnviron(void);
90 #define environ (*_NSGetEnviron())
92 extern char **environ;
96 #define DEBUG(...) g_message(__VA_ARGS__)
97 #define DEBUG_ENABLED 1
102 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable);
103 static void process_close (gpointer handle, gpointer data);
104 static gboolean is_pid_valid (pid_t pid);
106 #if !defined(__OpenBSD__)
108 open_process_map (int pid, const char *mode);
111 struct _WapiHandleOps _wapi_process_ops = {
112 process_close, /* close_shared */
116 process_wait, /* special_wait */
121 static struct sigaction previous_chld_sa;
123 static mono_once_t process_sig_chld_once = MONO_ONCE_INIT;
124 static void process_add_sigchld_handler (void);
126 /* The signal-safe logic to use mono_processes goes like this:
127 * - The list must be safe to traverse for the signal handler at all times.
128 * It's safe to: prepend an entry (which is a single store to 'mono_processes'),
129 * unlink an entry (assuming the unlinked entry isn't freed and doesn't
130 * change its 'next' pointer so that it can still be traversed).
131 * When cleaning up we first unlink an entry, then we verify that
132 * the read lock isn't locked. Then we can free the entry, since
133 * we know that nobody is using the old version of the list (including
134 * the unlinked entry).
135 * We also need to lock when adding and cleaning up so that those two
136 * operations don't mess with eachother. (This lock is not used in the
139 static struct MonoProcess *mono_processes = NULL;
140 static volatile gint32 mono_processes_read_lock = 0;
141 static volatile gint32 mono_processes_cleaning_up = 0;
142 static mono_mutex_t mono_processes_mutex;
143 static void mono_processes_cleanup (void);
145 static mono_once_t process_current_once=MONO_ONCE_INIT;
146 static gpointer current_process=NULL;
147 static char *cli_launcher;
149 static mono_once_t process_ops_once=MONO_ONCE_INIT;
151 static void process_ops_init (void)
153 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
154 WAPI_HANDLE_CAP_WAIT |
155 WAPI_HANDLE_CAP_SPECIAL_WAIT);
159 /* Check if a pid is valid - i.e. if a process exists with this pid. */
160 static gboolean is_pid_valid (pid_t pid)
162 gboolean result = FALSE;
164 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
165 if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
167 #elif defined(__HAIKU__)
169 if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
172 gchar *dir = g_strdup_printf ("/proc/%d", pid);
173 if (!access (dir, F_OK))
181 static void process_set_defaults (struct _WapiHandle_process *process_handle)
183 /* These seem to be the defaults on w2k */
184 process_handle->min_working_set = 204800;
185 process_handle->max_working_set = 1413120;
187 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
191 len16 (const gunichar2 *str)
202 utf16_concat (const gunichar2 *first, ...)
209 va_start (args, first);
210 total += len16 (first);
211 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
216 ret = g_new (gunichar2, total + 1);
222 for (s = first; *s != 0; s++)
224 va_start (args, first);
225 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
228 for (p = s; *p != 0; p++)
236 #ifdef PLATFORM_MACOSX
238 /* 0 = no detection; -1 = not 10.5 or higher; 1 = 10.5 or higher */
239 static int osx_10_5_or_higher;
242 detect_osx_10_5_or_higher (void)
248 if (uname (&u) != 0){
249 osx_10_5_or_higher = 1;
257 osx_10_5_or_higher = -1;
259 osx_10_5_or_higher = 1;
263 is_macos_10_5_or_higher (void)
265 if (osx_10_5_or_higher == 0)
266 detect_osx_10_5_or_higher ();
268 return (osx_10_5_or_higher == 1);
272 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
273 static const gunichar2 *utf16_space = utf16_space_bytes;
274 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
275 static const gunichar2 *utf16_quote = utf16_quote_bytes;
280 print_utf16 (gunichar2 *str)
284 res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
285 g_print ("%s\n", res);
290 /* Implemented as just a wrapper around CreateProcess () */
291 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
294 WapiProcessInformation process_info;
298 /* w2k just segfaults here, but we can do better than
301 SetLastError (ERROR_INVALID_PARAMETER);
305 if (sei->lpFile == NULL) {
306 /* w2k returns TRUE for this, for some reason. */
310 /* Put both executable and parameters into the second argument
311 * to CreateProcess (), so it searches $PATH. The conversion
312 * into and back out of utf8 is because there is no
313 * g_strdup_printf () equivalent for gunichar2 :-(
315 args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
317 SetLastError (ERROR_INVALID_DATA);
320 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
321 CREATE_UNICODE_ENVIRONMENT, NULL,
322 sei->lpDirectory, NULL, &process_info);
325 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
329 static char *handler;
330 static gunichar2 *handler_utf16;
332 if (handler_utf16 == (gunichar2 *)-1)
335 #ifdef PLATFORM_MACOSX
336 handler = g_strdup ("/usr/bin/open");
339 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
340 * if that fails, try to use gnome-open, then kfmclient
342 handler = g_find_program_in_path ("xdg-open");
343 if (handler == NULL){
344 handler = g_find_program_in_path ("gnome-open");
345 if (handler == NULL){
346 handler = g_find_program_in_path ("kfmclient");
347 if (handler == NULL){
348 handler_utf16 = (gunichar2 *) -1;
351 /* kfmclient needs exec argument */
353 handler = g_strconcat (old, " exec",
360 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
363 /* Put quotes around the filename, in case it's a url
364 * that contains #'s (CreateProcess() calls
365 * g_shell_parse_argv(), which deliberately throws
366 * away anything after an unquoted #). Fixes bug
369 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
370 sei->lpFile, utf16_quote,
371 sei->lpParameters == NULL ? NULL : utf16_space,
372 sei->lpParameters, NULL);
374 SetLastError (ERROR_INVALID_DATA);
377 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
378 CREATE_UNICODE_ENVIRONMENT, NULL,
379 sei->lpDirectory, NULL, &process_info);
382 if (GetLastError () != ERROR_OUTOFMEMORY)
383 SetLastError (ERROR_INVALID_DATA);
386 /* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
387 CloseHandle (process_info.hProcess);
388 process_info.hProcess = NULL;
391 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
392 sei->hProcess = process_info.hProcess;
394 CloseHandle (process_info.hProcess);
401 is_managed_binary (const gchar *filename)
403 int original_errno = errno;
404 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
405 int file = open (filename, O_RDONLY | O_LARGEFILE);
407 int file = open (filename, O_RDONLY);
410 unsigned char buffer[8];
411 off_t file_size, optional_header_offset;
412 off_t pe_header_offset;
413 gboolean managed = FALSE;
415 guint32 first_word, second_word;
417 /* If we are unable to open the file, then we definitely
418 * can't say that it is managed. The child mono process
419 * probably wouldn't be able to open it anyway.
422 errno = original_errno;
426 /* Retrieve the length of the file for future sanity checks. */
427 file_size = lseek (file, 0, SEEK_END);
428 lseek (file, 0, SEEK_SET);
430 /* We know we need to read a header field at offset 60. */
434 num_read = read (file, buffer, 2);
436 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
439 new_offset = lseek (file, 60, SEEK_SET);
441 if (new_offset != 60)
444 num_read = read (file, buffer, 4);
448 pe_header_offset = buffer[0]
453 if (pe_header_offset + 24 > file_size)
456 new_offset = lseek (file, pe_header_offset, SEEK_SET);
458 if (new_offset != pe_header_offset)
461 num_read = read (file, buffer, 4);
463 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
467 * Verify that the header we want in the optional header data
468 * is present in this binary.
470 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
472 if (new_offset != pe_header_offset + 20)
475 num_read = read (file, buffer, 2);
477 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
480 /* Read the CLR header address and size fields. These will be
481 * zero if the binary is not managed.
483 optional_header_offset = pe_header_offset + 24;
484 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
486 if (new_offset != optional_header_offset + 208)
489 num_read = read (file, buffer, 8);
491 /* We are not concerned with endianness, only with
492 * whether it is zero or not.
494 first_word = *(guint32 *)&buffer[0];
495 second_word = *(guint32 *)&buffer[4];
497 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
504 errno = original_errno;
508 gboolean CreateProcessWithLogonW (const gunichar2 *username,
509 const gunichar2 *domain,
510 const gunichar2 *password,
511 const guint32 logonFlags,
512 const gunichar2 *appname,
513 const gunichar2 *cmdline,
514 guint32 create_flags,
516 const gunichar2 *cwd,
517 WapiStartupInfo *startup,
518 WapiProcessInformation *process_info)
520 /* FIXME: use user information */
521 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
525 is_executable (const char *prog)
528 if (access (prog, X_OK) != 0)
530 if (stat (prog, &buf))
532 if (S_ISREG (buf.st_mode))
538 switchDirectorySeparators(gchar *path)
540 size_t i, pathLength = strlen(path);
542 /* Turn all the slashes round the right way, except for \' */
543 /* There are probably other characters that need to be excluded as well. */
544 for (i = 0; i < pathLength; i++)
546 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' ) {
552 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
553 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
554 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
555 gboolean inherit_handles, guint32 create_flags,
556 gpointer new_environ, const gunichar2 *cwd,
557 WapiStartupInfo *startup,
558 WapiProcessInformation *process_info)
560 gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
561 guint32 i, env_count = 0;
562 gboolean ret = FALSE;
564 struct _WapiHandle_process process_handle = {0}, *process_handle_data;
566 int in_fd, out_fd, err_fd;
569 int startup_pipe [2] = {-1, -1};
571 struct MonoProcess *mono_process;
572 gboolean fork_failed = FALSE;
574 mono_once (&process_ops_once, process_ops_init);
575 mono_once (&process_sig_chld_once, process_add_sigchld_handler);
577 /* appname and cmdline specify the executable and its args:
579 * If appname is not NULL, it is the name of the executable.
580 * Otherwise the executable is the first token in cmdline.
582 * Executable searching:
584 * If appname is not NULL, it can specify the full path and
585 * file name, or else a partial name and the current directory
586 * will be used. There is no additional searching.
588 * If appname is NULL, the first whitespace-delimited token in
589 * cmdline is used. If the name does not contain a full
590 * directory path, the search sequence is:
592 * 1) The directory containing the current process
593 * 2) The current working directory
594 * 3) The windows system directory (Ignored)
595 * 4) The windows directory (Ignored)
598 * Just to make things more interesting, tokens can contain
599 * white space if they are surrounded by quotation marks. I'm
600 * beginning to understand just why windows apps are generally
601 * so crap, with an API like this :-(
603 if (appname != NULL) {
604 cmd = mono_unicode_to_external (appname);
606 DEBUG ("%s: unicode conversion returned NULL",
609 SetLastError (ERROR_PATH_NOT_FOUND);
613 switchDirectorySeparators(cmd);
616 if (cmdline != NULL) {
617 args = mono_unicode_to_external (cmdline);
619 DEBUG ("%s: unicode conversion returned NULL", __func__);
621 SetLastError (ERROR_PATH_NOT_FOUND);
627 dir = mono_unicode_to_external (cwd);
629 DEBUG ("%s: unicode conversion returned NULL", __func__);
631 SetLastError (ERROR_PATH_NOT_FOUND);
635 /* Turn all the slashes round the right way */
636 switchDirectorySeparators(dir);
640 /* We can't put off locating the executable any longer :-( */
643 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
644 /* Strip off the drive letter. I can't
645 * believe that CP/M holdover is still
648 g_memmove (cmd, cmd+2, strlen (cmd)-2);
649 cmd[strlen (cmd)-2] = '\0';
652 unquoted = g_shell_unquote (cmd, NULL);
653 if (unquoted[0] == '/') {
654 /* Assume full path given */
655 prog = g_strdup (unquoted);
657 /* Executable existing ? */
658 if (!is_executable (prog)) {
659 DEBUG ("%s: Couldn't find executable %s",
662 SetLastError (ERROR_FILE_NOT_FOUND);
666 /* Search for file named by cmd in the current
669 char *curdir = g_get_current_dir ();
671 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
674 /* And make sure it's executable */
675 if (!is_executable (prog)) {
676 DEBUG ("%s: Couldn't find executable %s",
679 SetLastError (ERROR_FILE_NOT_FOUND);
685 args_after_prog = args;
690 /* Dig out the first token from args, taking quotation
694 /* First, strip off all leading whitespace */
695 args = g_strchug (args);
697 /* args_after_prog points to the contents of args
698 * after token has been set (otherwise argv[0] is
701 args_after_prog = args;
703 /* Assume the opening quote will always be the first
706 if (args[0] == '\"' || args [0] == '\'') {
708 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
709 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
710 /* We found the first token */
711 token = g_strndup (args+1, i-1);
712 args_after_prog = g_strchug (args + i + 1);
714 /* Quotation mark appeared in the
715 * middle of the token. Just give the
716 * whole first token, quotes and all,
723 /* No quote mark, or malformed */
724 for (i = 0; args[i] != '\0'; i++) {
725 if (g_ascii_isspace (args[i])) {
726 token = g_strndup (args, i);
727 args_after_prog = args + i + 1;
733 if (token == NULL && args[0] != '\0') {
734 /* Must be just one token in the string */
735 token = g_strdup (args);
736 args_after_prog = NULL;
741 DEBUG ("%s: Couldn't find what to exec", __func__);
743 SetLastError (ERROR_PATH_NOT_FOUND);
747 /* Turn all the slashes round the right way. Only for
750 switchDirectorySeparators(token);
752 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
753 /* Strip off the drive letter. I can't
754 * believe that CP/M holdover is still
757 g_memmove (token, token+2, strlen (token)-2);
758 token[strlen (token)-2] = '\0';
761 if (token[0] == '/') {
762 /* Assume full path given */
763 prog = g_strdup (token);
765 /* Executable existing ? */
766 if (!is_executable (prog)) {
767 DEBUG ("%s: Couldn't find executable %s",
770 SetLastError (ERROR_FILE_NOT_FOUND);
775 char *curdir = g_get_current_dir ();
777 /* FIXME: Need to record the directory
778 * containing the current process, and check
779 * that for the new executable as the first
783 prog = g_strdup_printf ("%s/%s", curdir, token);
786 /* I assume X_OK is the criterion to use,
789 if (!is_executable (prog)) {
791 prog = g_find_program_in_path (token);
793 DEBUG ("%s: Couldn't find executable %s", __func__, token);
796 SetLastError (ERROR_FILE_NOT_FOUND);
805 DEBUG ("%s: Exec prog [%s] args [%s]", __func__, prog,
808 /* Check for CLR binaries; if found, we will try to invoke
809 * them using the same mono binary that started us.
811 if (is_managed_binary (prog)) {
812 gunichar2 *newapp = NULL, *newcmd;
816 newapp = mono_unicode_from_external (cli_launcher, &bytes_ignored);
818 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
820 if (newapp != NULL) {
821 if (appname != NULL) {
822 newcmd = utf16_concat (newapp, utf16_space,
823 appname, utf16_space,
826 newcmd = utf16_concat (newapp, utf16_space,
830 g_free ((gunichar2 *)newapp);
832 if (newcmd != NULL) {
833 ret = CreateProcess (NULL, newcmd,
837 create_flags, new_environ,
841 g_free ((gunichar2 *)newcmd);
848 if (args_after_prog != NULL && *args_after_prog) {
851 qprog = g_shell_quote (prog);
852 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
855 full_prog = g_shell_quote (prog);
858 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
860 g_message ("CreateProcess: %s\n", gerr->message);
866 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
867 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
868 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
869 err_fd = GPOINTER_TO_UINT (startup->hStdError);
871 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
872 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
873 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
876 g_strlcpy (process_handle.proc_name, prog,
877 _WAPI_PROC_NAME_MAX_LEN - 1);
879 process_set_defaults (&process_handle);
881 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
882 if (handle == _WAPI_HANDLE_INVALID) {
883 g_warning ("%s: error creating process handle", __func__);
886 SetLastError (ERROR_OUTOFMEMORY);
890 /* new_environ is a block of NULL-terminated strings, which
891 * is itself NULL-terminated. Of course, passing an array of
892 * string pointers would have made things too easy :-(
894 * If new_environ is not NULL it specifies the entire set of
895 * environment variables in the new process. Otherwise the
896 * new process inherits the same environment.
898 if (new_environ != NULL) {
899 gunichar2 *new_environp;
901 /* Count the number of strings */
902 for (new_environp = (gunichar2 *)new_environ; *new_environp;
905 while (*new_environp) {
910 /* +2: one for the process handle value, and the last
913 env_strings = g_new0 (gchar *, env_count + 2);
915 /* Copy each environ string into 'strings' turning it
916 * into utf8 (or the requested encoding) at the same
920 for (new_environp = (gunichar2 *)new_environ; *new_environp;
922 env_strings[env_count] = mono_unicode_to_external (new_environp);
924 while (*new_environp) {
929 for (i = 0; environ[i] != NULL; i++) {
933 /* +2: one for the process handle value, and the last
936 env_strings = g_new0 (gchar *, env_count + 2);
938 /* Copy each environ string into 'strings' turning it
939 * into utf8 (or the requested encoding) at the same
943 for (i = 0; environ[i] != NULL; i++) {
944 env_strings[env_count] = g_strdup (environ[i]);
948 /* pass process handle info to the child, so it doesn't have
949 * to do an expensive search over the whole list
951 if (env_strings != NULL) {
952 struct _WapiHandleUnshared *handle_data;
953 struct _WapiHandle_shared_ref *ref;
955 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
956 ref = &handle_data->u.shared;
958 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
961 /* Create a pipe to make sure the child doesn't exit before
962 * we can add the process to the linked list of mono_processes */
963 if (pipe (startup_pipe) == -1) {
964 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
965 * This is just for a very hard to hit race condition in the first place */
966 startup_pipe [0] = startup_pipe [1] = -1;
967 DEBUG ("%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
970 thr_ret = _wapi_handle_lock_shared_handles ();
971 g_assert (thr_ret == 0);
976 SetLastError (ERROR_OUTOFMEMORY);
980 } else if (pid == 0) {
983 if (startup_pipe [0] != -1) {
984 /* Wait until the parent has updated it's internal data */
985 ssize_t _i G_GNUC_UNUSED = read (startup_pipe [0], &dummy, 1);
986 DEBUG ("%s: child: parent has completed its setup", __func__);
987 close (startup_pipe [0]);
988 close (startup_pipe [1]);
991 /* should we detach from the process group? */
993 /* Connect stdin, stdout and stderr */
998 if (inherit_handles != TRUE) {
999 /* FIXME: do something here */
1002 /* Close all file descriptors */
1003 for (i = getdtablesize () - 1; i > 2; i--) {
1007 #ifdef DEBUG_ENABLED
1008 DEBUG ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1010 for (i = 0; argv[i] != NULL; i++) {
1011 g_message ("arg %d: [%s]", i, argv[i]);
1014 for (i = 0; env_strings[i] != NULL; i++) {
1015 g_message ("env %d: [%s]", i, env_strings[i]);
1020 if (dir != NULL && chdir (dir) == -1) {
1026 execve (argv[0], argv, env_strings);
1033 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1034 (gpointer *)&process_handle_data);
1036 g_warning ("%s: error looking up process handle %p", __func__,
1038 _wapi_handle_unref (handle);
1042 process_handle_data->id = pid;
1044 /* Add our mono_process into the linked list of mono_processes */
1045 mono_process = (struct MonoProcess *) g_malloc0 (sizeof (struct MonoProcess));
1046 mono_process->pid = pid;
1047 mono_process->handle_count = 1;
1048 if (MONO_SEM_INIT (&mono_process->exit_sem, 0) != 0) {
1049 /* If we can't create the exit semaphore, we just don't add anything
1050 * to our list of mono processes. Waiting on the process will return
1052 g_warning ("%s: could not create exit semaphore for process.", strerror (errno));
1053 g_free (mono_process);
1055 /* Keep the process handle artificially alive until the process
1056 * exits so that the information in the handle isn't lost. */
1057 _wapi_handle_ref (handle);
1058 mono_process->handle = handle;
1060 process_handle_data->self = _wapi_getpid ();
1061 process_handle_data->mono_process = mono_process;
1063 mono_mutex_lock (&mono_processes_mutex);
1064 mono_process->next = mono_processes;
1065 mono_processes = mono_process;
1066 mono_mutex_unlock (&mono_processes_mutex);
1069 if (process_info != NULL) {
1070 process_info->hProcess = handle;
1071 process_info->dwProcessId = pid;
1073 /* FIXME: we might need to handle the thread info some
1076 process_info->hThread = INVALID_HANDLE_VALUE;
1077 process_info->dwThreadId = 0;
1081 _wapi_handle_unlock_shared_handles ();
1084 _wapi_handle_unref (handle);
1086 if (startup_pipe [1] != -1) {
1087 /* Write 1 byte, doesn't matter what */
1088 ssize_t _i G_GNUC_UNUSED = write (startup_pipe [1], startup_pipe, 1);
1089 close (startup_pipe [0]);
1090 close (startup_pipe [1]);
1097 if (full_prog != NULL) {
1109 if(env_strings != NULL) {
1110 g_strfreev (env_strings);
1116 DEBUG ("%s: returning handle %p for pid %d", __func__, handle,
1119 /* Check if something needs to be cleaned up. */
1120 mono_processes_cleanup ();
1125 static void process_set_name (struct _WapiHandle_process *process_handle)
1127 gchar *progname, *utf8_progname, *slash;
1129 progname=g_get_prgname ();
1130 utf8_progname=mono_utf8_from_external (progname);
1132 DEBUG ("%s: using [%s] as prog name", __func__, progname);
1134 if(utf8_progname!=NULL) {
1135 slash=strrchr (utf8_progname, '/');
1137 g_strlcpy (process_handle->proc_name, slash+1,
1138 _WAPI_PROC_NAME_MAX_LEN - 1);
1140 g_strlcpy (process_handle->proc_name, utf8_progname,
1141 _WAPI_PROC_NAME_MAX_LEN - 1);
1144 g_free (utf8_progname);
1148 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
1150 #if !GLIB_CHECK_VERSION (2,4,0)
1151 #define g_setenv(a,b,c) setenv(a,b,c)
1152 #define g_unsetenv(a) unsetenv(a)
1155 static void process_set_current (void)
1157 pid_t pid = _wapi_getpid ();
1158 const char *handle_env;
1159 struct _WapiHandle_process process_handle = {0};
1161 mono_once (&process_ops_once, process_ops_init);
1163 handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1164 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1166 if (handle_env != NULL) {
1167 struct _WapiHandle_process *process_handlep;
1168 gchar *procname = NULL;
1171 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
1173 DEBUG ("%s: Found my process handle: %p (offset %d 0x%x)",
1174 __func__, current_process, atoi (handle_env),
1177 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
1178 (gpointer *)&process_handlep);
1180 /* This test will probably break on linuxthreads, but
1181 * that should be ancient history on all distros we
1184 if (process_handlep->id == pid) {
1185 procname = process_handlep->proc_name;
1186 if (!strcmp (procname, "mono")) {
1187 /* Set a better process name */
1188 DEBUG ("%s: Setting better process name", __func__);
1190 process_set_name (process_handlep);
1192 DEBUG ("%s: Leaving process name: %s", __func__, procname);
1198 /* Wrong pid, so drop this handle and fall through to
1201 _wapi_handle_unref (current_process);
1205 /* We get here if the handle wasn't specified in the
1206 * environment, or if the process ID was wrong, or if the
1207 * handle lookup failed (eg if the parent process forked and
1208 * quit immediately, and deleted the shared data before the
1209 * child got a chance to attach it.)
1212 DEBUG ("%s: Need to create my own process handle", __func__);
1214 process_handle.id = pid;
1216 process_set_defaults (&process_handle);
1217 process_set_name (&process_handle);
1219 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1221 if (current_process == _WAPI_HANDLE_INVALID) {
1222 g_warning ("%s: error creating process handle", __func__);
1227 gpointer _wapi_process_duplicate ()
1229 mono_once (&process_current_once, process_set_current);
1231 _wapi_handle_ref (current_process);
1233 return(current_process);
1236 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1237 gpointer GetCurrentProcess (void)
1239 mono_once (&process_current_once, process_set_current);
1241 return(_WAPI_PROCESS_CURRENT);
1244 guint32 GetProcessId (gpointer handle)
1246 struct _WapiHandle_process *process_handle;
1249 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1250 /* This is a pseudo handle */
1251 return(GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
1254 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1255 (gpointer *)&process_handle);
1257 SetLastError (ERROR_INVALID_HANDLE);
1261 return (process_handle->id);
1264 guint32 GetCurrentProcessId (void)
1266 mono_once (&process_current_once, process_set_current);
1268 return (GetProcessId (current_process));
1271 /* Returns the process id as a convenience to the functions that call this */
1272 static pid_t signal_process_if_gone (gpointer handle)
1274 struct _WapiHandle_process *process_handle;
1277 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
1279 /* Make sure the process is signalled if it has exited - if
1280 * the parent process didn't wait for it then it won't be
1282 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1283 (gpointer *)&process_handle);
1285 /* It's possible that the handle has vanished during
1286 * the _wapi_search_handle before it gets here, so
1287 * don't spam the console with warnings.
1289 /* g_warning ("%s: error looking up process handle %p",
1290 __func__, handle);*/
1295 DEBUG ("%s: looking at process %d", __func__, process_handle->id);
1297 if (kill (process_handle->id, 0) == -1 &&
1300 /* The process is dead, (EPERM tells us a new process
1301 * has that ID, but as it's owned by someone else it
1302 * can't be the one listed in our shared memory file)
1304 _wapi_shared_handle_set_signal_state (handle, TRUE);
1307 return (process_handle->id);
1311 static gboolean process_enum (gpointer handle, gpointer user_data)
1313 GArray *processes=user_data;
1314 pid_t pid = signal_process_if_gone (handle);
1321 /* Ignore processes that have already exited (ie they are signalled) */
1322 if (_wapi_handle_issignalled (handle) == FALSE) {
1323 DEBUG ("%s: process %d added to array", __func__, pid);
1325 /* This ensures that duplicates aren't returned (see
1326 * the comment above _wapi_search_handle () for why
1329 for (i = 0; i < processes->len; i++) {
1330 if (g_array_index (processes, pid_t, i) == pid) {
1331 /* We've already got this one, return
1332 * FALSE to keep searching
1338 g_array_append_val (processes, pid);
1341 /* Return false to keep searching */
1344 #endif /* UNUSED_CODE */
1346 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
1348 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1350 guint32 count, fit, i, j;
1353 size_t proclength, size;
1354 #if defined(__OpenBSD__)
1355 struct kinfo_proc *result;
1358 name[1] = KERN_PROC;
1359 name[2] = KERN_PROC_ALL;
1361 name[4] = sizeof(struct kinfo_proc);
1364 struct kinfo_proc *result;
1365 static const int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
1368 mono_once (&process_current_once, process_set_current);
1375 #if defined(__OpenBSD__)
1376 size = (sizeof(name) / sizeof(*name));
1378 size = (sizeof(name) / sizeof(*name)) - 1;
1380 err = sysctl ((int *)name, size, NULL, &proclength, NULL, 0);
1383 result = malloc (proclength);
1388 #if defined(__OpenBSD__)
1389 name[5] = (int)(proclength / sizeof(struct kinfo_proc));
1392 err = sysctl ((int *) name, size, result, &proclength, NULL, 0);
1401 } while (err == 0 && !done);
1404 if (result != NULL) {
1411 count = proclength / sizeof(struct kinfo_proc);
1413 fit = len / sizeof(guint32);
1414 for (i = 0, j = 0; j< fit && i < count; i++) {
1415 #if defined(__OpenBSD__)
1416 pids [j++] = result [i].p_pid;
1418 if (result[i].kp_proc.p_pid > 0) /* Pid 0 not supported */
1419 pids [j++] = result [i].kp_proc.p_pid;
1424 *needed = j * sizeof(guint32);
1428 #elif defined(__HAIKU__)
1430 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1436 mono_once (&process_current_once, process_set_current);
1438 fit = len / sizeof (guint32);
1439 while (get_next_team_info (&cookie, &teamInfo) == B_OK && i < fit) {
1440 pids [i++] = teamInfo.team;
1442 *needed = i * sizeof (guint32);
1447 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1451 struct dirent *entry;
1453 mono_once (&process_current_once, process_set_current);
1455 dir = opendir ("/proc");
1461 fit = len / sizeof (guint32);
1462 while(i < fit && (entry = readdir (dir)) != NULL) {
1466 if (!isdigit (entry->d_name[0]))
1469 pid = (pid_t) strtol (entry->d_name, &endptr, 10);
1470 if (*endptr == '\0')
1471 pids [i++] = (guint32) pid;
1474 *needed = i * sizeof(guint32);
1480 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1483 pid_t checking_pid = signal_process_if_gone (handle);
1485 if (checking_pid == 0) {
1489 wanted_pid = GPOINTER_TO_UINT (user_data);
1491 /* It's possible to have more than one process handle with the
1492 * same pid, but only the one running process can be
1495 if (checking_pid == wanted_pid &&
1496 _wapi_handle_issignalled (handle) == FALSE) {
1497 /* If the handle is blown away in the window between
1498 * returning TRUE here and _wapi_search_handle pinging
1499 * the timestamp, the search will continue
1507 gboolean CloseProcess(gpointer handle)
1509 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1510 /* This is a pseudo handle */
1514 return CloseHandle (handle);
1518 * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1520 gpointer OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1522 /* Find the process handle that corresponds to pid */
1523 gpointer handle = NULL;
1525 mono_once (&process_current_once, process_set_current);
1527 DEBUG ("%s: looking for process %d", __func__, pid);
1529 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1530 process_open_compare,
1531 GUINT_TO_POINTER (pid), NULL, TRUE);
1533 if (is_pid_valid (pid)) {
1534 /* Return a pseudo handle for processes we
1535 * don't have handles for
1537 return GINT_TO_POINTER (_WAPI_PROCESS_UNHANDLED + pid);
1539 DEBUG ("%s: Can't find pid %d", __func__, pid);
1541 SetLastError (ERROR_PROC_NOT_FOUND);
1547 /* _wapi_search_handle () already added a ref */
1551 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1553 struct _WapiHandle_process *process_handle;
1557 mono_once (&process_current_once, process_set_current);
1563 pid = GPOINTER_TO_UINT (process) - _WAPI_PROCESS_UNHANDLED;
1564 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1565 /* This is a pseudo handle, so we don't know what the
1566 * exit code was, but we can check whether it's alive or not
1568 if (is_pid_valid (pid)) {
1569 *code = STILL_ACTIVE;
1576 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1577 (gpointer *)&process_handle);
1579 DEBUG ("%s: Can't find process %p", __func__, process);
1584 /* A process handle is only signalled if the process has exited
1585 * and has been waited for */
1587 /* Make sure any process exit has been noticed, before
1588 * checking if the process is signalled. Fixes bug 325463.
1590 process_wait (process, 0, TRUE);
1592 if (_wapi_handle_issignalled (process) == TRUE) {
1593 *code = process_handle->exitstatus;
1595 *code = STILL_ACTIVE;
1601 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1602 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1603 WapiFileTime *user_time)
1605 struct _WapiHandle_process *process_handle;
1607 gboolean ku_times_set = FALSE;
1609 mono_once (&process_current_once, process_set_current);
1611 if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1613 /* Not sure if w32 allows NULLs here or not */
1617 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1618 /* This is a pseudo handle, so just fail for now
1623 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1624 (gpointer *)&process_handle);
1626 DEBUG ("%s: Can't find process %p", __func__, process);
1631 *create_time=process_handle->create_time;
1633 /* A process handle is only signalled if the process has
1634 * exited. Otherwise exit_time isn't set
1636 if(_wapi_handle_issignalled (process)==TRUE) {
1637 *exit_time=process_handle->exit_time;
1640 #ifdef HAVE_GETRUSAGE
1641 if (process_handle->id == getpid ()) {
1642 struct rusage time_data;
1643 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1645 ku_times_set = TRUE;
1646 tick_val = (guint64)time_data.ru_utime.tv_sec * 10000000 + (guint64)time_data.ru_utime.tv_usec * 10;
1647 _wapi_guint64_to_filetime (tick_val, user_time);
1648 tick_val = (guint64)time_data.ru_stime.tv_sec * 10000000 + (guint64)time_data.ru_stime.tv_usec * 10;
1649 _wapi_guint64_to_filetime (tick_val, kernel_time);
1653 if (!ku_times_set) {
1654 memset (kernel_time, 0, sizeof (WapiFileTime));
1655 memset (user_time, 0, sizeof (WapiFileTime));
1663 gpointer address_start;
1664 gpointer address_end;
1666 gpointer address_offset;
1672 static void free_procmodule (WapiProcModule *mod)
1674 if (mod->perms != NULL) {
1675 g_free (mod->perms);
1677 if (mod->filename != NULL) {
1678 g_free (mod->filename);
1683 static gint find_procmodule (gconstpointer a, gconstpointer b)
1685 WapiProcModule *want = (WapiProcModule *)a;
1686 WapiProcModule *compare = (WapiProcModule *)b;
1688 if ((want->device == compare->device) &&
1689 (want->inode == compare->inode)) {
1696 #ifdef PLATFORM_MACOSX
1697 #include <mach-o/dyld.h>
1698 #include <mach-o/getsect.h>
1700 static GSList *load_modules (void)
1703 WapiProcModule *mod;
1704 uint32_t count = _dyld_image_count ();
1707 for (i = 0; i < count; i++) {
1708 #if SIZEOF_VOID_P == 8
1709 const struct mach_header_64 *hdr;
1710 const struct section_64 *sec;
1712 const struct mach_header *hdr;
1713 const struct section *sec;
1717 name = _dyld_get_image_name (i);
1718 #if SIZEOF_VOID_P == 8
1719 hdr = (const struct mach_header_64*)_dyld_get_image_header (i);
1720 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1722 hdr = _dyld_get_image_header (i);
1723 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1726 /* Some dynlibs do not have data sections on osx (#533893) */
1731 mod = g_new0 (WapiProcModule, 1);
1732 mod->address_start = GINT_TO_POINTER (sec->addr);
1733 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1734 mod->perms = g_strdup ("r--p");
1735 mod->address_offset = 0;
1736 mod->device = makedev (0, 0);
1737 mod->inode = (ino_t) i;
1738 mod->filename = g_strdup (name);
1740 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1741 ret = g_slist_prepend (ret, mod);
1743 free_procmodule (mod);
1747 ret = g_slist_reverse (ret);
1751 #elif defined(__OpenBSD__)
1753 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1755 if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1756 + sizeof (info->dlpi_phnum))
1759 struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1763 memcpy(cpy, info, sizeof(*info));
1765 g_ptr_array_add ((GPtrArray *)ptr, cpy);
1770 static GSList *load_modules (void)
1773 WapiProcModule *mod;
1774 GPtrArray *dlarray = g_ptr_array_new();
1777 if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1780 for (i = 0; i < dlarray->len; i++) {
1781 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1783 mod = g_new0 (WapiProcModule, 1);
1784 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1785 mod->address_end = (gpointer)(info->dlpi_addr +
1786 info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1787 mod->perms = g_strdup ("r--p");
1788 mod->address_offset = 0;
1789 mod->inode = (ino_t) i;
1790 mod->filename = g_strdup (info->dlpi_name);
1792 DEBUG ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1793 mod->inode, mod->filename, mod->address_start, mod->address_end);
1797 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1798 ret = g_slist_prepend (ret, mod);
1800 free_procmodule (mod);
1804 g_ptr_array_free (dlarray, TRUE);
1806 ret = g_slist_reverse (ret);
1810 #elif defined(__HAIKU__)
1812 static GSList *load_modules (void)
1815 WapiProcModule *mod;
1817 image_info imageInfo;
1819 while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
1820 mod = g_new0 (WapiProcModule, 1);
1821 mod->device = imageInfo.device;
1822 mod->inode = imageInfo.node;
1823 mod->filename = g_strdup (imageInfo.name);
1824 mod->address_start = MIN (imageInfo.text, imageInfo.data);
1825 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
1826 (uint8_t*)imageInfo.data + imageInfo.data_size);
1827 mod->perms = g_strdup ("r--p");
1828 mod->address_offset = 0;
1830 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1831 ret = g_slist_prepend (ret, mod);
1833 free_procmodule (mod);
1837 ret = g_slist_reverse (ret);
1842 static GSList *load_modules (FILE *fp)
1845 WapiProcModule *mod;
1846 gchar buf[MAXPATHLEN + 1], *p, *endp;
1847 gchar *start_start, *end_start, *prot_start, *offset_start;
1848 gchar *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1849 gpointer address_start, address_end, address_offset;
1850 guint32 maj_dev, min_dev;
1854 while (fgets (buf, sizeof(buf), fp)) {
1856 while (g_ascii_isspace (*p)) ++p;
1858 if (!g_ascii_isxdigit (*start_start)) {
1861 address_start = (gpointer)strtoul (start_start, &endp, 16);
1869 if (!g_ascii_isxdigit (*end_start)) {
1872 address_end = (gpointer)strtoul (end_start, &endp, 16);
1874 if (!g_ascii_isspace (*p)) {
1878 while (g_ascii_isspace (*p)) ++p;
1880 if (*prot_start != 'r' && *prot_start != '-') {
1883 memcpy (prot_buf, prot_start, 4);
1885 while (!g_ascii_isspace (*p)) ++p;
1887 while (g_ascii_isspace (*p)) ++p;
1889 if (!g_ascii_isxdigit (*offset_start)) {
1892 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1894 if (!g_ascii_isspace (*p)) {
1898 while(g_ascii_isspace (*p)) ++p;
1900 if (!g_ascii_isxdigit (*maj_dev_start)) {
1903 maj_dev = strtoul (maj_dev_start, &endp, 16);
1911 if (!g_ascii_isxdigit (*min_dev_start)) {
1914 min_dev = strtoul (min_dev_start, &endp, 16);
1916 if (!g_ascii_isspace (*p)) {
1920 while (g_ascii_isspace (*p)) ++p;
1922 if (!g_ascii_isxdigit (*inode_start)) {
1925 inode = (ino_t)strtol (inode_start, &endp, 10);
1927 if (!g_ascii_isspace (*p)) {
1931 device = makedev ((int)maj_dev, (int)min_dev);
1932 if ((device == 0) &&
1937 while(g_ascii_isspace (*p)) ++p;
1938 /* p now points to the filename */
1940 mod = g_new0 (WapiProcModule, 1);
1941 mod->address_start = address_start;
1942 mod->address_end = address_end;
1943 mod->perms = g_strdup (prot_buf);
1944 mod->address_offset = address_offset;
1945 mod->device = device;
1947 mod->filename = g_strdup (g_strstrip (p));
1949 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1950 ret = g_slist_prepend (ret, mod);
1952 free_procmodule (mod);
1956 ret = g_slist_reverse (ret);
1962 static gboolean match_procname_to_modulename (gchar *procname, gchar *modulename)
1964 char* lastsep = NULL;
1965 char* lastsep2 = NULL;
1968 gboolean result = FALSE;
1970 if (procname == NULL || modulename == NULL)
1973 pname = mono_path_resolve_symlinks (procname);
1974 mname = mono_path_resolve_symlinks (modulename);
1976 if (!strcmp (pname, mname))
1980 lastsep = strrchr (mname, '/');
1982 if (!strcmp (lastsep+1, pname))
1985 lastsep2 = strrchr (pname, '/');
1988 if (!strcmp (lastsep+1, lastsep2+1))
1991 if (!strcmp (mname, lastsep2+1))
2004 #if !defined(__OpenBSD__)
2006 open_process_map (int pid, const char *mode)
2009 const gchar *proc_path[] = {
2010 "/proc/%d/maps", /* GNU/Linux */
2011 "/proc/%d/map", /* FreeBSD */
2017 for (i = 0; fp == NULL && proc_path [i]; i++) {
2018 filename = g_strdup_printf (proc_path[i], pid);
2019 fp = fopen (filename, mode);
2027 gboolean EnumProcessModules (gpointer process, gpointer *modules,
2028 guint32 size, guint32 *needed)
2030 struct _WapiHandle_process *process_handle;
2032 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2035 GSList *mods = NULL;
2036 WapiProcModule *module;
2037 guint32 count, avail = size / sizeof(gpointer);
2040 gchar *proc_name = NULL;
2042 /* Store modules in an array of pointers (main module as
2043 * modules[0]), using the load address for each module as a
2044 * token. (Use 'NULL' as an alternative for the main module
2045 * so that the simple implementation can just return one item
2046 * for now.) Get the info from /proc/<pid>/maps on linux,
2047 * /proc/<pid>/map on FreeBSD, other systems will have to
2048 * implement /dev/kmem reading or whatever other horrid
2049 * technique is needed.
2051 if (size < sizeof(gpointer)) {
2055 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2056 /* This is a pseudo handle */
2057 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2059 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2060 (gpointer *)&process_handle);
2062 DEBUG ("%s: Can't find process %p", __func__, process);
2066 pid = process_handle->id;
2067 proc_name = process_handle->proc_name;
2070 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2072 mods = load_modules ();
2074 if ((fp = open_process_map (pid, "r")) == NULL) {
2075 /* No /proc/<pid>/maps so just return the main module
2079 *needed = sizeof(gpointer);
2081 mods = load_modules (fp);
2084 count = g_slist_length (mods);
2086 /* count + 1 to leave slot 0 for the main module */
2087 *needed = sizeof(gpointer) * (count + 1);
2089 /* Use the NULL shortcut, as the first line in
2090 * /proc/<pid>/maps isn't the executable, and we need
2091 * that first in the returned list. Check the module name
2092 * to see if it ends with the proc name and substitute
2093 * the first entry with it. FIXME if this turns out to
2097 for (i = 0; i < (avail - 1) && i < count; i++) {
2098 module = (WapiProcModule *)g_slist_nth_data (mods, i);
2099 if (modules[0] != NULL)
2100 modules[i] = module->address_start;
2101 else if (match_procname_to_modulename (proc_name, module->filename))
2102 modules[0] = module->address_start;
2104 modules[i + 1] = module->address_start;
2107 for (i = 0; i < count; i++) {
2108 free_procmodule (g_slist_nth_data (mods, i));
2110 g_slist_free (mods);
2116 static gchar *get_process_name_from_proc (pid_t pid)
2118 #if defined(__OpenBSD__)
2121 struct kinfo_proc *pi;
2122 #elif defined(PLATFORM_MACOSX)
2123 #if !(!defined (__mono_ppc__) && defined (TARGET_OSX))
2125 struct kinfo_proc *pi;
2126 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
2130 gchar *filename = NULL;
2135 #if defined(PLATFORM_SOLARIS)
2136 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
2137 if ((fp = fopen (filename, "r")) != NULL) {
2141 nread = fread (&info, sizeof (info), 1, fp);
2143 ret = g_strdup (info.pr_fname);
2149 #elif defined(PLATFORM_MACOSX)
2150 #if !defined (__mono_ppc__) && defined (TARGET_OSX)
2151 /* No proc name on OSX < 10.5 nor ppc nor iOS */
2152 memset (buf, '\0', sizeof(buf));
2153 proc_name (pid, buf, sizeof(buf));
2154 if (strlen (buf) > 0)
2155 ret = g_strdup (buf);
2157 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0)
2160 if ((pi = malloc(size)) == NULL)
2163 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
2164 if (errno == ENOMEM) {
2166 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__);
2171 if (strlen (pi->kp_proc.p_comm) > 0)
2172 ret = g_strdup (pi->kp_proc.p_comm);
2176 #elif defined(__OpenBSD__)
2178 mib [1] = KERN_PROC;
2179 mib [2] = KERN_PROC_PID;
2181 mib [4] = sizeof(struct kinfo_proc);
2185 if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0)
2188 if ((pi = malloc(size)) == NULL)
2191 mib[5] = (int)(size / sizeof(struct kinfo_proc));
2193 if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
2194 (size != sizeof (struct kinfo_proc))) {
2195 if (errno == ENOMEM) {
2202 if (strlen (pi->p_comm) > 0)
2203 ret = g_strdup (pi->p_comm);
2206 #elif defined(__HAIKU__)
2207 image_info imageInfo;
2210 if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
2211 ret = g_strdup (imageInfo.name);
2214 memset (buf, '\0', sizeof(buf));
2215 filename = g_strdup_printf ("/proc/%d/exe", pid);
2216 if (readlink (filename, buf, 255) > 0) {
2217 ret = g_strdup (buf);
2225 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
2226 if ((fp = fopen (filename, "r")) != NULL) {
2227 if (fgets (buf, 256, fp) != NULL) {
2228 ret = g_strdup (buf);
2239 filename = g_strdup_printf ("/proc/%d/stat", pid);
2240 if ((fp = fopen (filename, "r")) != NULL) {
2241 if (fgets (buf, 256, fp) != NULL) {
2244 start = strchr (buf, '(');
2245 if (start != NULL) {
2246 end = strchr (start + 1, ')');
2249 ret = g_strndup (start + 1,
2264 * wapi_process_get_path:
2266 * Return the full path of the executable of the process PID, or NULL if it cannot be determined.
2267 * Returns malloc-ed memory.
2270 wapi_process_get_path (pid_t pid)
2272 #if defined(PLATFORM_MACOSX) && !defined(__mono_ppc__) && defined(TARGET_OSX)
2273 gchar buf [PROC_PIDPATHINFO_MAXSIZE];
2276 res = proc_pidpath (pid, buf, sizeof (buf));
2279 if (buf [0] == '\0')
2281 return g_strdup (buf);
2283 return get_process_name_from_proc (pid);
2288 * wapi_process_set_cli_launcher:
2290 * Set the full path of the runtime executable used to launch managed exe's.
2293 wapi_process_set_cli_launcher (char *path)
2295 g_free (cli_launcher);
2296 cli_launcher = path ? g_strdup (path) : NULL;
2299 static guint32 get_module_name (gpointer process, gpointer module,
2300 gunichar2 *basename, guint32 size,
2303 struct _WapiHandle_process *process_handle;
2306 gunichar2 *procname;
2307 gchar *procname_ext = NULL;
2310 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2313 GSList *mods = NULL;
2314 WapiProcModule *found_module;
2317 gchar *proc_name = NULL;
2319 mono_once (&process_current_once, process_set_current);
2321 DEBUG ("%s: Getting module base name, process handle %p module %p",
2322 __func__, process, module);
2324 size = size*sizeof(gunichar2); /* adjust for unicode characters */
2326 if (basename == NULL || size == 0) {
2330 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2331 /* This is a pseudo handle */
2332 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2333 proc_name = get_process_name_from_proc (pid);
2335 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2336 (gpointer *)&process_handle);
2338 DEBUG ("%s: Can't find process %p", __func__,
2343 pid = process_handle->id;
2344 proc_name = g_strdup (process_handle->proc_name);
2347 /* Look up the address in /proc/<pid>/maps */
2348 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2350 mods = load_modules ();
2352 if ((fp = open_process_map (pid, "r")) == NULL) {
2353 if (errno == EACCES && module == NULL && base == TRUE) {
2354 procname_ext = get_process_name_from_proc (pid);
2356 /* No /proc/<pid>/maps, so just return failure
2363 mods = load_modules (fp);
2366 count = g_slist_length (mods);
2368 /* If module != NULL compare the address.
2369 * If module == NULL we are looking for the main module.
2370 * The best we can do for now check it the module name end with the process name.
2372 for (i = 0; i < count; i++) {
2373 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2374 if (procname_ext == NULL &&
2375 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2376 (module != NULL && found_module->address_start == module))) {
2378 procname_ext = g_path_get_basename (found_module->filename);
2380 procname_ext = g_strdup (found_module->filename);
2384 free_procmodule (found_module);
2387 if (procname_ext == NULL)
2389 /* If it's *still* null, we might have hit the
2390 * case where reading /proc/$pid/maps gives an
2391 * empty file for this user.
2393 procname_ext = get_process_name_from_proc (pid);
2396 g_slist_free (mods);
2400 if (procname_ext != NULL) {
2401 DEBUG ("%s: Process name is [%s]", __func__,
2404 procname = mono_unicode_from_external (procname_ext, &bytes);
2405 if (procname == NULL) {
2407 g_free (procname_ext);
2413 /* Add the terminator */
2417 DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2419 memcpy (basename, procname, size);
2421 DEBUG ("%s: Size %d larger than needed (%ld)",
2422 __func__, size, bytes);
2424 memcpy (basename, procname, bytes);
2428 g_free (procname_ext);
2436 guint32 GetModuleBaseName (gpointer process, gpointer module,
2437 gunichar2 *basename, guint32 size)
2439 return(get_module_name (process, module, basename, size, TRUE));
2442 guint32 GetModuleFileNameEx (gpointer process, gpointer module,
2443 gunichar2 *filename, guint32 size)
2445 return(get_module_name (process, module, filename, size, FALSE));
2448 gboolean GetModuleInformation (gpointer process, gpointer module,
2449 WapiModuleInfo *modinfo, guint32 size)
2451 struct _WapiHandle_process *process_handle;
2454 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2457 GSList *mods = NULL;
2458 WapiProcModule *found_module;
2461 gboolean ret = FALSE;
2462 gchar *proc_name = NULL;
2464 mono_once (&process_current_once, process_set_current);
2466 DEBUG ("%s: Getting module info, process handle %p module %p",
2467 __func__, process, module);
2469 if (modinfo == NULL || size < sizeof(WapiModuleInfo)) {
2473 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2474 /* This is a pseudo handle */
2475 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2476 proc_name = get_process_name_from_proc (pid);
2478 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2479 (gpointer *)&process_handle);
2481 DEBUG ("%s: Can't find process %p", __func__,
2486 pid = process_handle->id;
2487 proc_name = g_strdup (process_handle->proc_name);
2490 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2492 mods = load_modules ();
2494 /* Look up the address in /proc/<pid>/maps */
2495 if ((fp = open_process_map (pid, "r")) == NULL) {
2496 /* No /proc/<pid>/maps, so just return failure
2502 mods = load_modules (fp);
2505 count = g_slist_length (mods);
2507 /* If module != NULL compare the address.
2508 * If module == NULL we are looking for the main module.
2509 * The best we can do for now check it the module name end with the process name.
2511 for (i = 0; i < count; i++) {
2512 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2513 if ( ret == FALSE &&
2514 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2515 (module != NULL && found_module->address_start == module))) {
2516 modinfo->lpBaseOfDll = found_module->address_start;
2517 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2518 modinfo->EntryPoint = found_module->address_offset;
2522 free_procmodule (found_module);
2525 g_slist_free (mods);
2532 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2534 struct _WapiHandle_process *process_handle;
2537 mono_once (&process_current_once, process_set_current);
2539 if(min==NULL || max==NULL) {
2540 /* Not sure if w32 allows NULLs here or not */
2544 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2545 /* This is a pseudo handle, so just fail for now
2550 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2551 (gpointer *)&process_handle);
2553 DEBUG ("%s: Can't find process %p", __func__, process);
2558 *min=process_handle->min_working_set;
2559 *max=process_handle->max_working_set;
2564 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2566 struct _WapiHandle_process *process_handle;
2569 mono_once (&process_current_once, process_set_current);
2571 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2572 /* This is a pseudo handle, so just fail for now
2577 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2578 (gpointer *)&process_handle);
2580 DEBUG ("%s: Can't find process %p", __func__, process);
2585 process_handle->min_working_set=min;
2586 process_handle->max_working_set=max;
2593 TerminateProcess (gpointer process, gint32 exitCode)
2595 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 DEBUG ("%s: Can't find process %p", __func__,
2611 SetLastError (ERROR_INVALID_HANDLE);
2614 pid = process_handle->id;
2617 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2618 ret = kill (pid, signo);
2622 SetLastError (ERROR_INVALID_PARAMETER);
2625 SetLastError (ERROR_ACCESS_DENIED);
2628 SetLastError (ERROR_PROC_NOT_FOUND);
2631 SetLastError (ERROR_GEN_FAILURE);
2639 GetPriorityClass (gpointer process)
2641 #ifdef HAVE_GETPRIORITY
2642 struct _WapiHandle_process *process_handle;
2647 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2648 /* This is a pseudo handle */
2649 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2651 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2652 (gpointer *) &process_handle);
2655 SetLastError (ERROR_INVALID_HANDLE);
2658 pid = process_handle->id;
2662 ret = getpriority (PRIO_PROCESS, pid);
2663 if (ret == -1 && errno != 0) {
2667 SetLastError (ERROR_ACCESS_DENIED);
2670 SetLastError (ERROR_PROC_NOT_FOUND);
2673 SetLastError (ERROR_GEN_FAILURE);
2679 return NORMAL_PRIORITY_CLASS;
2681 return REALTIME_PRIORITY_CLASS;
2683 return HIGH_PRIORITY_CLASS;
2685 return ABOVE_NORMAL_PRIORITY_CLASS;
2687 return IDLE_PRIORITY_CLASS;
2689 return BELOW_NORMAL_PRIORITY_CLASS;
2691 return NORMAL_PRIORITY_CLASS;
2693 SetLastError (ERROR_NOT_SUPPORTED);
2699 SetPriorityClass (gpointer process, guint32 priority_class)
2701 #ifdef HAVE_SETPRIORITY
2702 struct _WapiHandle_process *process_handle;
2708 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2709 /* This is a pseudo handle */
2710 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2712 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2713 (gpointer *) &process_handle);
2716 SetLastError (ERROR_INVALID_HANDLE);
2719 pid = process_handle->id;
2722 switch (priority_class) {
2723 case IDLE_PRIORITY_CLASS:
2726 case BELOW_NORMAL_PRIORITY_CLASS:
2729 case NORMAL_PRIORITY_CLASS:
2732 case ABOVE_NORMAL_PRIORITY_CLASS:
2735 case HIGH_PRIORITY_CLASS:
2738 case REALTIME_PRIORITY_CLASS:
2742 SetLastError (ERROR_INVALID_PARAMETER);
2746 ret = setpriority (PRIO_PROCESS, pid, prio);
2751 SetLastError (ERROR_ACCESS_DENIED);
2754 SetLastError (ERROR_PROC_NOT_FOUND);
2757 SetLastError (ERROR_GEN_FAILURE);
2763 SetLastError (ERROR_NOT_SUPPORTED);
2769 mono_processes_cleanup (void)
2771 struct MonoProcess *mp;
2772 struct MonoProcess *prev = NULL;
2773 struct MonoProcess *candidate = NULL;
2774 gpointer unref_handle;
2777 DEBUG ("%s", __func__);
2779 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2780 if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
2783 mp = mono_processes;
2784 while (mp != NULL) {
2785 if (mp->pid == 0 && mp->handle != NULL) {
2786 /* This process has exited and we need to remove the artifical ref
2788 mono_mutex_lock (&mono_processes_mutex);
2789 unref_handle = mp->handle;
2791 mono_mutex_unlock (&mono_processes_mutex);
2793 _wapi_handle_unref (unref_handle);
2799 mp = mono_processes;
2801 while (mp != NULL) {
2802 if ((mp->handle_count == 0 && mp->pid == 0) || candidate != NULL) {
2804 _wapi_handle_spin (spin);
2808 /* We've found a candidate */
2809 mono_mutex_lock (&mono_processes_mutex);
2810 if (candidate == NULL) {
2812 if (mp == mono_processes) {
2813 mono_processes = mp->next;
2815 prev->next = mp->next;
2820 /* It's still safe to traverse the structure.*/
2821 mono_memory_barrier ();
2823 if (mono_processes_read_lock != 0) {
2824 /* The sigchld handler is watching us. Spin a bit and try again */
2827 } else if (spin >= 8) {
2828 /* Just give up for now */
2829 mono_mutex_unlock (&mono_processes_mutex);
2833 /* We've modified the list of processes, and we know the sigchld handler
2834 * isn't executing, so even if it executes at any moment, it'll see the
2835 * new version of the list. So now we can free the candidate. */
2836 DEBUG ("%s: freeing candidate %p", __func__, candidate);
2837 mp = candidate->next;
2838 MONO_SEM_DESTROY (&candidate->exit_sem);
2843 mono_mutex_unlock (&mono_processes_mutex);
2852 DEBUG ("%s done", __func__);
2854 InterlockedDecrement (&mono_processes_cleaning_up);
2858 process_close (gpointer handle, gpointer data)
2860 struct _WapiHandle_process *process_handle;
2862 DEBUG ("%s", __func__);
2864 process_handle = (struct _WapiHandle_process *) data;
2865 if (process_handle->mono_process && process_handle->self == _wapi_getpid ())
2866 InterlockedDecrement (&process_handle->mono_process->handle_count);
2867 mono_processes_cleanup ();
2871 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
2875 struct MonoProcess *p;
2878 fprintf (stdout, "SIG CHILD handler for pid: %i\n", info->si_pid);
2881 InterlockedIncrement (&mono_processes_read_lock);
2885 pid = waitpid (-1, &status, WNOHANG);
2886 } while (pid == -1 && errno == EINTR);
2892 fprintf (stdout, "child ended: %i", pid);
2896 if (p->pid == pid) {
2897 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2899 MONO_SEM_POST (&p->exit_sem);
2906 InterlockedDecrement (&mono_processes_read_lock);
2909 fprintf (stdout, "SIG CHILD handler: done looping.");
2915 static void process_add_sigchld_handler (void)
2918 struct sigaction sa;
2920 sa.sa_sigaction = mono_sigchld_signal_handler;
2921 sigemptyset (&sa.sa_mask);
2922 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2923 g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2924 DEBUG ("Added SIGCHLD handler");
2928 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2930 struct _WapiHandle_process *process_handle;
2936 struct MonoProcess *mp;
2938 gpointer current_thread;
2940 current_thread = wapi_get_current_thread_handle ();
2941 if (current_thread == NULL) {
2942 SetLastError (ERROR_INVALID_HANDLE);
2946 /* FIXME: We can now easily wait on processes that aren't our own children,
2947 * but WaitFor*Object won't call us for pseudo handles. */
2948 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2950 DEBUG ("%s (%p, %u)", __func__, handle, timeout);
2952 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS, (gpointer *)&process_handle);
2954 g_warning ("%s: error looking up process handle %p", __func__, handle);
2958 if (process_handle->exited) {
2959 /* We've already done this one */
2960 DEBUG ("%s (%p, %u): Process already exited", __func__, handle, timeout);
2961 return WAIT_OBJECT_0;
2964 pid = process_handle->id;
2966 DEBUG ("%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2968 /* We don't need to lock mono_processes here, the entry
2969 * has a handle_count > 0 which means it will not be freed. */
2970 mp = process_handle->mono_process;
2971 if (mp && process_handle->self != _wapi_getpid ()) {
2972 /* mono_process points to memory in another process' address space: we can't use it */
2976 start = mono_msec_ticks ();
2982 /* We have a semaphore we can wait on */
2983 if (timeout != INFINITE) {
2984 DEBUG ("%s (%p, %u): waiting on semaphore for %li ms...",
2985 __func__, handle, timeout, (timeout - (now - start)));
2987 ret = MONO_SEM_TIMEDWAIT_ALERTABLE (&mp->exit_sem, (timeout - (now - start)), alertable);
2989 DEBUG ("%s (%p, %u): waiting on semaphore forever...",
2990 __func__, handle, timeout);
2991 ret = MONO_SEM_WAIT_ALERTABLE (&mp->exit_sem, alertable);
2994 if (ret == -1 && errno != EINTR && errno != ETIMEDOUT) {
2995 DEBUG ("%s (%p, %u): sem_timedwait failure: %s",
2996 __func__, handle, timeout, g_strerror (errno));
2997 /* Should we return a failure here? */
3001 /* Success, process has exited */
3002 MONO_SEM_POST (&mp->exit_sem);
3006 /* We did not create this process, so we can't waidpid / sem_wait it.
3007 * We need to poll for the pid existence */
3008 DEBUG ("%s (%p, %u): polling on pid...", __func__, handle, timeout);
3009 if (!is_pid_valid (pid)) {
3010 /* Success, process has exited */
3016 DEBUG ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
3017 return WAIT_TIMEOUT;
3020 now = mono_msec_ticks ();
3021 if (now - start >= timeout) {
3022 DEBUG ("%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
3023 return WAIT_TIMEOUT;
3027 /* "timeout - (now - start)" will not underflow, since timeout is always >=0,
3028 * and we passed the check just above */
3029 _wapi_handle_spin (MIN (100, timeout - (now - start)));
3032 if (alertable && _wapi_thread_apc_pending (current_thread)) {
3033 DEBUG ("%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
3034 return WAIT_IO_COMPLETION;
3038 /* Process must have exited */
3039 DEBUG ("%s (%p, %u): Waited successfully", __func__, handle, timeout);
3041 ret = _wapi_handle_lock_shared_handles ();
3042 g_assert (ret == 0);
3044 status = mp ? mp->status : 0;
3045 if (WIFSIGNALED (status)) {
3046 process_handle->exitstatus = 128 + WTERMSIG (status);
3048 process_handle->exitstatus = WEXITSTATUS (status);
3050 _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
3052 process_handle->exited = TRUE;
3054 DEBUG ("%s (%p, %u): Setting pid %d signalled, exit status %d",
3055 __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
3057 _wapi_shared_handle_set_signal_state (handle, TRUE);
3059 _wapi_handle_unlock_shared_handles ();
3061 return WAIT_OBJECT_0;
3065 wapi_processes_cleanup (void)
3067 g_free (cli_launcher);