2 * processes.c: Process handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002-2011 Novell, Inc.
8 * Copyright 2011 Xamarin Inc
19 #include <sys/types.h>
27 #ifdef HAVE_SYS_PARAM_H
28 #include <sys/param.h>
32 #ifdef HAVE_SYS_WAIT_H
35 #ifdef HAVE_SYS_RESOURCE_H
36 #include <sys/resource.h>
39 #ifdef HAVE_SYS_MKDEV_H
40 #include <sys/mkdev.h>
47 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
49 #include <TargetConditionals.h>
50 #include <sys/resource.h>
57 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__)
59 #include <sys/sysctl.h>
60 # if !defined(__OpenBSD__)
61 # include <sys/utsname.h>
63 # if defined(__FreeBSD__)
64 # include <sys/user.h> /* struct kinfo_proc */
68 #ifdef PLATFORM_SOLARIS
69 /* procfs.h cannot be included if this define is set, but it seems to work fine if it is undefined */
70 #if _FILE_OFFSET_BITS == 64
71 #undef _FILE_OFFSET_BITS
73 #define _FILE_OFFSET_BITS 64
80 #include <KernelKit.h>
83 #include <mono/io-layer/wapi.h>
84 #include <mono/io-layer/wapi-private.h>
85 #include <mono/io-layer/handles-private.h>
86 #include <mono/io-layer/process-private.h>
87 #include <mono/io-layer/threads.h>
88 #include <mono/utils/strenc.h>
89 #include <mono/utils/mono-path.h>
90 #include <mono/io-layer/timefuncs-private.h>
91 #include <mono/utils/mono-time.h>
92 #include <mono/utils/mono-membar.h>
93 #include <mono/utils/mono-os-mutex.h>
94 #include <mono/utils/mono-signal-handler.h>
95 #include <mono/utils/mono-proclib.h>
96 #include <mono/utils/mono-once.h>
98 /* The process' environment strings */
99 #if defined(__APPLE__)
100 #if defined (TARGET_OSX)
101 /* Apple defines this in crt_externs.h but doesn't provide that header for
102 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
103 * in fact exist on all implementations (so far)
105 gchar ***_NSGetEnviron(void);
106 #define environ (*_NSGetEnviron())
108 static char *mono_environ[1] = { NULL };
109 #define environ mono_environ
110 #endif /* defined (TARGET_OSX) */
112 extern char **environ;
116 #define DEBUG(...) g_message(__VA_ARGS__)
117 #define DEBUG_ENABLED 1
122 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable);
123 static void process_close (gpointer handle, gpointer data);
124 static gboolean is_pid_valid (pid_t pid);
126 #if !(defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__HAIKU__))
128 open_process_map (int pid, const char *mode);
131 struct _WapiHandleOps _wapi_process_ops = {
132 process_close, /* close_shared */
136 process_wait, /* special_wait */
141 static struct sigaction previous_chld_sa;
143 static mono_once_t process_sig_chld_once = MONO_ONCE_INIT;
144 static void process_add_sigchld_handler (void);
146 /* The signal-safe logic to use mono_processes goes like this:
147 * - The list must be safe to traverse for the signal handler at all times.
148 * It's safe to: prepend an entry (which is a single store to 'mono_processes'),
149 * unlink an entry (assuming the unlinked entry isn't freed and doesn't
150 * change its 'next' pointer so that it can still be traversed).
151 * When cleaning up we first unlink an entry, then we verify that
152 * the read lock isn't locked. Then we can free the entry, since
153 * we know that nobody is using the old version of the list (including
154 * the unlinked entry).
155 * We also need to lock when adding and cleaning up so that those two
156 * operations don't mess with eachother. (This lock is not used in the
159 static struct MonoProcess *mono_processes = NULL;
160 static volatile gint32 mono_processes_cleaning_up = 0;
161 static mono_mutex_t mono_processes_mutex;
162 static void mono_processes_cleanup (void);
164 static gpointer current_process;
165 static char *cli_launcher;
167 static WapiHandle_process *
168 lookup_process_handle (gpointer handle)
170 WapiHandle_process *process_data;
173 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
174 (gpointer *)&process_data);
180 /* Check if a pid is valid - i.e. if a process exists with this pid. */
182 is_pid_valid (pid_t pid)
184 gboolean result = FALSE;
186 #if defined(HOST_WATCHOS)
187 result = TRUE; // TODO: Rewrite using sysctl
188 #elif defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__)
189 if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
191 #elif defined(__HAIKU__)
193 if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
196 char *dir = g_strdup_printf ("/proc/%d", pid);
197 if (!access (dir, F_OK))
206 process_set_defaults (WapiHandle_process *process_handle)
208 /* These seem to be the defaults on w2k */
209 process_handle->min_working_set = 204800;
210 process_handle->max_working_set = 1413120;
212 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
216 len16 (const gunichar2 *str)
227 utf16_concat (const gunichar2 *first, ...)
234 va_start (args, first);
235 total += len16 (first);
236 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
241 ret = g_new (gunichar2, total + 1);
247 for (s = first; *s != 0; s++)
249 va_start (args, first);
250 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
253 for (p = s; *p != 0; p++)
261 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
262 static const gunichar2 *utf16_space = utf16_space_bytes;
263 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
264 static const gunichar2 *utf16_quote = utf16_quote_bytes;
269 print_utf16 (gunichar2 *str)
273 res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
274 g_print ("%s\n", res);
279 /* Implemented as just a wrapper around CreateProcess () */
281 ShellExecuteEx (WapiShellExecuteInfo *sei)
284 WapiProcessInformation process_info;
288 /* w2k just segfaults here, but we can do better than
291 SetLastError (ERROR_INVALID_PARAMETER);
295 if (sei->lpFile == NULL)
296 /* w2k returns TRUE for this, for some reason. */
299 /* Put both executable and parameters into the second argument
300 * to CreateProcess (), so it searches $PATH. The conversion
301 * into and back out of utf8 is because there is no
302 * g_strdup_printf () equivalent for gunichar2 :-(
304 args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
306 SetLastError (ERROR_INVALID_DATA);
309 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
310 CREATE_UNICODE_ENVIRONMENT, NULL,
311 sei->lpDirectory, NULL, &process_info);
314 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
318 static char *handler;
319 static gunichar2 *handler_utf16;
321 if (handler_utf16 == (gunichar2 *)-1)
324 #ifdef PLATFORM_MACOSX
325 handler = g_strdup ("/usr/bin/open");
328 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
329 * if that fails, try to use gnome-open, then kfmclient
331 handler = g_find_program_in_path ("xdg-open");
332 if (handler == NULL){
333 handler = g_find_program_in_path ("gnome-open");
334 if (handler == NULL){
335 handler = g_find_program_in_path ("kfmclient");
336 if (handler == NULL){
337 handler_utf16 = (gunichar2 *) -1;
340 /* kfmclient needs exec argument */
342 handler = g_strconcat (old, " exec",
349 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
352 /* Put quotes around the filename, in case it's a url
353 * that contains #'s (CreateProcess() calls
354 * g_shell_parse_argv(), which deliberately throws
355 * away anything after an unquoted #). Fixes bug
358 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
359 sei->lpFile, utf16_quote,
360 sei->lpParameters == NULL ? NULL : utf16_space,
361 sei->lpParameters, NULL);
363 SetLastError (ERROR_INVALID_DATA);
366 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
367 CREATE_UNICODE_ENVIRONMENT, NULL,
368 sei->lpDirectory, NULL, &process_info);
371 if (GetLastError () != ERROR_OUTOFMEMORY)
372 SetLastError (ERROR_INVALID_DATA);
375 /* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
376 CloseHandle (process_info.hProcess);
377 process_info.hProcess = NULL;
380 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS)
381 sei->hProcess = process_info.hProcess;
383 CloseHandle (process_info.hProcess);
389 is_managed_binary (const char *filename)
391 int original_errno = errno;
392 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
393 int file = open (filename, O_RDONLY | O_LARGEFILE);
395 int file = open (filename, O_RDONLY);
398 unsigned char buffer[8];
399 off_t file_size, optional_header_offset;
400 off_t pe_header_offset;
401 gboolean managed = FALSE;
403 guint32 first_word, second_word;
405 /* If we are unable to open the file, then we definitely
406 * can't say that it is managed. The child mono process
407 * probably wouldn't be able to open it anyway.
410 errno = original_errno;
414 /* Retrieve the length of the file for future sanity checks. */
415 file_size = lseek (file, 0, SEEK_END);
416 lseek (file, 0, SEEK_SET);
418 /* We know we need to read a header field at offset 60. */
422 num_read = read (file, buffer, 2);
424 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
427 new_offset = lseek (file, 60, SEEK_SET);
429 if (new_offset != 60)
432 num_read = read (file, buffer, 4);
436 pe_header_offset = buffer[0]
441 if (pe_header_offset + 24 > file_size)
444 new_offset = lseek (file, pe_header_offset, SEEK_SET);
446 if (new_offset != pe_header_offset)
449 num_read = read (file, buffer, 4);
451 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
455 * Verify that the header we want in the optional header data
456 * is present in this binary.
458 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
460 if (new_offset != pe_header_offset + 20)
463 num_read = read (file, buffer, 2);
465 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
468 /* Read the CLR header address and size fields. These will be
469 * zero if the binary is not managed.
471 optional_header_offset = pe_header_offset + 24;
472 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
474 if (new_offset != optional_header_offset + 208)
477 num_read = read (file, buffer, 8);
479 /* We are not concerned with endianness, only with
480 * whether it is zero or not.
482 first_word = *(guint32 *)&buffer[0];
483 second_word = *(guint32 *)&buffer[4];
485 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
492 errno = original_errno;
497 CreateProcessWithLogonW (const gunichar2 *username,
498 const gunichar2 *domain,
499 const gunichar2 *password,
500 const guint32 logonFlags,
501 const gunichar2 *appname,
502 const gunichar2 *cmdline,
503 guint32 create_flags,
505 const gunichar2 *cwd,
506 WapiStartupInfo *startup,
507 WapiProcessInformation *process_info)
509 /* FIXME: use user information */
510 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
514 is_readable_or_executable (const char *prog)
517 int a = access (prog, R_OK);
518 int b = access (prog, X_OK);
519 if (a != 0 && b != 0)
521 if (stat (prog, &buf))
523 if (S_ISREG (buf.st_mode))
529 is_executable (const char *prog)
532 if (access (prog, X_OK) != 0)
534 if (stat (prog, &buf))
536 if (S_ISREG (buf.st_mode))
542 switch_dir_separators (char *path)
544 size_t i, pathLength = strlen(path);
546 /* Turn all the slashes round the right way, except for \' */
547 /* There are probably other characters that need to be excluded as well. */
548 for (i = 0; i < pathLength; i++) {
549 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' )
554 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
555 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
556 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
557 gboolean inherit_handles, guint32 create_flags,
558 gpointer new_environ, const gunichar2 *cwd,
559 WapiStartupInfo *startup,
560 WapiProcessInformation *process_info)
562 #if defined (HAVE_FORK) && defined (HAVE_EXECVE)
563 char *cmd = NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL;
564 char *dir = NULL, **env_strings = NULL, **argv = NULL;
565 guint32 i, env_count = 0;
566 gboolean ret = FALSE;
568 WapiHandle_process process_handle = {0}, *process_handle_data;
570 int in_fd, out_fd, err_fd;
573 int startup_pipe [2] = {-1, -1};
575 struct MonoProcess *mono_process;
576 gboolean fork_failed = FALSE;
578 mono_once (&process_sig_chld_once, process_add_sigchld_handler);
580 /* appname and cmdline specify the executable and its args:
582 * If appname is not NULL, it is the name of the executable.
583 * Otherwise the executable is the first token in cmdline.
585 * Executable searching:
587 * If appname is not NULL, it can specify the full path and
588 * file name, or else a partial name and the current directory
589 * will be used. There is no additional searching.
591 * If appname is NULL, the first whitespace-delimited token in
592 * cmdline is used. If the name does not contain a full
593 * directory path, the search sequence is:
595 * 1) The directory containing the current process
596 * 2) The current working directory
597 * 3) The windows system directory (Ignored)
598 * 4) The windows directory (Ignored)
601 * Just to make things more interesting, tokens can contain
602 * white space if they are surrounded by quotation marks. I'm
603 * beginning to understand just why windows apps are generally
604 * so crap, with an API like this :-(
606 if (appname != NULL) {
607 cmd = mono_unicode_to_external (appname);
609 DEBUG ("%s: unicode conversion returned NULL",
612 SetLastError (ERROR_PATH_NOT_FOUND);
616 switch_dir_separators(cmd);
619 if (cmdline != NULL) {
620 args = mono_unicode_to_external (cmdline);
622 DEBUG ("%s: unicode conversion returned NULL", __func__);
624 SetLastError (ERROR_PATH_NOT_FOUND);
630 dir = mono_unicode_to_external (cwd);
632 DEBUG ("%s: unicode conversion returned NULL", __func__);
634 SetLastError (ERROR_PATH_NOT_FOUND);
638 /* Turn all the slashes round the right way */
639 switch_dir_separators(dir);
643 /* We can't put off locating the executable any longer :-( */
646 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
647 /* Strip off the drive letter. I can't
648 * believe that CP/M holdover is still
651 g_memmove (cmd, cmd+2, strlen (cmd)-2);
652 cmd[strlen (cmd)-2] = '\0';
655 unquoted = g_shell_unquote (cmd, NULL);
656 if (unquoted[0] == '/') {
657 /* Assume full path given */
658 prog = g_strdup (unquoted);
660 /* Executable existing ? */
661 if (!is_readable_or_executable (prog)) {
662 DEBUG ("%s: Couldn't find executable %s",
665 SetLastError (ERROR_FILE_NOT_FOUND);
669 /* Search for file named by cmd in the current
672 char *curdir = g_get_current_dir ();
674 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
677 /* And make sure it's readable */
678 if (!is_readable_or_executable (prog)) {
679 DEBUG ("%s: Couldn't find executable %s",
682 SetLastError (ERROR_FILE_NOT_FOUND);
688 args_after_prog = args;
693 /* Dig out the first token from args, taking quotation
697 /* First, strip off all leading whitespace */
698 args = g_strchug (args);
700 /* args_after_prog points to the contents of args
701 * after token has been set (otherwise argv[0] is
704 args_after_prog = args;
706 /* Assume the opening quote will always be the first
709 if (args[0] == '\"' || args [0] == '\'') {
711 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
712 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
713 /* We found the first token */
714 token = g_strndup (args+1, i-1);
715 args_after_prog = g_strchug (args + i + 1);
717 /* Quotation mark appeared in the
718 * middle of the token. Just give the
719 * whole first token, quotes and all,
726 /* No quote mark, or malformed */
727 for (i = 0; args[i] != '\0'; i++) {
728 if (g_ascii_isspace (args[i])) {
729 token = g_strndup (args, i);
730 args_after_prog = args + i + 1;
736 if (token == NULL && args[0] != '\0') {
737 /* Must be just one token in the string */
738 token = g_strdup (args);
739 args_after_prog = NULL;
744 DEBUG ("%s: Couldn't find what to exec", __func__);
746 SetLastError (ERROR_PATH_NOT_FOUND);
750 /* Turn all the slashes round the right way. Only for
753 switch_dir_separators(token);
755 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
756 /* Strip off the drive letter. I can't
757 * believe that CP/M holdover is still
760 g_memmove (token, token+2, strlen (token)-2);
761 token[strlen (token)-2] = '\0';
764 if (token[0] == '/') {
765 /* Assume full path given */
766 prog = g_strdup (token);
768 /* Executable existing ? */
769 if (!is_readable_or_executable (prog)) {
770 DEBUG ("%s: Couldn't find executable %s",
773 SetLastError (ERROR_FILE_NOT_FOUND);
777 char *curdir = g_get_current_dir ();
779 /* FIXME: Need to record the directory
780 * containing the current process, and check
781 * that for the new executable as the first
785 prog = g_strdup_printf ("%s/%s", curdir, token);
788 /* I assume X_OK is the criterion to use,
791 * X_OK is too strict *if* the target is a CLR binary
793 if (!is_readable_or_executable (prog)) {
795 prog = g_find_program_in_path (token);
797 DEBUG ("%s: Couldn't find executable %s", __func__, token);
800 SetLastError (ERROR_FILE_NOT_FOUND);
809 DEBUG ("%s: Exec prog [%s] args [%s]", __func__, prog,
812 /* Check for CLR binaries; if found, we will try to invoke
813 * them using the same mono binary that started us.
815 if (is_managed_binary (prog)) {
816 gunichar2 *newapp = NULL, *newcmd;
820 newapp = mono_unicode_from_external (cli_launcher, &bytes_ignored);
822 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
824 if (newapp != NULL) {
825 if (appname != NULL) {
826 newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space,
827 appname, utf16_space,
830 newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space,
834 g_free ((gunichar2 *)newapp);
836 if (newcmd != NULL) {
837 ret = CreateProcess (NULL, newcmd,
841 create_flags, new_environ,
845 g_free ((gunichar2 *)newcmd);
851 if (!is_executable (prog)) {
852 DEBUG ("%s: Executable permisson not set on %s", __func__, prog);
853 SetLastError (ERROR_ACCESS_DENIED);
858 if (args_after_prog != NULL && *args_after_prog) {
861 qprog = g_shell_quote (prog);
862 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
865 full_prog = g_shell_quote (prog);
868 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
870 g_message ("CreateProcess: %s\n", gerr->message);
876 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
877 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
878 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
879 err_fd = GPOINTER_TO_UINT (startup->hStdError);
881 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
882 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
883 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
886 process_handle.proc_name = g_strdup (prog);
888 process_set_defaults (&process_handle);
890 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
891 if (handle == _WAPI_HANDLE_INVALID) {
892 g_warning ("%s: error creating process handle", __func__);
895 SetLastError (ERROR_OUTOFMEMORY);
899 /* new_environ is a block of NULL-terminated strings, which
900 * is itself NULL-terminated. Of course, passing an array of
901 * string pointers would have made things too easy :-(
903 * If new_environ is not NULL it specifies the entire set of
904 * environment variables in the new process. Otherwise the
905 * new process inherits the same environment.
908 gunichar2 *new_environp;
910 /* Count the number of strings */
911 for (new_environp = (gunichar2 *)new_environ; *new_environp;
914 while (*new_environp) {
919 /* +2: one for the process handle value, and the last
922 env_strings = g_new0 (char *, env_count + 2);
924 /* Copy each environ string into 'strings' turning it
925 * into utf8 (or the requested encoding) at the same
929 for (new_environp = (gunichar2 *)new_environ; *new_environp;
931 env_strings[env_count] = mono_unicode_to_external (new_environp);
933 while (*new_environp) {
938 for (i = 0; environ[i] != NULL; i++)
941 /* +2: one for the process handle value, and the last
944 env_strings = g_new0 (char *, env_count + 2);
946 /* Copy each environ string into 'strings' turning it
947 * into utf8 (or the requested encoding) at the same
951 for (i = 0; environ[i] != NULL; i++) {
952 env_strings[env_count] = g_strdup (environ[i]);
957 /* Create a pipe to make sure the child doesn't exit before
958 * we can add the process to the linked list of mono_processes */
959 if (pipe (startup_pipe) == -1) {
960 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
961 * This is just for a very hard to hit race condition in the first place */
962 startup_pipe [0] = startup_pipe [1] = -1;
963 DEBUG ("%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
966 thr_ret = _wapi_handle_lock_shared_handles ();
967 g_assert (thr_ret == 0);
972 SetLastError (ERROR_OUTOFMEMORY);
976 } else if (pid == 0) {
979 if (startup_pipe [0] != -1) {
980 /* Wait until the parent has updated it's internal data */
981 ssize_t _i G_GNUC_UNUSED = read (startup_pipe [0], &dummy, 1);
982 DEBUG ("%s: child: parent has completed its setup", __func__);
983 close (startup_pipe [0]);
984 close (startup_pipe [1]);
987 /* should we detach from the process group? */
989 /* Connect stdin, stdout and stderr */
994 if (inherit_handles != TRUE) {
995 /* FIXME: do something here */
998 /* Close all file descriptors */
999 for (i = wapi_getdtablesize () - 1; i > 2; i--)
1002 #ifdef DEBUG_ENABLED
1003 DEBUG ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1004 dir == NULL?".":dir);
1005 for (i = 0; argv[i] != NULL; i++)
1006 g_message ("arg %d: [%s]", i, argv[i]);
1008 for (i = 0; env_strings[i] != NULL; i++)
1009 g_message ("env %d: [%s]", i, env_strings[i]);
1013 if (dir != NULL && chdir (dir) == -1) {
1019 execve (argv[0], argv, env_strings);
1026 process_handle_data = lookup_process_handle (handle);
1027 if (!process_handle_data) {
1028 g_warning ("%s: error looking up process handle %p", __func__,
1030 _wapi_handle_unref (handle);
1034 process_handle_data->id = pid;
1036 /* Add our mono_process into the linked list of mono_processes */
1037 mono_process = (struct MonoProcess *) g_malloc0 (sizeof (struct MonoProcess));
1038 mono_process->pid = pid;
1039 mono_process->handle_count = 1;
1040 if (mono_os_sem_init (&mono_process->exit_sem, 0) != 0) {
1041 /* If we can't create the exit semaphore, we just don't add anything
1042 * to our list of mono processes. Waiting on the process will return
1044 g_warning ("%s: could not create exit semaphore for process.", strerror (errno));
1045 g_free (mono_process);
1047 /* Keep the process handle artificially alive until the process
1048 * exits so that the information in the handle isn't lost. */
1049 _wapi_handle_ref (handle);
1050 mono_process->handle = handle;
1052 process_handle_data->mono_process = mono_process;
1054 mono_os_mutex_lock (&mono_processes_mutex);
1055 mono_process->next = mono_processes;
1056 mono_processes = mono_process;
1057 mono_os_mutex_unlock (&mono_processes_mutex);
1060 if (process_info != NULL) {
1061 process_info->hProcess = handle;
1062 process_info->dwProcessId = pid;
1064 /* FIXME: we might need to handle the thread info some
1067 process_info->hThread = INVALID_HANDLE_VALUE;
1068 process_info->dwThreadId = 0;
1072 _wapi_handle_unlock_shared_handles ();
1075 _wapi_handle_unref (handle);
1077 if (startup_pipe [1] != -1) {
1078 /* Write 1 byte, doesn't matter what */
1079 ssize_t _i G_GNUC_UNUSED = write (startup_pipe [1], startup_pipe, 1);
1080 close (startup_pipe [0]);
1081 close (startup_pipe [1]);
1096 g_strfreev (env_strings);
1100 DEBUG ("%s: returning handle %p for pid %d", __func__, handle,
1103 /* Check if something needs to be cleaned up. */
1104 mono_processes_cleanup ();
1108 SetLastError (ERROR_NOT_SUPPORTED);
1110 #endif // defined (HAVE_FORK) && defined (HAVE_EXECVE)
1114 process_set_name (WapiHandle_process *process_handle)
1116 char *progname, *utf8_progname, *slash;
1118 progname = g_get_prgname ();
1119 utf8_progname = mono_utf8_from_external (progname);
1121 DEBUG ("%s: using [%s] as prog name", __func__, progname);
1123 if (utf8_progname) {
1124 slash = strrchr (utf8_progname, '/');
1126 process_handle->proc_name = g_strdup (slash+1);
1128 process_handle->proc_name = g_strdup (utf8_progname);
1129 g_free (utf8_progname);
1134 wapi_processes_init (void)
1136 pid_t pid = _wapi_getpid ();
1137 WapiHandle_process process_handle = {0};
1139 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
1140 (WapiHandleCapability)(WAPI_HANDLE_CAP_WAIT | WAPI_HANDLE_CAP_SPECIAL_WAIT));
1142 process_handle.id = pid;
1144 process_set_defaults (&process_handle);
1145 process_set_name (&process_handle);
1147 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1149 g_assert (current_process);
1151 mono_os_mutex_init (&mono_processes_mutex);
1155 _wapi_process_duplicate (void)
1157 _wapi_handle_ref (current_process);
1159 return current_process;
1162 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1164 GetCurrentProcess (void)
1166 return _WAPI_PROCESS_CURRENT;
1170 GetProcessId (gpointer handle)
1172 WapiHandle_process *process_handle;
1174 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1175 /* This is a pseudo handle */
1176 return WAPI_HANDLE_TO_PID (handle);
1178 process_handle = lookup_process_handle (handle);
1179 if (!process_handle) {
1180 SetLastError (ERROR_INVALID_HANDLE);
1184 return process_handle->id;
1188 process_open_compare (gpointer handle, gpointer user_data)
1191 WapiHandle_process *process_handle;
1194 g_assert (!WAPI_IS_PSEUDO_PROCESS_HANDLE (handle));
1196 process_handle = lookup_process_handle (handle);
1197 g_assert (process_handle);
1199 DEBUG ("%s: looking at process %d", __func__, process_handle->id);
1201 checking_pid = process_handle->id;
1203 if (checking_pid == 0)
1206 wanted_pid = GPOINTER_TO_UINT (user_data);
1208 /* It's possible to have more than one process handle with the
1209 * same pid, but only the one running process can be
1212 if (checking_pid == wanted_pid &&
1213 !_wapi_handle_issignalled (handle)) {
1214 /* If the handle is blown away in the window between
1215 * returning TRUE here and _wapi_search_handle pinging
1216 * the timestamp, the search will continue
1225 CloseProcess (gpointer handle)
1227 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1229 return CloseHandle (handle);
1233 * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1236 OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1238 /* Find the process handle that corresponds to pid */
1239 gpointer handle = NULL;
1241 DEBUG ("%s: looking for process %d", __func__, pid);
1243 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1244 process_open_compare,
1245 GUINT_TO_POINTER (pid), NULL, TRUE);
1247 if (is_pid_valid (pid)) {
1248 /* Return a pseudo handle for processes we
1249 * don't have handles for
1251 return WAPI_PID_TO_HANDLE (pid);
1253 DEBUG ("%s: Can't find pid %d", __func__, pid);
1255 SetLastError (ERROR_PROC_NOT_FOUND);
1261 /* _wapi_search_handle () already added a ref */
1266 GetExitCodeProcess (gpointer process, guint32 *code)
1268 WapiHandle_process *process_handle;
1274 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1275 pid = WAPI_HANDLE_TO_PID (process);
1276 /* This is a pseudo handle, so we don't know what the
1277 * exit code was, but we can check whether it's alive or not
1279 if (is_pid_valid (pid)) {
1280 *code = STILL_ACTIVE;
1287 process_handle = lookup_process_handle (process);
1288 if (!process_handle) {
1289 DEBUG ("%s: Can't find process %p", __func__, process);
1294 if (process_handle->id == _wapi_getpid ()) {
1295 *code = STILL_ACTIVE;
1299 /* A process handle is only signalled if the process has exited
1300 * and has been waited for */
1302 /* Make sure any process exit has been noticed, before
1303 * checking if the process is signalled. Fixes bug 325463.
1305 process_wait (process, 0, TRUE);
1307 if (_wapi_handle_issignalled (process))
1308 *code = process_handle->exitstatus;
1310 *code = STILL_ACTIVE;
1316 GetProcessTimes (gpointer process, WapiFileTime *create_time,
1317 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1318 WapiFileTime *user_time)
1320 WapiHandle_process *process_handle;
1321 gboolean ku_times_set = FALSE;
1323 if (create_time == NULL || exit_time == NULL || kernel_time == NULL ||
1325 /* Not sure if w32 allows NULLs here or not */
1328 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1329 gpointer pid = GINT_TO_POINTER (WAPI_HANDLE_TO_PID(process));
1330 gint64 start_ticks, user_ticks, kernel_ticks;
1332 mono_process_get_times (pid, &start_ticks, &user_ticks, &kernel_ticks);
1334 _wapi_guint64_to_filetime (start_ticks, create_time);
1335 _wapi_guint64_to_filetime (user_ticks, kernel_time);
1336 _wapi_guint64_to_filetime (kernel_ticks, user_time);
1341 process_handle = lookup_process_handle (process);
1342 if (!process_handle) {
1343 DEBUG ("%s: Can't find process %p", __func__, process);
1348 *create_time = process_handle->create_time;
1350 /* A process handle is only signalled if the process has
1351 * exited. Otherwise exit_time isn't set
1353 if (_wapi_handle_issignalled (process))
1354 *exit_time = process_handle->exit_time;
1356 #ifdef HAVE_GETRUSAGE
1357 if (process_handle->id == getpid ()) {
1358 struct rusage time_data;
1359 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1361 ku_times_set = TRUE;
1362 tick_val = (guint64)time_data.ru_utime.tv_sec * 10000000 + (guint64)time_data.ru_utime.tv_usec * 10;
1363 _wapi_guint64_to_filetime (tick_val, user_time);
1364 tick_val = (guint64)time_data.ru_stime.tv_sec * 10000000 + (guint64)time_data.ru_stime.tv_usec * 10;
1365 _wapi_guint64_to_filetime (tick_val, kernel_time);
1369 if (!ku_times_set) {
1370 memset (kernel_time, 0, sizeof (WapiFileTime));
1371 memset (user_time, 0, sizeof (WapiFileTime));
1379 gpointer address_start;
1380 gpointer address_end;
1382 gpointer address_offset;
1388 static void free_procmodule (WapiProcModule *mod)
1390 if (mod->perms != NULL) {
1391 g_free (mod->perms);
1393 if (mod->filename != NULL) {
1394 g_free (mod->filename);
1399 static gint find_procmodule (gconstpointer a, gconstpointer b)
1401 WapiProcModule *want = (WapiProcModule *)a;
1402 WapiProcModule *compare = (WapiProcModule *)b;
1404 if ((want->device == compare->device) &&
1405 (want->inode == compare->inode)) {
1412 #ifdef PLATFORM_MACOSX
1413 #include <mach-o/dyld.h>
1414 #include <mach-o/getsect.h>
1416 static GSList *load_modules (void)
1419 WapiProcModule *mod;
1420 uint32_t count = _dyld_image_count ();
1423 for (i = 0; i < count; i++) {
1424 #if SIZEOF_VOID_P == 8
1425 const struct mach_header_64 *hdr;
1426 const struct section_64 *sec;
1428 const struct mach_header *hdr;
1429 const struct section *sec;
1433 name = _dyld_get_image_name (i);
1434 #if SIZEOF_VOID_P == 8
1435 hdr = (const struct mach_header_64*)_dyld_get_image_header (i);
1436 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1438 hdr = _dyld_get_image_header (i);
1439 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1442 /* Some dynlibs do not have data sections on osx (#533893) */
1447 mod = g_new0 (WapiProcModule, 1);
1448 mod->address_start = GINT_TO_POINTER (sec->addr);
1449 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1450 mod->perms = g_strdup ("r--p");
1451 mod->address_offset = 0;
1452 mod->device = makedev (0, 0);
1454 mod->filename = g_strdup (name);
1456 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1457 ret = g_slist_prepend (ret, mod);
1459 free_procmodule (mod);
1463 ret = g_slist_reverse (ret);
1467 #elif defined(__OpenBSD__) || defined(__FreeBSD__)
1469 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1471 if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1472 + sizeof (info->dlpi_phnum))
1475 struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1479 memcpy(cpy, info, sizeof(*info));
1481 g_ptr_array_add ((GPtrArray *)ptr, cpy);
1486 static GSList *load_modules (void)
1489 WapiProcModule *mod;
1490 GPtrArray *dlarray = g_ptr_array_new();
1493 if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1496 for (i = 0; i < dlarray->len; i++) {
1497 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1499 mod = g_new0 (WapiProcModule, 1);
1500 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1501 mod->address_end = (gpointer)(info->dlpi_addr +
1502 info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1503 mod->perms = g_strdup ("r--p");
1504 mod->address_offset = 0;
1506 mod->filename = g_strdup (info->dlpi_name);
1508 DEBUG ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1509 mod->inode, mod->filename, mod->address_start, mod->address_end);
1513 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1514 ret = g_slist_prepend (ret, mod);
1516 free_procmodule (mod);
1520 g_ptr_array_free (dlarray, TRUE);
1522 ret = g_slist_reverse (ret);
1526 #elif defined(__HAIKU__)
1528 static GSList *load_modules (void)
1531 WapiProcModule *mod;
1533 image_info imageInfo;
1535 while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
1536 mod = g_new0 (WapiProcModule, 1);
1537 mod->device = imageInfo.device;
1538 mod->inode = imageInfo.node;
1539 mod->filename = g_strdup (imageInfo.name);
1540 mod->address_start = MIN (imageInfo.text, imageInfo.data);
1541 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
1542 (uint8_t*)imageInfo.data + imageInfo.data_size);
1543 mod->perms = g_strdup ("r--p");
1544 mod->address_offset = 0;
1546 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1547 ret = g_slist_prepend (ret, mod);
1549 free_procmodule (mod);
1553 ret = g_slist_reverse (ret);
1558 static GSList *load_modules (FILE *fp)
1561 WapiProcModule *mod;
1562 char buf[MAXPATHLEN + 1], *p, *endp;
1563 char *start_start, *end_start, *prot_start, *offset_start;
1564 char *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1565 gpointer address_start, address_end, address_offset;
1566 guint32 maj_dev, min_dev;
1570 while (fgets (buf, sizeof(buf), fp)) {
1572 while (g_ascii_isspace (*p)) ++p;
1574 if (!g_ascii_isxdigit (*start_start)) {
1577 address_start = (gpointer)strtoul (start_start, &endp, 16);
1585 if (!g_ascii_isxdigit (*end_start)) {
1588 address_end = (gpointer)strtoul (end_start, &endp, 16);
1590 if (!g_ascii_isspace (*p)) {
1594 while (g_ascii_isspace (*p)) ++p;
1596 if (*prot_start != 'r' && *prot_start != '-') {
1599 memcpy (prot_buf, prot_start, 4);
1601 while (!g_ascii_isspace (*p)) ++p;
1603 while (g_ascii_isspace (*p)) ++p;
1605 if (!g_ascii_isxdigit (*offset_start)) {
1608 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1610 if (!g_ascii_isspace (*p)) {
1614 while(g_ascii_isspace (*p)) ++p;
1616 if (!g_ascii_isxdigit (*maj_dev_start)) {
1619 maj_dev = strtoul (maj_dev_start, &endp, 16);
1627 if (!g_ascii_isxdigit (*min_dev_start)) {
1630 min_dev = strtoul (min_dev_start, &endp, 16);
1632 if (!g_ascii_isspace (*p)) {
1636 while (g_ascii_isspace (*p)) ++p;
1638 if (!g_ascii_isxdigit (*inode_start)) {
1641 inode = (guint64)strtol (inode_start, &endp, 10);
1643 if (!g_ascii_isspace (*p)) {
1647 device = makedev ((int)maj_dev, (int)min_dev);
1648 if ((device == 0) &&
1653 while(g_ascii_isspace (*p)) ++p;
1654 /* p now points to the filename */
1656 mod = g_new0 (WapiProcModule, 1);
1657 mod->address_start = address_start;
1658 mod->address_end = address_end;
1659 mod->perms = g_strdup (prot_buf);
1660 mod->address_offset = address_offset;
1661 mod->device = device;
1663 mod->filename = g_strdup (g_strstrip (p));
1665 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1666 ret = g_slist_prepend (ret, mod);
1668 free_procmodule (mod);
1672 ret = g_slist_reverse (ret);
1678 static gboolean match_procname_to_modulename (char *procname, char *modulename)
1680 char* lastsep = NULL;
1681 char* lastsep2 = NULL;
1684 gboolean result = FALSE;
1686 if (procname == NULL || modulename == NULL)
1689 DEBUG ("%s: procname=\"%s\", modulename=\"%s\"", __func__, procname, modulename);
1690 pname = mono_path_resolve_symlinks (procname);
1691 mname = mono_path_resolve_symlinks (modulename);
1693 if (!strcmp (pname, mname))
1697 lastsep = strrchr (mname, '/');
1699 if (!strcmp (lastsep+1, pname))
1702 lastsep2 = strrchr (pname, '/');
1705 if (!strcmp (lastsep+1, lastsep2+1))
1708 if (!strcmp (mname, lastsep2+1))
1718 DEBUG ("%s: result is %d", __func__, result);
1722 #if !(defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__HAIKU__))
1724 open_process_map (int pid, const char *mode)
1727 const char *proc_path[] = {
1728 "/proc/%d/maps", /* GNU/Linux */
1729 "/proc/%d/map", /* FreeBSD */
1735 for (i = 0; fp == NULL && proc_path [i]; i++) {
1736 filename = g_strdup_printf (proc_path[i], pid);
1737 fp = fopen (filename, mode);
1745 static char *get_process_name_from_proc (pid_t pid);
1747 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1748 guint32 size, guint32 *needed)
1750 WapiHandle_process *process_handle;
1751 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX) && !defined(__FreeBSD__)
1754 GSList *mods = NULL;
1755 WapiProcModule *module;
1756 guint32 count, avail = size / sizeof(gpointer);
1759 char *proc_name = NULL;
1761 /* Store modules in an array of pointers (main module as
1762 * modules[0]), using the load address for each module as a
1763 * token. (Use 'NULL' as an alternative for the main module
1764 * so that the simple implementation can just return one item
1765 * for now.) Get the info from /proc/<pid>/maps on linux,
1766 * /proc/<pid>/map on FreeBSD, other systems will have to
1767 * implement /dev/kmem reading or whatever other horrid
1768 * technique is needed.
1770 if (size < sizeof(gpointer))
1773 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1774 pid = WAPI_HANDLE_TO_PID (process);
1775 proc_name = get_process_name_from_proc (pid);
1777 process_handle = lookup_process_handle (process);
1778 if (!process_handle) {
1779 DEBUG ("%s: Can't find process %p", __func__, process);
1783 pid = process_handle->id;
1784 proc_name = g_strdup (process_handle->proc_name);
1787 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__HAIKU__)
1788 mods = load_modules ();
1791 *needed = sizeof(gpointer);
1795 fp = open_process_map (pid, "r");
1797 /* No /proc/<pid>/maps so just return the main module
1801 *needed = sizeof(gpointer);
1805 mods = load_modules (fp);
1808 count = g_slist_length (mods);
1810 /* count + 1 to leave slot 0 for the main module */
1811 *needed = sizeof(gpointer) * (count + 1);
1814 * Use the NULL shortcut, as the first line in
1815 * /proc/<pid>/maps isn't the executable, and we need
1816 * that first in the returned list. Check the module name
1817 * to see if it ends with the proc name and substitute
1818 * the first entry with it. FIXME if this turns out to
1822 for (i = 0; i < (avail - 1) && i < count; i++) {
1823 module = (WapiProcModule *)g_slist_nth_data (mods, i);
1824 if (modules[0] != NULL)
1825 modules[i] = module->address_start;
1826 else if (match_procname_to_modulename (proc_name, module->filename))
1827 modules[0] = module->address_start;
1829 modules[i + 1] = module->address_start;
1832 for (i = 0; i < count; i++) {
1833 free_procmodule ((WapiProcModule *)g_slist_nth_data (mods, i));
1835 g_slist_free (mods);
1842 get_process_name_from_proc (pid_t pid)
1844 #if defined(__OpenBSD__) || defined(__FreeBSD__)
1847 struct kinfo_proc *pi;
1848 #elif defined(PLATFORM_MACOSX)
1849 #if !(!defined (__mono_ppc__) && defined (TARGET_OSX))
1851 struct kinfo_proc *pi;
1852 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
1856 char *filename = NULL;
1861 #if defined(PLATFORM_SOLARIS)
1862 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
1863 if ((fp = fopen (filename, "r")) != NULL) {
1867 nread = fread (&info, sizeof (info), 1, fp);
1869 ret = g_strdup (info.pr_fname);
1875 #elif defined(PLATFORM_MACOSX)
1876 #if !defined (__mono_ppc__) && defined (TARGET_OSX)
1877 /* No proc name on OSX < 10.5 nor ppc nor iOS */
1878 memset (buf, '\0', sizeof(buf));
1879 proc_name (pid, buf, sizeof(buf));
1881 // Fixes proc_name triming values to 15 characters #32539
1882 if (strlen (buf) >= MAXCOMLEN - 1) {
1883 char path_buf [PROC_PIDPATHINFO_MAXSIZE];
1887 memset (path_buf, '\0', sizeof(path_buf));
1888 path_len = proc_pidpath (pid, path_buf, sizeof(path_buf));
1890 if (path_len > 0 && path_len < sizeof(path_buf)) {
1891 name_buf = path_buf + path_len;
1892 for(;name_buf > path_buf; name_buf--) {
1893 if (name_buf [0] == '/') {
1899 if (memcmp (buf, name_buf, MAXCOMLEN - 1) == 0)
1900 ret = g_strdup (name_buf);
1904 if (ret == NULL && strlen (buf) > 0)
1905 ret = g_strdup (buf);
1907 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0)
1910 if ((pi = malloc(size)) == NULL)
1913 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
1914 if (errno == ENOMEM) {
1916 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__);
1921 if (strlen (pi->kp_proc.p_comm) > 0)
1922 ret = g_strdup (pi->kp_proc.p_comm);
1926 #elif defined(__FreeBSD__)
1928 mib [1] = KERN_PROC;
1929 mib [2] = KERN_PROC_PID;
1931 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0) {
1932 DEBUG ("%s: sysctl() failed: %d", __func__, errno);
1936 if ((pi = malloc(size)) == NULL)
1939 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
1940 if (errno == ENOMEM) {
1942 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__);
1947 if (strlen (pi->ki_comm) > 0)
1948 ret = g_strdup (pi->ki_comm);
1950 #elif defined(__OpenBSD__)
1952 mib [1] = KERN_PROC;
1953 mib [2] = KERN_PROC_PID;
1955 mib [4] = sizeof(struct kinfo_proc);
1959 if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0) {
1960 DEBUG ("%s: sysctl() failed: %d", __func__, errno);
1964 if ((pi = malloc(size)) == NULL)
1967 mib[5] = (int)(size / sizeof(struct kinfo_proc));
1969 if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
1970 (size != sizeof (struct kinfo_proc))) {
1971 if (errno == ENOMEM) {
1978 #if defined(__OpenBSD__)
1979 if (strlen (pi->p_comm) > 0)
1980 ret = g_strdup (pi->p_comm);
1981 #elif defined(__FreeBSD__)
1982 if (strlen (pi->ki_comm) > 0)
1983 ret = g_strdup (pi->ki_comm);
1987 #elif defined(__HAIKU__)
1988 image_info imageInfo;
1991 if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
1992 ret = g_strdup (imageInfo.name);
1995 memset (buf, '\0', sizeof(buf));
1996 filename = g_strdup_printf ("/proc/%d/exe", pid);
1997 if (readlink (filename, buf, 255) > 0) {
1998 ret = g_strdup (buf);
2006 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
2007 if ((fp = fopen (filename, "r")) != NULL) {
2008 if (fgets (buf, 256, fp) != NULL) {
2009 ret = g_strdup (buf);
2020 filename = g_strdup_printf ("/proc/%d/stat", pid);
2021 if ((fp = fopen (filename, "r")) != NULL) {
2022 if (fgets (buf, 256, fp) != NULL) {
2025 start = strchr (buf, '(');
2026 if (start != NULL) {
2027 end = strchr (start + 1, ')');
2030 ret = g_strndup (start + 1,
2045 * wapi_process_get_path:
2047 * Return the full path of the executable of the process PID, or NULL if it cannot be determined.
2048 * Returns malloc-ed memory.
2051 wapi_process_get_path (pid_t pid)
2053 #if defined(PLATFORM_MACOSX) && !defined(__mono_ppc__) && defined(TARGET_OSX)
2054 char buf [PROC_PIDPATHINFO_MAXSIZE];
2057 res = proc_pidpath (pid, buf, sizeof (buf));
2060 if (buf [0] == '\0')
2062 return g_strdup (buf);
2064 return get_process_name_from_proc (pid);
2069 * wapi_process_set_cli_launcher:
2071 * Set the full path of the runtime executable used to launch managed exe's.
2074 wapi_process_set_cli_launcher (char *path)
2076 g_free (cli_launcher);
2077 cli_launcher = path ? g_strdup (path) : NULL;
2081 get_module_name (gpointer process, gpointer module,
2082 gunichar2 *basename, guint32 size,
2085 WapiHandle_process *process_handle;
2087 gunichar2 *procname;
2088 char *procname_ext = NULL;
2091 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX) && !defined(__FreeBSD__)
2094 GSList *mods = NULL;
2095 WapiProcModule *found_module;
2098 char *proc_name = NULL;
2100 DEBUG ("%s: Getting module base name, process handle %p module %p",
2101 __func__, process, module);
2103 size = size * sizeof (gunichar2); /* adjust for unicode characters */
2105 if (basename == NULL || size == 0)
2108 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2109 /* This is a pseudo handle */
2110 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2111 proc_name = get_process_name_from_proc (pid);
2113 process_handle = lookup_process_handle (process);
2114 if (!process_handle) {
2115 DEBUG ("%s: Can't find process %p", __func__,
2120 pid = process_handle->id;
2121 proc_name = g_strdup (process_handle->proc_name);
2124 /* Look up the address in /proc/<pid>/maps */
2125 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__HAIKU__)
2126 mods = load_modules ();
2128 fp = open_process_map (pid, "r");
2130 if (errno == EACCES && module == NULL && base == TRUE) {
2131 procname_ext = get_process_name_from_proc (pid);
2133 /* No /proc/<pid>/maps, so just return failure
2140 mods = load_modules (fp);
2144 count = g_slist_length (mods);
2146 /* If module != NULL compare the address.
2147 * If module == NULL we are looking for the main module.
2148 * The best we can do for now check it the module name end with the process name.
2150 for (i = 0; i < count; i++) {
2151 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2152 if (procname_ext == NULL &&
2153 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2154 (module != NULL && found_module->address_start == module))) {
2156 procname_ext = g_path_get_basename (found_module->filename);
2158 procname_ext = g_strdup (found_module->filename);
2161 free_procmodule (found_module);
2164 if (procname_ext == NULL) {
2165 /* If it's *still* null, we might have hit the
2166 * case where reading /proc/$pid/maps gives an
2167 * empty file for this user.
2169 procname_ext = get_process_name_from_proc (pid);
2172 g_slist_free (mods);
2176 DEBUG ("%s: Process name is [%s]", __func__,
2179 procname = mono_unicode_from_external (procname_ext, &bytes);
2180 if (procname == NULL) {
2182 g_free (procname_ext);
2188 /* Add the terminator */
2192 DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2194 memcpy (basename, procname, size);
2196 DEBUG ("%s: Size %d larger than needed (%ld)",
2197 __func__, size, bytes);
2199 memcpy (basename, procname, bytes);
2203 g_free (procname_ext);
2212 get_module_filename (gpointer process, gpointer module,
2213 gunichar2 *basename, guint32 size)
2218 gunichar2 *proc_path;
2220 size *= sizeof (gunichar2); /* adjust for unicode characters */
2222 if (basename == NULL || size == 0)
2225 pid = GetProcessId (process);
2227 path = wapi_process_get_path (pid);
2231 proc_path = mono_unicode_from_external (path, &bytes);
2234 if (proc_path == NULL)
2239 /* Add the terminator */
2243 DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2245 memcpy (basename, proc_path, size);
2247 DEBUG ("%s: Size %d larger than needed (%ld)",
2248 __func__, size, bytes);
2250 memcpy (basename, proc_path, bytes);
2259 GetModuleBaseName (gpointer process, gpointer module,
2260 gunichar2 *basename, guint32 size)
2262 return get_module_name (process, module, basename, size, TRUE);
2266 GetModuleFileNameEx (gpointer process, gpointer module,
2267 gunichar2 *filename, guint32 size)
2269 return get_module_filename (process, module, filename, size);
2273 GetModuleInformation (gpointer process, gpointer module,
2274 WapiModuleInfo *modinfo, guint32 size)
2276 WapiHandle_process *process_handle;
2278 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX) && !defined(__FreeBSD__)
2281 GSList *mods = NULL;
2282 WapiProcModule *found_module;
2285 gboolean ret = FALSE;
2286 char *proc_name = NULL;
2288 DEBUG ("%s: Getting module info, process handle %p module %p",
2289 __func__, process, module);
2291 if (modinfo == NULL || size < sizeof (WapiModuleInfo))
2294 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2295 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2296 proc_name = get_process_name_from_proc (pid);
2298 process_handle = lookup_process_handle (process);
2299 if (!process_handle) {
2300 DEBUG ("%s: Can't find process %p", __func__,
2305 pid = process_handle->id;
2306 proc_name = g_strdup (process_handle->proc_name);
2309 #if defined(PLATFORM_MACOSX) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__HAIKU__)
2310 mods = load_modules ();
2312 /* Look up the address in /proc/<pid>/maps */
2313 if ((fp = open_process_map (pid, "r")) == NULL) {
2314 /* No /proc/<pid>/maps, so just return failure
2320 mods = load_modules (fp);
2323 count = g_slist_length (mods);
2325 /* If module != NULL compare the address.
2326 * If module == NULL we are looking for the main module.
2327 * The best we can do for now check it the module name end with the process name.
2329 for (i = 0; i < count; i++) {
2330 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2332 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2333 (module != NULL && found_module->address_start == module))) {
2334 modinfo->lpBaseOfDll = found_module->address_start;
2335 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2336 modinfo->EntryPoint = found_module->address_offset;
2340 free_procmodule (found_module);
2343 g_slist_free (mods);
2350 GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2352 WapiHandle_process *process_handle;
2354 if (min == NULL || max == NULL)
2355 /* Not sure if w32 allows NULLs here or not */
2358 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2359 /* This is a pseudo handle, so just fail for now */
2362 process_handle = lookup_process_handle (process);
2363 if (!process_handle) {
2364 DEBUG ("%s: Can't find process %p", __func__, process);
2369 *min = process_handle->min_working_set;
2370 *max = process_handle->max_working_set;
2376 SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2378 WapiHandle_process *process_handle;
2380 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2381 /* This is a pseudo handle, so just fail for now
2385 process_handle = lookup_process_handle (process);
2386 if (!process_handle) {
2387 DEBUG ("%s: Can't find process %p", __func__, process);
2392 process_handle->min_working_set = min;
2393 process_handle->max_working_set = max;
2400 TerminateProcess (gpointer process, gint32 exitCode)
2402 #if defined(HAVE_KILL)
2403 WapiHandle_process *process_handle;
2408 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2409 /* This is a pseudo handle */
2410 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2412 process_handle = lookup_process_handle (process);
2413 if (!process_handle) {
2414 DEBUG ("%s: Can't find process %p", __func__, process);
2415 SetLastError (ERROR_INVALID_HANDLE);
2418 pid = process_handle->id;
2421 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2422 ret = kill (pid, signo);
2426 SetLastError (ERROR_INVALID_PARAMETER);
2429 SetLastError (ERROR_ACCESS_DENIED);
2432 SetLastError (ERROR_PROC_NOT_FOUND);
2435 SetLastError (ERROR_GEN_FAILURE);
2441 g_error ("kill() is not supported by this platform");
2447 GetPriorityClass (gpointer process)
2449 #ifdef HAVE_GETPRIORITY
2450 WapiHandle_process *process_handle;
2454 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2455 /* This is a pseudo handle */
2456 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2458 process_handle = lookup_process_handle (process);
2459 if (!process_handle) {
2460 SetLastError (ERROR_INVALID_HANDLE);
2463 pid = process_handle->id;
2467 ret = getpriority (PRIO_PROCESS, pid);
2468 if (ret == -1 && errno != 0) {
2472 SetLastError (ERROR_ACCESS_DENIED);
2475 SetLastError (ERROR_PROC_NOT_FOUND);
2478 SetLastError (ERROR_GEN_FAILURE);
2484 return NORMAL_PRIORITY_CLASS;
2486 return REALTIME_PRIORITY_CLASS;
2488 return HIGH_PRIORITY_CLASS;
2490 return ABOVE_NORMAL_PRIORITY_CLASS;
2492 return IDLE_PRIORITY_CLASS;
2494 return BELOW_NORMAL_PRIORITY_CLASS;
2496 return NORMAL_PRIORITY_CLASS;
2498 SetLastError (ERROR_NOT_SUPPORTED);
2504 SetPriorityClass (gpointer process, guint32 priority_class)
2506 #ifdef HAVE_SETPRIORITY
2507 WapiHandle_process *process_handle;
2512 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2513 /* This is a pseudo handle */
2514 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2516 process_handle = lookup_process_handle (process);
2517 if (!process_handle) {
2518 SetLastError (ERROR_INVALID_HANDLE);
2521 pid = process_handle->id;
2524 switch (priority_class) {
2525 case IDLE_PRIORITY_CLASS:
2528 case BELOW_NORMAL_PRIORITY_CLASS:
2531 case NORMAL_PRIORITY_CLASS:
2534 case ABOVE_NORMAL_PRIORITY_CLASS:
2537 case HIGH_PRIORITY_CLASS:
2540 case REALTIME_PRIORITY_CLASS:
2544 SetLastError (ERROR_INVALID_PARAMETER);
2548 ret = setpriority (PRIO_PROCESS, pid, prio);
2553 SetLastError (ERROR_ACCESS_DENIED);
2556 SetLastError (ERROR_PROC_NOT_FOUND);
2559 SetLastError (ERROR_GEN_FAILURE);
2565 SetLastError (ERROR_NOT_SUPPORTED);
2571 mono_processes_cleanup (void)
2573 struct MonoProcess *mp;
2574 struct MonoProcess *prev = NULL;
2575 GSList *finished = NULL;
2577 gpointer unref_handle;
2579 DEBUG ("%s", __func__);
2581 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2582 if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
2585 for (mp = mono_processes; mp; mp = mp->next) {
2586 if (mp->pid == 0 && mp->handle) {
2587 /* This process has exited and we need to remove the artifical ref
2589 mono_os_mutex_lock (&mono_processes_mutex);
2590 unref_handle = mp->handle;
2592 mono_os_mutex_unlock (&mono_processes_mutex);
2594 _wapi_handle_unref (unref_handle);
2599 * Remove processes which exited from the mono_processes list.
2600 * We need to synchronize with the sigchld handler here, which runs
2601 * asynchronously. The handler requires that the mono_processes list
2604 mono_os_mutex_lock (&mono_processes_mutex);
2606 mp = mono_processes;
2608 if (mp->handle_count == 0 && mp->freeable) {
2611 * This code can run parallel with the sigchld handler, but the
2612 * modifications it makes are safe.
2614 if (mp == mono_processes)
2615 mono_processes = mp->next;
2617 prev->next = mp->next;
2618 finished = g_slist_prepend (finished, mp);
2627 mono_memory_barrier ();
2629 for (l = finished; l; l = l->next) {
2631 * All the entries in the finished list are unlinked from mono_processes, and
2632 * they have the 'finished' flag set, which means the sigchld handler is done
2635 mp = (MonoProcess *)l->data;
2636 mono_os_sem_destroy (&mp->exit_sem);
2639 g_slist_free (finished);
2641 mono_os_mutex_unlock (&mono_processes_mutex);
2643 DEBUG ("%s done", __func__);
2645 InterlockedDecrement (&mono_processes_cleaning_up);
2649 process_close (gpointer handle, gpointer data)
2651 WapiHandle_process *process_handle;
2653 DEBUG ("%s", __func__);
2655 process_handle = (WapiHandle_process *) data;
2656 g_free (process_handle->proc_name);
2657 process_handle->proc_name = NULL;
2658 if (process_handle->mono_process)
2659 InterlockedDecrement (&process_handle->mono_process->handle_count);
2660 mono_processes_cleanup ();
2664 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
2668 struct MonoProcess *p;
2670 DEBUG ("SIG CHILD handler for pid: %i\n", info->si_pid);
2674 pid = waitpid (-1, &status, WNOHANG);
2675 } while (pid == -1 && errno == EINTR);
2680 DEBUG ("child ended: %i", pid);
2683 * This can run concurrently with the code in the rest of this module.
2685 for (p = mono_processes; p; p = p->next) {
2686 if (p->pid == pid) {
2691 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2693 mono_os_sem_post (&p->exit_sem);
2694 mono_memory_barrier ();
2695 /* Mark this as freeable, the pointer becomes invalid afterwards */
2700 DEBUG ("SIG CHILD handler: done looping.");
2706 process_add_sigchld_handler (void)
2709 struct sigaction sa;
2711 sa.sa_sigaction = mono_sigchld_signal_handler;
2712 sigemptyset (&sa.sa_mask);
2713 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2714 g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2715 DEBUG ("Added SIGCHLD handler");
2720 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2722 WapiHandle_process *process_handle;
2723 pid_t pid G_GNUC_UNUSED, ret;
2727 struct MonoProcess *mp;
2729 /* FIXME: We can now easily wait on processes that aren't our own children,
2730 * but WaitFor*Object won't call us for pseudo handles. */
2731 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2733 DEBUG ("%s (%p, %u)", __func__, handle, timeout);
2735 process_handle = lookup_process_handle (handle);
2736 if (!process_handle) {
2737 g_warning ("%s: error looking up process handle %p", __func__, handle);
2741 if (process_handle->exited) {
2742 /* We've already done this one */
2743 DEBUG ("%s (%p, %u): Process already exited", __func__, handle, timeout);
2744 return WAIT_OBJECT_0;
2747 pid = process_handle->id;
2749 DEBUG ("%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2751 /* We don't need to lock mono_processes here, the entry
2752 * has a handle_count > 0 which means it will not be freed. */
2753 mp = process_handle->mono_process;
2756 start = mono_msec_ticks ();
2760 if (timeout != INFINITE) {
2761 DEBUG ("%s (%p, %u): waiting on semaphore for %li ms...",
2762 __func__, handle, timeout, (timeout - (now - start)));
2763 ret = mono_os_sem_timedwait (&mp->exit_sem, (timeout - (now - start)), alertable ? MONO_SEM_FLAGS_ALERTABLE : MONO_SEM_FLAGS_NONE);
2765 DEBUG ("%s (%p, %u): waiting on semaphore forever...",
2766 __func__, handle, timeout);
2767 ret = mono_os_sem_wait (&mp->exit_sem, alertable ? MONO_SEM_FLAGS_ALERTABLE : MONO_SEM_FLAGS_NONE);
2770 if (ret == -1 && errno != EINTR && errno != ETIMEDOUT) {
2771 DEBUG ("%s (%p, %u): sem_timedwait failure: %s",
2772 __func__, handle, timeout, g_strerror (errno));
2773 /* Should we return a failure here? */
2777 /* Success, process has exited */
2778 mono_os_sem_post (&mp->exit_sem);
2783 DEBUG ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
2784 return WAIT_TIMEOUT;
2787 now = mono_msec_ticks ();
2788 if (now - start >= timeout) {
2789 DEBUG ("%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
2790 return WAIT_TIMEOUT;
2793 if (alertable && _wapi_thread_cur_apc_pending ()) {
2794 DEBUG ("%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
2795 return WAIT_IO_COMPLETION;
2799 /* Process must have exited */
2800 DEBUG ("%s (%p, %u): Waited successfully", __func__, handle, timeout);
2802 ret = _wapi_handle_lock_shared_handles ();
2803 g_assert (ret == 0);
2805 status = mp ? mp->status : 0;
2806 if (WIFSIGNALED (status))
2807 process_handle->exitstatus = 128 + WTERMSIG (status);
2809 process_handle->exitstatus = WEXITSTATUS (status);
2810 _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
2812 process_handle->exited = TRUE;
2814 DEBUG ("%s (%p, %u): Setting pid %d signalled, exit status %d",
2815 __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
2817 _wapi_handle_set_signal_state (handle, TRUE, TRUE);
2819 _wapi_handle_unlock_shared_handles ();
2821 return WAIT_OBJECT_0;
2825 wapi_processes_cleanup (void)
2827 g_free (cli_launcher);