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)
58 #define USE_OSX_LOADER
61 #if ( defined(__OpenBSD__) || defined(__FreeBSD__) ) && defined(HAVE_LINK_H)
62 #define USE_BSD_LOADER
65 #if defined(__HAIKU__)
66 #define USE_HAIKU_LOADER
69 #if defined(USE_OSX_LOADER) || defined(USE_BSD_LOADER)
71 #include <sys/sysctl.h>
72 # if !defined(__OpenBSD__)
73 # include <sys/utsname.h>
75 # if defined(__FreeBSD__)
76 # include <sys/user.h> /* struct kinfo_proc */
80 #ifdef PLATFORM_SOLARIS
81 /* procfs.h cannot be included if this define is set, but it seems to work fine if it is undefined */
82 #if _FILE_OFFSET_BITS == 64
83 #undef _FILE_OFFSET_BITS
85 #define _FILE_OFFSET_BITS 64
92 #include <KernelKit.h>
95 #include <mono/io-layer/wapi.h>
96 #include <mono/io-layer/wapi-private.h>
97 #include <mono/io-layer/handles-private.h>
98 #include <mono/io-layer/process-private.h>
99 #include <mono/io-layer/threads.h>
100 #include <mono/utils/strenc.h>
101 #include <mono/utils/mono-path.h>
102 #include <mono/io-layer/timefuncs-private.h>
103 #include <mono/utils/mono-time.h>
104 #include <mono/utils/mono-membar.h>
105 #include <mono/utils/mono-os-mutex.h>
106 #include <mono/utils/mono-signal-handler.h>
107 #include <mono/utils/mono-proclib.h>
108 #include <mono/utils/mono-once.h>
110 /* The process' environment strings */
111 #if defined(__APPLE__)
112 #if defined (TARGET_OSX)
113 /* Apple defines this in crt_externs.h but doesn't provide that header for
114 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
115 * in fact exist on all implementations (so far)
117 gchar ***_NSGetEnviron(void);
118 #define environ (*_NSGetEnviron())
120 static char *mono_environ[1] = { NULL };
121 #define environ mono_environ
122 #endif /* defined (TARGET_OSX) */
124 extern char **environ;
128 #define DEBUG(...) g_message(__VA_ARGS__)
129 #define DEBUG_ENABLED 1
134 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable);
135 static void process_close (gpointer handle, gpointer data);
136 static gboolean is_pid_valid (pid_t pid);
138 #if !(defined(USE_OSX_LOADER) || defined(USE_BSD_LOADER) || defined(USE_HAIKU_LOADER))
140 open_process_map (int pid, const char *mode);
143 struct _WapiHandleOps _wapi_process_ops = {
144 process_close, /* close_shared */
148 process_wait, /* special_wait */
153 static struct sigaction previous_chld_sa;
155 static mono_once_t process_sig_chld_once = MONO_ONCE_INIT;
156 static void process_add_sigchld_handler (void);
158 /* The signal-safe logic to use mono_processes goes like this:
159 * - The list must be safe to traverse for the signal handler at all times.
160 * It's safe to: prepend an entry (which is a single store to 'mono_processes'),
161 * unlink an entry (assuming the unlinked entry isn't freed and doesn't
162 * change its 'next' pointer so that it can still be traversed).
163 * When cleaning up we first unlink an entry, then we verify that
164 * the read lock isn't locked. Then we can free the entry, since
165 * we know that nobody is using the old version of the list (including
166 * the unlinked entry).
167 * We also need to lock when adding and cleaning up so that those two
168 * operations don't mess with eachother. (This lock is not used in the
171 static struct MonoProcess *mono_processes = NULL;
172 static volatile gint32 mono_processes_cleaning_up = 0;
173 static mono_mutex_t mono_processes_mutex;
174 static void mono_processes_cleanup (void);
176 static gpointer current_process;
177 static char *cli_launcher;
179 static WapiHandle_process *
180 lookup_process_handle (gpointer handle)
182 WapiHandle_process *process_data;
185 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
186 (gpointer *)&process_data);
192 /* Check if a pid is valid - i.e. if a process exists with this pid. */
194 is_pid_valid (pid_t pid)
196 gboolean result = FALSE;
198 #if defined(HOST_WATCHOS)
199 result = TRUE; // TODO: Rewrite using sysctl
200 #elif defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__)
201 if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
203 #elif defined(__HAIKU__)
205 if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
208 char *dir = g_strdup_printf ("/proc/%d", pid);
209 if (!access (dir, F_OK))
218 process_set_defaults (WapiHandle_process *process_handle)
220 /* These seem to be the defaults on w2k */
221 process_handle->min_working_set = 204800;
222 process_handle->max_working_set = 1413120;
224 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
228 len16 (const gunichar2 *str)
239 utf16_concat (const gunichar2 *first, ...)
246 va_start (args, first);
247 total += len16 (first);
248 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
253 ret = g_new (gunichar2, total + 1);
259 for (s = first; *s != 0; s++)
261 va_start (args, first);
262 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
265 for (p = s; *p != 0; p++)
273 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
274 static const gunichar2 *utf16_space = utf16_space_bytes;
275 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
276 static const gunichar2 *utf16_quote = utf16_quote_bytes;
281 print_utf16 (gunichar2 *str)
285 res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
286 g_print ("%s\n", res);
291 /* Implemented as just a wrapper around CreateProcess () */
293 ShellExecuteEx (WapiShellExecuteInfo *sei)
296 WapiProcessInformation process_info;
300 /* w2k just segfaults here, but we can do better than
303 SetLastError (ERROR_INVALID_PARAMETER);
307 if (sei->lpFile == NULL)
308 /* w2k returns TRUE for this, for some reason. */
311 /* Put both executable and parameters into the second argument
312 * to CreateProcess (), so it searches $PATH. The conversion
313 * into and back out of utf8 is because there is no
314 * g_strdup_printf () equivalent for gunichar2 :-(
316 args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
318 SetLastError (ERROR_INVALID_DATA);
321 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
322 CREATE_UNICODE_ENVIRONMENT, NULL,
323 sei->lpDirectory, NULL, &process_info);
326 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
330 static char *handler;
331 static gunichar2 *handler_utf16;
333 if (handler_utf16 == (gunichar2 *)-1)
336 #ifdef PLATFORM_MACOSX
337 handler = g_strdup ("/usr/bin/open");
340 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
341 * if that fails, try to use gnome-open, then kfmclient
343 handler = g_find_program_in_path ("xdg-open");
344 if (handler == NULL){
345 handler = g_find_program_in_path ("gnome-open");
346 if (handler == NULL){
347 handler = g_find_program_in_path ("kfmclient");
348 if (handler == NULL){
349 handler_utf16 = (gunichar2 *) -1;
352 /* kfmclient needs exec argument */
354 handler = g_strconcat (old, " exec",
361 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
364 /* Put quotes around the filename, in case it's a url
365 * that contains #'s (CreateProcess() calls
366 * g_shell_parse_argv(), which deliberately throws
367 * away anything after an unquoted #). Fixes bug
370 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
371 sei->lpFile, utf16_quote,
372 sei->lpParameters == NULL ? NULL : utf16_space,
373 sei->lpParameters, NULL);
375 SetLastError (ERROR_INVALID_DATA);
378 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
379 CREATE_UNICODE_ENVIRONMENT, NULL,
380 sei->lpDirectory, NULL, &process_info);
383 if (GetLastError () != ERROR_OUTOFMEMORY)
384 SetLastError (ERROR_INVALID_DATA);
387 /* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
388 CloseHandle (process_info.hProcess);
389 process_info.hProcess = NULL;
392 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS)
393 sei->hProcess = process_info.hProcess;
395 CloseHandle (process_info.hProcess);
401 is_managed_binary (const char *filename)
403 int original_errno = errno;
404 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
405 int file = open (filename, O_RDONLY | O_LARGEFILE);
407 int file = open (filename, O_RDONLY);
410 unsigned char buffer[8];
411 off_t file_size, optional_header_offset;
412 off_t pe_header_offset;
413 gboolean managed = FALSE;
415 guint32 first_word, second_word;
417 /* If we are unable to open the file, then we definitely
418 * can't say that it is managed. The child mono process
419 * probably wouldn't be able to open it anyway.
422 errno = original_errno;
426 /* Retrieve the length of the file for future sanity checks. */
427 file_size = lseek (file, 0, SEEK_END);
428 lseek (file, 0, SEEK_SET);
430 /* We know we need to read a header field at offset 60. */
434 num_read = read (file, buffer, 2);
436 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
439 new_offset = lseek (file, 60, SEEK_SET);
441 if (new_offset != 60)
444 num_read = read (file, buffer, 4);
448 pe_header_offset = buffer[0]
453 if (pe_header_offset + 24 > file_size)
456 new_offset = lseek (file, pe_header_offset, SEEK_SET);
458 if (new_offset != pe_header_offset)
461 num_read = read (file, buffer, 4);
463 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
467 * Verify that the header we want in the optional header data
468 * is present in this binary.
470 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
472 if (new_offset != pe_header_offset + 20)
475 num_read = read (file, buffer, 2);
477 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
480 /* Read the CLR header address and size fields. These will be
481 * zero if the binary is not managed.
483 optional_header_offset = pe_header_offset + 24;
484 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
486 if (new_offset != optional_header_offset + 208)
489 num_read = read (file, buffer, 8);
491 /* We are not concerned with endianness, only with
492 * whether it is zero or not.
494 first_word = *(guint32 *)&buffer[0];
495 second_word = *(guint32 *)&buffer[4];
497 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
504 errno = original_errno;
509 CreateProcessWithLogonW (const gunichar2 *username,
510 const gunichar2 *domain,
511 const gunichar2 *password,
512 const guint32 logonFlags,
513 const gunichar2 *appname,
514 const gunichar2 *cmdline,
515 guint32 create_flags,
517 const gunichar2 *cwd,
518 WapiStartupInfo *startup,
519 WapiProcessInformation *process_info)
521 /* FIXME: use user information */
522 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
526 is_readable_or_executable (const char *prog)
529 int a = access (prog, R_OK);
530 int b = access (prog, X_OK);
531 if (a != 0 && b != 0)
533 if (stat (prog, &buf))
535 if (S_ISREG (buf.st_mode))
541 is_executable (const char *prog)
544 if (access (prog, X_OK) != 0)
546 if (stat (prog, &buf))
548 if (S_ISREG (buf.st_mode))
554 switch_dir_separators (char *path)
556 size_t i, pathLength = strlen(path);
558 /* Turn all the slashes round the right way, except for \' */
559 /* There are probably other characters that need to be excluded as well. */
560 for (i = 0; i < pathLength; i++) {
561 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' )
566 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
567 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
568 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
569 gboolean inherit_handles, guint32 create_flags,
570 gpointer new_environ, const gunichar2 *cwd,
571 WapiStartupInfo *startup,
572 WapiProcessInformation *process_info)
574 #if defined (HAVE_FORK) && defined (HAVE_EXECVE)
575 char *cmd = NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL;
576 char *dir = NULL, **env_strings = NULL, **argv = NULL;
577 guint32 i, env_count = 0;
578 gboolean ret = FALSE;
580 WapiHandle_process process_handle = {0}, *process_handle_data;
582 int in_fd, out_fd, err_fd;
585 int startup_pipe [2] = {-1, -1};
587 struct MonoProcess *mono_process;
588 gboolean fork_failed = FALSE;
590 mono_once (&process_sig_chld_once, process_add_sigchld_handler);
592 /* appname and cmdline specify the executable and its args:
594 * If appname is not NULL, it is the name of the executable.
595 * Otherwise the executable is the first token in cmdline.
597 * Executable searching:
599 * If appname is not NULL, it can specify the full path and
600 * file name, or else a partial name and the current directory
601 * will be used. There is no additional searching.
603 * If appname is NULL, the first whitespace-delimited token in
604 * cmdline is used. If the name does not contain a full
605 * directory path, the search sequence is:
607 * 1) The directory containing the current process
608 * 2) The current working directory
609 * 3) The windows system directory (Ignored)
610 * 4) The windows directory (Ignored)
613 * Just to make things more interesting, tokens can contain
614 * white space if they are surrounded by quotation marks. I'm
615 * beginning to understand just why windows apps are generally
616 * so crap, with an API like this :-(
618 if (appname != NULL) {
619 cmd = mono_unicode_to_external (appname);
621 DEBUG ("%s: unicode conversion returned NULL",
624 SetLastError (ERROR_PATH_NOT_FOUND);
628 switch_dir_separators(cmd);
631 if (cmdline != NULL) {
632 args = mono_unicode_to_external (cmdline);
634 DEBUG ("%s: unicode conversion returned NULL", __func__);
636 SetLastError (ERROR_PATH_NOT_FOUND);
642 dir = mono_unicode_to_external (cwd);
644 DEBUG ("%s: unicode conversion returned NULL", __func__);
646 SetLastError (ERROR_PATH_NOT_FOUND);
650 /* Turn all the slashes round the right way */
651 switch_dir_separators(dir);
655 /* We can't put off locating the executable any longer :-( */
658 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
659 /* Strip off the drive letter. I can't
660 * believe that CP/M holdover is still
663 g_memmove (cmd, cmd+2, strlen (cmd)-2);
664 cmd[strlen (cmd)-2] = '\0';
667 unquoted = g_shell_unquote (cmd, NULL);
668 if (unquoted[0] == '/') {
669 /* Assume full path given */
670 prog = g_strdup (unquoted);
672 /* Executable existing ? */
673 if (!is_readable_or_executable (prog)) {
674 DEBUG ("%s: Couldn't find executable %s",
677 SetLastError (ERROR_FILE_NOT_FOUND);
681 /* Search for file named by cmd in the current
684 char *curdir = g_get_current_dir ();
686 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
689 /* And make sure it's readable */
690 if (!is_readable_or_executable (prog)) {
691 DEBUG ("%s: Couldn't find executable %s",
694 SetLastError (ERROR_FILE_NOT_FOUND);
700 args_after_prog = args;
705 /* Dig out the first token from args, taking quotation
709 /* First, strip off all leading whitespace */
710 args = g_strchug (args);
712 /* args_after_prog points to the contents of args
713 * after token has been set (otherwise argv[0] is
716 args_after_prog = args;
718 /* Assume the opening quote will always be the first
721 if (args[0] == '\"' || args [0] == '\'') {
723 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
724 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
725 /* We found the first token */
726 token = g_strndup (args+1, i-1);
727 args_after_prog = g_strchug (args + i + 1);
729 /* Quotation mark appeared in the
730 * middle of the token. Just give the
731 * whole first token, quotes and all,
738 /* No quote mark, or malformed */
739 for (i = 0; args[i] != '\0'; i++) {
740 if (g_ascii_isspace (args[i])) {
741 token = g_strndup (args, i);
742 args_after_prog = args + i + 1;
748 if (token == NULL && args[0] != '\0') {
749 /* Must be just one token in the string */
750 token = g_strdup (args);
751 args_after_prog = NULL;
756 DEBUG ("%s: Couldn't find what to exec", __func__);
758 SetLastError (ERROR_PATH_NOT_FOUND);
762 /* Turn all the slashes round the right way. Only for
765 switch_dir_separators(token);
767 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
768 /* Strip off the drive letter. I can't
769 * believe that CP/M holdover is still
772 g_memmove (token, token+2, strlen (token)-2);
773 token[strlen (token)-2] = '\0';
776 if (token[0] == '/') {
777 /* Assume full path given */
778 prog = g_strdup (token);
780 /* Executable existing ? */
781 if (!is_readable_or_executable (prog)) {
782 DEBUG ("%s: Couldn't find executable %s",
785 SetLastError (ERROR_FILE_NOT_FOUND);
789 char *curdir = g_get_current_dir ();
791 /* FIXME: Need to record the directory
792 * containing the current process, and check
793 * that for the new executable as the first
797 prog = g_strdup_printf ("%s/%s", curdir, token);
800 /* I assume X_OK is the criterion to use,
803 * X_OK is too strict *if* the target is a CLR binary
805 if (!is_readable_or_executable (prog)) {
807 prog = g_find_program_in_path (token);
809 DEBUG ("%s: Couldn't find executable %s", __func__, token);
812 SetLastError (ERROR_FILE_NOT_FOUND);
821 DEBUG ("%s: Exec prog [%s] args [%s]", __func__, prog,
824 /* Check for CLR binaries; if found, we will try to invoke
825 * them using the same mono binary that started us.
827 if (is_managed_binary (prog)) {
828 gunichar2 *newapp = NULL, *newcmd;
832 newapp = mono_unicode_from_external (cli_launcher, &bytes_ignored);
834 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
836 if (newapp != NULL) {
837 if (appname != NULL) {
838 newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space,
839 appname, utf16_space,
842 newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space,
846 g_free ((gunichar2 *)newapp);
848 if (newcmd != NULL) {
849 ret = CreateProcess (NULL, newcmd,
853 create_flags, new_environ,
857 g_free ((gunichar2 *)newcmd);
863 if (!is_executable (prog)) {
864 DEBUG ("%s: Executable permisson not set on %s", __func__, prog);
865 SetLastError (ERROR_ACCESS_DENIED);
870 if (args_after_prog != NULL && *args_after_prog) {
873 qprog = g_shell_quote (prog);
874 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
877 full_prog = g_shell_quote (prog);
880 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
882 g_message ("CreateProcess: %s\n", gerr->message);
888 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
889 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
890 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
891 err_fd = GPOINTER_TO_UINT (startup->hStdError);
893 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
894 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
895 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
898 process_handle.proc_name = g_strdup (prog);
900 process_set_defaults (&process_handle);
902 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
903 if (handle == _WAPI_HANDLE_INVALID) {
904 g_warning ("%s: error creating process handle", __func__);
907 SetLastError (ERROR_OUTOFMEMORY);
911 /* new_environ is a block of NULL-terminated strings, which
912 * is itself NULL-terminated. Of course, passing an array of
913 * string pointers would have made things too easy :-(
915 * If new_environ is not NULL it specifies the entire set of
916 * environment variables in the new process. Otherwise the
917 * new process inherits the same environment.
920 gunichar2 *new_environp;
922 /* Count the number of strings */
923 for (new_environp = (gunichar2 *)new_environ; *new_environp;
926 while (*new_environp) {
931 /* +2: one for the process handle value, and the last
934 env_strings = g_new0 (char *, env_count + 2);
936 /* Copy each environ string into 'strings' turning it
937 * into utf8 (or the requested encoding) at the same
941 for (new_environp = (gunichar2 *)new_environ; *new_environp;
943 env_strings[env_count] = mono_unicode_to_external (new_environp);
945 while (*new_environp) {
950 for (i = 0; environ[i] != NULL; i++)
953 /* +2: one for the process handle value, and the last
956 env_strings = g_new0 (char *, env_count + 2);
958 /* Copy each environ string into 'strings' turning it
959 * into utf8 (or the requested encoding) at the same
963 for (i = 0; environ[i] != NULL; i++) {
964 env_strings[env_count] = g_strdup (environ[i]);
969 /* Create a pipe to make sure the child doesn't exit before
970 * we can add the process to the linked list of mono_processes */
971 if (pipe (startup_pipe) == -1) {
972 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
973 * This is just for a very hard to hit race condition in the first place */
974 startup_pipe [0] = startup_pipe [1] = -1;
975 DEBUG ("%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
978 thr_ret = _wapi_handle_lock_shared_handles ();
979 g_assert (thr_ret == 0);
984 SetLastError (ERROR_OUTOFMEMORY);
988 } else if (pid == 0) {
991 if (startup_pipe [0] != -1) {
992 /* Wait until the parent has updated it's internal data */
993 ssize_t _i G_GNUC_UNUSED = read (startup_pipe [0], &dummy, 1);
994 DEBUG ("%s: child: parent has completed its setup", __func__);
995 close (startup_pipe [0]);
996 close (startup_pipe [1]);
999 /* should we detach from the process group? */
1001 /* Connect stdin, stdout and stderr */
1006 if (inherit_handles != TRUE) {
1007 /* FIXME: do something here */
1010 /* Close all file descriptors */
1011 for (i = wapi_getdtablesize () - 1; i > 2; i--)
1014 #ifdef DEBUG_ENABLED
1015 DEBUG ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1016 dir == NULL?".":dir);
1017 for (i = 0; argv[i] != NULL; i++)
1018 g_message ("arg %d: [%s]", i, argv[i]);
1020 for (i = 0; env_strings[i] != NULL; i++)
1021 g_message ("env %d: [%s]", i, env_strings[i]);
1025 if (dir != NULL && chdir (dir) == -1) {
1031 execve (argv[0], argv, env_strings);
1038 process_handle_data = lookup_process_handle (handle);
1039 if (!process_handle_data) {
1040 g_warning ("%s: error looking up process handle %p", __func__,
1042 _wapi_handle_unref (handle);
1046 process_handle_data->id = pid;
1048 /* Add our mono_process into the linked list of mono_processes */
1049 mono_process = (struct MonoProcess *) g_malloc0 (sizeof (struct MonoProcess));
1050 mono_process->pid = pid;
1051 mono_process->handle_count = 1;
1052 if (mono_os_sem_init (&mono_process->exit_sem, 0) != 0) {
1053 /* If we can't create the exit semaphore, we just don't add anything
1054 * to our list of mono processes. Waiting on the process will return
1056 g_warning ("%s: could not create exit semaphore for process.", strerror (errno));
1057 g_free (mono_process);
1059 /* Keep the process handle artificially alive until the process
1060 * exits so that the information in the handle isn't lost. */
1061 _wapi_handle_ref (handle);
1062 mono_process->handle = handle;
1064 process_handle_data->mono_process = mono_process;
1066 mono_os_mutex_lock (&mono_processes_mutex);
1067 mono_process->next = mono_processes;
1068 mono_processes = mono_process;
1069 mono_os_mutex_unlock (&mono_processes_mutex);
1072 if (process_info != NULL) {
1073 process_info->hProcess = handle;
1074 process_info->dwProcessId = pid;
1076 /* FIXME: we might need to handle the thread info some
1079 process_info->hThread = INVALID_HANDLE_VALUE;
1080 process_info->dwThreadId = 0;
1084 _wapi_handle_unlock_shared_handles ();
1087 _wapi_handle_unref (handle);
1089 if (startup_pipe [1] != -1) {
1090 /* Write 1 byte, doesn't matter what */
1091 ssize_t _i G_GNUC_UNUSED = write (startup_pipe [1], startup_pipe, 1);
1092 close (startup_pipe [0]);
1093 close (startup_pipe [1]);
1108 g_strfreev (env_strings);
1112 DEBUG ("%s: returning handle %p for pid %d", __func__, handle,
1115 /* Check if something needs to be cleaned up. */
1116 mono_processes_cleanup ();
1120 SetLastError (ERROR_NOT_SUPPORTED);
1122 #endif // defined (HAVE_FORK) && defined (HAVE_EXECVE)
1126 process_set_name (WapiHandle_process *process_handle)
1128 char *progname, *utf8_progname, *slash;
1130 progname = g_get_prgname ();
1131 utf8_progname = mono_utf8_from_external (progname);
1133 DEBUG ("%s: using [%s] as prog name", __func__, progname);
1135 if (utf8_progname) {
1136 slash = strrchr (utf8_progname, '/');
1138 process_handle->proc_name = g_strdup (slash+1);
1140 process_handle->proc_name = g_strdup (utf8_progname);
1141 g_free (utf8_progname);
1146 wapi_processes_init (void)
1148 pid_t pid = _wapi_getpid ();
1149 WapiHandle_process process_handle = {0};
1151 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
1152 (WapiHandleCapability)(WAPI_HANDLE_CAP_WAIT | WAPI_HANDLE_CAP_SPECIAL_WAIT));
1154 process_handle.id = pid;
1156 process_set_defaults (&process_handle);
1157 process_set_name (&process_handle);
1159 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1161 g_assert (current_process);
1163 mono_os_mutex_init (&mono_processes_mutex);
1167 _wapi_process_duplicate (void)
1169 _wapi_handle_ref (current_process);
1171 return current_process;
1174 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1176 GetCurrentProcess (void)
1178 return _WAPI_PROCESS_CURRENT;
1182 GetProcessId (gpointer handle)
1184 WapiHandle_process *process_handle;
1186 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1187 /* This is a pseudo handle */
1188 return WAPI_HANDLE_TO_PID (handle);
1190 process_handle = lookup_process_handle (handle);
1191 if (!process_handle) {
1192 SetLastError (ERROR_INVALID_HANDLE);
1196 return process_handle->id;
1200 process_open_compare (gpointer handle, gpointer user_data)
1203 WapiHandle_process *process_handle;
1206 g_assert (!WAPI_IS_PSEUDO_PROCESS_HANDLE (handle));
1208 process_handle = lookup_process_handle (handle);
1209 g_assert (process_handle);
1211 DEBUG ("%s: looking at process %d", __func__, process_handle->id);
1213 checking_pid = process_handle->id;
1215 if (checking_pid == 0)
1218 wanted_pid = GPOINTER_TO_UINT (user_data);
1220 /* It's possible to have more than one process handle with the
1221 * same pid, but only the one running process can be
1224 if (checking_pid == wanted_pid &&
1225 !_wapi_handle_issignalled (handle)) {
1226 /* If the handle is blown away in the window between
1227 * returning TRUE here and _wapi_search_handle pinging
1228 * the timestamp, the search will continue
1237 CloseProcess (gpointer handle)
1239 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1241 return CloseHandle (handle);
1245 * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1248 OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1250 /* Find the process handle that corresponds to pid */
1251 gpointer handle = NULL;
1253 DEBUG ("%s: looking for process %d", __func__, pid);
1255 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1256 process_open_compare,
1257 GUINT_TO_POINTER (pid), NULL, TRUE);
1259 if (is_pid_valid (pid)) {
1260 /* Return a pseudo handle for processes we
1261 * don't have handles for
1263 return WAPI_PID_TO_HANDLE (pid);
1265 DEBUG ("%s: Can't find pid %d", __func__, pid);
1267 SetLastError (ERROR_PROC_NOT_FOUND);
1273 /* _wapi_search_handle () already added a ref */
1278 GetExitCodeProcess (gpointer process, guint32 *code)
1280 WapiHandle_process *process_handle;
1286 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1287 pid = WAPI_HANDLE_TO_PID (process);
1288 /* This is a pseudo handle, so we don't know what the
1289 * exit code was, but we can check whether it's alive or not
1291 if (is_pid_valid (pid)) {
1292 *code = STILL_ACTIVE;
1299 process_handle = lookup_process_handle (process);
1300 if (!process_handle) {
1301 DEBUG ("%s: Can't find process %p", __func__, process);
1306 if (process_handle->id == _wapi_getpid ()) {
1307 *code = STILL_ACTIVE;
1311 /* A process handle is only signalled if the process has exited
1312 * and has been waited for */
1314 /* Make sure any process exit has been noticed, before
1315 * checking if the process is signalled. Fixes bug 325463.
1317 process_wait (process, 0, TRUE);
1319 if (_wapi_handle_issignalled (process))
1320 *code = process_handle->exitstatus;
1322 *code = STILL_ACTIVE;
1328 GetProcessTimes (gpointer process, WapiFileTime *create_time,
1329 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1330 WapiFileTime *user_time)
1332 WapiHandle_process *process_handle;
1333 gboolean ku_times_set = FALSE;
1335 if (create_time == NULL || exit_time == NULL || kernel_time == NULL ||
1337 /* Not sure if w32 allows NULLs here or not */
1340 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1341 gpointer pid = GINT_TO_POINTER (WAPI_HANDLE_TO_PID(process));
1342 gint64 start_ticks, user_ticks, kernel_ticks;
1344 mono_process_get_times (pid, &start_ticks, &user_ticks, &kernel_ticks);
1346 _wapi_guint64_to_filetime (start_ticks, create_time);
1347 _wapi_guint64_to_filetime (user_ticks, kernel_time);
1348 _wapi_guint64_to_filetime (kernel_ticks, user_time);
1353 process_handle = lookup_process_handle (process);
1354 if (!process_handle) {
1355 DEBUG ("%s: Can't find process %p", __func__, process);
1360 *create_time = process_handle->create_time;
1362 /* A process handle is only signalled if the process has
1363 * exited. Otherwise exit_time isn't set
1365 if (_wapi_handle_issignalled (process))
1366 *exit_time = process_handle->exit_time;
1368 #ifdef HAVE_GETRUSAGE
1369 if (process_handle->id == getpid ()) {
1370 struct rusage time_data;
1371 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1373 ku_times_set = TRUE;
1374 tick_val = (guint64)time_data.ru_utime.tv_sec * 10000000 + (guint64)time_data.ru_utime.tv_usec * 10;
1375 _wapi_guint64_to_filetime (tick_val, user_time);
1376 tick_val = (guint64)time_data.ru_stime.tv_sec * 10000000 + (guint64)time_data.ru_stime.tv_usec * 10;
1377 _wapi_guint64_to_filetime (tick_val, kernel_time);
1381 if (!ku_times_set) {
1382 memset (kernel_time, 0, sizeof (WapiFileTime));
1383 memset (user_time, 0, sizeof (WapiFileTime));
1391 gpointer address_start;
1392 gpointer address_end;
1394 gpointer address_offset;
1400 static void free_procmodule (WapiProcModule *mod)
1402 if (mod->perms != NULL) {
1403 g_free (mod->perms);
1405 if (mod->filename != NULL) {
1406 g_free (mod->filename);
1411 static gint find_procmodule (gconstpointer a, gconstpointer b)
1413 WapiProcModule *want = (WapiProcModule *)a;
1414 WapiProcModule *compare = (WapiProcModule *)b;
1416 if ((want->device == compare->device) &&
1417 (want->inode == compare->inode)) {
1424 #if defined(USE_OSX_LOADER)
1425 #include <mach-o/dyld.h>
1426 #include <mach-o/getsect.h>
1428 static GSList *load_modules (void)
1431 WapiProcModule *mod;
1432 uint32_t count = _dyld_image_count ();
1435 for (i = 0; i < count; i++) {
1436 #if SIZEOF_VOID_P == 8
1437 const struct mach_header_64 *hdr;
1438 const struct section_64 *sec;
1440 const struct mach_header *hdr;
1441 const struct section *sec;
1445 name = _dyld_get_image_name (i);
1446 #if SIZEOF_VOID_P == 8
1447 hdr = (const struct mach_header_64*)_dyld_get_image_header (i);
1448 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1450 hdr = _dyld_get_image_header (i);
1451 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1454 /* Some dynlibs do not have data sections on osx (#533893) */
1459 mod = g_new0 (WapiProcModule, 1);
1460 mod->address_start = GINT_TO_POINTER (sec->addr);
1461 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1462 mod->perms = g_strdup ("r--p");
1463 mod->address_offset = 0;
1464 mod->device = makedev (0, 0);
1466 mod->filename = g_strdup (name);
1468 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1469 ret = g_slist_prepend (ret, mod);
1471 free_procmodule (mod);
1475 ret = g_slist_reverse (ret);
1479 #elif defined(USE_BSD_LOADER)
1481 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1483 if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1484 + sizeof (info->dlpi_phnum))
1487 struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1491 memcpy(cpy, info, sizeof(*info));
1493 g_ptr_array_add ((GPtrArray *)ptr, cpy);
1498 static GSList *load_modules (void)
1501 WapiProcModule *mod;
1502 GPtrArray *dlarray = g_ptr_array_new();
1505 if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1508 for (i = 0; i < dlarray->len; i++) {
1509 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1511 mod = g_new0 (WapiProcModule, 1);
1512 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1513 mod->address_end = (gpointer)(info->dlpi_addr +
1514 info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1515 mod->perms = g_strdup ("r--p");
1516 mod->address_offset = 0;
1518 mod->filename = g_strdup (info->dlpi_name);
1520 DEBUG ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1521 mod->inode, mod->filename, mod->address_start, mod->address_end);
1525 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1526 ret = g_slist_prepend (ret, mod);
1528 free_procmodule (mod);
1532 g_ptr_array_free (dlarray, TRUE);
1534 ret = g_slist_reverse (ret);
1538 #elif defined(USE_HAIKU_LOADER)
1540 static GSList *load_modules (void)
1543 WapiProcModule *mod;
1545 image_info imageInfo;
1547 while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
1548 mod = g_new0 (WapiProcModule, 1);
1549 mod->device = imageInfo.device;
1550 mod->inode = imageInfo.node;
1551 mod->filename = g_strdup (imageInfo.name);
1552 mod->address_start = MIN (imageInfo.text, imageInfo.data);
1553 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
1554 (uint8_t*)imageInfo.data + imageInfo.data_size);
1555 mod->perms = g_strdup ("r--p");
1556 mod->address_offset = 0;
1558 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1559 ret = g_slist_prepend (ret, mod);
1561 free_procmodule (mod);
1565 ret = g_slist_reverse (ret);
1570 static GSList *load_modules (FILE *fp)
1573 WapiProcModule *mod;
1574 char buf[MAXPATHLEN + 1], *p, *endp;
1575 char *start_start, *end_start, *prot_start, *offset_start;
1576 char *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1577 gpointer address_start, address_end, address_offset;
1578 guint32 maj_dev, min_dev;
1582 while (fgets (buf, sizeof(buf), fp)) {
1584 while (g_ascii_isspace (*p)) ++p;
1586 if (!g_ascii_isxdigit (*start_start)) {
1589 address_start = (gpointer)strtoul (start_start, &endp, 16);
1597 if (!g_ascii_isxdigit (*end_start)) {
1600 address_end = (gpointer)strtoul (end_start, &endp, 16);
1602 if (!g_ascii_isspace (*p)) {
1606 while (g_ascii_isspace (*p)) ++p;
1608 if (*prot_start != 'r' && *prot_start != '-') {
1611 memcpy (prot_buf, prot_start, 4);
1613 while (!g_ascii_isspace (*p)) ++p;
1615 while (g_ascii_isspace (*p)) ++p;
1617 if (!g_ascii_isxdigit (*offset_start)) {
1620 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1622 if (!g_ascii_isspace (*p)) {
1626 while(g_ascii_isspace (*p)) ++p;
1628 if (!g_ascii_isxdigit (*maj_dev_start)) {
1631 maj_dev = strtoul (maj_dev_start, &endp, 16);
1639 if (!g_ascii_isxdigit (*min_dev_start)) {
1642 min_dev = strtoul (min_dev_start, &endp, 16);
1644 if (!g_ascii_isspace (*p)) {
1648 while (g_ascii_isspace (*p)) ++p;
1650 if (!g_ascii_isxdigit (*inode_start)) {
1653 inode = (guint64)strtol (inode_start, &endp, 10);
1655 if (!g_ascii_isspace (*p)) {
1659 device = makedev ((int)maj_dev, (int)min_dev);
1660 if ((device == 0) &&
1665 while(g_ascii_isspace (*p)) ++p;
1666 /* p now points to the filename */
1668 mod = g_new0 (WapiProcModule, 1);
1669 mod->address_start = address_start;
1670 mod->address_end = address_end;
1671 mod->perms = g_strdup (prot_buf);
1672 mod->address_offset = address_offset;
1673 mod->device = device;
1675 mod->filename = g_strdup (g_strstrip (p));
1677 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1678 ret = g_slist_prepend (ret, mod);
1680 free_procmodule (mod);
1684 ret = g_slist_reverse (ret);
1690 static gboolean match_procname_to_modulename (char *procname, char *modulename)
1692 char* lastsep = NULL;
1693 char* lastsep2 = NULL;
1696 gboolean result = FALSE;
1698 if (procname == NULL || modulename == NULL)
1701 DEBUG ("%s: procname=\"%s\", modulename=\"%s\"", __func__, procname, modulename);
1702 pname = mono_path_resolve_symlinks (procname);
1703 mname = mono_path_resolve_symlinks (modulename);
1705 if (!strcmp (pname, mname))
1709 lastsep = strrchr (mname, '/');
1711 if (!strcmp (lastsep+1, pname))
1714 lastsep2 = strrchr (pname, '/');
1717 if (!strcmp (lastsep+1, lastsep2+1))
1720 if (!strcmp (mname, lastsep2+1))
1730 DEBUG ("%s: result is %d", __func__, result);
1734 #if !(defined(USE_OSX_LOADER) || defined(USE_BSD_LOADER) || defined(USE_HAIKU_LOADER))
1736 open_process_map (int pid, const char *mode)
1739 const char *proc_path[] = {
1740 "/proc/%d/maps", /* GNU/Linux */
1741 "/proc/%d/map", /* FreeBSD */
1747 for (i = 0; fp == NULL && proc_path [i]; i++) {
1748 filename = g_strdup_printf (proc_path[i], pid);
1749 fp = fopen (filename, mode);
1757 static char *get_process_name_from_proc (pid_t pid);
1759 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1760 guint32 size, guint32 *needed)
1762 WapiHandle_process *process_handle;
1763 #if !defined(USE_OSX_LOADER) && !defined(USE_BSD_LOADER)
1766 GSList *mods = NULL;
1767 WapiProcModule *module;
1768 guint32 count, avail = size / sizeof(gpointer);
1771 char *proc_name = NULL;
1773 /* Store modules in an array of pointers (main module as
1774 * modules[0]), using the load address for each module as a
1775 * token. (Use 'NULL' as an alternative for the main module
1776 * so that the simple implementation can just return one item
1777 * for now.) Get the info from /proc/<pid>/maps on linux,
1778 * /proc/<pid>/map on FreeBSD, other systems will have to
1779 * implement /dev/kmem reading or whatever other horrid
1780 * technique is needed.
1782 if (size < sizeof(gpointer))
1785 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1786 pid = WAPI_HANDLE_TO_PID (process);
1787 proc_name = get_process_name_from_proc (pid);
1789 process_handle = lookup_process_handle (process);
1790 if (!process_handle) {
1791 DEBUG ("%s: Can't find process %p", __func__, process);
1795 pid = process_handle->id;
1796 proc_name = g_strdup (process_handle->proc_name);
1799 #if defined(USE_OSX_LOADER) || defined(USE_BSD_LOADER) || defined(USE_HAIKU_LOADER)
1800 mods = load_modules ();
1803 *needed = sizeof(gpointer);
1807 fp = open_process_map (pid, "r");
1809 /* No /proc/<pid>/maps so just return the main module
1813 *needed = sizeof(gpointer);
1817 mods = load_modules (fp);
1820 count = g_slist_length (mods);
1822 /* count + 1 to leave slot 0 for the main module */
1823 *needed = sizeof(gpointer) * (count + 1);
1826 * Use the NULL shortcut, as the first line in
1827 * /proc/<pid>/maps isn't the executable, and we need
1828 * that first in the returned list. Check the module name
1829 * to see if it ends with the proc name and substitute
1830 * the first entry with it. FIXME if this turns out to
1834 for (i = 0; i < (avail - 1) && i < count; i++) {
1835 module = (WapiProcModule *)g_slist_nth_data (mods, i);
1836 if (modules[0] != NULL)
1837 modules[i] = module->address_start;
1838 else if (match_procname_to_modulename (proc_name, module->filename))
1839 modules[0] = module->address_start;
1841 modules[i + 1] = module->address_start;
1844 for (i = 0; i < count; i++) {
1845 free_procmodule ((WapiProcModule *)g_slist_nth_data (mods, i));
1847 g_slist_free (mods);
1854 get_process_name_from_proc (pid_t pid)
1856 #if defined(USE_BSD_LOADER)
1859 struct kinfo_proc *pi;
1860 #elif defined(USE_OSX_LOADER)
1861 #if !(!defined (__mono_ppc__) && defined (TARGET_OSX))
1863 struct kinfo_proc *pi;
1864 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
1868 char *filename = NULL;
1873 #if defined(PLATFORM_SOLARIS)
1874 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
1875 if ((fp = fopen (filename, "r")) != NULL) {
1879 nread = fread (&info, sizeof (info), 1, fp);
1881 ret = g_strdup (info.pr_fname);
1887 #elif defined(USE_OSX_LOADER)
1888 #if !defined (__mono_ppc__) && defined (TARGET_OSX)
1889 /* No proc name on OSX < 10.5 nor ppc nor iOS */
1890 memset (buf, '\0', sizeof(buf));
1891 proc_name (pid, buf, sizeof(buf));
1893 // Fixes proc_name triming values to 15 characters #32539
1894 if (strlen (buf) >= MAXCOMLEN - 1) {
1895 char path_buf [PROC_PIDPATHINFO_MAXSIZE];
1899 memset (path_buf, '\0', sizeof(path_buf));
1900 path_len = proc_pidpath (pid, path_buf, sizeof(path_buf));
1902 if (path_len > 0 && path_len < sizeof(path_buf)) {
1903 name_buf = path_buf + path_len;
1904 for(;name_buf > path_buf; name_buf--) {
1905 if (name_buf [0] == '/') {
1911 if (memcmp (buf, name_buf, MAXCOMLEN - 1) == 0)
1912 ret = g_strdup (name_buf);
1916 if (ret == NULL && strlen (buf) > 0)
1917 ret = g_strdup (buf);
1919 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0)
1922 if ((pi = malloc(size)) == NULL)
1925 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
1926 if (errno == ENOMEM) {
1928 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__);
1933 if (strlen (pi->kp_proc.p_comm) > 0)
1934 ret = g_strdup (pi->kp_proc.p_comm);
1938 #elif defined(USE_BSD_LOADER)
1939 #if defined(__FreeBSD__)
1941 mib [1] = KERN_PROC;
1942 mib [2] = KERN_PROC_PID;
1944 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0) {
1945 DEBUG ("%s: sysctl() failed: %d", __func__, errno);
1949 if ((pi = malloc(size)) == NULL)
1952 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
1953 if (errno == ENOMEM) {
1955 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__);
1960 if (strlen (pi->ki_comm) > 0)
1961 ret = g_strdup (pi->ki_comm);
1963 #elif defined(__OpenBSD__)
1965 mib [1] = KERN_PROC;
1966 mib [2] = KERN_PROC_PID;
1968 mib [4] = sizeof(struct kinfo_proc);
1972 if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0) {
1973 DEBUG ("%s: sysctl() failed: %d", __func__, errno);
1977 if ((pi = malloc(size)) == NULL)
1980 mib[5] = (int)(size / sizeof(struct kinfo_proc));
1982 if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
1983 (size != sizeof (struct kinfo_proc))) {
1984 if (errno == ENOMEM) {
1991 if (strlen (pi->p_comm) > 0)
1992 ret = g_strdup (pi->p_comm);
1996 #elif defined(USE_HAIKU_LOADER)
1997 image_info imageInfo;
2000 if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
2001 ret = g_strdup (imageInfo.name);
2004 memset (buf, '\0', sizeof(buf));
2005 filename = g_strdup_printf ("/proc/%d/exe", pid);
2006 if (readlink (filename, buf, 255) > 0) {
2007 ret = g_strdup (buf);
2015 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
2016 if ((fp = fopen (filename, "r")) != NULL) {
2017 if (fgets (buf, 256, fp) != NULL) {
2018 ret = g_strdup (buf);
2029 filename = g_strdup_printf ("/proc/%d/stat", pid);
2030 if ((fp = fopen (filename, "r")) != NULL) {
2031 if (fgets (buf, 256, fp) != NULL) {
2034 start = strchr (buf, '(');
2035 if (start != NULL) {
2036 end = strchr (start + 1, ')');
2039 ret = g_strndup (start + 1,
2054 * wapi_process_get_path:
2056 * Return the full path of the executable of the process PID, or NULL if it cannot be determined.
2057 * Returns malloc-ed memory.
2060 wapi_process_get_path (pid_t pid)
2062 #if defined(PLATFORM_MACOSX) && !defined(__mono_ppc__) && defined(TARGET_OSX)
2063 char buf [PROC_PIDPATHINFO_MAXSIZE];
2066 res = proc_pidpath (pid, buf, sizeof (buf));
2069 if (buf [0] == '\0')
2071 return g_strdup (buf);
2073 return get_process_name_from_proc (pid);
2078 * wapi_process_set_cli_launcher:
2080 * Set the full path of the runtime executable used to launch managed exe's.
2083 wapi_process_set_cli_launcher (char *path)
2085 g_free (cli_launcher);
2086 cli_launcher = path ? g_strdup (path) : NULL;
2090 get_module_name (gpointer process, gpointer module,
2091 gunichar2 *basename, guint32 size,
2094 WapiHandle_process *process_handle;
2096 gunichar2 *procname;
2097 char *procname_ext = NULL;
2100 #if !defined(USE_OSX_LOADER) && !defined(USE_BSD_LOADER)
2103 GSList *mods = NULL;
2104 WapiProcModule *found_module;
2107 char *proc_name = NULL;
2109 DEBUG ("%s: Getting module base name, process handle %p module %p",
2110 __func__, process, module);
2112 size = size * sizeof (gunichar2); /* adjust for unicode characters */
2114 if (basename == NULL || size == 0)
2117 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2118 /* This is a pseudo handle */
2119 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2120 proc_name = get_process_name_from_proc (pid);
2122 process_handle = lookup_process_handle (process);
2123 if (!process_handle) {
2124 DEBUG ("%s: Can't find process %p", __func__,
2129 pid = process_handle->id;
2130 proc_name = g_strdup (process_handle->proc_name);
2133 /* Look up the address in /proc/<pid>/maps */
2134 #if defined(USE_OSX_LOADER) || defined(USE_BSD_LOADER) || defined(USE_HAIKU_LOADER)
2135 mods = load_modules ();
2137 fp = open_process_map (pid, "r");
2139 if (errno == EACCES && module == NULL && base == TRUE) {
2140 procname_ext = get_process_name_from_proc (pid);
2142 /* No /proc/<pid>/maps, so just return failure
2149 mods = load_modules (fp);
2153 count = g_slist_length (mods);
2155 /* If module != NULL compare the address.
2156 * If module == NULL we are looking for the main module.
2157 * The best we can do for now check it the module name end with the process name.
2159 for (i = 0; i < count; i++) {
2160 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2161 if (procname_ext == NULL &&
2162 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2163 (module != NULL && found_module->address_start == module))) {
2165 procname_ext = g_path_get_basename (found_module->filename);
2167 procname_ext = g_strdup (found_module->filename);
2170 free_procmodule (found_module);
2173 if (procname_ext == NULL) {
2174 /* If it's *still* null, we might have hit the
2175 * case where reading /proc/$pid/maps gives an
2176 * empty file for this user.
2178 procname_ext = get_process_name_from_proc (pid);
2181 g_slist_free (mods);
2185 DEBUG ("%s: Process name is [%s]", __func__,
2188 procname = mono_unicode_from_external (procname_ext, &bytes);
2189 if (procname == NULL) {
2191 g_free (procname_ext);
2197 /* Add the terminator */
2201 DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2203 memcpy (basename, procname, size);
2205 DEBUG ("%s: Size %d larger than needed (%ld)",
2206 __func__, size, bytes);
2208 memcpy (basename, procname, bytes);
2212 g_free (procname_ext);
2221 get_module_filename (gpointer process, gpointer module,
2222 gunichar2 *basename, guint32 size)
2227 gunichar2 *proc_path;
2229 size *= sizeof (gunichar2); /* adjust for unicode characters */
2231 if (basename == NULL || size == 0)
2234 pid = GetProcessId (process);
2236 path = wapi_process_get_path (pid);
2240 proc_path = mono_unicode_from_external (path, &bytes);
2243 if (proc_path == NULL)
2248 /* Add the terminator */
2252 DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2254 memcpy (basename, proc_path, size);
2256 DEBUG ("%s: Size %d larger than needed (%ld)",
2257 __func__, size, bytes);
2259 memcpy (basename, proc_path, bytes);
2268 GetModuleBaseName (gpointer process, gpointer module,
2269 gunichar2 *basename, guint32 size)
2271 return get_module_name (process, module, basename, size, TRUE);
2275 GetModuleFileNameEx (gpointer process, gpointer module,
2276 gunichar2 *filename, guint32 size)
2278 return get_module_filename (process, module, filename, size);
2282 GetModuleInformation (gpointer process, gpointer module,
2283 WapiModuleInfo *modinfo, guint32 size)
2285 WapiHandle_process *process_handle;
2287 #if !defined(USE_OSX_LOADER) && !defined(USE_BSD_LOADER)
2290 GSList *mods = NULL;
2291 WapiProcModule *found_module;
2294 gboolean ret = FALSE;
2295 char *proc_name = NULL;
2297 DEBUG ("%s: Getting module info, process handle %p module %p",
2298 __func__, process, module);
2300 if (modinfo == NULL || size < sizeof (WapiModuleInfo))
2303 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2304 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2305 proc_name = get_process_name_from_proc (pid);
2307 process_handle = lookup_process_handle (process);
2308 if (!process_handle) {
2309 DEBUG ("%s: Can't find process %p", __func__,
2314 pid = process_handle->id;
2315 proc_name = g_strdup (process_handle->proc_name);
2318 #if defined(USE_OSX_LOADER) || defined(USE_BSD_LOADER) || defined(USE_HAIKU_LOADER)
2319 mods = load_modules ();
2321 /* Look up the address in /proc/<pid>/maps */
2322 if ((fp = open_process_map (pid, "r")) == NULL) {
2323 /* No /proc/<pid>/maps, so just return failure
2329 mods = load_modules (fp);
2332 count = g_slist_length (mods);
2334 /* If module != NULL compare the address.
2335 * If module == NULL we are looking for the main module.
2336 * The best we can do for now check it the module name end with the process name.
2338 for (i = 0; i < count; i++) {
2339 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2341 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2342 (module != NULL && found_module->address_start == module))) {
2343 modinfo->lpBaseOfDll = found_module->address_start;
2344 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2345 modinfo->EntryPoint = found_module->address_offset;
2349 free_procmodule (found_module);
2352 g_slist_free (mods);
2359 GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2361 WapiHandle_process *process_handle;
2363 if (min == NULL || max == NULL)
2364 /* Not sure if w32 allows NULLs here or not */
2367 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2368 /* This is a pseudo handle, so just fail for now */
2371 process_handle = lookup_process_handle (process);
2372 if (!process_handle) {
2373 DEBUG ("%s: Can't find process %p", __func__, process);
2378 *min = process_handle->min_working_set;
2379 *max = process_handle->max_working_set;
2385 SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2387 WapiHandle_process *process_handle;
2389 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2390 /* This is a pseudo handle, so just fail for now
2394 process_handle = lookup_process_handle (process);
2395 if (!process_handle) {
2396 DEBUG ("%s: Can't find process %p", __func__, process);
2401 process_handle->min_working_set = min;
2402 process_handle->max_working_set = max;
2409 TerminateProcess (gpointer process, gint32 exitCode)
2411 #if defined(HAVE_KILL)
2412 WapiHandle_process *process_handle;
2417 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2418 /* This is a pseudo handle */
2419 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2421 process_handle = lookup_process_handle (process);
2422 if (!process_handle) {
2423 DEBUG ("%s: Can't find process %p", __func__, process);
2424 SetLastError (ERROR_INVALID_HANDLE);
2427 pid = process_handle->id;
2430 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2431 ret = kill (pid, signo);
2435 SetLastError (ERROR_INVALID_PARAMETER);
2438 SetLastError (ERROR_ACCESS_DENIED);
2441 SetLastError (ERROR_PROC_NOT_FOUND);
2444 SetLastError (ERROR_GEN_FAILURE);
2450 g_error ("kill() is not supported by this platform");
2456 GetPriorityClass (gpointer process)
2458 #ifdef HAVE_GETPRIORITY
2459 WapiHandle_process *process_handle;
2463 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2464 /* This is a pseudo handle */
2465 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2467 process_handle = lookup_process_handle (process);
2468 if (!process_handle) {
2469 SetLastError (ERROR_INVALID_HANDLE);
2472 pid = process_handle->id;
2476 ret = getpriority (PRIO_PROCESS, pid);
2477 if (ret == -1 && errno != 0) {
2481 SetLastError (ERROR_ACCESS_DENIED);
2484 SetLastError (ERROR_PROC_NOT_FOUND);
2487 SetLastError (ERROR_GEN_FAILURE);
2493 return NORMAL_PRIORITY_CLASS;
2495 return REALTIME_PRIORITY_CLASS;
2497 return HIGH_PRIORITY_CLASS;
2499 return ABOVE_NORMAL_PRIORITY_CLASS;
2501 return IDLE_PRIORITY_CLASS;
2503 return BELOW_NORMAL_PRIORITY_CLASS;
2505 return NORMAL_PRIORITY_CLASS;
2507 SetLastError (ERROR_NOT_SUPPORTED);
2513 SetPriorityClass (gpointer process, guint32 priority_class)
2515 #ifdef HAVE_SETPRIORITY
2516 WapiHandle_process *process_handle;
2521 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2522 /* This is a pseudo handle */
2523 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2525 process_handle = lookup_process_handle (process);
2526 if (!process_handle) {
2527 SetLastError (ERROR_INVALID_HANDLE);
2530 pid = process_handle->id;
2533 switch (priority_class) {
2534 case IDLE_PRIORITY_CLASS:
2537 case BELOW_NORMAL_PRIORITY_CLASS:
2540 case NORMAL_PRIORITY_CLASS:
2543 case ABOVE_NORMAL_PRIORITY_CLASS:
2546 case HIGH_PRIORITY_CLASS:
2549 case REALTIME_PRIORITY_CLASS:
2553 SetLastError (ERROR_INVALID_PARAMETER);
2557 ret = setpriority (PRIO_PROCESS, pid, prio);
2562 SetLastError (ERROR_ACCESS_DENIED);
2565 SetLastError (ERROR_PROC_NOT_FOUND);
2568 SetLastError (ERROR_GEN_FAILURE);
2574 SetLastError (ERROR_NOT_SUPPORTED);
2580 mono_processes_cleanup (void)
2582 struct MonoProcess *mp;
2583 struct MonoProcess *prev = NULL;
2584 GSList *finished = NULL;
2586 gpointer unref_handle;
2588 DEBUG ("%s", __func__);
2590 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2591 if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
2594 for (mp = mono_processes; mp; mp = mp->next) {
2595 if (mp->pid == 0 && mp->handle) {
2596 /* This process has exited and we need to remove the artifical ref
2598 mono_os_mutex_lock (&mono_processes_mutex);
2599 unref_handle = mp->handle;
2601 mono_os_mutex_unlock (&mono_processes_mutex);
2603 _wapi_handle_unref (unref_handle);
2608 * Remove processes which exited from the mono_processes list.
2609 * We need to synchronize with the sigchld handler here, which runs
2610 * asynchronously. The handler requires that the mono_processes list
2613 mono_os_mutex_lock (&mono_processes_mutex);
2615 mp = mono_processes;
2617 if (mp->handle_count == 0 && mp->freeable) {
2620 * This code can run parallel with the sigchld handler, but the
2621 * modifications it makes are safe.
2623 if (mp == mono_processes)
2624 mono_processes = mp->next;
2626 prev->next = mp->next;
2627 finished = g_slist_prepend (finished, mp);
2636 mono_memory_barrier ();
2638 for (l = finished; l; l = l->next) {
2640 * All the entries in the finished list are unlinked from mono_processes, and
2641 * they have the 'finished' flag set, which means the sigchld handler is done
2644 mp = (MonoProcess *)l->data;
2645 mono_os_sem_destroy (&mp->exit_sem);
2648 g_slist_free (finished);
2650 mono_os_mutex_unlock (&mono_processes_mutex);
2652 DEBUG ("%s done", __func__);
2654 InterlockedDecrement (&mono_processes_cleaning_up);
2658 process_close (gpointer handle, gpointer data)
2660 WapiHandle_process *process_handle;
2662 DEBUG ("%s", __func__);
2664 process_handle = (WapiHandle_process *) data;
2665 g_free (process_handle->proc_name);
2666 process_handle->proc_name = NULL;
2667 if (process_handle->mono_process)
2668 InterlockedDecrement (&process_handle->mono_process->handle_count);
2669 mono_processes_cleanup ();
2673 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
2677 struct MonoProcess *p;
2679 DEBUG ("SIG CHILD handler for pid: %i\n", info->si_pid);
2683 pid = waitpid (-1, &status, WNOHANG);
2684 } while (pid == -1 && errno == EINTR);
2689 DEBUG ("child ended: %i", pid);
2692 * This can run concurrently with the code in the rest of this module.
2694 for (p = mono_processes; p; p = p->next) {
2695 if (p->pid == pid) {
2700 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2702 mono_os_sem_post (&p->exit_sem);
2703 mono_memory_barrier ();
2704 /* Mark this as freeable, the pointer becomes invalid afterwards */
2709 DEBUG ("SIG CHILD handler: done looping.");
2715 process_add_sigchld_handler (void)
2718 struct sigaction sa;
2720 sa.sa_sigaction = mono_sigchld_signal_handler;
2721 sigemptyset (&sa.sa_mask);
2722 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2723 g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2724 DEBUG ("Added SIGCHLD handler");
2729 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2731 WapiHandle_process *process_handle;
2732 pid_t pid G_GNUC_UNUSED, ret;
2736 struct MonoProcess *mp;
2738 /* FIXME: We can now easily wait on processes that aren't our own children,
2739 * but WaitFor*Object won't call us for pseudo handles. */
2740 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2742 DEBUG ("%s (%p, %u)", __func__, handle, timeout);
2744 process_handle = lookup_process_handle (handle);
2745 if (!process_handle) {
2746 g_warning ("%s: error looking up process handle %p", __func__, handle);
2750 if (process_handle->exited) {
2751 /* We've already done this one */
2752 DEBUG ("%s (%p, %u): Process already exited", __func__, handle, timeout);
2753 return WAIT_OBJECT_0;
2756 pid = process_handle->id;
2758 DEBUG ("%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2760 /* We don't need to lock mono_processes here, the entry
2761 * has a handle_count > 0 which means it will not be freed. */
2762 mp = process_handle->mono_process;
2765 start = mono_msec_ticks ();
2769 if (timeout != INFINITE) {
2770 DEBUG ("%s (%p, %u): waiting on semaphore for %li ms...",
2771 __func__, handle, timeout, (timeout - (now - start)));
2772 ret = mono_os_sem_timedwait (&mp->exit_sem, (timeout - (now - start)), alertable ? MONO_SEM_FLAGS_ALERTABLE : MONO_SEM_FLAGS_NONE);
2774 DEBUG ("%s (%p, %u): waiting on semaphore forever...",
2775 __func__, handle, timeout);
2776 ret = mono_os_sem_wait (&mp->exit_sem, alertable ? MONO_SEM_FLAGS_ALERTABLE : MONO_SEM_FLAGS_NONE);
2779 if (ret == -1 && errno != EINTR && errno != ETIMEDOUT) {
2780 DEBUG ("%s (%p, %u): sem_timedwait failure: %s",
2781 __func__, handle, timeout, g_strerror (errno));
2782 /* Should we return a failure here? */
2786 /* Success, process has exited */
2787 mono_os_sem_post (&mp->exit_sem);
2792 DEBUG ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
2793 return WAIT_TIMEOUT;
2796 now = mono_msec_ticks ();
2797 if (now - start >= timeout) {
2798 DEBUG ("%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
2799 return WAIT_TIMEOUT;
2802 if (alertable && _wapi_thread_cur_apc_pending ()) {
2803 DEBUG ("%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
2804 return WAIT_IO_COMPLETION;
2808 /* Process must have exited */
2809 DEBUG ("%s (%p, %u): Waited successfully", __func__, handle, timeout);
2811 ret = _wapi_handle_lock_shared_handles ();
2812 g_assert (ret == 0);
2814 status = mp ? mp->status : 0;
2815 if (WIFSIGNALED (status))
2816 process_handle->exitstatus = 128 + WTERMSIG (status);
2818 process_handle->exitstatus = WEXITSTATUS (status);
2819 _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
2821 process_handle->exited = TRUE;
2823 DEBUG ("%s (%p, %u): Setting pid %d signalled, exit status %d",
2824 __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
2826 _wapi_handle_set_signal_state (handle, TRUE, TRUE);
2828 _wapi_handle_unlock_shared_handles ();
2830 return WAIT_OBJECT_0;
2834 wapi_processes_cleanup (void)
2836 g_free (cli_launcher);