2 * processes.c: Process handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002-2006 Novell, Inc.
18 #include <sys/types.h>
24 #include <sys/resource.h>
26 #include <sys/param.h>
29 #ifdef HAVE_SYS_MKDEV_H
30 #include <sys/mkdev.h>
33 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
35 #include <sys/resource.h>
38 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
40 #include <sys/sysctl.h>
41 # if !defined(__OpenBSD__)
42 # include <sys/utsname.h>
46 #ifdef PLATFORM_SOLARIS
47 /* procfs.h cannot be included if this define is set, but it seems to work fine if it is undefined */
48 #if _FILE_OFFSET_BITS == 64
49 #undef _FILE_OFFSET_BITS
51 #define _FILE_OFFSET_BITS 64
58 #include <KernelKit.h>
61 #include <mono/io-layer/wapi.h>
62 #include <mono/io-layer/wapi-private.h>
63 #include <mono/io-layer/handles-private.h>
64 #include <mono/io-layer/misc-private.h>
65 #include <mono/io-layer/mono-mutex.h>
66 #include <mono/io-layer/process-private.h>
67 #include <mono/io-layer/threads.h>
68 #include <mono/utils/strenc.h>
69 #include <mono/utils/mono-path.h>
70 #include <mono/io-layer/timefuncs-private.h>
71 #include <mono/utils/mono-time.h>
72 #include <mono/utils/mono-membar.h>
74 /* The process' environment strings */
75 #if defined(__APPLE__) && !defined (__arm__)
76 /* Apple defines this in crt_externs.h but doesn't provide that header for
77 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
78 * in fact exist on all implementations (so far)
80 gchar ***_NSGetEnviron(void);
81 #define environ (*_NSGetEnviron())
83 extern char **environ;
88 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable);
89 static void process_close (gpointer handle, gpointer data);
90 static gboolean is_pid_valid (pid_t pid);
92 #if !defined(__OpenBSD__)
94 open_process_map (int pid, const char *mode);
97 struct _WapiHandleOps _wapi_process_ops = {
98 process_close, /* close_shared */
102 process_wait, /* special_wait */
107 static struct sigaction previous_chld_sa;
109 static mono_once_t process_sig_chld_once = MONO_ONCE_INIT;
110 static void process_add_sigchld_handler (void);
112 /* The signal-safe logic to use mono_processes goes like this:
113 * - The list must be safe to traverse for the signal handler at all times.
114 * It's safe to: prepend an entry (which is a single store to 'mono_processes'),
115 * unlink an entry (assuming the unlinked entry isn't freed and doesn't
116 * change its 'next' pointer so that it can still be traversed).
117 * When cleaning up we first unlink an entry, then we verify that
118 * the read lock isn't locked. Then we can free the entry, since
119 * we know that nobody is using the old version of the list (including
120 * the unlinked entry).
121 * We also need to lock when adding and cleaning up so that those two
122 * operations don't mess with eachother. (This lock is not used in the
125 static struct MonoProcess *mono_processes = NULL;
126 static volatile gint32 mono_processes_read_lock = 0;
127 static volatile gint32 mono_processes_cleaning_up = 0;
128 static mono_mutex_t mono_processes_mutex;
129 static void mono_processes_cleanup (void);
131 static mono_once_t process_current_once=MONO_ONCE_INIT;
132 static gpointer current_process=NULL;
134 static mono_once_t process_ops_once=MONO_ONCE_INIT;
136 static void process_ops_init (void)
138 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
139 WAPI_HANDLE_CAP_WAIT |
140 WAPI_HANDLE_CAP_SPECIAL_WAIT);
144 /* Check if a pid is valid - i.e. if a process exists with this pid. */
145 static gboolean is_pid_valid (pid_t pid)
147 gboolean result = FALSE;
149 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
150 if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
152 #elif defined(__HAIKU__)
154 if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
157 gchar *dir = g_strdup_printf ("/proc/%d", pid);
158 if (!access (dir, F_OK))
166 static void process_set_defaults (struct _WapiHandle_process *process_handle)
168 /* These seem to be the defaults on w2k */
169 process_handle->min_working_set = 204800;
170 process_handle->max_working_set = 1413120;
172 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
176 len16 (const gunichar2 *str)
187 utf16_concat (const gunichar2 *first, ...)
194 va_start (args, first);
195 total += len16 (first);
196 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
201 ret = g_new (gunichar2, total + 1);
207 for (s = first; *s != 0; s++)
209 va_start (args, first);
210 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
213 for (p = s; *p != 0; p++)
221 #ifdef PLATFORM_MACOSX
223 /* 0 = no detection; -1 = not 10.5 or higher; 1 = 10.5 or higher */
224 static int osx_10_5_or_higher;
227 detect_osx_10_5_or_higher (void)
233 if (uname (&u) != 0){
234 osx_10_5_or_higher = 1;
242 osx_10_5_or_higher = -1;
244 osx_10_5_or_higher = 1;
248 is_macos_10_5_or_higher (void)
250 if (osx_10_5_or_higher == 0)
251 detect_osx_10_5_or_higher ();
253 return (osx_10_5_or_higher == 1);
257 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
258 static const gunichar2 *utf16_space = utf16_space_bytes;
259 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
260 static const gunichar2 *utf16_quote = utf16_quote_bytes;
265 print_utf16 (gunichar2 *str)
269 res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
270 g_print ("%s\n", res);
275 /* Implemented as just a wrapper around CreateProcess () */
276 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
279 WapiProcessInformation process_info;
283 /* w2k just segfaults here, but we can do better than
286 SetLastError (ERROR_INVALID_PARAMETER);
290 if (sei->lpFile == NULL) {
291 /* w2k returns TRUE for this, for some reason. */
295 /* Put both executable and parameters into the second argument
296 * to CreateProcess (), so it searches $PATH. The conversion
297 * into and back out of utf8 is because there is no
298 * g_strdup_printf () equivalent for gunichar2 :-(
300 args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
302 SetLastError (ERROR_INVALID_DATA);
305 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
306 CREATE_UNICODE_ENVIRONMENT, NULL,
307 sei->lpDirectory, NULL, &process_info);
310 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
314 static char *handler;
315 static gunichar2 *handler_utf16;
317 if (handler_utf16 == (gunichar2 *)-1)
320 #ifdef PLATFORM_MACOSX
321 if (is_macos_10_5_or_higher ())
322 handler = g_strdup ("/usr/bin/open -W");
324 handler = g_strdup ("/usr/bin/open");
327 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
328 * if that fails, try to use gnome-open, then kfmclient
330 handler = g_find_program_in_path ("xdg-open");
331 if (handler == NULL){
332 handler = g_find_program_in_path ("gnome-open");
333 if (handler == NULL){
334 handler = g_find_program_in_path ("kfmclient");
335 if (handler == NULL){
336 handler_utf16 = (gunichar2 *) -1;
339 /* kfmclient needs exec argument */
341 handler = g_strconcat (old, " exec",
348 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
351 /* Put quotes around the filename, in case it's a url
352 * that contains #'s (CreateProcess() calls
353 * g_shell_parse_argv(), which deliberately throws
354 * away anything after an unquoted #). Fixes bug
357 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
358 sei->lpFile, utf16_quote,
359 sei->lpParameters == NULL ? NULL : utf16_space,
360 sei->lpParameters, NULL);
362 SetLastError (ERROR_INVALID_DATA);
365 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
366 CREATE_UNICODE_ENVIRONMENT, NULL,
367 sei->lpDirectory, NULL, &process_info);
370 SetLastError (ERROR_INVALID_DATA);
375 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
376 sei->hProcess = process_info.hProcess;
378 CloseHandle (process_info.hProcess);
385 is_managed_binary (const gchar *filename)
387 int original_errno = errno;
388 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
389 int file = open (filename, O_RDONLY | O_LARGEFILE);
391 int file = open (filename, O_RDONLY);
394 unsigned char buffer[8];
395 off_t file_size, optional_header_offset;
396 off_t pe_header_offset;
397 gboolean managed = FALSE;
399 guint32 first_word, second_word;
401 /* If we are unable to open the file, then we definitely
402 * can't say that it is managed. The child mono process
403 * probably wouldn't be able to open it anyway.
406 errno = original_errno;
410 /* Retrieve the length of the file for future sanity checks. */
411 file_size = lseek (file, 0, SEEK_END);
412 lseek (file, 0, SEEK_SET);
414 /* We know we need to read a header field at offset 60. */
418 num_read = read (file, buffer, 2);
420 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
423 new_offset = lseek (file, 60, SEEK_SET);
425 if (new_offset != 60)
428 num_read = read (file, buffer, 4);
432 pe_header_offset = buffer[0]
437 if (pe_header_offset + 24 > file_size)
440 new_offset = lseek (file, pe_header_offset, SEEK_SET);
442 if (new_offset != pe_header_offset)
445 num_read = read (file, buffer, 4);
447 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
451 * Verify that the header we want in the optional header data
452 * is present in this binary.
454 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
456 if (new_offset != pe_header_offset + 20)
459 num_read = read (file, buffer, 2);
461 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
464 /* Read the CLR header address and size fields. These will be
465 * zero if the binary is not managed.
467 optional_header_offset = pe_header_offset + 24;
468 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
470 if (new_offset != optional_header_offset + 208)
473 num_read = read (file, buffer, 8);
475 /* We are not concerned with endianness, only with
476 * whether it is zero or not.
478 first_word = *(guint32 *)&buffer[0];
479 second_word = *(guint32 *)&buffer[4];
481 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
488 errno = original_errno;
492 gboolean CreateProcessWithLogonW (const gunichar2 *username,
493 const gunichar2 *domain,
494 const gunichar2 *password,
495 const guint32 logonFlags,
496 const gunichar2 *appname,
497 const gunichar2 *cmdline,
498 guint32 create_flags,
500 const gunichar2 *cwd,
501 WapiStartupInfo *startup,
502 WapiProcessInformation *process_info)
504 /* FIXME: use user information */
505 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
509 is_executable (const char *prog)
512 if (access (prog, X_OK) != 0)
514 if (stat (prog, &buf))
516 if (S_ISREG (buf.st_mode))
521 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
522 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
523 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
524 gboolean inherit_handles, guint32 create_flags,
525 gpointer new_environ, const gunichar2 *cwd,
526 WapiStartupInfo *startup,
527 WapiProcessInformation *process_info)
529 gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
530 guint32 i, env_count = 0;
531 gboolean ret = FALSE;
533 struct _WapiHandle_process process_handle = {0}, *process_handle_data;
535 int in_fd, out_fd, err_fd;
538 int startup_pipe [2] = {-1, -1};
540 struct MonoProcess *mono_process;
542 mono_once (&process_ops_once, process_ops_init);
543 mono_once (&process_sig_chld_once, process_add_sigchld_handler);
545 /* appname and cmdline specify the executable and its args:
547 * If appname is not NULL, it is the name of the executable.
548 * Otherwise the executable is the first token in cmdline.
550 * Executable searching:
552 * If appname is not NULL, it can specify the full path and
553 * file name, or else a partial name and the current directory
554 * will be used. There is no additional searching.
556 * If appname is NULL, the first whitespace-delimited token in
557 * cmdline is used. If the name does not contain a full
558 * directory path, the search sequence is:
560 * 1) The directory containing the current process
561 * 2) The current working directory
562 * 3) The windows system directory (Ignored)
563 * 4) The windows directory (Ignored)
566 * Just to make things more interesting, tokens can contain
567 * white space if they are surrounded by quotation marks. I'm
568 * beginning to understand just why windows apps are generally
569 * so crap, with an API like this :-(
571 if (appname != NULL) {
572 cmd = mono_unicode_to_external (appname);
575 g_message ("%s: unicode conversion returned NULL",
579 SetLastError (ERROR_PATH_NOT_FOUND);
583 /* Turn all the slashes round the right way */
584 for (i = 0; i < strlen (cmd); i++) {
585 if (cmd[i] == '\\') {
591 if (cmdline != NULL) {
592 args = mono_unicode_to_external (cmdline);
595 g_message ("%s: unicode conversion returned NULL", __func__);
598 SetLastError (ERROR_PATH_NOT_FOUND);
604 dir = mono_unicode_to_external (cwd);
607 g_message ("%s: unicode conversion returned NULL", __func__);
610 SetLastError (ERROR_PATH_NOT_FOUND);
614 /* Turn all the slashes round the right way */
615 for (i = 0; i < strlen (dir); i++) {
616 if (dir[i] == '\\') {
623 /* We can't put off locating the executable any longer :-( */
626 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
627 /* Strip off the drive letter. I can't
628 * believe that CP/M holdover is still
631 g_memmove (cmd, cmd+2, strlen (cmd)-2);
632 cmd[strlen (cmd)-2] = '\0';
635 unquoted = g_shell_unquote (cmd, NULL);
636 if (unquoted[0] == '/') {
637 /* Assume full path given */
638 prog = g_strdup (unquoted);
640 /* Executable existing ? */
641 if (!is_executable (prog)) {
643 g_message ("%s: Couldn't find executable %s",
647 SetLastError (ERROR_FILE_NOT_FOUND);
651 /* Search for file named by cmd in the current
654 char *curdir = g_get_current_dir ();
656 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
659 /* And make sure it's executable */
660 if (!is_executable (prog)) {
662 g_message ("%s: Couldn't find executable %s",
666 SetLastError (ERROR_FILE_NOT_FOUND);
672 args_after_prog = args;
678 /* Dig out the first token from args, taking quotation
682 /* First, strip off all leading whitespace */
683 args = g_strchug (args);
685 /* args_after_prog points to the contents of args
686 * after token has been set (otherwise argv[0] is
689 args_after_prog = args;
691 /* Assume the opening quote will always be the first
694 if (args[0] == '\"' || args [0] == '\'') {
696 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
697 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
698 /* We found the first token */
699 token = g_strndup (args+1, i-1);
700 args_after_prog = g_strchug (args + i + 1);
702 /* Quotation mark appeared in the
703 * middle of the token. Just give the
704 * whole first token, quotes and all,
711 /* No quote mark, or malformed */
712 for (i = 0; args[i] != '\0'; i++) {
713 if (g_ascii_isspace (args[i])) {
714 token = g_strndup (args, i);
715 args_after_prog = args + i + 1;
721 if (token == NULL && args[0] != '\0') {
722 /* Must be just one token in the string */
723 token = g_strdup (args);
724 args_after_prog = NULL;
730 g_message ("%s: Couldn't find what to exec", __func__);
733 SetLastError (ERROR_PATH_NOT_FOUND);
737 /* Turn all the slashes round the right way. Only for
740 token_len = strlen (token);
741 for (i = 0; i < token_len; i++) {
742 if (token[i] == '\\') {
747 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
748 /* Strip off the drive letter. I can't
749 * believe that CP/M holdover is still
752 g_memmove (token, token+2, strlen (token)-2);
753 token[strlen (token)-2] = '\0';
756 if (token[0] == '/') {
757 /* Assume full path given */
758 prog = g_strdup (token);
760 /* Executable existing ? */
761 if (!is_executable (prog)) {
763 g_message ("%s: Couldn't find executable %s",
767 SetLastError (ERROR_FILE_NOT_FOUND);
772 char *curdir = g_get_current_dir ();
774 /* FIXME: Need to record the directory
775 * containing the current process, and check
776 * that for the new executable as the first
780 prog = g_strdup_printf ("%s/%s", curdir, token);
783 /* I assume X_OK is the criterion to use,
786 if (!is_executable (prog)) {
788 prog = g_find_program_in_path (token);
791 g_message ("%s: Couldn't find executable %s", __func__, token);
795 SetLastError (ERROR_FILE_NOT_FOUND);
805 g_message ("%s: Exec prog [%s] args [%s]", __func__, prog,
809 /* Check for CLR binaries; if found, we will try to invoke
810 * them using the same mono binary that started us.
812 if (is_managed_binary (prog)) {
813 gunichar2 *newapp, *newcmd;
816 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
818 if (newapp != NULL) {
819 if (appname != NULL) {
820 newcmd = utf16_concat (newapp, utf16_space,
821 appname, utf16_space,
824 newcmd = utf16_concat (newapp, utf16_space,
828 g_free ((gunichar2 *)newapp);
830 if (newcmd != NULL) {
831 ret = CreateProcess (NULL, newcmd,
835 create_flags, new_environ,
839 g_free ((gunichar2 *)newcmd);
846 if (args_after_prog != NULL && *args_after_prog) {
849 qprog = g_shell_quote (prog);
850 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
853 full_prog = g_shell_quote (prog);
856 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
858 g_message ("CreateProcess: %s\n", gerr->message);
864 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
865 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
866 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
867 err_fd = GPOINTER_TO_UINT (startup->hStdError);
869 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
870 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
871 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
874 g_strlcpy (process_handle.proc_name, prog,
875 _WAPI_PROC_NAME_MAX_LEN - 1);
877 process_set_defaults (&process_handle);
879 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
880 if (handle == _WAPI_HANDLE_INVALID) {
881 g_warning ("%s: error creating process handle", __func__);
884 SetLastError (ERROR_OUTOFMEMORY);
888 /* new_environ is a block of NULL-terminated strings, which
889 * is itself NULL-terminated. Of course, passing an array of
890 * string pointers would have made things too easy :-(
892 * If new_environ is not NULL it specifies the entire set of
893 * environment variables in the new process. Otherwise the
894 * new process inherits the same environment.
896 if (new_environ != NULL) {
897 gunichar2 *new_environp;
899 /* Count the number of strings */
900 for (new_environp = (gunichar2 *)new_environ; *new_environp;
903 while (*new_environp) {
908 /* +2: one for the process handle value, and the last
911 env_strings = g_new0 (gchar *, env_count + 2);
913 /* Copy each environ string into 'strings' turning it
914 * into utf8 (or the requested encoding) at the same
918 for (new_environp = (gunichar2 *)new_environ; *new_environp;
920 env_strings[env_count] = mono_unicode_to_external (new_environp);
922 while (*new_environp) {
927 for (i = 0; environ[i] != NULL; i++) {
931 /* +2: one for the process handle value, and the last
934 env_strings = g_new0 (gchar *, env_count + 2);
936 /* Copy each environ string into 'strings' turning it
937 * into utf8 (or the requested encoding) at the same
941 for (i = 0; environ[i] != NULL; i++) {
942 env_strings[env_count] = g_strdup (environ[i]);
946 /* pass process handle info to the child, so it doesn't have
947 * to do an expensive search over the whole list
949 if (env_strings != NULL) {
950 struct _WapiHandleUnshared *handle_data;
951 struct _WapiHandle_shared_ref *ref;
953 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
954 ref = &handle_data->u.shared;
956 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
959 /* Create a pipe to make sure the child doesn't exit before
960 * we can add the process to the linked list of mono_processes */
961 if (pipe (startup_pipe) == -1) {
962 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
963 * This is just for a very hard to hit race condition in the first place */
964 startup_pipe [0] = startup_pipe [1] = -1;
966 g_warning ("%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
970 thr_ret = _wapi_handle_lock_shared_handles ();
971 g_assert (thr_ret == 0);
976 SetLastError (ERROR_OUTOFMEMORY);
977 _wapi_handle_unref (handle);
979 } else if (pid == 0) {
982 if (startup_pipe [0] != -1) {
983 /* Wait until the parent has updated it's internal data */
984 read (startup_pipe [0], &dummy, 1);
986 g_warning ("%s: child: parent has completed its setup", __func__);
988 close (startup_pipe [0]);
989 close (startup_pipe [1]);
992 /* should we detach from the process group? */
994 /* Connect stdin, stdout and stderr */
999 if (inherit_handles != TRUE) {
1000 /* FIXME: do something here */
1003 /* Close all file descriptors */
1004 for (i = getdtablesize () - 1; i > 2; i--) {
1009 g_message ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1011 for (i = 0; argv[i] != NULL; i++) {
1012 g_message ("arg %d: [%s]", i, argv[i]);
1015 for (i = 0; env_strings[i] != NULL; i++) {
1016 g_message ("env %d: [%s]", i, env_strings[i]);
1021 if (dir != NULL && chdir (dir) == -1) {
1027 execve (argv[0], argv, env_strings);
1034 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1035 (gpointer *)&process_handle_data);
1037 g_warning ("%s: error looking up process handle %p", __func__,
1039 _wapi_handle_unref (handle);
1043 process_handle_data->id = pid;
1045 /* Add our mono_process into the linked list of mono_processes */
1046 mono_process = (struct MonoProcess *) g_malloc0 (sizeof (struct MonoProcess));
1047 mono_process->pid = pid;
1048 mono_process->handle_count = 1;
1049 if (MONO_SEM_INIT (&mono_process->exit_sem, 0) != 0) {
1050 /* If we can't create the exit semaphore, we just don't add anything
1051 * to our list of mono processes. Waiting on the process will return
1053 g_warning ("%s: could not create exit semaphore for process.", strerror (errno));
1054 g_free (mono_process);
1056 /* Keep the process handle artificially alive until the process
1057 * exits so that the information in the handle isn't lost. */
1058 _wapi_handle_ref (handle);
1059 mono_process->handle = handle;
1061 process_handle_data->self = _wapi_getpid ();
1062 process_handle_data->mono_process = mono_process;
1064 mono_mutex_lock (&mono_processes_mutex);
1065 mono_process->next = mono_processes;
1066 mono_processes = mono_process;
1067 mono_mutex_unlock (&mono_processes_mutex);
1070 if (process_info != NULL) {
1071 process_info->hProcess = handle;
1072 process_info->dwProcessId = pid;
1074 /* FIXME: we might need to handle the thread info some
1077 process_info->hThread = INVALID_HANDLE_VALUE;
1078 process_info->dwThreadId = 0;
1082 _wapi_handle_unlock_shared_handles ();
1084 if (startup_pipe [1] != -1) {
1085 /* Write 1 byte, doesn't matter what */
1086 write (startup_pipe [1], startup_pipe, 1);
1087 close (startup_pipe [0]);
1088 close (startup_pipe [1]);
1095 if (full_prog != NULL) {
1107 if(env_strings != NULL) {
1108 g_strfreev (env_strings);
1115 g_message ("%s: returning handle %p for pid %d", __func__, handle,
1119 /* Check if something needs to be cleaned up. */
1120 mono_processes_cleanup ();
1125 static void process_set_name (struct _WapiHandle_process *process_handle)
1127 gchar *progname, *utf8_progname, *slash;
1129 progname=g_get_prgname ();
1130 utf8_progname=mono_utf8_from_external (progname);
1133 g_message ("%s: using [%s] as prog name", __func__, progname);
1136 if(utf8_progname!=NULL) {
1137 slash=strrchr (utf8_progname, '/');
1139 g_strlcpy (process_handle->proc_name, slash+1,
1140 _WAPI_PROC_NAME_MAX_LEN - 1);
1142 g_strlcpy (process_handle->proc_name, utf8_progname,
1143 _WAPI_PROC_NAME_MAX_LEN - 1);
1146 g_free (utf8_progname);
1150 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
1152 #if !GLIB_CHECK_VERSION (2,4,0)
1153 #define g_setenv(a,b,c) setenv(a,b,c)
1154 #define g_unsetenv(a) unsetenv(a)
1157 static void process_set_current (void)
1159 pid_t pid = _wapi_getpid ();
1160 const char *handle_env;
1161 struct _WapiHandle_process process_handle = {0};
1163 mono_once (&process_ops_once, process_ops_init);
1165 handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1166 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1168 if (handle_env != NULL) {
1169 struct _WapiHandle_process *process_handlep;
1170 gchar *procname = NULL;
1173 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
1176 g_message ("%s: Found my process handle: %p (offset %d 0x%x)",
1177 __func__, current_process, atoi (handle_env),
1181 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
1182 (gpointer *)&process_handlep);
1184 /* This test will probably break on linuxthreads, but
1185 * that should be ancient history on all distros we
1188 if (process_handlep->id == pid) {
1189 procname = process_handlep->proc_name;
1190 if (!strcmp (procname, "mono")) {
1191 /* Set a better process name */
1193 g_message ("%s: Setting better process name", __func__);
1196 process_set_name (process_handlep);
1199 g_message ("%s: Leaving process name: %s", __func__, procname);
1206 /* Wrong pid, so drop this handle and fall through to
1209 _wapi_handle_unref (current_process);
1213 /* We get here if the handle wasn't specified in the
1214 * environment, or if the process ID was wrong, or if the
1215 * handle lookup failed (eg if the parent process forked and
1216 * quit immediately, and deleted the shared data before the
1217 * child got a chance to attach it.)
1221 g_message ("%s: Need to create my own process handle", __func__);
1224 process_handle.id = pid;
1226 process_set_defaults (&process_handle);
1227 process_set_name (&process_handle);
1229 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1231 if (current_process == _WAPI_HANDLE_INVALID) {
1232 g_warning ("%s: error creating process handle", __func__);
1237 gpointer _wapi_process_duplicate ()
1239 mono_once (&process_current_once, process_set_current);
1241 _wapi_handle_ref (current_process);
1243 return(current_process);
1246 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1247 gpointer GetCurrentProcess (void)
1249 mono_once (&process_current_once, process_set_current);
1251 return(_WAPI_PROCESS_CURRENT);
1254 guint32 GetProcessId (gpointer handle)
1256 struct _WapiHandle_process *process_handle;
1259 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1260 /* This is a pseudo handle */
1261 return(GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
1264 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1265 (gpointer *)&process_handle);
1267 SetLastError (ERROR_INVALID_HANDLE);
1271 return (process_handle->id);
1274 guint32 GetCurrentProcessId (void)
1276 mono_once (&process_current_once, process_set_current);
1278 return (GetProcessId (current_process));
1281 /* Returns the process id as a convenience to the functions that call this */
1282 static pid_t signal_process_if_gone (gpointer handle)
1284 struct _WapiHandle_process *process_handle;
1287 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
1289 /* Make sure the process is signalled if it has exited - if
1290 * the parent process didn't wait for it then it won't be
1292 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1293 (gpointer *)&process_handle);
1295 /* It's possible that the handle has vanished during
1296 * the _wapi_search_handle before it gets here, so
1297 * don't spam the console with warnings.
1299 /* g_warning ("%s: error looking up process handle %p",
1300 __func__, handle);*/
1306 g_message ("%s: looking at process %d", __func__, process_handle->id);
1309 if (kill (process_handle->id, 0) == -1 &&
1312 /* The process is dead, (EPERM tells us a new process
1313 * has that ID, but as it's owned by someone else it
1314 * can't be the one listed in our shared memory file)
1316 _wapi_shared_handle_set_signal_state (handle, TRUE);
1319 return (process_handle->id);
1323 static gboolean process_enum (gpointer handle, gpointer user_data)
1325 GArray *processes=user_data;
1326 pid_t pid = signal_process_if_gone (handle);
1333 /* Ignore processes that have already exited (ie they are signalled) */
1334 if (_wapi_handle_issignalled (handle) == FALSE) {
1336 g_message ("%s: process %d added to array", __func__, pid);
1339 /* This ensures that duplicates aren't returned (see
1340 * the comment above _wapi_search_handle () for why
1343 for (i = 0; i < processes->len; i++) {
1344 if (g_array_index (processes, pid_t, i) == pid) {
1345 /* We've already got this one, return
1346 * FALSE to keep searching
1352 g_array_append_val (processes, pid);
1355 /* Return false to keep searching */
1358 #endif /* UNUSED_CODE */
1360 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
1362 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1364 guint32 count, fit, i, j;
1367 size_t proclength, size;
1368 #if defined(__OpenBSD__)
1369 struct kinfo_proc2 *result;
1372 name[1] = KERN_PROC2;
1373 name[2] = KERN_PROC_ALL;
1375 name[4] = sizeof(struct kinfo_proc2);
1378 struct kinfo_proc *result;
1379 static const int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
1382 mono_once (&process_current_once, process_set_current);
1389 #if defined(__OpenBSD__)
1390 size = (sizeof(name) / sizeof(*name));
1392 size = (sizeof(name) / sizeof(*name)) - 1;
1394 err = sysctl ((int *)name, size, NULL, &proclength, NULL, 0);
1397 result = malloc (proclength);
1402 #if defined(__OpenBSD__)
1403 name[5] = (int)(proclength / sizeof(struct kinfo_proc2));
1406 err = sysctl ((int *) name, size, result, &proclength, NULL, 0);
1413 } while (err == 0 && !done);
1416 if (result != NULL) {
1423 #if defined(__OpenBSD__)
1424 count = proclength / sizeof(struct kinfo_proc2);
1426 count = proclength / sizeof(struct kinfo_proc);
1428 fit = len / sizeof(guint32);
1429 for (i = 0, j = 0; j< fit && i < count; i++) {
1430 #if defined(__OpenBSD__)
1431 pids [j++] = result [i].p_pid;
1433 if (result[i].kp_proc.p_pid > 0) /* Pid 0 not supported */
1434 pids [j++] = result [i].kp_proc.p_pid;
1439 *needed = j * sizeof(guint32);
1443 #elif defined(__HAIKU__)
1445 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1451 mono_once (&process_current_once, process_set_current);
1453 fit = len / sizeof (guint32);
1454 while (get_next_team_info (&cookie, &teamInfo) == B_OK && i < fit) {
1455 pids [i++] = teamInfo.team;
1457 *needed = i * sizeof (guint32);
1462 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1466 struct dirent *entry;
1468 mono_once (&process_current_once, process_set_current);
1470 dir = opendir ("/proc");
1476 fit = len / sizeof (guint32);
1477 while(i < fit && (entry = readdir (dir)) != NULL) {
1481 if (!isdigit (entry->d_name[0]))
1484 pid = (pid_t) strtol (entry->d_name, &endptr, 10);
1485 if (*endptr == '\0')
1486 pids [i++] = (guint32) pid;
1489 *needed = i * sizeof(guint32);
1495 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1498 pid_t checking_pid = signal_process_if_gone (handle);
1500 if (checking_pid == 0) {
1504 wanted_pid = GPOINTER_TO_UINT (user_data);
1506 /* It's possible to have more than one process handle with the
1507 * same pid, but only the one running process can be
1510 if (checking_pid == wanted_pid &&
1511 _wapi_handle_issignalled (handle) == FALSE) {
1512 /* If the handle is blown away in the window between
1513 * returning TRUE here and _wapi_search_handle pinging
1514 * the timestamp, the search will continue
1522 gboolean CloseProcess(gpointer handle)
1524 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1525 /* This is a pseudo handle */
1529 return CloseHandle (handle);
1532 gpointer OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1534 /* Find the process handle that corresponds to pid */
1535 gpointer handle = NULL;
1537 mono_once (&process_current_once, process_set_current);
1540 g_message ("%s: looking for process %d", __func__, pid);
1543 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1544 process_open_compare,
1545 GUINT_TO_POINTER (pid), NULL, TRUE);
1547 if (is_pid_valid (pid)) {
1548 /* Return a pseudo handle for processes we
1549 * don't have handles for
1551 return GINT_TO_POINTER (_WAPI_PROCESS_UNHANDLED + pid);
1554 g_message ("%s: Can't find pid %d", __func__, pid);
1557 SetLastError (ERROR_PROC_NOT_FOUND);
1563 _wapi_handle_ref (handle);
1568 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1570 struct _WapiHandle_process *process_handle;
1574 mono_once (&process_current_once, process_set_current);
1580 pid = GPOINTER_TO_UINT (process) - _WAPI_PROCESS_UNHANDLED;
1581 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1582 /* This is a pseudo handle, so we don't know what the
1583 * exit code was, but we can check whether it's alive or not
1585 if (is_pid_valid (pid)) {
1586 *code = STILL_ACTIVE;
1593 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1594 (gpointer *)&process_handle);
1597 g_message ("%s: Can't find process %p", __func__, process);
1603 /* A process handle is only signalled if the process has exited
1604 * and has been waited for */
1606 /* Make sure any process exit has been noticed, before
1607 * checking if the process is signalled. Fixes bug 325463.
1609 process_wait (process, 0, TRUE);
1611 if (_wapi_handle_issignalled (process) == TRUE) {
1612 *code = process_handle->exitstatus;
1614 *code = STILL_ACTIVE;
1620 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1621 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1622 WapiFileTime *user_time)
1624 struct _WapiHandle_process *process_handle;
1626 gboolean ku_times_set = FALSE;
1628 mono_once (&process_current_once, process_set_current);
1630 if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1632 /* Not sure if w32 allows NULLs here or not */
1636 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1637 /* This is a pseudo handle, so just fail for now
1642 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1643 (gpointer *)&process_handle);
1646 g_message ("%s: Can't find process %p", __func__, process);
1652 *create_time=process_handle->create_time;
1654 /* A process handle is only signalled if the process has
1655 * exited. Otherwise exit_time isn't set
1657 if(_wapi_handle_issignalled (process)==TRUE) {
1658 *exit_time=process_handle->exit_time;
1661 #ifdef HAVE_GETRUSAGE
1662 if (process_handle->id == getpid ()) {
1663 struct rusage time_data;
1664 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1666 gint64 *tick_val_ptr;
1667 ku_times_set = TRUE;
1668 tick_val = time_data.ru_utime.tv_sec * 10000000 + time_data.ru_utime.tv_usec * 10;
1669 tick_val_ptr = (gint64*)user_time;
1670 *tick_val_ptr = tick_val;
1671 tick_val = time_data.ru_stime.tv_sec * 10000000 + time_data.ru_stime.tv_usec * 10;
1672 tick_val_ptr = (gint64*)kernel_time;
1673 *tick_val_ptr = tick_val;
1677 if (!ku_times_set) {
1678 memset (kernel_time, 0, sizeof (WapiFileTime));
1679 memset (user_time, 0, sizeof (WapiFileTime));
1687 gpointer address_start;
1688 gpointer address_end;
1690 gpointer address_offset;
1696 static void free_procmodule (WapiProcModule *mod)
1698 if (mod->perms != NULL) {
1699 g_free (mod->perms);
1701 if (mod->filename != NULL) {
1702 g_free (mod->filename);
1707 static gint find_procmodule (gconstpointer a, gconstpointer b)
1709 WapiProcModule *want = (WapiProcModule *)a;
1710 WapiProcModule *compare = (WapiProcModule *)b;
1712 if ((want->device == compare->device) &&
1713 (want->inode == compare->inode)) {
1720 #ifdef PLATFORM_MACOSX
1721 #include <mach-o/dyld.h>
1722 #include <mach-o/getsect.h>
1724 static GSList *load_modules (void)
1727 WapiProcModule *mod;
1728 uint32_t count = _dyld_image_count ();
1731 for (i = 0; i < count; i++) {
1732 #if SIZEOF_VOID_P == 8
1733 const struct mach_header_64 *hdr;
1734 const struct section_64 *sec;
1736 const struct mach_header *hdr;
1737 const struct section *sec;
1742 slide = _dyld_get_image_vmaddr_slide (i);
1743 name = _dyld_get_image_name (i);
1744 hdr = _dyld_get_image_header (i);
1745 #if SIZEOF_VOID_P == 8
1746 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1748 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1751 /* Some dynlibs do not have data sections on osx (#533893) */
1756 mod = g_new0 (WapiProcModule, 1);
1757 mod->address_start = GINT_TO_POINTER (sec->addr);
1758 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1759 mod->perms = g_strdup ("r--p");
1760 mod->address_offset = 0;
1761 mod->device = makedev (0, 0);
1762 mod->inode = (ino_t) i;
1763 mod->filename = g_strdup (name);
1765 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1766 ret = g_slist_prepend (ret, mod);
1768 free_procmodule (mod);
1772 ret = g_slist_reverse (ret);
1776 #elif defined(__OpenBSD__)
1778 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1780 if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1781 + sizeof (info->dlpi_phnum))
1784 struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1788 memcpy(cpy, info, sizeof(*info));
1790 g_ptr_array_add ((GPtrArray *)ptr, cpy);
1795 static GSList *load_modules (void)
1798 WapiProcModule *mod;
1799 GPtrArray *dlarray = g_ptr_array_new();
1802 if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1805 for (i = 0; i < dlarray->len; i++) {
1806 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1808 mod = g_new0 (WapiProcModule, 1);
1809 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1810 mod->address_end = (gpointer)(info->dlpi_addr +
1811 info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1812 mod->perms = g_strdup ("r--p");
1813 mod->address_offset = 0;
1814 mod->inode = (ino_t) i;
1815 mod->filename = g_strdup (info->dlpi_name);
1818 g_message ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1819 mod->inode, mod->filename, mod->address_start, mod->address_end);
1824 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1825 ret = g_slist_prepend (ret, mod);
1827 free_procmodule (mod);
1831 g_ptr_array_free (dlarray, TRUE);
1833 ret = g_slist_reverse (ret);
1837 #elif defined(__HAIKU__)
1839 static GSList *load_modules (void)
1842 WapiProcModule *mod;
1844 image_info imageInfo;
1846 while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
1847 mod = g_new0 (WapiProcModule, 1);
1848 mod->device = imageInfo.device;
1849 mod->inode = imageInfo.node;
1850 mod->filename = g_strdup (imageInfo.name);
1851 mod->address_start = MIN (imageInfo.text, imageInfo.data);
1852 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
1853 (uint8_t*)imageInfo.data + imageInfo.data_size);
1854 mod->perms = g_strdup ("r--p");
1855 mod->address_offset = 0;
1857 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1858 ret = g_slist_prepend (ret, mod);
1860 free_procmodule (mod);
1864 ret = g_slist_reverse (ret);
1869 static GSList *load_modules (FILE *fp)
1872 WapiProcModule *mod;
1873 gchar buf[MAXPATHLEN + 1], *p, *endp;
1874 gchar *start_start, *end_start, *prot_start, *offset_start;
1875 gchar *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1876 gpointer address_start, address_end, address_offset;
1877 guint32 maj_dev, min_dev;
1881 while (fgets (buf, sizeof(buf), fp)) {
1883 while (g_ascii_isspace (*p)) ++p;
1885 if (!g_ascii_isxdigit (*start_start)) {
1888 address_start = (gpointer)strtoul (start_start, &endp, 16);
1896 if (!g_ascii_isxdigit (*end_start)) {
1899 address_end = (gpointer)strtoul (end_start, &endp, 16);
1901 if (!g_ascii_isspace (*p)) {
1905 while (g_ascii_isspace (*p)) ++p;
1907 if (*prot_start != 'r' && *prot_start != '-') {
1910 memcpy (prot_buf, prot_start, 4);
1912 while (!g_ascii_isspace (*p)) ++p;
1914 while (g_ascii_isspace (*p)) ++p;
1916 if (!g_ascii_isxdigit (*offset_start)) {
1919 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1921 if (!g_ascii_isspace (*p)) {
1925 while(g_ascii_isspace (*p)) ++p;
1927 if (!g_ascii_isxdigit (*maj_dev_start)) {
1930 maj_dev = strtoul (maj_dev_start, &endp, 16);
1938 if (!g_ascii_isxdigit (*min_dev_start)) {
1941 min_dev = strtoul (min_dev_start, &endp, 16);
1943 if (!g_ascii_isspace (*p)) {
1947 while (g_ascii_isspace (*p)) ++p;
1949 if (!g_ascii_isxdigit (*inode_start)) {
1952 inode = (ino_t)strtol (inode_start, &endp, 10);
1954 if (!g_ascii_isspace (*p)) {
1958 device = makedev ((int)maj_dev, (int)min_dev);
1959 if ((device == 0) &&
1964 while(g_ascii_isspace (*p)) ++p;
1965 /* p now points to the filename */
1967 mod = g_new0 (WapiProcModule, 1);
1968 mod->address_start = address_start;
1969 mod->address_end = address_end;
1970 mod->perms = g_strdup (prot_buf);
1971 mod->address_offset = address_offset;
1972 mod->device = device;
1974 mod->filename = g_strdup (g_strstrip (p));
1976 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1977 ret = g_slist_prepend (ret, mod);
1979 free_procmodule (mod);
1983 ret = g_slist_reverse (ret);
1989 static gboolean match_procname_to_modulename (gchar *procname, gchar *modulename)
1991 char* lastsep = NULL;
1994 gboolean result = FALSE;
1996 if (procname == NULL || modulename == NULL)
1999 pname = mono_path_resolve_symlinks (procname);
2000 mname = mono_path_resolve_symlinks (modulename);
2002 if (!strcmp (pname, mname))
2006 lastsep = strrchr (mname, '/');
2008 if (!strcmp (lastsep+1, pname))
2018 #if !defined(__OpenBSD__)
2020 open_process_map (int pid, const char *mode)
2023 const gchar *proc_path[] = {
2024 "/proc/%d/maps", /* GNU/Linux */
2025 "/proc/%d/map", /* FreeBSD */
2031 for (i = 0; fp == NULL && proc_path [i]; i++) {
2032 filename = g_strdup_printf (proc_path[i], pid);
2033 fp = fopen (filename, mode);
2041 gboolean EnumProcessModules (gpointer process, gpointer *modules,
2042 guint32 size, guint32 *needed)
2044 struct _WapiHandle_process *process_handle;
2046 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2049 GSList *mods = NULL;
2050 WapiProcModule *module;
2051 guint32 count, avail = size / sizeof(gpointer);
2054 gchar *proc_name = NULL;
2056 /* Store modules in an array of pointers (main module as
2057 * modules[0]), using the load address for each module as a
2058 * token. (Use 'NULL' as an alternative for the main module
2059 * so that the simple implementation can just return one item
2060 * for now.) Get the info from /proc/<pid>/maps on linux,
2061 * /proc/<pid>/map on FreeBSD, other systems will have to
2062 * implement /dev/kmem reading or whatever other horrid
2063 * technique is needed.
2065 if (size < sizeof(gpointer)) {
2069 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2070 /* This is a pseudo handle */
2071 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2073 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2074 (gpointer *)&process_handle);
2077 g_message ("%s: Can't find process %p", __func__, process);
2082 pid = process_handle->id;
2083 proc_name = process_handle->proc_name;
2086 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2088 mods = load_modules ();
2090 if ((fp = open_process_map (pid, "r")) == NULL) {
2091 /* No /proc/<pid>/maps so just return the main module
2095 *needed = sizeof(gpointer);
2097 mods = load_modules (fp);
2100 count = g_slist_length (mods);
2102 /* count + 1 to leave slot 0 for the main module */
2103 *needed = sizeof(gpointer) * (count + 1);
2105 /* Use the NULL shortcut, as the first line in
2106 * /proc/<pid>/maps isn't the executable, and we need
2107 * that first in the returned list. Check the module name
2108 * to see if it ends with the proc name and substitute
2109 * the first entry with it. FIXME if this turns out to
2113 for (i = 0; i < (avail - 1) && i < count; i++) {
2114 module = (WapiProcModule *)g_slist_nth_data (mods, i);
2115 if (modules[0] != NULL)
2116 modules[i] = module->address_start;
2117 else if (match_procname_to_modulename (proc_name, module->filename))
2118 modules[0] = module->address_start;
2120 modules[i + 1] = module->address_start;
2123 for (i = 0; i < count; i++) {
2124 free_procmodule (g_slist_nth_data (mods, i));
2126 g_slist_free (mods);
2132 static gchar *get_process_name_from_proc (pid_t pid)
2137 struct kinfo_proc2 *pi;
2138 #elif defined(PLATFORM_MACOSX)
2140 struct kinfo_proc *pi;
2141 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
2144 gchar *filename = NULL;
2149 #if defined(PLATFORM_SOLARIS)
2150 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
2151 if ((fp = fopen (filename, "r")) != NULL) {
2155 nread = fread (&info, sizeof (info), 1, fp);
2157 ret = g_strdup (info.pr_fname);
2163 #elif defined(PLATFORM_MACOSX)
2164 #if (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5) && !defined (__mono_ppc__) && !defined(__arm__)
2165 /* No proc name on OSX < 10.5 nor ppc nor iOS */
2166 memset (buf, '\0', sizeof(buf));
2167 proc_name (pid, buf, sizeof(buf));
2168 if (strlen (buf) > 0)
2169 ret = g_strdup (buf);
2171 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0)
2174 if ((pi = malloc(size)) == NULL)
2177 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
2178 if (errno == ENOMEM) {
2181 g_message ("%s: Didn't allocate enough memory for kproc info", __func__);
2187 if (strlen (pi->kp_proc.p_comm) > 0)
2188 ret = g_strdup (pi->kp_proc.p_comm);
2192 #elif defined(__OpenBSD__)
2195 struct kinfo_proc2 *pi;
2198 mib [1] = KERN_PROC2;
2199 mib [2] = KERN_PROC_PID;
2201 mib [4] = sizeof(struct kinfo_proc2);
2205 if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0)
2208 if ((pi = malloc(size)) == NULL)
2211 mib[5] = (int)(size / sizeof(struct kinfo_proc2));
2213 if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
2214 (size != sizeof (struct kinfo_proc2))) {
2215 if (errno == ENOMEM) {
2222 if (strlen (pi->p_comm) > 0)
2223 ret = g_strdup (pi->p_comm);
2226 #elif defined(__HAIKU__)
2227 image_info imageInfo;
2230 if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
2231 ret = g_strdup (imageInfo.name);
2234 memset (buf, '\0', sizeof(buf));
2235 filename = g_strdup_printf ("/proc/%d/exe", pid);
2236 if (readlink (filename, buf, 255) > 0) {
2237 ret = g_strdup (buf);
2245 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
2246 if ((fp = fopen (filename, "r")) != NULL) {
2247 if (fgets (buf, 256, fp) != NULL) {
2248 ret = g_strdup (buf);
2259 filename = g_strdup_printf ("/proc/%d/stat", pid);
2260 if ((fp = fopen (filename, "r")) != NULL) {
2261 if (fgets (buf, 256, fp) != NULL) {
2264 start = strchr (buf, '(');
2265 if (start != NULL) {
2266 end = strchr (start + 1, ')');
2269 ret = g_strndup (start + 1,
2283 static guint32 get_module_name (gpointer process, gpointer module,
2284 gunichar2 *basename, guint32 size,
2287 struct _WapiHandle_process *process_handle;
2290 gunichar2 *procname;
2291 gchar *procname_ext = NULL;
2294 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2297 GSList *mods = NULL;
2298 WapiProcModule *found_module;
2301 gchar *proc_name = NULL;
2303 mono_once (&process_current_once, process_set_current);
2306 g_message ("%s: Getting module base name, process handle %p module %p",
2307 __func__, process, module);
2310 size = size*sizeof(gunichar2); /* adjust for unicode characters */
2312 if (basename == NULL || size == 0) {
2316 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2317 /* This is a pseudo handle */
2318 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2319 proc_name = get_process_name_from_proc (pid);
2321 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2322 (gpointer *)&process_handle);
2325 g_message ("%s: Can't find process %p", __func__,
2331 pid = process_handle->id;
2332 proc_name = g_strdup (process_handle->proc_name);
2335 /* Look up the address in /proc/<pid>/maps */
2336 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2338 mods = load_modules ();
2340 if ((fp = open_process_map (pid, "r")) == NULL) {
2341 if (errno == EACCES && module == NULL && base == TRUE) {
2342 procname_ext = get_process_name_from_proc (pid);
2344 /* No /proc/<pid>/maps, so just return failure
2351 mods = load_modules (fp);
2354 count = g_slist_length (mods);
2356 /* If module != NULL compare the address.
2357 * If module == NULL we are looking for the main module.
2358 * The best we can do for now check it the module name end with the process name.
2360 for (i = 0; i < count; i++) {
2361 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2362 if (procname_ext == NULL &&
2363 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2364 (module != NULL && found_module->address_start == module))) {
2366 procname_ext = g_path_get_basename (found_module->filename);
2368 procname_ext = g_strdup (found_module->filename);
2372 free_procmodule (found_module);
2375 if (procname_ext == NULL)
2377 /* If it's *still* null, we might have hit the
2378 * case where reading /proc/$pid/maps gives an
2379 * empty file for this user.
2381 procname_ext = get_process_name_from_proc (pid);
2384 g_slist_free (mods);
2388 if (procname_ext != NULL) {
2390 g_message ("%s: Process name is [%s]", __func__,
2394 procname = mono_unicode_from_external (procname_ext, &bytes);
2395 if (procname == NULL) {
2397 g_free (procname_ext);
2403 /* Add the terminator */
2408 g_message ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2411 memcpy (basename, procname, size);
2414 g_message ("%s: Size %d larger than needed (%ld)",
2415 __func__, size, bytes);
2418 memcpy (basename, procname, bytes);
2422 g_free (procname_ext);
2430 guint32 GetModuleBaseName (gpointer process, gpointer module,
2431 gunichar2 *basename, guint32 size)
2433 return(get_module_name (process, module, basename, size, TRUE));
2436 guint32 GetModuleFileNameEx (gpointer process, gpointer module,
2437 gunichar2 *filename, guint32 size)
2439 return(get_module_name (process, module, filename, size, FALSE));
2442 gboolean GetModuleInformation (gpointer process, gpointer module,
2443 WapiModuleInfo *modinfo, guint32 size)
2445 struct _WapiHandle_process *process_handle;
2448 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2451 GSList *mods = NULL;
2452 WapiProcModule *found_module;
2455 gboolean ret = FALSE;
2456 gchar *proc_name = NULL;
2458 mono_once (&process_current_once, process_set_current);
2461 g_message ("%s: Getting module info, process handle %p module %p",
2462 __func__, process, module);
2465 if (modinfo == NULL || size < sizeof(WapiModuleInfo)) {
2469 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2470 /* This is a pseudo handle */
2471 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2472 proc_name = get_process_name_from_proc (pid);
2474 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2475 (gpointer *)&process_handle);
2478 g_message ("%s: Can't find process %p", __func__,
2484 pid = process_handle->id;
2485 proc_name = g_strdup (process_handle->proc_name);
2488 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2490 mods = load_modules ();
2492 /* Look up the address in /proc/<pid>/maps */
2493 if ((fp = open_process_map (pid, "r")) == NULL) {
2494 /* No /proc/<pid>/maps, so just return failure
2500 mods = load_modules (fp);
2503 count = g_slist_length (mods);
2505 /* If module != NULL compare the address.
2506 * If module == NULL we are looking for the main module.
2507 * The best we can do for now check it the module name end with the process name.
2509 for (i = 0; i < count; i++) {
2510 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2511 if ( ret == FALSE &&
2512 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2513 (module != NULL && found_module->address_start == module))) {
2514 modinfo->lpBaseOfDll = found_module->address_start;
2515 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2516 modinfo->EntryPoint = found_module->address_offset;
2520 free_procmodule (found_module);
2523 g_slist_free (mods);
2530 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2532 struct _WapiHandle_process *process_handle;
2535 mono_once (&process_current_once, process_set_current);
2537 if(min==NULL || max==NULL) {
2538 /* Not sure if w32 allows NULLs here or not */
2542 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2543 /* This is a pseudo handle, so just fail for now
2548 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2549 (gpointer *)&process_handle);
2552 g_message ("%s: Can't find process %p", __func__, process);
2558 *min=process_handle->min_working_set;
2559 *max=process_handle->max_working_set;
2564 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2566 struct _WapiHandle_process *process_handle;
2569 mono_once (&process_current_once, process_set_current);
2571 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2572 /* This is a pseudo handle, so just fail for now
2577 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2578 (gpointer *)&process_handle);
2581 g_message ("%s: Can't find process %p", __func__, process);
2587 process_handle->min_working_set=min;
2588 process_handle->max_working_set=max;
2595 TerminateProcess (gpointer process, gint32 exitCode)
2597 struct _WapiHandle_process *process_handle;
2603 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2604 /* This is a pseudo handle */
2605 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2607 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2608 (gpointer *) &process_handle);
2612 g_message ("%s: Can't find process %p", __func__,
2615 SetLastError (ERROR_INVALID_HANDLE);
2618 pid = process_handle->id;
2621 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2622 ret = kill (pid, signo);
2626 SetLastError (ERROR_INVALID_PARAMETER);
2629 SetLastError (ERROR_ACCESS_DENIED);
2632 SetLastError (ERROR_PROC_NOT_FOUND);
2635 SetLastError (ERROR_GEN_FAILURE);
2643 GetPriorityClass (gpointer process)
2645 #ifdef HAVE_GETPRIORITY
2646 struct _WapiHandle_process *process_handle;
2651 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2652 /* This is a pseudo handle */
2653 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2655 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2656 (gpointer *) &process_handle);
2659 SetLastError (ERROR_INVALID_HANDLE);
2662 pid = process_handle->id;
2666 ret = getpriority (PRIO_PROCESS, pid);
2667 if (ret == -1 && errno != 0) {
2671 SetLastError (ERROR_ACCESS_DENIED);
2674 SetLastError (ERROR_PROC_NOT_FOUND);
2677 SetLastError (ERROR_GEN_FAILURE);
2683 return NORMAL_PRIORITY_CLASS;
2685 return REALTIME_PRIORITY_CLASS;
2687 return HIGH_PRIORITY_CLASS;
2689 return ABOVE_NORMAL_PRIORITY_CLASS;
2691 return IDLE_PRIORITY_CLASS;
2693 return BELOW_NORMAL_PRIORITY_CLASS;
2695 return NORMAL_PRIORITY_CLASS;
2697 SetLastError (ERROR_NOT_SUPPORTED);
2703 SetPriorityClass (gpointer process, guint32 priority_class)
2705 #ifdef HAVE_SETPRIORITY
2706 struct _WapiHandle_process *process_handle;
2712 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2713 /* This is a pseudo handle */
2714 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2716 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2717 (gpointer *) &process_handle);
2720 SetLastError (ERROR_INVALID_HANDLE);
2723 pid = process_handle->id;
2726 switch (priority_class) {
2727 case IDLE_PRIORITY_CLASS:
2730 case BELOW_NORMAL_PRIORITY_CLASS:
2733 case NORMAL_PRIORITY_CLASS:
2736 case ABOVE_NORMAL_PRIORITY_CLASS:
2739 case HIGH_PRIORITY_CLASS:
2742 case REALTIME_PRIORITY_CLASS:
2746 SetLastError (ERROR_INVALID_PARAMETER);
2750 ret = setpriority (PRIO_PROCESS, pid, prio);
2755 SetLastError (ERROR_ACCESS_DENIED);
2758 SetLastError (ERROR_PROC_NOT_FOUND);
2761 SetLastError (ERROR_GEN_FAILURE);
2767 SetLastError (ERROR_NOT_SUPPORTED);
2773 mono_processes_cleanup (void)
2775 struct MonoProcess *mp;
2776 struct MonoProcess *prev = NULL;
2777 struct MonoProcess *candidate = NULL;
2778 gpointer unref_handle;
2782 g_warning ("%s", __func__);
2785 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2786 if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
2789 mp = mono_processes;
2790 while (mp != NULL) {
2791 if (mp->pid == 0 && mp->handle != NULL) {
2792 /* This process has exited and we need to remove the artifical ref
2794 mono_mutex_lock (&mono_processes_mutex);
2795 unref_handle = mp->handle;
2797 mono_mutex_unlock (&mono_processes_mutex);
2799 _wapi_handle_unref (unref_handle);
2805 mp = mono_processes;
2807 while (mp != NULL) {
2808 if ((mp->handle_count == 0 && mp->pid == 0) || candidate != NULL) {
2810 _wapi_handle_spin (spin);
2814 /* We've found a candidate */
2815 mono_mutex_lock (&mono_processes_mutex);
2816 if (candidate == NULL) {
2818 if (mp == mono_processes) {
2819 mono_processes = mp->next;
2821 prev->next = mp->next;
2826 /* It's still safe to traverse the structure.*/
2827 mono_memory_barrier ();
2829 if (mono_processes_read_lock != 0) {
2830 /* The sigchld handler is watching us. Spin a bit and try again */
2833 } else if (spin >= 8) {
2834 /* Just give up for now */
2835 mono_mutex_unlock (&mono_processes_mutex);
2839 /* We've modified the list of processes, and we know the sigchld handler
2840 * isn't executing, so even if it executes at any moment, it'll see the
2841 * new version of the list. So now we can free the candidate. */
2843 g_warning ("%s: freeing candidate %p", __func__, candidate);
2845 mp = candidate->next;
2846 MONO_SEM_DESTROY (&candidate->exit_sem);
2851 mono_mutex_unlock (&mono_processes_mutex);
2861 g_warning ("%s done", __func__);
2864 InterlockedDecrement (&mono_processes_cleaning_up);
2868 process_close (gpointer handle, gpointer data)
2870 struct _WapiHandle_process *process_handle;
2873 g_warning ("%s", __func__);
2876 process_handle = (struct _WapiHandle_process *) data;
2877 if (process_handle->mono_process && process_handle->self == _wapi_getpid ())
2878 InterlockedDecrement (&process_handle->mono_process->handle_count);
2879 mono_processes_cleanup ();
2884 mono_sigchld_signal_handler (int _dummy, siginfo_t *info, void *context)
2888 struct MonoProcess *p;
2891 fprintf (stdout, "SIG CHILD handler for pid: %i\n", info->si_pid);
2894 InterlockedIncrement (&mono_processes_read_lock);
2898 pid = waitpid (-1, &status, WNOHANG);
2899 } while (pid == -1 && errno == EINTR);
2905 fprintf (stdout, "child ended: %i", pid);
2909 if (p->pid == pid) {
2910 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2912 MONO_SEM_POST (&p->exit_sem);
2919 InterlockedDecrement (&mono_processes_read_lock);
2922 fprintf (stdout, "SIG CHILD handler: done looping.");
2927 static void process_add_sigchld_handler (void)
2930 struct sigaction sa;
2932 sa.sa_sigaction = mono_sigchld_signal_handler;
2933 sigemptyset (&sa.sa_mask);
2934 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2935 g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2937 g_warning ("Added SIGCHLD handler");
2942 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2944 struct _WapiHandle_process *process_handle;
2950 struct MonoProcess *mp;
2952 gpointer current_thread;
2954 current_thread = _wapi_thread_handle_from_id (pthread_self ());
2955 if (current_thread == NULL) {
2956 SetLastError (ERROR_INVALID_HANDLE);
2960 /* FIXME: We can now easily wait on processes that aren't our own children,
2961 * but WaitFor*Object won't call us for pseudo handles. */
2962 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2965 g_warning ("%s (%p, %u)", __func__, handle, timeout);
2968 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS, (gpointer *)&process_handle);
2970 g_warning ("%s: error looking up process handle %p", __func__, handle);
2974 if (process_handle->exited) {
2975 /* We've already done this one */
2977 g_warning ("%s (%p, %u): Process already exited", __func__, handle, timeout);
2979 return WAIT_OBJECT_0;
2982 pid = process_handle->id;
2985 g_warning ("%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2988 /* We don't need to lock mono_processes here, the entry
2989 * has a handle_count > 0 which means it will not be freed. */
2990 mp = process_handle->mono_process;
2991 if (mp && process_handle->self != _wapi_getpid ()) {
2992 /* mono_process points to memory in another process' address space: we can't use it */
2996 start = mono_msec_ticks ();
3002 /* We have a semaphore we can wait on */
3003 if (timeout != INFINITE) {
3005 g_warning ("%s (%p, %u): waiting on semaphore for %li ms...",
3006 __func__, handle, timeout, (timeout - (now - start)));
3009 ret = MONO_SEM_TIMEDWAIT_ALERTABLE (&mp->exit_sem, (timeout - (now - start)), alertable);
3012 g_warning ("%s (%p, %u): waiting on semaphore forever...",
3013 __func__, handle, timeout);
3015 ret = MONO_SEM_WAIT_ALERTABLE (&mp->exit_sem, alertable);
3018 if (ret == -1 && errno != EINTR && errno != ETIMEDOUT) {
3020 g_warning ("%s (%p, %u): sem_timedwait failure: %s",
3021 __func__, handle, timeout, g_strerror (errno));
3023 /* Should we return a failure here? */
3027 /* Success, process has exited */
3028 MONO_SEM_POST (&mp->exit_sem);
3032 /* We did not create this process, so we can't waidpid / sem_wait it.
3033 * We need to poll for the pid existence */
3035 g_warning ("%s (%p, %u): polling on pid...", __func__, handle, timeout);
3037 if (!is_pid_valid (pid)) {
3038 /* Success, process has exited */
3045 g_warning ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
3047 return WAIT_TIMEOUT;
3050 now = mono_msec_ticks ();
3051 if (now - start >= timeout) {
3053 g_warning ("%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
3055 return WAIT_TIMEOUT;
3059 /* "timeout - (now - start)" will not underflow, since timeout is always >=0,
3060 * and we passed the check just above */
3061 _wapi_handle_spin (MIN (100, timeout - (now - start)));
3064 if (alertable && _wapi_thread_apc_pending (current_thread)) {
3066 g_warning ("%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
3068 return WAIT_IO_COMPLETION;
3072 /* Process must have exited */
3074 g_warning ("%s (%p, %u): Waited successfully", __func__, handle, timeout);
3077 ret = _wapi_handle_lock_shared_handles ();
3078 g_assert (ret == 0);
3080 status = mp ? mp->status : 0;
3081 if (WIFSIGNALED (status)) {
3082 process_handle->exitstatus = 128 + WTERMSIG (status);
3084 process_handle->exitstatus = WEXITSTATUS (status);
3086 _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
3088 process_handle->exited = TRUE;
3091 g_warning ("%s (%p, %u): Setting pid %d signalled, exit status %d",
3092 __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
3095 _wapi_shared_handle_set_signal_state (handle, TRUE);
3097 _wapi_handle_unlock_shared_handles ();
3099 return WAIT_OBJECT_0;