2 * processes.c: Process handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002-2011 Novell, Inc.
8 * Copyright 2011 Xamarin Inc
9 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
20 #include <sys/types.h>
28 #ifdef HAVE_SYS_PARAM_H
29 #include <sys/param.h>
33 #ifdef HAVE_SYS_WAIT_H
36 #ifdef HAVE_SYS_RESOURCE_H
37 #include <sys/resource.h>
40 #ifdef HAVE_SYS_MKDEV_H
41 #include <sys/mkdev.h>
48 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
50 #include <TargetConditionals.h>
51 #include <sys/resource.h>
58 #if defined(PLATFORM_MACOSX)
59 #define USE_OSX_LOADER
62 #if ( defined(__OpenBSD__) || defined(__FreeBSD__) ) && defined(HAVE_LINK_H)
63 #define USE_BSD_LOADER
66 #if defined(__HAIKU__)
67 #define USE_HAIKU_LOADER
70 #if defined(USE_OSX_LOADER) || defined(USE_BSD_LOADER)
72 #include <sys/sysctl.h>
73 # if !defined(__OpenBSD__)
74 # include <sys/utsname.h>
76 # if defined(__FreeBSD__)
77 # include <sys/user.h> /* struct kinfo_proc */
81 #ifdef PLATFORM_SOLARIS
82 /* procfs.h cannot be included if this define is set, but it seems to work fine if it is undefined */
83 #if _FILE_OFFSET_BITS == 64
84 #undef _FILE_OFFSET_BITS
86 #define _FILE_OFFSET_BITS 64
93 #include <KernelKit.h>
96 #include <mono/io-layer/wapi.h>
97 #include <mono/io-layer/wapi-private.h>
98 #include <mono/io-layer/process-private.h>
99 #include <mono/io-layer/io-trace.h>
100 #include <mono/utils/strenc.h>
101 #include <mono/utils/mono-path.h>
102 #include <mono/io-layer/timefuncs-private.h>
103 #include <mono/utils/mono-time.h>
104 #include <mono/utils/mono-membar.h>
105 #include <mono/utils/mono-os-mutex.h>
106 #include <mono/utils/mono-signal-handler.h>
107 #include <mono/utils/mono-proclib.h>
108 #include <mono/utils/mono-once.h>
109 #include <mono/utils/mono-logger-internals.h>
110 #include <mono/utils/w32handle.h>
112 #define STILL_ACTIVE STATUS_PENDING
114 /* The process' environment strings */
115 #if defined(__APPLE__)
116 #if defined (TARGET_OSX)
117 /* Apple defines this in crt_externs.h but doesn't provide that header for
118 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
119 * in fact exist on all implementations (so far)
121 gchar ***_NSGetEnviron(void);
122 #define environ (*_NSGetEnviron())
124 static char *mono_environ[1] = { NULL };
125 #define environ mono_environ
126 #endif /* defined (TARGET_OSX) */
128 extern char **environ;
131 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean *alerted);
132 static void process_close (gpointer handle, gpointer data);
133 static void process_details (gpointer data);
134 static const gchar* process_typename (void);
135 static gsize process_typesize (void);
136 static gboolean is_pid_valid (pid_t pid);
138 #if !(defined(USE_OSX_LOADER) || defined(USE_BSD_LOADER) || defined(USE_HAIKU_LOADER))
140 open_process_map (int pid, const char *mode);
143 static MonoW32HandleOps _wapi_process_ops = {
144 process_close, /* close_shared */
148 process_wait, /* special_wait */
150 process_details, /* details */
151 process_typename, /* typename */
152 process_typesize, /* typesize */
156 static struct sigaction previous_chld_sa;
158 static mono_once_t process_sig_chld_once = MONO_ONCE_INIT;
159 static void process_add_sigchld_handler (void);
161 /* The signal-safe logic to use mono_processes goes like this:
162 * - The list must be safe to traverse for the signal handler at all times.
163 * It's safe to: prepend an entry (which is a single store to 'mono_processes'),
164 * unlink an entry (assuming the unlinked entry isn't freed and doesn't
165 * change its 'next' pointer so that it can still be traversed).
166 * When cleaning up we first unlink an entry, then we verify that
167 * the read lock isn't locked. Then we can free the entry, since
168 * we know that nobody is using the old version of the list (including
169 * the unlinked entry).
170 * We also need to lock when adding and cleaning up so that those two
171 * operations don't mess with eachother. (This lock is not used in the
174 static struct MonoProcess *mono_processes = NULL;
175 static volatile gint32 mono_processes_cleaning_up = 0;
176 static mono_mutex_t mono_processes_mutex;
177 static void mono_processes_cleanup (void);
179 static gpointer current_process;
180 static char *cli_launcher;
182 static WapiHandle_process *
183 lookup_process_handle (gpointer handle)
185 WapiHandle_process *process_data;
188 ret = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS,
189 (gpointer *)&process_data);
195 /* Check if a pid is valid - i.e. if a process exists with this pid. */
197 is_pid_valid (pid_t pid)
199 gboolean result = FALSE;
201 #if defined(HOST_WATCHOS)
202 result = TRUE; // TODO: Rewrite using sysctl
203 #elif defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__)
204 if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
206 #elif defined(__HAIKU__)
208 if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
211 char *dir = g_strdup_printf ("/proc/%d", pid);
212 if (!access (dir, F_OK))
221 process_set_defaults (WapiHandle_process *process_handle)
223 /* These seem to be the defaults on w2k */
224 process_handle->min_working_set = 204800;
225 process_handle->max_working_set = 1413120;
227 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
231 len16 (const gunichar2 *str)
242 utf16_concat (const gunichar2 *first, ...)
249 va_start (args, first);
250 total += len16 (first);
251 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
256 ret = g_new (gunichar2, total + 1);
262 for (s = first; *s != 0; s++)
264 va_start (args, first);
265 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
268 for (p = s; *p != 0; p++)
276 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
277 static const gunichar2 *utf16_space = utf16_space_bytes;
278 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
279 static const gunichar2 *utf16_quote = utf16_quote_bytes;
284 print_utf16 (gunichar2 *str)
288 res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
289 g_print ("%s\n", res);
294 /* Implemented as just a wrapper around CreateProcess () */
296 ShellExecuteEx (WapiShellExecuteInfo *sei)
299 WapiProcessInformation process_info;
303 /* w2k just segfaults here, but we can do better than
306 SetLastError (ERROR_INVALID_PARAMETER);
310 if (sei->lpFile == NULL)
311 /* w2k returns TRUE for this, for some reason. */
314 /* Put both executable and parameters into the second argument
315 * to CreateProcess (), so it searches $PATH. The conversion
316 * into and back out of utf8 is because there is no
317 * g_strdup_printf () equivalent for gunichar2 :-(
319 args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
321 SetLastError (ERROR_INVALID_DATA);
324 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
325 CREATE_UNICODE_ENVIRONMENT, NULL,
326 sei->lpDirectory, NULL, &process_info);
329 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
333 static char *handler;
334 static gunichar2 *handler_utf16;
336 if (handler_utf16 == (gunichar2 *)-1)
339 #ifdef PLATFORM_MACOSX
340 handler = g_strdup ("/usr/bin/open");
343 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
344 * if that fails, try to use gnome-open, then kfmclient
346 handler = g_find_program_in_path ("xdg-open");
347 if (handler == NULL){
348 handler = g_find_program_in_path ("gnome-open");
349 if (handler == NULL){
350 handler = g_find_program_in_path ("kfmclient");
351 if (handler == NULL){
352 handler_utf16 = (gunichar2 *) -1;
355 /* kfmclient needs exec argument */
357 handler = g_strconcat (old, " exec",
364 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
367 /* Put quotes around the filename, in case it's a url
368 * that contains #'s (CreateProcess() calls
369 * g_shell_parse_argv(), which deliberately throws
370 * away anything after an unquoted #). Fixes bug
373 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
374 sei->lpFile, utf16_quote,
375 sei->lpParameters == NULL ? NULL : utf16_space,
376 sei->lpParameters, NULL);
378 SetLastError (ERROR_INVALID_DATA);
381 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
382 CREATE_UNICODE_ENVIRONMENT, NULL,
383 sei->lpDirectory, NULL, &process_info);
386 if (GetLastError () != ERROR_OUTOFMEMORY)
387 SetLastError (ERROR_INVALID_DATA);
390 /* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
391 CloseHandle (process_info.hProcess);
392 process_info.hProcess = NULL;
395 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS)
396 sei->hProcess = process_info.hProcess;
398 CloseHandle (process_info.hProcess);
404 is_managed_binary (const char *filename)
406 int original_errno = errno;
407 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
408 int file = open (filename, O_RDONLY | O_LARGEFILE);
410 int file = open (filename, O_RDONLY);
413 unsigned char buffer[8];
414 off_t file_size, optional_header_offset;
415 off_t pe_header_offset;
416 gboolean managed = FALSE;
418 guint32 first_word, second_word;
420 /* If we are unable to open the file, then we definitely
421 * can't say that it is managed. The child mono process
422 * probably wouldn't be able to open it anyway.
425 errno = original_errno;
429 /* Retrieve the length of the file for future sanity checks. */
430 file_size = lseek (file, 0, SEEK_END);
431 lseek (file, 0, SEEK_SET);
433 /* We know we need to read a header field at offset 60. */
437 num_read = read (file, buffer, 2);
439 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
442 new_offset = lseek (file, 60, SEEK_SET);
444 if (new_offset != 60)
447 num_read = read (file, buffer, 4);
451 pe_header_offset = buffer[0]
456 if (pe_header_offset + 24 > file_size)
459 new_offset = lseek (file, pe_header_offset, SEEK_SET);
461 if (new_offset != pe_header_offset)
464 num_read = read (file, buffer, 4);
466 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
470 * Verify that the header we want in the optional header data
471 * is present in this binary.
473 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
475 if (new_offset != pe_header_offset + 20)
478 num_read = read (file, buffer, 2);
480 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
483 /* Read the CLR header address and size fields. These will be
484 * zero if the binary is not managed.
486 optional_header_offset = pe_header_offset + 24;
487 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
489 if (new_offset != optional_header_offset + 208)
492 num_read = read (file, buffer, 8);
494 /* We are not concerned with endianness, only with
495 * whether it is zero or not.
497 first_word = *(guint32 *)&buffer[0];
498 second_word = *(guint32 *)&buffer[4];
500 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
507 errno = original_errno;
512 CreateProcessWithLogonW (const gunichar2 *username,
513 const gunichar2 *domain,
514 const gunichar2 *password,
515 const guint32 logonFlags,
516 const gunichar2 *appname,
517 const gunichar2 *cmdline,
518 guint32 create_flags,
520 const gunichar2 *cwd,
521 WapiStartupInfo *startup,
522 WapiProcessInformation *process_info)
524 /* FIXME: use user information */
525 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
529 is_readable_or_executable (const char *prog)
532 int a = access (prog, R_OK);
533 int b = access (prog, X_OK);
534 if (a != 0 && b != 0)
536 if (stat (prog, &buf))
538 if (S_ISREG (buf.st_mode))
544 is_executable (const char *prog)
547 if (access (prog, X_OK) != 0)
549 if (stat (prog, &buf))
551 if (S_ISREG (buf.st_mode))
557 switch_dir_separators (char *path)
559 size_t i, pathLength = strlen(path);
561 /* Turn all the slashes round the right way, except for \' */
562 /* There are probably other characters that need to be excluded as well. */
563 for (i = 0; i < pathLength; i++) {
564 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' )
569 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
570 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
571 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
572 gboolean inherit_handles, guint32 create_flags,
573 gpointer new_environ, const gunichar2 *cwd,
574 WapiStartupInfo *startup,
575 WapiProcessInformation *process_info)
577 #if defined (HAVE_FORK) && defined (HAVE_EXECVE)
578 char *cmd = NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL;
579 char *dir = NULL, **env_strings = NULL, **argv = NULL;
580 guint32 i, env_count = 0;
581 gboolean ret = FALSE;
582 gpointer handle = NULL;
583 WapiHandle_process process_handle = {0}, *process_handle_data;
585 int in_fd, out_fd, err_fd;
587 int startup_pipe [2] = {-1, -1};
589 struct MonoProcess *mono_process;
590 gboolean fork_failed = FALSE;
592 mono_once (&process_sig_chld_once, process_add_sigchld_handler);
594 /* appname and cmdline specify the executable and its args:
596 * If appname is not NULL, it is the name of the executable.
597 * Otherwise the executable is the first token in cmdline.
599 * Executable searching:
601 * If appname is not NULL, it can specify the full path and
602 * file name, or else a partial name and the current directory
603 * will be used. There is no additional searching.
605 * If appname is NULL, the first whitespace-delimited token in
606 * cmdline is used. If the name does not contain a full
607 * directory path, the search sequence is:
609 * 1) The directory containing the current process
610 * 2) The current working directory
611 * 3) The windows system directory (Ignored)
612 * 4) The windows directory (Ignored)
615 * Just to make things more interesting, tokens can contain
616 * white space if they are surrounded by quotation marks. I'm
617 * beginning to understand just why windows apps are generally
618 * so crap, with an API like this :-(
620 if (appname != NULL) {
621 cmd = mono_unicode_to_external (appname);
623 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL",
626 SetLastError (ERROR_PATH_NOT_FOUND);
630 switch_dir_separators(cmd);
633 if (cmdline != NULL) {
634 args = mono_unicode_to_external (cmdline);
636 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
638 SetLastError (ERROR_PATH_NOT_FOUND);
644 dir = mono_unicode_to_external (cwd);
646 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
648 SetLastError (ERROR_PATH_NOT_FOUND);
652 /* Turn all the slashes round the right way */
653 switch_dir_separators(dir);
657 /* We can't put off locating the executable any longer :-( */
660 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
661 /* Strip off the drive letter. I can't
662 * believe that CP/M holdover is still
665 g_memmove (cmd, cmd+2, strlen (cmd)-2);
666 cmd[strlen (cmd)-2] = '\0';
669 unquoted = g_shell_unquote (cmd, NULL);
670 if (unquoted[0] == '/') {
671 /* Assume full path given */
672 prog = g_strdup (unquoted);
674 /* Executable existing ? */
675 if (!is_readable_or_executable (prog)) {
676 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s",
679 SetLastError (ERROR_FILE_NOT_FOUND);
683 /* Search for file named by cmd in the current
686 char *curdir = g_get_current_dir ();
688 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
691 /* And make sure it's readable */
692 if (!is_readable_or_executable (prog)) {
693 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s",
696 SetLastError (ERROR_FILE_NOT_FOUND);
702 args_after_prog = args;
707 /* Dig out the first token from args, taking quotation
711 /* First, strip off all leading whitespace */
712 args = g_strchug (args);
714 /* args_after_prog points to the contents of args
715 * after token has been set (otherwise argv[0] is
718 args_after_prog = args;
720 /* Assume the opening quote will always be the first
723 if (args[0] == '\"' || args [0] == '\'') {
725 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
726 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
727 /* We found the first token */
728 token = g_strndup (args+1, i-1);
729 args_after_prog = g_strchug (args + i + 1);
731 /* Quotation mark appeared in the
732 * middle of the token. Just give the
733 * whole first token, quotes and all,
740 /* No quote mark, or malformed */
741 for (i = 0; args[i] != '\0'; i++) {
742 if (g_ascii_isspace (args[i])) {
743 token = g_strndup (args, i);
744 args_after_prog = args + i + 1;
750 if (token == NULL && args[0] != '\0') {
751 /* Must be just one token in the string */
752 token = g_strdup (args);
753 args_after_prog = NULL;
758 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find what to exec", __func__);
760 SetLastError (ERROR_PATH_NOT_FOUND);
764 /* Turn all the slashes round the right way. Only for
767 switch_dir_separators(token);
769 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
770 /* Strip off the drive letter. I can't
771 * believe that CP/M holdover is still
774 g_memmove (token, token+2, strlen (token)-2);
775 token[strlen (token)-2] = '\0';
778 if (token[0] == '/') {
779 /* Assume full path given */
780 prog = g_strdup (token);
782 /* Executable existing ? */
783 if (!is_readable_or_executable (prog)) {
784 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s",
787 SetLastError (ERROR_FILE_NOT_FOUND);
791 char *curdir = g_get_current_dir ();
793 /* FIXME: Need to record the directory
794 * containing the current process, and check
795 * that for the new executable as the first
799 prog = g_strdup_printf ("%s/%s", curdir, token);
802 /* I assume X_OK is the criterion to use,
805 * X_OK is too strict *if* the target is a CLR binary
807 if (!is_readable_or_executable (prog)) {
809 prog = g_find_program_in_path (token);
811 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s", __func__, token);
814 SetLastError (ERROR_FILE_NOT_FOUND);
823 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Exec prog [%s] args [%s]", __func__, prog,
826 /* Check for CLR binaries; if found, we will try to invoke
827 * them using the same mono binary that started us.
829 if (is_managed_binary (prog)) {
830 gunichar2 *newapp = NULL, *newcmd;
834 newapp = mono_unicode_from_external (cli_launcher, &bytes_ignored);
836 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
838 if (newapp != NULL) {
839 if (appname != NULL) {
840 newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space,
841 appname, utf16_space,
844 newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space,
848 g_free ((gunichar2 *)newapp);
850 if (newcmd != NULL) {
851 ret = CreateProcess (NULL, newcmd,
855 create_flags, new_environ,
859 g_free ((gunichar2 *)newcmd);
865 if (!is_executable (prog)) {
866 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Executable permisson not set on %s", __func__, prog);
867 SetLastError (ERROR_ACCESS_DENIED);
872 if (args_after_prog != NULL && *args_after_prog) {
875 qprog = g_shell_quote (prog);
876 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
879 full_prog = g_shell_quote (prog);
882 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
884 g_message ("CreateProcess: %s\n", gerr->message);
890 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
891 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
892 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
893 err_fd = GPOINTER_TO_UINT (startup->hStdError);
895 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
896 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
897 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
900 process_handle.proc_name = g_strdup (prog);
902 process_set_defaults (&process_handle);
904 handle = mono_w32handle_new (MONO_W32HANDLE_PROCESS, &process_handle);
905 if (handle == INVALID_HANDLE_VALUE) {
906 g_warning ("%s: error creating process handle", __func__);
909 SetLastError (ERROR_OUTOFMEMORY);
913 /* new_environ is a block of NULL-terminated strings, which
914 * is itself NULL-terminated. Of course, passing an array of
915 * string pointers would have made things too easy :-(
917 * If new_environ is not NULL it specifies the entire set of
918 * environment variables in the new process. Otherwise the
919 * new process inherits the same environment.
922 gunichar2 *new_environp;
924 /* Count the number of strings */
925 for (new_environp = (gunichar2 *)new_environ; *new_environp;
928 while (*new_environp) {
933 /* +2: one for the process handle value, and the last
936 env_strings = g_new0 (char *, env_count + 2);
938 /* Copy each environ string into 'strings' turning it
939 * into utf8 (or the requested encoding) at the same
943 for (new_environp = (gunichar2 *)new_environ; *new_environp;
945 env_strings[env_count] = mono_unicode_to_external (new_environp);
947 while (*new_environp) {
952 for (i = 0; environ[i] != NULL; i++)
955 /* +2: one for the process handle value, and the last
958 env_strings = g_new0 (char *, env_count + 2);
960 /* Copy each environ string into 'strings' turning it
961 * into utf8 (or the requested encoding) at the same
965 for (i = 0; environ[i] != NULL; i++) {
966 env_strings[env_count] = g_strdup (environ[i]);
971 /* Create a pipe to make sure the child doesn't exit before
972 * we can add the process to the linked list of mono_processes */
973 if (pipe (startup_pipe) == -1) {
974 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
975 * This is just for a very hard to hit race condition in the first place */
976 startup_pipe [0] = startup_pipe [1] = -1;
977 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
980 switch (pid = fork ()) {
981 case -1: /* Error */ {
982 SetLastError (ERROR_OUTOFMEMORY);
987 case 0: /* Child */ {
988 if (startup_pipe [0] != -1) {
989 /* Wait until the parent has updated it's internal data */
990 ssize_t _i G_GNUC_UNUSED = read (startup_pipe [0], &dummy, 1);
991 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: child: parent has completed its setup", __func__);
992 close (startup_pipe [0]);
993 close (startup_pipe [1]);
996 /* should we detach from the process group? */
998 /* Connect stdin, stdout and stderr */
1003 if (inherit_handles != TRUE) {
1004 /* FIXME: do something here */
1007 /* Close all file descriptors */
1008 for (i = mono_w32handle_fd_reserve - 1; i > 2; i--)
1011 #ifdef DEBUG_ENABLED
1012 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1013 dir == NULL?".":dir);
1014 for (i = 0; argv[i] != NULL; i++)
1015 g_message ("arg %d: [%s]", i, argv[i]);
1017 for (i = 0; env_strings[i] != NULL; i++)
1018 g_message ("env %d: [%s]", i, env_strings[i]);
1022 if (dir != NULL && chdir (dir) == -1) {
1028 execve (argv[0], argv, env_strings);
1035 default: /* Parent */ {
1036 process_handle_data = lookup_process_handle (handle);
1037 if (!process_handle_data) {
1038 g_warning ("%s: error looking up process handle %p", __func__, handle);
1039 mono_w32handle_unref (handle);
1041 process_handle_data->id = pid;
1043 /* Add our mono_process into the linked list of mono_processes */
1044 mono_process = (struct MonoProcess *) g_malloc0 (sizeof (struct MonoProcess));
1045 mono_process->pid = pid;
1046 mono_process->handle_count = 1;
1047 mono_os_sem_init (&mono_process->exit_sem, 0);
1049 /* Keep the process handle artificially alive until the process
1050 * exits so that the information in the handle isn't lost. */
1051 mono_w32handle_ref (handle);
1052 mono_process->handle = handle;
1054 process_handle_data->mono_process = mono_process;
1056 mono_os_mutex_lock (&mono_processes_mutex);
1057 mono_process->next = mono_processes;
1058 mono_processes = mono_process;
1059 mono_os_mutex_unlock (&mono_processes_mutex);
1061 if (process_info != NULL) {
1062 process_info->hProcess = handle;
1063 process_info->dwProcessId = pid;
1065 /* FIXME: we might need to handle the thread info some day */
1066 process_info->hThread = INVALID_HANDLE_VALUE;
1067 process_info->dwThreadId = 0;
1076 mono_w32handle_unref (handle);
1078 if (startup_pipe [1] != -1) {
1079 /* Write 1 byte, doesn't matter what */
1080 ssize_t _i G_GNUC_UNUSED = write (startup_pipe [1], startup_pipe, 1);
1081 close (startup_pipe [0]);
1082 close (startup_pipe [1]);
1097 g_strfreev (env_strings);
1101 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: returning handle %p for pid %d", __func__, handle, pid);
1103 /* Check if something needs to be cleaned up. */
1104 mono_processes_cleanup ();
1108 SetLastError (ERROR_NOT_SUPPORTED);
1110 #endif // defined (HAVE_FORK) && defined (HAVE_EXECVE)
1114 process_set_name (WapiHandle_process *process_handle)
1116 char *progname, *utf8_progname, *slash;
1118 progname = g_get_prgname ();
1119 utf8_progname = mono_utf8_from_external (progname);
1121 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: using [%s] as prog name", __func__, progname);
1123 if (utf8_progname) {
1124 slash = strrchr (utf8_progname, '/');
1126 process_handle->proc_name = g_strdup (slash+1);
1128 process_handle->proc_name = g_strdup (utf8_progname);
1129 g_free (utf8_progname);
1134 _wapi_processes_init (void)
1136 pid_t pid = wapi_getpid ();
1137 WapiHandle_process process_handle = {0};
1139 mono_w32handle_register_ops (MONO_W32HANDLE_PROCESS, &_wapi_process_ops);
1141 mono_w32handle_register_capabilities (MONO_W32HANDLE_PROCESS,
1142 (MonoW32HandleCapability)(MONO_W32HANDLE_CAP_WAIT | MONO_W32HANDLE_CAP_SPECIAL_WAIT));
1144 process_handle.id = pid;
1146 process_set_defaults (&process_handle);
1147 process_set_name (&process_handle);
1149 current_process = mono_w32handle_new (MONO_W32HANDLE_PROCESS,
1151 g_assert (current_process);
1153 mono_os_mutex_init (&mono_processes_mutex);
1157 _wapi_process_duplicate (void)
1159 mono_w32handle_ref (current_process);
1161 return current_process;
1164 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1166 GetCurrentProcess (void)
1168 return _WAPI_PROCESS_CURRENT;
1172 GetProcessId (gpointer handle)
1174 WapiHandle_process *process_handle;
1176 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1177 /* This is a pseudo handle */
1178 return WAPI_HANDLE_TO_PID (handle);
1180 process_handle = lookup_process_handle (handle);
1181 if (!process_handle) {
1182 SetLastError (ERROR_INVALID_HANDLE);
1186 return process_handle->id;
1190 process_open_compare (gpointer handle, gpointer user_data)
1193 WapiHandle_process *process_handle;
1196 g_assert (!WAPI_IS_PSEUDO_PROCESS_HANDLE (handle));
1198 process_handle = lookup_process_handle (handle);
1199 g_assert (process_handle);
1201 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking at process %d", __func__, process_handle->id);
1203 checking_pid = process_handle->id;
1205 if (checking_pid == 0)
1208 wanted_pid = GPOINTER_TO_UINT (user_data);
1210 /* It's possible to have more than one process handle with the
1211 * same pid, but only the one running process can be
1214 if (checking_pid == wanted_pid &&
1215 !mono_w32handle_issignalled (handle)) {
1216 /* If the handle is blown away in the window between
1217 * returning TRUE here and mono_w32handle_search pinging
1218 * the timestamp, the search will continue
1227 CloseProcess (gpointer handle)
1229 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1231 return CloseHandle (handle);
1235 * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1238 OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1240 /* Find the process handle that corresponds to pid */
1241 gpointer handle = NULL;
1243 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking for process %d", __func__, pid);
1245 handle = mono_w32handle_search (MONO_W32HANDLE_PROCESS,
1246 process_open_compare,
1247 GUINT_TO_POINTER (pid), NULL, TRUE);
1249 if (is_pid_valid (pid)) {
1250 /* Return a pseudo handle for processes we
1251 * don't have handles for
1253 return WAPI_PID_TO_HANDLE (pid);
1255 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find pid %d", __func__, pid);
1257 SetLastError (ERROR_PROC_NOT_FOUND);
1263 /* mono_w32handle_search () already added a ref */
1268 GetExitCodeProcess (gpointer process, guint32 *code)
1270 WapiHandle_process *process_handle;
1277 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1278 pid = WAPI_HANDLE_TO_PID (process);
1279 /* This is a pseudo handle, so we don't know what the
1280 * exit code was, but we can check whether it's alive or not
1282 if (is_pid_valid (pid)) {
1283 *code = STILL_ACTIVE;
1291 process_handle = lookup_process_handle (process);
1292 if (!process_handle) {
1293 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
1298 if (process_handle->id == wapi_getpid ()) {
1299 *code = STILL_ACTIVE;
1303 /* A process handle is only signalled if the process has exited
1304 * and has been waited for */
1306 /* Make sure any process exit has been noticed, before
1307 * checking if the process is signalled. Fixes bug 325463.
1309 process_wait (process, 0, &alerted);
1311 if (mono_w32handle_issignalled (process))
1312 *code = process_handle->exitstatus;
1314 *code = STILL_ACTIVE;
1320 GetProcessTimes (gpointer process, WapiFileTime *create_time,
1321 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1322 WapiFileTime *user_time)
1324 WapiHandle_process *process_handle;
1325 gboolean ku_times_set = FALSE;
1327 if (create_time == NULL || exit_time == NULL || kernel_time == NULL ||
1329 /* Not sure if w32 allows NULLs here or not */
1332 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1333 gpointer pid = GINT_TO_POINTER (WAPI_HANDLE_TO_PID(process));
1334 gint64 start_ticks, user_ticks, kernel_ticks;
1336 mono_process_get_times (pid, &start_ticks, &user_ticks, &kernel_ticks);
1338 _wapi_guint64_to_filetime (start_ticks, create_time);
1339 _wapi_guint64_to_filetime (user_ticks, kernel_time);
1340 _wapi_guint64_to_filetime (kernel_ticks, user_time);
1345 process_handle = lookup_process_handle (process);
1346 if (!process_handle) {
1347 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
1352 *create_time = process_handle->create_time;
1354 /* A process handle is only signalled if the process has
1355 * exited. Otherwise exit_time isn't set
1357 if (mono_w32handle_issignalled (process))
1358 *exit_time = process_handle->exit_time;
1360 #ifdef HAVE_GETRUSAGE
1361 if (process_handle->id == getpid ()) {
1362 struct rusage time_data;
1363 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1365 ku_times_set = TRUE;
1366 tick_val = (guint64)time_data.ru_utime.tv_sec * 10000000 + (guint64)time_data.ru_utime.tv_usec * 10;
1367 _wapi_guint64_to_filetime (tick_val, user_time);
1368 tick_val = (guint64)time_data.ru_stime.tv_sec * 10000000 + (guint64)time_data.ru_stime.tv_usec * 10;
1369 _wapi_guint64_to_filetime (tick_val, kernel_time);
1373 if (!ku_times_set) {
1374 memset (kernel_time, 0, sizeof (WapiFileTime));
1375 memset (user_time, 0, sizeof (WapiFileTime));
1383 gpointer address_start;
1384 gpointer address_end;
1386 gpointer address_offset;
1392 static void free_procmodule (WapiProcModule *mod)
1394 if (mod->perms != NULL) {
1395 g_free (mod->perms);
1397 if (mod->filename != NULL) {
1398 g_free (mod->filename);
1403 static gint find_procmodule (gconstpointer a, gconstpointer b)
1405 WapiProcModule *want = (WapiProcModule *)a;
1406 WapiProcModule *compare = (WapiProcModule *)b;
1408 if ((want->device == compare->device) &&
1409 (want->inode == compare->inode)) {
1416 #if defined(USE_OSX_LOADER)
1417 #include <mach-o/dyld.h>
1418 #include <mach-o/getsect.h>
1420 static GSList *load_modules (void)
1423 WapiProcModule *mod;
1424 uint32_t count = _dyld_image_count ();
1427 for (i = 0; i < count; i++) {
1428 #if SIZEOF_VOID_P == 8
1429 const struct mach_header_64 *hdr;
1430 const struct section_64 *sec;
1432 const struct mach_header *hdr;
1433 const struct section *sec;
1437 name = _dyld_get_image_name (i);
1438 #if SIZEOF_VOID_P == 8
1439 hdr = (const struct mach_header_64*)_dyld_get_image_header (i);
1440 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1442 hdr = _dyld_get_image_header (i);
1443 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1446 /* Some dynlibs do not have data sections on osx (#533893) */
1451 mod = g_new0 (WapiProcModule, 1);
1452 mod->address_start = GINT_TO_POINTER (sec->addr);
1453 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1454 mod->perms = g_strdup ("r--p");
1455 mod->address_offset = 0;
1456 mod->device = makedev (0, 0);
1458 mod->filename = g_strdup (name);
1460 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1461 ret = g_slist_prepend (ret, mod);
1463 free_procmodule (mod);
1467 ret = g_slist_reverse (ret);
1471 #elif defined(USE_BSD_LOADER)
1473 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1475 if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1476 + sizeof (info->dlpi_phnum))
1479 struct dl_phdr_info *cpy = g_calloc (1, sizeof(struct dl_phdr_info));
1483 memcpy(cpy, info, sizeof(*info));
1485 g_ptr_array_add ((GPtrArray *)ptr, cpy);
1490 static GSList *load_modules (void)
1493 WapiProcModule *mod;
1494 GPtrArray *dlarray = g_ptr_array_new();
1497 if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1500 for (i = 0; i < dlarray->len; i++) {
1501 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1503 mod = g_new0 (WapiProcModule, 1);
1504 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1505 mod->address_end = (gpointer)(info->dlpi_addr +
1506 info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1507 mod->perms = g_strdup ("r--p");
1508 mod->address_offset = 0;
1510 mod->filename = g_strdup (info->dlpi_name);
1512 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1513 mod->inode, mod->filename, mod->address_start, mod->address_end);
1517 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1518 ret = g_slist_prepend (ret, mod);
1520 free_procmodule (mod);
1524 g_ptr_array_free (dlarray, TRUE);
1526 ret = g_slist_reverse (ret);
1530 #elif defined(USE_HAIKU_LOADER)
1532 static GSList *load_modules (void)
1535 WapiProcModule *mod;
1537 image_info imageInfo;
1539 while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
1540 mod = g_new0 (WapiProcModule, 1);
1541 mod->device = imageInfo.device;
1542 mod->inode = imageInfo.node;
1543 mod->filename = g_strdup (imageInfo.name);
1544 mod->address_start = MIN (imageInfo.text, imageInfo.data);
1545 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
1546 (uint8_t*)imageInfo.data + imageInfo.data_size);
1547 mod->perms = g_strdup ("r--p");
1548 mod->address_offset = 0;
1550 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1551 ret = g_slist_prepend (ret, mod);
1553 free_procmodule (mod);
1557 ret = g_slist_reverse (ret);
1562 static GSList *load_modules (FILE *fp)
1565 WapiProcModule *mod;
1566 char buf[MAXPATHLEN + 1], *p, *endp;
1567 char *start_start, *end_start, *prot_start, *offset_start;
1568 char *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1569 gpointer address_start, address_end, address_offset;
1570 guint32 maj_dev, min_dev;
1574 while (fgets (buf, sizeof(buf), fp)) {
1576 while (g_ascii_isspace (*p)) ++p;
1578 if (!g_ascii_isxdigit (*start_start)) {
1581 address_start = (gpointer)strtoul (start_start, &endp, 16);
1589 if (!g_ascii_isxdigit (*end_start)) {
1592 address_end = (gpointer)strtoul (end_start, &endp, 16);
1594 if (!g_ascii_isspace (*p)) {
1598 while (g_ascii_isspace (*p)) ++p;
1600 if (*prot_start != 'r' && *prot_start != '-') {
1603 memcpy (prot_buf, prot_start, 4);
1605 while (!g_ascii_isspace (*p)) ++p;
1607 while (g_ascii_isspace (*p)) ++p;
1609 if (!g_ascii_isxdigit (*offset_start)) {
1612 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1614 if (!g_ascii_isspace (*p)) {
1618 while(g_ascii_isspace (*p)) ++p;
1620 if (!g_ascii_isxdigit (*maj_dev_start)) {
1623 maj_dev = strtoul (maj_dev_start, &endp, 16);
1631 if (!g_ascii_isxdigit (*min_dev_start)) {
1634 min_dev = strtoul (min_dev_start, &endp, 16);
1636 if (!g_ascii_isspace (*p)) {
1640 while (g_ascii_isspace (*p)) ++p;
1642 if (!g_ascii_isxdigit (*inode_start)) {
1645 inode = (guint64)strtol (inode_start, &endp, 10);
1647 if (!g_ascii_isspace (*p)) {
1651 device = makedev ((int)maj_dev, (int)min_dev);
1652 if ((device == 0) &&
1657 while(g_ascii_isspace (*p)) ++p;
1658 /* p now points to the filename */
1660 mod = g_new0 (WapiProcModule, 1);
1661 mod->address_start = address_start;
1662 mod->address_end = address_end;
1663 mod->perms = g_strdup (prot_buf);
1664 mod->address_offset = address_offset;
1665 mod->device = device;
1667 mod->filename = g_strdup (g_strstrip (p));
1669 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1670 ret = g_slist_prepend (ret, mod);
1672 free_procmodule (mod);
1676 ret = g_slist_reverse (ret);
1682 static gboolean match_procname_to_modulename (char *procname, char *modulename)
1684 char* lastsep = NULL;
1685 char* lastsep2 = NULL;
1688 gboolean result = FALSE;
1690 if (procname == NULL || modulename == NULL)
1693 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: procname=\"%s\", modulename=\"%s\"", __func__, procname, modulename);
1694 pname = mono_path_resolve_symlinks (procname);
1695 mname = mono_path_resolve_symlinks (modulename);
1697 if (!strcmp (pname, mname))
1701 lastsep = strrchr (mname, '/');
1703 if (!strcmp (lastsep+1, pname))
1706 lastsep2 = strrchr (pname, '/');
1709 if (!strcmp (lastsep+1, lastsep2+1))
1712 if (!strcmp (mname, lastsep2+1))
1722 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: result is %d", __func__, result);
1726 #if !(defined(USE_OSX_LOADER) || defined(USE_BSD_LOADER) || defined(USE_HAIKU_LOADER))
1728 open_process_map (int pid, const char *mode)
1731 const char *proc_path[] = {
1732 "/proc/%d/maps", /* GNU/Linux */
1733 "/proc/%d/map", /* FreeBSD */
1739 for (i = 0; fp == NULL && proc_path [i]; i++) {
1740 filename = g_strdup_printf (proc_path[i], pid);
1741 fp = fopen (filename, mode);
1749 static char *get_process_name_from_proc (pid_t pid);
1751 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1752 guint32 size, guint32 *needed)
1754 WapiHandle_process *process_handle;
1755 #if !defined(USE_OSX_LOADER) && !defined(USE_BSD_LOADER)
1758 GSList *mods = NULL;
1759 WapiProcModule *module;
1760 guint32 count, avail = size / sizeof(gpointer);
1763 char *proc_name = NULL;
1765 /* Store modules in an array of pointers (main module as
1766 * modules[0]), using the load address for each module as a
1767 * token. (Use 'NULL' as an alternative for the main module
1768 * so that the simple implementation can just return one item
1769 * for now.) Get the info from /proc/<pid>/maps on linux,
1770 * /proc/<pid>/map on FreeBSD, other systems will have to
1771 * implement /dev/kmem reading or whatever other horrid
1772 * technique is needed.
1774 if (size < sizeof(gpointer))
1777 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1778 pid = WAPI_HANDLE_TO_PID (process);
1779 proc_name = get_process_name_from_proc (pid);
1781 process_handle = lookup_process_handle (process);
1782 if (!process_handle) {
1783 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
1787 pid = process_handle->id;
1788 proc_name = g_strdup (process_handle->proc_name);
1791 #if defined(USE_OSX_LOADER) || defined(USE_BSD_LOADER) || defined(USE_HAIKU_LOADER)
1792 mods = load_modules ();
1795 *needed = sizeof(gpointer);
1799 fp = open_process_map (pid, "r");
1801 /* No /proc/<pid>/maps so just return the main module
1805 *needed = sizeof(gpointer);
1809 mods = load_modules (fp);
1812 count = g_slist_length (mods);
1814 /* count + 1 to leave slot 0 for the main module */
1815 *needed = sizeof(gpointer) * (count + 1);
1818 * Use the NULL shortcut, as the first line in
1819 * /proc/<pid>/maps isn't the executable, and we need
1820 * that first in the returned list. Check the module name
1821 * to see if it ends with the proc name and substitute
1822 * the first entry with it. FIXME if this turns out to
1826 for (i = 0; i < (avail - 1) && i < count; i++) {
1827 module = (WapiProcModule *)g_slist_nth_data (mods, i);
1828 if (modules[0] != NULL)
1829 modules[i] = module->address_start;
1830 else if (match_procname_to_modulename (proc_name, module->filename))
1831 modules[0] = module->address_start;
1833 modules[i + 1] = module->address_start;
1836 for (i = 0; i < count; i++) {
1837 free_procmodule ((WapiProcModule *)g_slist_nth_data (mods, i));
1839 g_slist_free (mods);
1846 get_process_name_from_proc (pid_t pid)
1848 #if defined(USE_BSD_LOADER)
1851 struct kinfo_proc *pi;
1852 #elif defined(USE_OSX_LOADER)
1853 #if !(!defined (__mono_ppc__) && defined (TARGET_OSX))
1855 struct kinfo_proc *pi;
1856 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
1860 char *filename = NULL;
1865 #if defined(PLATFORM_SOLARIS)
1866 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
1867 if ((fp = fopen (filename, "r")) != NULL) {
1871 nread = fread (&info, sizeof (info), 1, fp);
1873 ret = g_strdup (info.pr_fname);
1879 #elif defined(USE_OSX_LOADER)
1880 #if !defined (__mono_ppc__) && defined (TARGET_OSX)
1881 /* No proc name on OSX < 10.5 nor ppc nor iOS */
1882 memset (buf, '\0', sizeof(buf));
1883 proc_name (pid, buf, sizeof(buf));
1885 // Fixes proc_name triming values to 15 characters #32539
1886 if (strlen (buf) >= MAXCOMLEN - 1) {
1887 char path_buf [PROC_PIDPATHINFO_MAXSIZE];
1891 memset (path_buf, '\0', sizeof(path_buf));
1892 path_len = proc_pidpath (pid, path_buf, sizeof(path_buf));
1894 if (path_len > 0 && path_len < sizeof(path_buf)) {
1895 name_buf = path_buf + path_len;
1896 for(;name_buf > path_buf; name_buf--) {
1897 if (name_buf [0] == '/') {
1903 if (memcmp (buf, name_buf, MAXCOMLEN - 1) == 0)
1904 ret = g_strdup (name_buf);
1908 if (ret == NULL && strlen (buf) > 0)
1909 ret = g_strdup (buf);
1911 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0)
1914 if ((pi = g_malloc (size)) == NULL)
1917 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
1918 if (errno == ENOMEM) {
1920 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't allocate enough memory for kproc info", __func__);
1925 if (strlen (pi->kp_proc.p_comm) > 0)
1926 ret = g_strdup (pi->kp_proc.p_comm);
1930 #elif defined(USE_BSD_LOADER)
1931 #if defined(__FreeBSD__)
1933 mib [1] = KERN_PROC;
1934 mib [2] = KERN_PROC_PID;
1936 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0) {
1937 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: sysctl() failed: %d", __func__, errno);
1941 if ((pi = g_malloc (size)) == NULL)
1944 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
1945 if (errno == ENOMEM) {
1947 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't allocate enough memory for kproc info", __func__);
1952 if (strlen (pi->ki_comm) > 0)
1953 ret = g_strdup (pi->ki_comm);
1955 #elif defined(__OpenBSD__)
1957 mib [1] = KERN_PROC;
1958 mib [2] = KERN_PROC_PID;
1960 mib [4] = sizeof(struct kinfo_proc);
1964 if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0) {
1965 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: sysctl() failed: %d", __func__, errno);
1969 if ((pi = g_malloc (size)) == NULL)
1972 mib[5] = (int)(size / sizeof(struct kinfo_proc));
1974 if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
1975 (size != sizeof (struct kinfo_proc))) {
1976 if (errno == ENOMEM) {
1983 if (strlen (pi->p_comm) > 0)
1984 ret = g_strdup (pi->p_comm);
1988 #elif defined(USE_HAIKU_LOADER)
1989 image_info imageInfo;
1992 if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
1993 ret = g_strdup (imageInfo.name);
1996 memset (buf, '\0', sizeof(buf));
1997 filename = g_strdup_printf ("/proc/%d/exe", pid);
1998 if (readlink (filename, buf, 255) > 0) {
1999 ret = g_strdup (buf);
2007 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
2008 if ((fp = fopen (filename, "r")) != NULL) {
2009 if (fgets (buf, 256, fp) != NULL) {
2010 ret = g_strdup (buf);
2021 filename = g_strdup_printf ("/proc/%d/stat", pid);
2022 if ((fp = fopen (filename, "r")) != NULL) {
2023 if (fgets (buf, 256, fp) != NULL) {
2026 start = strchr (buf, '(');
2027 if (start != NULL) {
2028 end = strchr (start + 1, ')');
2031 ret = g_strndup (start + 1,
2046 * wapi_process_get_path:
2048 * Return the full path of the executable of the process PID, or NULL if it cannot be determined.
2049 * Returns malloc-ed memory.
2052 wapi_process_get_path (pid_t pid)
2054 #if defined(PLATFORM_MACOSX) && !defined(__mono_ppc__) && defined(TARGET_OSX)
2055 char buf [PROC_PIDPATHINFO_MAXSIZE];
2058 res = proc_pidpath (pid, buf, sizeof (buf));
2061 if (buf [0] == '\0')
2063 return g_strdup (buf);
2065 return get_process_name_from_proc (pid);
2070 * wapi_process_set_cli_launcher:
2072 * Set the full path of the runtime executable used to launch managed exe's.
2075 wapi_process_set_cli_launcher (char *path)
2077 g_free (cli_launcher);
2078 cli_launcher = path ? g_strdup (path) : NULL;
2082 get_module_name (gpointer process, gpointer module,
2083 gunichar2 *basename, guint32 size,
2086 WapiHandle_process *process_handle;
2088 gunichar2 *procname;
2089 char *procname_ext = NULL;
2092 #if !defined(USE_OSX_LOADER) && !defined(USE_BSD_LOADER)
2095 GSList *mods = NULL;
2096 WapiProcModule *found_module;
2099 char *proc_name = NULL;
2101 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Getting module base name, process handle %p module %p",
2102 __func__, process, module);
2104 size = size * sizeof (gunichar2); /* adjust for unicode characters */
2106 if (basename == NULL || size == 0)
2109 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2110 /* This is a pseudo handle */
2111 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2112 proc_name = get_process_name_from_proc (pid);
2114 process_handle = lookup_process_handle (process);
2115 if (!process_handle) {
2116 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__,
2121 pid = process_handle->id;
2122 proc_name = g_strdup (process_handle->proc_name);
2125 /* Look up the address in /proc/<pid>/maps */
2126 #if defined(USE_OSX_LOADER) || defined(USE_BSD_LOADER) || defined(USE_HAIKU_LOADER)
2127 mods = load_modules ();
2129 fp = open_process_map (pid, "r");
2131 if (errno == EACCES && module == NULL && base == TRUE) {
2132 procname_ext = get_process_name_from_proc (pid);
2134 /* No /proc/<pid>/maps, so just return failure
2141 mods = load_modules (fp);
2145 count = g_slist_length (mods);
2147 /* If module != NULL compare the address.
2148 * If module == NULL we are looking for the main module.
2149 * The best we can do for now check it the module name end with the process name.
2151 for (i = 0; i < count; i++) {
2152 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2153 if (procname_ext == NULL &&
2154 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2155 (module != NULL && found_module->address_start == module))) {
2157 procname_ext = g_path_get_basename (found_module->filename);
2159 procname_ext = g_strdup (found_module->filename);
2162 free_procmodule (found_module);
2165 if (procname_ext == NULL) {
2166 /* If it's *still* null, we might have hit the
2167 * case where reading /proc/$pid/maps gives an
2168 * empty file for this user.
2170 procname_ext = get_process_name_from_proc (pid);
2173 g_slist_free (mods);
2177 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Process name is [%s]", __func__,
2180 procname = mono_unicode_from_external (procname_ext, &bytes);
2181 if (procname == NULL) {
2183 g_free (procname_ext);
2189 /* Add the terminator */
2193 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2195 memcpy (basename, procname, size);
2197 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %d larger than needed (%ld)",
2198 __func__, size, bytes);
2200 memcpy (basename, procname, bytes);
2204 g_free (procname_ext);
2213 get_module_filename (gpointer process, gpointer module,
2214 gunichar2 *basename, guint32 size)
2219 gunichar2 *proc_path;
2221 size *= sizeof (gunichar2); /* adjust for unicode characters */
2223 if (basename == NULL || size == 0)
2226 pid = GetProcessId (process);
2228 path = wapi_process_get_path (pid);
2232 proc_path = mono_unicode_from_external (path, &bytes);
2235 if (proc_path == NULL)
2240 /* Add the terminator */
2244 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2246 memcpy (basename, proc_path, size);
2248 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %d larger than needed (%ld)",
2249 __func__, size, bytes);
2251 memcpy (basename, proc_path, bytes);
2260 GetModuleBaseName (gpointer process, gpointer module,
2261 gunichar2 *basename, guint32 size)
2263 return get_module_name (process, module, basename, size, TRUE);
2267 GetModuleFileNameEx (gpointer process, gpointer module,
2268 gunichar2 *filename, guint32 size)
2270 return get_module_filename (process, module, filename, size);
2274 GetModuleInformation (gpointer process, gpointer module,
2275 WapiModuleInfo *modinfo, guint32 size)
2277 WapiHandle_process *process_handle;
2279 #if !defined(USE_OSX_LOADER) && !defined(USE_BSD_LOADER)
2282 GSList *mods = NULL;
2283 WapiProcModule *found_module;
2286 gboolean ret = FALSE;
2287 char *proc_name = NULL;
2289 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Getting module info, process handle %p module %p",
2290 __func__, process, module);
2292 if (modinfo == NULL || size < sizeof (WapiModuleInfo))
2295 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2296 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2297 proc_name = get_process_name_from_proc (pid);
2299 process_handle = lookup_process_handle (process);
2300 if (!process_handle) {
2301 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__,
2306 pid = process_handle->id;
2307 proc_name = g_strdup (process_handle->proc_name);
2310 #if defined(USE_OSX_LOADER) || defined(USE_BSD_LOADER) || defined(USE_HAIKU_LOADER)
2311 mods = load_modules ();
2313 /* Look up the address in /proc/<pid>/maps */
2314 if ((fp = open_process_map (pid, "r")) == NULL) {
2315 /* No /proc/<pid>/maps, so just return failure
2321 mods = load_modules (fp);
2324 count = g_slist_length (mods);
2326 /* If module != NULL compare the address.
2327 * If module == NULL we are looking for the main module.
2328 * The best we can do for now check it the module name end with the process name.
2330 for (i = 0; i < count; i++) {
2331 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2333 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2334 (module != NULL && found_module->address_start == module))) {
2335 modinfo->lpBaseOfDll = found_module->address_start;
2336 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2337 modinfo->EntryPoint = found_module->address_offset;
2341 free_procmodule (found_module);
2344 g_slist_free (mods);
2351 GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2353 WapiHandle_process *process_handle;
2355 if (min == NULL || max == NULL)
2356 /* Not sure if w32 allows NULLs here or not */
2359 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2360 /* This is a pseudo handle, so just fail for now */
2363 process_handle = lookup_process_handle (process);
2364 if (!process_handle) {
2365 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
2370 *min = process_handle->min_working_set;
2371 *max = process_handle->max_working_set;
2377 SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2379 WapiHandle_process *process_handle;
2381 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2382 /* This is a pseudo handle, so just fail for now
2386 process_handle = lookup_process_handle (process);
2387 if (!process_handle) {
2388 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
2393 process_handle->min_working_set = min;
2394 process_handle->max_working_set = max;
2401 TerminateProcess (gpointer process, gint32 exitCode)
2403 #if defined(HAVE_KILL)
2404 WapiHandle_process *process_handle;
2409 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2410 /* This is a pseudo handle */
2411 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2413 process_handle = lookup_process_handle (process);
2414 if (!process_handle) {
2415 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
2416 SetLastError (ERROR_INVALID_HANDLE);
2419 pid = process_handle->id;
2422 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2423 ret = kill (pid, signo);
2427 SetLastError (ERROR_INVALID_PARAMETER);
2430 SetLastError (ERROR_ACCESS_DENIED);
2433 SetLastError (ERROR_PROC_NOT_FOUND);
2436 SetLastError (ERROR_GEN_FAILURE);
2442 g_error ("kill() is not supported by this platform");
2448 GetPriorityClass (gpointer process)
2450 #ifdef HAVE_GETPRIORITY
2451 WapiHandle_process *process_handle;
2455 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2456 /* This is a pseudo handle */
2457 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2459 process_handle = lookup_process_handle (process);
2460 if (!process_handle) {
2461 SetLastError (ERROR_INVALID_HANDLE);
2464 pid = process_handle->id;
2468 ret = getpriority (PRIO_PROCESS, pid);
2469 if (ret == -1 && errno != 0) {
2473 SetLastError (ERROR_ACCESS_DENIED);
2476 SetLastError (ERROR_PROC_NOT_FOUND);
2479 SetLastError (ERROR_GEN_FAILURE);
2485 return NORMAL_PRIORITY_CLASS;
2487 return REALTIME_PRIORITY_CLASS;
2489 return HIGH_PRIORITY_CLASS;
2491 return ABOVE_NORMAL_PRIORITY_CLASS;
2493 return IDLE_PRIORITY_CLASS;
2495 return BELOW_NORMAL_PRIORITY_CLASS;
2497 return NORMAL_PRIORITY_CLASS;
2499 SetLastError (ERROR_NOT_SUPPORTED);
2505 SetPriorityClass (gpointer process, guint32 priority_class)
2507 #ifdef HAVE_SETPRIORITY
2508 WapiHandle_process *process_handle;
2513 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2514 /* This is a pseudo handle */
2515 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2517 process_handle = lookup_process_handle (process);
2518 if (!process_handle) {
2519 SetLastError (ERROR_INVALID_HANDLE);
2522 pid = process_handle->id;
2525 switch (priority_class) {
2526 case IDLE_PRIORITY_CLASS:
2529 case BELOW_NORMAL_PRIORITY_CLASS:
2532 case NORMAL_PRIORITY_CLASS:
2535 case ABOVE_NORMAL_PRIORITY_CLASS:
2538 case HIGH_PRIORITY_CLASS:
2541 case REALTIME_PRIORITY_CLASS:
2545 SetLastError (ERROR_INVALID_PARAMETER);
2549 ret = setpriority (PRIO_PROCESS, pid, prio);
2554 SetLastError (ERROR_ACCESS_DENIED);
2557 SetLastError (ERROR_PROC_NOT_FOUND);
2560 SetLastError (ERROR_GEN_FAILURE);
2566 SetLastError (ERROR_NOT_SUPPORTED);
2572 mono_processes_cleanup (void)
2574 struct MonoProcess *mp;
2575 struct MonoProcess *prev = NULL;
2576 GSList *finished = NULL;
2578 gpointer unref_handle;
2580 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s", __func__);
2582 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2583 if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
2586 for (mp = mono_processes; mp; mp = mp->next) {
2587 if (mp->pid == 0 && mp->handle) {
2588 /* This process has exited and we need to remove the artifical ref
2590 mono_os_mutex_lock (&mono_processes_mutex);
2591 unref_handle = mp->handle;
2593 mono_os_mutex_unlock (&mono_processes_mutex);
2595 mono_w32handle_unref (unref_handle);
2600 * Remove processes which exited from the mono_processes list.
2601 * We need to synchronize with the sigchld handler here, which runs
2602 * asynchronously. The handler requires that the mono_processes list
2605 mono_os_mutex_lock (&mono_processes_mutex);
2607 mp = mono_processes;
2609 if (mp->handle_count == 0 && mp->freeable) {
2612 * This code can run parallel with the sigchld handler, but the
2613 * modifications it makes are safe.
2615 if (mp == mono_processes)
2616 mono_processes = mp->next;
2618 prev->next = mp->next;
2619 finished = g_slist_prepend (finished, mp);
2628 mono_memory_barrier ();
2630 for (l = finished; l; l = l->next) {
2632 * All the entries in the finished list are unlinked from mono_processes, and
2633 * they have the 'finished' flag set, which means the sigchld handler is done
2636 mp = (MonoProcess *)l->data;
2637 mono_os_sem_destroy (&mp->exit_sem);
2640 g_slist_free (finished);
2642 mono_os_mutex_unlock (&mono_processes_mutex);
2644 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s done", __func__);
2646 InterlockedDecrement (&mono_processes_cleaning_up);
2650 process_close (gpointer handle, gpointer data)
2652 WapiHandle_process *process_handle;
2654 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s", __func__);
2656 process_handle = (WapiHandle_process *) data;
2657 g_free (process_handle->proc_name);
2658 process_handle->proc_name = NULL;
2659 if (process_handle->mono_process)
2660 InterlockedDecrement (&process_handle->mono_process->handle_count);
2661 mono_processes_cleanup ();
2664 static void process_details (gpointer data)
2666 WapiHandle_process *process_handle = (WapiHandle_process *) data;
2667 g_print ("id: %d, exited: %s, exitstatus: %d",
2668 process_handle->id, process_handle->exited ? "true" : "false", process_handle->exitstatus);
2671 static const gchar* process_typename (void)
2676 static gsize process_typesize (void)
2678 return sizeof (WapiHandle_process);
2682 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
2686 struct MonoProcess *p;
2688 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "SIG CHILD handler for pid: %i\n", info->si_pid);
2692 pid = waitpid (-1, &status, WNOHANG);
2693 } while (pid == -1 && errno == EINTR);
2698 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "child ended: %i", pid);
2701 * This can run concurrently with the code in the rest of this module.
2703 for (p = mono_processes; p; p = p->next) {
2704 if (p->pid == pid) {
2709 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2711 mono_os_sem_post (&p->exit_sem);
2712 mono_memory_barrier ();
2713 /* Mark this as freeable, the pointer becomes invalid afterwards */
2718 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "SIG CHILD handler: done looping.");
2724 process_add_sigchld_handler (void)
2727 struct sigaction sa;
2729 sa.sa_sigaction = mono_sigchld_signal_handler;
2730 sigemptyset (&sa.sa_mask);
2731 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2732 g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2733 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "Added SIGCHLD handler");
2738 process_wait (gpointer handle, guint32 timeout, gboolean *alerted)
2740 WapiHandle_process *process_handle;
2741 pid_t pid G_GNUC_UNUSED, ret;
2744 struct MonoProcess *mp;
2746 /* FIXME: We can now easily wait on processes that aren't our own children,
2747 * but WaitFor*Object won't call us for pseudo handles. */
2748 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2750 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u)", __func__, handle, timeout);
2755 process_handle = lookup_process_handle (handle);
2756 if (!process_handle) {
2757 g_warning ("%s: error looking up process handle %p", __func__, handle);
2761 if (process_handle->exited) {
2762 /* We've already done this one */
2763 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): Process already exited", __func__, handle, timeout);
2764 return WAIT_OBJECT_0;
2767 pid = process_handle->id;
2769 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2771 /* We don't need to lock mono_processes here, the entry
2772 * has a handle_count > 0 which means it will not be freed. */
2773 mp = process_handle->mono_process;
2777 if (pid == mono_process_current_pid ()) {
2778 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on current process", __func__, handle, timeout);
2779 return WAIT_TIMEOUT;
2782 /* This path is used when calling Process.HasExited, so
2783 * it is only used to poll the state of the process, not
2784 * to actually wait on it to exit */
2785 g_assert (timeout == 0);
2787 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on non-child process", __func__, handle, timeout);
2789 res = waitpid (pid, &status, WNOHANG);
2791 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): non-child process WAIT_TIMEOUT", __func__, handle, timeout);
2792 return WAIT_TIMEOUT;
2795 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): non-child process waited successfully", __func__, handle, timeout);
2796 return WAIT_OBJECT_0;
2799 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): non-child process WAIT_FAILED, error : %s (%d))", __func__, handle, timeout, g_strerror (errno), errno);
2803 start = mono_msec_ticks ();
2807 if (timeout != INFINITE) {
2808 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on semaphore for %li ms...",
2809 __func__, handle, timeout, (timeout - (now - start)));
2810 ret = mono_os_sem_timedwait (&mp->exit_sem, (timeout - (now - start)), alerted ? MONO_SEM_FLAGS_ALERTABLE : MONO_SEM_FLAGS_NONE);
2812 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on semaphore forever...",
2813 __func__, handle, timeout);
2814 ret = mono_os_sem_wait (&mp->exit_sem, alerted ? MONO_SEM_FLAGS_ALERTABLE : MONO_SEM_FLAGS_NONE);
2817 if (ret == MONO_SEM_TIMEDWAIT_RET_SUCCESS) {
2818 /* Success, process has exited */
2819 mono_os_sem_post (&mp->exit_sem);
2823 if (ret == MONO_SEM_TIMEDWAIT_RET_TIMEDOUT) {
2824 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
2825 return WAIT_TIMEOUT;
2828 now = mono_msec_ticks ();
2829 if (now - start >= timeout) {
2830 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
2831 return WAIT_TIMEOUT;
2834 if (alerted && ret == MONO_SEM_TIMEDWAIT_RET_ALERTED) {
2835 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
2837 return WAIT_IO_COMPLETION;
2841 /* Process must have exited */
2842 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): Waited successfully", __func__, handle, timeout);
2844 status = mp ? mp->status : 0;
2845 if (WIFSIGNALED (status))
2846 process_handle->exitstatus = 128 + WTERMSIG (status);
2848 process_handle->exitstatus = WEXITSTATUS (status);
2849 _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
2851 process_handle->exited = TRUE;
2853 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): Setting pid %d signalled, exit status %d",
2854 __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
2856 mono_w32handle_set_signal_state (handle, TRUE, TRUE);
2858 return WAIT_OBJECT_0;
2862 wapi_processes_cleanup (void)
2864 g_free (cli_launcher);