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/handles-private.h>
99 #include <mono/io-layer/process-private.h>
100 #include <mono/io-layer/threads.h>
101 #include <mono/io-layer/io-trace.h>
102 #include <mono/utils/strenc.h>
103 #include <mono/utils/mono-path.h>
104 #include <mono/io-layer/timefuncs-private.h>
105 #include <mono/utils/mono-time.h>
106 #include <mono/utils/mono-membar.h>
107 #include <mono/utils/mono-os-mutex.h>
108 #include <mono/utils/mono-signal-handler.h>
109 #include <mono/utils/mono-proclib.h>
110 #include <mono/utils/mono-once.h>
111 #include <mono/utils/mono-logger-internals.h>
113 /* The process' environment strings */
114 #if defined(__APPLE__)
115 #if defined (TARGET_OSX)
116 /* Apple defines this in crt_externs.h but doesn't provide that header for
117 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
118 * in fact exist on all implementations (so far)
120 gchar ***_NSGetEnviron(void);
121 #define environ (*_NSGetEnviron())
123 static char *mono_environ[1] = { NULL };
124 #define environ mono_environ
125 #endif /* defined (TARGET_OSX) */
127 extern char **environ;
130 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable);
131 static void process_close (gpointer handle, gpointer data);
132 static gboolean is_pid_valid (pid_t pid);
134 #if !(defined(USE_OSX_LOADER) || defined(USE_BSD_LOADER) || defined(USE_HAIKU_LOADER))
136 open_process_map (int pid, const char *mode);
139 struct _WapiHandleOps _wapi_process_ops = {
140 process_close, /* close_shared */
144 process_wait, /* special_wait */
149 static struct sigaction previous_chld_sa;
151 static mono_once_t process_sig_chld_once = MONO_ONCE_INIT;
152 static void process_add_sigchld_handler (void);
154 /* The signal-safe logic to use mono_processes goes like this:
155 * - The list must be safe to traverse for the signal handler at all times.
156 * It's safe to: prepend an entry (which is a single store to 'mono_processes'),
157 * unlink an entry (assuming the unlinked entry isn't freed and doesn't
158 * change its 'next' pointer so that it can still be traversed).
159 * When cleaning up we first unlink an entry, then we verify that
160 * the read lock isn't locked. Then we can free the entry, since
161 * we know that nobody is using the old version of the list (including
162 * the unlinked entry).
163 * We also need to lock when adding and cleaning up so that those two
164 * operations don't mess with eachother. (This lock is not used in the
167 static struct MonoProcess *mono_processes = NULL;
168 static volatile gint32 mono_processes_cleaning_up = 0;
169 static mono_mutex_t mono_processes_mutex;
170 static void mono_processes_cleanup (void);
172 static gpointer current_process;
173 static char *cli_launcher;
175 static WapiHandle_process *
176 lookup_process_handle (gpointer handle)
178 WapiHandle_process *process_data;
181 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
182 (gpointer *)&process_data);
188 /* Check if a pid is valid - i.e. if a process exists with this pid. */
190 is_pid_valid (pid_t pid)
192 gboolean result = FALSE;
194 #if defined(HOST_WATCHOS)
195 result = TRUE; // TODO: Rewrite using sysctl
196 #elif defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__)
197 if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
199 #elif defined(__HAIKU__)
201 if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
204 char *dir = g_strdup_printf ("/proc/%d", pid);
205 if (!access (dir, F_OK))
214 process_set_defaults (WapiHandle_process *process_handle)
216 /* These seem to be the defaults on w2k */
217 process_handle->min_working_set = 204800;
218 process_handle->max_working_set = 1413120;
220 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
224 len16 (const gunichar2 *str)
235 utf16_concat (const gunichar2 *first, ...)
242 va_start (args, first);
243 total += len16 (first);
244 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
249 ret = g_new (gunichar2, total + 1);
255 for (s = first; *s != 0; s++)
257 va_start (args, first);
258 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
261 for (p = s; *p != 0; p++)
269 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
270 static const gunichar2 *utf16_space = utf16_space_bytes;
271 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
272 static const gunichar2 *utf16_quote = utf16_quote_bytes;
277 print_utf16 (gunichar2 *str)
281 res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
282 g_print ("%s\n", res);
287 /* Implemented as just a wrapper around CreateProcess () */
289 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. */
307 /* Put both executable and parameters into the second argument
308 * to CreateProcess (), so it searches $PATH. The conversion
309 * into and back out of utf8 is because there is no
310 * g_strdup_printf () equivalent for gunichar2 :-(
312 args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
314 SetLastError (ERROR_INVALID_DATA);
317 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
318 CREATE_UNICODE_ENVIRONMENT, NULL,
319 sei->lpDirectory, NULL, &process_info);
322 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
326 static char *handler;
327 static gunichar2 *handler_utf16;
329 if (handler_utf16 == (gunichar2 *)-1)
332 #ifdef PLATFORM_MACOSX
333 handler = g_strdup ("/usr/bin/open");
336 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
337 * if that fails, try to use gnome-open, then kfmclient
339 handler = g_find_program_in_path ("xdg-open");
340 if (handler == NULL){
341 handler = g_find_program_in_path ("gnome-open");
342 if (handler == NULL){
343 handler = g_find_program_in_path ("kfmclient");
344 if (handler == NULL){
345 handler_utf16 = (gunichar2 *) -1;
348 /* kfmclient needs exec argument */
350 handler = g_strconcat (old, " exec",
357 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
360 /* Put quotes around the filename, in case it's a url
361 * that contains #'s (CreateProcess() calls
362 * g_shell_parse_argv(), which deliberately throws
363 * away anything after an unquoted #). Fixes bug
366 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
367 sei->lpFile, utf16_quote,
368 sei->lpParameters == NULL ? NULL : utf16_space,
369 sei->lpParameters, NULL);
371 SetLastError (ERROR_INVALID_DATA);
374 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
375 CREATE_UNICODE_ENVIRONMENT, NULL,
376 sei->lpDirectory, NULL, &process_info);
379 if (GetLastError () != ERROR_OUTOFMEMORY)
380 SetLastError (ERROR_INVALID_DATA);
383 /* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
384 CloseHandle (process_info.hProcess);
385 process_info.hProcess = NULL;
388 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS)
389 sei->hProcess = process_info.hProcess;
391 CloseHandle (process_info.hProcess);
397 is_managed_binary (const char *filename)
399 int original_errno = errno;
400 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
401 int file = open (filename, O_RDONLY | O_LARGEFILE);
403 int file = open (filename, O_RDONLY);
406 unsigned char buffer[8];
407 off_t file_size, optional_header_offset;
408 off_t pe_header_offset;
409 gboolean managed = FALSE;
411 guint32 first_word, second_word;
413 /* If we are unable to open the file, then we definitely
414 * can't say that it is managed. The child mono process
415 * probably wouldn't be able to open it anyway.
418 errno = original_errno;
422 /* Retrieve the length of the file for future sanity checks. */
423 file_size = lseek (file, 0, SEEK_END);
424 lseek (file, 0, SEEK_SET);
426 /* We know we need to read a header field at offset 60. */
430 num_read = read (file, buffer, 2);
432 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
435 new_offset = lseek (file, 60, SEEK_SET);
437 if (new_offset != 60)
440 num_read = read (file, buffer, 4);
444 pe_header_offset = buffer[0]
449 if (pe_header_offset + 24 > file_size)
452 new_offset = lseek (file, pe_header_offset, SEEK_SET);
454 if (new_offset != pe_header_offset)
457 num_read = read (file, buffer, 4);
459 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
463 * Verify that the header we want in the optional header data
464 * is present in this binary.
466 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
468 if (new_offset != pe_header_offset + 20)
471 num_read = read (file, buffer, 2);
473 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
476 /* Read the CLR header address and size fields. These will be
477 * zero if the binary is not managed.
479 optional_header_offset = pe_header_offset + 24;
480 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
482 if (new_offset != optional_header_offset + 208)
485 num_read = read (file, buffer, 8);
487 /* We are not concerned with endianness, only with
488 * whether it is zero or not.
490 first_word = *(guint32 *)&buffer[0];
491 second_word = *(guint32 *)&buffer[4];
493 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
500 errno = original_errno;
505 CreateProcessWithLogonW (const gunichar2 *username,
506 const gunichar2 *domain,
507 const gunichar2 *password,
508 const guint32 logonFlags,
509 const gunichar2 *appname,
510 const gunichar2 *cmdline,
511 guint32 create_flags,
513 const gunichar2 *cwd,
514 WapiStartupInfo *startup,
515 WapiProcessInformation *process_info)
517 /* FIXME: use user information */
518 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
522 is_readable_or_executable (const char *prog)
525 int a = access (prog, R_OK);
526 int b = access (prog, X_OK);
527 if (a != 0 && b != 0)
529 if (stat (prog, &buf))
531 if (S_ISREG (buf.st_mode))
537 is_executable (const char *prog)
540 if (access (prog, X_OK) != 0)
542 if (stat (prog, &buf))
544 if (S_ISREG (buf.st_mode))
550 switch_dir_separators (char *path)
552 size_t i, pathLength = strlen(path);
554 /* Turn all the slashes round the right way, except for \' */
555 /* There are probably other characters that need to be excluded as well. */
556 for (i = 0; i < pathLength; i++) {
557 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' )
562 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
563 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
564 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
565 gboolean inherit_handles, guint32 create_flags,
566 gpointer new_environ, const gunichar2 *cwd,
567 WapiStartupInfo *startup,
568 WapiProcessInformation *process_info)
570 #if defined (HAVE_FORK) && defined (HAVE_EXECVE)
571 char *cmd = NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL;
572 char *dir = NULL, **env_strings = NULL, **argv = NULL;
573 guint32 i, env_count = 0;
574 gboolean ret = FALSE;
575 gpointer handle = NULL;
576 WapiHandle_process process_handle = {0}, *process_handle_data;
578 int in_fd, out_fd, err_fd;
580 int startup_pipe [2] = {-1, -1};
582 struct MonoProcess *mono_process;
583 gboolean fork_failed = FALSE;
585 mono_once (&process_sig_chld_once, process_add_sigchld_handler);
587 /* appname and cmdline specify the executable and its args:
589 * If appname is not NULL, it is the name of the executable.
590 * Otherwise the executable is the first token in cmdline.
592 * Executable searching:
594 * If appname is not NULL, it can specify the full path and
595 * file name, or else a partial name and the current directory
596 * will be used. There is no additional searching.
598 * If appname is NULL, the first whitespace-delimited token in
599 * cmdline is used. If the name does not contain a full
600 * directory path, the search sequence is:
602 * 1) The directory containing the current process
603 * 2) The current working directory
604 * 3) The windows system directory (Ignored)
605 * 4) The windows directory (Ignored)
608 * Just to make things more interesting, tokens can contain
609 * white space if they are surrounded by quotation marks. I'm
610 * beginning to understand just why windows apps are generally
611 * so crap, with an API like this :-(
613 if (appname != NULL) {
614 cmd = mono_unicode_to_external (appname);
616 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL",
619 SetLastError (ERROR_PATH_NOT_FOUND);
623 switch_dir_separators(cmd);
626 if (cmdline != NULL) {
627 args = mono_unicode_to_external (cmdline);
629 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
631 SetLastError (ERROR_PATH_NOT_FOUND);
637 dir = mono_unicode_to_external (cwd);
639 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
641 SetLastError (ERROR_PATH_NOT_FOUND);
645 /* Turn all the slashes round the right way */
646 switch_dir_separators(dir);
650 /* We can't put off locating the executable any longer :-( */
653 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
654 /* Strip off the drive letter. I can't
655 * believe that CP/M holdover is still
658 g_memmove (cmd, cmd+2, strlen (cmd)-2);
659 cmd[strlen (cmd)-2] = '\0';
662 unquoted = g_shell_unquote (cmd, NULL);
663 if (unquoted[0] == '/') {
664 /* Assume full path given */
665 prog = g_strdup (unquoted);
667 /* Executable existing ? */
668 if (!is_readable_or_executable (prog)) {
669 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s",
672 SetLastError (ERROR_FILE_NOT_FOUND);
676 /* Search for file named by cmd in the current
679 char *curdir = g_get_current_dir ();
681 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
684 /* And make sure it's readable */
685 if (!is_readable_or_executable (prog)) {
686 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s",
689 SetLastError (ERROR_FILE_NOT_FOUND);
695 args_after_prog = args;
700 /* Dig out the first token from args, taking quotation
704 /* First, strip off all leading whitespace */
705 args = g_strchug (args);
707 /* args_after_prog points to the contents of args
708 * after token has been set (otherwise argv[0] is
711 args_after_prog = args;
713 /* Assume the opening quote will always be the first
716 if (args[0] == '\"' || args [0] == '\'') {
718 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
719 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
720 /* We found the first token */
721 token = g_strndup (args+1, i-1);
722 args_after_prog = g_strchug (args + i + 1);
724 /* Quotation mark appeared in the
725 * middle of the token. Just give the
726 * whole first token, quotes and all,
733 /* No quote mark, or malformed */
734 for (i = 0; args[i] != '\0'; i++) {
735 if (g_ascii_isspace (args[i])) {
736 token = g_strndup (args, i);
737 args_after_prog = args + i + 1;
743 if (token == NULL && args[0] != '\0') {
744 /* Must be just one token in the string */
745 token = g_strdup (args);
746 args_after_prog = NULL;
751 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find what to exec", __func__);
753 SetLastError (ERROR_PATH_NOT_FOUND);
757 /* Turn all the slashes round the right way. Only for
760 switch_dir_separators(token);
762 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
763 /* Strip off the drive letter. I can't
764 * believe that CP/M holdover is still
767 g_memmove (token, token+2, strlen (token)-2);
768 token[strlen (token)-2] = '\0';
771 if (token[0] == '/') {
772 /* Assume full path given */
773 prog = g_strdup (token);
775 /* Executable existing ? */
776 if (!is_readable_or_executable (prog)) {
777 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s",
780 SetLastError (ERROR_FILE_NOT_FOUND);
784 char *curdir = g_get_current_dir ();
786 /* FIXME: Need to record the directory
787 * containing the current process, and check
788 * that for the new executable as the first
792 prog = g_strdup_printf ("%s/%s", curdir, token);
795 /* I assume X_OK is the criterion to use,
798 * X_OK is too strict *if* the target is a CLR binary
800 if (!is_readable_or_executable (prog)) {
802 prog = g_find_program_in_path (token);
804 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s", __func__, token);
807 SetLastError (ERROR_FILE_NOT_FOUND);
816 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Exec prog [%s] args [%s]", __func__, prog,
819 /* Check for CLR binaries; if found, we will try to invoke
820 * them using the same mono binary that started us.
822 if (is_managed_binary (prog)) {
823 gunichar2 *newapp = NULL, *newcmd;
827 newapp = mono_unicode_from_external (cli_launcher, &bytes_ignored);
829 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
831 if (newapp != NULL) {
832 if (appname != NULL) {
833 newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space,
834 appname, utf16_space,
837 newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space,
841 g_free ((gunichar2 *)newapp);
843 if (newcmd != NULL) {
844 ret = CreateProcess (NULL, newcmd,
848 create_flags, new_environ,
852 g_free ((gunichar2 *)newcmd);
858 if (!is_executable (prog)) {
859 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Executable permisson not set on %s", __func__, prog);
860 SetLastError (ERROR_ACCESS_DENIED);
865 if (args_after_prog != NULL && *args_after_prog) {
868 qprog = g_shell_quote (prog);
869 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
872 full_prog = g_shell_quote (prog);
875 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
877 g_message ("CreateProcess: %s\n", gerr->message);
883 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
884 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
885 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
886 err_fd = GPOINTER_TO_UINT (startup->hStdError);
888 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
889 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
890 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
893 process_handle.proc_name = g_strdup (prog);
895 process_set_defaults (&process_handle);
897 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
898 if (handle == _WAPI_HANDLE_INVALID) {
899 g_warning ("%s: error creating process handle", __func__);
902 SetLastError (ERROR_OUTOFMEMORY);
906 /* new_environ is a block of NULL-terminated strings, which
907 * is itself NULL-terminated. Of course, passing an array of
908 * string pointers would have made things too easy :-(
910 * If new_environ is not NULL it specifies the entire set of
911 * environment variables in the new process. Otherwise the
912 * new process inherits the same environment.
915 gunichar2 *new_environp;
917 /* Count the number of strings */
918 for (new_environp = (gunichar2 *)new_environ; *new_environp;
921 while (*new_environp) {
926 /* +2: one for the process handle value, and the last
929 env_strings = g_new0 (char *, env_count + 2);
931 /* Copy each environ string into 'strings' turning it
932 * into utf8 (or the requested encoding) at the same
936 for (new_environp = (gunichar2 *)new_environ; *new_environp;
938 env_strings[env_count] = mono_unicode_to_external (new_environp);
940 while (*new_environp) {
945 for (i = 0; environ[i] != NULL; i++)
948 /* +2: one for the process handle value, and the last
951 env_strings = g_new0 (char *, env_count + 2);
953 /* Copy each environ string into 'strings' turning it
954 * into utf8 (or the requested encoding) at the same
958 for (i = 0; environ[i] != NULL; i++) {
959 env_strings[env_count] = g_strdup (environ[i]);
964 /* Create a pipe to make sure the child doesn't exit before
965 * we can add the process to the linked list of mono_processes */
966 if (pipe (startup_pipe) == -1) {
967 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
968 * This is just for a very hard to hit race condition in the first place */
969 startup_pipe [0] = startup_pipe [1] = -1;
970 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__);
973 switch (pid = fork ()) {
974 case -1: /* Error */ {
975 SetLastError (ERROR_OUTOFMEMORY);
980 case 0: /* Child */ {
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 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%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 = wapi_getdtablesize () - 1; i > 2; i--)
1004 #ifdef DEBUG_ENABLED
1005 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1006 dir == NULL?".":dir);
1007 for (i = 0; argv[i] != NULL; i++)
1008 g_message ("arg %d: [%s]", i, argv[i]);
1010 for (i = 0; env_strings[i] != NULL; i++)
1011 g_message ("env %d: [%s]", i, env_strings[i]);
1015 if (dir != NULL && chdir (dir) == -1) {
1021 execve (argv[0], argv, env_strings);
1028 default: /* Parent */ {
1029 process_handle_data = lookup_process_handle (handle);
1030 if (!process_handle_data) {
1031 g_warning ("%s: error looking up process handle %p", __func__, handle);
1032 _wapi_handle_unref (handle);
1034 process_handle_data->id = pid;
1036 /* Add our mono_process into the linked list of mono_processes */
1037 mono_process = (struct MonoProcess *) g_malloc0 (sizeof (struct MonoProcess));
1038 mono_process->pid = pid;
1039 mono_process->handle_count = 1;
1040 if (mono_os_sem_init (&mono_process->exit_sem, 0) != 0) {
1041 /* If we can't create the exit semaphore, we just don't add anything
1042 * to our list of mono processes. Waiting on the process will return
1044 g_warning ("%s: could not create exit semaphore for process.", strerror (errno));
1045 g_free (mono_process);
1047 /* Keep the process handle artificially alive until the process
1048 * exits so that the information in the handle isn't lost. */
1049 _wapi_handle_ref (handle);
1050 mono_process->handle = handle;
1052 process_handle_data->mono_process = mono_process;
1054 mono_os_mutex_lock (&mono_processes_mutex);
1055 mono_process->next = mono_processes;
1056 mono_processes = mono_process;
1057 mono_os_mutex_unlock (&mono_processes_mutex);
1060 if (process_info != NULL) {
1061 process_info->hProcess = handle;
1062 process_info->dwProcessId = pid;
1064 /* FIXME: we might need to handle the thread info some day */
1065 process_info->hThread = INVALID_HANDLE_VALUE;
1066 process_info->dwThreadId = 0;
1075 _wapi_handle_unref (handle);
1077 if (startup_pipe [1] != -1) {
1078 /* Write 1 byte, doesn't matter what */
1079 ssize_t _i G_GNUC_UNUSED = write (startup_pipe [1], startup_pipe, 1);
1080 close (startup_pipe [0]);
1081 close (startup_pipe [1]);
1096 g_strfreev (env_strings);
1100 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: returning handle %p for pid %d", __func__, handle, pid);
1102 /* Check if something needs to be cleaned up. */
1103 mono_processes_cleanup ();
1107 SetLastError (ERROR_NOT_SUPPORTED);
1109 #endif // defined (HAVE_FORK) && defined (HAVE_EXECVE)
1113 process_set_name (WapiHandle_process *process_handle)
1115 char *progname, *utf8_progname, *slash;
1117 progname = g_get_prgname ();
1118 utf8_progname = mono_utf8_from_external (progname);
1120 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: using [%s] as prog name", __func__, progname);
1122 if (utf8_progname) {
1123 slash = strrchr (utf8_progname, '/');
1125 process_handle->proc_name = g_strdup (slash+1);
1127 process_handle->proc_name = g_strdup (utf8_progname);
1128 g_free (utf8_progname);
1133 wapi_processes_init (void)
1135 pid_t pid = _wapi_getpid ();
1136 WapiHandle_process process_handle = {0};
1138 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
1139 (WapiHandleCapability)(WAPI_HANDLE_CAP_WAIT | WAPI_HANDLE_CAP_SPECIAL_WAIT));
1141 process_handle.id = pid;
1143 process_set_defaults (&process_handle);
1144 process_set_name (&process_handle);
1146 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1148 g_assert (current_process);
1150 mono_os_mutex_init (&mono_processes_mutex);
1154 _wapi_process_duplicate (void)
1156 _wapi_handle_ref (current_process);
1158 return current_process;
1161 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1163 GetCurrentProcess (void)
1165 return _WAPI_PROCESS_CURRENT;
1169 GetProcessId (gpointer handle)
1171 WapiHandle_process *process_handle;
1173 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1174 /* This is a pseudo handle */
1175 return WAPI_HANDLE_TO_PID (handle);
1177 process_handle = lookup_process_handle (handle);
1178 if (!process_handle) {
1179 SetLastError (ERROR_INVALID_HANDLE);
1183 return process_handle->id;
1187 process_open_compare (gpointer handle, gpointer user_data)
1190 WapiHandle_process *process_handle;
1193 g_assert (!WAPI_IS_PSEUDO_PROCESS_HANDLE (handle));
1195 process_handle = lookup_process_handle (handle);
1196 g_assert (process_handle);
1198 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking at process %d", __func__, process_handle->id);
1200 checking_pid = process_handle->id;
1202 if (checking_pid == 0)
1205 wanted_pid = GPOINTER_TO_UINT (user_data);
1207 /* It's possible to have more than one process handle with the
1208 * same pid, but only the one running process can be
1211 if (checking_pid == wanted_pid &&
1212 !_wapi_handle_issignalled (handle)) {
1213 /* If the handle is blown away in the window between
1214 * returning TRUE here and _wapi_search_handle pinging
1215 * the timestamp, the search will continue
1224 CloseProcess (gpointer handle)
1226 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1228 return CloseHandle (handle);
1232 * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1235 OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1237 /* Find the process handle that corresponds to pid */
1238 gpointer handle = NULL;
1240 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking for process %d", __func__, pid);
1242 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1243 process_open_compare,
1244 GUINT_TO_POINTER (pid), NULL, TRUE);
1246 if (is_pid_valid (pid)) {
1247 /* Return a pseudo handle for processes we
1248 * don't have handles for
1250 return WAPI_PID_TO_HANDLE (pid);
1252 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find pid %d", __func__, pid);
1254 SetLastError (ERROR_PROC_NOT_FOUND);
1260 /* _wapi_search_handle () already added a ref */
1265 GetExitCodeProcess (gpointer process, guint32 *code)
1267 WapiHandle_process *process_handle;
1273 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1274 pid = WAPI_HANDLE_TO_PID (process);
1275 /* This is a pseudo handle, so we don't know what the
1276 * exit code was, but we can check whether it's alive or not
1278 if (is_pid_valid (pid)) {
1279 *code = STILL_ACTIVE;
1287 process_handle = lookup_process_handle (process);
1288 if (!process_handle) {
1289 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
1294 if (process_handle->id == _wapi_getpid ()) {
1295 *code = STILL_ACTIVE;
1299 /* A process handle is only signalled if the process has exited
1300 * and has been waited for */
1302 /* Make sure any process exit has been noticed, before
1303 * checking if the process is signalled. Fixes bug 325463.
1305 process_wait (process, 0, TRUE);
1307 if (_wapi_handle_issignalled (process))
1308 *code = process_handle->exitstatus;
1310 *code = STILL_ACTIVE;
1316 GetProcessTimes (gpointer process, WapiFileTime *create_time,
1317 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1318 WapiFileTime *user_time)
1320 WapiHandle_process *process_handle;
1321 gboolean ku_times_set = FALSE;
1323 if (create_time == NULL || exit_time == NULL || kernel_time == NULL ||
1325 /* Not sure if w32 allows NULLs here or not */
1328 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1329 gpointer pid = GINT_TO_POINTER (WAPI_HANDLE_TO_PID(process));
1330 gint64 start_ticks, user_ticks, kernel_ticks;
1332 mono_process_get_times (pid, &start_ticks, &user_ticks, &kernel_ticks);
1334 _wapi_guint64_to_filetime (start_ticks, create_time);
1335 _wapi_guint64_to_filetime (user_ticks, kernel_time);
1336 _wapi_guint64_to_filetime (kernel_ticks, user_time);
1341 process_handle = lookup_process_handle (process);
1342 if (!process_handle) {
1343 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
1348 *create_time = process_handle->create_time;
1350 /* A process handle is only signalled if the process has
1351 * exited. Otherwise exit_time isn't set
1353 if (_wapi_handle_issignalled (process))
1354 *exit_time = process_handle->exit_time;
1356 #ifdef HAVE_GETRUSAGE
1357 if (process_handle->id == getpid ()) {
1358 struct rusage time_data;
1359 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1361 ku_times_set = TRUE;
1362 tick_val = (guint64)time_data.ru_utime.tv_sec * 10000000 + (guint64)time_data.ru_utime.tv_usec * 10;
1363 _wapi_guint64_to_filetime (tick_val, user_time);
1364 tick_val = (guint64)time_data.ru_stime.tv_sec * 10000000 + (guint64)time_data.ru_stime.tv_usec * 10;
1365 _wapi_guint64_to_filetime (tick_val, kernel_time);
1369 if (!ku_times_set) {
1370 memset (kernel_time, 0, sizeof (WapiFileTime));
1371 memset (user_time, 0, sizeof (WapiFileTime));
1379 gpointer address_start;
1380 gpointer address_end;
1382 gpointer address_offset;
1388 static void free_procmodule (WapiProcModule *mod)
1390 if (mod->perms != NULL) {
1391 g_free (mod->perms);
1393 if (mod->filename != NULL) {
1394 g_free (mod->filename);
1399 static gint find_procmodule (gconstpointer a, gconstpointer b)
1401 WapiProcModule *want = (WapiProcModule *)a;
1402 WapiProcModule *compare = (WapiProcModule *)b;
1404 if ((want->device == compare->device) &&
1405 (want->inode == compare->inode)) {
1412 #if defined(USE_OSX_LOADER)
1413 #include <mach-o/dyld.h>
1414 #include <mach-o/getsect.h>
1416 static GSList *load_modules (void)
1419 WapiProcModule *mod;
1420 uint32_t count = _dyld_image_count ();
1423 for (i = 0; i < count; i++) {
1424 #if SIZEOF_VOID_P == 8
1425 const struct mach_header_64 *hdr;
1426 const struct section_64 *sec;
1428 const struct mach_header *hdr;
1429 const struct section *sec;
1433 name = _dyld_get_image_name (i);
1434 #if SIZEOF_VOID_P == 8
1435 hdr = (const struct mach_header_64*)_dyld_get_image_header (i);
1436 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1438 hdr = _dyld_get_image_header (i);
1439 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1442 /* Some dynlibs do not have data sections on osx (#533893) */
1447 mod = g_new0 (WapiProcModule, 1);
1448 mod->address_start = GINT_TO_POINTER (sec->addr);
1449 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1450 mod->perms = g_strdup ("r--p");
1451 mod->address_offset = 0;
1452 mod->device = makedev (0, 0);
1454 mod->filename = g_strdup (name);
1456 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1457 ret = g_slist_prepend (ret, mod);
1459 free_procmodule (mod);
1463 ret = g_slist_reverse (ret);
1467 #elif defined(USE_BSD_LOADER)
1469 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1471 if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1472 + sizeof (info->dlpi_phnum))
1475 struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1479 memcpy(cpy, info, sizeof(*info));
1481 g_ptr_array_add ((GPtrArray *)ptr, cpy);
1486 static GSList *load_modules (void)
1489 WapiProcModule *mod;
1490 GPtrArray *dlarray = g_ptr_array_new();
1493 if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1496 for (i = 0; i < dlarray->len; i++) {
1497 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1499 mod = g_new0 (WapiProcModule, 1);
1500 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1501 mod->address_end = (gpointer)(info->dlpi_addr +
1502 info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1503 mod->perms = g_strdup ("r--p");
1504 mod->address_offset = 0;
1506 mod->filename = g_strdup (info->dlpi_name);
1508 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1509 mod->inode, mod->filename, mod->address_start, mod->address_end);
1513 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1514 ret = g_slist_prepend (ret, mod);
1516 free_procmodule (mod);
1520 g_ptr_array_free (dlarray, TRUE);
1522 ret = g_slist_reverse (ret);
1526 #elif defined(USE_HAIKU_LOADER)
1528 static GSList *load_modules (void)
1531 WapiProcModule *mod;
1533 image_info imageInfo;
1535 while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
1536 mod = g_new0 (WapiProcModule, 1);
1537 mod->device = imageInfo.device;
1538 mod->inode = imageInfo.node;
1539 mod->filename = g_strdup (imageInfo.name);
1540 mod->address_start = MIN (imageInfo.text, imageInfo.data);
1541 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
1542 (uint8_t*)imageInfo.data + imageInfo.data_size);
1543 mod->perms = g_strdup ("r--p");
1544 mod->address_offset = 0;
1546 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1547 ret = g_slist_prepend (ret, mod);
1549 free_procmodule (mod);
1553 ret = g_slist_reverse (ret);
1558 static GSList *load_modules (FILE *fp)
1561 WapiProcModule *mod;
1562 char buf[MAXPATHLEN + 1], *p, *endp;
1563 char *start_start, *end_start, *prot_start, *offset_start;
1564 char *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1565 gpointer address_start, address_end, address_offset;
1566 guint32 maj_dev, min_dev;
1570 while (fgets (buf, sizeof(buf), fp)) {
1572 while (g_ascii_isspace (*p)) ++p;
1574 if (!g_ascii_isxdigit (*start_start)) {
1577 address_start = (gpointer)strtoul (start_start, &endp, 16);
1585 if (!g_ascii_isxdigit (*end_start)) {
1588 address_end = (gpointer)strtoul (end_start, &endp, 16);
1590 if (!g_ascii_isspace (*p)) {
1594 while (g_ascii_isspace (*p)) ++p;
1596 if (*prot_start != 'r' && *prot_start != '-') {
1599 memcpy (prot_buf, prot_start, 4);
1601 while (!g_ascii_isspace (*p)) ++p;
1603 while (g_ascii_isspace (*p)) ++p;
1605 if (!g_ascii_isxdigit (*offset_start)) {
1608 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1610 if (!g_ascii_isspace (*p)) {
1614 while(g_ascii_isspace (*p)) ++p;
1616 if (!g_ascii_isxdigit (*maj_dev_start)) {
1619 maj_dev = strtoul (maj_dev_start, &endp, 16);
1627 if (!g_ascii_isxdigit (*min_dev_start)) {
1630 min_dev = strtoul (min_dev_start, &endp, 16);
1632 if (!g_ascii_isspace (*p)) {
1636 while (g_ascii_isspace (*p)) ++p;
1638 if (!g_ascii_isxdigit (*inode_start)) {
1641 inode = (guint64)strtol (inode_start, &endp, 10);
1643 if (!g_ascii_isspace (*p)) {
1647 device = makedev ((int)maj_dev, (int)min_dev);
1648 if ((device == 0) &&
1653 while(g_ascii_isspace (*p)) ++p;
1654 /* p now points to the filename */
1656 mod = g_new0 (WapiProcModule, 1);
1657 mod->address_start = address_start;
1658 mod->address_end = address_end;
1659 mod->perms = g_strdup (prot_buf);
1660 mod->address_offset = address_offset;
1661 mod->device = device;
1663 mod->filename = g_strdup (g_strstrip (p));
1665 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1666 ret = g_slist_prepend (ret, mod);
1668 free_procmodule (mod);
1672 ret = g_slist_reverse (ret);
1678 static gboolean match_procname_to_modulename (char *procname, char *modulename)
1680 char* lastsep = NULL;
1681 char* lastsep2 = NULL;
1684 gboolean result = FALSE;
1686 if (procname == NULL || modulename == NULL)
1689 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: procname=\"%s\", modulename=\"%s\"", __func__, procname, modulename);
1690 pname = mono_path_resolve_symlinks (procname);
1691 mname = mono_path_resolve_symlinks (modulename);
1693 if (!strcmp (pname, mname))
1697 lastsep = strrchr (mname, '/');
1699 if (!strcmp (lastsep+1, pname))
1702 lastsep2 = strrchr (pname, '/');
1705 if (!strcmp (lastsep+1, lastsep2+1))
1708 if (!strcmp (mname, lastsep2+1))
1718 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: result is %d", __func__, result);
1722 #if !(defined(USE_OSX_LOADER) || defined(USE_BSD_LOADER) || defined(USE_HAIKU_LOADER))
1724 open_process_map (int pid, const char *mode)
1727 const char *proc_path[] = {
1728 "/proc/%d/maps", /* GNU/Linux */
1729 "/proc/%d/map", /* FreeBSD */
1735 for (i = 0; fp == NULL && proc_path [i]; i++) {
1736 filename = g_strdup_printf (proc_path[i], pid);
1737 fp = fopen (filename, mode);
1745 static char *get_process_name_from_proc (pid_t pid);
1747 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1748 guint32 size, guint32 *needed)
1750 WapiHandle_process *process_handle;
1751 #if !defined(USE_OSX_LOADER) && !defined(USE_BSD_LOADER)
1754 GSList *mods = NULL;
1755 WapiProcModule *module;
1756 guint32 count, avail = size / sizeof(gpointer);
1759 char *proc_name = NULL;
1761 /* Store modules in an array of pointers (main module as
1762 * modules[0]), using the load address for each module as a
1763 * token. (Use 'NULL' as an alternative for the main module
1764 * so that the simple implementation can just return one item
1765 * for now.) Get the info from /proc/<pid>/maps on linux,
1766 * /proc/<pid>/map on FreeBSD, other systems will have to
1767 * implement /dev/kmem reading or whatever other horrid
1768 * technique is needed.
1770 if (size < sizeof(gpointer))
1773 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1774 pid = WAPI_HANDLE_TO_PID (process);
1775 proc_name = get_process_name_from_proc (pid);
1777 process_handle = lookup_process_handle (process);
1778 if (!process_handle) {
1779 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
1783 pid = process_handle->id;
1784 proc_name = g_strdup (process_handle->proc_name);
1787 #if defined(USE_OSX_LOADER) || defined(USE_BSD_LOADER) || defined(USE_HAIKU_LOADER)
1788 mods = load_modules ();
1791 *needed = sizeof(gpointer);
1795 fp = open_process_map (pid, "r");
1797 /* No /proc/<pid>/maps so just return the main module
1801 *needed = sizeof(gpointer);
1805 mods = load_modules (fp);
1808 count = g_slist_length (mods);
1810 /* count + 1 to leave slot 0 for the main module */
1811 *needed = sizeof(gpointer) * (count + 1);
1814 * Use the NULL shortcut, as the first line in
1815 * /proc/<pid>/maps isn't the executable, and we need
1816 * that first in the returned list. Check the module name
1817 * to see if it ends with the proc name and substitute
1818 * the first entry with it. FIXME if this turns out to
1822 for (i = 0; i < (avail - 1) && i < count; i++) {
1823 module = (WapiProcModule *)g_slist_nth_data (mods, i);
1824 if (modules[0] != NULL)
1825 modules[i] = module->address_start;
1826 else if (match_procname_to_modulename (proc_name, module->filename))
1827 modules[0] = module->address_start;
1829 modules[i + 1] = module->address_start;
1832 for (i = 0; i < count; i++) {
1833 free_procmodule ((WapiProcModule *)g_slist_nth_data (mods, i));
1835 g_slist_free (mods);
1842 get_process_name_from_proc (pid_t pid)
1844 #if defined(USE_BSD_LOADER)
1847 struct kinfo_proc *pi;
1848 #elif defined(USE_OSX_LOADER)
1849 #if !(!defined (__mono_ppc__) && defined (TARGET_OSX))
1851 struct kinfo_proc *pi;
1852 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
1856 char *filename = NULL;
1861 #if defined(PLATFORM_SOLARIS)
1862 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
1863 if ((fp = fopen (filename, "r")) != NULL) {
1867 nread = fread (&info, sizeof (info), 1, fp);
1869 ret = g_strdup (info.pr_fname);
1875 #elif defined(USE_OSX_LOADER)
1876 #if !defined (__mono_ppc__) && defined (TARGET_OSX)
1877 /* No proc name on OSX < 10.5 nor ppc nor iOS */
1878 memset (buf, '\0', sizeof(buf));
1879 proc_name (pid, buf, sizeof(buf));
1881 // Fixes proc_name triming values to 15 characters #32539
1882 if (strlen (buf) >= MAXCOMLEN - 1) {
1883 char path_buf [PROC_PIDPATHINFO_MAXSIZE];
1887 memset (path_buf, '\0', sizeof(path_buf));
1888 path_len = proc_pidpath (pid, path_buf, sizeof(path_buf));
1890 if (path_len > 0 && path_len < sizeof(path_buf)) {
1891 name_buf = path_buf + path_len;
1892 for(;name_buf > path_buf; name_buf--) {
1893 if (name_buf [0] == '/') {
1899 if (memcmp (buf, name_buf, MAXCOMLEN - 1) == 0)
1900 ret = g_strdup (name_buf);
1904 if (ret == NULL && strlen (buf) > 0)
1905 ret = g_strdup (buf);
1907 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0)
1910 if ((pi = malloc(size)) == NULL)
1913 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
1914 if (errno == ENOMEM) {
1916 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't allocate enough memory for kproc info", __func__);
1921 if (strlen (pi->kp_proc.p_comm) > 0)
1922 ret = g_strdup (pi->kp_proc.p_comm);
1926 #elif defined(USE_BSD_LOADER)
1927 #if defined(__FreeBSD__)
1929 mib [1] = KERN_PROC;
1930 mib [2] = KERN_PROC_PID;
1932 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0) {
1933 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: sysctl() failed: %d", __func__, errno);
1937 if ((pi = malloc(size)) == NULL)
1940 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
1941 if (errno == ENOMEM) {
1943 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't allocate enough memory for kproc info", __func__);
1948 if (strlen (pi->ki_comm) > 0)
1949 ret = g_strdup (pi->ki_comm);
1951 #elif defined(__OpenBSD__)
1953 mib [1] = KERN_PROC;
1954 mib [2] = KERN_PROC_PID;
1956 mib [4] = sizeof(struct kinfo_proc);
1960 if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0) {
1961 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: sysctl() failed: %d", __func__, errno);
1965 if ((pi = malloc(size)) == NULL)
1968 mib[5] = (int)(size / sizeof(struct kinfo_proc));
1970 if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
1971 (size != sizeof (struct kinfo_proc))) {
1972 if (errno == ENOMEM) {
1979 if (strlen (pi->p_comm) > 0)
1980 ret = g_strdup (pi->p_comm);
1984 #elif defined(USE_HAIKU_LOADER)
1985 image_info imageInfo;
1988 if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
1989 ret = g_strdup (imageInfo.name);
1992 memset (buf, '\0', sizeof(buf));
1993 filename = g_strdup_printf ("/proc/%d/exe", pid);
1994 if (readlink (filename, buf, 255) > 0) {
1995 ret = g_strdup (buf);
2003 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
2004 if ((fp = fopen (filename, "r")) != NULL) {
2005 if (fgets (buf, 256, fp) != NULL) {
2006 ret = g_strdup (buf);
2017 filename = g_strdup_printf ("/proc/%d/stat", pid);
2018 if ((fp = fopen (filename, "r")) != NULL) {
2019 if (fgets (buf, 256, fp) != NULL) {
2022 start = strchr (buf, '(');
2023 if (start != NULL) {
2024 end = strchr (start + 1, ')');
2027 ret = g_strndup (start + 1,
2042 * wapi_process_get_path:
2044 * Return the full path of the executable of the process PID, or NULL if it cannot be determined.
2045 * Returns malloc-ed memory.
2048 wapi_process_get_path (pid_t pid)
2050 #if defined(PLATFORM_MACOSX) && !defined(__mono_ppc__) && defined(TARGET_OSX)
2051 char buf [PROC_PIDPATHINFO_MAXSIZE];
2054 res = proc_pidpath (pid, buf, sizeof (buf));
2057 if (buf [0] == '\0')
2059 return g_strdup (buf);
2061 return get_process_name_from_proc (pid);
2066 * wapi_process_set_cli_launcher:
2068 * Set the full path of the runtime executable used to launch managed exe's.
2071 wapi_process_set_cli_launcher (char *path)
2073 g_free (cli_launcher);
2074 cli_launcher = path ? g_strdup (path) : NULL;
2078 get_module_name (gpointer process, gpointer module,
2079 gunichar2 *basename, guint32 size,
2082 WapiHandle_process *process_handle;
2084 gunichar2 *procname;
2085 char *procname_ext = NULL;
2088 #if !defined(USE_OSX_LOADER) && !defined(USE_BSD_LOADER)
2091 GSList *mods = NULL;
2092 WapiProcModule *found_module;
2095 char *proc_name = NULL;
2097 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Getting module base name, process handle %p module %p",
2098 __func__, process, module);
2100 size = size * sizeof (gunichar2); /* adjust for unicode characters */
2102 if (basename == NULL || size == 0)
2105 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2106 /* This is a pseudo handle */
2107 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2108 proc_name = get_process_name_from_proc (pid);
2110 process_handle = lookup_process_handle (process);
2111 if (!process_handle) {
2112 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__,
2117 pid = process_handle->id;
2118 proc_name = g_strdup (process_handle->proc_name);
2121 /* Look up the address in /proc/<pid>/maps */
2122 #if defined(USE_OSX_LOADER) || defined(USE_BSD_LOADER) || defined(USE_HAIKU_LOADER)
2123 mods = load_modules ();
2125 fp = open_process_map (pid, "r");
2127 if (errno == EACCES && module == NULL && base == TRUE) {
2128 procname_ext = get_process_name_from_proc (pid);
2130 /* No /proc/<pid>/maps, so just return failure
2137 mods = load_modules (fp);
2141 count = g_slist_length (mods);
2143 /* If module != NULL compare the address.
2144 * If module == NULL we are looking for the main module.
2145 * The best we can do for now check it the module name end with the process name.
2147 for (i = 0; i < count; i++) {
2148 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2149 if (procname_ext == NULL &&
2150 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2151 (module != NULL && found_module->address_start == module))) {
2153 procname_ext = g_path_get_basename (found_module->filename);
2155 procname_ext = g_strdup (found_module->filename);
2158 free_procmodule (found_module);
2161 if (procname_ext == NULL) {
2162 /* If it's *still* null, we might have hit the
2163 * case where reading /proc/$pid/maps gives an
2164 * empty file for this user.
2166 procname_ext = get_process_name_from_proc (pid);
2169 g_slist_free (mods);
2173 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Process name is [%s]", __func__,
2176 procname = mono_unicode_from_external (procname_ext, &bytes);
2177 if (procname == NULL) {
2179 g_free (procname_ext);
2185 /* Add the terminator */
2189 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2191 memcpy (basename, procname, size);
2193 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %d larger than needed (%ld)",
2194 __func__, size, bytes);
2196 memcpy (basename, procname, bytes);
2200 g_free (procname_ext);
2209 get_module_filename (gpointer process, gpointer module,
2210 gunichar2 *basename, guint32 size)
2215 gunichar2 *proc_path;
2217 size *= sizeof (gunichar2); /* adjust for unicode characters */
2219 if (basename == NULL || size == 0)
2222 pid = GetProcessId (process);
2224 path = wapi_process_get_path (pid);
2228 proc_path = mono_unicode_from_external (path, &bytes);
2231 if (proc_path == NULL)
2236 /* Add the terminator */
2240 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2242 memcpy (basename, proc_path, size);
2244 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %d larger than needed (%ld)",
2245 __func__, size, bytes);
2247 memcpy (basename, proc_path, bytes);
2256 GetModuleBaseName (gpointer process, gpointer module,
2257 gunichar2 *basename, guint32 size)
2259 return get_module_name (process, module, basename, size, TRUE);
2263 GetModuleFileNameEx (gpointer process, gpointer module,
2264 gunichar2 *filename, guint32 size)
2266 return get_module_filename (process, module, filename, size);
2270 GetModuleInformation (gpointer process, gpointer module,
2271 WapiModuleInfo *modinfo, guint32 size)
2273 WapiHandle_process *process_handle;
2275 #if !defined(USE_OSX_LOADER) && !defined(USE_BSD_LOADER)
2278 GSList *mods = NULL;
2279 WapiProcModule *found_module;
2282 gboolean ret = FALSE;
2283 char *proc_name = NULL;
2285 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Getting module info, process handle %p module %p",
2286 __func__, process, module);
2288 if (modinfo == NULL || size < sizeof (WapiModuleInfo))
2291 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2292 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2293 proc_name = get_process_name_from_proc (pid);
2295 process_handle = lookup_process_handle (process);
2296 if (!process_handle) {
2297 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__,
2302 pid = process_handle->id;
2303 proc_name = g_strdup (process_handle->proc_name);
2306 #if defined(USE_OSX_LOADER) || defined(USE_BSD_LOADER) || defined(USE_HAIKU_LOADER)
2307 mods = load_modules ();
2309 /* Look up the address in /proc/<pid>/maps */
2310 if ((fp = open_process_map (pid, "r")) == NULL) {
2311 /* No /proc/<pid>/maps, so just return failure
2317 mods = load_modules (fp);
2320 count = g_slist_length (mods);
2322 /* If module != NULL compare the address.
2323 * If module == NULL we are looking for the main module.
2324 * The best we can do for now check it the module name end with the process name.
2326 for (i = 0; i < count; i++) {
2327 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2329 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2330 (module != NULL && found_module->address_start == module))) {
2331 modinfo->lpBaseOfDll = found_module->address_start;
2332 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2333 modinfo->EntryPoint = found_module->address_offset;
2337 free_procmodule (found_module);
2340 g_slist_free (mods);
2347 GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2349 WapiHandle_process *process_handle;
2351 if (min == NULL || max == NULL)
2352 /* Not sure if w32 allows NULLs here or not */
2355 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2356 /* This is a pseudo handle, so just fail for now */
2359 process_handle = lookup_process_handle (process);
2360 if (!process_handle) {
2361 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
2366 *min = process_handle->min_working_set;
2367 *max = process_handle->max_working_set;
2373 SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2375 WapiHandle_process *process_handle;
2377 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2378 /* This is a pseudo handle, so just fail for now
2382 process_handle = lookup_process_handle (process);
2383 if (!process_handle) {
2384 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
2389 process_handle->min_working_set = min;
2390 process_handle->max_working_set = max;
2397 TerminateProcess (gpointer process, gint32 exitCode)
2399 #if defined(HAVE_KILL)
2400 WapiHandle_process *process_handle;
2405 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2406 /* This is a pseudo handle */
2407 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2409 process_handle = lookup_process_handle (process);
2410 if (!process_handle) {
2411 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
2412 SetLastError (ERROR_INVALID_HANDLE);
2415 pid = process_handle->id;
2418 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2419 ret = kill (pid, signo);
2423 SetLastError (ERROR_INVALID_PARAMETER);
2426 SetLastError (ERROR_ACCESS_DENIED);
2429 SetLastError (ERROR_PROC_NOT_FOUND);
2432 SetLastError (ERROR_GEN_FAILURE);
2438 g_error ("kill() is not supported by this platform");
2444 GetPriorityClass (gpointer process)
2446 #ifdef HAVE_GETPRIORITY
2447 WapiHandle_process *process_handle;
2451 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2452 /* This is a pseudo handle */
2453 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2455 process_handle = lookup_process_handle (process);
2456 if (!process_handle) {
2457 SetLastError (ERROR_INVALID_HANDLE);
2460 pid = process_handle->id;
2464 ret = getpriority (PRIO_PROCESS, pid);
2465 if (ret == -1 && errno != 0) {
2469 SetLastError (ERROR_ACCESS_DENIED);
2472 SetLastError (ERROR_PROC_NOT_FOUND);
2475 SetLastError (ERROR_GEN_FAILURE);
2481 return NORMAL_PRIORITY_CLASS;
2483 return REALTIME_PRIORITY_CLASS;
2485 return HIGH_PRIORITY_CLASS;
2487 return ABOVE_NORMAL_PRIORITY_CLASS;
2489 return IDLE_PRIORITY_CLASS;
2491 return BELOW_NORMAL_PRIORITY_CLASS;
2493 return NORMAL_PRIORITY_CLASS;
2495 SetLastError (ERROR_NOT_SUPPORTED);
2501 SetPriorityClass (gpointer process, guint32 priority_class)
2503 #ifdef HAVE_SETPRIORITY
2504 WapiHandle_process *process_handle;
2509 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2510 /* This is a pseudo handle */
2511 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2513 process_handle = lookup_process_handle (process);
2514 if (!process_handle) {
2515 SetLastError (ERROR_INVALID_HANDLE);
2518 pid = process_handle->id;
2521 switch (priority_class) {
2522 case IDLE_PRIORITY_CLASS:
2525 case BELOW_NORMAL_PRIORITY_CLASS:
2528 case NORMAL_PRIORITY_CLASS:
2531 case ABOVE_NORMAL_PRIORITY_CLASS:
2534 case HIGH_PRIORITY_CLASS:
2537 case REALTIME_PRIORITY_CLASS:
2541 SetLastError (ERROR_INVALID_PARAMETER);
2545 ret = setpriority (PRIO_PROCESS, pid, prio);
2550 SetLastError (ERROR_ACCESS_DENIED);
2553 SetLastError (ERROR_PROC_NOT_FOUND);
2556 SetLastError (ERROR_GEN_FAILURE);
2562 SetLastError (ERROR_NOT_SUPPORTED);
2568 mono_processes_cleanup (void)
2570 struct MonoProcess *mp;
2571 struct MonoProcess *prev = NULL;
2572 GSList *finished = NULL;
2574 gpointer unref_handle;
2576 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s", __func__);
2578 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2579 if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
2582 for (mp = mono_processes; mp; mp = mp->next) {
2583 if (mp->pid == 0 && mp->handle) {
2584 /* This process has exited and we need to remove the artifical ref
2586 mono_os_mutex_lock (&mono_processes_mutex);
2587 unref_handle = mp->handle;
2589 mono_os_mutex_unlock (&mono_processes_mutex);
2591 _wapi_handle_unref (unref_handle);
2596 * Remove processes which exited from the mono_processes list.
2597 * We need to synchronize with the sigchld handler here, which runs
2598 * asynchronously. The handler requires that the mono_processes list
2601 mono_os_mutex_lock (&mono_processes_mutex);
2603 mp = mono_processes;
2605 if (mp->handle_count == 0 && mp->freeable) {
2608 * This code can run parallel with the sigchld handler, but the
2609 * modifications it makes are safe.
2611 if (mp == mono_processes)
2612 mono_processes = mp->next;
2614 prev->next = mp->next;
2615 finished = g_slist_prepend (finished, mp);
2624 mono_memory_barrier ();
2626 for (l = finished; l; l = l->next) {
2628 * All the entries in the finished list are unlinked from mono_processes, and
2629 * they have the 'finished' flag set, which means the sigchld handler is done
2632 mp = (MonoProcess *)l->data;
2633 mono_os_sem_destroy (&mp->exit_sem);
2636 g_slist_free (finished);
2638 mono_os_mutex_unlock (&mono_processes_mutex);
2640 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s done", __func__);
2642 InterlockedDecrement (&mono_processes_cleaning_up);
2646 process_close (gpointer handle, gpointer data)
2648 WapiHandle_process *process_handle;
2650 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s", __func__);
2652 process_handle = (WapiHandle_process *) data;
2653 g_free (process_handle->proc_name);
2654 process_handle->proc_name = NULL;
2655 if (process_handle->mono_process)
2656 InterlockedDecrement (&process_handle->mono_process->handle_count);
2657 mono_processes_cleanup ();
2661 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
2665 struct MonoProcess *p;
2667 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "SIG CHILD handler for pid: %i\n", info->si_pid);
2671 pid = waitpid (-1, &status, WNOHANG);
2672 } while (pid == -1 && errno == EINTR);
2677 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "child ended: %i", pid);
2680 * This can run concurrently with the code in the rest of this module.
2682 for (p = mono_processes; p; p = p->next) {
2683 if (p->pid == pid) {
2688 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2690 mono_os_sem_post (&p->exit_sem);
2691 mono_memory_barrier ();
2692 /* Mark this as freeable, the pointer becomes invalid afterwards */
2697 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "SIG CHILD handler: done looping.");
2703 process_add_sigchld_handler (void)
2706 struct sigaction sa;
2708 sa.sa_sigaction = mono_sigchld_signal_handler;
2709 sigemptyset (&sa.sa_mask);
2710 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2711 g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2712 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "Added SIGCHLD handler");
2717 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2719 WapiHandle_process *process_handle;
2720 pid_t pid G_GNUC_UNUSED, ret;
2723 struct MonoProcess *mp;
2725 /* FIXME: We can now easily wait on processes that aren't our own children,
2726 * but WaitFor*Object won't call us for pseudo handles. */
2727 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2729 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u)", __func__, handle, timeout);
2731 process_handle = lookup_process_handle (handle);
2732 if (!process_handle) {
2733 g_warning ("%s: error looking up process handle %p", __func__, handle);
2737 if (process_handle->exited) {
2738 /* We've already done this one */
2739 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): Process already exited", __func__, handle, timeout);
2740 return WAIT_OBJECT_0;
2743 pid = process_handle->id;
2745 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2747 /* We don't need to lock mono_processes here, the entry
2748 * has a handle_count > 0 which means it will not be freed. */
2749 mp = process_handle->mono_process;
2753 if (pid == mono_process_current_pid ()) {
2754 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on current process", __func__, handle, timeout);
2755 return WAIT_TIMEOUT;
2758 /* This path is used when calling Process.HasExited, so
2759 * it is only used to poll the state of the process, not
2760 * to actually wait on it to exit */
2761 g_assert (timeout == 0);
2763 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on non-child process", __func__, handle, timeout);
2765 res = waitpid (pid, &status, WNOHANG);
2767 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): non-child process WAIT_TIMEOUT", __func__, handle, timeout);
2768 return WAIT_TIMEOUT;
2771 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): non-child process waited successfully", __func__, handle, timeout);
2772 return WAIT_OBJECT_0;
2775 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);
2779 start = mono_msec_ticks ();
2783 if (timeout != INFINITE) {
2784 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on semaphore for %li ms...",
2785 __func__, handle, timeout, (timeout - (now - start)));
2786 ret = mono_os_sem_timedwait (&mp->exit_sem, (timeout - (now - start)), alertable ? MONO_SEM_FLAGS_ALERTABLE : MONO_SEM_FLAGS_NONE);
2788 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on semaphore forever...",
2789 __func__, handle, timeout);
2790 ret = mono_os_sem_wait (&mp->exit_sem, alertable ? MONO_SEM_FLAGS_ALERTABLE : MONO_SEM_FLAGS_NONE);
2793 if (ret == -1 && errno != EINTR && errno != ETIMEDOUT) {
2794 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): sem_timedwait failure: %s",
2795 __func__, handle, timeout, g_strerror (errno));
2796 /* Should we return a failure here? */
2800 /* Success, process has exited */
2801 mono_os_sem_post (&mp->exit_sem);
2806 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
2807 return WAIT_TIMEOUT;
2810 now = mono_msec_ticks ();
2811 if (now - start >= timeout) {
2812 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
2813 return WAIT_TIMEOUT;
2816 if (alertable && _wapi_thread_cur_apc_pending ()) {
2817 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
2818 return WAIT_IO_COMPLETION;
2822 /* Process must have exited */
2823 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): Waited successfully", __func__, handle, timeout);
2825 status = mp ? mp->status : 0;
2826 if (WIFSIGNALED (status))
2827 process_handle->exitstatus = 128 + WTERMSIG (status);
2829 process_handle->exitstatus = WEXITSTATUS (status);
2830 _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
2832 process_handle->exited = TRUE;
2834 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): Setting pid %d signalled, exit status %d",
2835 __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
2837 _wapi_handle_set_signal_state (handle, TRUE, TRUE);
2839 return WAIT_OBJECT_0;
2843 wapi_processes_cleanup (void)
2845 g_free (cli_launcher);