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>
43 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
45 #include <TargetConditionals.h>
46 #include <sys/resource.h>
53 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
55 #include <sys/sysctl.h>
56 # if !defined(__OpenBSD__)
57 # include <sys/utsname.h>
61 #ifdef PLATFORM_SOLARIS
62 /* procfs.h cannot be included if this define is set, but it seems to work fine if it is undefined */
63 #if _FILE_OFFSET_BITS == 64
64 #undef _FILE_OFFSET_BITS
66 #define _FILE_OFFSET_BITS 64
73 #include <KernelKit.h>
76 #include <mono/io-layer/wapi.h>
77 #include <mono/io-layer/wapi-private.h>
78 #include <mono/io-layer/handles-private.h>
79 #include <mono/io-layer/misc-private.h>
80 #include <mono/io-layer/process-private.h>
81 #include <mono/io-layer/threads.h>
82 #include <mono/utils/strenc.h>
83 #include <mono/utils/mono-path.h>
84 #include <mono/io-layer/timefuncs-private.h>
85 #include <mono/utils/mono-time.h>
86 #include <mono/utils/mono-membar.h>
87 #include <mono/utils/mono-mutex.h>
88 #include <mono/utils/mono-signal-handler.h>
90 /* The process' environment strings */
91 #if defined(__APPLE__) && !defined (__arm__)
92 /* Apple defines this in crt_externs.h but doesn't provide that header for
93 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
94 * in fact exist on all implementations (so far)
96 char ***_NSGetEnviron(void);
97 #define environ (*_NSGetEnviron())
99 extern char **environ;
103 #define DEBUG(...) g_message(__VA_ARGS__)
104 #define DEBUG_ENABLED 1
109 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable);
110 static void process_close (gpointer handle, gpointer data);
111 static gboolean is_pid_valid (pid_t pid);
113 #if !defined(__OpenBSD__)
115 open_process_map (int pid, const char *mode);
118 struct _WapiHandleOps _wapi_process_ops = {
119 process_close, /* close_shared */
123 process_wait, /* special_wait */
128 static struct sigaction previous_chld_sa;
130 static mono_once_t process_sig_chld_once = MONO_ONCE_INIT;
131 static void process_add_sigchld_handler (void);
133 /* The signal-safe logic to use mono_processes goes like this:
134 * - The list must be safe to traverse for the signal handler at all times.
135 * It's safe to: prepend an entry (which is a single store to 'mono_processes'),
136 * unlink an entry (assuming the unlinked entry isn't freed and doesn't
137 * change its 'next' pointer so that it can still be traversed).
138 * When cleaning up we first unlink an entry, then we verify that
139 * the read lock isn't locked. Then we can free the entry, since
140 * we know that nobody is using the old version of the list (including
141 * the unlinked entry).
142 * We also need to lock when adding and cleaning up so that those two
143 * operations don't mess with eachother. (This lock is not used in the
146 static struct MonoProcess *mono_processes = NULL;
147 static volatile gint32 mono_processes_read_lock = 0;
148 static volatile gint32 mono_processes_cleaning_up = 0;
149 static mono_mutex_t mono_processes_mutex;
150 static void mono_processes_cleanup (void);
152 static gpointer current_process;
153 static char *cli_launcher;
155 static WapiHandle_process *
156 lookup_process_handle (gpointer handle)
158 WapiHandle_process *process_data;
161 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
162 (gpointer *)&process_data);
168 /* Check if a pid is valid - i.e. if a process exists with this pid. */
170 is_pid_valid (pid_t pid)
172 gboolean result = FALSE;
174 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
175 if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
177 #elif defined(__HAIKU__)
179 if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
182 char *dir = g_strdup_printf ("/proc/%d", pid);
183 if (!access (dir, F_OK))
192 process_set_defaults (WapiHandle_process *process_handle)
194 /* These seem to be the defaults on w2k */
195 process_handle->min_working_set = 204800;
196 process_handle->max_working_set = 1413120;
198 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
202 len16 (const gunichar2 *str)
213 utf16_concat (const gunichar2 *first, ...)
220 va_start (args, first);
221 total += len16 (first);
222 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
227 ret = g_new (gunichar2, total + 1);
233 for (s = first; *s != 0; s++)
235 va_start (args, first);
236 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
239 for (p = s; *p != 0; p++)
247 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
248 static const gunichar2 *utf16_space = utf16_space_bytes;
249 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
250 static const gunichar2 *utf16_quote = utf16_quote_bytes;
255 print_utf16 (gunichar2 *str)
259 res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
260 g_print ("%s\n", res);
265 /* Implemented as just a wrapper around CreateProcess () */
267 ShellExecuteEx (WapiShellExecuteInfo *sei)
270 WapiProcessInformation process_info;
274 /* w2k just segfaults here, but we can do better than
277 SetLastError (ERROR_INVALID_PARAMETER);
281 if (sei->lpFile == NULL)
282 /* w2k returns TRUE for this, for some reason. */
285 /* Put both executable and parameters into the second argument
286 * to CreateProcess (), so it searches $PATH. The conversion
287 * into and back out of utf8 is because there is no
288 * g_strdup_printf () equivalent for gunichar2 :-(
290 args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
292 SetLastError (ERROR_INVALID_DATA);
295 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
296 CREATE_UNICODE_ENVIRONMENT, NULL,
297 sei->lpDirectory, NULL, &process_info);
300 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
304 static char *handler;
305 static gunichar2 *handler_utf16;
307 if (handler_utf16 == (gunichar2 *)-1)
310 #ifdef PLATFORM_MACOSX
311 handler = g_strdup ("/usr/bin/open");
314 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
315 * if that fails, try to use gnome-open, then kfmclient
317 handler = g_find_program_in_path ("xdg-open");
318 if (handler == NULL){
319 handler = g_find_program_in_path ("gnome-open");
320 if (handler == NULL){
321 handler = g_find_program_in_path ("kfmclient");
322 if (handler == NULL){
323 handler_utf16 = (gunichar2 *) -1;
326 /* kfmclient needs exec argument */
328 handler = g_strconcat (old, " exec",
335 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
338 /* Put quotes around the filename, in case it's a url
339 * that contains #'s (CreateProcess() calls
340 * g_shell_parse_argv(), which deliberately throws
341 * away anything after an unquoted #). Fixes bug
344 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
345 sei->lpFile, utf16_quote,
346 sei->lpParameters == NULL ? NULL : utf16_space,
347 sei->lpParameters, NULL);
349 SetLastError (ERROR_INVALID_DATA);
352 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
353 CREATE_UNICODE_ENVIRONMENT, NULL,
354 sei->lpDirectory, NULL, &process_info);
357 if (GetLastError () != ERROR_OUTOFMEMORY)
358 SetLastError (ERROR_INVALID_DATA);
361 /* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
362 CloseHandle (process_info.hProcess);
363 process_info.hProcess = NULL;
366 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS)
367 sei->hProcess = process_info.hProcess;
369 CloseHandle (process_info.hProcess);
375 is_managed_binary (const char *filename)
377 int original_errno = errno;
378 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
379 int file = open (filename, O_RDONLY | O_LARGEFILE);
381 int file = open (filename, O_RDONLY);
384 unsigned char buffer[8];
385 off_t file_size, optional_header_offset;
386 off_t pe_header_offset;
387 gboolean managed = FALSE;
389 guint32 first_word, second_word;
391 /* If we are unable to open the file, then we definitely
392 * can't say that it is managed. The child mono process
393 * probably wouldn't be able to open it anyway.
396 errno = original_errno;
400 /* Retrieve the length of the file for future sanity checks. */
401 file_size = lseek (file, 0, SEEK_END);
402 lseek (file, 0, SEEK_SET);
404 /* We know we need to read a header field at offset 60. */
408 num_read = read (file, buffer, 2);
410 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
413 new_offset = lseek (file, 60, SEEK_SET);
415 if (new_offset != 60)
418 num_read = read (file, buffer, 4);
422 pe_header_offset = buffer[0]
427 if (pe_header_offset + 24 > file_size)
430 new_offset = lseek (file, pe_header_offset, SEEK_SET);
432 if (new_offset != pe_header_offset)
435 num_read = read (file, buffer, 4);
437 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
441 * Verify that the header we want in the optional header data
442 * is present in this binary.
444 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
446 if (new_offset != pe_header_offset + 20)
449 num_read = read (file, buffer, 2);
451 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
454 /* Read the CLR header address and size fields. These will be
455 * zero if the binary is not managed.
457 optional_header_offset = pe_header_offset + 24;
458 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
460 if (new_offset != optional_header_offset + 208)
463 num_read = read (file, buffer, 8);
465 /* We are not concerned with endianness, only with
466 * whether it is zero or not.
468 first_word = *(guint32 *)&buffer[0];
469 second_word = *(guint32 *)&buffer[4];
471 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
478 errno = original_errno;
483 CreateProcessWithLogonW (const gunichar2 *username,
484 const gunichar2 *domain,
485 const gunichar2 *password,
486 const guint32 logonFlags,
487 const gunichar2 *appname,
488 const gunichar2 *cmdline,
489 guint32 create_flags,
491 const gunichar2 *cwd,
492 WapiStartupInfo *startup,
493 WapiProcessInformation *process_info)
495 /* FIXME: use user information */
496 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
500 is_readable (const char *prog)
503 if (access (prog, R_OK) != 0)
505 if (stat (prog, &buf))
507 if (S_ISREG (buf.st_mode))
513 is_executable (const char *prog)
516 if (access (prog, X_OK) != 0)
518 if (stat (prog, &buf))
520 if (S_ISREG (buf.st_mode))
526 switch_dir_separators (char *path)
528 size_t i, pathLength = strlen(path);
530 /* Turn all the slashes round the right way, except for \' */
531 /* There are probably other characters that need to be excluded as well. */
532 for (i = 0; i < pathLength; i++) {
533 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' )
538 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
539 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
540 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
541 gboolean inherit_handles, guint32 create_flags,
542 gpointer new_environ, const gunichar2 *cwd,
543 WapiStartupInfo *startup,
544 WapiProcessInformation *process_info)
546 char *cmd = NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL;
547 char *dir = NULL, **env_strings = NULL, **argv = NULL;
548 guint32 i, env_count = 0;
549 gboolean ret = FALSE;
551 WapiHandle_process process_handle = {0}, *process_handle_data;
553 int in_fd, out_fd, err_fd;
556 int startup_pipe [2] = {-1, -1};
558 struct MonoProcess *mono_process;
559 gboolean fork_failed = FALSE;
561 mono_once (&process_sig_chld_once, process_add_sigchld_handler);
563 /* appname and cmdline specify the executable and its args:
565 * If appname is not NULL, it is the name of the executable.
566 * Otherwise the executable is the first token in cmdline.
568 * Executable searching:
570 * If appname is not NULL, it can specify the full path and
571 * file name, or else a partial name and the current directory
572 * will be used. There is no additional searching.
574 * If appname is NULL, the first whitespace-delimited token in
575 * cmdline is used. If the name does not contain a full
576 * directory path, the search sequence is:
578 * 1) The directory containing the current process
579 * 2) The current working directory
580 * 3) The windows system directory (Ignored)
581 * 4) The windows directory (Ignored)
584 * Just to make things more interesting, tokens can contain
585 * white space if they are surrounded by quotation marks. I'm
586 * beginning to understand just why windows apps are generally
587 * so crap, with an API like this :-(
589 if (appname != NULL) {
590 cmd = mono_unicode_to_external (appname);
592 DEBUG ("%s: unicode conversion returned NULL",
595 SetLastError (ERROR_PATH_NOT_FOUND);
599 switch_dir_separators(cmd);
602 if (cmdline != NULL) {
603 args = mono_unicode_to_external (cmdline);
605 DEBUG ("%s: unicode conversion returned NULL", __func__);
607 SetLastError (ERROR_PATH_NOT_FOUND);
613 dir = mono_unicode_to_external (cwd);
615 DEBUG ("%s: unicode conversion returned NULL", __func__);
617 SetLastError (ERROR_PATH_NOT_FOUND);
621 /* Turn all the slashes round the right way */
622 switch_dir_separators(dir);
626 /* We can't put off locating the executable any longer :-( */
629 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
630 /* Strip off the drive letter. I can't
631 * believe that CP/M holdover is still
634 g_memmove (cmd, cmd+2, strlen (cmd)-2);
635 cmd[strlen (cmd)-2] = '\0';
638 unquoted = g_shell_unquote (cmd, NULL);
639 if (unquoted[0] == '/') {
640 /* Assume full path given */
641 prog = g_strdup (unquoted);
643 /* Executable existing ? */
644 if (!is_readable (prog)) {
645 DEBUG ("%s: Couldn't find executable %s",
648 SetLastError (ERROR_FILE_NOT_FOUND);
652 /* Search for file named by cmd in the current
655 char *curdir = g_get_current_dir ();
657 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
660 /* And make sure it's readable */
661 if (!is_readable (prog)) {
662 DEBUG ("%s: Couldn't find executable %s",
665 SetLastError (ERROR_FILE_NOT_FOUND);
671 args_after_prog = args;
676 /* Dig out the first token from args, taking quotation
680 /* First, strip off all leading whitespace */
681 args = g_strchug (args);
683 /* args_after_prog points to the contents of args
684 * after token has been set (otherwise argv[0] is
687 args_after_prog = args;
689 /* Assume the opening quote will always be the first
692 if (args[0] == '\"' || args [0] == '\'') {
694 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
695 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
696 /* We found the first token */
697 token = g_strndup (args+1, i-1);
698 args_after_prog = g_strchug (args + i + 1);
700 /* Quotation mark appeared in the
701 * middle of the token. Just give the
702 * whole first token, quotes and all,
709 /* No quote mark, or malformed */
710 for (i = 0; args[i] != '\0'; i++) {
711 if (g_ascii_isspace (args[i])) {
712 token = g_strndup (args, i);
713 args_after_prog = args + i + 1;
719 if (token == NULL && args[0] != '\0') {
720 /* Must be just one token in the string */
721 token = g_strdup (args);
722 args_after_prog = NULL;
727 DEBUG ("%s: Couldn't find what to exec", __func__);
729 SetLastError (ERROR_PATH_NOT_FOUND);
733 /* Turn all the slashes round the right way. Only for
736 switch_dir_separators(token);
738 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
739 /* Strip off the drive letter. I can't
740 * believe that CP/M holdover is still
743 g_memmove (token, token+2, strlen (token)-2);
744 token[strlen (token)-2] = '\0';
747 if (token[0] == '/') {
748 /* Assume full path given */
749 prog = g_strdup (token);
751 /* Executable existing ? */
752 if (!is_readable (prog)) {
753 DEBUG ("%s: Couldn't find executable %s",
756 SetLastError (ERROR_FILE_NOT_FOUND);
760 char *curdir = g_get_current_dir ();
762 /* FIXME: Need to record the directory
763 * containing the current process, and check
764 * that for the new executable as the first
768 prog = g_strdup_printf ("%s/%s", curdir, token);
771 /* I assume X_OK is the criterion to use,
774 * X_OK is too strict *if* the target is a CLR binary
776 if (!is_readable (prog)) {
778 prog = g_find_program_in_path (token);
780 DEBUG ("%s: Couldn't find executable %s", __func__, token);
783 SetLastError (ERROR_FILE_NOT_FOUND);
792 DEBUG ("%s: Exec prog [%s] args [%s]", __func__, prog,
795 /* Check for CLR binaries; if found, we will try to invoke
796 * them using the same mono binary that started us.
798 if (is_managed_binary (prog)) {
799 gunichar2 *newapp = NULL, *newcmd;
803 newapp = mono_unicode_from_external (cli_launcher, &bytes_ignored);
805 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
807 if (newapp != NULL) {
808 if (appname != NULL) {
809 newcmd = utf16_concat (newapp, utf16_space,
810 appname, utf16_space,
813 newcmd = utf16_concat (newapp, utf16_space,
817 g_free ((gunichar2 *)newapp);
819 if (newcmd != NULL) {
820 ret = CreateProcess (NULL, newcmd,
824 create_flags, new_environ,
828 g_free ((gunichar2 *)newcmd);
834 if (!is_executable (prog)) {
835 DEBUG ("%s: Executable permisson not set on %s", __func__, prog);
837 SetLastError (ERROR_ACCESS_DENIED);
842 if (args_after_prog != NULL && *args_after_prog) {
845 qprog = g_shell_quote (prog);
846 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
849 full_prog = g_shell_quote (prog);
852 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
854 g_message ("CreateProcess: %s\n", gerr->message);
860 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
861 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
862 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
863 err_fd = GPOINTER_TO_UINT (startup->hStdError);
865 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
866 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
867 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
870 process_handle.proc_name = g_strdup (prog);
872 process_set_defaults (&process_handle);
874 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
875 if (handle == _WAPI_HANDLE_INVALID) {
876 g_warning ("%s: error creating process handle", __func__);
879 SetLastError (ERROR_OUTOFMEMORY);
883 /* new_environ is a block of NULL-terminated strings, which
884 * is itself NULL-terminated. Of course, passing an array of
885 * string pointers would have made things too easy :-(
887 * If new_environ is not NULL it specifies the entire set of
888 * environment variables in the new process. Otherwise the
889 * new process inherits the same environment.
892 gunichar2 *new_environp;
894 /* Count the number of strings */
895 for (new_environp = (gunichar2 *)new_environ; *new_environp;
898 while (*new_environp) {
903 /* +2: one for the process handle value, and the last
906 env_strings = g_new0 (char *, env_count + 2);
908 /* Copy each environ string into 'strings' turning it
909 * into utf8 (or the requested encoding) at the same
913 for (new_environp = (gunichar2 *)new_environ; *new_environp;
915 env_strings[env_count] = mono_unicode_to_external (new_environp);
917 while (*new_environp) {
922 for (i = 0; environ[i] != NULL; i++)
925 /* +2: one for the process handle value, and the last
928 env_strings = g_new0 (char *, env_count + 2);
930 /* Copy each environ string into 'strings' turning it
931 * into utf8 (or the requested encoding) at the same
935 for (i = 0; environ[i] != NULL; i++) {
936 env_strings[env_count] = g_strdup (environ[i]);
941 /* Create a pipe to make sure the child doesn't exit before
942 * we can add the process to the linked list of mono_processes */
943 if (pipe (startup_pipe) == -1) {
944 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
945 * This is just for a very hard to hit race condition in the first place */
946 startup_pipe [0] = startup_pipe [1] = -1;
947 DEBUG ("%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
950 thr_ret = _wapi_handle_lock_shared_handles ();
951 g_assert (thr_ret == 0);
956 SetLastError (ERROR_OUTOFMEMORY);
960 } else if (pid == 0) {
963 if (startup_pipe [0] != -1) {
964 /* Wait until the parent has updated it's internal data */
965 ssize_t _i G_GNUC_UNUSED = read (startup_pipe [0], &dummy, 1);
966 DEBUG ("%s: child: parent has completed its setup", __func__);
967 close (startup_pipe [0]);
968 close (startup_pipe [1]);
971 /* should we detach from the process group? */
973 /* Connect stdin, stdout and stderr */
978 if (inherit_handles != TRUE) {
979 /* FIXME: do something here */
982 /* Close all file descriptors */
983 for (i = wapi_getdtablesize () - 1; i > 2; i--)
987 DEBUG ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
988 dir == NULL?".":dir);
989 for (i = 0; argv[i] != NULL; i++)
990 g_message ("arg %d: [%s]", i, argv[i]);
992 for (i = 0; env_strings[i] != NULL; i++)
993 g_message ("env %d: [%s]", i, env_strings[i]);
997 if (dir != NULL && chdir (dir) == -1) {
1003 execve (argv[0], argv, env_strings);
1010 process_handle_data = lookup_process_handle (handle);
1011 if (!process_handle_data) {
1012 g_warning ("%s: error looking up process handle %p", __func__,
1014 _wapi_handle_unref (handle);
1018 process_handle_data->id = pid;
1020 /* Add our mono_process into the linked list of mono_processes */
1021 mono_process = (struct MonoProcess *) g_malloc0 (sizeof (struct MonoProcess));
1022 mono_process->pid = pid;
1023 mono_process->handle_count = 1;
1024 if (MONO_SEM_INIT (&mono_process->exit_sem, 0) != 0) {
1025 /* If we can't create the exit semaphore, we just don't add anything
1026 * to our list of mono processes. Waiting on the process will return
1028 g_warning ("%s: could not create exit semaphore for process.", strerror (errno));
1029 g_free (mono_process);
1031 /* Keep the process handle artificially alive until the process
1032 * exits so that the information in the handle isn't lost. */
1033 _wapi_handle_ref (handle);
1034 mono_process->handle = handle;
1036 process_handle_data->mono_process = mono_process;
1038 mono_mutex_lock (&mono_processes_mutex);
1039 mono_process->next = mono_processes;
1040 mono_processes = mono_process;
1041 mono_mutex_unlock (&mono_processes_mutex);
1044 if (process_info != NULL) {
1045 process_info->hProcess = handle;
1046 process_info->dwProcessId = pid;
1048 /* FIXME: we might need to handle the thread info some
1051 process_info->hThread = INVALID_HANDLE_VALUE;
1052 process_info->dwThreadId = 0;
1056 _wapi_handle_unlock_shared_handles ();
1059 _wapi_handle_unref (handle);
1061 if (startup_pipe [1] != -1) {
1062 /* Write 1 byte, doesn't matter what */
1063 ssize_t _i G_GNUC_UNUSED = write (startup_pipe [1], startup_pipe, 1);
1064 close (startup_pipe [0]);
1065 close (startup_pipe [1]);
1080 g_strfreev (env_strings);
1084 DEBUG ("%s: returning handle %p for pid %d", __func__, handle,
1087 /* Check if something needs to be cleaned up. */
1088 mono_processes_cleanup ();
1094 process_set_name (WapiHandle_process *process_handle)
1096 char *progname, *utf8_progname, *slash;
1098 progname = g_get_prgname ();
1099 utf8_progname = mono_utf8_from_external (progname);
1101 DEBUG ("%s: using [%s] as prog name", __func__, progname);
1103 if (utf8_progname) {
1104 slash = strrchr (utf8_progname, '/');
1106 process_handle->proc_name = g_strdup (slash+1);
1108 process_handle->proc_name = g_strdup (utf8_progname);
1109 g_free (utf8_progname);
1114 wapi_processes_init (void)
1116 pid_t pid = _wapi_getpid ();
1117 WapiHandle_process process_handle = {0};
1119 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
1120 WAPI_HANDLE_CAP_WAIT |
1121 WAPI_HANDLE_CAP_SPECIAL_WAIT);
1123 process_handle.id = pid;
1125 process_set_defaults (&process_handle);
1126 process_set_name (&process_handle);
1128 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1130 g_assert (current_process);
1134 _wapi_process_duplicate (void)
1136 _wapi_handle_ref (current_process);
1138 return current_process;
1141 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1143 GetCurrentProcess (void)
1145 return _WAPI_PROCESS_CURRENT;
1149 GetProcessId (gpointer handle)
1151 WapiHandle_process *process_handle;
1153 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1154 /* This is a pseudo handle */
1155 return WAPI_HANDLE_TO_PID (handle);
1157 process_handle = lookup_process_handle (handle);
1158 if (!process_handle) {
1159 SetLastError (ERROR_INVALID_HANDLE);
1163 return process_handle->id;
1167 process_open_compare (gpointer handle, gpointer user_data)
1170 WapiHandle_process *process_handle;
1173 g_assert (!WAPI_IS_PSEUDO_PROCESS_HANDLE (handle));
1175 process_handle = lookup_process_handle (handle);
1176 g_assert (process_handle);
1178 DEBUG ("%s: looking at process %d", __func__, process_handle->id);
1180 checking_pid = process_handle->id;
1182 if (checking_pid == 0)
1185 wanted_pid = GPOINTER_TO_UINT (user_data);
1187 /* It's possible to have more than one process handle with the
1188 * same pid, but only the one running process can be
1191 if (checking_pid == wanted_pid &&
1192 !_wapi_handle_issignalled (handle)) {
1193 /* If the handle is blown away in the window between
1194 * returning TRUE here and _wapi_search_handle pinging
1195 * the timestamp, the search will continue
1204 CloseProcess (gpointer handle)
1206 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1208 return CloseHandle (handle);
1212 * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1215 OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1217 /* Find the process handle that corresponds to pid */
1218 gpointer handle = NULL;
1220 DEBUG ("%s: looking for process %d", __func__, pid);
1222 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1223 process_open_compare,
1224 GUINT_TO_POINTER (pid), NULL, TRUE);
1226 if (is_pid_valid (pid)) {
1227 /* Return a pseudo handle for processes we
1228 * don't have handles for
1230 return WAPI_PID_TO_HANDLE (pid);
1232 DEBUG ("%s: Can't find pid %d", __func__, pid);
1234 SetLastError (ERROR_PROC_NOT_FOUND);
1240 /* _wapi_search_handle () already added a ref */
1245 GetExitCodeProcess (gpointer process, guint32 *code)
1247 WapiHandle_process *process_handle;
1253 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1254 pid = WAPI_HANDLE_TO_PID (process);
1255 /* This is a pseudo handle, so we don't know what the
1256 * exit code was, but we can check whether it's alive or not
1258 if (is_pid_valid (pid)) {
1259 *code = STILL_ACTIVE;
1266 process_handle = lookup_process_handle (process);
1267 if (!process_handle) {
1268 DEBUG ("%s: Can't find process %p", __func__, process);
1273 if (process_handle->id == _wapi_getpid ()) {
1274 *code = STILL_ACTIVE;
1278 /* A process handle is only signalled if the process has exited
1279 * and has been waited for */
1281 /* Make sure any process exit has been noticed, before
1282 * checking if the process is signalled. Fixes bug 325463.
1284 process_wait (process, 0, TRUE);
1286 if (_wapi_handle_issignalled (process))
1287 *code = process_handle->exitstatus;
1289 *code = STILL_ACTIVE;
1295 GetProcessTimes (gpointer process, WapiFileTime *create_time,
1296 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1297 WapiFileTime *user_time)
1299 WapiHandle_process *process_handle;
1300 gboolean ku_times_set = FALSE;
1302 if (create_time == NULL || exit_time == NULL || kernel_time == NULL ||
1304 /* Not sure if w32 allows NULLs here or not */
1307 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
1308 /* This is a pseudo handle, so just fail for now
1312 process_handle = lookup_process_handle (process);
1313 if (!process_handle) {
1314 DEBUG ("%s: Can't find process %p", __func__, process);
1319 *create_time = process_handle->create_time;
1321 /* A process handle is only signalled if the process has
1322 * exited. Otherwise exit_time isn't set
1324 if (_wapi_handle_issignalled (process))
1325 *exit_time = process_handle->exit_time;
1327 #ifdef HAVE_GETRUSAGE
1328 if (process_handle->id == getpid ()) {
1329 struct rusage time_data;
1330 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1332 ku_times_set = TRUE;
1333 tick_val = (guint64)time_data.ru_utime.tv_sec * 10000000 + (guint64)time_data.ru_utime.tv_usec * 10;
1334 _wapi_guint64_to_filetime (tick_val, user_time);
1335 tick_val = (guint64)time_data.ru_stime.tv_sec * 10000000 + (guint64)time_data.ru_stime.tv_usec * 10;
1336 _wapi_guint64_to_filetime (tick_val, kernel_time);
1340 if (!ku_times_set) {
1341 memset (kernel_time, 0, sizeof (WapiFileTime));
1342 memset (user_time, 0, sizeof (WapiFileTime));
1350 gpointer address_start;
1351 gpointer address_end;
1353 gpointer address_offset;
1359 static void free_procmodule (WapiProcModule *mod)
1361 if (mod->perms != NULL) {
1362 g_free (mod->perms);
1364 if (mod->filename != NULL) {
1365 g_free (mod->filename);
1370 static gint find_procmodule (gconstpointer a, gconstpointer b)
1372 WapiProcModule *want = (WapiProcModule *)a;
1373 WapiProcModule *compare = (WapiProcModule *)b;
1375 if ((want->device == compare->device) &&
1376 (want->inode == compare->inode)) {
1383 #ifdef PLATFORM_MACOSX
1384 #include <mach-o/dyld.h>
1385 #include <mach-o/getsect.h>
1387 static GSList *load_modules (void)
1390 WapiProcModule *mod;
1391 uint32_t count = _dyld_image_count ();
1394 for (i = 0; i < count; i++) {
1395 #if SIZEOF_VOID_P == 8
1396 const struct mach_header_64 *hdr;
1397 const struct section_64 *sec;
1399 const struct mach_header *hdr;
1400 const struct section *sec;
1404 name = _dyld_get_image_name (i);
1405 #if SIZEOF_VOID_P == 8
1406 hdr = (const struct mach_header_64*)_dyld_get_image_header (i);
1407 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1409 hdr = _dyld_get_image_header (i);
1410 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1413 /* Some dynlibs do not have data sections on osx (#533893) */
1418 mod = g_new0 (WapiProcModule, 1);
1419 mod->address_start = GINT_TO_POINTER (sec->addr);
1420 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1421 mod->perms = g_strdup ("r--p");
1422 mod->address_offset = 0;
1423 mod->device = makedev (0, 0);
1425 mod->filename = g_strdup (name);
1427 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1428 ret = g_slist_prepend (ret, mod);
1430 free_procmodule (mod);
1434 ret = g_slist_reverse (ret);
1438 #elif defined(__OpenBSD__)
1440 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1442 if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1443 + sizeof (info->dlpi_phnum))
1446 struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1450 memcpy(cpy, info, sizeof(*info));
1452 g_ptr_array_add ((GPtrArray *)ptr, cpy);
1457 static GSList *load_modules (void)
1460 WapiProcModule *mod;
1461 GPtrArray *dlarray = g_ptr_array_new();
1464 if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1467 for (i = 0; i < dlarray->len; i++) {
1468 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1470 mod = g_new0 (WapiProcModule, 1);
1471 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1472 mod->address_end = (gpointer)(info->dlpi_addr +
1473 info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1474 mod->perms = g_strdup ("r--p");
1475 mod->address_offset = 0;
1477 mod->filename = g_strdup (info->dlpi_name);
1479 DEBUG ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1480 mod->inode, mod->filename, mod->address_start, mod->address_end);
1484 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1485 ret = g_slist_prepend (ret, mod);
1487 free_procmodule (mod);
1491 g_ptr_array_free (dlarray, TRUE);
1493 ret = g_slist_reverse (ret);
1497 #elif defined(__HAIKU__)
1499 static GSList *load_modules (void)
1502 WapiProcModule *mod;
1504 image_info imageInfo;
1506 while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
1507 mod = g_new0 (WapiProcModule, 1);
1508 mod->device = imageInfo.device;
1509 mod->inode = imageInfo.node;
1510 mod->filename = g_strdup (imageInfo.name);
1511 mod->address_start = MIN (imageInfo.text, imageInfo.data);
1512 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
1513 (uint8_t*)imageInfo.data + imageInfo.data_size);
1514 mod->perms = g_strdup ("r--p");
1515 mod->address_offset = 0;
1517 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1518 ret = g_slist_prepend (ret, mod);
1520 free_procmodule (mod);
1524 ret = g_slist_reverse (ret);
1529 static GSList *load_modules (FILE *fp)
1532 WapiProcModule *mod;
1533 char buf[MAXPATHLEN + 1], *p, *endp;
1534 char *start_start, *end_start, *prot_start, *offset_start;
1535 char *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1536 gpointer address_start, address_end, address_offset;
1537 guint32 maj_dev, min_dev;
1541 while (fgets (buf, sizeof(buf), fp)) {
1543 while (g_ascii_isspace (*p)) ++p;
1545 if (!g_ascii_isxdigit (*start_start)) {
1548 address_start = (gpointer)strtoul (start_start, &endp, 16);
1556 if (!g_ascii_isxdigit (*end_start)) {
1559 address_end = (gpointer)strtoul (end_start, &endp, 16);
1561 if (!g_ascii_isspace (*p)) {
1565 while (g_ascii_isspace (*p)) ++p;
1567 if (*prot_start != 'r' && *prot_start != '-') {
1570 memcpy (prot_buf, prot_start, 4);
1572 while (!g_ascii_isspace (*p)) ++p;
1574 while (g_ascii_isspace (*p)) ++p;
1576 if (!g_ascii_isxdigit (*offset_start)) {
1579 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1581 if (!g_ascii_isspace (*p)) {
1585 while(g_ascii_isspace (*p)) ++p;
1587 if (!g_ascii_isxdigit (*maj_dev_start)) {
1590 maj_dev = strtoul (maj_dev_start, &endp, 16);
1598 if (!g_ascii_isxdigit (*min_dev_start)) {
1601 min_dev = strtoul (min_dev_start, &endp, 16);
1603 if (!g_ascii_isspace (*p)) {
1607 while (g_ascii_isspace (*p)) ++p;
1609 if (!g_ascii_isxdigit (*inode_start)) {
1612 inode = (guint64)strtol (inode_start, &endp, 10);
1614 if (!g_ascii_isspace (*p)) {
1618 device = makedev ((int)maj_dev, (int)min_dev);
1619 if ((device == 0) &&
1624 while(g_ascii_isspace (*p)) ++p;
1625 /* p now points to the filename */
1627 mod = g_new0 (WapiProcModule, 1);
1628 mod->address_start = address_start;
1629 mod->address_end = address_end;
1630 mod->perms = g_strdup (prot_buf);
1631 mod->address_offset = address_offset;
1632 mod->device = device;
1634 mod->filename = g_strdup (g_strstrip (p));
1636 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1637 ret = g_slist_prepend (ret, mod);
1639 free_procmodule (mod);
1643 ret = g_slist_reverse (ret);
1649 static gboolean match_procname_to_modulename (char *procname, char *modulename)
1651 char* lastsep = NULL;
1652 char* lastsep2 = NULL;
1655 gboolean result = FALSE;
1657 if (procname == NULL || modulename == NULL)
1660 pname = mono_path_resolve_symlinks (procname);
1661 mname = mono_path_resolve_symlinks (modulename);
1663 if (!strcmp (pname, mname))
1667 lastsep = strrchr (mname, '/');
1669 if (!strcmp (lastsep+1, pname))
1672 lastsep2 = strrchr (pname, '/');
1675 if (!strcmp (lastsep+1, lastsep2+1))
1678 if (!strcmp (mname, lastsep2+1))
1691 #if !defined(__OpenBSD__)
1693 open_process_map (int pid, const char *mode)
1696 const char *proc_path[] = {
1697 "/proc/%d/maps", /* GNU/Linux */
1698 "/proc/%d/map", /* FreeBSD */
1704 for (i = 0; fp == NULL && proc_path [i]; i++) {
1705 filename = g_strdup_printf (proc_path[i], pid);
1706 fp = fopen (filename, mode);
1714 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1715 guint32 size, guint32 *needed)
1717 WapiHandle_process *process_handle;
1718 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
1721 GSList *mods = NULL;
1722 WapiProcModule *module;
1723 guint32 count, avail = size / sizeof(gpointer);
1726 char *proc_name = NULL;
1728 /* Store modules in an array of pointers (main module as
1729 * modules[0]), using the load address for each module as a
1730 * token. (Use 'NULL' as an alternative for the main module
1731 * so that the simple implementation can just return one item
1732 * for now.) Get the info from /proc/<pid>/maps on linux,
1733 * /proc/<pid>/map on FreeBSD, other systems will have to
1734 * implement /dev/kmem reading or whatever other horrid
1735 * technique is needed.
1737 if (size < sizeof(gpointer))
1740 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1741 pid = WAPI_HANDLE_TO_PID (process);
1743 process_handle = lookup_process_handle (process);
1744 if (!process_handle) {
1745 DEBUG ("%s: Can't find process %p", __func__, process);
1749 pid = process_handle->id;
1750 proc_name = process_handle->proc_name;
1753 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
1754 mods = load_modules ();
1757 *needed = sizeof(gpointer);
1761 fp = open_process_map (pid, "r");
1763 /* No /proc/<pid>/maps so just return the main module
1767 *needed = sizeof(gpointer);
1770 mods = load_modules (fp);
1773 count = g_slist_length (mods);
1775 /* count + 1 to leave slot 0 for the main module */
1776 *needed = sizeof(gpointer) * (count + 1);
1779 * Use the NULL shortcut, as the first line in
1780 * /proc/<pid>/maps isn't the executable, and we need
1781 * that first in the returned list. Check the module name
1782 * to see if it ends with the proc name and substitute
1783 * the first entry with it. FIXME if this turns out to
1787 for (i = 0; i < (avail - 1) && i < count; i++) {
1788 module = (WapiProcModule *)g_slist_nth_data (mods, i);
1789 if (modules[0] != NULL)
1790 modules[i] = module->address_start;
1791 else if (match_procname_to_modulename (proc_name, module->filename))
1792 modules[0] = module->address_start;
1794 modules[i + 1] = module->address_start;
1797 for (i = 0; i < count; i++) {
1798 free_procmodule (g_slist_nth_data (mods, i));
1800 g_slist_free (mods);
1806 get_process_name_from_proc (pid_t pid)
1808 #if defined(__OpenBSD__)
1811 struct kinfo_proc *pi;
1812 #elif defined(PLATFORM_MACOSX)
1813 #if !(!defined (__mono_ppc__) && defined (TARGET_OSX))
1815 struct kinfo_proc *pi;
1816 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
1820 char *filename = NULL;
1825 #if defined(PLATFORM_SOLARIS)
1826 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
1827 if ((fp = fopen (filename, "r")) != NULL) {
1831 nread = fread (&info, sizeof (info), 1, fp);
1833 ret = g_strdup (info.pr_fname);
1839 #elif defined(PLATFORM_MACOSX)
1840 #if !defined (__mono_ppc__) && defined (TARGET_OSX)
1841 /* No proc name on OSX < 10.5 nor ppc nor iOS */
1842 memset (buf, '\0', sizeof(buf));
1843 proc_name (pid, buf, sizeof(buf));
1844 if (strlen (buf) > 0)
1845 ret = g_strdup (buf);
1847 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0)
1850 if ((pi = malloc(size)) == NULL)
1853 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
1854 if (errno == ENOMEM) {
1856 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__);
1861 if (strlen (pi->kp_proc.p_comm) > 0)
1862 ret = g_strdup (pi->kp_proc.p_comm);
1866 #elif defined(__OpenBSD__)
1868 mib [1] = KERN_PROC;
1869 mib [2] = KERN_PROC_PID;
1871 mib [4] = sizeof(struct kinfo_proc);
1875 if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0)
1878 if ((pi = malloc(size)) == NULL)
1881 mib[5] = (int)(size / sizeof(struct kinfo_proc));
1883 if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
1884 (size != sizeof (struct kinfo_proc))) {
1885 if (errno == ENOMEM) {
1892 if (strlen (pi->p_comm) > 0)
1893 ret = g_strdup (pi->p_comm);
1896 #elif defined(__HAIKU__)
1897 image_info imageInfo;
1900 if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
1901 ret = g_strdup (imageInfo.name);
1904 memset (buf, '\0', sizeof(buf));
1905 filename = g_strdup_printf ("/proc/%d/exe", pid);
1906 if (readlink (filename, buf, 255) > 0) {
1907 ret = g_strdup (buf);
1915 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
1916 if ((fp = fopen (filename, "r")) != NULL) {
1917 if (fgets (buf, 256, fp) != NULL) {
1918 ret = g_strdup (buf);
1929 filename = g_strdup_printf ("/proc/%d/stat", pid);
1930 if ((fp = fopen (filename, "r")) != NULL) {
1931 if (fgets (buf, 256, fp) != NULL) {
1934 start = strchr (buf, '(');
1935 if (start != NULL) {
1936 end = strchr (start + 1, ')');
1939 ret = g_strndup (start + 1,
1954 * wapi_process_get_path:
1956 * Return the full path of the executable of the process PID, or NULL if it cannot be determined.
1957 * Returns malloc-ed memory.
1960 wapi_process_get_path (pid_t pid)
1962 #if defined(PLATFORM_MACOSX) && !defined(__mono_ppc__) && defined(TARGET_OSX)
1963 char buf [PROC_PIDPATHINFO_MAXSIZE];
1966 res = proc_pidpath (pid, buf, sizeof (buf));
1969 if (buf [0] == '\0')
1971 return g_strdup (buf);
1973 return get_process_name_from_proc (pid);
1978 * wapi_process_set_cli_launcher:
1980 * Set the full path of the runtime executable used to launch managed exe's.
1983 wapi_process_set_cli_launcher (char *path)
1985 g_free (cli_launcher);
1986 cli_launcher = path ? g_strdup (path) : NULL;
1990 get_module_name (gpointer process, gpointer module,
1991 gunichar2 *basename, guint32 size,
1994 WapiHandle_process *process_handle;
1996 gunichar2 *procname;
1997 char *procname_ext = NULL;
2000 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2003 GSList *mods = NULL;
2004 WapiProcModule *found_module;
2007 char *proc_name = NULL;
2009 DEBUG ("%s: Getting module base name, process handle %p module %p",
2010 __func__, process, module);
2012 size = size * sizeof (gunichar2); /* adjust for unicode characters */
2014 if (basename == NULL || size == 0)
2017 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2018 /* This is a pseudo handle */
2019 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2020 proc_name = get_process_name_from_proc (pid);
2022 process_handle = lookup_process_handle (process);
2023 if (!process_handle) {
2024 DEBUG ("%s: Can't find process %p", __func__,
2029 pid = process_handle->id;
2030 proc_name = g_strdup (process_handle->proc_name);
2033 /* Look up the address in /proc/<pid>/maps */
2034 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2035 mods = load_modules ();
2037 fp = open_process_map (pid, "r");
2039 if (errno == EACCES && module == NULL && base == TRUE) {
2040 procname_ext = get_process_name_from_proc (pid);
2042 /* No /proc/<pid>/maps, so just return failure
2049 mods = load_modules (fp);
2053 count = g_slist_length (mods);
2055 /* If module != NULL compare the address.
2056 * If module == NULL we are looking for the main module.
2057 * The best we can do for now check it the module name end with the process name.
2059 for (i = 0; i < count; i++) {
2060 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2061 if (procname_ext == NULL &&
2062 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2063 (module != NULL && found_module->address_start == module))) {
2065 procname_ext = g_path_get_basename (found_module->filename);
2067 procname_ext = g_strdup (found_module->filename);
2070 free_procmodule (found_module);
2073 if (procname_ext == NULL) {
2074 /* If it's *still* null, we might have hit the
2075 * case where reading /proc/$pid/maps gives an
2076 * empty file for this user.
2078 procname_ext = get_process_name_from_proc (pid);
2081 g_slist_free (mods);
2085 DEBUG ("%s: Process name is [%s]", __func__,
2088 procname = mono_unicode_from_external (procname_ext, &bytes);
2089 if (procname == NULL) {
2091 g_free (procname_ext);
2097 /* Add the terminator */
2101 DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2103 memcpy (basename, procname, size);
2105 DEBUG ("%s: Size %d larger than needed (%ld)",
2106 __func__, size, bytes);
2108 memcpy (basename, procname, bytes);
2112 g_free (procname_ext);
2121 GetModuleBaseName (gpointer process, gpointer module,
2122 gunichar2 *basename, guint32 size)
2124 return get_module_name (process, module, basename, size, TRUE);
2128 GetModuleFileNameEx (gpointer process, gpointer module,
2129 gunichar2 *filename, guint32 size)
2131 return get_module_name (process, module, filename, size, FALSE);
2135 GetModuleInformation (gpointer process, gpointer module,
2136 WapiModuleInfo *modinfo, guint32 size)
2138 WapiHandle_process *process_handle;
2140 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2143 GSList *mods = NULL;
2144 WapiProcModule *found_module;
2147 gboolean ret = FALSE;
2148 char *proc_name = NULL;
2150 DEBUG ("%s: Getting module info, process handle %p module %p",
2151 __func__, process, module);
2153 if (modinfo == NULL || size < sizeof (WapiModuleInfo))
2156 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2157 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2158 proc_name = get_process_name_from_proc (pid);
2160 process_handle = lookup_process_handle (process);
2161 if (!process_handle) {
2162 DEBUG ("%s: Can't find process %p", __func__,
2167 pid = process_handle->id;
2168 proc_name = g_strdup (process_handle->proc_name);
2171 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2172 mods = load_modules ();
2174 /* Look up the address in /proc/<pid>/maps */
2175 if ((fp = open_process_map (pid, "r")) == NULL) {
2176 /* No /proc/<pid>/maps, so just return failure
2182 mods = load_modules (fp);
2185 count = g_slist_length (mods);
2187 /* If module != NULL compare the address.
2188 * If module == NULL we are looking for the main module.
2189 * The best we can do for now check it the module name end with the process name.
2191 for (i = 0; i < count; i++) {
2192 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2194 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2195 (module != NULL && found_module->address_start == module))) {
2196 modinfo->lpBaseOfDll = found_module->address_start;
2197 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2198 modinfo->EntryPoint = found_module->address_offset;
2202 free_procmodule (found_module);
2205 g_slist_free (mods);
2212 GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2214 WapiHandle_process *process_handle;
2216 if (min == NULL || max == NULL)
2217 /* Not sure if w32 allows NULLs here or not */
2220 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2221 /* This is a pseudo handle, so just fail for now */
2224 process_handle = lookup_process_handle (process);
2225 if (!process_handle) {
2226 DEBUG ("%s: Can't find process %p", __func__, process);
2231 *min = process_handle->min_working_set;
2232 *max = process_handle->max_working_set;
2238 SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2240 WapiHandle_process *process_handle;
2242 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2243 /* This is a pseudo handle, so just fail for now
2247 process_handle = lookup_process_handle (process);
2248 if (!process_handle) {
2249 DEBUG ("%s: Can't find process %p", __func__, process);
2254 process_handle->min_working_set = min;
2255 process_handle->max_working_set = max;
2262 TerminateProcess (gpointer process, gint32 exitCode)
2264 WapiHandle_process *process_handle;
2269 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2270 /* This is a pseudo handle */
2271 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2273 process_handle = lookup_process_handle (process);
2274 if (!process_handle) {
2275 DEBUG ("%s: Can't find process %p", __func__, process);
2276 SetLastError (ERROR_INVALID_HANDLE);
2279 pid = process_handle->id;
2282 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2283 ret = kill (pid, signo);
2287 SetLastError (ERROR_INVALID_PARAMETER);
2290 SetLastError (ERROR_ACCESS_DENIED);
2293 SetLastError (ERROR_PROC_NOT_FOUND);
2296 SetLastError (ERROR_GEN_FAILURE);
2304 GetPriorityClass (gpointer process)
2306 #ifdef HAVE_GETPRIORITY
2307 WapiHandle_process *process_handle;
2311 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2312 /* This is a pseudo handle */
2313 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2315 process_handle = lookup_process_handle (process);
2316 if (!process_handle) {
2317 SetLastError (ERROR_INVALID_HANDLE);
2320 pid = process_handle->id;
2324 ret = getpriority (PRIO_PROCESS, pid);
2325 if (ret == -1 && errno != 0) {
2329 SetLastError (ERROR_ACCESS_DENIED);
2332 SetLastError (ERROR_PROC_NOT_FOUND);
2335 SetLastError (ERROR_GEN_FAILURE);
2341 return NORMAL_PRIORITY_CLASS;
2343 return REALTIME_PRIORITY_CLASS;
2345 return HIGH_PRIORITY_CLASS;
2347 return ABOVE_NORMAL_PRIORITY_CLASS;
2349 return IDLE_PRIORITY_CLASS;
2351 return BELOW_NORMAL_PRIORITY_CLASS;
2353 return NORMAL_PRIORITY_CLASS;
2355 SetLastError (ERROR_NOT_SUPPORTED);
2361 SetPriorityClass (gpointer process, guint32 priority_class)
2363 #ifdef HAVE_SETPRIORITY
2364 WapiHandle_process *process_handle;
2369 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2370 /* This is a pseudo handle */
2371 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2373 process_handle = lookup_process_handle (process);
2374 if (!process_handle) {
2375 SetLastError (ERROR_INVALID_HANDLE);
2378 pid = process_handle->id;
2381 switch (priority_class) {
2382 case IDLE_PRIORITY_CLASS:
2385 case BELOW_NORMAL_PRIORITY_CLASS:
2388 case NORMAL_PRIORITY_CLASS:
2391 case ABOVE_NORMAL_PRIORITY_CLASS:
2394 case HIGH_PRIORITY_CLASS:
2397 case REALTIME_PRIORITY_CLASS:
2401 SetLastError (ERROR_INVALID_PARAMETER);
2405 ret = setpriority (PRIO_PROCESS, pid, prio);
2410 SetLastError (ERROR_ACCESS_DENIED);
2413 SetLastError (ERROR_PROC_NOT_FOUND);
2416 SetLastError (ERROR_GEN_FAILURE);
2422 SetLastError (ERROR_NOT_SUPPORTED);
2428 mono_processes_cleanup (void)
2430 struct MonoProcess *mp;
2431 struct MonoProcess *prev = NULL;
2432 struct MonoProcess *candidate = NULL;
2433 gpointer unref_handle;
2436 DEBUG ("%s", __func__);
2438 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2439 if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
2442 mp = mono_processes;
2443 while (mp != NULL) {
2444 if (mp->pid == 0 && mp->handle != NULL) {
2445 /* This process has exited and we need to remove the artifical ref
2447 mono_mutex_lock (&mono_processes_mutex);
2448 unref_handle = mp->handle;
2450 mono_mutex_unlock (&mono_processes_mutex);
2452 _wapi_handle_unref (unref_handle);
2459 * Remove processes which exited from the mono_processes list.
2460 * We need to synchronize with the sigchld handler here, which runs
2461 * asynchronously. The handler requires that the mono_processes list
2464 mp = mono_processes;
2466 while (mp != NULL) {
2467 if ((mp->handle_count == 0 && mp->pid == 0) || candidate != NULL) {
2469 _wapi_handle_spin (spin);
2473 /* We've found a candidate */
2474 mono_mutex_lock (&mono_processes_mutex);
2476 * This code can run parallel with the sigchld handler, but the
2477 * modifications it makes are safe.
2479 if (candidate == NULL) {
2481 if (mp == mono_processes) {
2482 mono_processes = mp->next;
2484 prev->next = mp->next;
2489 /* It's still safe to traverse the structure.*/
2490 mono_memory_barrier ();
2492 if (mono_processes_read_lock != 0) {
2493 /* The sigchld handler is watching us. Spin a bit and try again */
2496 } else if (spin >= 8) {
2497 /* Just give up for now */
2498 mono_mutex_unlock (&mono_processes_mutex);
2502 /* We've modified the list of processes, and we know the sigchld handler
2503 * isn't executing, so even if it executes at any moment, it'll see the
2504 * new version of the list. So now we can free the candidate. */
2505 DEBUG ("%s: freeing candidate %p", __func__, candidate);
2506 mp = candidate->next;
2507 MONO_SEM_DESTROY (&candidate->exit_sem);
2512 mono_mutex_unlock (&mono_processes_mutex);
2521 DEBUG ("%s done", __func__);
2523 InterlockedDecrement (&mono_processes_cleaning_up);
2527 process_close (gpointer handle, gpointer data)
2529 WapiHandle_process *process_handle;
2531 DEBUG ("%s", __func__);
2533 process_handle = (WapiHandle_process *) data;
2534 g_free (process_handle->proc_name);
2535 process_handle->proc_name = NULL;
2536 if (process_handle->mono_process)
2537 InterlockedDecrement (&process_handle->mono_process->handle_count);
2538 mono_processes_cleanup ();
2542 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
2546 struct MonoProcess *p;
2548 DEBUG ("SIG CHILD handler for pid: %i\n", info->si_pid);
2550 InterlockedIncrement (&mono_processes_read_lock);
2554 pid = waitpid (-1, &status, WNOHANG);
2555 } while (pid == -1 && errno == EINTR);
2560 DEBUG ("child ended: %i", pid);
2563 if (p->pid == pid) {
2564 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2566 MONO_SEM_POST (&p->exit_sem);
2573 InterlockedDecrement (&mono_processes_read_lock);
2575 DEBUG ("SIG CHILD handler: done looping.");
2581 process_add_sigchld_handler (void)
2584 struct sigaction sa;
2586 sa.sa_sigaction = mono_sigchld_signal_handler;
2587 sigemptyset (&sa.sa_mask);
2588 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2589 g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2590 DEBUG ("Added SIGCHLD handler");
2595 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2597 WapiHandle_process *process_handle;
2602 struct MonoProcess *mp;
2604 /* FIXME: We can now easily wait on processes that aren't our own children,
2605 * but WaitFor*Object won't call us for pseudo handles. */
2606 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2608 DEBUG ("%s (%p, %u)", __func__, handle, timeout);
2610 process_handle = lookup_process_handle (handle);
2611 if (!process_handle) {
2612 g_warning ("%s: error looking up process handle %p", __func__, handle);
2616 if (process_handle->exited) {
2617 /* We've already done this one */
2618 DEBUG ("%s (%p, %u): Process already exited", __func__, handle, timeout);
2619 return WAIT_OBJECT_0;
2622 pid = process_handle->id;
2624 DEBUG ("%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2626 /* We don't need to lock mono_processes here, the entry
2627 * has a handle_count > 0 which means it will not be freed. */
2628 mp = process_handle->mono_process;
2631 start = mono_msec_ticks ();
2635 if (timeout != INFINITE) {
2636 DEBUG ("%s (%p, %u): waiting on semaphore for %li ms...",
2637 __func__, handle, timeout, (timeout - (now - start)));
2639 ret = MONO_SEM_TIMEDWAIT_ALERTABLE (&mp->exit_sem, (timeout - (now - start)), alertable);
2641 DEBUG ("%s (%p, %u): waiting on semaphore forever...",
2642 __func__, handle, timeout);
2643 ret = MONO_SEM_WAIT_ALERTABLE (&mp->exit_sem, alertable);
2646 if (ret == -1 && errno != EINTR && errno != ETIMEDOUT) {
2647 DEBUG ("%s (%p, %u): sem_timedwait failure: %s",
2648 __func__, handle, timeout, g_strerror (errno));
2649 /* Should we return a failure here? */
2653 /* Success, process has exited */
2654 MONO_SEM_POST (&mp->exit_sem);
2659 DEBUG ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
2660 return WAIT_TIMEOUT;
2663 now = mono_msec_ticks ();
2664 if (now - start >= timeout) {
2665 DEBUG ("%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
2666 return WAIT_TIMEOUT;
2669 if (alertable && _wapi_thread_cur_apc_pending ()) {
2670 DEBUG ("%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
2671 return WAIT_IO_COMPLETION;
2675 /* Process must have exited */
2676 DEBUG ("%s (%p, %u): Waited successfully", __func__, handle, timeout);
2678 ret = _wapi_handle_lock_shared_handles ();
2679 g_assert (ret == 0);
2681 status = mp ? mp->status : 0;
2682 if (WIFSIGNALED (status))
2683 process_handle->exitstatus = 128 + WTERMSIG (status);
2685 process_handle->exitstatus = WEXITSTATUS (status);
2686 _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
2688 process_handle->exited = TRUE;
2690 DEBUG ("%s (%p, %u): Setting pid %d signalled, exit status %d",
2691 __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
2693 _wapi_handle_set_signal_state (handle, TRUE, TRUE);
2695 _wapi_handle_unlock_shared_handles ();
2697 return WAIT_OBJECT_0;
2701 wapi_processes_cleanup (void)
2703 g_free (cli_launcher);