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>
25 #include <sys/resource.h>
27 #ifdef HAVE_SYS_PARAM_H
28 #include <sys/param.h>
32 #ifdef HAVE_SYS_MKDEV_H
33 #include <sys/mkdev.h>
36 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
38 #include <TargetConditionals.h>
39 #include <sys/resource.h>
46 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
48 #include <sys/sysctl.h>
49 # if !defined(__OpenBSD__)
50 # include <sys/utsname.h>
54 #ifdef PLATFORM_SOLARIS
55 /* procfs.h cannot be included if this define is set, but it seems to work fine if it is undefined */
56 #if _FILE_OFFSET_BITS == 64
57 #undef _FILE_OFFSET_BITS
59 #define _FILE_OFFSET_BITS 64
66 #include <KernelKit.h>
69 #include <mono/io-layer/wapi.h>
70 #include <mono/io-layer/wapi-private.h>
71 #include <mono/io-layer/handles-private.h>
72 #include <mono/io-layer/misc-private.h>
73 #include <mono/io-layer/process-private.h>
74 #include <mono/io-layer/threads.h>
75 #include <mono/utils/strenc.h>
76 #include <mono/utils/mono-path.h>
77 #include <mono/io-layer/timefuncs-private.h>
78 #include <mono/utils/mono-time.h>
79 #include <mono/utils/mono-membar.h>
80 #include <mono/utils/mono-mutex.h>
81 #include <mono/utils/mono-signal-handler.h>
83 /* The process' environment strings */
84 #if defined(__APPLE__) && !defined (__arm__)
85 /* Apple defines this in crt_externs.h but doesn't provide that header for
86 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
87 * in fact exist on all implementations (so far)
89 char ***_NSGetEnviron(void);
90 #define environ (*_NSGetEnviron())
92 extern char **environ;
96 #define DEBUG(...) g_message(__VA_ARGS__)
97 #define DEBUG_ENABLED 1
102 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable);
103 static void process_close (gpointer handle, gpointer data);
104 static gboolean is_pid_valid (pid_t pid);
106 #if !defined(__OpenBSD__)
108 open_process_map (int pid, const char *mode);
111 struct _WapiHandleOps _wapi_process_ops = {
112 process_close, /* close_shared */
116 process_wait, /* special_wait */
121 static struct sigaction previous_chld_sa;
123 static mono_once_t process_sig_chld_once = MONO_ONCE_INIT;
124 static void process_add_sigchld_handler (void);
126 /* The signal-safe logic to use mono_processes goes like this:
127 * - The list must be safe to traverse for the signal handler at all times.
128 * It's safe to: prepend an entry (which is a single store to 'mono_processes'),
129 * unlink an entry (assuming the unlinked entry isn't freed and doesn't
130 * change its 'next' pointer so that it can still be traversed).
131 * When cleaning up we first unlink an entry, then we verify that
132 * the read lock isn't locked. Then we can free the entry, since
133 * we know that nobody is using the old version of the list (including
134 * the unlinked entry).
135 * We also need to lock when adding and cleaning up so that those two
136 * operations don't mess with eachother. (This lock is not used in the
139 static struct MonoProcess *mono_processes = NULL;
140 static volatile gint32 mono_processes_read_lock = 0;
141 static volatile gint32 mono_processes_cleaning_up = 0;
142 static mono_mutex_t mono_processes_mutex;
143 static void mono_processes_cleanup (void);
145 static gpointer current_process;
146 static char *cli_launcher;
148 static WapiHandle_process *
149 lookup_process_handle (gpointer handle)
151 WapiHandle_process *process_data;
154 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
155 (gpointer *)&process_data);
161 /* Check if a pid is valid - i.e. if a process exists with this pid. */
163 is_pid_valid (pid_t pid)
165 gboolean result = FALSE;
167 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
168 if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
170 #elif defined(__HAIKU__)
172 if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
175 char *dir = g_strdup_printf ("/proc/%d", pid);
176 if (!access (dir, F_OK))
185 process_set_defaults (WapiHandle_process *process_handle)
187 /* These seem to be the defaults on w2k */
188 process_handle->min_working_set = 204800;
189 process_handle->max_working_set = 1413120;
191 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
195 len16 (const gunichar2 *str)
206 utf16_concat (const gunichar2 *first, ...)
213 va_start (args, first);
214 total += len16 (first);
215 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
220 ret = g_new (gunichar2, total + 1);
226 for (s = first; *s != 0; s++)
228 va_start (args, first);
229 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
232 for (p = s; *p != 0; p++)
240 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
241 static const gunichar2 *utf16_space = utf16_space_bytes;
242 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
243 static const gunichar2 *utf16_quote = utf16_quote_bytes;
248 print_utf16 (gunichar2 *str)
252 res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
253 g_print ("%s\n", res);
258 /* Implemented as just a wrapper around CreateProcess () */
260 ShellExecuteEx (WapiShellExecuteInfo *sei)
263 WapiProcessInformation process_info;
267 /* w2k just segfaults here, but we can do better than
270 SetLastError (ERROR_INVALID_PARAMETER);
274 if (sei->lpFile == NULL)
275 /* w2k returns TRUE for this, for some reason. */
278 /* Put both executable and parameters into the second argument
279 * to CreateProcess (), so it searches $PATH. The conversion
280 * into and back out of utf8 is because there is no
281 * g_strdup_printf () equivalent for gunichar2 :-(
283 args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
285 SetLastError (ERROR_INVALID_DATA);
288 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
289 CREATE_UNICODE_ENVIRONMENT, NULL,
290 sei->lpDirectory, NULL, &process_info);
293 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
297 static char *handler;
298 static gunichar2 *handler_utf16;
300 if (handler_utf16 == (gunichar2 *)-1)
303 #ifdef PLATFORM_MACOSX
304 handler = g_strdup ("/usr/bin/open");
307 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
308 * if that fails, try to use gnome-open, then kfmclient
310 handler = g_find_program_in_path ("xdg-open");
311 if (handler == NULL){
312 handler = g_find_program_in_path ("gnome-open");
313 if (handler == NULL){
314 handler = g_find_program_in_path ("kfmclient");
315 if (handler == NULL){
316 handler_utf16 = (gunichar2 *) -1;
319 /* kfmclient needs exec argument */
321 handler = g_strconcat (old, " exec",
328 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
331 /* Put quotes around the filename, in case it's a url
332 * that contains #'s (CreateProcess() calls
333 * g_shell_parse_argv(), which deliberately throws
334 * away anything after an unquoted #). Fixes bug
337 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
338 sei->lpFile, utf16_quote,
339 sei->lpParameters == NULL ? NULL : utf16_space,
340 sei->lpParameters, NULL);
342 SetLastError (ERROR_INVALID_DATA);
345 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
346 CREATE_UNICODE_ENVIRONMENT, NULL,
347 sei->lpDirectory, NULL, &process_info);
350 if (GetLastError () != ERROR_OUTOFMEMORY)
351 SetLastError (ERROR_INVALID_DATA);
354 /* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
355 CloseHandle (process_info.hProcess);
356 process_info.hProcess = NULL;
359 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS)
360 sei->hProcess = process_info.hProcess;
362 CloseHandle (process_info.hProcess);
368 is_managed_binary (const char *filename)
370 int original_errno = errno;
371 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
372 int file = open (filename, O_RDONLY | O_LARGEFILE);
374 int file = open (filename, O_RDONLY);
377 unsigned char buffer[8];
378 off_t file_size, optional_header_offset;
379 off_t pe_header_offset;
380 gboolean managed = FALSE;
382 guint32 first_word, second_word;
384 /* If we are unable to open the file, then we definitely
385 * can't say that it is managed. The child mono process
386 * probably wouldn't be able to open it anyway.
389 errno = original_errno;
393 /* Retrieve the length of the file for future sanity checks. */
394 file_size = lseek (file, 0, SEEK_END);
395 lseek (file, 0, SEEK_SET);
397 /* We know we need to read a header field at offset 60. */
401 num_read = read (file, buffer, 2);
403 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
406 new_offset = lseek (file, 60, SEEK_SET);
408 if (new_offset != 60)
411 num_read = read (file, buffer, 4);
415 pe_header_offset = buffer[0]
420 if (pe_header_offset + 24 > file_size)
423 new_offset = lseek (file, pe_header_offset, SEEK_SET);
425 if (new_offset != pe_header_offset)
428 num_read = read (file, buffer, 4);
430 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
434 * Verify that the header we want in the optional header data
435 * is present in this binary.
437 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
439 if (new_offset != pe_header_offset + 20)
442 num_read = read (file, buffer, 2);
444 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
447 /* Read the CLR header address and size fields. These will be
448 * zero if the binary is not managed.
450 optional_header_offset = pe_header_offset + 24;
451 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
453 if (new_offset != optional_header_offset + 208)
456 num_read = read (file, buffer, 8);
458 /* We are not concerned with endianness, only with
459 * whether it is zero or not.
461 first_word = *(guint32 *)&buffer[0];
462 second_word = *(guint32 *)&buffer[4];
464 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
471 errno = original_errno;
476 CreateProcessWithLogonW (const gunichar2 *username,
477 const gunichar2 *domain,
478 const gunichar2 *password,
479 const guint32 logonFlags,
480 const gunichar2 *appname,
481 const gunichar2 *cmdline,
482 guint32 create_flags,
484 const gunichar2 *cwd,
485 WapiStartupInfo *startup,
486 WapiProcessInformation *process_info)
488 /* FIXME: use user information */
489 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
493 is_readable (const char *prog)
496 if (access (prog, R_OK) != 0)
498 if (stat (prog, &buf))
500 if (S_ISREG (buf.st_mode))
506 is_executable (const char *prog)
509 if (access (prog, X_OK) != 0)
511 if (stat (prog, &buf))
513 if (S_ISREG (buf.st_mode))
519 switch_dir_separators (char *path)
521 size_t i, pathLength = strlen(path);
523 /* Turn all the slashes round the right way, except for \' */
524 /* There are probably other characters that need to be excluded as well. */
525 for (i = 0; i < pathLength; i++) {
526 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' )
531 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
532 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
533 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
534 gboolean inherit_handles, guint32 create_flags,
535 gpointer new_environ, const gunichar2 *cwd,
536 WapiStartupInfo *startup,
537 WapiProcessInformation *process_info)
539 char *cmd = NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL;
540 char *dir = NULL, **env_strings = NULL, **argv = NULL;
541 guint32 i, env_count = 0;
542 gboolean ret = FALSE;
544 WapiHandle_process process_handle = {0}, *process_handle_data;
546 int in_fd, out_fd, err_fd;
549 int startup_pipe [2] = {-1, -1};
551 struct MonoProcess *mono_process;
552 gboolean fork_failed = FALSE;
554 mono_once (&process_sig_chld_once, process_add_sigchld_handler);
556 /* appname and cmdline specify the executable and its args:
558 * If appname is not NULL, it is the name of the executable.
559 * Otherwise the executable is the first token in cmdline.
561 * Executable searching:
563 * If appname is not NULL, it can specify the full path and
564 * file name, or else a partial name and the current directory
565 * will be used. There is no additional searching.
567 * If appname is NULL, the first whitespace-delimited token in
568 * cmdline is used. If the name does not contain a full
569 * directory path, the search sequence is:
571 * 1) The directory containing the current process
572 * 2) The current working directory
573 * 3) The windows system directory (Ignored)
574 * 4) The windows directory (Ignored)
577 * Just to make things more interesting, tokens can contain
578 * white space if they are surrounded by quotation marks. I'm
579 * beginning to understand just why windows apps are generally
580 * so crap, with an API like this :-(
582 if (appname != NULL) {
583 cmd = mono_unicode_to_external (appname);
585 DEBUG ("%s: unicode conversion returned NULL",
588 SetLastError (ERROR_PATH_NOT_FOUND);
592 switch_dir_separators(cmd);
595 if (cmdline != NULL) {
596 args = mono_unicode_to_external (cmdline);
598 DEBUG ("%s: unicode conversion returned NULL", __func__);
600 SetLastError (ERROR_PATH_NOT_FOUND);
606 dir = mono_unicode_to_external (cwd);
608 DEBUG ("%s: unicode conversion returned NULL", __func__);
610 SetLastError (ERROR_PATH_NOT_FOUND);
614 /* Turn all the slashes round the right way */
615 switch_dir_separators(dir);
619 /* We can't put off locating the executable any longer :-( */
622 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
623 /* Strip off the drive letter. I can't
624 * believe that CP/M holdover is still
627 g_memmove (cmd, cmd+2, strlen (cmd)-2);
628 cmd[strlen (cmd)-2] = '\0';
631 unquoted = g_shell_unquote (cmd, NULL);
632 if (unquoted[0] == '/') {
633 /* Assume full path given */
634 prog = g_strdup (unquoted);
636 /* Executable existing ? */
637 if (!is_readable (prog)) {
638 DEBUG ("%s: Couldn't find executable %s",
641 SetLastError (ERROR_FILE_NOT_FOUND);
645 /* Search for file named by cmd in the current
648 char *curdir = g_get_current_dir ();
650 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
653 /* And make sure it's readable */
654 if (!is_readable (prog)) {
655 DEBUG ("%s: Couldn't find executable %s",
658 SetLastError (ERROR_FILE_NOT_FOUND);
664 args_after_prog = args;
669 /* Dig out the first token from args, taking quotation
673 /* First, strip off all leading whitespace */
674 args = g_strchug (args);
676 /* args_after_prog points to the contents of args
677 * after token has been set (otherwise argv[0] is
680 args_after_prog = args;
682 /* Assume the opening quote will always be the first
685 if (args[0] == '\"' || args [0] == '\'') {
687 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
688 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
689 /* We found the first token */
690 token = g_strndup (args+1, i-1);
691 args_after_prog = g_strchug (args + i + 1);
693 /* Quotation mark appeared in the
694 * middle of the token. Just give the
695 * whole first token, quotes and all,
702 /* No quote mark, or malformed */
703 for (i = 0; args[i] != '\0'; i++) {
704 if (g_ascii_isspace (args[i])) {
705 token = g_strndup (args, i);
706 args_after_prog = args + i + 1;
712 if (token == NULL && args[0] != '\0') {
713 /* Must be just one token in the string */
714 token = g_strdup (args);
715 args_after_prog = NULL;
720 DEBUG ("%s: Couldn't find what to exec", __func__);
722 SetLastError (ERROR_PATH_NOT_FOUND);
726 /* Turn all the slashes round the right way. Only for
729 switch_dir_separators(token);
731 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
732 /* Strip off the drive letter. I can't
733 * believe that CP/M holdover is still
736 g_memmove (token, token+2, strlen (token)-2);
737 token[strlen (token)-2] = '\0';
740 if (token[0] == '/') {
741 /* Assume full path given */
742 prog = g_strdup (token);
744 /* Executable existing ? */
745 if (!is_readable (prog)) {
746 DEBUG ("%s: Couldn't find executable %s",
749 SetLastError (ERROR_FILE_NOT_FOUND);
753 char *curdir = g_get_current_dir ();
755 /* FIXME: Need to record the directory
756 * containing the current process, and check
757 * that for the new executable as the first
761 prog = g_strdup_printf ("%s/%s", curdir, token);
764 /* I assume X_OK is the criterion to use,
767 * X_OK is too strict *if* the target is a CLR binary
769 if (!is_readable (prog)) {
771 prog = g_find_program_in_path (token);
773 DEBUG ("%s: Couldn't find executable %s", __func__, token);
776 SetLastError (ERROR_FILE_NOT_FOUND);
785 DEBUG ("%s: Exec prog [%s] args [%s]", __func__, prog,
788 /* Check for CLR binaries; if found, we will try to invoke
789 * them using the same mono binary that started us.
791 if (is_managed_binary (prog)) {
792 gunichar2 *newapp = NULL, *newcmd;
796 newapp = mono_unicode_from_external (cli_launcher, &bytes_ignored);
798 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
800 if (newapp != NULL) {
801 if (appname != NULL) {
802 newcmd = utf16_concat (newapp, utf16_space,
803 appname, utf16_space,
806 newcmd = utf16_concat (newapp, utf16_space,
810 g_free ((gunichar2 *)newapp);
812 if (newcmd != NULL) {
813 ret = CreateProcess (NULL, newcmd,
817 create_flags, new_environ,
821 g_free ((gunichar2 *)newcmd);
827 if (!is_executable (prog)) {
828 DEBUG ("%s: Executable permisson not set on %s", __func__, prog);
830 SetLastError (ERROR_ACCESS_DENIED);
835 if (args_after_prog != NULL && *args_after_prog) {
838 qprog = g_shell_quote (prog);
839 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
842 full_prog = g_shell_quote (prog);
845 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
847 g_message ("CreateProcess: %s\n", gerr->message);
853 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
854 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
855 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
856 err_fd = GPOINTER_TO_UINT (startup->hStdError);
858 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
859 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
860 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
863 process_handle.proc_name = g_strdup (prog);
865 process_set_defaults (&process_handle);
867 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
868 if (handle == _WAPI_HANDLE_INVALID) {
869 g_warning ("%s: error creating process handle", __func__);
872 SetLastError (ERROR_OUTOFMEMORY);
876 /* new_environ is a block of NULL-terminated strings, which
877 * is itself NULL-terminated. Of course, passing an array of
878 * string pointers would have made things too easy :-(
880 * If new_environ is not NULL it specifies the entire set of
881 * environment variables in the new process. Otherwise the
882 * new process inherits the same environment.
885 gunichar2 *new_environp;
887 /* Count the number of strings */
888 for (new_environp = (gunichar2 *)new_environ; *new_environp;
891 while (*new_environp) {
896 /* +2: one for the process handle value, and the last
899 env_strings = g_new0 (char *, env_count + 2);
901 /* Copy each environ string into 'strings' turning it
902 * into utf8 (or the requested encoding) at the same
906 for (new_environp = (gunichar2 *)new_environ; *new_environp;
908 env_strings[env_count] = mono_unicode_to_external (new_environp);
910 while (*new_environp) {
915 for (i = 0; environ[i] != NULL; i++)
918 /* +2: one for the process handle value, and the last
921 env_strings = g_new0 (char *, env_count + 2);
923 /* Copy each environ string into 'strings' turning it
924 * into utf8 (or the requested encoding) at the same
928 for (i = 0; environ[i] != NULL; i++) {
929 env_strings[env_count] = g_strdup (environ[i]);
934 /* Create a pipe to make sure the child doesn't exit before
935 * we can add the process to the linked list of mono_processes */
936 if (pipe (startup_pipe) == -1) {
937 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
938 * This is just for a very hard to hit race condition in the first place */
939 startup_pipe [0] = startup_pipe [1] = -1;
940 DEBUG ("%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
943 thr_ret = _wapi_handle_lock_shared_handles ();
944 g_assert (thr_ret == 0);
949 SetLastError (ERROR_OUTOFMEMORY);
953 } else if (pid == 0) {
956 if (startup_pipe [0] != -1) {
957 /* Wait until the parent has updated it's internal data */
958 ssize_t _i G_GNUC_UNUSED = read (startup_pipe [0], &dummy, 1);
959 DEBUG ("%s: child: parent has completed its setup", __func__);
960 close (startup_pipe [0]);
961 close (startup_pipe [1]);
964 /* should we detach from the process group? */
966 /* Connect stdin, stdout and stderr */
971 if (inherit_handles != TRUE) {
972 /* FIXME: do something here */
975 /* Close all file descriptors */
976 for (i = wapi_getdtablesize () - 1; i > 2; i--)
980 DEBUG ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
981 dir == NULL?".":dir);
982 for (i = 0; argv[i] != NULL; i++)
983 g_message ("arg %d: [%s]", i, argv[i]);
985 for (i = 0; env_strings[i] != NULL; i++)
986 g_message ("env %d: [%s]", i, env_strings[i]);
990 if (dir != NULL && chdir (dir) == -1) {
996 execve (argv[0], argv, env_strings);
1003 process_handle_data = lookup_process_handle (handle);
1004 if (!process_handle_data) {
1005 g_warning ("%s: error looking up process handle %p", __func__,
1007 _wapi_handle_unref (handle);
1011 process_handle_data->id = pid;
1013 /* Add our mono_process into the linked list of mono_processes */
1014 mono_process = (struct MonoProcess *) g_malloc0 (sizeof (struct MonoProcess));
1015 mono_process->pid = pid;
1016 mono_process->handle_count = 1;
1017 if (MONO_SEM_INIT (&mono_process->exit_sem, 0) != 0) {
1018 /* If we can't create the exit semaphore, we just don't add anything
1019 * to our list of mono processes. Waiting on the process will return
1021 g_warning ("%s: could not create exit semaphore for process.", strerror (errno));
1022 g_free (mono_process);
1024 /* Keep the process handle artificially alive until the process
1025 * exits so that the information in the handle isn't lost. */
1026 _wapi_handle_ref (handle);
1027 mono_process->handle = handle;
1029 process_handle_data->mono_process = mono_process;
1031 mono_mutex_lock (&mono_processes_mutex);
1032 mono_process->next = mono_processes;
1033 mono_processes = mono_process;
1034 mono_mutex_unlock (&mono_processes_mutex);
1037 if (process_info != NULL) {
1038 process_info->hProcess = handle;
1039 process_info->dwProcessId = pid;
1041 /* FIXME: we might need to handle the thread info some
1044 process_info->hThread = INVALID_HANDLE_VALUE;
1045 process_info->dwThreadId = 0;
1049 _wapi_handle_unlock_shared_handles ();
1052 _wapi_handle_unref (handle);
1054 if (startup_pipe [1] != -1) {
1055 /* Write 1 byte, doesn't matter what */
1056 ssize_t _i G_GNUC_UNUSED = write (startup_pipe [1], startup_pipe, 1);
1057 close (startup_pipe [0]);
1058 close (startup_pipe [1]);
1073 g_strfreev (env_strings);
1077 DEBUG ("%s: returning handle %p for pid %d", __func__, handle,
1080 /* Check if something needs to be cleaned up. */
1081 mono_processes_cleanup ();
1087 process_set_name (WapiHandle_process *process_handle)
1089 char *progname, *utf8_progname, *slash;
1091 progname = g_get_prgname ();
1092 utf8_progname = mono_utf8_from_external (progname);
1094 DEBUG ("%s: using [%s] as prog name", __func__, progname);
1096 if (utf8_progname) {
1097 slash = strrchr (utf8_progname, '/');
1099 process_handle->proc_name = g_strdup (slash+1);
1101 process_handle->proc_name = g_strdup (utf8_progname);
1102 g_free (utf8_progname);
1107 wapi_processes_init (void)
1109 pid_t pid = _wapi_getpid ();
1110 WapiHandle_process process_handle = {0};
1112 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
1113 WAPI_HANDLE_CAP_WAIT |
1114 WAPI_HANDLE_CAP_SPECIAL_WAIT);
1116 process_handle.id = pid;
1118 process_set_defaults (&process_handle);
1119 process_set_name (&process_handle);
1121 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1123 g_assert (current_process);
1127 _wapi_process_duplicate (void)
1129 _wapi_handle_ref (current_process);
1131 return current_process;
1134 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1136 GetCurrentProcess (void)
1138 return _WAPI_PROCESS_CURRENT;
1142 GetProcessId (gpointer handle)
1144 WapiHandle_process *process_handle;
1146 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1147 /* This is a pseudo handle */
1148 return WAPI_HANDLE_TO_PID (handle);
1150 process_handle = lookup_process_handle (handle);
1151 if (!process_handle) {
1152 SetLastError (ERROR_INVALID_HANDLE);
1156 return process_handle->id;
1160 process_open_compare (gpointer handle, gpointer user_data)
1163 WapiHandle_process *process_handle;
1166 g_assert (!WAPI_IS_PSEUDO_PROCESS_HANDLE (handle));
1168 process_handle = lookup_process_handle (handle);
1169 g_assert (process_handle);
1171 DEBUG ("%s: looking at process %d", __func__, process_handle->id);
1173 checking_pid = process_handle->id;
1175 if (checking_pid == 0)
1178 wanted_pid = GPOINTER_TO_UINT (user_data);
1180 /* It's possible to have more than one process handle with the
1181 * same pid, but only the one running process can be
1184 if (checking_pid == wanted_pid &&
1185 !_wapi_handle_issignalled (handle)) {
1186 /* If the handle is blown away in the window between
1187 * returning TRUE here and _wapi_search_handle pinging
1188 * the timestamp, the search will continue
1197 CloseProcess (gpointer handle)
1199 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1201 return CloseHandle (handle);
1205 * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1208 OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1210 /* Find the process handle that corresponds to pid */
1211 gpointer handle = NULL;
1213 DEBUG ("%s: looking for process %d", __func__, pid);
1215 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1216 process_open_compare,
1217 GUINT_TO_POINTER (pid), NULL, TRUE);
1219 if (is_pid_valid (pid)) {
1220 /* Return a pseudo handle for processes we
1221 * don't have handles for
1223 return WAPI_PID_TO_HANDLE (pid);
1225 DEBUG ("%s: Can't find pid %d", __func__, pid);
1227 SetLastError (ERROR_PROC_NOT_FOUND);
1233 /* _wapi_search_handle () already added a ref */
1238 GetExitCodeProcess (gpointer process, guint32 *code)
1240 WapiHandle_process *process_handle;
1246 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1247 pid = WAPI_HANDLE_TO_PID (process);
1248 /* This is a pseudo handle, so we don't know what the
1249 * exit code was, but we can check whether it's alive or not
1251 if (is_pid_valid (pid)) {
1252 *code = STILL_ACTIVE;
1259 process_handle = lookup_process_handle (process);
1260 if (!process_handle) {
1261 DEBUG ("%s: Can't find process %p", __func__, process);
1266 /* A process handle is only signalled if the process has exited
1267 * and has been waited for */
1269 /* Make sure any process exit has been noticed, before
1270 * checking if the process is signalled. Fixes bug 325463.
1272 process_wait (process, 0, TRUE);
1274 if (_wapi_handle_issignalled (process))
1275 *code = process_handle->exitstatus;
1277 *code = STILL_ACTIVE;
1283 GetProcessTimes (gpointer process, WapiFileTime *create_time,
1284 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1285 WapiFileTime *user_time)
1287 WapiHandle_process *process_handle;
1288 gboolean ku_times_set = FALSE;
1290 if (create_time == NULL || exit_time == NULL || kernel_time == NULL ||
1292 /* Not sure if w32 allows NULLs here or not */
1295 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
1296 /* This is a pseudo handle, so just fail for now
1300 process_handle = lookup_process_handle (process);
1301 if (!process_handle) {
1302 DEBUG ("%s: Can't find process %p", __func__, process);
1307 *create_time = process_handle->create_time;
1309 /* A process handle is only signalled if the process has
1310 * exited. Otherwise exit_time isn't set
1312 if (_wapi_handle_issignalled (process))
1313 *exit_time = process_handle->exit_time;
1315 #ifdef HAVE_GETRUSAGE
1316 if (process_handle->id == getpid ()) {
1317 struct rusage time_data;
1318 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1320 ku_times_set = TRUE;
1321 tick_val = (guint64)time_data.ru_utime.tv_sec * 10000000 + (guint64)time_data.ru_utime.tv_usec * 10;
1322 _wapi_guint64_to_filetime (tick_val, user_time);
1323 tick_val = (guint64)time_data.ru_stime.tv_sec * 10000000 + (guint64)time_data.ru_stime.tv_usec * 10;
1324 _wapi_guint64_to_filetime (tick_val, kernel_time);
1328 if (!ku_times_set) {
1329 memset (kernel_time, 0, sizeof (WapiFileTime));
1330 memset (user_time, 0, sizeof (WapiFileTime));
1338 gpointer address_start;
1339 gpointer address_end;
1341 gpointer address_offset;
1347 static void free_procmodule (WapiProcModule *mod)
1349 if (mod->perms != NULL) {
1350 g_free (mod->perms);
1352 if (mod->filename != NULL) {
1353 g_free (mod->filename);
1358 static gint find_procmodule (gconstpointer a, gconstpointer b)
1360 WapiProcModule *want = (WapiProcModule *)a;
1361 WapiProcModule *compare = (WapiProcModule *)b;
1363 if ((want->device == compare->device) &&
1364 (want->inode == compare->inode)) {
1371 #ifdef PLATFORM_MACOSX
1372 #include <mach-o/dyld.h>
1373 #include <mach-o/getsect.h>
1375 static GSList *load_modules (void)
1378 WapiProcModule *mod;
1379 uint32_t count = _dyld_image_count ();
1382 for (i = 0; i < count; i++) {
1383 #if SIZEOF_VOID_P == 8
1384 const struct mach_header_64 *hdr;
1385 const struct section_64 *sec;
1387 const struct mach_header *hdr;
1388 const struct section *sec;
1392 name = _dyld_get_image_name (i);
1393 #if SIZEOF_VOID_P == 8
1394 hdr = (const struct mach_header_64*)_dyld_get_image_header (i);
1395 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1397 hdr = _dyld_get_image_header (i);
1398 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1401 /* Some dynlibs do not have data sections on osx (#533893) */
1406 mod = g_new0 (WapiProcModule, 1);
1407 mod->address_start = GINT_TO_POINTER (sec->addr);
1408 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1409 mod->perms = g_strdup ("r--p");
1410 mod->address_offset = 0;
1411 mod->device = makedev (0, 0);
1412 mod->inode = (ino_t) i;
1413 mod->filename = g_strdup (name);
1415 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1416 ret = g_slist_prepend (ret, mod);
1418 free_procmodule (mod);
1422 ret = g_slist_reverse (ret);
1426 #elif defined(__OpenBSD__)
1428 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1430 if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1431 + sizeof (info->dlpi_phnum))
1434 struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1438 memcpy(cpy, info, sizeof(*info));
1440 g_ptr_array_add ((GPtrArray *)ptr, cpy);
1445 static GSList *load_modules (void)
1448 WapiProcModule *mod;
1449 GPtrArray *dlarray = g_ptr_array_new();
1452 if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1455 for (i = 0; i < dlarray->len; i++) {
1456 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1458 mod = g_new0 (WapiProcModule, 1);
1459 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1460 mod->address_end = (gpointer)(info->dlpi_addr +
1461 info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1462 mod->perms = g_strdup ("r--p");
1463 mod->address_offset = 0;
1464 mod->inode = (ino_t) i;
1465 mod->filename = g_strdup (info->dlpi_name);
1467 DEBUG ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1468 mod->inode, mod->filename, mod->address_start, mod->address_end);
1472 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1473 ret = g_slist_prepend (ret, mod);
1475 free_procmodule (mod);
1479 g_ptr_array_free (dlarray, TRUE);
1481 ret = g_slist_reverse (ret);
1485 #elif defined(__HAIKU__)
1487 static GSList *load_modules (void)
1490 WapiProcModule *mod;
1492 image_info imageInfo;
1494 while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
1495 mod = g_new0 (WapiProcModule, 1);
1496 mod->device = imageInfo.device;
1497 mod->inode = imageInfo.node;
1498 mod->filename = g_strdup (imageInfo.name);
1499 mod->address_start = MIN (imageInfo.text, imageInfo.data);
1500 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
1501 (uint8_t*)imageInfo.data + imageInfo.data_size);
1502 mod->perms = g_strdup ("r--p");
1503 mod->address_offset = 0;
1505 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1506 ret = g_slist_prepend (ret, mod);
1508 free_procmodule (mod);
1512 ret = g_slist_reverse (ret);
1517 static GSList *load_modules (FILE *fp)
1520 WapiProcModule *mod;
1521 char buf[MAXPATHLEN + 1], *p, *endp;
1522 char *start_start, *end_start, *prot_start, *offset_start;
1523 char *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1524 gpointer address_start, address_end, address_offset;
1525 guint32 maj_dev, min_dev;
1529 while (fgets (buf, sizeof(buf), fp)) {
1531 while (g_ascii_isspace (*p)) ++p;
1533 if (!g_ascii_isxdigit (*start_start)) {
1536 address_start = (gpointer)strtoul (start_start, &endp, 16);
1544 if (!g_ascii_isxdigit (*end_start)) {
1547 address_end = (gpointer)strtoul (end_start, &endp, 16);
1549 if (!g_ascii_isspace (*p)) {
1553 while (g_ascii_isspace (*p)) ++p;
1555 if (*prot_start != 'r' && *prot_start != '-') {
1558 memcpy (prot_buf, prot_start, 4);
1560 while (!g_ascii_isspace (*p)) ++p;
1562 while (g_ascii_isspace (*p)) ++p;
1564 if (!g_ascii_isxdigit (*offset_start)) {
1567 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1569 if (!g_ascii_isspace (*p)) {
1573 while(g_ascii_isspace (*p)) ++p;
1575 if (!g_ascii_isxdigit (*maj_dev_start)) {
1578 maj_dev = strtoul (maj_dev_start, &endp, 16);
1586 if (!g_ascii_isxdigit (*min_dev_start)) {
1589 min_dev = strtoul (min_dev_start, &endp, 16);
1591 if (!g_ascii_isspace (*p)) {
1595 while (g_ascii_isspace (*p)) ++p;
1597 if (!g_ascii_isxdigit (*inode_start)) {
1600 inode = (ino_t)strtol (inode_start, &endp, 10);
1602 if (!g_ascii_isspace (*p)) {
1606 device = makedev ((int)maj_dev, (int)min_dev);
1607 if ((device == 0) &&
1612 while(g_ascii_isspace (*p)) ++p;
1613 /* p now points to the filename */
1615 mod = g_new0 (WapiProcModule, 1);
1616 mod->address_start = address_start;
1617 mod->address_end = address_end;
1618 mod->perms = g_strdup (prot_buf);
1619 mod->address_offset = address_offset;
1620 mod->device = device;
1622 mod->filename = g_strdup (g_strstrip (p));
1624 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1625 ret = g_slist_prepend (ret, mod);
1627 free_procmodule (mod);
1631 ret = g_slist_reverse (ret);
1637 static gboolean match_procname_to_modulename (char *procname, char *modulename)
1639 char* lastsep = NULL;
1640 char* lastsep2 = NULL;
1643 gboolean result = FALSE;
1645 if (procname == NULL || modulename == NULL)
1648 pname = mono_path_resolve_symlinks (procname);
1649 mname = mono_path_resolve_symlinks (modulename);
1651 if (!strcmp (pname, mname))
1655 lastsep = strrchr (mname, '/');
1657 if (!strcmp (lastsep+1, pname))
1660 lastsep2 = strrchr (pname, '/');
1663 if (!strcmp (lastsep+1, lastsep2+1))
1666 if (!strcmp (mname, lastsep2+1))
1679 #if !defined(__OpenBSD__)
1681 open_process_map (int pid, const char *mode)
1684 const char *proc_path[] = {
1685 "/proc/%d/maps", /* GNU/Linux */
1686 "/proc/%d/map", /* FreeBSD */
1692 for (i = 0; fp == NULL && proc_path [i]; i++) {
1693 filename = g_strdup_printf (proc_path[i], pid);
1694 fp = fopen (filename, mode);
1702 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1703 guint32 size, guint32 *needed)
1705 WapiHandle_process *process_handle;
1706 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
1709 GSList *mods = NULL;
1710 WapiProcModule *module;
1711 guint32 count, avail = size / sizeof(gpointer);
1714 char *proc_name = NULL;
1716 /* Store modules in an array of pointers (main module as
1717 * modules[0]), using the load address for each module as a
1718 * token. (Use 'NULL' as an alternative for the main module
1719 * so that the simple implementation can just return one item
1720 * for now.) Get the info from /proc/<pid>/maps on linux,
1721 * /proc/<pid>/map on FreeBSD, other systems will have to
1722 * implement /dev/kmem reading or whatever other horrid
1723 * technique is needed.
1725 if (size < sizeof(gpointer))
1728 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1729 pid = WAPI_HANDLE_TO_PID (process);
1731 process_handle = lookup_process_handle (process);
1732 if (!process_handle) {
1733 DEBUG ("%s: Can't find process %p", __func__, process);
1737 pid = process_handle->id;
1738 proc_name = process_handle->proc_name;
1741 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
1742 mods = load_modules ();
1745 *needed = sizeof(gpointer);
1749 fp = open_process_map (pid, "r");
1751 /* No /proc/<pid>/maps so just return the main module
1755 *needed = sizeof(gpointer);
1758 mods = load_modules (fp);
1761 count = g_slist_length (mods);
1763 /* count + 1 to leave slot 0 for the main module */
1764 *needed = sizeof(gpointer) * (count + 1);
1767 * Use the NULL shortcut, as the first line in
1768 * /proc/<pid>/maps isn't the executable, and we need
1769 * that first in the returned list. Check the module name
1770 * to see if it ends with the proc name and substitute
1771 * the first entry with it. FIXME if this turns out to
1775 for (i = 0; i < (avail - 1) && i < count; i++) {
1776 module = (WapiProcModule *)g_slist_nth_data (mods, i);
1777 if (modules[0] != NULL)
1778 modules[i] = module->address_start;
1779 else if (match_procname_to_modulename (proc_name, module->filename))
1780 modules[0] = module->address_start;
1782 modules[i + 1] = module->address_start;
1785 for (i = 0; i < count; i++) {
1786 free_procmodule (g_slist_nth_data (mods, i));
1788 g_slist_free (mods);
1794 get_process_name_from_proc (pid_t pid)
1796 #if defined(__OpenBSD__)
1799 struct kinfo_proc *pi;
1800 #elif defined(PLATFORM_MACOSX)
1801 #if !(!defined (__mono_ppc__) && defined (TARGET_OSX))
1803 struct kinfo_proc *pi;
1804 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
1808 char *filename = NULL;
1813 #if defined(PLATFORM_SOLARIS)
1814 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
1815 if ((fp = fopen (filename, "r")) != NULL) {
1819 nread = fread (&info, sizeof (info), 1, fp);
1821 ret = g_strdup (info.pr_fname);
1827 #elif defined(PLATFORM_MACOSX)
1828 #if !defined (__mono_ppc__) && defined (TARGET_OSX)
1829 /* No proc name on OSX < 10.5 nor ppc nor iOS */
1830 memset (buf, '\0', sizeof(buf));
1831 proc_name (pid, buf, sizeof(buf));
1832 if (strlen (buf) > 0)
1833 ret = g_strdup (buf);
1835 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0)
1838 if ((pi = malloc(size)) == NULL)
1841 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
1842 if (errno == ENOMEM) {
1844 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__);
1849 if (strlen (pi->kp_proc.p_comm) > 0)
1850 ret = g_strdup (pi->kp_proc.p_comm);
1854 #elif defined(__OpenBSD__)
1856 mib [1] = KERN_PROC;
1857 mib [2] = KERN_PROC_PID;
1859 mib [4] = sizeof(struct kinfo_proc);
1863 if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0)
1866 if ((pi = malloc(size)) == NULL)
1869 mib[5] = (int)(size / sizeof(struct kinfo_proc));
1871 if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
1872 (size != sizeof (struct kinfo_proc))) {
1873 if (errno == ENOMEM) {
1880 if (strlen (pi->p_comm) > 0)
1881 ret = g_strdup (pi->p_comm);
1884 #elif defined(__HAIKU__)
1885 image_info imageInfo;
1888 if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
1889 ret = g_strdup (imageInfo.name);
1892 memset (buf, '\0', sizeof(buf));
1893 filename = g_strdup_printf ("/proc/%d/exe", pid);
1894 if (readlink (filename, buf, 255) > 0) {
1895 ret = g_strdup (buf);
1903 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
1904 if ((fp = fopen (filename, "r")) != NULL) {
1905 if (fgets (buf, 256, fp) != NULL) {
1906 ret = g_strdup (buf);
1917 filename = g_strdup_printf ("/proc/%d/stat", pid);
1918 if ((fp = fopen (filename, "r")) != NULL) {
1919 if (fgets (buf, 256, fp) != NULL) {
1922 start = strchr (buf, '(');
1923 if (start != NULL) {
1924 end = strchr (start + 1, ')');
1927 ret = g_strndup (start + 1,
1942 * wapi_process_get_path:
1944 * Return the full path of the executable of the process PID, or NULL if it cannot be determined.
1945 * Returns malloc-ed memory.
1948 wapi_process_get_path (pid_t pid)
1950 #if defined(PLATFORM_MACOSX) && !defined(__mono_ppc__) && defined(TARGET_OSX)
1951 char buf [PROC_PIDPATHINFO_MAXSIZE];
1954 res = proc_pidpath (pid, buf, sizeof (buf));
1957 if (buf [0] == '\0')
1959 return g_strdup (buf);
1961 return get_process_name_from_proc (pid);
1966 * wapi_process_set_cli_launcher:
1968 * Set the full path of the runtime executable used to launch managed exe's.
1971 wapi_process_set_cli_launcher (char *path)
1973 g_free (cli_launcher);
1974 cli_launcher = path ? g_strdup (path) : NULL;
1978 get_module_name (gpointer process, gpointer module,
1979 gunichar2 *basename, guint32 size,
1982 WapiHandle_process *process_handle;
1984 gunichar2 *procname;
1985 char *procname_ext = NULL;
1988 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
1991 GSList *mods = NULL;
1992 WapiProcModule *found_module;
1995 char *proc_name = NULL;
1997 DEBUG ("%s: Getting module base name, process handle %p module %p",
1998 __func__, process, module);
2000 size = size * sizeof (gunichar2); /* adjust for unicode characters */
2002 if (basename == NULL || size == 0)
2005 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2006 /* This is a pseudo handle */
2007 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2008 proc_name = get_process_name_from_proc (pid);
2010 process_handle = lookup_process_handle (process);
2011 if (!process_handle) {
2012 DEBUG ("%s: Can't find process %p", __func__,
2017 pid = process_handle->id;
2018 proc_name = g_strdup (process_handle->proc_name);
2021 /* Look up the address in /proc/<pid>/maps */
2022 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2023 mods = load_modules ();
2025 fp = open_process_map (pid, "r");
2027 if (errno == EACCES && module == NULL && base == TRUE) {
2028 procname_ext = get_process_name_from_proc (pid);
2030 /* No /proc/<pid>/maps, so just return failure
2037 mods = load_modules (fp);
2041 count = g_slist_length (mods);
2043 /* If module != NULL compare the address.
2044 * If module == NULL we are looking for the main module.
2045 * The best we can do for now check it the module name end with the process name.
2047 for (i = 0; i < count; i++) {
2048 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2049 if (procname_ext == NULL &&
2050 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2051 (module != NULL && found_module->address_start == module))) {
2053 procname_ext = g_path_get_basename (found_module->filename);
2055 procname_ext = g_strdup (found_module->filename);
2058 free_procmodule (found_module);
2061 if (procname_ext == NULL) {
2062 /* If it's *still* null, we might have hit the
2063 * case where reading /proc/$pid/maps gives an
2064 * empty file for this user.
2066 procname_ext = get_process_name_from_proc (pid);
2069 g_slist_free (mods);
2073 DEBUG ("%s: Process name is [%s]", __func__,
2076 procname = mono_unicode_from_external (procname_ext, &bytes);
2077 if (procname == NULL) {
2079 g_free (procname_ext);
2085 /* Add the terminator */
2089 DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2091 memcpy (basename, procname, size);
2093 DEBUG ("%s: Size %d larger than needed (%ld)",
2094 __func__, size, bytes);
2096 memcpy (basename, procname, bytes);
2100 g_free (procname_ext);
2109 GetModuleBaseName (gpointer process, gpointer module,
2110 gunichar2 *basename, guint32 size)
2112 return get_module_name (process, module, basename, size, TRUE);
2116 GetModuleFileNameEx (gpointer process, gpointer module,
2117 gunichar2 *filename, guint32 size)
2119 return get_module_name (process, module, filename, size, FALSE);
2123 GetModuleInformation (gpointer process, gpointer module,
2124 WapiModuleInfo *modinfo, guint32 size)
2126 WapiHandle_process *process_handle;
2128 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2131 GSList *mods = NULL;
2132 WapiProcModule *found_module;
2135 gboolean ret = FALSE;
2136 char *proc_name = NULL;
2138 DEBUG ("%s: Getting module info, process handle %p module %p",
2139 __func__, process, module);
2141 if (modinfo == NULL || size < sizeof (WapiModuleInfo))
2144 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2145 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2146 proc_name = get_process_name_from_proc (pid);
2148 process_handle = lookup_process_handle (process);
2149 if (!process_handle) {
2150 DEBUG ("%s: Can't find process %p", __func__,
2155 pid = process_handle->id;
2156 proc_name = g_strdup (process_handle->proc_name);
2159 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2160 mods = load_modules ();
2162 /* Look up the address in /proc/<pid>/maps */
2163 if ((fp = open_process_map (pid, "r")) == NULL) {
2164 /* No /proc/<pid>/maps, so just return failure
2170 mods = load_modules (fp);
2173 count = g_slist_length (mods);
2175 /* If module != NULL compare the address.
2176 * If module == NULL we are looking for the main module.
2177 * The best we can do for now check it the module name end with the process name.
2179 for (i = 0; i < count; i++) {
2180 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2182 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2183 (module != NULL && found_module->address_start == module))) {
2184 modinfo->lpBaseOfDll = found_module->address_start;
2185 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2186 modinfo->EntryPoint = found_module->address_offset;
2190 free_procmodule (found_module);
2193 g_slist_free (mods);
2200 GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2202 WapiHandle_process *process_handle;
2204 if (min == NULL || max == NULL)
2205 /* Not sure if w32 allows NULLs here or not */
2208 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2209 /* This is a pseudo handle, so just fail for now */
2212 process_handle = lookup_process_handle (process);
2213 if (!process_handle) {
2214 DEBUG ("%s: Can't find process %p", __func__, process);
2219 *min = process_handle->min_working_set;
2220 *max = process_handle->max_working_set;
2226 SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2228 WapiHandle_process *process_handle;
2230 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2231 /* This is a pseudo handle, so just fail for now
2235 process_handle = lookup_process_handle (process);
2236 if (!process_handle) {
2237 DEBUG ("%s: Can't find process %p", __func__, process);
2242 process_handle->min_working_set = min;
2243 process_handle->max_working_set = max;
2250 TerminateProcess (gpointer process, gint32 exitCode)
2252 WapiHandle_process *process_handle;
2257 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2258 /* This is a pseudo handle */
2259 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2261 process_handle = lookup_process_handle (process);
2262 if (!process_handle) {
2263 DEBUG ("%s: Can't find process %p", __func__, process);
2264 SetLastError (ERROR_INVALID_HANDLE);
2267 pid = process_handle->id;
2270 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2271 ret = kill (pid, signo);
2275 SetLastError (ERROR_INVALID_PARAMETER);
2278 SetLastError (ERROR_ACCESS_DENIED);
2281 SetLastError (ERROR_PROC_NOT_FOUND);
2284 SetLastError (ERROR_GEN_FAILURE);
2292 GetPriorityClass (gpointer process)
2294 #ifdef HAVE_GETPRIORITY
2295 WapiHandle_process *process_handle;
2299 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2300 /* This is a pseudo handle */
2301 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2303 process_handle = lookup_process_handle (process);
2304 if (!process_handle) {
2305 SetLastError (ERROR_INVALID_HANDLE);
2308 pid = process_handle->id;
2312 ret = getpriority (PRIO_PROCESS, pid);
2313 if (ret == -1 && errno != 0) {
2317 SetLastError (ERROR_ACCESS_DENIED);
2320 SetLastError (ERROR_PROC_NOT_FOUND);
2323 SetLastError (ERROR_GEN_FAILURE);
2329 return NORMAL_PRIORITY_CLASS;
2331 return REALTIME_PRIORITY_CLASS;
2333 return HIGH_PRIORITY_CLASS;
2335 return ABOVE_NORMAL_PRIORITY_CLASS;
2337 return IDLE_PRIORITY_CLASS;
2339 return BELOW_NORMAL_PRIORITY_CLASS;
2341 return NORMAL_PRIORITY_CLASS;
2343 SetLastError (ERROR_NOT_SUPPORTED);
2349 SetPriorityClass (gpointer process, guint32 priority_class)
2351 #ifdef HAVE_SETPRIORITY
2352 WapiHandle_process *process_handle;
2357 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2358 /* This is a pseudo handle */
2359 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2361 process_handle = lookup_process_handle (process);
2362 if (!process_handle) {
2363 SetLastError (ERROR_INVALID_HANDLE);
2366 pid = process_handle->id;
2369 switch (priority_class) {
2370 case IDLE_PRIORITY_CLASS:
2373 case BELOW_NORMAL_PRIORITY_CLASS:
2376 case NORMAL_PRIORITY_CLASS:
2379 case ABOVE_NORMAL_PRIORITY_CLASS:
2382 case HIGH_PRIORITY_CLASS:
2385 case REALTIME_PRIORITY_CLASS:
2389 SetLastError (ERROR_INVALID_PARAMETER);
2393 ret = setpriority (PRIO_PROCESS, pid, prio);
2398 SetLastError (ERROR_ACCESS_DENIED);
2401 SetLastError (ERROR_PROC_NOT_FOUND);
2404 SetLastError (ERROR_GEN_FAILURE);
2410 SetLastError (ERROR_NOT_SUPPORTED);
2416 mono_processes_cleanup (void)
2418 struct MonoProcess *mp;
2419 struct MonoProcess *prev = NULL;
2420 struct MonoProcess *candidate = NULL;
2421 gpointer unref_handle;
2424 DEBUG ("%s", __func__);
2426 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2427 if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
2430 mp = mono_processes;
2431 while (mp != NULL) {
2432 if (mp->pid == 0 && mp->handle != NULL) {
2433 /* This process has exited and we need to remove the artifical ref
2435 mono_mutex_lock (&mono_processes_mutex);
2436 unref_handle = mp->handle;
2438 mono_mutex_unlock (&mono_processes_mutex);
2440 _wapi_handle_unref (unref_handle);
2447 * Remove processes which exited from the mono_processes list.
2448 * We need to synchronize with the sigchld handler here, which runs
2449 * asynchronously. The handler requires that the mono_processes list
2452 mp = mono_processes;
2454 while (mp != NULL) {
2455 if ((mp->handle_count == 0 && mp->pid == 0) || candidate != NULL) {
2457 _wapi_handle_spin (spin);
2461 /* We've found a candidate */
2462 mono_mutex_lock (&mono_processes_mutex);
2464 * This code can run parallel with the sigchld handler, but the
2465 * modifications it makes are safe.
2467 if (candidate == NULL) {
2469 if (mp == mono_processes) {
2470 mono_processes = mp->next;
2472 prev->next = mp->next;
2477 /* It's still safe to traverse the structure.*/
2478 mono_memory_barrier ();
2480 if (mono_processes_read_lock != 0) {
2481 /* The sigchld handler is watching us. Spin a bit and try again */
2484 } else if (spin >= 8) {
2485 /* Just give up for now */
2486 mono_mutex_unlock (&mono_processes_mutex);
2490 /* We've modified the list of processes, and we know the sigchld handler
2491 * isn't executing, so even if it executes at any moment, it'll see the
2492 * new version of the list. So now we can free the candidate. */
2493 DEBUG ("%s: freeing candidate %p", __func__, candidate);
2494 mp = candidate->next;
2495 MONO_SEM_DESTROY (&candidate->exit_sem);
2500 mono_mutex_unlock (&mono_processes_mutex);
2509 DEBUG ("%s done", __func__);
2511 InterlockedDecrement (&mono_processes_cleaning_up);
2515 process_close (gpointer handle, gpointer data)
2517 WapiHandle_process *process_handle;
2519 DEBUG ("%s", __func__);
2521 process_handle = (WapiHandle_process *) data;
2522 g_free (process_handle->proc_name);
2523 process_handle->proc_name = NULL;
2524 if (process_handle->mono_process)
2525 InterlockedDecrement (&process_handle->mono_process->handle_count);
2526 mono_processes_cleanup ();
2530 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
2534 struct MonoProcess *p;
2536 DEBUG ("SIG CHILD handler for pid: %i\n", info->si_pid);
2538 InterlockedIncrement (&mono_processes_read_lock);
2542 pid = waitpid (-1, &status, WNOHANG);
2543 } while (pid == -1 && errno == EINTR);
2548 DEBUG ("child ended: %i", pid);
2551 if (p->pid == pid) {
2552 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2554 MONO_SEM_POST (&p->exit_sem);
2561 InterlockedDecrement (&mono_processes_read_lock);
2563 DEBUG ("SIG CHILD handler: done looping.");
2569 process_add_sigchld_handler (void)
2572 struct sigaction sa;
2574 sa.sa_sigaction = mono_sigchld_signal_handler;
2575 sigemptyset (&sa.sa_mask);
2576 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2577 g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2578 DEBUG ("Added SIGCHLD handler");
2583 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2585 WapiHandle_process *process_handle;
2590 struct MonoProcess *mp;
2592 /* FIXME: We can now easily wait on processes that aren't our own children,
2593 * but WaitFor*Object won't call us for pseudo handles. */
2594 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2596 DEBUG ("%s (%p, %u)", __func__, handle, timeout);
2598 process_handle = lookup_process_handle (handle);
2599 if (!process_handle) {
2600 g_warning ("%s: error looking up process handle %p", __func__, handle);
2604 if (process_handle->exited) {
2605 /* We've already done this one */
2606 DEBUG ("%s (%p, %u): Process already exited", __func__, handle, timeout);
2607 return WAIT_OBJECT_0;
2610 pid = process_handle->id;
2612 DEBUG ("%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2614 /* We don't need to lock mono_processes here, the entry
2615 * has a handle_count > 0 which means it will not be freed. */
2616 mp = process_handle->mono_process;
2619 start = mono_msec_ticks ();
2623 if (timeout != INFINITE) {
2624 DEBUG ("%s (%p, %u): waiting on semaphore for %li ms...",
2625 __func__, handle, timeout, (timeout - (now - start)));
2627 ret = MONO_SEM_TIMEDWAIT_ALERTABLE (&mp->exit_sem, (timeout - (now - start)), alertable);
2629 DEBUG ("%s (%p, %u): waiting on semaphore forever...",
2630 __func__, handle, timeout);
2631 ret = MONO_SEM_WAIT_ALERTABLE (&mp->exit_sem, alertable);
2634 if (ret == -1 && errno != EINTR && errno != ETIMEDOUT) {
2635 DEBUG ("%s (%p, %u): sem_timedwait failure: %s",
2636 __func__, handle, timeout, g_strerror (errno));
2637 /* Should we return a failure here? */
2641 /* Success, process has exited */
2642 MONO_SEM_POST (&mp->exit_sem);
2647 DEBUG ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
2648 return WAIT_TIMEOUT;
2651 now = mono_msec_ticks ();
2652 if (now - start >= timeout) {
2653 DEBUG ("%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
2654 return WAIT_TIMEOUT;
2657 if (alertable && _wapi_thread_cur_apc_pending ()) {
2658 DEBUG ("%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
2659 return WAIT_IO_COMPLETION;
2663 /* Process must have exited */
2664 DEBUG ("%s (%p, %u): Waited successfully", __func__, handle, timeout);
2666 ret = _wapi_handle_lock_shared_handles ();
2667 g_assert (ret == 0);
2669 status = mp ? mp->status : 0;
2670 if (WIFSIGNALED (status))
2671 process_handle->exitstatus = 128 + WTERMSIG (status);
2673 process_handle->exitstatus = WEXITSTATUS (status);
2674 _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
2676 process_handle->exited = TRUE;
2678 DEBUG ("%s (%p, %u): Setting pid %d signalled, exit status %d",
2679 __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
2681 _wapi_handle_set_signal_state (handle, TRUE, TRUE);
2683 _wapi_handle_unlock_shared_handles ();
2685 return WAIT_OBJECT_0;
2689 wapi_processes_cleanup (void)
2691 g_free (cli_launcher);