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 void switchDirectorySeparators(gchar *path)
523 size_t i, pathLength = strlen(path);
525 /* Turn all the slashes round the right way, except for \' */
526 /* There are probably other characters that need to be excluded as well. */
527 for (i = 0; i < pathLength; i++)
529 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' ) {
535 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
536 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
537 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
538 gboolean inherit_handles, guint32 create_flags,
539 gpointer new_environ, const gunichar2 *cwd,
540 WapiStartupInfo *startup,
541 WapiProcessInformation *process_info)
543 gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
544 guint32 i, env_count = 0;
545 gboolean ret = FALSE;
547 struct _WapiHandle_process process_handle = {0}, *process_handle_data;
549 int in_fd, out_fd, err_fd;
552 int startup_pipe [2] = {-1, -1};
554 struct MonoProcess *mono_process;
556 mono_once (&process_ops_once, process_ops_init);
557 mono_once (&process_sig_chld_once, process_add_sigchld_handler);
559 /* appname and cmdline specify the executable and its args:
561 * If appname is not NULL, it is the name of the executable.
562 * Otherwise the executable is the first token in cmdline.
564 * Executable searching:
566 * If appname is not NULL, it can specify the full path and
567 * file name, or else a partial name and the current directory
568 * will be used. There is no additional searching.
570 * If appname is NULL, the first whitespace-delimited token in
571 * cmdline is used. If the name does not contain a full
572 * directory path, the search sequence is:
574 * 1) The directory containing the current process
575 * 2) The current working directory
576 * 3) The windows system directory (Ignored)
577 * 4) The windows directory (Ignored)
580 * Just to make things more interesting, tokens can contain
581 * white space if they are surrounded by quotation marks. I'm
582 * beginning to understand just why windows apps are generally
583 * so crap, with an API like this :-(
585 if (appname != NULL) {
586 cmd = mono_unicode_to_external (appname);
589 g_message ("%s: unicode conversion returned NULL",
593 SetLastError (ERROR_PATH_NOT_FOUND);
597 switchDirectorySeparators(cmd);
600 if (cmdline != NULL) {
601 args = mono_unicode_to_external (cmdline);
604 g_message ("%s: unicode conversion returned NULL", __func__);
607 SetLastError (ERROR_PATH_NOT_FOUND);
613 dir = mono_unicode_to_external (cwd);
616 g_message ("%s: unicode conversion returned NULL", __func__);
619 SetLastError (ERROR_PATH_NOT_FOUND);
623 /* Turn all the slashes round the right way */
624 switchDirectorySeparators(dir);
628 /* We can't put off locating the executable any longer :-( */
631 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
632 /* Strip off the drive letter. I can't
633 * believe that CP/M holdover is still
636 g_memmove (cmd, cmd+2, strlen (cmd)-2);
637 cmd[strlen (cmd)-2] = '\0';
640 unquoted = g_shell_unquote (cmd, NULL);
641 if (unquoted[0] == '/') {
642 /* Assume full path given */
643 prog = g_strdup (unquoted);
645 /* Executable existing ? */
646 if (!is_executable (prog)) {
648 g_message ("%s: Couldn't find executable %s",
652 SetLastError (ERROR_FILE_NOT_FOUND);
656 /* Search for file named by cmd in the current
659 char *curdir = g_get_current_dir ();
661 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
664 /* And make sure it's executable */
665 if (!is_executable (prog)) {
667 g_message ("%s: Couldn't find executable %s",
671 SetLastError (ERROR_FILE_NOT_FOUND);
677 args_after_prog = args;
683 /* Dig out the first token from args, taking quotation
687 /* First, strip off all leading whitespace */
688 args = g_strchug (args);
690 /* args_after_prog points to the contents of args
691 * after token has been set (otherwise argv[0] is
694 args_after_prog = args;
696 /* Assume the opening quote will always be the first
699 if (args[0] == '\"' || args [0] == '\'') {
701 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
702 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
703 /* We found the first token */
704 token = g_strndup (args+1, i-1);
705 args_after_prog = g_strchug (args + i + 1);
707 /* Quotation mark appeared in the
708 * middle of the token. Just give the
709 * whole first token, quotes and all,
716 /* No quote mark, or malformed */
717 for (i = 0; args[i] != '\0'; i++) {
718 if (g_ascii_isspace (args[i])) {
719 token = g_strndup (args, i);
720 args_after_prog = args + i + 1;
726 if (token == NULL && args[0] != '\0') {
727 /* Must be just one token in the string */
728 token = g_strdup (args);
729 args_after_prog = NULL;
735 g_message ("%s: Couldn't find what to exec", __func__);
738 SetLastError (ERROR_PATH_NOT_FOUND);
742 /* Turn all the slashes round the right way. Only for
745 switchDirectorySeparators(token);
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)
2134 #if defined(__OpenBSD__)
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__)
2194 mib [1] = KERN_PROC2;
2195 mib [2] = KERN_PROC_PID;
2197 mib [4] = sizeof(struct kinfo_proc2);
2201 if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0)
2204 if ((pi = malloc(size)) == NULL)
2207 mib[5] = (int)(size / sizeof(struct kinfo_proc2));
2209 if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
2210 (size != sizeof (struct kinfo_proc2))) {
2211 if (errno == ENOMEM) {
2218 if (strlen (pi->p_comm) > 0)
2219 ret = g_strdup (pi->p_comm);
2222 #elif defined(__HAIKU__)
2223 image_info imageInfo;
2226 if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
2227 ret = g_strdup (imageInfo.name);
2230 memset (buf, '\0', sizeof(buf));
2231 filename = g_strdup_printf ("/proc/%d/exe", pid);
2232 if (readlink (filename, buf, 255) > 0) {
2233 ret = g_strdup (buf);
2241 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
2242 if ((fp = fopen (filename, "r")) != NULL) {
2243 if (fgets (buf, 256, fp) != NULL) {
2244 ret = g_strdup (buf);
2255 filename = g_strdup_printf ("/proc/%d/stat", pid);
2256 if ((fp = fopen (filename, "r")) != NULL) {
2257 if (fgets (buf, 256, fp) != NULL) {
2260 start = strchr (buf, '(');
2261 if (start != NULL) {
2262 end = strchr (start + 1, ')');
2265 ret = g_strndup (start + 1,
2279 static guint32 get_module_name (gpointer process, gpointer module,
2280 gunichar2 *basename, guint32 size,
2283 struct _WapiHandle_process *process_handle;
2286 gunichar2 *procname;
2287 gchar *procname_ext = NULL;
2290 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2293 GSList *mods = NULL;
2294 WapiProcModule *found_module;
2297 gchar *proc_name = NULL;
2299 mono_once (&process_current_once, process_set_current);
2302 g_message ("%s: Getting module base name, process handle %p module %p",
2303 __func__, process, module);
2306 size = size*sizeof(gunichar2); /* adjust for unicode characters */
2308 if (basename == NULL || size == 0) {
2312 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2313 /* This is a pseudo handle */
2314 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2315 proc_name = get_process_name_from_proc (pid);
2317 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2318 (gpointer *)&process_handle);
2321 g_message ("%s: Can't find process %p", __func__,
2327 pid = process_handle->id;
2328 proc_name = g_strdup (process_handle->proc_name);
2331 /* Look up the address in /proc/<pid>/maps */
2332 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2334 mods = load_modules ();
2336 if ((fp = open_process_map (pid, "r")) == NULL) {
2337 if (errno == EACCES && module == NULL && base == TRUE) {
2338 procname_ext = get_process_name_from_proc (pid);
2340 /* No /proc/<pid>/maps, so just return failure
2347 mods = load_modules (fp);
2350 count = g_slist_length (mods);
2352 /* If module != NULL compare the address.
2353 * If module == NULL we are looking for the main module.
2354 * The best we can do for now check it the module name end with the process name.
2356 for (i = 0; i < count; i++) {
2357 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2358 if (procname_ext == NULL &&
2359 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2360 (module != NULL && found_module->address_start == module))) {
2362 procname_ext = g_path_get_basename (found_module->filename);
2364 procname_ext = g_strdup (found_module->filename);
2368 free_procmodule (found_module);
2371 if (procname_ext == NULL)
2373 /* If it's *still* null, we might have hit the
2374 * case where reading /proc/$pid/maps gives an
2375 * empty file for this user.
2377 procname_ext = get_process_name_from_proc (pid);
2380 g_slist_free (mods);
2384 if (procname_ext != NULL) {
2386 g_message ("%s: Process name is [%s]", __func__,
2390 procname = mono_unicode_from_external (procname_ext, &bytes);
2391 if (procname == NULL) {
2393 g_free (procname_ext);
2399 /* Add the terminator */
2404 g_message ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2407 memcpy (basename, procname, size);
2410 g_message ("%s: Size %d larger than needed (%ld)",
2411 __func__, size, bytes);
2414 memcpy (basename, procname, bytes);
2418 g_free (procname_ext);
2426 guint32 GetModuleBaseName (gpointer process, gpointer module,
2427 gunichar2 *basename, guint32 size)
2429 return(get_module_name (process, module, basename, size, TRUE));
2432 guint32 GetModuleFileNameEx (gpointer process, gpointer module,
2433 gunichar2 *filename, guint32 size)
2435 return(get_module_name (process, module, filename, size, FALSE));
2438 gboolean GetModuleInformation (gpointer process, gpointer module,
2439 WapiModuleInfo *modinfo, guint32 size)
2441 struct _WapiHandle_process *process_handle;
2444 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2447 GSList *mods = NULL;
2448 WapiProcModule *found_module;
2451 gboolean ret = FALSE;
2452 gchar *proc_name = NULL;
2454 mono_once (&process_current_once, process_set_current);
2457 g_message ("%s: Getting module info, process handle %p module %p",
2458 __func__, process, module);
2461 if (modinfo == NULL || size < sizeof(WapiModuleInfo)) {
2465 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2466 /* This is a pseudo handle */
2467 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2468 proc_name = get_process_name_from_proc (pid);
2470 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2471 (gpointer *)&process_handle);
2474 g_message ("%s: Can't find process %p", __func__,
2480 pid = process_handle->id;
2481 proc_name = g_strdup (process_handle->proc_name);
2484 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2486 mods = load_modules ();
2488 /* Look up the address in /proc/<pid>/maps */
2489 if ((fp = open_process_map (pid, "r")) == NULL) {
2490 /* No /proc/<pid>/maps, so just return failure
2496 mods = load_modules (fp);
2499 count = g_slist_length (mods);
2501 /* If module != NULL compare the address.
2502 * If module == NULL we are looking for the main module.
2503 * The best we can do for now check it the module name end with the process name.
2505 for (i = 0; i < count; i++) {
2506 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2507 if ( ret == FALSE &&
2508 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2509 (module != NULL && found_module->address_start == module))) {
2510 modinfo->lpBaseOfDll = found_module->address_start;
2511 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2512 modinfo->EntryPoint = found_module->address_offset;
2516 free_procmodule (found_module);
2519 g_slist_free (mods);
2526 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2528 struct _WapiHandle_process *process_handle;
2531 mono_once (&process_current_once, process_set_current);
2533 if(min==NULL || max==NULL) {
2534 /* Not sure if w32 allows NULLs here or not */
2538 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2539 /* This is a pseudo handle, so just fail for now
2544 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2545 (gpointer *)&process_handle);
2548 g_message ("%s: Can't find process %p", __func__, process);
2554 *min=process_handle->min_working_set;
2555 *max=process_handle->max_working_set;
2560 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2562 struct _WapiHandle_process *process_handle;
2565 mono_once (&process_current_once, process_set_current);
2567 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2568 /* This is a pseudo handle, so just fail for now
2573 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2574 (gpointer *)&process_handle);
2577 g_message ("%s: Can't find process %p", __func__, process);
2583 process_handle->min_working_set=min;
2584 process_handle->max_working_set=max;
2591 TerminateProcess (gpointer process, gint32 exitCode)
2593 struct _WapiHandle_process *process_handle;
2599 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2600 /* This is a pseudo handle */
2601 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2603 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2604 (gpointer *) &process_handle);
2608 g_message ("%s: Can't find process %p", __func__,
2611 SetLastError (ERROR_INVALID_HANDLE);
2614 pid = process_handle->id;
2617 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2618 ret = kill (pid, signo);
2622 SetLastError (ERROR_INVALID_PARAMETER);
2625 SetLastError (ERROR_ACCESS_DENIED);
2628 SetLastError (ERROR_PROC_NOT_FOUND);
2631 SetLastError (ERROR_GEN_FAILURE);
2639 GetPriorityClass (gpointer process)
2641 #ifdef HAVE_GETPRIORITY
2642 struct _WapiHandle_process *process_handle;
2647 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2648 /* This is a pseudo handle */
2649 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2651 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2652 (gpointer *) &process_handle);
2655 SetLastError (ERROR_INVALID_HANDLE);
2658 pid = process_handle->id;
2662 ret = getpriority (PRIO_PROCESS, pid);
2663 if (ret == -1 && errno != 0) {
2667 SetLastError (ERROR_ACCESS_DENIED);
2670 SetLastError (ERROR_PROC_NOT_FOUND);
2673 SetLastError (ERROR_GEN_FAILURE);
2679 return NORMAL_PRIORITY_CLASS;
2681 return REALTIME_PRIORITY_CLASS;
2683 return HIGH_PRIORITY_CLASS;
2685 return ABOVE_NORMAL_PRIORITY_CLASS;
2687 return IDLE_PRIORITY_CLASS;
2689 return BELOW_NORMAL_PRIORITY_CLASS;
2691 return NORMAL_PRIORITY_CLASS;
2693 SetLastError (ERROR_NOT_SUPPORTED);
2699 SetPriorityClass (gpointer process, guint32 priority_class)
2701 #ifdef HAVE_SETPRIORITY
2702 struct _WapiHandle_process *process_handle;
2708 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2709 /* This is a pseudo handle */
2710 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2712 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2713 (gpointer *) &process_handle);
2716 SetLastError (ERROR_INVALID_HANDLE);
2719 pid = process_handle->id;
2722 switch (priority_class) {
2723 case IDLE_PRIORITY_CLASS:
2726 case BELOW_NORMAL_PRIORITY_CLASS:
2729 case NORMAL_PRIORITY_CLASS:
2732 case ABOVE_NORMAL_PRIORITY_CLASS:
2735 case HIGH_PRIORITY_CLASS:
2738 case REALTIME_PRIORITY_CLASS:
2742 SetLastError (ERROR_INVALID_PARAMETER);
2746 ret = setpriority (PRIO_PROCESS, pid, prio);
2751 SetLastError (ERROR_ACCESS_DENIED);
2754 SetLastError (ERROR_PROC_NOT_FOUND);
2757 SetLastError (ERROR_GEN_FAILURE);
2763 SetLastError (ERROR_NOT_SUPPORTED);
2769 mono_processes_cleanup (void)
2771 struct MonoProcess *mp;
2772 struct MonoProcess *prev = NULL;
2773 struct MonoProcess *candidate = NULL;
2774 gpointer unref_handle;
2778 g_warning ("%s", __func__);
2781 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2782 if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
2785 mp = mono_processes;
2786 while (mp != NULL) {
2787 if (mp->pid == 0 && mp->handle != NULL) {
2788 /* This process has exited and we need to remove the artifical ref
2790 mono_mutex_lock (&mono_processes_mutex);
2791 unref_handle = mp->handle;
2793 mono_mutex_unlock (&mono_processes_mutex);
2795 _wapi_handle_unref (unref_handle);
2801 mp = mono_processes;
2803 while (mp != NULL) {
2804 if ((mp->handle_count == 0 && mp->pid == 0) || candidate != NULL) {
2806 _wapi_handle_spin (spin);
2810 /* We've found a candidate */
2811 mono_mutex_lock (&mono_processes_mutex);
2812 if (candidate == NULL) {
2814 if (mp == mono_processes) {
2815 mono_processes = mp->next;
2817 prev->next = mp->next;
2822 /* It's still safe to traverse the structure.*/
2823 mono_memory_barrier ();
2825 if (mono_processes_read_lock != 0) {
2826 /* The sigchld handler is watching us. Spin a bit and try again */
2829 } else if (spin >= 8) {
2830 /* Just give up for now */
2831 mono_mutex_unlock (&mono_processes_mutex);
2835 /* We've modified the list of processes, and we know the sigchld handler
2836 * isn't executing, so even if it executes at any moment, it'll see the
2837 * new version of the list. So now we can free the candidate. */
2839 g_warning ("%s: freeing candidate %p", __func__, candidate);
2841 mp = candidate->next;
2842 MONO_SEM_DESTROY (&candidate->exit_sem);
2847 mono_mutex_unlock (&mono_processes_mutex);
2857 g_warning ("%s done", __func__);
2860 InterlockedDecrement (&mono_processes_cleaning_up);
2864 process_close (gpointer handle, gpointer data)
2866 struct _WapiHandle_process *process_handle;
2869 g_warning ("%s", __func__);
2872 process_handle = (struct _WapiHandle_process *) data;
2873 if (process_handle->mono_process && process_handle->self == _wapi_getpid ())
2874 InterlockedDecrement (&process_handle->mono_process->handle_count);
2875 mono_processes_cleanup ();
2880 mono_sigchld_signal_handler (int _dummy, siginfo_t *info, void *context)
2884 struct MonoProcess *p;
2887 fprintf (stdout, "SIG CHILD handler for pid: %i\n", info->si_pid);
2890 InterlockedIncrement (&mono_processes_read_lock);
2894 pid = waitpid (-1, &status, WNOHANG);
2895 } while (pid == -1 && errno == EINTR);
2901 fprintf (stdout, "child ended: %i", pid);
2905 if (p->pid == pid) {
2906 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2908 MONO_SEM_POST (&p->exit_sem);
2915 InterlockedDecrement (&mono_processes_read_lock);
2918 fprintf (stdout, "SIG CHILD handler: done looping.");
2923 static void process_add_sigchld_handler (void)
2926 struct sigaction sa;
2928 sa.sa_sigaction = mono_sigchld_signal_handler;
2929 sigemptyset (&sa.sa_mask);
2930 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2931 g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2933 g_warning ("Added SIGCHLD handler");
2938 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2940 struct _WapiHandle_process *process_handle;
2946 struct MonoProcess *mp;
2948 gpointer current_thread;
2950 current_thread = _wapi_thread_handle_from_id (pthread_self ());
2951 if (current_thread == NULL) {
2952 SetLastError (ERROR_INVALID_HANDLE);
2956 /* FIXME: We can now easily wait on processes that aren't our own children,
2957 * but WaitFor*Object won't call us for pseudo handles. */
2958 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2961 g_warning ("%s (%p, %u)", __func__, handle, timeout);
2964 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS, (gpointer *)&process_handle);
2966 g_warning ("%s: error looking up process handle %p", __func__, handle);
2970 if (process_handle->exited) {
2971 /* We've already done this one */
2973 g_warning ("%s (%p, %u): Process already exited", __func__, handle, timeout);
2975 return WAIT_OBJECT_0;
2978 pid = process_handle->id;
2981 g_warning ("%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2984 /* We don't need to lock mono_processes here, the entry
2985 * has a handle_count > 0 which means it will not be freed. */
2986 mp = process_handle->mono_process;
2987 if (mp && process_handle->self != _wapi_getpid ()) {
2988 /* mono_process points to memory in another process' address space: we can't use it */
2992 start = mono_msec_ticks ();
2998 /* We have a semaphore we can wait on */
2999 if (timeout != INFINITE) {
3001 g_warning ("%s (%p, %u): waiting on semaphore for %li ms...",
3002 __func__, handle, timeout, (timeout - (now - start)));
3005 ret = MONO_SEM_TIMEDWAIT_ALERTABLE (&mp->exit_sem, (timeout - (now - start)), alertable);
3008 g_warning ("%s (%p, %u): waiting on semaphore forever...",
3009 __func__, handle, timeout);
3011 ret = MONO_SEM_WAIT_ALERTABLE (&mp->exit_sem, alertable);
3014 if (ret == -1 && errno != EINTR && errno != ETIMEDOUT) {
3016 g_warning ("%s (%p, %u): sem_timedwait failure: %s",
3017 __func__, handle, timeout, g_strerror (errno));
3019 /* Should we return a failure here? */
3023 /* Success, process has exited */
3024 MONO_SEM_POST (&mp->exit_sem);
3028 /* We did not create this process, so we can't waidpid / sem_wait it.
3029 * We need to poll for the pid existence */
3031 g_warning ("%s (%p, %u): polling on pid...", __func__, handle, timeout);
3033 if (!is_pid_valid (pid)) {
3034 /* Success, process has exited */
3041 g_warning ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
3043 return WAIT_TIMEOUT;
3046 now = mono_msec_ticks ();
3047 if (now - start >= timeout) {
3049 g_warning ("%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
3051 return WAIT_TIMEOUT;
3055 /* "timeout - (now - start)" will not underflow, since timeout is always >=0,
3056 * and we passed the check just above */
3057 _wapi_handle_spin (MIN (100, timeout - (now - start)));
3060 if (alertable && _wapi_thread_apc_pending (current_thread)) {
3062 g_warning ("%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
3064 return WAIT_IO_COMPLETION;
3068 /* Process must have exited */
3070 g_warning ("%s (%p, %u): Waited successfully", __func__, handle, timeout);
3073 ret = _wapi_handle_lock_shared_handles ();
3074 g_assert (ret == 0);
3076 status = mp ? mp->status : 0;
3077 if (WIFSIGNALED (status)) {
3078 process_handle->exitstatus = 128 + WTERMSIG (status);
3080 process_handle->exitstatus = WEXITSTATUS (status);
3082 _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
3084 process_handle->exited = TRUE;
3087 g_warning ("%s (%p, %u): Setting pid %d signalled, exit status %d",
3088 __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
3091 _wapi_shared_handle_set_signal_state (handle, TRUE);
3093 _wapi_handle_unlock_shared_handles ();
3095 return WAIT_OBJECT_0;