2 * processes.c: Process handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002-2011 Novell, Inc.
8 * Copyright 2011 Xamarin Inc
19 #include <sys/types.h>
27 #ifdef HAVE_SYS_PARAM_H
28 #include <sys/param.h>
32 #ifdef HAVE_SYS_WAIT_H
35 #ifdef HAVE_SYS_RESOURCE_H
36 #include <sys/resource.h>
39 #ifdef HAVE_SYS_MKDEV_H
40 #include <sys/mkdev.h>
47 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
49 #include <TargetConditionals.h>
50 #include <sys/resource.h>
57 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
59 #include <sys/sysctl.h>
60 # if !defined(__OpenBSD__)
61 # include <sys/utsname.h>
65 #ifdef PLATFORM_SOLARIS
66 /* procfs.h cannot be included if this define is set, but it seems to work fine if it is undefined */
67 #if _FILE_OFFSET_BITS == 64
68 #undef _FILE_OFFSET_BITS
70 #define _FILE_OFFSET_BITS 64
77 #include <KernelKit.h>
80 #include <mono/io-layer/wapi.h>
81 #include <mono/io-layer/wapi-private.h>
82 #include <mono/io-layer/handles-private.h>
83 #include <mono/io-layer/misc-private.h>
84 #include <mono/io-layer/process-private.h>
85 #include <mono/io-layer/threads.h>
86 #include <mono/utils/strenc.h>
87 #include <mono/utils/mono-path.h>
88 #include <mono/io-layer/timefuncs-private.h>
89 #include <mono/utils/mono-time.h>
90 #include <mono/utils/mono-membar.h>
91 #include <mono/utils/mono-mutex.h>
92 #include <mono/utils/mono-signal-handler.h>
93 #include <mono/utils/mono-proclib.h>
95 /* The process' environment strings */
96 #if defined(__APPLE__) && !defined (__arm__) && !defined (__aarch64__)
97 /* Apple defines this in crt_externs.h but doesn't provide that header for
98 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
99 * in fact exist on all implementations (so far)
101 char ***_NSGetEnviron(void);
102 #define environ (*_NSGetEnviron())
104 extern char **environ;
108 #define DEBUG(...) g_message(__VA_ARGS__)
109 #define DEBUG_ENABLED 1
114 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable);
115 static void process_close (gpointer handle, gpointer data);
116 static gboolean is_pid_valid (pid_t pid);
118 #if !(defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__))
120 open_process_map (int pid, const char *mode);
123 struct _WapiHandleOps _wapi_process_ops = {
124 process_close, /* close_shared */
128 process_wait, /* special_wait */
133 static struct sigaction previous_chld_sa;
135 static mono_once_t process_sig_chld_once = MONO_ONCE_INIT;
136 static void process_add_sigchld_handler (void);
138 /* The signal-safe logic to use mono_processes goes like this:
139 * - The list must be safe to traverse for the signal handler at all times.
140 * It's safe to: prepend an entry (which is a single store to 'mono_processes'),
141 * unlink an entry (assuming the unlinked entry isn't freed and doesn't
142 * change its 'next' pointer so that it can still be traversed).
143 * When cleaning up we first unlink an entry, then we verify that
144 * the read lock isn't locked. Then we can free the entry, since
145 * we know that nobody is using the old version of the list (including
146 * the unlinked entry).
147 * We also need to lock when adding and cleaning up so that those two
148 * operations don't mess with eachother. (This lock is not used in the
151 static struct MonoProcess *mono_processes = NULL;
152 static volatile gint32 mono_processes_cleaning_up = 0;
153 static mono_mutex_t mono_processes_mutex;
154 static void mono_processes_cleanup (void);
156 static gpointer current_process;
157 static char *cli_launcher;
159 static WapiHandle_process *
160 lookup_process_handle (gpointer handle)
162 WapiHandle_process *process_data;
165 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
166 (gpointer *)&process_data);
172 /* Check if a pid is valid - i.e. if a process exists with this pid. */
174 is_pid_valid (pid_t pid)
176 gboolean result = FALSE;
178 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
179 if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
181 #elif defined(__HAIKU__)
183 if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
186 char *dir = g_strdup_printf ("/proc/%d", pid);
187 if (!access (dir, F_OK))
196 process_set_defaults (WapiHandle_process *process_handle)
198 /* These seem to be the defaults on w2k */
199 process_handle->min_working_set = 204800;
200 process_handle->max_working_set = 1413120;
202 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
206 len16 (const gunichar2 *str)
217 utf16_concat (const gunichar2 *first, ...)
224 va_start (args, first);
225 total += len16 (first);
226 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
231 ret = g_new (gunichar2, total + 1);
237 for (s = first; *s != 0; s++)
239 va_start (args, first);
240 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
243 for (p = s; *p != 0; p++)
251 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
252 static const gunichar2 *utf16_space = utf16_space_bytes;
253 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
254 static const gunichar2 *utf16_quote = utf16_quote_bytes;
259 print_utf16 (gunichar2 *str)
263 res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
264 g_print ("%s\n", res);
269 /* Implemented as just a wrapper around CreateProcess () */
271 ShellExecuteEx (WapiShellExecuteInfo *sei)
274 WapiProcessInformation process_info;
278 /* w2k just segfaults here, but we can do better than
281 SetLastError (ERROR_INVALID_PARAMETER);
285 if (sei->lpFile == NULL)
286 /* w2k returns TRUE for this, for some reason. */
289 /* Put both executable and parameters into the second argument
290 * to CreateProcess (), so it searches $PATH. The conversion
291 * into and back out of utf8 is because there is no
292 * g_strdup_printf () equivalent for gunichar2 :-(
294 args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
296 SetLastError (ERROR_INVALID_DATA);
299 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
300 CREATE_UNICODE_ENVIRONMENT, NULL,
301 sei->lpDirectory, NULL, &process_info);
304 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
308 static char *handler;
309 static gunichar2 *handler_utf16;
311 if (handler_utf16 == (gunichar2 *)-1)
314 #ifdef PLATFORM_MACOSX
315 handler = g_strdup ("/usr/bin/open");
318 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
319 * if that fails, try to use gnome-open, then kfmclient
321 handler = g_find_program_in_path ("xdg-open");
322 if (handler == NULL){
323 handler = g_find_program_in_path ("gnome-open");
324 if (handler == NULL){
325 handler = g_find_program_in_path ("kfmclient");
326 if (handler == NULL){
327 handler_utf16 = (gunichar2 *) -1;
330 /* kfmclient needs exec argument */
332 handler = g_strconcat (old, " exec",
339 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
342 /* Put quotes around the filename, in case it's a url
343 * that contains #'s (CreateProcess() calls
344 * g_shell_parse_argv(), which deliberately throws
345 * away anything after an unquoted #). Fixes bug
348 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
349 sei->lpFile, utf16_quote,
350 sei->lpParameters == NULL ? NULL : utf16_space,
351 sei->lpParameters, NULL);
353 SetLastError (ERROR_INVALID_DATA);
356 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
357 CREATE_UNICODE_ENVIRONMENT, NULL,
358 sei->lpDirectory, NULL, &process_info);
361 if (GetLastError () != ERROR_OUTOFMEMORY)
362 SetLastError (ERROR_INVALID_DATA);
365 /* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
366 CloseHandle (process_info.hProcess);
367 process_info.hProcess = NULL;
370 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS)
371 sei->hProcess = process_info.hProcess;
373 CloseHandle (process_info.hProcess);
379 is_managed_binary (const char *filename)
381 int original_errno = errno;
382 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
383 int file = open (filename, O_RDONLY | O_LARGEFILE);
385 int file = open (filename, O_RDONLY);
388 unsigned char buffer[8];
389 off_t file_size, optional_header_offset;
390 off_t pe_header_offset;
391 gboolean managed = FALSE;
393 guint32 first_word, second_word;
395 /* If we are unable to open the file, then we definitely
396 * can't say that it is managed. The child mono process
397 * probably wouldn't be able to open it anyway.
400 errno = original_errno;
404 /* Retrieve the length of the file for future sanity checks. */
405 file_size = lseek (file, 0, SEEK_END);
406 lseek (file, 0, SEEK_SET);
408 /* We know we need to read a header field at offset 60. */
412 num_read = read (file, buffer, 2);
414 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
417 new_offset = lseek (file, 60, SEEK_SET);
419 if (new_offset != 60)
422 num_read = read (file, buffer, 4);
426 pe_header_offset = buffer[0]
431 if (pe_header_offset + 24 > file_size)
434 new_offset = lseek (file, pe_header_offset, SEEK_SET);
436 if (new_offset != pe_header_offset)
439 num_read = read (file, buffer, 4);
441 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
445 * Verify that the header we want in the optional header data
446 * is present in this binary.
448 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
450 if (new_offset != pe_header_offset + 20)
453 num_read = read (file, buffer, 2);
455 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
458 /* Read the CLR header address and size fields. These will be
459 * zero if the binary is not managed.
461 optional_header_offset = pe_header_offset + 24;
462 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
464 if (new_offset != optional_header_offset + 208)
467 num_read = read (file, buffer, 8);
469 /* We are not concerned with endianness, only with
470 * whether it is zero or not.
472 first_word = *(guint32 *)&buffer[0];
473 second_word = *(guint32 *)&buffer[4];
475 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
482 errno = original_errno;
487 CreateProcessWithLogonW (const gunichar2 *username,
488 const gunichar2 *domain,
489 const gunichar2 *password,
490 const guint32 logonFlags,
491 const gunichar2 *appname,
492 const gunichar2 *cmdline,
493 guint32 create_flags,
495 const gunichar2 *cwd,
496 WapiStartupInfo *startup,
497 WapiProcessInformation *process_info)
499 /* FIXME: use user information */
500 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
504 is_readable_or_executable (const char *prog)
507 int a = access (prog, R_OK);
508 int b = access (prog, X_OK);
509 if (a != 0 && b != 0)
511 if (stat (prog, &buf))
513 if (S_ISREG (buf.st_mode))
519 is_executable (const char *prog)
522 if (access (prog, X_OK) != 0)
524 if (stat (prog, &buf))
526 if (S_ISREG (buf.st_mode))
532 switch_dir_separators (char *path)
534 size_t i, pathLength = strlen(path);
536 /* Turn all the slashes round the right way, except for \' */
537 /* There are probably other characters that need to be excluded as well. */
538 for (i = 0; i < pathLength; i++) {
539 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' )
544 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
545 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
546 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
547 gboolean inherit_handles, guint32 create_flags,
548 gpointer new_environ, const gunichar2 *cwd,
549 WapiStartupInfo *startup,
550 WapiProcessInformation *process_info)
552 char *cmd = NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL;
553 char *dir = NULL, **env_strings = NULL, **argv = NULL;
554 guint32 i, env_count = 0;
555 gboolean ret = FALSE;
557 WapiHandle_process process_handle = {0}, *process_handle_data;
559 int in_fd, out_fd, err_fd;
562 int startup_pipe [2] = {-1, -1};
564 struct MonoProcess *mono_process;
565 gboolean fork_failed = FALSE;
567 mono_once (&process_sig_chld_once, process_add_sigchld_handler);
569 /* appname and cmdline specify the executable and its args:
571 * If appname is not NULL, it is the name of the executable.
572 * Otherwise the executable is the first token in cmdline.
574 * Executable searching:
576 * If appname is not NULL, it can specify the full path and
577 * file name, or else a partial name and the current directory
578 * will be used. There is no additional searching.
580 * If appname is NULL, the first whitespace-delimited token in
581 * cmdline is used. If the name does not contain a full
582 * directory path, the search sequence is:
584 * 1) The directory containing the current process
585 * 2) The current working directory
586 * 3) The windows system directory (Ignored)
587 * 4) The windows directory (Ignored)
590 * Just to make things more interesting, tokens can contain
591 * white space if they are surrounded by quotation marks. I'm
592 * beginning to understand just why windows apps are generally
593 * so crap, with an API like this :-(
595 if (appname != NULL) {
596 cmd = mono_unicode_to_external (appname);
598 DEBUG ("%s: unicode conversion returned NULL",
601 SetLastError (ERROR_PATH_NOT_FOUND);
605 switch_dir_separators(cmd);
608 if (cmdline != NULL) {
609 args = mono_unicode_to_external (cmdline);
611 DEBUG ("%s: unicode conversion returned NULL", __func__);
613 SetLastError (ERROR_PATH_NOT_FOUND);
619 dir = mono_unicode_to_external (cwd);
621 DEBUG ("%s: unicode conversion returned NULL", __func__);
623 SetLastError (ERROR_PATH_NOT_FOUND);
627 /* Turn all the slashes round the right way */
628 switch_dir_separators(dir);
632 /* We can't put off locating the executable any longer :-( */
635 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
636 /* Strip off the drive letter. I can't
637 * believe that CP/M holdover is still
640 g_memmove (cmd, cmd+2, strlen (cmd)-2);
641 cmd[strlen (cmd)-2] = '\0';
644 unquoted = g_shell_unquote (cmd, NULL);
645 if (unquoted[0] == '/') {
646 /* Assume full path given */
647 prog = g_strdup (unquoted);
649 /* Executable existing ? */
650 if (!is_readable_or_executable (prog)) {
651 DEBUG ("%s: Couldn't find executable %s",
654 SetLastError (ERROR_FILE_NOT_FOUND);
658 /* Search for file named by cmd in the current
661 char *curdir = g_get_current_dir ();
663 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
666 /* And make sure it's readable */
667 if (!is_readable_or_executable (prog)) {
668 DEBUG ("%s: Couldn't find executable %s",
671 SetLastError (ERROR_FILE_NOT_FOUND);
677 args_after_prog = args;
682 /* Dig out the first token from args, taking quotation
686 /* First, strip off all leading whitespace */
687 args = g_strchug (args);
689 /* args_after_prog points to the contents of args
690 * after token has been set (otherwise argv[0] is
693 args_after_prog = args;
695 /* Assume the opening quote will always be the first
698 if (args[0] == '\"' || args [0] == '\'') {
700 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
701 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
702 /* We found the first token */
703 token = g_strndup (args+1, i-1);
704 args_after_prog = g_strchug (args + i + 1);
706 /* Quotation mark appeared in the
707 * middle of the token. Just give the
708 * whole first token, quotes and all,
715 /* No quote mark, or malformed */
716 for (i = 0; args[i] != '\0'; i++) {
717 if (g_ascii_isspace (args[i])) {
718 token = g_strndup (args, i);
719 args_after_prog = args + i + 1;
725 if (token == NULL && args[0] != '\0') {
726 /* Must be just one token in the string */
727 token = g_strdup (args);
728 args_after_prog = NULL;
733 DEBUG ("%s: Couldn't find what to exec", __func__);
735 SetLastError (ERROR_PATH_NOT_FOUND);
739 /* Turn all the slashes round the right way. Only for
742 switch_dir_separators(token);
744 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
745 /* Strip off the drive letter. I can't
746 * believe that CP/M holdover is still
749 g_memmove (token, token+2, strlen (token)-2);
750 token[strlen (token)-2] = '\0';
753 if (token[0] == '/') {
754 /* Assume full path given */
755 prog = g_strdup (token);
757 /* Executable existing ? */
758 if (!is_readable_or_executable (prog)) {
759 DEBUG ("%s: Couldn't find executable %s",
762 SetLastError (ERROR_FILE_NOT_FOUND);
766 char *curdir = g_get_current_dir ();
768 /* FIXME: Need to record the directory
769 * containing the current process, and check
770 * that for the new executable as the first
774 prog = g_strdup_printf ("%s/%s", curdir, token);
777 /* I assume X_OK is the criterion to use,
780 * X_OK is too strict *if* the target is a CLR binary
782 if (!is_readable_or_executable (prog)) {
784 prog = g_find_program_in_path (token);
786 DEBUG ("%s: Couldn't find executable %s", __func__, token);
789 SetLastError (ERROR_FILE_NOT_FOUND);
798 DEBUG ("%s: Exec prog [%s] args [%s]", __func__, prog,
801 /* Check for CLR binaries; if found, we will try to invoke
802 * them using the same mono binary that started us.
804 if (is_managed_binary (prog)) {
805 gunichar2 *newapp = NULL, *newcmd;
809 newapp = mono_unicode_from_external (cli_launcher, &bytes_ignored);
811 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
813 if (newapp != NULL) {
814 if (appname != NULL) {
815 newcmd = utf16_concat (newapp, utf16_space,
816 appname, utf16_space,
819 newcmd = utf16_concat (newapp, utf16_space,
823 g_free ((gunichar2 *)newapp);
825 if (newcmd != NULL) {
826 ret = CreateProcess (NULL, newcmd,
830 create_flags, new_environ,
834 g_free ((gunichar2 *)newcmd);
840 if (!is_executable (prog)) {
841 DEBUG ("%s: Executable permisson not set on %s", __func__, prog);
843 SetLastError (ERROR_ACCESS_DENIED);
848 if (args_after_prog != NULL && *args_after_prog) {
851 qprog = g_shell_quote (prog);
852 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
855 full_prog = g_shell_quote (prog);
858 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
860 g_message ("CreateProcess: %s\n", gerr->message);
866 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
867 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
868 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
869 err_fd = GPOINTER_TO_UINT (startup->hStdError);
871 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
872 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
873 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
876 process_handle.proc_name = g_strdup (prog);
878 process_set_defaults (&process_handle);
880 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
881 if (handle == _WAPI_HANDLE_INVALID) {
882 g_warning ("%s: error creating process handle", __func__);
885 SetLastError (ERROR_OUTOFMEMORY);
889 /* new_environ is a block of NULL-terminated strings, which
890 * is itself NULL-terminated. Of course, passing an array of
891 * string pointers would have made things too easy :-(
893 * If new_environ is not NULL it specifies the entire set of
894 * environment variables in the new process. Otherwise the
895 * new process inherits the same environment.
898 gunichar2 *new_environp;
900 /* Count the number of strings */
901 for (new_environp = (gunichar2 *)new_environ; *new_environp;
904 while (*new_environp) {
909 /* +2: one for the process handle value, and the last
912 env_strings = g_new0 (char *, env_count + 2);
914 /* Copy each environ string into 'strings' turning it
915 * into utf8 (or the requested encoding) at the same
919 for (new_environp = (gunichar2 *)new_environ; *new_environp;
921 env_strings[env_count] = mono_unicode_to_external (new_environp);
923 while (*new_environp) {
928 for (i = 0; environ[i] != NULL; i++)
931 /* +2: one for the process handle value, and the last
934 env_strings = g_new0 (char *, env_count + 2);
936 /* Copy each environ string into 'strings' turning it
937 * into utf8 (or the requested encoding) at the same
941 for (i = 0; environ[i] != NULL; i++) {
942 env_strings[env_count] = g_strdup (environ[i]);
947 /* Create a pipe to make sure the child doesn't exit before
948 * we can add the process to the linked list of mono_processes */
949 if (pipe (startup_pipe) == -1) {
950 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
951 * This is just for a very hard to hit race condition in the first place */
952 startup_pipe [0] = startup_pipe [1] = -1;
953 DEBUG ("%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
956 thr_ret = _wapi_handle_lock_shared_handles ();
957 g_assert (thr_ret == 0);
962 SetLastError (ERROR_OUTOFMEMORY);
966 } else if (pid == 0) {
969 if (startup_pipe [0] != -1) {
970 /* Wait until the parent has updated it's internal data */
971 ssize_t _i G_GNUC_UNUSED = read (startup_pipe [0], &dummy, 1);
972 DEBUG ("%s: child: parent has completed its setup", __func__);
973 close (startup_pipe [0]);
974 close (startup_pipe [1]);
977 /* should we detach from the process group? */
979 /* Connect stdin, stdout and stderr */
984 if (inherit_handles != TRUE) {
985 /* FIXME: do something here */
988 /* Close all file descriptors */
989 for (i = wapi_getdtablesize () - 1; i > 2; i--)
993 DEBUG ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
994 dir == NULL?".":dir);
995 for (i = 0; argv[i] != NULL; i++)
996 g_message ("arg %d: [%s]", i, argv[i]);
998 for (i = 0; env_strings[i] != NULL; i++)
999 g_message ("env %d: [%s]", i, env_strings[i]);
1003 if (dir != NULL && chdir (dir) == -1) {
1009 execve (argv[0], argv, env_strings);
1016 process_handle_data = lookup_process_handle (handle);
1017 if (!process_handle_data) {
1018 g_warning ("%s: error looking up process handle %p", __func__,
1020 _wapi_handle_unref (handle);
1024 process_handle_data->id = pid;
1026 /* Add our mono_process into the linked list of mono_processes */
1027 mono_process = (struct MonoProcess *) g_malloc0 (sizeof (struct MonoProcess));
1028 mono_process->pid = pid;
1029 mono_process->handle_count = 1;
1030 if (MONO_SEM_INIT (&mono_process->exit_sem, 0) != 0) {
1031 /* If we can't create the exit semaphore, we just don't add anything
1032 * to our list of mono processes. Waiting on the process will return
1034 g_warning ("%s: could not create exit semaphore for process.", strerror (errno));
1035 g_free (mono_process);
1037 /* Keep the process handle artificially alive until the process
1038 * exits so that the information in the handle isn't lost. */
1039 _wapi_handle_ref (handle);
1040 mono_process->handle = handle;
1042 process_handle_data->mono_process = mono_process;
1044 mono_mutex_lock (&mono_processes_mutex);
1045 mono_process->next = mono_processes;
1046 mono_processes = mono_process;
1047 mono_mutex_unlock (&mono_processes_mutex);
1050 if (process_info != NULL) {
1051 process_info->hProcess = handle;
1052 process_info->dwProcessId = pid;
1054 /* FIXME: we might need to handle the thread info some
1057 process_info->hThread = INVALID_HANDLE_VALUE;
1058 process_info->dwThreadId = 0;
1062 _wapi_handle_unlock_shared_handles ();
1065 _wapi_handle_unref (handle);
1067 if (startup_pipe [1] != -1) {
1068 /* Write 1 byte, doesn't matter what */
1069 ssize_t _i G_GNUC_UNUSED = write (startup_pipe [1], startup_pipe, 1);
1070 close (startup_pipe [0]);
1071 close (startup_pipe [1]);
1086 g_strfreev (env_strings);
1090 DEBUG ("%s: returning handle %p for pid %d", __func__, handle,
1093 /* Check if something needs to be cleaned up. */
1094 mono_processes_cleanup ();
1100 process_set_name (WapiHandle_process *process_handle)
1102 char *progname, *utf8_progname, *slash;
1104 progname = g_get_prgname ();
1105 utf8_progname = mono_utf8_from_external (progname);
1107 DEBUG ("%s: using [%s] as prog name", __func__, progname);
1109 if (utf8_progname) {
1110 slash = strrchr (utf8_progname, '/');
1112 process_handle->proc_name = g_strdup (slash+1);
1114 process_handle->proc_name = g_strdup (utf8_progname);
1115 g_free (utf8_progname);
1120 wapi_processes_init (void)
1122 pid_t pid = _wapi_getpid ();
1123 WapiHandle_process process_handle = {0};
1125 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
1126 WAPI_HANDLE_CAP_WAIT |
1127 WAPI_HANDLE_CAP_SPECIAL_WAIT);
1129 process_handle.id = pid;
1131 process_set_defaults (&process_handle);
1132 process_set_name (&process_handle);
1134 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1136 g_assert (current_process);
1140 _wapi_process_duplicate (void)
1142 _wapi_handle_ref (current_process);
1144 return current_process;
1147 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1149 GetCurrentProcess (void)
1151 return _WAPI_PROCESS_CURRENT;
1155 GetProcessId (gpointer handle)
1157 WapiHandle_process *process_handle;
1159 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1160 /* This is a pseudo handle */
1161 return WAPI_HANDLE_TO_PID (handle);
1163 process_handle = lookup_process_handle (handle);
1164 if (!process_handle) {
1165 SetLastError (ERROR_INVALID_HANDLE);
1169 return process_handle->id;
1173 process_open_compare (gpointer handle, gpointer user_data)
1176 WapiHandle_process *process_handle;
1179 g_assert (!WAPI_IS_PSEUDO_PROCESS_HANDLE (handle));
1181 process_handle = lookup_process_handle (handle);
1182 g_assert (process_handle);
1184 DEBUG ("%s: looking at process %d", __func__, process_handle->id);
1186 checking_pid = process_handle->id;
1188 if (checking_pid == 0)
1191 wanted_pid = GPOINTER_TO_UINT (user_data);
1193 /* It's possible to have more than one process handle with the
1194 * same pid, but only the one running process can be
1197 if (checking_pid == wanted_pid &&
1198 !_wapi_handle_issignalled (handle)) {
1199 /* If the handle is blown away in the window between
1200 * returning TRUE here and _wapi_search_handle pinging
1201 * the timestamp, the search will continue
1210 CloseProcess (gpointer handle)
1212 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1214 return CloseHandle (handle);
1218 * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1221 OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1223 /* Find the process handle that corresponds to pid */
1224 gpointer handle = NULL;
1226 DEBUG ("%s: looking for process %d", __func__, pid);
1228 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1229 process_open_compare,
1230 GUINT_TO_POINTER (pid), NULL, TRUE);
1232 if (is_pid_valid (pid)) {
1233 /* Return a pseudo handle for processes we
1234 * don't have handles for
1236 return WAPI_PID_TO_HANDLE (pid);
1238 DEBUG ("%s: Can't find pid %d", __func__, pid);
1240 SetLastError (ERROR_PROC_NOT_FOUND);
1246 /* _wapi_search_handle () already added a ref */
1251 GetExitCodeProcess (gpointer process, guint32 *code)
1253 WapiHandle_process *process_handle;
1259 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1260 pid = WAPI_HANDLE_TO_PID (process);
1261 /* This is a pseudo handle, so we don't know what the
1262 * exit code was, but we can check whether it's alive or not
1264 if (is_pid_valid (pid)) {
1265 *code = STILL_ACTIVE;
1272 process_handle = lookup_process_handle (process);
1273 if (!process_handle) {
1274 DEBUG ("%s: Can't find process %p", __func__, process);
1279 if (process_handle->id == _wapi_getpid ()) {
1280 *code = STILL_ACTIVE;
1284 /* A process handle is only signalled if the process has exited
1285 * and has been waited for */
1287 /* Make sure any process exit has been noticed, before
1288 * checking if the process is signalled. Fixes bug 325463.
1290 process_wait (process, 0, TRUE);
1292 if (_wapi_handle_issignalled (process))
1293 *code = process_handle->exitstatus;
1295 *code = STILL_ACTIVE;
1301 GetProcessTimes (gpointer process, WapiFileTime *create_time,
1302 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1303 WapiFileTime *user_time)
1305 WapiHandle_process *process_handle;
1306 gboolean ku_times_set = FALSE;
1308 if (create_time == NULL || exit_time == NULL || kernel_time == NULL ||
1310 /* Not sure if w32 allows NULLs here or not */
1313 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1314 gpointer pid = GINT_TO_POINTER (WAPI_HANDLE_TO_PID(process));
1315 gint64 start_ticks, user_ticks, kernel_ticks;
1317 mono_process_get_times (pid, &start_ticks, &user_ticks, &kernel_ticks);
1319 _wapi_guint64_to_filetime (start_ticks, create_time);
1320 _wapi_guint64_to_filetime (user_ticks, kernel_time);
1321 _wapi_guint64_to_filetime (kernel_ticks, user_time);
1326 process_handle = lookup_process_handle (process);
1327 if (!process_handle) {
1328 DEBUG ("%s: Can't find process %p", __func__, process);
1333 *create_time = process_handle->create_time;
1335 /* A process handle is only signalled if the process has
1336 * exited. Otherwise exit_time isn't set
1338 if (_wapi_handle_issignalled (process))
1339 *exit_time = process_handle->exit_time;
1341 #ifdef HAVE_GETRUSAGE
1342 if (process_handle->id == getpid ()) {
1343 struct rusage time_data;
1344 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1346 ku_times_set = TRUE;
1347 tick_val = (guint64)time_data.ru_utime.tv_sec * 10000000 + (guint64)time_data.ru_utime.tv_usec * 10;
1348 _wapi_guint64_to_filetime (tick_val, user_time);
1349 tick_val = (guint64)time_data.ru_stime.tv_sec * 10000000 + (guint64)time_data.ru_stime.tv_usec * 10;
1350 _wapi_guint64_to_filetime (tick_val, kernel_time);
1354 if (!ku_times_set) {
1355 memset (kernel_time, 0, sizeof (WapiFileTime));
1356 memset (user_time, 0, sizeof (WapiFileTime));
1364 gpointer address_start;
1365 gpointer address_end;
1367 gpointer address_offset;
1373 static void free_procmodule (WapiProcModule *mod)
1375 if (mod->perms != NULL) {
1376 g_free (mod->perms);
1378 if (mod->filename != NULL) {
1379 g_free (mod->filename);
1384 static gint find_procmodule (gconstpointer a, gconstpointer b)
1386 WapiProcModule *want = (WapiProcModule *)a;
1387 WapiProcModule *compare = (WapiProcModule *)b;
1389 if ((want->device == compare->device) &&
1390 (want->inode == compare->inode)) {
1397 #ifdef PLATFORM_MACOSX
1398 #include <mach-o/dyld.h>
1399 #include <mach-o/getsect.h>
1401 static GSList *load_modules (void)
1404 WapiProcModule *mod;
1405 uint32_t count = _dyld_image_count ();
1408 for (i = 0; i < count; i++) {
1409 #if SIZEOF_VOID_P == 8
1410 const struct mach_header_64 *hdr;
1411 const struct section_64 *sec;
1413 const struct mach_header *hdr;
1414 const struct section *sec;
1418 name = _dyld_get_image_name (i);
1419 #if SIZEOF_VOID_P == 8
1420 hdr = (const struct mach_header_64*)_dyld_get_image_header (i);
1421 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1423 hdr = _dyld_get_image_header (i);
1424 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1427 /* Some dynlibs do not have data sections on osx (#533893) */
1432 mod = g_new0 (WapiProcModule, 1);
1433 mod->address_start = GINT_TO_POINTER (sec->addr);
1434 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1435 mod->perms = g_strdup ("r--p");
1436 mod->address_offset = 0;
1437 mod->device = makedev (0, 0);
1439 mod->filename = g_strdup (name);
1441 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1442 ret = g_slist_prepend (ret, mod);
1444 free_procmodule (mod);
1448 ret = g_slist_reverse (ret);
1452 #elif defined(__OpenBSD__)
1454 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1456 if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1457 + sizeof (info->dlpi_phnum))
1460 struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1464 memcpy(cpy, info, sizeof(*info));
1466 g_ptr_array_add ((GPtrArray *)ptr, cpy);
1471 static GSList *load_modules (void)
1474 WapiProcModule *mod;
1475 GPtrArray *dlarray = g_ptr_array_new();
1478 if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1481 for (i = 0; i < dlarray->len; i++) {
1482 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1484 mod = g_new0 (WapiProcModule, 1);
1485 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1486 mod->address_end = (gpointer)(info->dlpi_addr +
1487 info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1488 mod->perms = g_strdup ("r--p");
1489 mod->address_offset = 0;
1491 mod->filename = g_strdup (info->dlpi_name);
1493 DEBUG ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1494 mod->inode, mod->filename, mod->address_start, mod->address_end);
1498 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1499 ret = g_slist_prepend (ret, mod);
1501 free_procmodule (mod);
1505 g_ptr_array_free (dlarray, TRUE);
1507 ret = g_slist_reverse (ret);
1511 #elif defined(__HAIKU__)
1513 static GSList *load_modules (void)
1516 WapiProcModule *mod;
1518 image_info imageInfo;
1520 while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
1521 mod = g_new0 (WapiProcModule, 1);
1522 mod->device = imageInfo.device;
1523 mod->inode = imageInfo.node;
1524 mod->filename = g_strdup (imageInfo.name);
1525 mod->address_start = MIN (imageInfo.text, imageInfo.data);
1526 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
1527 (uint8_t*)imageInfo.data + imageInfo.data_size);
1528 mod->perms = g_strdup ("r--p");
1529 mod->address_offset = 0;
1531 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1532 ret = g_slist_prepend (ret, mod);
1534 free_procmodule (mod);
1538 ret = g_slist_reverse (ret);
1543 static GSList *load_modules (FILE *fp)
1546 WapiProcModule *mod;
1547 char buf[MAXPATHLEN + 1], *p, *endp;
1548 char *start_start, *end_start, *prot_start, *offset_start;
1549 char *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1550 gpointer address_start, address_end, address_offset;
1551 guint32 maj_dev, min_dev;
1555 while (fgets (buf, sizeof(buf), fp)) {
1557 while (g_ascii_isspace (*p)) ++p;
1559 if (!g_ascii_isxdigit (*start_start)) {
1562 address_start = (gpointer)strtoul (start_start, &endp, 16);
1570 if (!g_ascii_isxdigit (*end_start)) {
1573 address_end = (gpointer)strtoul (end_start, &endp, 16);
1575 if (!g_ascii_isspace (*p)) {
1579 while (g_ascii_isspace (*p)) ++p;
1581 if (*prot_start != 'r' && *prot_start != '-') {
1584 memcpy (prot_buf, prot_start, 4);
1586 while (!g_ascii_isspace (*p)) ++p;
1588 while (g_ascii_isspace (*p)) ++p;
1590 if (!g_ascii_isxdigit (*offset_start)) {
1593 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1595 if (!g_ascii_isspace (*p)) {
1599 while(g_ascii_isspace (*p)) ++p;
1601 if (!g_ascii_isxdigit (*maj_dev_start)) {
1604 maj_dev = strtoul (maj_dev_start, &endp, 16);
1612 if (!g_ascii_isxdigit (*min_dev_start)) {
1615 min_dev = strtoul (min_dev_start, &endp, 16);
1617 if (!g_ascii_isspace (*p)) {
1621 while (g_ascii_isspace (*p)) ++p;
1623 if (!g_ascii_isxdigit (*inode_start)) {
1626 inode = (guint64)strtol (inode_start, &endp, 10);
1628 if (!g_ascii_isspace (*p)) {
1632 device = makedev ((int)maj_dev, (int)min_dev);
1633 if ((device == 0) &&
1638 while(g_ascii_isspace (*p)) ++p;
1639 /* p now points to the filename */
1641 mod = g_new0 (WapiProcModule, 1);
1642 mod->address_start = address_start;
1643 mod->address_end = address_end;
1644 mod->perms = g_strdup (prot_buf);
1645 mod->address_offset = address_offset;
1646 mod->device = device;
1648 mod->filename = g_strdup (g_strstrip (p));
1650 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1651 ret = g_slist_prepend (ret, mod);
1653 free_procmodule (mod);
1657 ret = g_slist_reverse (ret);
1663 static gboolean match_procname_to_modulename (char *procname, char *modulename)
1665 char* lastsep = NULL;
1666 char* lastsep2 = NULL;
1669 gboolean result = FALSE;
1671 if (procname == NULL || modulename == NULL)
1674 pname = mono_path_resolve_symlinks (procname);
1675 mname = mono_path_resolve_symlinks (modulename);
1677 if (!strcmp (pname, mname))
1681 lastsep = strrchr (mname, '/');
1683 if (!strcmp (lastsep+1, pname))
1686 lastsep2 = strrchr (pname, '/');
1689 if (!strcmp (lastsep+1, lastsep2+1))
1692 if (!strcmp (mname, lastsep2+1))
1705 #if !(defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__))
1707 open_process_map (int pid, const char *mode)
1710 const char *proc_path[] = {
1711 "/proc/%d/maps", /* GNU/Linux */
1712 "/proc/%d/map", /* FreeBSD */
1718 for (i = 0; fp == NULL && proc_path [i]; i++) {
1719 filename = g_strdup_printf (proc_path[i], pid);
1720 fp = fopen (filename, mode);
1728 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1729 guint32 size, guint32 *needed)
1731 WapiHandle_process *process_handle;
1732 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
1735 GSList *mods = NULL;
1736 WapiProcModule *module;
1737 guint32 count, avail = size / sizeof(gpointer);
1740 char *proc_name = NULL;
1742 /* Store modules in an array of pointers (main module as
1743 * modules[0]), using the load address for each module as a
1744 * token. (Use 'NULL' as an alternative for the main module
1745 * so that the simple implementation can just return one item
1746 * for now.) Get the info from /proc/<pid>/maps on linux,
1747 * /proc/<pid>/map on FreeBSD, other systems will have to
1748 * implement /dev/kmem reading or whatever other horrid
1749 * technique is needed.
1751 if (size < sizeof(gpointer))
1754 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1755 pid = WAPI_HANDLE_TO_PID (process);
1757 process_handle = lookup_process_handle (process);
1758 if (!process_handle) {
1759 DEBUG ("%s: Can't find process %p", __func__, process);
1763 pid = process_handle->id;
1764 proc_name = process_handle->proc_name;
1767 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
1768 mods = load_modules ();
1771 *needed = sizeof(gpointer);
1775 fp = open_process_map (pid, "r");
1777 /* No /proc/<pid>/maps so just return the main module
1781 *needed = sizeof(gpointer);
1784 mods = load_modules (fp);
1787 count = g_slist_length (mods);
1789 /* count + 1 to leave slot 0 for the main module */
1790 *needed = sizeof(gpointer) * (count + 1);
1793 * Use the NULL shortcut, as the first line in
1794 * /proc/<pid>/maps isn't the executable, and we need
1795 * that first in the returned list. Check the module name
1796 * to see if it ends with the proc name and substitute
1797 * the first entry with it. FIXME if this turns out to
1801 for (i = 0; i < (avail - 1) && i < count; i++) {
1802 module = (WapiProcModule *)g_slist_nth_data (mods, i);
1803 if (modules[0] != NULL)
1804 modules[i] = module->address_start;
1805 else if (match_procname_to_modulename (proc_name, module->filename))
1806 modules[0] = module->address_start;
1808 modules[i + 1] = module->address_start;
1811 for (i = 0; i < count; i++) {
1812 free_procmodule (g_slist_nth_data (mods, i));
1814 g_slist_free (mods);
1820 get_process_name_from_proc (pid_t pid)
1822 #if defined(__OpenBSD__)
1825 struct kinfo_proc *pi;
1826 #elif defined(PLATFORM_MACOSX)
1827 #if !(!defined (__mono_ppc__) && defined (TARGET_OSX))
1829 struct kinfo_proc *pi;
1830 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
1834 char *filename = NULL;
1839 #if defined(PLATFORM_SOLARIS)
1840 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
1841 if ((fp = fopen (filename, "r")) != NULL) {
1845 nread = fread (&info, sizeof (info), 1, fp);
1847 ret = g_strdup (info.pr_fname);
1853 #elif defined(PLATFORM_MACOSX)
1854 #if !defined (__mono_ppc__) && defined (TARGET_OSX)
1855 /* No proc name on OSX < 10.5 nor ppc nor iOS */
1856 memset (buf, '\0', sizeof(buf));
1857 proc_name (pid, buf, sizeof(buf));
1858 if (strlen (buf) > 0)
1859 ret = g_strdup (buf);
1861 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0)
1864 if ((pi = malloc(size)) == NULL)
1867 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
1868 if (errno == ENOMEM) {
1870 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__);
1875 if (strlen (pi->kp_proc.p_comm) > 0)
1876 ret = g_strdup (pi->kp_proc.p_comm);
1880 #elif defined(__OpenBSD__)
1882 mib [1] = KERN_PROC;
1883 mib [2] = KERN_PROC_PID;
1885 mib [4] = sizeof(struct kinfo_proc);
1889 if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0)
1892 if ((pi = malloc(size)) == NULL)
1895 mib[5] = (int)(size / sizeof(struct kinfo_proc));
1897 if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
1898 (size != sizeof (struct kinfo_proc))) {
1899 if (errno == ENOMEM) {
1906 if (strlen (pi->p_comm) > 0)
1907 ret = g_strdup (pi->p_comm);
1910 #elif defined(__HAIKU__)
1911 image_info imageInfo;
1914 if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
1915 ret = g_strdup (imageInfo.name);
1918 memset (buf, '\0', sizeof(buf));
1919 filename = g_strdup_printf ("/proc/%d/exe", pid);
1920 if (readlink (filename, buf, 255) > 0) {
1921 ret = g_strdup (buf);
1929 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
1930 if ((fp = fopen (filename, "r")) != NULL) {
1931 if (fgets (buf, 256, fp) != NULL) {
1932 ret = g_strdup (buf);
1943 filename = g_strdup_printf ("/proc/%d/stat", pid);
1944 if ((fp = fopen (filename, "r")) != NULL) {
1945 if (fgets (buf, 256, fp) != NULL) {
1948 start = strchr (buf, '(');
1949 if (start != NULL) {
1950 end = strchr (start + 1, ')');
1953 ret = g_strndup (start + 1,
1968 * wapi_process_get_path:
1970 * Return the full path of the executable of the process PID, or NULL if it cannot be determined.
1971 * Returns malloc-ed memory.
1974 wapi_process_get_path (pid_t pid)
1976 #if defined(PLATFORM_MACOSX) && !defined(__mono_ppc__) && defined(TARGET_OSX)
1977 char buf [PROC_PIDPATHINFO_MAXSIZE];
1980 res = proc_pidpath (pid, buf, sizeof (buf));
1983 if (buf [0] == '\0')
1985 return g_strdup (buf);
1987 return get_process_name_from_proc (pid);
1992 * wapi_process_set_cli_launcher:
1994 * Set the full path of the runtime executable used to launch managed exe's.
1997 wapi_process_set_cli_launcher (char *path)
1999 g_free (cli_launcher);
2000 cli_launcher = path ? g_strdup (path) : NULL;
2004 get_module_name (gpointer process, gpointer module,
2005 gunichar2 *basename, guint32 size,
2008 WapiHandle_process *process_handle;
2010 gunichar2 *procname;
2011 char *procname_ext = NULL;
2014 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2017 GSList *mods = NULL;
2018 WapiProcModule *found_module;
2021 char *proc_name = NULL;
2023 DEBUG ("%s: Getting module base name, process handle %p module %p",
2024 __func__, process, module);
2026 size = size * sizeof (gunichar2); /* adjust for unicode characters */
2028 if (basename == NULL || size == 0)
2031 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2032 /* This is a pseudo handle */
2033 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2034 proc_name = get_process_name_from_proc (pid);
2036 process_handle = lookup_process_handle (process);
2037 if (!process_handle) {
2038 DEBUG ("%s: Can't find process %p", __func__,
2043 pid = process_handle->id;
2044 proc_name = g_strdup (process_handle->proc_name);
2047 /* Look up the address in /proc/<pid>/maps */
2048 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2049 mods = load_modules ();
2051 fp = open_process_map (pid, "r");
2053 if (errno == EACCES && module == NULL && base == TRUE) {
2054 procname_ext = get_process_name_from_proc (pid);
2056 /* No /proc/<pid>/maps, so just return failure
2063 mods = load_modules (fp);
2067 count = g_slist_length (mods);
2069 /* If module != NULL compare the address.
2070 * If module == NULL we are looking for the main module.
2071 * The best we can do for now check it the module name end with the process name.
2073 for (i = 0; i < count; i++) {
2074 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2075 if (procname_ext == NULL &&
2076 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2077 (module != NULL && found_module->address_start == module))) {
2079 procname_ext = g_path_get_basename (found_module->filename);
2081 procname_ext = g_strdup (found_module->filename);
2084 free_procmodule (found_module);
2087 if (procname_ext == NULL) {
2088 /* If it's *still* null, we might have hit the
2089 * case where reading /proc/$pid/maps gives an
2090 * empty file for this user.
2092 procname_ext = get_process_name_from_proc (pid);
2095 g_slist_free (mods);
2099 DEBUG ("%s: Process name is [%s]", __func__,
2102 procname = mono_unicode_from_external (procname_ext, &bytes);
2103 if (procname == NULL) {
2105 g_free (procname_ext);
2111 /* Add the terminator */
2115 DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2117 memcpy (basename, procname, size);
2119 DEBUG ("%s: Size %d larger than needed (%ld)",
2120 __func__, size, bytes);
2122 memcpy (basename, procname, bytes);
2126 g_free (procname_ext);
2135 GetModuleBaseName (gpointer process, gpointer module,
2136 gunichar2 *basename, guint32 size)
2138 return get_module_name (process, module, basename, size, TRUE);
2142 GetModuleFileNameEx (gpointer process, gpointer module,
2143 gunichar2 *filename, guint32 size)
2145 return get_module_name (process, module, filename, size, FALSE);
2149 GetModuleInformation (gpointer process, gpointer module,
2150 WapiModuleInfo *modinfo, guint32 size)
2152 WapiHandle_process *process_handle;
2154 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2157 GSList *mods = NULL;
2158 WapiProcModule *found_module;
2161 gboolean ret = FALSE;
2162 char *proc_name = NULL;
2164 DEBUG ("%s: Getting module info, process handle %p module %p",
2165 __func__, process, module);
2167 if (modinfo == NULL || size < sizeof (WapiModuleInfo))
2170 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2171 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2172 proc_name = get_process_name_from_proc (pid);
2174 process_handle = lookup_process_handle (process);
2175 if (!process_handle) {
2176 DEBUG ("%s: Can't find process %p", __func__,
2181 pid = process_handle->id;
2182 proc_name = g_strdup (process_handle->proc_name);
2185 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2186 mods = load_modules ();
2188 /* Look up the address in /proc/<pid>/maps */
2189 if ((fp = open_process_map (pid, "r")) == NULL) {
2190 /* No /proc/<pid>/maps, so just return failure
2196 mods = load_modules (fp);
2199 count = g_slist_length (mods);
2201 /* If module != NULL compare the address.
2202 * If module == NULL we are looking for the main module.
2203 * The best we can do for now check it the module name end with the process name.
2205 for (i = 0; i < count; i++) {
2206 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2208 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2209 (module != NULL && found_module->address_start == module))) {
2210 modinfo->lpBaseOfDll = found_module->address_start;
2211 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2212 modinfo->EntryPoint = found_module->address_offset;
2216 free_procmodule (found_module);
2219 g_slist_free (mods);
2226 GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2228 WapiHandle_process *process_handle;
2230 if (min == NULL || max == NULL)
2231 /* Not sure if w32 allows NULLs here or not */
2234 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2235 /* This is a pseudo handle, so just fail for now */
2238 process_handle = lookup_process_handle (process);
2239 if (!process_handle) {
2240 DEBUG ("%s: Can't find process %p", __func__, process);
2245 *min = process_handle->min_working_set;
2246 *max = process_handle->max_working_set;
2252 SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2254 WapiHandle_process *process_handle;
2256 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2257 /* This is a pseudo handle, so just fail for now
2261 process_handle = lookup_process_handle (process);
2262 if (!process_handle) {
2263 DEBUG ("%s: Can't find process %p", __func__, process);
2268 process_handle->min_working_set = min;
2269 process_handle->max_working_set = max;
2276 TerminateProcess (gpointer process, gint32 exitCode)
2278 WapiHandle_process *process_handle;
2283 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2284 /* This is a pseudo handle */
2285 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2287 process_handle = lookup_process_handle (process);
2288 if (!process_handle) {
2289 DEBUG ("%s: Can't find process %p", __func__, process);
2290 SetLastError (ERROR_INVALID_HANDLE);
2293 pid = process_handle->id;
2296 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2297 ret = kill (pid, signo);
2301 SetLastError (ERROR_INVALID_PARAMETER);
2304 SetLastError (ERROR_ACCESS_DENIED);
2307 SetLastError (ERROR_PROC_NOT_FOUND);
2310 SetLastError (ERROR_GEN_FAILURE);
2318 GetPriorityClass (gpointer process)
2320 #ifdef HAVE_GETPRIORITY
2321 WapiHandle_process *process_handle;
2325 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2326 /* This is a pseudo handle */
2327 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2329 process_handle = lookup_process_handle (process);
2330 if (!process_handle) {
2331 SetLastError (ERROR_INVALID_HANDLE);
2334 pid = process_handle->id;
2338 ret = getpriority (PRIO_PROCESS, pid);
2339 if (ret == -1 && errno != 0) {
2343 SetLastError (ERROR_ACCESS_DENIED);
2346 SetLastError (ERROR_PROC_NOT_FOUND);
2349 SetLastError (ERROR_GEN_FAILURE);
2355 return NORMAL_PRIORITY_CLASS;
2357 return REALTIME_PRIORITY_CLASS;
2359 return HIGH_PRIORITY_CLASS;
2361 return ABOVE_NORMAL_PRIORITY_CLASS;
2363 return IDLE_PRIORITY_CLASS;
2365 return BELOW_NORMAL_PRIORITY_CLASS;
2367 return NORMAL_PRIORITY_CLASS;
2369 SetLastError (ERROR_NOT_SUPPORTED);
2375 SetPriorityClass (gpointer process, guint32 priority_class)
2377 #ifdef HAVE_SETPRIORITY
2378 WapiHandle_process *process_handle;
2383 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2384 /* This is a pseudo handle */
2385 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2387 process_handle = lookup_process_handle (process);
2388 if (!process_handle) {
2389 SetLastError (ERROR_INVALID_HANDLE);
2392 pid = process_handle->id;
2395 switch (priority_class) {
2396 case IDLE_PRIORITY_CLASS:
2399 case BELOW_NORMAL_PRIORITY_CLASS:
2402 case NORMAL_PRIORITY_CLASS:
2405 case ABOVE_NORMAL_PRIORITY_CLASS:
2408 case HIGH_PRIORITY_CLASS:
2411 case REALTIME_PRIORITY_CLASS:
2415 SetLastError (ERROR_INVALID_PARAMETER);
2419 ret = setpriority (PRIO_PROCESS, pid, prio);
2424 SetLastError (ERROR_ACCESS_DENIED);
2427 SetLastError (ERROR_PROC_NOT_FOUND);
2430 SetLastError (ERROR_GEN_FAILURE);
2436 SetLastError (ERROR_NOT_SUPPORTED);
2442 mono_processes_cleanup (void)
2444 struct MonoProcess *mp;
2445 struct MonoProcess *prev = NULL;
2446 GSList *finished = NULL;
2448 gpointer unref_handle;
2450 DEBUG ("%s", __func__);
2452 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2453 if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
2456 for (mp = mono_processes; mp; mp = mp->next) {
2457 if (mp->pid == 0 && mp->handle) {
2458 /* This process has exited and we need to remove the artifical ref
2460 mono_mutex_lock (&mono_processes_mutex);
2461 unref_handle = mp->handle;
2463 mono_mutex_unlock (&mono_processes_mutex);
2465 _wapi_handle_unref (unref_handle);
2470 * Remove processes which exited from the mono_processes list.
2471 * We need to synchronize with the sigchld handler here, which runs
2472 * asynchronously. The handler requires that the mono_processes list
2475 mono_mutex_lock (&mono_processes_mutex);
2477 mp = mono_processes;
2479 if (mp->handle_count == 0 && mp->freeable) {
2482 * This code can run parallel with the sigchld handler, but the
2483 * modifications it makes are safe.
2485 if (mp == mono_processes)
2486 mono_processes = mp->next;
2488 prev->next = mp->next;
2489 finished = g_slist_prepend (finished, mp);
2498 mono_memory_barrier ();
2500 for (l = finished; l; l = l->next) {
2502 * All the entries in the finished list are unlinked from mono_processes, and
2503 * they have the 'finished' flag set, which means the sigchld handler is done
2507 MONO_SEM_DESTROY (&mp->exit_sem);
2510 g_slist_free (finished);
2512 mono_mutex_unlock (&mono_processes_mutex);
2514 DEBUG ("%s done", __func__);
2516 InterlockedDecrement (&mono_processes_cleaning_up);
2520 process_close (gpointer handle, gpointer data)
2522 WapiHandle_process *process_handle;
2524 DEBUG ("%s", __func__);
2526 process_handle = (WapiHandle_process *) data;
2527 g_free (process_handle->proc_name);
2528 process_handle->proc_name = NULL;
2529 if (process_handle->mono_process)
2530 InterlockedDecrement (&process_handle->mono_process->handle_count);
2531 mono_processes_cleanup ();
2535 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
2539 struct MonoProcess *p;
2541 DEBUG ("SIG CHILD handler for pid: %i\n", info->si_pid);
2545 pid = waitpid (-1, &status, WNOHANG);
2546 } while (pid == -1 && errno == EINTR);
2551 DEBUG ("child ended: %i", pid);
2554 * This can run concurrently with the code in the rest of this module.
2556 for (p = mono_processes; p; p = p->next) {
2557 if (p->pid == pid) {
2562 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2564 MONO_SEM_POST (&p->exit_sem);
2565 mono_memory_barrier ();
2566 /* Mark this as freeable, the pointer becomes invalid afterwards */
2571 DEBUG ("SIG CHILD handler: done looping.");
2577 process_add_sigchld_handler (void)
2580 struct sigaction sa;
2582 sa.sa_sigaction = mono_sigchld_signal_handler;
2583 sigemptyset (&sa.sa_mask);
2584 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2585 g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2586 DEBUG ("Added SIGCHLD handler");
2591 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2593 WapiHandle_process *process_handle;
2594 pid_t pid G_GNUC_UNUSED, ret;
2598 struct MonoProcess *mp;
2600 /* FIXME: We can now easily wait on processes that aren't our own children,
2601 * but WaitFor*Object won't call us for pseudo handles. */
2602 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2604 DEBUG ("%s (%p, %u)", __func__, handle, timeout);
2606 process_handle = lookup_process_handle (handle);
2607 if (!process_handle) {
2608 g_warning ("%s: error looking up process handle %p", __func__, handle);
2612 if (process_handle->exited) {
2613 /* We've already done this one */
2614 DEBUG ("%s (%p, %u): Process already exited", __func__, handle, timeout);
2615 return WAIT_OBJECT_0;
2618 pid = process_handle->id;
2620 DEBUG ("%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2622 /* We don't need to lock mono_processes here, the entry
2623 * has a handle_count > 0 which means it will not be freed. */
2624 mp = process_handle->mono_process;
2627 start = mono_msec_ticks ();
2631 if (timeout != INFINITE) {
2632 DEBUG ("%s (%p, %u): waiting on semaphore for %li ms...",
2633 __func__, handle, timeout, (timeout - (now - start)));
2635 ret = MONO_SEM_TIMEDWAIT_ALERTABLE (&mp->exit_sem, (timeout - (now - start)), alertable);
2637 DEBUG ("%s (%p, %u): waiting on semaphore forever...",
2638 __func__, handle, timeout);
2639 ret = MONO_SEM_WAIT_ALERTABLE (&mp->exit_sem, alertable);
2642 if (ret == -1 && errno != EINTR && errno != ETIMEDOUT) {
2643 DEBUG ("%s (%p, %u): sem_timedwait failure: %s",
2644 __func__, handle, timeout, g_strerror (errno));
2645 /* Should we return a failure here? */
2649 /* Success, process has exited */
2650 MONO_SEM_POST (&mp->exit_sem);
2655 DEBUG ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
2656 return WAIT_TIMEOUT;
2659 now = mono_msec_ticks ();
2660 if (now - start >= timeout) {
2661 DEBUG ("%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
2662 return WAIT_TIMEOUT;
2665 if (alertable && _wapi_thread_cur_apc_pending ()) {
2666 DEBUG ("%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
2667 return WAIT_IO_COMPLETION;
2671 /* Process must have exited */
2672 DEBUG ("%s (%p, %u): Waited successfully", __func__, handle, timeout);
2674 ret = _wapi_handle_lock_shared_handles ();
2675 g_assert (ret == 0);
2677 status = mp ? mp->status : 0;
2678 if (WIFSIGNALED (status))
2679 process_handle->exitstatus = 128 + WTERMSIG (status);
2681 process_handle->exitstatus = WEXITSTATUS (status);
2682 _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
2684 process_handle->exited = TRUE;
2686 DEBUG ("%s (%p, %u): Setting pid %d signalled, exit status %d",
2687 __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
2689 _wapi_handle_set_signal_state (handle, TRUE, TRUE);
2691 _wapi_handle_unlock_shared_handles ();
2693 return WAIT_OBJECT_0;
2697 wapi_processes_cleanup (void)
2699 g_free (cli_launcher);