2 * processes.c: Process handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002-2011 Novell, Inc.
8 * Copyright 2011 Xamarin Inc
19 #include <sys/types.h>
25 #include <sys/resource.h>
27 #include <sys/param.h>
30 #ifdef HAVE_SYS_MKDEV_H
31 #include <sys/mkdev.h>
34 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
36 #include <TargetConditionals.h>
37 #include <sys/resource.h>
44 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
46 #include <sys/sysctl.h>
47 # if !defined(__OpenBSD__)
48 # include <sys/utsname.h>
52 #ifdef PLATFORM_SOLARIS
53 /* procfs.h cannot be included if this define is set, but it seems to work fine if it is undefined */
54 #if _FILE_OFFSET_BITS == 64
55 #undef _FILE_OFFSET_BITS
57 #define _FILE_OFFSET_BITS 64
64 #include <KernelKit.h>
67 #include <mono/io-layer/wapi.h>
68 #include <mono/io-layer/wapi-private.h>
69 #include <mono/io-layer/handles-private.h>
70 #include <mono/io-layer/misc-private.h>
71 #include <mono/io-layer/process-private.h>
72 #include <mono/io-layer/threads.h>
73 #include <mono/utils/strenc.h>
74 #include <mono/utils/mono-path.h>
75 #include <mono/io-layer/timefuncs-private.h>
76 #include <mono/utils/mono-time.h>
77 #include <mono/utils/mono-membar.h>
78 #include <mono/utils/mono-mutex.h>
79 #include <mono/utils/mono-signal-handler.h>
81 /* The process' environment strings */
82 #if defined(__APPLE__) && !defined (__arm__)
83 /* Apple defines this in crt_externs.h but doesn't provide that header for
84 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
85 * in fact exist on all implementations (so far)
87 gchar ***_NSGetEnviron(void);
88 #define environ (*_NSGetEnviron())
90 extern char **environ;
94 #define DEBUG(...) g_message(__VA_ARGS__)
95 #define DEBUG_ENABLED 1
100 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable);
101 static void process_close (gpointer handle, gpointer data);
102 static gboolean is_pid_valid (pid_t pid);
104 #if !defined(__OpenBSD__)
106 open_process_map (int pid, const char *mode);
109 struct _WapiHandleOps _wapi_process_ops = {
110 process_close, /* close_shared */
114 process_wait, /* special_wait */
119 static struct sigaction previous_chld_sa;
121 static mono_once_t process_sig_chld_once = MONO_ONCE_INIT;
122 static void process_add_sigchld_handler (void);
124 /* The signal-safe logic to use mono_processes goes like this:
125 * - The list must be safe to traverse for the signal handler at all times.
126 * It's safe to: prepend an entry (which is a single store to 'mono_processes'),
127 * unlink an entry (assuming the unlinked entry isn't freed and doesn't
128 * change its 'next' pointer so that it can still be traversed).
129 * When cleaning up we first unlink an entry, then we verify that
130 * the read lock isn't locked. Then we can free the entry, since
131 * we know that nobody is using the old version of the list (including
132 * the unlinked entry).
133 * We also need to lock when adding and cleaning up so that those two
134 * operations don't mess with eachother. (This lock is not used in the
137 static struct MonoProcess *mono_processes = NULL;
138 static volatile gint32 mono_processes_read_lock = 0;
139 static volatile gint32 mono_processes_cleaning_up = 0;
140 static mono_mutex_t mono_processes_mutex;
141 static void mono_processes_cleanup (void);
143 static mono_once_t process_current_once=MONO_ONCE_INIT;
144 static gpointer current_process=NULL;
145 static char *cli_launcher;
147 static mono_once_t process_ops_once=MONO_ONCE_INIT;
149 static void process_ops_init (void)
151 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
152 WAPI_HANDLE_CAP_WAIT |
153 WAPI_HANDLE_CAP_SPECIAL_WAIT);
157 /* Check if a pid is valid - i.e. if a process exists with this pid. */
158 static gboolean is_pid_valid (pid_t pid)
160 gboolean result = FALSE;
162 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
163 if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
165 #elif defined(__HAIKU__)
167 if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
170 gchar *dir = g_strdup_printf ("/proc/%d", pid);
171 if (!access (dir, F_OK))
179 static void process_set_defaults (struct _WapiHandle_process *process_handle)
181 /* These seem to be the defaults on w2k */
182 process_handle->min_working_set = 204800;
183 process_handle->max_working_set = 1413120;
185 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
189 len16 (const gunichar2 *str)
200 utf16_concat (const gunichar2 *first, ...)
207 va_start (args, first);
208 total += len16 (first);
209 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
214 ret = g_new (gunichar2, total + 1);
220 for (s = first; *s != 0; s++)
222 va_start (args, first);
223 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
226 for (p = s; *p != 0; p++)
234 #ifdef PLATFORM_MACOSX
236 /* 0 = no detection; -1 = not 10.5 or higher; 1 = 10.5 or higher */
237 static int osx_10_5_or_higher;
240 detect_osx_10_5_or_higher (void)
246 if (uname (&u) != 0){
247 osx_10_5_or_higher = 1;
255 osx_10_5_or_higher = -1;
257 osx_10_5_or_higher = 1;
261 is_macos_10_5_or_higher (void)
263 if (osx_10_5_or_higher == 0)
264 detect_osx_10_5_or_higher ();
266 return (osx_10_5_or_higher == 1);
270 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
271 static const gunichar2 *utf16_space = utf16_space_bytes;
272 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
273 static const gunichar2 *utf16_quote = utf16_quote_bytes;
278 print_utf16 (gunichar2 *str)
282 res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
283 g_print ("%s\n", res);
288 /* Implemented as just a wrapper around CreateProcess () */
289 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
292 WapiProcessInformation process_info;
296 /* w2k just segfaults here, but we can do better than
299 SetLastError (ERROR_INVALID_PARAMETER);
303 if (sei->lpFile == NULL) {
304 /* w2k returns TRUE for this, for some reason. */
308 /* Put both executable and parameters into the second argument
309 * to CreateProcess (), so it searches $PATH. The conversion
310 * into and back out of utf8 is because there is no
311 * g_strdup_printf () equivalent for gunichar2 :-(
313 args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
315 SetLastError (ERROR_INVALID_DATA);
318 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
319 CREATE_UNICODE_ENVIRONMENT, NULL,
320 sei->lpDirectory, NULL, &process_info);
323 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
327 static char *handler;
328 static gunichar2 *handler_utf16;
330 if (handler_utf16 == (gunichar2 *)-1)
333 #ifdef PLATFORM_MACOSX
334 handler = g_strdup ("/usr/bin/open");
337 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
338 * if that fails, try to use gnome-open, then kfmclient
340 handler = g_find_program_in_path ("xdg-open");
341 if (handler == NULL){
342 handler = g_find_program_in_path ("gnome-open");
343 if (handler == NULL){
344 handler = g_find_program_in_path ("kfmclient");
345 if (handler == NULL){
346 handler_utf16 = (gunichar2 *) -1;
349 /* kfmclient needs exec argument */
351 handler = g_strconcat (old, " exec",
358 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
361 /* Put quotes around the filename, in case it's a url
362 * that contains #'s (CreateProcess() calls
363 * g_shell_parse_argv(), which deliberately throws
364 * away anything after an unquoted #). Fixes bug
367 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
368 sei->lpFile, utf16_quote,
369 sei->lpParameters == NULL ? NULL : utf16_space,
370 sei->lpParameters, NULL);
372 SetLastError (ERROR_INVALID_DATA);
375 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
376 CREATE_UNICODE_ENVIRONMENT, NULL,
377 sei->lpDirectory, NULL, &process_info);
380 if (GetLastError () != ERROR_OUTOFMEMORY)
381 SetLastError (ERROR_INVALID_DATA);
384 /* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
385 CloseHandle (process_info.hProcess);
386 process_info.hProcess = NULL;
389 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
390 sei->hProcess = process_info.hProcess;
392 CloseHandle (process_info.hProcess);
399 is_managed_binary (const gchar *filename)
401 int original_errno = errno;
402 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
403 int file = open (filename, O_RDONLY | O_LARGEFILE);
405 int file = open (filename, O_RDONLY);
408 unsigned char buffer[8];
409 off_t file_size, optional_header_offset;
410 off_t pe_header_offset;
411 gboolean managed = FALSE;
413 guint32 first_word, second_word;
415 /* If we are unable to open the file, then we definitely
416 * can't say that it is managed. The child mono process
417 * probably wouldn't be able to open it anyway.
420 errno = original_errno;
424 /* Retrieve the length of the file for future sanity checks. */
425 file_size = lseek (file, 0, SEEK_END);
426 lseek (file, 0, SEEK_SET);
428 /* We know we need to read a header field at offset 60. */
432 num_read = read (file, buffer, 2);
434 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
437 new_offset = lseek (file, 60, SEEK_SET);
439 if (new_offset != 60)
442 num_read = read (file, buffer, 4);
446 pe_header_offset = buffer[0]
451 if (pe_header_offset + 24 > file_size)
454 new_offset = lseek (file, pe_header_offset, SEEK_SET);
456 if (new_offset != pe_header_offset)
459 num_read = read (file, buffer, 4);
461 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
465 * Verify that the header we want in the optional header data
466 * is present in this binary.
468 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
470 if (new_offset != pe_header_offset + 20)
473 num_read = read (file, buffer, 2);
475 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
478 /* Read the CLR header address and size fields. These will be
479 * zero if the binary is not managed.
481 optional_header_offset = pe_header_offset + 24;
482 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
484 if (new_offset != optional_header_offset + 208)
487 num_read = read (file, buffer, 8);
489 /* We are not concerned with endianness, only with
490 * whether it is zero or not.
492 first_word = *(guint32 *)&buffer[0];
493 second_word = *(guint32 *)&buffer[4];
495 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
502 errno = original_errno;
506 gboolean CreateProcessWithLogonW (const gunichar2 *username,
507 const gunichar2 *domain,
508 const gunichar2 *password,
509 const guint32 logonFlags,
510 const gunichar2 *appname,
511 const gunichar2 *cmdline,
512 guint32 create_flags,
514 const gunichar2 *cwd,
515 WapiStartupInfo *startup,
516 WapiProcessInformation *process_info)
518 /* FIXME: use user information */
519 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
523 is_executable (const char *prog)
526 if (access (prog, X_OK) != 0)
528 if (stat (prog, &buf))
530 if (S_ISREG (buf.st_mode))
536 switchDirectorySeparators(gchar *path)
538 size_t i, pathLength = strlen(path);
540 /* Turn all the slashes round the right way, except for \' */
541 /* There are probably other characters that need to be excluded as well. */
542 for (i = 0; i < pathLength; i++)
544 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' ) {
550 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
551 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
552 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
553 gboolean inherit_handles, guint32 create_flags,
554 gpointer new_environ, const gunichar2 *cwd,
555 WapiStartupInfo *startup,
556 WapiProcessInformation *process_info)
558 gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
559 guint32 i, env_count = 0;
560 gboolean ret = FALSE;
562 struct _WapiHandle_process process_handle = {0}, *process_handle_data;
564 int in_fd, out_fd, err_fd;
567 int startup_pipe [2] = {-1, -1};
569 struct MonoProcess *mono_process;
570 gboolean fork_failed = FALSE;
572 mono_once (&process_ops_once, process_ops_init);
573 mono_once (&process_sig_chld_once, process_add_sigchld_handler);
575 /* appname and cmdline specify the executable and its args:
577 * If appname is not NULL, it is the name of the executable.
578 * Otherwise the executable is the first token in cmdline.
580 * Executable searching:
582 * If appname is not NULL, it can specify the full path and
583 * file name, or else a partial name and the current directory
584 * will be used. There is no additional searching.
586 * If appname is NULL, the first whitespace-delimited token in
587 * cmdline is used. If the name does not contain a full
588 * directory path, the search sequence is:
590 * 1) The directory containing the current process
591 * 2) The current working directory
592 * 3) The windows system directory (Ignored)
593 * 4) The windows directory (Ignored)
596 * Just to make things more interesting, tokens can contain
597 * white space if they are surrounded by quotation marks. I'm
598 * beginning to understand just why windows apps are generally
599 * so crap, with an API like this :-(
601 if (appname != NULL) {
602 cmd = mono_unicode_to_external (appname);
604 DEBUG ("%s: unicode conversion returned NULL",
607 SetLastError (ERROR_PATH_NOT_FOUND);
611 switchDirectorySeparators(cmd);
614 if (cmdline != NULL) {
615 args = mono_unicode_to_external (cmdline);
617 DEBUG ("%s: unicode conversion returned NULL", __func__);
619 SetLastError (ERROR_PATH_NOT_FOUND);
625 dir = mono_unicode_to_external (cwd);
627 DEBUG ("%s: unicode conversion returned NULL", __func__);
629 SetLastError (ERROR_PATH_NOT_FOUND);
633 /* Turn all the slashes round the right way */
634 switchDirectorySeparators(dir);
638 /* We can't put off locating the executable any longer :-( */
641 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
642 /* Strip off the drive letter. I can't
643 * believe that CP/M holdover is still
646 g_memmove (cmd, cmd+2, strlen (cmd)-2);
647 cmd[strlen (cmd)-2] = '\0';
650 unquoted = g_shell_unquote (cmd, NULL);
651 if (unquoted[0] == '/') {
652 /* Assume full path given */
653 prog = g_strdup (unquoted);
655 /* Executable existing ? */
656 if (!is_executable (prog)) {
657 DEBUG ("%s: Couldn't find executable %s",
660 SetLastError (ERROR_FILE_NOT_FOUND);
664 /* Search for file named by cmd in the current
667 char *curdir = g_get_current_dir ();
669 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
672 /* And make sure it's executable */
673 if (!is_executable (prog)) {
674 DEBUG ("%s: Couldn't find executable %s",
677 SetLastError (ERROR_FILE_NOT_FOUND);
683 args_after_prog = args;
688 /* Dig out the first token from args, taking quotation
692 /* First, strip off all leading whitespace */
693 args = g_strchug (args);
695 /* args_after_prog points to the contents of args
696 * after token has been set (otherwise argv[0] is
699 args_after_prog = args;
701 /* Assume the opening quote will always be the first
704 if (args[0] == '\"' || args [0] == '\'') {
706 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
707 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
708 /* We found the first token */
709 token = g_strndup (args+1, i-1);
710 args_after_prog = g_strchug (args + i + 1);
712 /* Quotation mark appeared in the
713 * middle of the token. Just give the
714 * whole first token, quotes and all,
721 /* No quote mark, or malformed */
722 for (i = 0; args[i] != '\0'; i++) {
723 if (g_ascii_isspace (args[i])) {
724 token = g_strndup (args, i);
725 args_after_prog = args + i + 1;
731 if (token == NULL && args[0] != '\0') {
732 /* Must be just one token in the string */
733 token = g_strdup (args);
734 args_after_prog = NULL;
739 DEBUG ("%s: Couldn't find what to exec", __func__);
741 SetLastError (ERROR_PATH_NOT_FOUND);
745 /* Turn all the slashes round the right way. Only for
748 switchDirectorySeparators(token);
750 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
751 /* Strip off the drive letter. I can't
752 * believe that CP/M holdover is still
755 g_memmove (token, token+2, strlen (token)-2);
756 token[strlen (token)-2] = '\0';
759 if (token[0] == '/') {
760 /* Assume full path given */
761 prog = g_strdup (token);
763 /* Executable existing ? */
764 if (!is_executable (prog)) {
765 DEBUG ("%s: Couldn't find executable %s",
768 SetLastError (ERROR_FILE_NOT_FOUND);
773 char *curdir = g_get_current_dir ();
775 /* FIXME: Need to record the directory
776 * containing the current process, and check
777 * that for the new executable as the first
781 prog = g_strdup_printf ("%s/%s", curdir, token);
784 /* I assume X_OK is the criterion to use,
787 if (!is_executable (prog)) {
789 prog = g_find_program_in_path (token);
791 DEBUG ("%s: Couldn't find executable %s", __func__, token);
794 SetLastError (ERROR_FILE_NOT_FOUND);
803 DEBUG ("%s: Exec prog [%s] args [%s]", __func__, prog,
806 /* Check for CLR binaries; if found, we will try to invoke
807 * them using the same mono binary that started us.
809 if (is_managed_binary (prog)) {
810 gunichar2 *newapp = NULL, *newcmd;
814 newapp = mono_unicode_from_external (cli_launcher, &bytes_ignored);
816 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
818 if (newapp != NULL) {
819 if (appname != NULL) {
820 newcmd = utf16_concat (newapp, utf16_space,
821 appname, utf16_space,
824 newcmd = utf16_concat (newapp, utf16_space,
828 g_free ((gunichar2 *)newapp);
830 if (newcmd != NULL) {
831 ret = CreateProcess (NULL, newcmd,
835 create_flags, new_environ,
839 g_free ((gunichar2 *)newcmd);
846 if (args_after_prog != NULL && *args_after_prog) {
849 qprog = g_shell_quote (prog);
850 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
853 full_prog = g_shell_quote (prog);
856 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
858 g_message ("CreateProcess: %s\n", gerr->message);
864 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
865 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
866 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
867 err_fd = GPOINTER_TO_UINT (startup->hStdError);
869 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
870 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
871 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
874 g_strlcpy (process_handle.proc_name, prog,
875 _WAPI_PROC_NAME_MAX_LEN - 1);
877 process_set_defaults (&process_handle);
879 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
880 if (handle == _WAPI_HANDLE_INVALID) {
881 g_warning ("%s: error creating process handle", __func__);
884 SetLastError (ERROR_OUTOFMEMORY);
888 /* new_environ is a block of NULL-terminated strings, which
889 * is itself NULL-terminated. Of course, passing an array of
890 * string pointers would have made things too easy :-(
892 * If new_environ is not NULL it specifies the entire set of
893 * environment variables in the new process. Otherwise the
894 * new process inherits the same environment.
896 if (new_environ != NULL) {
897 gunichar2 *new_environp;
899 /* Count the number of strings */
900 for (new_environp = (gunichar2 *)new_environ; *new_environp;
903 while (*new_environp) {
908 /* +2: one for the process handle value, and the last
911 env_strings = g_new0 (gchar *, env_count + 2);
913 /* Copy each environ string into 'strings' turning it
914 * into utf8 (or the requested encoding) at the same
918 for (new_environp = (gunichar2 *)new_environ; *new_environp;
920 env_strings[env_count] = mono_unicode_to_external (new_environp);
922 while (*new_environp) {
927 for (i = 0; environ[i] != NULL; i++) {
931 /* +2: one for the process handle value, and the last
934 env_strings = g_new0 (gchar *, env_count + 2);
936 /* Copy each environ string into 'strings' turning it
937 * into utf8 (or the requested encoding) at the same
941 for (i = 0; environ[i] != NULL; i++) {
942 env_strings[env_count] = g_strdup (environ[i]);
946 /* pass process handle info to the child, so it doesn't have
947 * to do an expensive search over the whole list
949 if (env_strings != NULL) {
950 struct _WapiHandleUnshared *handle_data;
951 struct _WapiHandle_shared_ref *ref;
953 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
954 ref = &handle_data->u.shared;
956 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
959 /* Create a pipe to make sure the child doesn't exit before
960 * we can add the process to the linked list of mono_processes */
961 if (pipe (startup_pipe) == -1) {
962 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
963 * This is just for a very hard to hit race condition in the first place */
964 startup_pipe [0] = startup_pipe [1] = -1;
965 DEBUG ("%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
968 thr_ret = _wapi_handle_lock_shared_handles ();
969 g_assert (thr_ret == 0);
974 SetLastError (ERROR_OUTOFMEMORY);
978 } else if (pid == 0) {
981 if (startup_pipe [0] != -1) {
982 /* Wait until the parent has updated it's internal data */
983 ssize_t _i G_GNUC_UNUSED = read (startup_pipe [0], &dummy, 1);
984 DEBUG ("%s: child: parent has completed its setup", __func__);
985 close (startup_pipe [0]);
986 close (startup_pipe [1]);
989 /* should we detach from the process group? */
991 /* Connect stdin, stdout and stderr */
996 if (inherit_handles != TRUE) {
997 /* FIXME: do something here */
1000 /* Close all file descriptors */
1001 for (i = getdtablesize () - 1; i > 2; i--) {
1005 #ifdef DEBUG_ENABLED
1006 DEBUG ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1008 for (i = 0; argv[i] != NULL; i++) {
1009 g_message ("arg %d: [%s]", i, argv[i]);
1012 for (i = 0; env_strings[i] != NULL; i++) {
1013 g_message ("env %d: [%s]", i, env_strings[i]);
1018 if (dir != NULL && chdir (dir) == -1) {
1024 execve (argv[0], argv, env_strings);
1031 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1032 (gpointer *)&process_handle_data);
1034 g_warning ("%s: error looking up process handle %p", __func__,
1036 _wapi_handle_unref (handle);
1040 process_handle_data->id = pid;
1042 /* Add our mono_process into the linked list of mono_processes */
1043 mono_process = (struct MonoProcess *) g_malloc0 (sizeof (struct MonoProcess));
1044 mono_process->pid = pid;
1045 mono_process->handle_count = 1;
1046 if (MONO_SEM_INIT (&mono_process->exit_sem, 0) != 0) {
1047 /* If we can't create the exit semaphore, we just don't add anything
1048 * to our list of mono processes. Waiting on the process will return
1050 g_warning ("%s: could not create exit semaphore for process.", strerror (errno));
1051 g_free (mono_process);
1053 /* Keep the process handle artificially alive until the process
1054 * exits so that the information in the handle isn't lost. */
1055 _wapi_handle_ref (handle);
1056 mono_process->handle = handle;
1058 process_handle_data->self = _wapi_getpid ();
1059 process_handle_data->mono_process = mono_process;
1061 mono_mutex_lock (&mono_processes_mutex);
1062 mono_process->next = mono_processes;
1063 mono_processes = mono_process;
1064 mono_mutex_unlock (&mono_processes_mutex);
1067 if (process_info != NULL) {
1068 process_info->hProcess = handle;
1069 process_info->dwProcessId = pid;
1071 /* FIXME: we might need to handle the thread info some
1074 process_info->hThread = INVALID_HANDLE_VALUE;
1075 process_info->dwThreadId = 0;
1079 _wapi_handle_unlock_shared_handles ();
1082 _wapi_handle_unref (handle);
1084 if (startup_pipe [1] != -1) {
1085 /* Write 1 byte, doesn't matter what */
1086 ssize_t _i G_GNUC_UNUSED = write (startup_pipe [1], startup_pipe, 1);
1087 close (startup_pipe [0]);
1088 close (startup_pipe [1]);
1095 if (full_prog != NULL) {
1107 if(env_strings != NULL) {
1108 g_strfreev (env_strings);
1114 DEBUG ("%s: returning handle %p for pid %d", __func__, handle,
1117 /* Check if something needs to be cleaned up. */
1118 mono_processes_cleanup ();
1123 static void process_set_name (struct _WapiHandle_process *process_handle)
1125 gchar *progname, *utf8_progname, *slash;
1127 progname=g_get_prgname ();
1128 utf8_progname=mono_utf8_from_external (progname);
1130 DEBUG ("%s: using [%s] as prog name", __func__, progname);
1132 if(utf8_progname!=NULL) {
1133 slash=strrchr (utf8_progname, '/');
1135 g_strlcpy (process_handle->proc_name, slash+1,
1136 _WAPI_PROC_NAME_MAX_LEN - 1);
1138 g_strlcpy (process_handle->proc_name, utf8_progname,
1139 _WAPI_PROC_NAME_MAX_LEN - 1);
1142 g_free (utf8_progname);
1146 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
1148 #if !GLIB_CHECK_VERSION (2,4,0)
1149 #define g_setenv(a,b,c) setenv(a,b,c)
1150 #define g_unsetenv(a) unsetenv(a)
1153 static void process_set_current (void)
1155 pid_t pid = _wapi_getpid ();
1156 const char *handle_env;
1157 struct _WapiHandle_process process_handle = {0};
1159 mono_once (&process_ops_once, process_ops_init);
1161 handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1162 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1164 if (handle_env != NULL) {
1165 struct _WapiHandle_process *process_handlep;
1166 gchar *procname = NULL;
1169 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
1171 DEBUG ("%s: Found my process handle: %p (offset %d 0x%x)",
1172 __func__, current_process, atoi (handle_env),
1175 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
1176 (gpointer *)&process_handlep);
1178 /* This test will probably break on linuxthreads, but
1179 * that should be ancient history on all distros we
1182 if (process_handlep->id == pid) {
1183 procname = process_handlep->proc_name;
1184 if (!strcmp (procname, "mono")) {
1185 /* Set a better process name */
1186 DEBUG ("%s: Setting better process name", __func__);
1188 process_set_name (process_handlep);
1190 DEBUG ("%s: Leaving process name: %s", __func__, procname);
1196 /* Wrong pid, so drop this handle and fall through to
1199 _wapi_handle_unref (current_process);
1203 /* We get here if the handle wasn't specified in the
1204 * environment, or if the process ID was wrong, or if the
1205 * handle lookup failed (eg if the parent process forked and
1206 * quit immediately, and deleted the shared data before the
1207 * child got a chance to attach it.)
1210 DEBUG ("%s: Need to create my own process handle", __func__);
1212 process_handle.id = pid;
1214 process_set_defaults (&process_handle);
1215 process_set_name (&process_handle);
1217 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1219 if (current_process == _WAPI_HANDLE_INVALID) {
1220 g_warning ("%s: error creating process handle", __func__);
1225 gpointer _wapi_process_duplicate ()
1227 mono_once (&process_current_once, process_set_current);
1229 _wapi_handle_ref (current_process);
1231 return(current_process);
1234 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1235 gpointer GetCurrentProcess (void)
1237 mono_once (&process_current_once, process_set_current);
1239 return(_WAPI_PROCESS_CURRENT);
1242 guint32 GetProcessId (gpointer handle)
1244 struct _WapiHandle_process *process_handle;
1247 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1248 /* This is a pseudo handle */
1249 return(GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
1252 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1253 (gpointer *)&process_handle);
1255 SetLastError (ERROR_INVALID_HANDLE);
1259 return (process_handle->id);
1262 guint32 GetCurrentProcessId (void)
1264 mono_once (&process_current_once, process_set_current);
1266 return (GetProcessId (current_process));
1269 /* Returns the process id as a convenience to the functions that call this */
1270 static pid_t signal_process_if_gone (gpointer handle)
1272 struct _WapiHandle_process *process_handle;
1275 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
1277 /* Make sure the process is signalled if it has exited - if
1278 * the parent process didn't wait for it then it won't be
1280 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1281 (gpointer *)&process_handle);
1283 /* It's possible that the handle has vanished during
1284 * the _wapi_search_handle before it gets here, so
1285 * don't spam the console with warnings.
1287 /* g_warning ("%s: error looking up process handle %p",
1288 __func__, handle);*/
1293 DEBUG ("%s: looking at process %d", __func__, process_handle->id);
1295 if (kill (process_handle->id, 0) == -1 &&
1298 /* The process is dead, (EPERM tells us a new process
1299 * has that ID, but as it's owned by someone else it
1300 * can't be the one listed in our shared memory file)
1302 _wapi_shared_handle_set_signal_state (handle, TRUE);
1305 return (process_handle->id);
1309 static gboolean process_enum (gpointer handle, gpointer user_data)
1311 GArray *processes=user_data;
1312 pid_t pid = signal_process_if_gone (handle);
1319 /* Ignore processes that have already exited (ie they are signalled) */
1320 if (_wapi_handle_issignalled (handle) == FALSE) {
1321 DEBUG ("%s: process %d added to array", __func__, pid);
1323 /* This ensures that duplicates aren't returned (see
1324 * the comment above _wapi_search_handle () for why
1327 for (i = 0; i < processes->len; i++) {
1328 if (g_array_index (processes, pid_t, i) == pid) {
1329 /* We've already got this one, return
1330 * FALSE to keep searching
1336 g_array_append_val (processes, pid);
1339 /* Return false to keep searching */
1342 #endif /* UNUSED_CODE */
1344 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
1346 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1348 guint32 count, fit, i, j;
1351 size_t proclength, size;
1352 #if defined(__OpenBSD__)
1353 struct kinfo_proc *result;
1356 name[1] = KERN_PROC;
1357 name[2] = KERN_PROC_ALL;
1359 name[4] = sizeof(struct kinfo_proc);
1362 struct kinfo_proc *result;
1363 static const int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
1366 mono_once (&process_current_once, process_set_current);
1373 #if defined(__OpenBSD__)
1374 size = (sizeof(name) / sizeof(*name));
1376 size = (sizeof(name) / sizeof(*name)) - 1;
1378 err = sysctl ((int *)name, size, NULL, &proclength, NULL, 0);
1381 result = malloc (proclength);
1386 #if defined(__OpenBSD__)
1387 name[5] = (int)(proclength / sizeof(struct kinfo_proc));
1390 err = sysctl ((int *) name, size, result, &proclength, NULL, 0);
1399 } while (err == 0 && !done);
1402 if (result != NULL) {
1409 count = proclength / sizeof(struct kinfo_proc);
1411 fit = len / sizeof(guint32);
1412 for (i = 0, j = 0; j< fit && i < count; i++) {
1413 #if defined(__OpenBSD__)
1414 pids [j++] = result [i].p_pid;
1416 if (result[i].kp_proc.p_pid > 0) /* Pid 0 not supported */
1417 pids [j++] = result [i].kp_proc.p_pid;
1422 *needed = j * sizeof(guint32);
1426 #elif defined(__HAIKU__)
1428 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1434 mono_once (&process_current_once, process_set_current);
1436 fit = len / sizeof (guint32);
1437 while (get_next_team_info (&cookie, &teamInfo) == B_OK && i < fit) {
1438 pids [i++] = teamInfo.team;
1440 *needed = i * sizeof (guint32);
1445 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1449 struct dirent *entry;
1451 mono_once (&process_current_once, process_set_current);
1453 dir = opendir ("/proc");
1459 fit = len / sizeof (guint32);
1460 while(i < fit && (entry = readdir (dir)) != NULL) {
1464 if (!isdigit (entry->d_name[0]))
1467 pid = (pid_t) strtol (entry->d_name, &endptr, 10);
1468 if (*endptr == '\0')
1469 pids [i++] = (guint32) pid;
1472 *needed = i * sizeof(guint32);
1478 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1481 pid_t checking_pid = signal_process_if_gone (handle);
1483 if (checking_pid == 0) {
1487 wanted_pid = GPOINTER_TO_UINT (user_data);
1489 /* It's possible to have more than one process handle with the
1490 * same pid, but only the one running process can be
1493 if (checking_pid == wanted_pid &&
1494 _wapi_handle_issignalled (handle) == FALSE) {
1495 /* If the handle is blown away in the window between
1496 * returning TRUE here and _wapi_search_handle pinging
1497 * the timestamp, the search will continue
1505 gboolean CloseProcess(gpointer handle)
1507 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1508 /* This is a pseudo handle */
1512 return CloseHandle (handle);
1516 * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1518 gpointer OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1520 /* Find the process handle that corresponds to pid */
1521 gpointer handle = NULL;
1523 mono_once (&process_current_once, process_set_current);
1525 DEBUG ("%s: looking for process %d", __func__, pid);
1527 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1528 process_open_compare,
1529 GUINT_TO_POINTER (pid), NULL, TRUE);
1531 if (is_pid_valid (pid)) {
1532 /* Return a pseudo handle for processes we
1533 * don't have handles for
1535 return GINT_TO_POINTER (_WAPI_PROCESS_UNHANDLED + pid);
1537 DEBUG ("%s: Can't find pid %d", __func__, pid);
1539 SetLastError (ERROR_PROC_NOT_FOUND);
1545 /* _wapi_search_handle () already added a ref */
1549 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1551 struct _WapiHandle_process *process_handle;
1555 mono_once (&process_current_once, process_set_current);
1561 pid = GPOINTER_TO_UINT (process) - _WAPI_PROCESS_UNHANDLED;
1562 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1563 /* This is a pseudo handle, so we don't know what the
1564 * exit code was, but we can check whether it's alive or not
1566 if (is_pid_valid (pid)) {
1567 *code = STILL_ACTIVE;
1574 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1575 (gpointer *)&process_handle);
1577 DEBUG ("%s: Can't find process %p", __func__, process);
1582 /* A process handle is only signalled if the process has exited
1583 * and has been waited for */
1585 /* Make sure any process exit has been noticed, before
1586 * checking if the process is signalled. Fixes bug 325463.
1588 process_wait (process, 0, TRUE);
1590 if (_wapi_handle_issignalled (process) == TRUE) {
1591 *code = process_handle->exitstatus;
1593 *code = STILL_ACTIVE;
1599 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1600 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1601 WapiFileTime *user_time)
1603 struct _WapiHandle_process *process_handle;
1605 gboolean ku_times_set = FALSE;
1607 mono_once (&process_current_once, process_set_current);
1609 if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1611 /* Not sure if w32 allows NULLs here or not */
1615 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1616 /* This is a pseudo handle, so just fail for now
1621 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1622 (gpointer *)&process_handle);
1624 DEBUG ("%s: Can't find process %p", __func__, process);
1629 *create_time=process_handle->create_time;
1631 /* A process handle is only signalled if the process has
1632 * exited. Otherwise exit_time isn't set
1634 if(_wapi_handle_issignalled (process)==TRUE) {
1635 *exit_time=process_handle->exit_time;
1638 #ifdef HAVE_GETRUSAGE
1639 if (process_handle->id == getpid ()) {
1640 struct rusage time_data;
1641 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1643 ku_times_set = TRUE;
1644 tick_val = (guint64)time_data.ru_utime.tv_sec * 10000000 + (guint64)time_data.ru_utime.tv_usec * 10;
1645 _wapi_guint64_to_filetime (tick_val, user_time);
1646 tick_val = (guint64)time_data.ru_stime.tv_sec * 10000000 + (guint64)time_data.ru_stime.tv_usec * 10;
1647 _wapi_guint64_to_filetime (tick_val, kernel_time);
1651 if (!ku_times_set) {
1652 memset (kernel_time, 0, sizeof (WapiFileTime));
1653 memset (user_time, 0, sizeof (WapiFileTime));
1661 gpointer address_start;
1662 gpointer address_end;
1664 gpointer address_offset;
1670 static void free_procmodule (WapiProcModule *mod)
1672 if (mod->perms != NULL) {
1673 g_free (mod->perms);
1675 if (mod->filename != NULL) {
1676 g_free (mod->filename);
1681 static gint find_procmodule (gconstpointer a, gconstpointer b)
1683 WapiProcModule *want = (WapiProcModule *)a;
1684 WapiProcModule *compare = (WapiProcModule *)b;
1686 if ((want->device == compare->device) &&
1687 (want->inode == compare->inode)) {
1694 #ifdef PLATFORM_MACOSX
1695 #include <mach-o/dyld.h>
1696 #include <mach-o/getsect.h>
1698 static GSList *load_modules (void)
1701 WapiProcModule *mod;
1702 uint32_t count = _dyld_image_count ();
1705 for (i = 0; i < count; i++) {
1706 #if SIZEOF_VOID_P == 8
1707 const struct mach_header_64 *hdr;
1708 const struct section_64 *sec;
1710 const struct mach_header *hdr;
1711 const struct section *sec;
1715 name = _dyld_get_image_name (i);
1716 #if SIZEOF_VOID_P == 8
1717 hdr = (const struct mach_header_64*)_dyld_get_image_header (i);
1718 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1720 hdr = _dyld_get_image_header (i);
1721 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1724 /* Some dynlibs do not have data sections on osx (#533893) */
1729 mod = g_new0 (WapiProcModule, 1);
1730 mod->address_start = GINT_TO_POINTER (sec->addr);
1731 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1732 mod->perms = g_strdup ("r--p");
1733 mod->address_offset = 0;
1734 mod->device = makedev (0, 0);
1735 mod->inode = (ino_t) i;
1736 mod->filename = g_strdup (name);
1738 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1739 ret = g_slist_prepend (ret, mod);
1741 free_procmodule (mod);
1745 ret = g_slist_reverse (ret);
1749 #elif defined(__OpenBSD__)
1751 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1753 if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1754 + sizeof (info->dlpi_phnum))
1757 struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1761 memcpy(cpy, info, sizeof(*info));
1763 g_ptr_array_add ((GPtrArray *)ptr, cpy);
1768 static GSList *load_modules (void)
1771 WapiProcModule *mod;
1772 GPtrArray *dlarray = g_ptr_array_new();
1775 if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1778 for (i = 0; i < dlarray->len; i++) {
1779 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1781 mod = g_new0 (WapiProcModule, 1);
1782 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1783 mod->address_end = (gpointer)(info->dlpi_addr +
1784 info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1785 mod->perms = g_strdup ("r--p");
1786 mod->address_offset = 0;
1787 mod->inode = (ino_t) i;
1788 mod->filename = g_strdup (info->dlpi_name);
1790 DEBUG ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1791 mod->inode, mod->filename, mod->address_start, mod->address_end);
1795 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1796 ret = g_slist_prepend (ret, mod);
1798 free_procmodule (mod);
1802 g_ptr_array_free (dlarray, TRUE);
1804 ret = g_slist_reverse (ret);
1808 #elif defined(__HAIKU__)
1810 static GSList *load_modules (void)
1813 WapiProcModule *mod;
1815 image_info imageInfo;
1817 while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
1818 mod = g_new0 (WapiProcModule, 1);
1819 mod->device = imageInfo.device;
1820 mod->inode = imageInfo.node;
1821 mod->filename = g_strdup (imageInfo.name);
1822 mod->address_start = MIN (imageInfo.text, imageInfo.data);
1823 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
1824 (uint8_t*)imageInfo.data + imageInfo.data_size);
1825 mod->perms = g_strdup ("r--p");
1826 mod->address_offset = 0;
1828 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1829 ret = g_slist_prepend (ret, mod);
1831 free_procmodule (mod);
1835 ret = g_slist_reverse (ret);
1840 static GSList *load_modules (FILE *fp)
1843 WapiProcModule *mod;
1844 gchar buf[MAXPATHLEN + 1], *p, *endp;
1845 gchar *start_start, *end_start, *prot_start, *offset_start;
1846 gchar *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1847 gpointer address_start, address_end, address_offset;
1848 guint32 maj_dev, min_dev;
1852 while (fgets (buf, sizeof(buf), fp)) {
1854 while (g_ascii_isspace (*p)) ++p;
1856 if (!g_ascii_isxdigit (*start_start)) {
1859 address_start = (gpointer)strtoul (start_start, &endp, 16);
1867 if (!g_ascii_isxdigit (*end_start)) {
1870 address_end = (gpointer)strtoul (end_start, &endp, 16);
1872 if (!g_ascii_isspace (*p)) {
1876 while (g_ascii_isspace (*p)) ++p;
1878 if (*prot_start != 'r' && *prot_start != '-') {
1881 memcpy (prot_buf, prot_start, 4);
1883 while (!g_ascii_isspace (*p)) ++p;
1885 while (g_ascii_isspace (*p)) ++p;
1887 if (!g_ascii_isxdigit (*offset_start)) {
1890 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1892 if (!g_ascii_isspace (*p)) {
1896 while(g_ascii_isspace (*p)) ++p;
1898 if (!g_ascii_isxdigit (*maj_dev_start)) {
1901 maj_dev = strtoul (maj_dev_start, &endp, 16);
1909 if (!g_ascii_isxdigit (*min_dev_start)) {
1912 min_dev = strtoul (min_dev_start, &endp, 16);
1914 if (!g_ascii_isspace (*p)) {
1918 while (g_ascii_isspace (*p)) ++p;
1920 if (!g_ascii_isxdigit (*inode_start)) {
1923 inode = (ino_t)strtol (inode_start, &endp, 10);
1925 if (!g_ascii_isspace (*p)) {
1929 device = makedev ((int)maj_dev, (int)min_dev);
1930 if ((device == 0) &&
1935 while(g_ascii_isspace (*p)) ++p;
1936 /* p now points to the filename */
1938 mod = g_new0 (WapiProcModule, 1);
1939 mod->address_start = address_start;
1940 mod->address_end = address_end;
1941 mod->perms = g_strdup (prot_buf);
1942 mod->address_offset = address_offset;
1943 mod->device = device;
1945 mod->filename = g_strdup (g_strstrip (p));
1947 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1948 ret = g_slist_prepend (ret, mod);
1950 free_procmodule (mod);
1954 ret = g_slist_reverse (ret);
1960 static gboolean match_procname_to_modulename (gchar *procname, gchar *modulename)
1962 char* lastsep = NULL;
1963 char* lastsep2 = NULL;
1966 gboolean result = FALSE;
1968 if (procname == NULL || modulename == NULL)
1971 pname = mono_path_resolve_symlinks (procname);
1972 mname = mono_path_resolve_symlinks (modulename);
1974 if (!strcmp (pname, mname))
1978 lastsep = strrchr (mname, '/');
1980 if (!strcmp (lastsep+1, pname))
1983 lastsep2 = strrchr (pname, '/');
1986 if (!strcmp (lastsep+1, lastsep2+1))
1989 if (!strcmp (mname, lastsep2+1))
2002 #if !defined(__OpenBSD__)
2004 open_process_map (int pid, const char *mode)
2007 const gchar *proc_path[] = {
2008 "/proc/%d/maps", /* GNU/Linux */
2009 "/proc/%d/map", /* FreeBSD */
2015 for (i = 0; fp == NULL && proc_path [i]; i++) {
2016 filename = g_strdup_printf (proc_path[i], pid);
2017 fp = fopen (filename, mode);
2025 gboolean EnumProcessModules (gpointer process, gpointer *modules,
2026 guint32 size, guint32 *needed)
2028 struct _WapiHandle_process *process_handle;
2030 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2033 GSList *mods = NULL;
2034 WapiProcModule *module;
2035 guint32 count, avail = size / sizeof(gpointer);
2038 gchar *proc_name = NULL;
2040 /* Store modules in an array of pointers (main module as
2041 * modules[0]), using the load address for each module as a
2042 * token. (Use 'NULL' as an alternative for the main module
2043 * so that the simple implementation can just return one item
2044 * for now.) Get the info from /proc/<pid>/maps on linux,
2045 * /proc/<pid>/map on FreeBSD, other systems will have to
2046 * implement /dev/kmem reading or whatever other horrid
2047 * technique is needed.
2049 if (size < sizeof(gpointer)) {
2053 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2054 /* This is a pseudo handle */
2055 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2057 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2058 (gpointer *)&process_handle);
2060 DEBUG ("%s: Can't find process %p", __func__, process);
2064 pid = process_handle->id;
2065 proc_name = process_handle->proc_name;
2068 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2070 mods = load_modules ();
2072 if ((fp = open_process_map (pid, "r")) == NULL) {
2073 /* No /proc/<pid>/maps so just return the main module
2077 *needed = sizeof(gpointer);
2079 mods = load_modules (fp);
2082 count = g_slist_length (mods);
2084 /* count + 1 to leave slot 0 for the main module */
2085 *needed = sizeof(gpointer) * (count + 1);
2087 /* Use the NULL shortcut, as the first line in
2088 * /proc/<pid>/maps isn't the executable, and we need
2089 * that first in the returned list. Check the module name
2090 * to see if it ends with the proc name and substitute
2091 * the first entry with it. FIXME if this turns out to
2095 for (i = 0; i < (avail - 1) && i < count; i++) {
2096 module = (WapiProcModule *)g_slist_nth_data (mods, i);
2097 if (modules[0] != NULL)
2098 modules[i] = module->address_start;
2099 else if (match_procname_to_modulename (proc_name, module->filename))
2100 modules[0] = module->address_start;
2102 modules[i + 1] = module->address_start;
2105 for (i = 0; i < count; i++) {
2106 free_procmodule (g_slist_nth_data (mods, i));
2108 g_slist_free (mods);
2114 static gchar *get_process_name_from_proc (pid_t pid)
2116 #if defined(__OpenBSD__)
2119 struct kinfo_proc *pi;
2120 #elif defined(PLATFORM_MACOSX)
2121 #if !(!defined (__mono_ppc__) && defined (TARGET_OSX))
2123 struct kinfo_proc *pi;
2124 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
2128 gchar *filename = NULL;
2133 #if defined(PLATFORM_SOLARIS)
2134 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
2135 if ((fp = fopen (filename, "r")) != NULL) {
2139 nread = fread (&info, sizeof (info), 1, fp);
2141 ret = g_strdup (info.pr_fname);
2147 #elif defined(PLATFORM_MACOSX)
2148 #if !defined (__mono_ppc__) && defined (TARGET_OSX)
2149 /* No proc name on OSX < 10.5 nor ppc nor iOS */
2150 memset (buf, '\0', sizeof(buf));
2151 proc_name (pid, buf, sizeof(buf));
2152 if (strlen (buf) > 0)
2153 ret = g_strdup (buf);
2155 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0)
2158 if ((pi = malloc(size)) == NULL)
2161 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
2162 if (errno == ENOMEM) {
2164 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__);
2169 if (strlen (pi->kp_proc.p_comm) > 0)
2170 ret = g_strdup (pi->kp_proc.p_comm);
2174 #elif defined(__OpenBSD__)
2176 mib [1] = KERN_PROC;
2177 mib [2] = KERN_PROC_PID;
2179 mib [4] = sizeof(struct kinfo_proc);
2183 if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0)
2186 if ((pi = malloc(size)) == NULL)
2189 mib[5] = (int)(size / sizeof(struct kinfo_proc));
2191 if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
2192 (size != sizeof (struct kinfo_proc))) {
2193 if (errno == ENOMEM) {
2200 if (strlen (pi->p_comm) > 0)
2201 ret = g_strdup (pi->p_comm);
2204 #elif defined(__HAIKU__)
2205 image_info imageInfo;
2208 if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
2209 ret = g_strdup (imageInfo.name);
2212 memset (buf, '\0', sizeof(buf));
2213 filename = g_strdup_printf ("/proc/%d/exe", pid);
2214 if (readlink (filename, buf, 255) > 0) {
2215 ret = g_strdup (buf);
2223 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
2224 if ((fp = fopen (filename, "r")) != NULL) {
2225 if (fgets (buf, 256, fp) != NULL) {
2226 ret = g_strdup (buf);
2237 filename = g_strdup_printf ("/proc/%d/stat", pid);
2238 if ((fp = fopen (filename, "r")) != NULL) {
2239 if (fgets (buf, 256, fp) != NULL) {
2242 start = strchr (buf, '(');
2243 if (start != NULL) {
2244 end = strchr (start + 1, ')');
2247 ret = g_strndup (start + 1,
2262 * wapi_process_get_path:
2264 * Return the full path of the executable of the process PID, or NULL if it cannot be determined.
2265 * Returns malloc-ed memory.
2268 wapi_process_get_path (pid_t pid)
2270 #if defined(PLATFORM_MACOSX) && !defined(__mono_ppc__) && defined(TARGET_OSX)
2271 gchar buf [PROC_PIDPATHINFO_MAXSIZE];
2274 res = proc_pidpath (pid, buf, sizeof (buf));
2277 if (buf [0] == '\0')
2279 return g_strdup (buf);
2281 return get_process_name_from_proc (pid);
2286 * wapi_process_set_cli_launcher:
2288 * Set the full path of the runtime executable used to launch managed exe's.
2291 wapi_process_set_cli_launcher (char *path)
2293 g_free (cli_launcher);
2294 cli_launcher = path ? g_strdup (path) : NULL;
2297 static guint32 get_module_name (gpointer process, gpointer module,
2298 gunichar2 *basename, guint32 size,
2301 struct _WapiHandle_process *process_handle;
2304 gunichar2 *procname;
2305 gchar *procname_ext = NULL;
2308 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2311 GSList *mods = NULL;
2312 WapiProcModule *found_module;
2315 gchar *proc_name = NULL;
2317 mono_once (&process_current_once, process_set_current);
2319 DEBUG ("%s: Getting module base name, process handle %p module %p",
2320 __func__, process, module);
2322 size = size*sizeof(gunichar2); /* adjust for unicode characters */
2324 if (basename == NULL || size == 0) {
2328 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2329 /* This is a pseudo handle */
2330 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2331 proc_name = get_process_name_from_proc (pid);
2333 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2334 (gpointer *)&process_handle);
2336 DEBUG ("%s: Can't find process %p", __func__,
2341 pid = process_handle->id;
2342 proc_name = g_strdup (process_handle->proc_name);
2345 /* Look up the address in /proc/<pid>/maps */
2346 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2348 mods = load_modules ();
2350 if ((fp = open_process_map (pid, "r")) == NULL) {
2351 if (errno == EACCES && module == NULL && base == TRUE) {
2352 procname_ext = get_process_name_from_proc (pid);
2354 /* No /proc/<pid>/maps, so just return failure
2361 mods = load_modules (fp);
2364 count = g_slist_length (mods);
2366 /* If module != NULL compare the address.
2367 * If module == NULL we are looking for the main module.
2368 * The best we can do for now check it the module name end with the process name.
2370 for (i = 0; i < count; i++) {
2371 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2372 if (procname_ext == NULL &&
2373 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2374 (module != NULL && found_module->address_start == module))) {
2376 procname_ext = g_path_get_basename (found_module->filename);
2378 procname_ext = g_strdup (found_module->filename);
2382 free_procmodule (found_module);
2385 if (procname_ext == NULL)
2387 /* If it's *still* null, we might have hit the
2388 * case where reading /proc/$pid/maps gives an
2389 * empty file for this user.
2391 procname_ext = get_process_name_from_proc (pid);
2394 g_slist_free (mods);
2398 if (procname_ext != NULL) {
2399 DEBUG ("%s: Process name is [%s]", __func__,
2402 procname = mono_unicode_from_external (procname_ext, &bytes);
2403 if (procname == NULL) {
2405 g_free (procname_ext);
2411 /* Add the terminator */
2415 DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2417 memcpy (basename, procname, size);
2419 DEBUG ("%s: Size %d larger than needed (%ld)",
2420 __func__, size, bytes);
2422 memcpy (basename, procname, bytes);
2426 g_free (procname_ext);
2434 guint32 GetModuleBaseName (gpointer process, gpointer module,
2435 gunichar2 *basename, guint32 size)
2437 return(get_module_name (process, module, basename, size, TRUE));
2440 guint32 GetModuleFileNameEx (gpointer process, gpointer module,
2441 gunichar2 *filename, guint32 size)
2443 return(get_module_name (process, module, filename, size, FALSE));
2446 gboolean GetModuleInformation (gpointer process, gpointer module,
2447 WapiModuleInfo *modinfo, guint32 size)
2449 struct _WapiHandle_process *process_handle;
2452 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2455 GSList *mods = NULL;
2456 WapiProcModule *found_module;
2459 gboolean ret = FALSE;
2460 gchar *proc_name = NULL;
2462 mono_once (&process_current_once, process_set_current);
2464 DEBUG ("%s: Getting module info, process handle %p module %p",
2465 __func__, process, module);
2467 if (modinfo == NULL || size < sizeof(WapiModuleInfo)) {
2471 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2472 /* This is a pseudo handle */
2473 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2474 proc_name = get_process_name_from_proc (pid);
2476 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2477 (gpointer *)&process_handle);
2479 DEBUG ("%s: Can't find process %p", __func__,
2484 pid = process_handle->id;
2485 proc_name = g_strdup (process_handle->proc_name);
2488 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2490 mods = load_modules ();
2492 /* Look up the address in /proc/<pid>/maps */
2493 if ((fp = open_process_map (pid, "r")) == NULL) {
2494 /* No /proc/<pid>/maps, so just return failure
2500 mods = load_modules (fp);
2503 count = g_slist_length (mods);
2505 /* If module != NULL compare the address.
2506 * If module == NULL we are looking for the main module.
2507 * The best we can do for now check it the module name end with the process name.
2509 for (i = 0; i < count; i++) {
2510 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2511 if ( ret == FALSE &&
2512 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2513 (module != NULL && found_module->address_start == module))) {
2514 modinfo->lpBaseOfDll = found_module->address_start;
2515 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2516 modinfo->EntryPoint = found_module->address_offset;
2520 free_procmodule (found_module);
2523 g_slist_free (mods);
2530 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2532 struct _WapiHandle_process *process_handle;
2535 mono_once (&process_current_once, process_set_current);
2537 if(min==NULL || max==NULL) {
2538 /* Not sure if w32 allows NULLs here or not */
2542 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2543 /* This is a pseudo handle, so just fail for now
2548 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2549 (gpointer *)&process_handle);
2551 DEBUG ("%s: Can't find process %p", __func__, process);
2556 *min=process_handle->min_working_set;
2557 *max=process_handle->max_working_set;
2562 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2564 struct _WapiHandle_process *process_handle;
2567 mono_once (&process_current_once, process_set_current);
2569 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2570 /* This is a pseudo handle, so just fail for now
2575 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2576 (gpointer *)&process_handle);
2578 DEBUG ("%s: Can't find process %p", __func__, process);
2583 process_handle->min_working_set=min;
2584 process_handle->max_working_set=max;
2591 TerminateProcess (gpointer process, gint32 exitCode)
2593 struct _WapiHandle_process *process_handle;
2599 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2600 /* This is a pseudo handle */
2601 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2603 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2604 (gpointer *) &process_handle);
2607 DEBUG ("%s: Can't find process %p", __func__,
2609 SetLastError (ERROR_INVALID_HANDLE);
2612 pid = process_handle->id;
2615 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2616 ret = kill (pid, signo);
2620 SetLastError (ERROR_INVALID_PARAMETER);
2623 SetLastError (ERROR_ACCESS_DENIED);
2626 SetLastError (ERROR_PROC_NOT_FOUND);
2629 SetLastError (ERROR_GEN_FAILURE);
2637 GetPriorityClass (gpointer process)
2639 #ifdef HAVE_GETPRIORITY
2640 struct _WapiHandle_process *process_handle;
2645 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2646 /* This is a pseudo handle */
2647 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2649 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2650 (gpointer *) &process_handle);
2653 SetLastError (ERROR_INVALID_HANDLE);
2656 pid = process_handle->id;
2660 ret = getpriority (PRIO_PROCESS, pid);
2661 if (ret == -1 && errno != 0) {
2665 SetLastError (ERROR_ACCESS_DENIED);
2668 SetLastError (ERROR_PROC_NOT_FOUND);
2671 SetLastError (ERROR_GEN_FAILURE);
2677 return NORMAL_PRIORITY_CLASS;
2679 return REALTIME_PRIORITY_CLASS;
2681 return HIGH_PRIORITY_CLASS;
2683 return ABOVE_NORMAL_PRIORITY_CLASS;
2685 return IDLE_PRIORITY_CLASS;
2687 return BELOW_NORMAL_PRIORITY_CLASS;
2689 return NORMAL_PRIORITY_CLASS;
2691 SetLastError (ERROR_NOT_SUPPORTED);
2697 SetPriorityClass (gpointer process, guint32 priority_class)
2699 #ifdef HAVE_SETPRIORITY
2700 struct _WapiHandle_process *process_handle;
2706 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2707 /* This is a pseudo handle */
2708 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2710 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2711 (gpointer *) &process_handle);
2714 SetLastError (ERROR_INVALID_HANDLE);
2717 pid = process_handle->id;
2720 switch (priority_class) {
2721 case IDLE_PRIORITY_CLASS:
2724 case BELOW_NORMAL_PRIORITY_CLASS:
2727 case NORMAL_PRIORITY_CLASS:
2730 case ABOVE_NORMAL_PRIORITY_CLASS:
2733 case HIGH_PRIORITY_CLASS:
2736 case REALTIME_PRIORITY_CLASS:
2740 SetLastError (ERROR_INVALID_PARAMETER);
2744 ret = setpriority (PRIO_PROCESS, pid, prio);
2749 SetLastError (ERROR_ACCESS_DENIED);
2752 SetLastError (ERROR_PROC_NOT_FOUND);
2755 SetLastError (ERROR_GEN_FAILURE);
2761 SetLastError (ERROR_NOT_SUPPORTED);
2767 mono_processes_cleanup (void)
2769 struct MonoProcess *mp;
2770 struct MonoProcess *prev = NULL;
2771 struct MonoProcess *candidate = NULL;
2772 gpointer unref_handle;
2775 DEBUG ("%s", __func__);
2777 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2778 if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
2781 mp = mono_processes;
2782 while (mp != NULL) {
2783 if (mp->pid == 0 && mp->handle != NULL) {
2784 /* This process has exited and we need to remove the artifical ref
2786 mono_mutex_lock (&mono_processes_mutex);
2787 unref_handle = mp->handle;
2789 mono_mutex_unlock (&mono_processes_mutex);
2791 _wapi_handle_unref (unref_handle);
2797 mp = mono_processes;
2799 while (mp != NULL) {
2800 if ((mp->handle_count == 0 && mp->pid == 0) || candidate != NULL) {
2802 _wapi_handle_spin (spin);
2806 /* We've found a candidate */
2807 mono_mutex_lock (&mono_processes_mutex);
2808 if (candidate == NULL) {
2810 if (mp == mono_processes) {
2811 mono_processes = mp->next;
2813 prev->next = mp->next;
2818 /* It's still safe to traverse the structure.*/
2819 mono_memory_barrier ();
2821 if (mono_processes_read_lock != 0) {
2822 /* The sigchld handler is watching us. Spin a bit and try again */
2825 } else if (spin >= 8) {
2826 /* Just give up for now */
2827 mono_mutex_unlock (&mono_processes_mutex);
2831 /* We've modified the list of processes, and we know the sigchld handler
2832 * isn't executing, so even if it executes at any moment, it'll see the
2833 * new version of the list. So now we can free the candidate. */
2834 DEBUG ("%s: freeing candidate %p", __func__, candidate);
2835 mp = candidate->next;
2836 MONO_SEM_DESTROY (&candidate->exit_sem);
2841 mono_mutex_unlock (&mono_processes_mutex);
2850 DEBUG ("%s done", __func__);
2852 InterlockedDecrement (&mono_processes_cleaning_up);
2856 process_close (gpointer handle, gpointer data)
2858 struct _WapiHandle_process *process_handle;
2860 DEBUG ("%s", __func__);
2862 process_handle = (struct _WapiHandle_process *) data;
2863 if (process_handle->mono_process && process_handle->self == _wapi_getpid ())
2864 InterlockedDecrement (&process_handle->mono_process->handle_count);
2865 mono_processes_cleanup ();
2869 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
2873 struct MonoProcess *p;
2876 fprintf (stdout, "SIG CHILD handler for pid: %i\n", info->si_pid);
2879 InterlockedIncrement (&mono_processes_read_lock);
2883 pid = waitpid (-1, &status, WNOHANG);
2884 } while (pid == -1 && errno == EINTR);
2890 fprintf (stdout, "child ended: %i", pid);
2894 if (p->pid == pid) {
2895 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2897 MONO_SEM_POST (&p->exit_sem);
2904 InterlockedDecrement (&mono_processes_read_lock);
2907 fprintf (stdout, "SIG CHILD handler: done looping.");
2913 static void process_add_sigchld_handler (void)
2916 struct sigaction sa;
2918 sa.sa_sigaction = mono_sigchld_signal_handler;
2919 sigemptyset (&sa.sa_mask);
2920 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2921 g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2922 DEBUG ("Added SIGCHLD handler");
2926 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2928 struct _WapiHandle_process *process_handle;
2934 struct MonoProcess *mp;
2936 gpointer current_thread;
2938 current_thread = wapi_get_current_thread_handle ();
2939 if (current_thread == NULL) {
2940 SetLastError (ERROR_INVALID_HANDLE);
2944 /* FIXME: We can now easily wait on processes that aren't our own children,
2945 * but WaitFor*Object won't call us for pseudo handles. */
2946 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2948 DEBUG ("%s (%p, %u)", __func__, handle, timeout);
2950 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS, (gpointer *)&process_handle);
2952 g_warning ("%s: error looking up process handle %p", __func__, handle);
2956 if (process_handle->exited) {
2957 /* We've already done this one */
2958 DEBUG ("%s (%p, %u): Process already exited", __func__, handle, timeout);
2959 return WAIT_OBJECT_0;
2962 pid = process_handle->id;
2964 DEBUG ("%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2966 /* We don't need to lock mono_processes here, the entry
2967 * has a handle_count > 0 which means it will not be freed. */
2968 mp = process_handle->mono_process;
2969 if (mp && process_handle->self != _wapi_getpid ()) {
2970 /* mono_process points to memory in another process' address space: we can't use it */
2974 start = mono_msec_ticks ();
2980 /* We have a semaphore we can wait on */
2981 if (timeout != INFINITE) {
2982 DEBUG ("%s (%p, %u): waiting on semaphore for %li ms...",
2983 __func__, handle, timeout, (timeout - (now - start)));
2985 ret = MONO_SEM_TIMEDWAIT_ALERTABLE (&mp->exit_sem, (timeout - (now - start)), alertable);
2987 DEBUG ("%s (%p, %u): waiting on semaphore forever...",
2988 __func__, handle, timeout);
2989 ret = MONO_SEM_WAIT_ALERTABLE (&mp->exit_sem, alertable);
2992 if (ret == -1 && errno != EINTR && errno != ETIMEDOUT) {
2993 DEBUG ("%s (%p, %u): sem_timedwait failure: %s",
2994 __func__, handle, timeout, g_strerror (errno));
2995 /* Should we return a failure here? */
2999 /* Success, process has exited */
3000 MONO_SEM_POST (&mp->exit_sem);
3004 /* We did not create this process, so we can't waidpid / sem_wait it.
3005 * We need to poll for the pid existence */
3006 DEBUG ("%s (%p, %u): polling on pid...", __func__, handle, timeout);
3007 if (!is_pid_valid (pid)) {
3008 /* Success, process has exited */
3014 DEBUG ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
3015 return WAIT_TIMEOUT;
3018 now = mono_msec_ticks ();
3019 if (now - start >= timeout) {
3020 DEBUG ("%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
3021 return WAIT_TIMEOUT;
3025 /* "timeout - (now - start)" will not underflow, since timeout is always >=0,
3026 * and we passed the check just above */
3027 _wapi_handle_spin (MIN (100, timeout - (now - start)));
3030 if (alertable && _wapi_thread_apc_pending (current_thread)) {
3031 DEBUG ("%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
3032 return WAIT_IO_COMPLETION;
3036 /* Process must have exited */
3037 DEBUG ("%s (%p, %u): Waited successfully", __func__, handle, timeout);
3039 ret = _wapi_handle_lock_shared_handles ();
3040 g_assert (ret == 0);
3042 status = mp ? mp->status : 0;
3043 if (WIFSIGNALED (status)) {
3044 process_handle->exitstatus = 128 + WTERMSIG (status);
3046 process_handle->exitstatus = WEXITSTATUS (status);
3048 _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
3050 process_handle->exited = TRUE;
3052 DEBUG ("%s (%p, %u): Setting pid %d signalled, exit status %d",
3053 __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
3055 _wapi_shared_handle_set_signal_state (handle, TRUE);
3057 _wapi_handle_unlock_shared_handles ();
3059 return WAIT_OBJECT_0;
3063 wapi_processes_cleanup (void)
3065 g_free (cli_launcher);