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/misc-private.h>
87 #include <mono/io-layer/process-private.h>
88 #include <mono/io-layer/threads.h>
89 #include <mono/utils/strenc.h>
90 #include <mono/utils/mono-path.h>
91 #include <mono/io-layer/timefuncs-private.h>
92 #include <mono/utils/mono-time.h>
93 #include <mono/utils/mono-membar.h>
94 #include <mono/utils/mono-mutex.h>
95 #include <mono/utils/mono-signal-handler.h>
96 #include <mono/utils/mono-proclib.h>
98 /* The process' environment strings */
99 #if defined(__APPLE__) && !defined (__arm__) && !defined (__aarch64__)
100 /* Apple defines this in crt_externs.h but doesn't provide that header for
101 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
102 * in fact exist on all implementations (so far)
104 char ***_NSGetEnviron(void);
105 #define environ (*_NSGetEnviron())
107 extern char **environ;
111 #define DEBUG(...) g_message(__VA_ARGS__)
112 #define DEBUG_ENABLED 1
117 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable);
118 static void process_close (gpointer handle, gpointer data);
119 static gboolean is_pid_valid (pid_t pid);
121 #if !(defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__HAIKU__))
123 open_process_map (int pid, const char *mode);
126 struct _WapiHandleOps _wapi_process_ops = {
127 process_close, /* close_shared */
131 process_wait, /* special_wait */
136 static struct sigaction previous_chld_sa;
138 static mono_once_t process_sig_chld_once = MONO_ONCE_INIT;
139 static void process_add_sigchld_handler (void);
141 /* The signal-safe logic to use mono_processes goes like this:
142 * - The list must be safe to traverse for the signal handler at all times.
143 * It's safe to: prepend an entry (which is a single store to 'mono_processes'),
144 * unlink an entry (assuming the unlinked entry isn't freed and doesn't
145 * change its 'next' pointer so that it can still be traversed).
146 * When cleaning up we first unlink an entry, then we verify that
147 * the read lock isn't locked. Then we can free the entry, since
148 * we know that nobody is using the old version of the list (including
149 * the unlinked entry).
150 * We also need to lock when adding and cleaning up so that those two
151 * operations don't mess with eachother. (This lock is not used in the
154 static struct MonoProcess *mono_processes = NULL;
155 static volatile gint32 mono_processes_cleaning_up = 0;
156 static mono_mutex_t mono_processes_mutex;
157 static void mono_processes_cleanup (void);
159 static gpointer current_process;
160 static char *cli_launcher;
162 static WapiHandle_process *
163 lookup_process_handle (gpointer handle)
165 WapiHandle_process *process_data;
168 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
169 (gpointer *)&process_data);
175 /* Check if a pid is valid - i.e. if a process exists with this pid. */
177 is_pid_valid (pid_t pid)
179 gboolean result = FALSE;
181 #if defined(HOST_WATCHOS)
182 result = TRUE; // TODO: Rewrite using sysctl
183 #elif defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__)
184 if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
186 #elif defined(__HAIKU__)
188 if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
191 char *dir = g_strdup_printf ("/proc/%d", pid);
192 if (!access (dir, F_OK))
201 process_set_defaults (WapiHandle_process *process_handle)
203 /* These seem to be the defaults on w2k */
204 process_handle->min_working_set = 204800;
205 process_handle->max_working_set = 1413120;
207 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
211 len16 (const gunichar2 *str)
222 utf16_concat (const gunichar2 *first, ...)
229 va_start (args, first);
230 total += len16 (first);
231 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
236 ret = g_new (gunichar2, total + 1);
242 for (s = first; *s != 0; s++)
244 va_start (args, first);
245 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
248 for (p = s; *p != 0; p++)
256 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
257 static const gunichar2 *utf16_space = utf16_space_bytes;
258 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
259 static const gunichar2 *utf16_quote = utf16_quote_bytes;
264 print_utf16 (gunichar2 *str)
268 res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
269 g_print ("%s\n", res);
274 /* Implemented as just a wrapper around CreateProcess () */
276 ShellExecuteEx (WapiShellExecuteInfo *sei)
279 WapiProcessInformation process_info;
283 /* w2k just segfaults here, but we can do better than
286 SetLastError (ERROR_INVALID_PARAMETER);
290 if (sei->lpFile == NULL)
291 /* w2k returns TRUE for this, for some reason. */
294 /* Put both executable and parameters into the second argument
295 * to CreateProcess (), so it searches $PATH. The conversion
296 * into and back out of utf8 is because there is no
297 * g_strdup_printf () equivalent for gunichar2 :-(
299 args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
301 SetLastError (ERROR_INVALID_DATA);
304 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
305 CREATE_UNICODE_ENVIRONMENT, NULL,
306 sei->lpDirectory, NULL, &process_info);
309 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
313 static char *handler;
314 static gunichar2 *handler_utf16;
316 if (handler_utf16 == (gunichar2 *)-1)
319 #ifdef PLATFORM_MACOSX
320 handler = g_strdup ("/usr/bin/open");
323 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
324 * if that fails, try to use gnome-open, then kfmclient
326 handler = g_find_program_in_path ("xdg-open");
327 if (handler == NULL){
328 handler = g_find_program_in_path ("gnome-open");
329 if (handler == NULL){
330 handler = g_find_program_in_path ("kfmclient");
331 if (handler == NULL){
332 handler_utf16 = (gunichar2 *) -1;
335 /* kfmclient needs exec argument */
337 handler = g_strconcat (old, " exec",
344 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
347 /* Put quotes around the filename, in case it's a url
348 * that contains #'s (CreateProcess() calls
349 * g_shell_parse_argv(), which deliberately throws
350 * away anything after an unquoted #). Fixes bug
353 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
354 sei->lpFile, utf16_quote,
355 sei->lpParameters == NULL ? NULL : utf16_space,
356 sei->lpParameters, NULL);
358 SetLastError (ERROR_INVALID_DATA);
361 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
362 CREATE_UNICODE_ENVIRONMENT, NULL,
363 sei->lpDirectory, NULL, &process_info);
366 if (GetLastError () != ERROR_OUTOFMEMORY)
367 SetLastError (ERROR_INVALID_DATA);
370 /* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
371 CloseHandle (process_info.hProcess);
372 process_info.hProcess = NULL;
375 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS)
376 sei->hProcess = process_info.hProcess;
378 CloseHandle (process_info.hProcess);
384 is_managed_binary (const char *filename)
386 int original_errno = errno;
387 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
388 int file = open (filename, O_RDONLY | O_LARGEFILE);
390 int file = open (filename, O_RDONLY);
393 unsigned char buffer[8];
394 off_t file_size, optional_header_offset;
395 off_t pe_header_offset;
396 gboolean managed = FALSE;
398 guint32 first_word, second_word;
400 /* If we are unable to open the file, then we definitely
401 * can't say that it is managed. The child mono process
402 * probably wouldn't be able to open it anyway.
405 errno = original_errno;
409 /* Retrieve the length of the file for future sanity checks. */
410 file_size = lseek (file, 0, SEEK_END);
411 lseek (file, 0, SEEK_SET);
413 /* We know we need to read a header field at offset 60. */
417 num_read = read (file, buffer, 2);
419 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
422 new_offset = lseek (file, 60, SEEK_SET);
424 if (new_offset != 60)
427 num_read = read (file, buffer, 4);
431 pe_header_offset = buffer[0]
436 if (pe_header_offset + 24 > file_size)
439 new_offset = lseek (file, pe_header_offset, SEEK_SET);
441 if (new_offset != pe_header_offset)
444 num_read = read (file, buffer, 4);
446 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
450 * Verify that the header we want in the optional header data
451 * is present in this binary.
453 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
455 if (new_offset != pe_header_offset + 20)
458 num_read = read (file, buffer, 2);
460 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
463 /* Read the CLR header address and size fields. These will be
464 * zero if the binary is not managed.
466 optional_header_offset = pe_header_offset + 24;
467 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
469 if (new_offset != optional_header_offset + 208)
472 num_read = read (file, buffer, 8);
474 /* We are not concerned with endianness, only with
475 * whether it is zero or not.
477 first_word = *(guint32 *)&buffer[0];
478 second_word = *(guint32 *)&buffer[4];
480 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
487 errno = original_errno;
492 CreateProcessWithLogonW (const gunichar2 *username,
493 const gunichar2 *domain,
494 const gunichar2 *password,
495 const guint32 logonFlags,
496 const gunichar2 *appname,
497 const gunichar2 *cmdline,
498 guint32 create_flags,
500 const gunichar2 *cwd,
501 WapiStartupInfo *startup,
502 WapiProcessInformation *process_info)
504 /* FIXME: use user information */
505 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
509 is_readable_or_executable (const char *prog)
512 int a = access (prog, R_OK);
513 int b = access (prog, X_OK);
514 if (a != 0 && b != 0)
516 if (stat (prog, &buf))
518 if (S_ISREG (buf.st_mode))
524 is_executable (const char *prog)
527 if (access (prog, X_OK) != 0)
529 if (stat (prog, &buf))
531 if (S_ISREG (buf.st_mode))
537 switch_dir_separators (char *path)
539 size_t i, pathLength = strlen(path);
541 /* Turn all the slashes round the right way, except for \' */
542 /* There are probably other characters that need to be excluded as well. */
543 for (i = 0; i < pathLength; i++) {
544 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' )
549 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
550 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
551 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
552 gboolean inherit_handles, guint32 create_flags,
553 gpointer new_environ, const gunichar2 *cwd,
554 WapiStartupInfo *startup,
555 WapiProcessInformation *process_info)
557 #if defined (HAVE_FORK) && defined (HAVE_EXECVE)
558 char *cmd = NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL;
559 char *dir = NULL, **env_strings = NULL, **argv = NULL;
560 guint32 i, env_count = 0;
561 gboolean ret = FALSE;
563 WapiHandle_process process_handle = {0}, *process_handle_data;
565 int in_fd, out_fd, err_fd;
568 int startup_pipe [2] = {-1, -1};
570 struct MonoProcess *mono_process;
571 gboolean fork_failed = FALSE;
573 mono_once (&process_sig_chld_once, process_add_sigchld_handler);
575 /* appname and cmdline specify the executable and its args:
577 * If appname is not NULL, it is the name of the executable.
578 * Otherwise the executable is the first token in cmdline.
580 * Executable searching:
582 * If appname is not NULL, it can specify the full path and
583 * file name, or else a partial name and the current directory
584 * will be used. There is no additional searching.
586 * If appname is NULL, the first whitespace-delimited token in
587 * cmdline is used. If the name does not contain a full
588 * directory path, the search sequence is:
590 * 1) The directory containing the current process
591 * 2) The current working directory
592 * 3) The windows system directory (Ignored)
593 * 4) The windows directory (Ignored)
596 * Just to make things more interesting, tokens can contain
597 * white space if they are surrounded by quotation marks. I'm
598 * beginning to understand just why windows apps are generally
599 * so crap, with an API like this :-(
601 if (appname != NULL) {
602 cmd = mono_unicode_to_external (appname);
604 DEBUG ("%s: unicode conversion returned NULL",
607 SetLastError (ERROR_PATH_NOT_FOUND);
611 switch_dir_separators(cmd);
614 if (cmdline != NULL) {
615 args = mono_unicode_to_external (cmdline);
617 DEBUG ("%s: unicode conversion returned NULL", __func__);
619 SetLastError (ERROR_PATH_NOT_FOUND);
625 dir = mono_unicode_to_external (cwd);
627 DEBUG ("%s: unicode conversion returned NULL", __func__);
629 SetLastError (ERROR_PATH_NOT_FOUND);
633 /* Turn all the slashes round the right way */
634 switch_dir_separators(dir);
638 /* We can't put off locating the executable any longer :-( */
641 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
642 /* Strip off the drive letter. I can't
643 * believe that CP/M holdover is still
646 g_memmove (cmd, cmd+2, strlen (cmd)-2);
647 cmd[strlen (cmd)-2] = '\0';
650 unquoted = g_shell_unquote (cmd, NULL);
651 if (unquoted[0] == '/') {
652 /* Assume full path given */
653 prog = g_strdup (unquoted);
655 /* Executable existing ? */
656 if (!is_readable_or_executable (prog)) {
657 DEBUG ("%s: Couldn't find executable %s",
660 SetLastError (ERROR_FILE_NOT_FOUND);
664 /* Search for file named by cmd in the current
667 char *curdir = g_get_current_dir ();
669 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
672 /* And make sure it's readable */
673 if (!is_readable_or_executable (prog)) {
674 DEBUG ("%s: Couldn't find executable %s",
677 SetLastError (ERROR_FILE_NOT_FOUND);
683 args_after_prog = args;
688 /* Dig out the first token from args, taking quotation
692 /* First, strip off all leading whitespace */
693 args = g_strchug (args);
695 /* args_after_prog points to the contents of args
696 * after token has been set (otherwise argv[0] is
699 args_after_prog = args;
701 /* Assume the opening quote will always be the first
704 if (args[0] == '\"' || args [0] == '\'') {
706 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
707 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
708 /* We found the first token */
709 token = g_strndup (args+1, i-1);
710 args_after_prog = g_strchug (args + i + 1);
712 /* Quotation mark appeared in the
713 * middle of the token. Just give the
714 * whole first token, quotes and all,
721 /* No quote mark, or malformed */
722 for (i = 0; args[i] != '\0'; i++) {
723 if (g_ascii_isspace (args[i])) {
724 token = g_strndup (args, i);
725 args_after_prog = args + i + 1;
731 if (token == NULL && args[0] != '\0') {
732 /* Must be just one token in the string */
733 token = g_strdup (args);
734 args_after_prog = NULL;
739 DEBUG ("%s: Couldn't find what to exec", __func__);
741 SetLastError (ERROR_PATH_NOT_FOUND);
745 /* Turn all the slashes round the right way. Only for
748 switch_dir_separators(token);
750 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
751 /* Strip off the drive letter. I can't
752 * believe that CP/M holdover is still
755 g_memmove (token, token+2, strlen (token)-2);
756 token[strlen (token)-2] = '\0';
759 if (token[0] == '/') {
760 /* Assume full path given */
761 prog = g_strdup (token);
763 /* Executable existing ? */
764 if (!is_readable_or_executable (prog)) {
765 DEBUG ("%s: Couldn't find executable %s",
768 SetLastError (ERROR_FILE_NOT_FOUND);
772 char *curdir = g_get_current_dir ();
774 /* FIXME: Need to record the directory
775 * containing the current process, and check
776 * that for the new executable as the first
780 prog = g_strdup_printf ("%s/%s", curdir, token);
783 /* I assume X_OK is the criterion to use,
786 * X_OK is too strict *if* the target is a CLR binary
788 if (!is_readable_or_executable (prog)) {
790 prog = g_find_program_in_path (token);
792 DEBUG ("%s: Couldn't find executable %s", __func__, token);
795 SetLastError (ERROR_FILE_NOT_FOUND);
804 DEBUG ("%s: Exec prog [%s] args [%s]", __func__, prog,
807 /* Check for CLR binaries; if found, we will try to invoke
808 * them using the same mono binary that started us.
810 if (is_managed_binary (prog)) {
811 gunichar2 *newapp = NULL, *newcmd;
815 newapp = mono_unicode_from_external (cli_launcher, &bytes_ignored);
817 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
819 if (newapp != NULL) {
820 if (appname != NULL) {
821 newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space,
822 appname, utf16_space,
825 newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space,
829 g_free ((gunichar2 *)newapp);
831 if (newcmd != NULL) {
832 ret = CreateProcess (NULL, newcmd,
836 create_flags, new_environ,
840 g_free ((gunichar2 *)newcmd);
846 if (!is_executable (prog)) {
847 DEBUG ("%s: Executable permisson not set on %s", __func__, prog);
848 SetLastError (ERROR_ACCESS_DENIED);
853 if (args_after_prog != NULL && *args_after_prog) {
856 qprog = g_shell_quote (prog);
857 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
860 full_prog = g_shell_quote (prog);
863 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
865 g_message ("CreateProcess: %s\n", gerr->message);
871 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
872 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
873 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
874 err_fd = GPOINTER_TO_UINT (startup->hStdError);
876 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
877 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
878 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
881 process_handle.proc_name = g_strdup (prog);
883 process_set_defaults (&process_handle);
885 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
886 if (handle == _WAPI_HANDLE_INVALID) {
887 g_warning ("%s: error creating process handle", __func__);
890 SetLastError (ERROR_OUTOFMEMORY);
894 /* new_environ is a block of NULL-terminated strings, which
895 * is itself NULL-terminated. Of course, passing an array of
896 * string pointers would have made things too easy :-(
898 * If new_environ is not NULL it specifies the entire set of
899 * environment variables in the new process. Otherwise the
900 * new process inherits the same environment.
903 gunichar2 *new_environp;
905 /* Count the number of strings */
906 for (new_environp = (gunichar2 *)new_environ; *new_environp;
909 while (*new_environp) {
914 /* +2: one for the process handle value, and the last
917 env_strings = g_new0 (char *, env_count + 2);
919 /* Copy each environ string into 'strings' turning it
920 * into utf8 (or the requested encoding) at the same
924 for (new_environp = (gunichar2 *)new_environ; *new_environp;
926 env_strings[env_count] = mono_unicode_to_external (new_environp);
928 while (*new_environp) {
933 for (i = 0; environ[i] != NULL; i++)
936 /* +2: one for the process handle value, and the last
939 env_strings = g_new0 (char *, env_count + 2);
941 /* Copy each environ string into 'strings' turning it
942 * into utf8 (or the requested encoding) at the same
946 for (i = 0; environ[i] != NULL; i++) {
947 env_strings[env_count] = g_strdup (environ[i]);
952 /* Create a pipe to make sure the child doesn't exit before
953 * we can add the process to the linked list of mono_processes */
954 if (pipe (startup_pipe) == -1) {
955 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
956 * This is just for a very hard to hit race condition in the first place */
957 startup_pipe [0] = startup_pipe [1] = -1;
958 DEBUG ("%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
961 thr_ret = _wapi_handle_lock_shared_handles ();
962 g_assert (thr_ret == 0);
967 SetLastError (ERROR_OUTOFMEMORY);
971 } else if (pid == 0) {
974 if (startup_pipe [0] != -1) {
975 /* Wait until the parent has updated it's internal data */
976 ssize_t _i G_GNUC_UNUSED = read (startup_pipe [0], &dummy, 1);
977 DEBUG ("%s: child: parent has completed its setup", __func__);
978 close (startup_pipe [0]);
979 close (startup_pipe [1]);
982 /* should we detach from the process group? */
984 /* Connect stdin, stdout and stderr */
989 if (inherit_handles != TRUE) {
990 /* FIXME: do something here */
993 /* Close all file descriptors */
994 for (i = wapi_getdtablesize () - 1; i > 2; i--)
998 DEBUG ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
999 dir == NULL?".":dir);
1000 for (i = 0; argv[i] != NULL; i++)
1001 g_message ("arg %d: [%s]", i, argv[i]);
1003 for (i = 0; env_strings[i] != NULL; i++)
1004 g_message ("env %d: [%s]", i, env_strings[i]);
1008 if (dir != NULL && chdir (dir) == -1) {
1014 execve (argv[0], argv, env_strings);
1021 process_handle_data = lookup_process_handle (handle);
1022 if (!process_handle_data) {
1023 g_warning ("%s: error looking up process handle %p", __func__,
1025 _wapi_handle_unref (handle);
1029 process_handle_data->id = pid;
1031 /* Add our mono_process into the linked list of mono_processes */
1032 mono_process = (struct MonoProcess *) g_malloc0 (sizeof (struct MonoProcess));
1033 mono_process->pid = pid;
1034 mono_process->handle_count = 1;
1035 if (MONO_SEM_INIT (&mono_process->exit_sem, 0) != 0) {
1036 /* If we can't create the exit semaphore, we just don't add anything
1037 * to our list of mono processes. Waiting on the process will return
1039 g_warning ("%s: could not create exit semaphore for process.", strerror (errno));
1040 g_free (mono_process);
1042 /* Keep the process handle artificially alive until the process
1043 * exits so that the information in the handle isn't lost. */
1044 _wapi_handle_ref (handle);
1045 mono_process->handle = handle;
1047 process_handle_data->mono_process = mono_process;
1049 mono_mutex_lock (&mono_processes_mutex);
1050 mono_process->next = mono_processes;
1051 mono_processes = mono_process;
1052 mono_mutex_unlock (&mono_processes_mutex);
1055 if (process_info != NULL) {
1056 process_info->hProcess = handle;
1057 process_info->dwProcessId = pid;
1059 /* FIXME: we might need to handle the thread info some
1062 process_info->hThread = INVALID_HANDLE_VALUE;
1063 process_info->dwThreadId = 0;
1067 _wapi_handle_unlock_shared_handles ();
1070 _wapi_handle_unref (handle);
1072 if (startup_pipe [1] != -1) {
1073 /* Write 1 byte, doesn't matter what */
1074 ssize_t _i G_GNUC_UNUSED = write (startup_pipe [1], startup_pipe, 1);
1075 close (startup_pipe [0]);
1076 close (startup_pipe [1]);
1091 g_strfreev (env_strings);
1095 DEBUG ("%s: returning handle %p for pid %d", __func__, handle,
1098 /* Check if something needs to be cleaned up. */
1099 mono_processes_cleanup ();
1103 SetLastError (ERROR_NOT_SUPPORTED);
1105 #endif // defined (HAVE_FORK) && defined (HAVE_EXECVE)
1109 process_set_name (WapiHandle_process *process_handle)
1111 char *progname, *utf8_progname, *slash;
1113 progname = g_get_prgname ();
1114 utf8_progname = mono_utf8_from_external (progname);
1116 DEBUG ("%s: using [%s] as prog name", __func__, progname);
1118 if (utf8_progname) {
1119 slash = strrchr (utf8_progname, '/');
1121 process_handle->proc_name = g_strdup (slash+1);
1123 process_handle->proc_name = g_strdup (utf8_progname);
1124 g_free (utf8_progname);
1129 wapi_processes_init (void)
1131 pid_t pid = _wapi_getpid ();
1132 WapiHandle_process process_handle = {0};
1134 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
1135 WAPI_HANDLE_CAP_WAIT |
1136 WAPI_HANDLE_CAP_SPECIAL_WAIT);
1138 process_handle.id = pid;
1140 process_set_defaults (&process_handle);
1141 process_set_name (&process_handle);
1143 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1145 g_assert (current_process);
1149 _wapi_process_duplicate (void)
1151 _wapi_handle_ref (current_process);
1153 return current_process;
1156 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1158 GetCurrentProcess (void)
1160 return _WAPI_PROCESS_CURRENT;
1164 GetProcessId (gpointer handle)
1166 WapiHandle_process *process_handle;
1168 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1169 /* This is a pseudo handle */
1170 return WAPI_HANDLE_TO_PID (handle);
1172 process_handle = lookup_process_handle (handle);
1173 if (!process_handle) {
1174 SetLastError (ERROR_INVALID_HANDLE);
1178 return process_handle->id;
1182 process_open_compare (gpointer handle, gpointer user_data)
1185 WapiHandle_process *process_handle;
1188 g_assert (!WAPI_IS_PSEUDO_PROCESS_HANDLE (handle));
1190 process_handle = lookup_process_handle (handle);
1191 g_assert (process_handle);
1193 DEBUG ("%s: looking at process %d", __func__, process_handle->id);
1195 checking_pid = process_handle->id;
1197 if (checking_pid == 0)
1200 wanted_pid = GPOINTER_TO_UINT (user_data);
1202 /* It's possible to have more than one process handle with the
1203 * same pid, but only the one running process can be
1206 if (checking_pid == wanted_pid &&
1207 !_wapi_handle_issignalled (handle)) {
1208 /* If the handle is blown away in the window between
1209 * returning TRUE here and _wapi_search_handle pinging
1210 * the timestamp, the search will continue
1219 CloseProcess (gpointer handle)
1221 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1223 return CloseHandle (handle);
1227 * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1230 OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1232 /* Find the process handle that corresponds to pid */
1233 gpointer handle = NULL;
1235 DEBUG ("%s: looking for process %d", __func__, pid);
1237 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1238 process_open_compare,
1239 GUINT_TO_POINTER (pid), NULL, TRUE);
1241 if (is_pid_valid (pid)) {
1242 /* Return a pseudo handle for processes we
1243 * don't have handles for
1245 return WAPI_PID_TO_HANDLE (pid);
1247 DEBUG ("%s: Can't find pid %d", __func__, pid);
1249 SetLastError (ERROR_PROC_NOT_FOUND);
1255 /* _wapi_search_handle () already added a ref */
1260 GetExitCodeProcess (gpointer process, guint32 *code)
1262 WapiHandle_process *process_handle;
1268 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1269 pid = WAPI_HANDLE_TO_PID (process);
1270 /* This is a pseudo handle, so we don't know what the
1271 * exit code was, but we can check whether it's alive or not
1273 if (is_pid_valid (pid)) {
1274 *code = STILL_ACTIVE;
1281 process_handle = lookup_process_handle (process);
1282 if (!process_handle) {
1283 DEBUG ("%s: Can't find process %p", __func__, process);
1288 if (process_handle->id == _wapi_getpid ()) {
1289 *code = STILL_ACTIVE;
1293 /* A process handle is only signalled if the process has exited
1294 * and has been waited for */
1296 /* Make sure any process exit has been noticed, before
1297 * checking if the process is signalled. Fixes bug 325463.
1299 process_wait (process, 0, TRUE);
1301 if (_wapi_handle_issignalled (process))
1302 *code = process_handle->exitstatus;
1304 *code = STILL_ACTIVE;
1310 GetProcessTimes (gpointer process, WapiFileTime *create_time,
1311 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1312 WapiFileTime *user_time)
1314 WapiHandle_process *process_handle;
1315 gboolean ku_times_set = FALSE;
1317 if (create_time == NULL || exit_time == NULL || kernel_time == NULL ||
1319 /* Not sure if w32 allows NULLs here or not */
1322 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1323 gpointer pid = GINT_TO_POINTER (WAPI_HANDLE_TO_PID(process));
1324 gint64 start_ticks, user_ticks, kernel_ticks;
1326 mono_process_get_times (pid, &start_ticks, &user_ticks, &kernel_ticks);
1328 _wapi_guint64_to_filetime (start_ticks, create_time);
1329 _wapi_guint64_to_filetime (user_ticks, kernel_time);
1330 _wapi_guint64_to_filetime (kernel_ticks, user_time);
1335 process_handle = lookup_process_handle (process);
1336 if (!process_handle) {
1337 DEBUG ("%s: Can't find process %p", __func__, process);
1342 *create_time = process_handle->create_time;
1344 /* A process handle is only signalled if the process has
1345 * exited. Otherwise exit_time isn't set
1347 if (_wapi_handle_issignalled (process))
1348 *exit_time = process_handle->exit_time;
1350 #ifdef HAVE_GETRUSAGE
1351 if (process_handle->id == getpid ()) {
1352 struct rusage time_data;
1353 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1355 ku_times_set = TRUE;
1356 tick_val = (guint64)time_data.ru_utime.tv_sec * 10000000 + (guint64)time_data.ru_utime.tv_usec * 10;
1357 _wapi_guint64_to_filetime (tick_val, user_time);
1358 tick_val = (guint64)time_data.ru_stime.tv_sec * 10000000 + (guint64)time_data.ru_stime.tv_usec * 10;
1359 _wapi_guint64_to_filetime (tick_val, kernel_time);
1363 if (!ku_times_set) {
1364 memset (kernel_time, 0, sizeof (WapiFileTime));
1365 memset (user_time, 0, sizeof (WapiFileTime));
1373 gpointer address_start;
1374 gpointer address_end;
1376 gpointer address_offset;
1382 static void free_procmodule (WapiProcModule *mod)
1384 if (mod->perms != NULL) {
1385 g_free (mod->perms);
1387 if (mod->filename != NULL) {
1388 g_free (mod->filename);
1393 static gint find_procmodule (gconstpointer a, gconstpointer b)
1395 WapiProcModule *want = (WapiProcModule *)a;
1396 WapiProcModule *compare = (WapiProcModule *)b;
1398 if ((want->device == compare->device) &&
1399 (want->inode == compare->inode)) {
1406 #ifdef PLATFORM_MACOSX
1407 #include <mach-o/dyld.h>
1408 #include <mach-o/getsect.h>
1410 static GSList *load_modules (void)
1413 WapiProcModule *mod;
1414 uint32_t count = _dyld_image_count ();
1417 for (i = 0; i < count; i++) {
1418 #if SIZEOF_VOID_P == 8
1419 const struct mach_header_64 *hdr;
1420 const struct section_64 *sec;
1422 const struct mach_header *hdr;
1423 const struct section *sec;
1427 name = _dyld_get_image_name (i);
1428 #if SIZEOF_VOID_P == 8
1429 hdr = (const struct mach_header_64*)_dyld_get_image_header (i);
1430 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1432 hdr = _dyld_get_image_header (i);
1433 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1436 /* Some dynlibs do not have data sections on osx (#533893) */
1441 mod = g_new0 (WapiProcModule, 1);
1442 mod->address_start = GINT_TO_POINTER (sec->addr);
1443 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1444 mod->perms = g_strdup ("r--p");
1445 mod->address_offset = 0;
1446 mod->device = makedev (0, 0);
1448 mod->filename = g_strdup (name);
1450 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1451 ret = g_slist_prepend (ret, mod);
1453 free_procmodule (mod);
1457 ret = g_slist_reverse (ret);
1461 #elif defined(__OpenBSD__) || defined(__FreeBSD__)
1463 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1465 if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1466 + sizeof (info->dlpi_phnum))
1469 struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1473 memcpy(cpy, info, sizeof(*info));
1475 g_ptr_array_add ((GPtrArray *)ptr, cpy);
1480 static GSList *load_modules (void)
1483 WapiProcModule *mod;
1484 GPtrArray *dlarray = g_ptr_array_new();
1487 if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1490 for (i = 0; i < dlarray->len; i++) {
1491 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1493 mod = g_new0 (WapiProcModule, 1);
1494 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1495 mod->address_end = (gpointer)(info->dlpi_addr +
1496 info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1497 mod->perms = g_strdup ("r--p");
1498 mod->address_offset = 0;
1500 mod->filename = g_strdup (info->dlpi_name);
1502 DEBUG ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1503 mod->inode, mod->filename, mod->address_start, mod->address_end);
1507 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1508 ret = g_slist_prepend (ret, mod);
1510 free_procmodule (mod);
1514 g_ptr_array_free (dlarray, TRUE);
1516 ret = g_slist_reverse (ret);
1520 #elif defined(__HAIKU__)
1522 static GSList *load_modules (void)
1525 WapiProcModule *mod;
1527 image_info imageInfo;
1529 while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
1530 mod = g_new0 (WapiProcModule, 1);
1531 mod->device = imageInfo.device;
1532 mod->inode = imageInfo.node;
1533 mod->filename = g_strdup (imageInfo.name);
1534 mod->address_start = MIN (imageInfo.text, imageInfo.data);
1535 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
1536 (uint8_t*)imageInfo.data + imageInfo.data_size);
1537 mod->perms = g_strdup ("r--p");
1538 mod->address_offset = 0;
1540 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1541 ret = g_slist_prepend (ret, mod);
1543 free_procmodule (mod);
1547 ret = g_slist_reverse (ret);
1552 static GSList *load_modules (FILE *fp)
1555 WapiProcModule *mod;
1556 char buf[MAXPATHLEN + 1], *p, *endp;
1557 char *start_start, *end_start, *prot_start, *offset_start;
1558 char *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1559 gpointer address_start, address_end, address_offset;
1560 guint32 maj_dev, min_dev;
1564 while (fgets (buf, sizeof(buf), fp)) {
1566 while (g_ascii_isspace (*p)) ++p;
1568 if (!g_ascii_isxdigit (*start_start)) {
1571 address_start = (gpointer)strtoul (start_start, &endp, 16);
1579 if (!g_ascii_isxdigit (*end_start)) {
1582 address_end = (gpointer)strtoul (end_start, &endp, 16);
1584 if (!g_ascii_isspace (*p)) {
1588 while (g_ascii_isspace (*p)) ++p;
1590 if (*prot_start != 'r' && *prot_start != '-') {
1593 memcpy (prot_buf, prot_start, 4);
1595 while (!g_ascii_isspace (*p)) ++p;
1597 while (g_ascii_isspace (*p)) ++p;
1599 if (!g_ascii_isxdigit (*offset_start)) {
1602 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1604 if (!g_ascii_isspace (*p)) {
1608 while(g_ascii_isspace (*p)) ++p;
1610 if (!g_ascii_isxdigit (*maj_dev_start)) {
1613 maj_dev = strtoul (maj_dev_start, &endp, 16);
1621 if (!g_ascii_isxdigit (*min_dev_start)) {
1624 min_dev = strtoul (min_dev_start, &endp, 16);
1626 if (!g_ascii_isspace (*p)) {
1630 while (g_ascii_isspace (*p)) ++p;
1632 if (!g_ascii_isxdigit (*inode_start)) {
1635 inode = (guint64)strtol (inode_start, &endp, 10);
1637 if (!g_ascii_isspace (*p)) {
1641 device = makedev ((int)maj_dev, (int)min_dev);
1642 if ((device == 0) &&
1647 while(g_ascii_isspace (*p)) ++p;
1648 /* p now points to the filename */
1650 mod = g_new0 (WapiProcModule, 1);
1651 mod->address_start = address_start;
1652 mod->address_end = address_end;
1653 mod->perms = g_strdup (prot_buf);
1654 mod->address_offset = address_offset;
1655 mod->device = device;
1657 mod->filename = g_strdup (g_strstrip (p));
1659 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1660 ret = g_slist_prepend (ret, mod);
1662 free_procmodule (mod);
1666 ret = g_slist_reverse (ret);
1672 static gboolean match_procname_to_modulename (char *procname, char *modulename)
1674 char* lastsep = NULL;
1675 char* lastsep2 = NULL;
1678 gboolean result = FALSE;
1680 if (procname == NULL || modulename == NULL)
1683 DEBUG ("%s: procname=\"%s\", modulename=\"%s\"", __func__, procname, modulename);
1684 pname = mono_path_resolve_symlinks (procname);
1685 mname = mono_path_resolve_symlinks (modulename);
1687 if (!strcmp (pname, mname))
1691 lastsep = strrchr (mname, '/');
1693 if (!strcmp (lastsep+1, pname))
1696 lastsep2 = strrchr (pname, '/');
1699 if (!strcmp (lastsep+1, lastsep2+1))
1702 if (!strcmp (mname, lastsep2+1))
1712 DEBUG ("%s: result is %d", __func__, result);
1716 #if !(defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__HAIKU__))
1718 open_process_map (int pid, const char *mode)
1721 const char *proc_path[] = {
1722 "/proc/%d/maps", /* GNU/Linux */
1723 "/proc/%d/map", /* FreeBSD */
1729 for (i = 0; fp == NULL && proc_path [i]; i++) {
1730 filename = g_strdup_printf (proc_path[i], pid);
1731 fp = fopen (filename, mode);
1739 static char *get_process_name_from_proc (pid_t pid);
1741 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1742 guint32 size, guint32 *needed)
1744 WapiHandle_process *process_handle;
1745 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX) && !defined(__FreeBSD__)
1748 GSList *mods = NULL;
1749 WapiProcModule *module;
1750 guint32 count, avail = size / sizeof(gpointer);
1753 char *proc_name = NULL;
1755 /* Store modules in an array of pointers (main module as
1756 * modules[0]), using the load address for each module as a
1757 * token. (Use 'NULL' as an alternative for the main module
1758 * so that the simple implementation can just return one item
1759 * for now.) Get the info from /proc/<pid>/maps on linux,
1760 * /proc/<pid>/map on FreeBSD, other systems will have to
1761 * implement /dev/kmem reading or whatever other horrid
1762 * technique is needed.
1764 if (size < sizeof(gpointer))
1767 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1768 pid = WAPI_HANDLE_TO_PID (process);
1769 proc_name = get_process_name_from_proc (pid);
1771 process_handle = lookup_process_handle (process);
1772 if (!process_handle) {
1773 DEBUG ("%s: Can't find process %p", __func__, process);
1777 pid = process_handle->id;
1778 proc_name = process_handle->proc_name;
1781 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__HAIKU__)
1782 mods = load_modules ();
1785 *needed = sizeof(gpointer);
1789 fp = open_process_map (pid, "r");
1791 /* No /proc/<pid>/maps so just return the main module
1795 *needed = sizeof(gpointer);
1798 mods = load_modules (fp);
1801 count = g_slist_length (mods);
1803 /* count + 1 to leave slot 0 for the main module */
1804 *needed = sizeof(gpointer) * (count + 1);
1807 * Use the NULL shortcut, as the first line in
1808 * /proc/<pid>/maps isn't the executable, and we need
1809 * that first in the returned list. Check the module name
1810 * to see if it ends with the proc name and substitute
1811 * the first entry with it. FIXME if this turns out to
1815 for (i = 0; i < (avail - 1) && i < count; i++) {
1816 module = (WapiProcModule *)g_slist_nth_data (mods, i);
1817 if (modules[0] != NULL)
1818 modules[i] = module->address_start;
1819 else if (match_procname_to_modulename (proc_name, module->filename))
1820 modules[0] = module->address_start;
1822 modules[i + 1] = module->address_start;
1825 for (i = 0; i < count; i++) {
1826 free_procmodule (g_slist_nth_data (mods, i));
1828 g_slist_free (mods);
1834 get_process_name_from_proc (pid_t pid)
1836 #if defined(__OpenBSD__) || defined(__FreeBSD__)
1839 struct kinfo_proc *pi;
1840 #elif defined(PLATFORM_MACOSX)
1841 #if !(!defined (__mono_ppc__) && defined (TARGET_OSX))
1843 struct kinfo_proc *pi;
1844 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
1848 char *filename = NULL;
1853 #if defined(PLATFORM_SOLARIS)
1854 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
1855 if ((fp = fopen (filename, "r")) != NULL) {
1859 nread = fread (&info, sizeof (info), 1, fp);
1861 ret = g_strdup (info.pr_fname);
1867 #elif defined(PLATFORM_MACOSX)
1868 #if !defined (__mono_ppc__) && defined (TARGET_OSX)
1869 /* No proc name on OSX < 10.5 nor ppc nor iOS */
1870 memset (buf, '\0', sizeof(buf));
1871 proc_name (pid, buf, sizeof(buf));
1873 // Fixes proc_name triming values to 15 characters #32539
1874 if (strlen (buf) >= MAXCOMLEN - 1) {
1875 char path_buf [PROC_PIDPATHINFO_MAXSIZE];
1879 memset (path_buf, '\0', sizeof(path_buf));
1880 path_len = proc_pidpath (pid, path_buf, sizeof(path_buf));
1882 if (path_len > 0 && path_len < sizeof(path_buf)) {
1883 name_buf = path_buf + path_len;
1884 for(;name_buf > path_buf; name_buf--) {
1885 if (name_buf [0] == '/') {
1891 if (memcmp (buf, name_buf, MAXCOMLEN - 1) == 0)
1892 ret = g_strdup (name_buf);
1896 if (ret == NULL && strlen (buf) > 0)
1897 ret = g_strdup (buf);
1899 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0)
1902 if ((pi = malloc(size)) == NULL)
1905 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
1906 if (errno == ENOMEM) {
1908 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__);
1913 if (strlen (pi->kp_proc.p_comm) > 0)
1914 ret = g_strdup (pi->kp_proc.p_comm);
1918 #elif defined(__FreeBSD__)
1920 mib [1] = KERN_PROC;
1921 mib [2] = KERN_PROC_PID;
1923 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0) {
1924 DEBUG ("%s: sysctl() failed: %d", __func__, errno);
1928 if ((pi = malloc(size)) == NULL)
1931 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
1932 if (errno == ENOMEM) {
1934 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__);
1939 if (strlen (pi->ki_comm) > 0)
1940 ret = g_strdup (pi->ki_comm);
1942 #elif defined(__OpenBSD__)
1944 mib [1] = KERN_PROC;
1945 mib [2] = KERN_PROC_PID;
1947 mib [4] = sizeof(struct kinfo_proc);
1951 if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0) {
1952 DEBUG ("%s: sysctl() failed: %d", __func__, errno);
1956 if ((pi = malloc(size)) == NULL)
1959 mib[5] = (int)(size / sizeof(struct kinfo_proc));
1961 if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
1962 (size != sizeof (struct kinfo_proc))) {
1963 if (errno == ENOMEM) {
1970 #if defined(__OpenBSD__)
1971 if (strlen (pi->p_comm) > 0)
1972 ret = g_strdup (pi->p_comm);
1973 #elif defined(__FreeBSD__)
1974 if (strlen (pi->ki_comm) > 0)
1975 ret = g_strdup (pi->ki_comm);
1979 #elif defined(__HAIKU__)
1980 image_info imageInfo;
1983 if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
1984 ret = g_strdup (imageInfo.name);
1987 memset (buf, '\0', sizeof(buf));
1988 filename = g_strdup_printf ("/proc/%d/exe", pid);
1989 if (readlink (filename, buf, 255) > 0) {
1990 ret = g_strdup (buf);
1998 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
1999 if ((fp = fopen (filename, "r")) != NULL) {
2000 if (fgets (buf, 256, fp) != NULL) {
2001 ret = g_strdup (buf);
2012 filename = g_strdup_printf ("/proc/%d/stat", pid);
2013 if ((fp = fopen (filename, "r")) != NULL) {
2014 if (fgets (buf, 256, fp) != NULL) {
2017 start = strchr (buf, '(');
2018 if (start != NULL) {
2019 end = strchr (start + 1, ')');
2022 ret = g_strndup (start + 1,
2037 * wapi_process_get_path:
2039 * Return the full path of the executable of the process PID, or NULL if it cannot be determined.
2040 * Returns malloc-ed memory.
2043 wapi_process_get_path (pid_t pid)
2045 #if defined(PLATFORM_MACOSX) && !defined(__mono_ppc__) && defined(TARGET_OSX)
2046 char buf [PROC_PIDPATHINFO_MAXSIZE];
2049 res = proc_pidpath (pid, buf, sizeof (buf));
2052 if (buf [0] == '\0')
2054 return g_strdup (buf);
2056 return get_process_name_from_proc (pid);
2061 * wapi_process_set_cli_launcher:
2063 * Set the full path of the runtime executable used to launch managed exe's.
2066 wapi_process_set_cli_launcher (char *path)
2068 g_free (cli_launcher);
2069 cli_launcher = path ? g_strdup (path) : NULL;
2073 get_module_name (gpointer process, gpointer module,
2074 gunichar2 *basename, guint32 size,
2077 WapiHandle_process *process_handle;
2079 gunichar2 *procname;
2080 char *procname_ext = NULL;
2083 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX) && !defined(__FreeBSD__)
2086 GSList *mods = NULL;
2087 WapiProcModule *found_module;
2090 char *proc_name = NULL;
2092 DEBUG ("%s: Getting module base name, process handle %p module %p",
2093 __func__, process, module);
2095 size = size * sizeof (gunichar2); /* adjust for unicode characters */
2097 if (basename == NULL || size == 0)
2100 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2101 /* This is a pseudo handle */
2102 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2103 proc_name = get_process_name_from_proc (pid);
2105 process_handle = lookup_process_handle (process);
2106 if (!process_handle) {
2107 DEBUG ("%s: Can't find process %p", __func__,
2112 pid = process_handle->id;
2113 proc_name = g_strdup (process_handle->proc_name);
2116 /* Look up the address in /proc/<pid>/maps */
2117 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__HAIKU__)
2118 mods = load_modules ();
2120 fp = open_process_map (pid, "r");
2122 if (errno == EACCES && module == NULL && base == TRUE) {
2123 procname_ext = get_process_name_from_proc (pid);
2125 /* No /proc/<pid>/maps, so just return failure
2132 mods = load_modules (fp);
2136 count = g_slist_length (mods);
2138 /* If module != NULL compare the address.
2139 * If module == NULL we are looking for the main module.
2140 * The best we can do for now check it the module name end with the process name.
2142 for (i = 0; i < count; i++) {
2143 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2144 if (procname_ext == NULL &&
2145 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2146 (module != NULL && found_module->address_start == module))) {
2148 procname_ext = g_path_get_basename (found_module->filename);
2150 procname_ext = g_strdup (found_module->filename);
2153 free_procmodule (found_module);
2156 if (procname_ext == NULL) {
2157 /* If it's *still* null, we might have hit the
2158 * case where reading /proc/$pid/maps gives an
2159 * empty file for this user.
2161 procname_ext = get_process_name_from_proc (pid);
2164 g_slist_free (mods);
2168 DEBUG ("%s: Process name is [%s]", __func__,
2171 procname = mono_unicode_from_external (procname_ext, &bytes);
2172 if (procname == NULL) {
2174 g_free (procname_ext);
2180 /* Add the terminator */
2184 DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2186 memcpy (basename, procname, size);
2188 DEBUG ("%s: Size %d larger than needed (%ld)",
2189 __func__, size, bytes);
2191 memcpy (basename, procname, bytes);
2195 g_free (procname_ext);
2204 get_module_filename (gpointer process, gpointer module,
2205 gunichar2 *basename, guint32 size)
2210 gunichar2 *proc_path;
2212 size *= sizeof (gunichar2); /* adjust for unicode characters */
2214 if (basename == NULL || size == 0)
2217 pid = GetProcessId (process);
2219 path = wapi_process_get_path (pid);
2223 proc_path = mono_unicode_from_external (path, &bytes);
2226 if (proc_path == NULL)
2231 /* Add the terminator */
2235 DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2237 memcpy (basename, proc_path, size);
2239 DEBUG ("%s: Size %d larger than needed (%ld)",
2240 __func__, size, bytes);
2242 memcpy (basename, proc_path, bytes);
2251 GetModuleBaseName (gpointer process, gpointer module,
2252 gunichar2 *basename, guint32 size)
2254 return get_module_name (process, module, basename, size, TRUE);
2258 GetModuleFileNameEx (gpointer process, gpointer module,
2259 gunichar2 *filename, guint32 size)
2261 return get_module_filename (process, module, filename, size);
2265 GetModuleInformation (gpointer process, gpointer module,
2266 WapiModuleInfo *modinfo, guint32 size)
2268 WapiHandle_process *process_handle;
2270 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX) && !defined(__FreeBSD__)
2273 GSList *mods = NULL;
2274 WapiProcModule *found_module;
2277 gboolean ret = FALSE;
2278 char *proc_name = NULL;
2280 DEBUG ("%s: Getting module info, process handle %p module %p",
2281 __func__, process, module);
2283 if (modinfo == NULL || size < sizeof (WapiModuleInfo))
2286 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2287 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2288 proc_name = get_process_name_from_proc (pid);
2290 process_handle = lookup_process_handle (process);
2291 if (!process_handle) {
2292 DEBUG ("%s: Can't find process %p", __func__,
2297 pid = process_handle->id;
2298 proc_name = g_strdup (process_handle->proc_name);
2301 #if defined(PLATFORM_MACOSX) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__HAIKU__)
2302 mods = load_modules ();
2304 /* Look up the address in /proc/<pid>/maps */
2305 if ((fp = open_process_map (pid, "r")) == NULL) {
2306 /* No /proc/<pid>/maps, so just return failure
2312 mods = load_modules (fp);
2315 count = g_slist_length (mods);
2317 /* If module != NULL compare the address.
2318 * If module == NULL we are looking for the main module.
2319 * The best we can do for now check it the module name end with the process name.
2321 for (i = 0; i < count; i++) {
2322 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2324 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2325 (module != NULL && found_module->address_start == module))) {
2326 modinfo->lpBaseOfDll = found_module->address_start;
2327 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2328 modinfo->EntryPoint = found_module->address_offset;
2332 free_procmodule (found_module);
2335 g_slist_free (mods);
2342 GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2344 WapiHandle_process *process_handle;
2346 if (min == NULL || max == NULL)
2347 /* Not sure if w32 allows NULLs here or not */
2350 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2351 /* This is a pseudo handle, so just fail for now */
2354 process_handle = lookup_process_handle (process);
2355 if (!process_handle) {
2356 DEBUG ("%s: Can't find process %p", __func__, process);
2361 *min = process_handle->min_working_set;
2362 *max = process_handle->max_working_set;
2368 SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2370 WapiHandle_process *process_handle;
2372 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2373 /* This is a pseudo handle, so just fail for now
2377 process_handle = lookup_process_handle (process);
2378 if (!process_handle) {
2379 DEBUG ("%s: Can't find process %p", __func__, process);
2384 process_handle->min_working_set = min;
2385 process_handle->max_working_set = max;
2392 TerminateProcess (gpointer process, gint32 exitCode)
2394 #if defined(HAVE_KILL)
2395 WapiHandle_process *process_handle;
2400 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2401 /* This is a pseudo handle */
2402 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2404 process_handle = lookup_process_handle (process);
2405 if (!process_handle) {
2406 DEBUG ("%s: Can't find process %p", __func__, process);
2407 SetLastError (ERROR_INVALID_HANDLE);
2410 pid = process_handle->id;
2413 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2414 ret = kill (pid, signo);
2418 SetLastError (ERROR_INVALID_PARAMETER);
2421 SetLastError (ERROR_ACCESS_DENIED);
2424 SetLastError (ERROR_PROC_NOT_FOUND);
2427 SetLastError (ERROR_GEN_FAILURE);
2433 g_error ("kill() is not supported by this platform");
2439 GetPriorityClass (gpointer process)
2441 #ifdef HAVE_GETPRIORITY
2442 WapiHandle_process *process_handle;
2446 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2447 /* This is a pseudo handle */
2448 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2450 process_handle = lookup_process_handle (process);
2451 if (!process_handle) {
2452 SetLastError (ERROR_INVALID_HANDLE);
2455 pid = process_handle->id;
2459 ret = getpriority (PRIO_PROCESS, pid);
2460 if (ret == -1 && errno != 0) {
2464 SetLastError (ERROR_ACCESS_DENIED);
2467 SetLastError (ERROR_PROC_NOT_FOUND);
2470 SetLastError (ERROR_GEN_FAILURE);
2476 return NORMAL_PRIORITY_CLASS;
2478 return REALTIME_PRIORITY_CLASS;
2480 return HIGH_PRIORITY_CLASS;
2482 return ABOVE_NORMAL_PRIORITY_CLASS;
2484 return IDLE_PRIORITY_CLASS;
2486 return BELOW_NORMAL_PRIORITY_CLASS;
2488 return NORMAL_PRIORITY_CLASS;
2490 SetLastError (ERROR_NOT_SUPPORTED);
2496 SetPriorityClass (gpointer process, guint32 priority_class)
2498 #ifdef HAVE_SETPRIORITY
2499 WapiHandle_process *process_handle;
2504 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2505 /* This is a pseudo handle */
2506 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2508 process_handle = lookup_process_handle (process);
2509 if (!process_handle) {
2510 SetLastError (ERROR_INVALID_HANDLE);
2513 pid = process_handle->id;
2516 switch (priority_class) {
2517 case IDLE_PRIORITY_CLASS:
2520 case BELOW_NORMAL_PRIORITY_CLASS:
2523 case NORMAL_PRIORITY_CLASS:
2526 case ABOVE_NORMAL_PRIORITY_CLASS:
2529 case HIGH_PRIORITY_CLASS:
2532 case REALTIME_PRIORITY_CLASS:
2536 SetLastError (ERROR_INVALID_PARAMETER);
2540 ret = setpriority (PRIO_PROCESS, pid, prio);
2545 SetLastError (ERROR_ACCESS_DENIED);
2548 SetLastError (ERROR_PROC_NOT_FOUND);
2551 SetLastError (ERROR_GEN_FAILURE);
2557 SetLastError (ERROR_NOT_SUPPORTED);
2563 mono_processes_cleanup (void)
2565 struct MonoProcess *mp;
2566 struct MonoProcess *prev = NULL;
2567 GSList *finished = NULL;
2569 gpointer unref_handle;
2571 DEBUG ("%s", __func__);
2573 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2574 if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
2577 for (mp = mono_processes; mp; mp = mp->next) {
2578 if (mp->pid == 0 && mp->handle) {
2579 /* This process has exited and we need to remove the artifical ref
2581 mono_mutex_lock (&mono_processes_mutex);
2582 unref_handle = mp->handle;
2584 mono_mutex_unlock (&mono_processes_mutex);
2586 _wapi_handle_unref (unref_handle);
2591 * Remove processes which exited from the mono_processes list.
2592 * We need to synchronize with the sigchld handler here, which runs
2593 * asynchronously. The handler requires that the mono_processes list
2596 mono_mutex_lock (&mono_processes_mutex);
2598 mp = mono_processes;
2600 if (mp->handle_count == 0 && mp->freeable) {
2603 * This code can run parallel with the sigchld handler, but the
2604 * modifications it makes are safe.
2606 if (mp == mono_processes)
2607 mono_processes = mp->next;
2609 prev->next = mp->next;
2610 finished = g_slist_prepend (finished, mp);
2619 mono_memory_barrier ();
2621 for (l = finished; l; l = l->next) {
2623 * All the entries in the finished list are unlinked from mono_processes, and
2624 * they have the 'finished' flag set, which means the sigchld handler is done
2628 MONO_SEM_DESTROY (&mp->exit_sem);
2631 g_slist_free (finished);
2633 mono_mutex_unlock (&mono_processes_mutex);
2635 DEBUG ("%s done", __func__);
2637 InterlockedDecrement (&mono_processes_cleaning_up);
2641 process_close (gpointer handle, gpointer data)
2643 WapiHandle_process *process_handle;
2645 DEBUG ("%s", __func__);
2647 process_handle = (WapiHandle_process *) data;
2648 g_free (process_handle->proc_name);
2649 process_handle->proc_name = NULL;
2650 if (process_handle->mono_process)
2651 InterlockedDecrement (&process_handle->mono_process->handle_count);
2652 mono_processes_cleanup ();
2656 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
2660 struct MonoProcess *p;
2662 DEBUG ("SIG CHILD handler for pid: %i\n", info->si_pid);
2666 pid = waitpid (-1, &status, WNOHANG);
2667 } while (pid == -1 && errno == EINTR);
2672 DEBUG ("child ended: %i", pid);
2675 * This can run concurrently with the code in the rest of this module.
2677 for (p = mono_processes; p; p = p->next) {
2678 if (p->pid == pid) {
2683 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2685 MONO_SEM_POST (&p->exit_sem);
2686 mono_memory_barrier ();
2687 /* Mark this as freeable, the pointer becomes invalid afterwards */
2692 DEBUG ("SIG CHILD handler: done looping.");
2698 process_add_sigchld_handler (void)
2701 struct sigaction sa;
2703 sa.sa_sigaction = mono_sigchld_signal_handler;
2704 sigemptyset (&sa.sa_mask);
2705 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2706 g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2707 DEBUG ("Added SIGCHLD handler");
2712 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2714 WapiHandle_process *process_handle;
2715 pid_t pid G_GNUC_UNUSED, ret;
2719 struct MonoProcess *mp;
2721 /* FIXME: We can now easily wait on processes that aren't our own children,
2722 * but WaitFor*Object won't call us for pseudo handles. */
2723 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2725 DEBUG ("%s (%p, %u)", __func__, handle, timeout);
2727 process_handle = lookup_process_handle (handle);
2728 if (!process_handle) {
2729 g_warning ("%s: error looking up process handle %p", __func__, handle);
2733 if (process_handle->exited) {
2734 /* We've already done this one */
2735 DEBUG ("%s (%p, %u): Process already exited", __func__, handle, timeout);
2736 return WAIT_OBJECT_0;
2739 pid = process_handle->id;
2741 DEBUG ("%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2743 /* We don't need to lock mono_processes here, the entry
2744 * has a handle_count > 0 which means it will not be freed. */
2745 mp = process_handle->mono_process;
2748 start = mono_msec_ticks ();
2752 if (timeout != INFINITE) {
2753 DEBUG ("%s (%p, %u): waiting on semaphore for %li ms...",
2754 __func__, handle, timeout, (timeout - (now - start)));
2756 ret = MONO_SEM_TIMEDWAIT_ALERTABLE (&mp->exit_sem, (timeout - (now - start)), alertable);
2758 DEBUG ("%s (%p, %u): waiting on semaphore forever...",
2759 __func__, handle, timeout);
2760 ret = MONO_SEM_WAIT_ALERTABLE (&mp->exit_sem, alertable);
2763 if (ret == -1 && errno != EINTR && errno != ETIMEDOUT) {
2764 DEBUG ("%s (%p, %u): sem_timedwait failure: %s",
2765 __func__, handle, timeout, g_strerror (errno));
2766 /* Should we return a failure here? */
2770 /* Success, process has exited */
2771 MONO_SEM_POST (&mp->exit_sem);
2776 DEBUG ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
2777 return WAIT_TIMEOUT;
2780 now = mono_msec_ticks ();
2781 if (now - start >= timeout) {
2782 DEBUG ("%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
2783 return WAIT_TIMEOUT;
2786 if (alertable && _wapi_thread_cur_apc_pending ()) {
2787 DEBUG ("%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
2788 return WAIT_IO_COMPLETION;
2792 /* Process must have exited */
2793 DEBUG ("%s (%p, %u): Waited successfully", __func__, handle, timeout);
2795 ret = _wapi_handle_lock_shared_handles ();
2796 g_assert (ret == 0);
2798 status = mp ? mp->status : 0;
2799 if (WIFSIGNALED (status))
2800 process_handle->exitstatus = 128 + WTERMSIG (status);
2802 process_handle->exitstatus = WEXITSTATUS (status);
2803 _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
2805 process_handle->exited = TRUE;
2807 DEBUG ("%s (%p, %u): Setting pid %d signalled, exit status %d",
2808 __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
2810 _wapi_handle_set_signal_state (handle, TRUE, TRUE);
2812 _wapi_handle_unlock_shared_handles ();
2814 return WAIT_OBJECT_0;
2818 wapi_processes_cleanup (void)
2820 g_free (cli_launcher);