[runtime] Fix "make distcheck"
[mono-project.git] / mono / io-layer / processes.c
blob439e4e5f32e5a8491b5690ecf50e9184a367e089
1 /*
2 * processes.c: Process handles
4 * Author:
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002-2011 Novell, Inc.
8 * Copyright 2011 Xamarin Inc
9 */
11 #include <config.h>
12 #include <glib.h>
13 #include <stdio.h>
14 #include <string.h>
15 #include <pthread.h>
16 #include <sched.h>
17 #include <sys/time.h>
18 #include <errno.h>
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <unistd.h>
22 #ifdef HAVE_SIGNAL_H
23 #include <signal.h>
24 #endif
25 #include <sys/time.h>
26 #include <fcntl.h>
27 #ifdef HAVE_SYS_PARAM_H
28 #include <sys/param.h>
29 #endif
30 #include <ctype.h>
32 #ifdef HAVE_SYS_WAIT_H
33 #include <sys/wait.h>
34 #endif
35 #ifdef HAVE_SYS_RESOURCE_H
36 #include <sys/resource.h>
37 #endif
39 #ifdef HAVE_SYS_MKDEV_H
40 #include <sys/mkdev.h>
41 #endif
43 #ifdef HAVE_UTIME_H
44 #include <utime.h>
45 #endif
47 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
48 #ifdef __APPLE__
49 #include <TargetConditionals.h>
50 #include <sys/resource.h>
51 #ifdef HAVE_LIBPROC_H
52 /* proc_name */
53 #include <libproc.h>
54 #endif
55 #endif
57 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
58 #include <sys/proc.h>
59 #include <sys/sysctl.h>
60 # if !defined(__OpenBSD__)
61 # include <sys/utsname.h>
62 # endif
63 #endif
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
69 #include <procfs.h>
70 #define _FILE_OFFSET_BITS 64
71 #else
72 #include <procfs.h>
73 #endif
74 #endif
76 #ifdef __HAIKU__
77 #include <KernelKit.h>
78 #endif
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>
94 /* The process' environment strings */
95 #if defined(__APPLE__) && !defined (__arm__) && !defined (__aarch64__)
96 /* Apple defines this in crt_externs.h but doesn't provide that header for
97 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
98 * in fact exist on all implementations (so far)
100 char ***_NSGetEnviron(void);
101 #define environ (*_NSGetEnviron())
102 #else
103 extern char **environ;
104 #endif
106 #if 0
107 #define DEBUG(...) g_message(__VA_ARGS__)
108 #define DEBUG_ENABLED 1
109 #else
110 #define DEBUG(...)
111 #endif
113 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable);
114 static void process_close (gpointer handle, gpointer data);
115 static gboolean is_pid_valid (pid_t pid);
117 #if !defined(__OpenBSD__)
118 static FILE *
119 open_process_map (int pid, const char *mode);
120 #endif
122 struct _WapiHandleOps _wapi_process_ops = {
123 process_close, /* close_shared */
124 NULL, /* signal */
125 NULL, /* own */
126 NULL, /* is_owned */
127 process_wait, /* special_wait */
128 NULL /* prewait */
131 #if HAVE_SIGACTION
132 static struct sigaction previous_chld_sa;
133 #endif
134 static mono_once_t process_sig_chld_once = MONO_ONCE_INIT;
135 static void process_add_sigchld_handler (void);
137 /* The signal-safe logic to use mono_processes goes like this:
138 * - The list must be safe to traverse for the signal handler at all times.
139 * It's safe to: prepend an entry (which is a single store to 'mono_processes'),
140 * unlink an entry (assuming the unlinked entry isn't freed and doesn't
141 * change its 'next' pointer so that it can still be traversed).
142 * When cleaning up we first unlink an entry, then we verify that
143 * the read lock isn't locked. Then we can free the entry, since
144 * we know that nobody is using the old version of the list (including
145 * the unlinked entry).
146 * We also need to lock when adding and cleaning up so that those two
147 * operations don't mess with eachother. (This lock is not used in the
148 * signal handler)
150 static struct MonoProcess *mono_processes = NULL;
151 static volatile gint32 mono_processes_cleaning_up = 0;
152 static mono_mutex_t mono_processes_mutex;
153 static void mono_processes_cleanup (void);
155 static gpointer current_process;
156 static char *cli_launcher;
158 static WapiHandle_process *
159 lookup_process_handle (gpointer handle)
161 WapiHandle_process *process_data;
162 gboolean ret;
164 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
165 (gpointer *)&process_data);
166 if (!ret)
167 return NULL;
168 return process_data;
171 /* Check if a pid is valid - i.e. if a process exists with this pid. */
172 static gboolean
173 is_pid_valid (pid_t pid)
175 gboolean result = FALSE;
177 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
178 if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
179 result = TRUE;
180 #elif defined(__HAIKU__)
181 team_info teamInfo;
182 if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
183 result = TRUE;
184 #else
185 char *dir = g_strdup_printf ("/proc/%d", pid);
186 if (!access (dir, F_OK))
187 result = TRUE;
188 g_free (dir);
189 #endif
191 return result;
194 static void
195 process_set_defaults (WapiHandle_process *process_handle)
197 /* These seem to be the defaults on w2k */
198 process_handle->min_working_set = 204800;
199 process_handle->max_working_set = 1413120;
201 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
204 static int
205 len16 (const gunichar2 *str)
207 int len = 0;
209 while (*str++ != 0)
210 len++;
212 return len;
215 static gunichar2 *
216 utf16_concat (const gunichar2 *first, ...)
218 va_list args;
219 int total = 0, i;
220 const gunichar2 *s;
221 gunichar2 *ret;
223 va_start (args, first);
224 total += len16 (first);
225 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
226 total += len16 (s);
228 va_end (args);
230 ret = g_new (gunichar2, total + 1);
231 if (ret == NULL)
232 return NULL;
234 ret [total] = 0;
235 i = 0;
236 for (s = first; *s != 0; s++)
237 ret [i++] = *s;
238 va_start (args, first);
239 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
240 const gunichar2 *p;
242 for (p = s; *p != 0; p++)
243 ret [i++] = *p;
245 va_end (args);
247 return ret;
250 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
251 static const gunichar2 *utf16_space = utf16_space_bytes;
252 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
253 static const gunichar2 *utf16_quote = utf16_quote_bytes;
255 #ifdef DEBUG_ENABLED
256 /* Useful in gdb */
257 void
258 print_utf16 (gunichar2 *str)
260 char *res;
262 res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
263 g_print ("%s\n", res);
264 g_free (res);
266 #endif
268 /* Implemented as just a wrapper around CreateProcess () */
269 gboolean
270 ShellExecuteEx (WapiShellExecuteInfo *sei)
272 gboolean ret;
273 WapiProcessInformation process_info;
274 gunichar2 *args;
276 if (sei == NULL) {
277 /* w2k just segfaults here, but we can do better than
278 * that
280 SetLastError (ERROR_INVALID_PARAMETER);
281 return FALSE;
284 if (sei->lpFile == NULL)
285 /* w2k returns TRUE for this, for some reason. */
286 return TRUE;
288 /* Put both executable and parameters into the second argument
289 * to CreateProcess (), so it searches $PATH. The conversion
290 * into and back out of utf8 is because there is no
291 * g_strdup_printf () equivalent for gunichar2 :-(
293 args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
294 if (args == NULL) {
295 SetLastError (ERROR_INVALID_DATA);
296 return FALSE;
298 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
299 CREATE_UNICODE_ENVIRONMENT, NULL,
300 sei->lpDirectory, NULL, &process_info);
301 g_free (args);
303 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
304 return ret;
306 if (!ret) {
307 static char *handler;
308 static gunichar2 *handler_utf16;
310 if (handler_utf16 == (gunichar2 *)-1)
311 return FALSE;
313 #ifdef PLATFORM_MACOSX
314 handler = g_strdup ("/usr/bin/open");
315 #else
317 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
318 * if that fails, try to use gnome-open, then kfmclient
320 handler = g_find_program_in_path ("xdg-open");
321 if (handler == NULL){
322 handler = g_find_program_in_path ("gnome-open");
323 if (handler == NULL){
324 handler = g_find_program_in_path ("kfmclient");
325 if (handler == NULL){
326 handler_utf16 = (gunichar2 *) -1;
327 return FALSE;
328 } else {
329 /* kfmclient needs exec argument */
330 char *old = handler;
331 handler = g_strconcat (old, " exec",
332 NULL);
333 g_free (old);
337 #endif
338 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
339 g_free (handler);
341 /* Put quotes around the filename, in case it's a url
342 * that contains #'s (CreateProcess() calls
343 * g_shell_parse_argv(), which deliberately throws
344 * away anything after an unquoted #). Fixes bug
345 * 371567.
347 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
348 sei->lpFile, utf16_quote,
349 sei->lpParameters == NULL ? NULL : utf16_space,
350 sei->lpParameters, NULL);
351 if (args == NULL) {
352 SetLastError (ERROR_INVALID_DATA);
353 return FALSE;
355 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
356 CREATE_UNICODE_ENVIRONMENT, NULL,
357 sei->lpDirectory, NULL, &process_info);
358 g_free (args);
359 if (!ret) {
360 if (GetLastError () != ERROR_OUTOFMEMORY)
361 SetLastError (ERROR_INVALID_DATA);
362 return FALSE;
364 /* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
365 CloseHandle (process_info.hProcess);
366 process_info.hProcess = NULL;
369 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS)
370 sei->hProcess = process_info.hProcess;
371 else
372 CloseHandle (process_info.hProcess);
374 return ret;
377 static gboolean
378 is_managed_binary (const char *filename)
380 int original_errno = errno;
381 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
382 int file = open (filename, O_RDONLY | O_LARGEFILE);
383 #else
384 int file = open (filename, O_RDONLY);
385 #endif
386 off_t new_offset;
387 unsigned char buffer[8];
388 off_t file_size, optional_header_offset;
389 off_t pe_header_offset;
390 gboolean managed = FALSE;
391 int num_read;
392 guint32 first_word, second_word;
394 /* If we are unable to open the file, then we definitely
395 * can't say that it is managed. The child mono process
396 * probably wouldn't be able to open it anyway.
398 if (file < 0) {
399 errno = original_errno;
400 return FALSE;
403 /* Retrieve the length of the file for future sanity checks. */
404 file_size = lseek (file, 0, SEEK_END);
405 lseek (file, 0, SEEK_SET);
407 /* We know we need to read a header field at offset 60. */
408 if (file_size < 64)
409 goto leave;
411 num_read = read (file, buffer, 2);
413 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
414 goto leave;
416 new_offset = lseek (file, 60, SEEK_SET);
418 if (new_offset != 60)
419 goto leave;
421 num_read = read (file, buffer, 4);
423 if (num_read != 4)
424 goto leave;
425 pe_header_offset = buffer[0]
426 | (buffer[1] << 8)
427 | (buffer[2] << 16)
428 | (buffer[3] << 24);
430 if (pe_header_offset + 24 > file_size)
431 goto leave;
433 new_offset = lseek (file, pe_header_offset, SEEK_SET);
435 if (new_offset != pe_header_offset)
436 goto leave;
438 num_read = read (file, buffer, 4);
440 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
441 goto leave;
444 * Verify that the header we want in the optional header data
445 * is present in this binary.
447 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
449 if (new_offset != pe_header_offset + 20)
450 goto leave;
452 num_read = read (file, buffer, 2);
454 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
455 goto leave;
457 /* Read the CLR header address and size fields. These will be
458 * zero if the binary is not managed.
460 optional_header_offset = pe_header_offset + 24;
461 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
463 if (new_offset != optional_header_offset + 208)
464 goto leave;
466 num_read = read (file, buffer, 8);
468 /* We are not concerned with endianness, only with
469 * whether it is zero or not.
471 first_word = *(guint32 *)&buffer[0];
472 second_word = *(guint32 *)&buffer[4];
474 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
475 goto leave;
477 managed = TRUE;
479 leave:
480 close (file);
481 errno = original_errno;
482 return managed;
485 gboolean
486 CreateProcessWithLogonW (const gunichar2 *username,
487 const gunichar2 *domain,
488 const gunichar2 *password,
489 const guint32 logonFlags,
490 const gunichar2 *appname,
491 const gunichar2 *cmdline,
492 guint32 create_flags,
493 gpointer env,
494 const gunichar2 *cwd,
495 WapiStartupInfo *startup,
496 WapiProcessInformation *process_info)
498 /* FIXME: use user information */
499 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
502 static gboolean
503 is_readable_or_executable (const char *prog)
505 struct stat buf;
506 int a = access (prog, R_OK);
507 int b = access (prog, X_OK);
508 if (a != 0 && b != 0)
509 return FALSE;
510 if (stat (prog, &buf))
511 return FALSE;
512 if (S_ISREG (buf.st_mode))
513 return TRUE;
514 return FALSE;
517 static gboolean
518 is_executable (const char *prog)
520 struct stat buf;
521 if (access (prog, X_OK) != 0)
522 return FALSE;
523 if (stat (prog, &buf))
524 return FALSE;
525 if (S_ISREG (buf.st_mode))
526 return TRUE;
527 return FALSE;
530 static void
531 switch_dir_separators (char *path)
533 size_t i, pathLength = strlen(path);
535 /* Turn all the slashes round the right way, except for \' */
536 /* There are probably other characters that need to be excluded as well. */
537 for (i = 0; i < pathLength; i++) {
538 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' )
539 path[i] = '/';
543 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
544 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
545 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
546 gboolean inherit_handles, guint32 create_flags,
547 gpointer new_environ, const gunichar2 *cwd,
548 WapiStartupInfo *startup,
549 WapiProcessInformation *process_info)
551 char *cmd = NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL;
552 char *dir = NULL, **env_strings = NULL, **argv = NULL;
553 guint32 i, env_count = 0;
554 gboolean ret = FALSE;
555 gpointer handle;
556 WapiHandle_process process_handle = {0}, *process_handle_data;
557 GError *gerr = NULL;
558 int in_fd, out_fd, err_fd;
559 pid_t pid;
560 int thr_ret;
561 int startup_pipe [2] = {-1, -1};
562 int dummy;
563 struct MonoProcess *mono_process;
564 gboolean fork_failed = FALSE;
566 mono_once (&process_sig_chld_once, process_add_sigchld_handler);
568 /* appname and cmdline specify the executable and its args:
570 * If appname is not NULL, it is the name of the executable.
571 * Otherwise the executable is the first token in cmdline.
573 * Executable searching:
575 * If appname is not NULL, it can specify the full path and
576 * file name, or else a partial name and the current directory
577 * will be used. There is no additional searching.
579 * If appname is NULL, the first whitespace-delimited token in
580 * cmdline is used. If the name does not contain a full
581 * directory path, the search sequence is:
583 * 1) The directory containing the current process
584 * 2) The current working directory
585 * 3) The windows system directory (Ignored)
586 * 4) The windows directory (Ignored)
587 * 5) $PATH
589 * Just to make things more interesting, tokens can contain
590 * white space if they are surrounded by quotation marks. I'm
591 * beginning to understand just why windows apps are generally
592 * so crap, with an API like this :-(
594 if (appname != NULL) {
595 cmd = mono_unicode_to_external (appname);
596 if (cmd == NULL) {
597 DEBUG ("%s: unicode conversion returned NULL",
598 __func__);
600 SetLastError (ERROR_PATH_NOT_FOUND);
601 goto free_strings;
604 switch_dir_separators(cmd);
607 if (cmdline != NULL) {
608 args = mono_unicode_to_external (cmdline);
609 if (args == NULL) {
610 DEBUG ("%s: unicode conversion returned NULL", __func__);
612 SetLastError (ERROR_PATH_NOT_FOUND);
613 goto free_strings;
617 if (cwd != NULL) {
618 dir = mono_unicode_to_external (cwd);
619 if (dir == NULL) {
620 DEBUG ("%s: unicode conversion returned NULL", __func__);
622 SetLastError (ERROR_PATH_NOT_FOUND);
623 goto free_strings;
626 /* Turn all the slashes round the right way */
627 switch_dir_separators(dir);
631 /* We can't put off locating the executable any longer :-( */
632 if (cmd != NULL) {
633 char *unquoted;
634 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
635 /* Strip off the drive letter. I can't
636 * believe that CP/M holdover is still
637 * visible...
639 g_memmove (cmd, cmd+2, strlen (cmd)-2);
640 cmd[strlen (cmd)-2] = '\0';
643 unquoted = g_shell_unquote (cmd, NULL);
644 if (unquoted[0] == '/') {
645 /* Assume full path given */
646 prog = g_strdup (unquoted);
648 /* Executable existing ? */
649 if (!is_readable_or_executable (prog)) {
650 DEBUG ("%s: Couldn't find executable %s",
651 __func__, prog);
652 g_free (unquoted);
653 SetLastError (ERROR_FILE_NOT_FOUND);
654 goto free_strings;
656 } else {
657 /* Search for file named by cmd in the current
658 * directory
660 char *curdir = g_get_current_dir ();
662 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
663 g_free (curdir);
665 /* And make sure it's readable */
666 if (!is_readable_or_executable (prog)) {
667 DEBUG ("%s: Couldn't find executable %s",
668 __func__, prog);
669 g_free (unquoted);
670 SetLastError (ERROR_FILE_NOT_FOUND);
671 goto free_strings;
674 g_free (unquoted);
676 args_after_prog = args;
677 } else {
678 char *token = NULL;
679 char quote;
681 /* Dig out the first token from args, taking quotation
682 * marks into account
685 /* First, strip off all leading whitespace */
686 args = g_strchug (args);
688 /* args_after_prog points to the contents of args
689 * after token has been set (otherwise argv[0] is
690 * duplicated)
692 args_after_prog = args;
694 /* Assume the opening quote will always be the first
695 * character
697 if (args[0] == '\"' || args [0] == '\'') {
698 quote = args [0];
699 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
700 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
701 /* We found the first token */
702 token = g_strndup (args+1, i-1);
703 args_after_prog = g_strchug (args + i + 1);
704 } else {
705 /* Quotation mark appeared in the
706 * middle of the token. Just give the
707 * whole first token, quotes and all,
708 * to exec.
713 if (token == NULL) {
714 /* No quote mark, or malformed */
715 for (i = 0; args[i] != '\0'; i++) {
716 if (g_ascii_isspace (args[i])) {
717 token = g_strndup (args, i);
718 args_after_prog = args + i + 1;
719 break;
724 if (token == NULL && args[0] != '\0') {
725 /* Must be just one token in the string */
726 token = g_strdup (args);
727 args_after_prog = NULL;
730 if (token == NULL) {
731 /* Give up */
732 DEBUG ("%s: Couldn't find what to exec", __func__);
734 SetLastError (ERROR_PATH_NOT_FOUND);
735 goto free_strings;
738 /* Turn all the slashes round the right way. Only for
739 * the prg. name
741 switch_dir_separators(token);
743 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
744 /* Strip off the drive letter. I can't
745 * believe that CP/M holdover is still
746 * visible...
748 g_memmove (token, token+2, strlen (token)-2);
749 token[strlen (token)-2] = '\0';
752 if (token[0] == '/') {
753 /* Assume full path given */
754 prog = g_strdup (token);
756 /* Executable existing ? */
757 if (!is_readable_or_executable (prog)) {
758 DEBUG ("%s: Couldn't find executable %s",
759 __func__, token);
760 g_free (token);
761 SetLastError (ERROR_FILE_NOT_FOUND);
762 goto free_strings;
764 } else {
765 char *curdir = g_get_current_dir ();
767 /* FIXME: Need to record the directory
768 * containing the current process, and check
769 * that for the new executable as the first
770 * place to look
773 prog = g_strdup_printf ("%s/%s", curdir, token);
774 g_free (curdir);
776 /* I assume X_OK is the criterion to use,
777 * rather than F_OK
779 * X_OK is too strict *if* the target is a CLR binary
781 if (!is_readable_or_executable (prog)) {
782 g_free (prog);
783 prog = g_find_program_in_path (token);
784 if (prog == NULL) {
785 DEBUG ("%s: Couldn't find executable %s", __func__, token);
787 g_free (token);
788 SetLastError (ERROR_FILE_NOT_FOUND);
789 goto free_strings;
794 g_free (token);
797 DEBUG ("%s: Exec prog [%s] args [%s]", __func__, prog,
798 args_after_prog);
800 /* Check for CLR binaries; if found, we will try to invoke
801 * them using the same mono binary that started us.
803 if (is_managed_binary (prog)) {
804 gunichar2 *newapp = NULL, *newcmd;
805 gsize bytes_ignored;
807 if (cli_launcher)
808 newapp = mono_unicode_from_external (cli_launcher, &bytes_ignored);
809 else
810 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
812 if (newapp != NULL) {
813 if (appname != NULL) {
814 newcmd = utf16_concat (newapp, utf16_space,
815 appname, utf16_space,
816 cmdline, NULL);
817 } else {
818 newcmd = utf16_concat (newapp, utf16_space,
819 cmdline, NULL);
822 g_free ((gunichar2 *)newapp);
824 if (newcmd != NULL) {
825 ret = CreateProcess (NULL, newcmd,
826 process_attrs,
827 thread_attrs,
828 inherit_handles,
829 create_flags, new_environ,
830 cwd, startup,
831 process_info);
833 g_free ((gunichar2 *)newcmd);
835 goto free_strings;
838 } else {
839 if (!is_executable (prog)) {
840 DEBUG ("%s: Executable permisson not set on %s", __func__, prog);
841 SetLastError (ERROR_ACCESS_DENIED);
842 goto free_strings;
846 if (args_after_prog != NULL && *args_after_prog) {
847 char *qprog;
849 qprog = g_shell_quote (prog);
850 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
851 g_free (qprog);
852 } else {
853 full_prog = g_shell_quote (prog);
856 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
857 if (ret == FALSE) {
858 g_message ("CreateProcess: %s\n", gerr->message);
859 g_error_free (gerr);
860 gerr = NULL;
861 goto free_strings;
864 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
865 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
866 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
867 err_fd = GPOINTER_TO_UINT (startup->hStdError);
868 } else {
869 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
870 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
871 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
874 process_handle.proc_name = g_strdup (prog);
876 process_set_defaults (&process_handle);
878 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
879 if (handle == _WAPI_HANDLE_INVALID) {
880 g_warning ("%s: error creating process handle", __func__);
882 ret = FALSE;
883 SetLastError (ERROR_OUTOFMEMORY);
884 goto free_strings;
887 /* new_environ is a block of NULL-terminated strings, which
888 * is itself NULL-terminated. Of course, passing an array of
889 * string pointers would have made things too easy :-(
891 * If new_environ is not NULL it specifies the entire set of
892 * environment variables in the new process. Otherwise the
893 * new process inherits the same environment.
895 if (new_environ) {
896 gunichar2 *new_environp;
898 /* Count the number of strings */
899 for (new_environp = (gunichar2 *)new_environ; *new_environp;
900 new_environp++) {
901 env_count++;
902 while (*new_environp) {
903 new_environp++;
907 /* +2: one for the process handle value, and the last
908 * one is NULL
910 env_strings = g_new0 (char *, env_count + 2);
912 /* Copy each environ string into 'strings' turning it
913 * into utf8 (or the requested encoding) at the same
914 * time
916 env_count = 0;
917 for (new_environp = (gunichar2 *)new_environ; *new_environp;
918 new_environp++) {
919 env_strings[env_count] = mono_unicode_to_external (new_environp);
920 env_count++;
921 while (*new_environp) {
922 new_environp++;
925 } else {
926 for (i = 0; environ[i] != NULL; i++)
927 env_count++;
929 /* +2: one for the process handle value, and the last
930 * one is NULL
932 env_strings = g_new0 (char *, env_count + 2);
934 /* Copy each environ string into 'strings' turning it
935 * into utf8 (or the requested encoding) at the same
936 * time
938 env_count = 0;
939 for (i = 0; environ[i] != NULL; i++) {
940 env_strings[env_count] = g_strdup (environ[i]);
941 env_count++;
945 /* Create a pipe to make sure the child doesn't exit before
946 * we can add the process to the linked list of mono_processes */
947 if (pipe (startup_pipe) == -1) {
948 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
949 * This is just for a very hard to hit race condition in the first place */
950 startup_pipe [0] = startup_pipe [1] = -1;
951 DEBUG ("%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
954 thr_ret = _wapi_handle_lock_shared_handles ();
955 g_assert (thr_ret == 0);
957 pid = fork ();
958 if (pid == -1) {
959 /* Error */
960 SetLastError (ERROR_OUTOFMEMORY);
961 ret = FALSE;
962 fork_failed = TRUE;
963 goto cleanup;
964 } else if (pid == 0) {
965 /* Child */
967 if (startup_pipe [0] != -1) {
968 /* Wait until the parent has updated it's internal data */
969 ssize_t _i G_GNUC_UNUSED = read (startup_pipe [0], &dummy, 1);
970 DEBUG ("%s: child: parent has completed its setup", __func__);
971 close (startup_pipe [0]);
972 close (startup_pipe [1]);
975 /* should we detach from the process group? */
977 /* Connect stdin, stdout and stderr */
978 dup2 (in_fd, 0);
979 dup2 (out_fd, 1);
980 dup2 (err_fd, 2);
982 if (inherit_handles != TRUE) {
983 /* FIXME: do something here */
986 /* Close all file descriptors */
987 for (i = wapi_getdtablesize () - 1; i > 2; i--)
988 close (i);
990 #ifdef DEBUG_ENABLED
991 DEBUG ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
992 dir == NULL?".":dir);
993 for (i = 0; argv[i] != NULL; i++)
994 g_message ("arg %d: [%s]", i, argv[i]);
996 for (i = 0; env_strings[i] != NULL; i++)
997 g_message ("env %d: [%s]", i, env_strings[i]);
998 #endif
1000 /* set cwd */
1001 if (dir != NULL && chdir (dir) == -1) {
1002 /* set error */
1003 _exit (-1);
1006 /* exec */
1007 execve (argv[0], argv, env_strings);
1009 /* set error */
1010 _exit (-1);
1012 /* parent */
1014 process_handle_data = lookup_process_handle (handle);
1015 if (!process_handle_data) {
1016 g_warning ("%s: error looking up process handle %p", __func__,
1017 handle);
1018 _wapi_handle_unref (handle);
1019 goto cleanup;
1022 process_handle_data->id = pid;
1024 /* Add our mono_process into the linked list of mono_processes */
1025 mono_process = (struct MonoProcess *) g_malloc0 (sizeof (struct MonoProcess));
1026 mono_process->pid = pid;
1027 mono_process->handle_count = 1;
1028 if (MONO_SEM_INIT (&mono_process->exit_sem, 0) != 0) {
1029 /* If we can't create the exit semaphore, we just don't add anything
1030 * to our list of mono processes. Waiting on the process will return
1031 * immediately. */
1032 g_warning ("%s: could not create exit semaphore for process.", strerror (errno));
1033 g_free (mono_process);
1034 } else {
1035 /* Keep the process handle artificially alive until the process
1036 * exits so that the information in the handle isn't lost. */
1037 _wapi_handle_ref (handle);
1038 mono_process->handle = handle;
1040 process_handle_data->mono_process = mono_process;
1042 mono_mutex_lock (&mono_processes_mutex);
1043 mono_process->next = mono_processes;
1044 mono_processes = mono_process;
1045 mono_mutex_unlock (&mono_processes_mutex);
1048 if (process_info != NULL) {
1049 process_info->hProcess = handle;
1050 process_info->dwProcessId = pid;
1052 /* FIXME: we might need to handle the thread info some
1053 * day
1055 process_info->hThread = INVALID_HANDLE_VALUE;
1056 process_info->dwThreadId = 0;
1059 cleanup:
1060 _wapi_handle_unlock_shared_handles ();
1062 if (fork_failed)
1063 _wapi_handle_unref (handle);
1065 if (startup_pipe [1] != -1) {
1066 /* Write 1 byte, doesn't matter what */
1067 ssize_t _i G_GNUC_UNUSED = write (startup_pipe [1], startup_pipe, 1);
1068 close (startup_pipe [0]);
1069 close (startup_pipe [1]);
1072 free_strings:
1073 if (cmd)
1074 g_free (cmd);
1075 if (full_prog)
1076 g_free (full_prog);
1077 if (prog)
1078 g_free (prog);
1079 if (args)
1080 g_free (args);
1081 if (dir)
1082 g_free (dir);
1083 if (env_strings)
1084 g_strfreev (env_strings);
1085 if (argv)
1086 g_strfreev (argv);
1088 DEBUG ("%s: returning handle %p for pid %d", __func__, handle,
1089 pid);
1091 /* Check if something needs to be cleaned up. */
1092 mono_processes_cleanup ();
1094 return ret;
1097 static void
1098 process_set_name (WapiHandle_process *process_handle)
1100 char *progname, *utf8_progname, *slash;
1102 progname = g_get_prgname ();
1103 utf8_progname = mono_utf8_from_external (progname);
1105 DEBUG ("%s: using [%s] as prog name", __func__, progname);
1107 if (utf8_progname) {
1108 slash = strrchr (utf8_progname, '/');
1109 if (slash)
1110 process_handle->proc_name = g_strdup (slash+1);
1111 else
1112 process_handle->proc_name = g_strdup (utf8_progname);
1113 g_free (utf8_progname);
1117 void
1118 wapi_processes_init (void)
1120 pid_t pid = _wapi_getpid ();
1121 WapiHandle_process process_handle = {0};
1123 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
1124 WAPI_HANDLE_CAP_WAIT |
1125 WAPI_HANDLE_CAP_SPECIAL_WAIT);
1127 process_handle.id = pid;
1129 process_set_defaults (&process_handle);
1130 process_set_name (&process_handle);
1132 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1133 &process_handle);
1134 g_assert (current_process);
1137 gpointer
1138 _wapi_process_duplicate (void)
1140 _wapi_handle_ref (current_process);
1142 return current_process;
1145 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1146 gpointer
1147 GetCurrentProcess (void)
1149 return _WAPI_PROCESS_CURRENT;
1152 guint32
1153 GetProcessId (gpointer handle)
1155 WapiHandle_process *process_handle;
1157 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1158 /* This is a pseudo handle */
1159 return WAPI_HANDLE_TO_PID (handle);
1161 process_handle = lookup_process_handle (handle);
1162 if (!process_handle) {
1163 SetLastError (ERROR_INVALID_HANDLE);
1164 return 0;
1167 return process_handle->id;
1170 static gboolean
1171 process_open_compare (gpointer handle, gpointer user_data)
1173 pid_t wanted_pid;
1174 WapiHandle_process *process_handle;
1175 pid_t checking_pid;
1177 g_assert (!WAPI_IS_PSEUDO_PROCESS_HANDLE (handle));
1179 process_handle = lookup_process_handle (handle);
1180 g_assert (process_handle);
1182 DEBUG ("%s: looking at process %d", __func__, process_handle->id);
1184 checking_pid = process_handle->id;
1186 if (checking_pid == 0)
1187 return FALSE;
1189 wanted_pid = GPOINTER_TO_UINT (user_data);
1191 /* It's possible to have more than one process handle with the
1192 * same pid, but only the one running process can be
1193 * unsignalled
1195 if (checking_pid == wanted_pid &&
1196 !_wapi_handle_issignalled (handle)) {
1197 /* If the handle is blown away in the window between
1198 * returning TRUE here and _wapi_search_handle pinging
1199 * the timestamp, the search will continue
1201 return TRUE;
1202 } else {
1203 return FALSE;
1207 gboolean
1208 CloseProcess (gpointer handle)
1210 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1211 return TRUE;
1212 return CloseHandle (handle);
1216 * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1218 gpointer
1219 OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1221 /* Find the process handle that corresponds to pid */
1222 gpointer handle = NULL;
1224 DEBUG ("%s: looking for process %d", __func__, pid);
1226 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1227 process_open_compare,
1228 GUINT_TO_POINTER (pid), NULL, TRUE);
1229 if (handle == 0) {
1230 if (is_pid_valid (pid)) {
1231 /* Return a pseudo handle for processes we
1232 * don't have handles for
1234 return WAPI_PID_TO_HANDLE (pid);
1235 } else {
1236 DEBUG ("%s: Can't find pid %d", __func__, pid);
1238 SetLastError (ERROR_PROC_NOT_FOUND);
1240 return NULL;
1244 /* _wapi_search_handle () already added a ref */
1245 return handle;
1248 gboolean
1249 GetExitCodeProcess (gpointer process, guint32 *code)
1251 WapiHandle_process *process_handle;
1252 guint32 pid = -1;
1254 if (!code)
1255 return FALSE;
1257 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1258 pid = WAPI_HANDLE_TO_PID (process);
1259 /* This is a pseudo handle, so we don't know what the
1260 * exit code was, but we can check whether it's alive or not
1262 if (is_pid_valid (pid)) {
1263 *code = STILL_ACTIVE;
1264 return TRUE;
1265 } else {
1266 return FALSE;
1270 process_handle = lookup_process_handle (process);
1271 if (!process_handle) {
1272 DEBUG ("%s: Can't find process %p", __func__, process);
1274 return FALSE;
1277 if (process_handle->id == _wapi_getpid ()) {
1278 *code = STILL_ACTIVE;
1279 return TRUE;
1282 /* A process handle is only signalled if the process has exited
1283 * and has been waited for */
1285 /* Make sure any process exit has been noticed, before
1286 * checking if the process is signalled. Fixes bug 325463.
1288 process_wait (process, 0, TRUE);
1290 if (_wapi_handle_issignalled (process))
1291 *code = process_handle->exitstatus;
1292 else
1293 *code = STILL_ACTIVE;
1295 return TRUE;
1298 gboolean
1299 GetProcessTimes (gpointer process, WapiFileTime *create_time,
1300 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1301 WapiFileTime *user_time)
1303 WapiHandle_process *process_handle;
1304 gboolean ku_times_set = FALSE;
1306 if (create_time == NULL || exit_time == NULL || kernel_time == NULL ||
1307 user_time == NULL)
1308 /* Not sure if w32 allows NULLs here or not */
1309 return FALSE;
1311 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
1312 /* This is a pseudo handle, so just fail for now
1314 return FALSE;
1316 process_handle = lookup_process_handle (process);
1317 if (!process_handle) {
1318 DEBUG ("%s: Can't find process %p", __func__, process);
1320 return FALSE;
1323 *create_time = process_handle->create_time;
1325 /* A process handle is only signalled if the process has
1326 * exited. Otherwise exit_time isn't set
1328 if (_wapi_handle_issignalled (process))
1329 *exit_time = process_handle->exit_time;
1331 #ifdef HAVE_GETRUSAGE
1332 if (process_handle->id == getpid ()) {
1333 struct rusage time_data;
1334 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1335 guint64 tick_val;
1336 ku_times_set = TRUE;
1337 tick_val = (guint64)time_data.ru_utime.tv_sec * 10000000 + (guint64)time_data.ru_utime.tv_usec * 10;
1338 _wapi_guint64_to_filetime (tick_val, user_time);
1339 tick_val = (guint64)time_data.ru_stime.tv_sec * 10000000 + (guint64)time_data.ru_stime.tv_usec * 10;
1340 _wapi_guint64_to_filetime (tick_val, kernel_time);
1343 #endif
1344 if (!ku_times_set) {
1345 memset (kernel_time, 0, sizeof (WapiFileTime));
1346 memset (user_time, 0, sizeof (WapiFileTime));
1349 return TRUE;
1352 typedef struct
1354 gpointer address_start;
1355 gpointer address_end;
1356 char *perms;
1357 gpointer address_offset;
1358 guint64 device;
1359 guint64 inode;
1360 char *filename;
1361 } WapiProcModule;
1363 static void free_procmodule (WapiProcModule *mod)
1365 if (mod->perms != NULL) {
1366 g_free (mod->perms);
1368 if (mod->filename != NULL) {
1369 g_free (mod->filename);
1371 g_free (mod);
1374 static gint find_procmodule (gconstpointer a, gconstpointer b)
1376 WapiProcModule *want = (WapiProcModule *)a;
1377 WapiProcModule *compare = (WapiProcModule *)b;
1379 if ((want->device == compare->device) &&
1380 (want->inode == compare->inode)) {
1381 return(0);
1382 } else {
1383 return(1);
1387 #ifdef PLATFORM_MACOSX
1388 #include <mach-o/dyld.h>
1389 #include <mach-o/getsect.h>
1391 static GSList *load_modules (void)
1393 GSList *ret = NULL;
1394 WapiProcModule *mod;
1395 uint32_t count = _dyld_image_count ();
1396 int i = 0;
1398 for (i = 0; i < count; i++) {
1399 #if SIZEOF_VOID_P == 8
1400 const struct mach_header_64 *hdr;
1401 const struct section_64 *sec;
1402 #else
1403 const struct mach_header *hdr;
1404 const struct section *sec;
1405 #endif
1406 const char *name;
1408 name = _dyld_get_image_name (i);
1409 #if SIZEOF_VOID_P == 8
1410 hdr = (const struct mach_header_64*)_dyld_get_image_header (i);
1411 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1412 #else
1413 hdr = _dyld_get_image_header (i);
1414 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1415 #endif
1417 /* Some dynlibs do not have data sections on osx (#533893) */
1418 if (sec == 0) {
1419 continue;
1422 mod = g_new0 (WapiProcModule, 1);
1423 mod->address_start = GINT_TO_POINTER (sec->addr);
1424 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1425 mod->perms = g_strdup ("r--p");
1426 mod->address_offset = 0;
1427 mod->device = makedev (0, 0);
1428 mod->inode = i;
1429 mod->filename = g_strdup (name);
1431 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1432 ret = g_slist_prepend (ret, mod);
1433 } else {
1434 free_procmodule (mod);
1438 ret = g_slist_reverse (ret);
1440 return(ret);
1442 #elif defined(__OpenBSD__)
1443 #include <link.h>
1444 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1446 if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1447 + sizeof (info->dlpi_phnum))
1448 return (-1);
1450 struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1451 if (!cpy)
1452 return (-1);
1454 memcpy(cpy, info, sizeof(*info));
1456 g_ptr_array_add ((GPtrArray *)ptr, cpy);
1458 return (0);
1461 static GSList *load_modules (void)
1463 GSList *ret = NULL;
1464 WapiProcModule *mod;
1465 GPtrArray *dlarray = g_ptr_array_new();
1466 int i;
1468 if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1469 return (ret);
1471 for (i = 0; i < dlarray->len; i++) {
1472 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1474 mod = g_new0 (WapiProcModule, 1);
1475 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1476 mod->address_end = (gpointer)(info->dlpi_addr +
1477 info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1478 mod->perms = g_strdup ("r--p");
1479 mod->address_offset = 0;
1480 mod->inode = i;
1481 mod->filename = g_strdup (info->dlpi_name);
1483 DEBUG ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1484 mod->inode, mod->filename, mod->address_start, mod->address_end);
1486 free(info);
1488 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1489 ret = g_slist_prepend (ret, mod);
1490 } else {
1491 free_procmodule (mod);
1495 g_ptr_array_free (dlarray, TRUE);
1497 ret = g_slist_reverse (ret);
1499 return(ret);
1501 #elif defined(__HAIKU__)
1503 static GSList *load_modules (void)
1505 GSList *ret = NULL;
1506 WapiProcModule *mod;
1507 int32 cookie = 0;
1508 image_info imageInfo;
1510 while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
1511 mod = g_new0 (WapiProcModule, 1);
1512 mod->device = imageInfo.device;
1513 mod->inode = imageInfo.node;
1514 mod->filename = g_strdup (imageInfo.name);
1515 mod->address_start = MIN (imageInfo.text, imageInfo.data);
1516 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
1517 (uint8_t*)imageInfo.data + imageInfo.data_size);
1518 mod->perms = g_strdup ("r--p");
1519 mod->address_offset = 0;
1521 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1522 ret = g_slist_prepend (ret, mod);
1523 } else {
1524 free_procmodule (mod);
1528 ret = g_slist_reverse (ret);
1530 return ret;
1532 #else
1533 static GSList *load_modules (FILE *fp)
1535 GSList *ret = NULL;
1536 WapiProcModule *mod;
1537 char buf[MAXPATHLEN + 1], *p, *endp;
1538 char *start_start, *end_start, *prot_start, *offset_start;
1539 char *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1540 gpointer address_start, address_end, address_offset;
1541 guint32 maj_dev, min_dev;
1542 guint64 inode;
1543 guint64 device;
1545 while (fgets (buf, sizeof(buf), fp)) {
1546 p = buf;
1547 while (g_ascii_isspace (*p)) ++p;
1548 start_start = p;
1549 if (!g_ascii_isxdigit (*start_start)) {
1550 continue;
1552 address_start = (gpointer)strtoul (start_start, &endp, 16);
1553 p = endp;
1554 if (*p != '-') {
1555 continue;
1558 ++p;
1559 end_start = p;
1560 if (!g_ascii_isxdigit (*end_start)) {
1561 continue;
1563 address_end = (gpointer)strtoul (end_start, &endp, 16);
1564 p = endp;
1565 if (!g_ascii_isspace (*p)) {
1566 continue;
1569 while (g_ascii_isspace (*p)) ++p;
1570 prot_start = p;
1571 if (*prot_start != 'r' && *prot_start != '-') {
1572 continue;
1574 memcpy (prot_buf, prot_start, 4);
1575 prot_buf[4] = '\0';
1576 while (!g_ascii_isspace (*p)) ++p;
1578 while (g_ascii_isspace (*p)) ++p;
1579 offset_start = p;
1580 if (!g_ascii_isxdigit (*offset_start)) {
1581 continue;
1583 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1584 p = endp;
1585 if (!g_ascii_isspace (*p)) {
1586 continue;
1589 while(g_ascii_isspace (*p)) ++p;
1590 maj_dev_start = p;
1591 if (!g_ascii_isxdigit (*maj_dev_start)) {
1592 continue;
1594 maj_dev = strtoul (maj_dev_start, &endp, 16);
1595 p = endp;
1596 if (*p != ':') {
1597 continue;
1600 ++p;
1601 min_dev_start = p;
1602 if (!g_ascii_isxdigit (*min_dev_start)) {
1603 continue;
1605 min_dev = strtoul (min_dev_start, &endp, 16);
1606 p = endp;
1607 if (!g_ascii_isspace (*p)) {
1608 continue;
1611 while (g_ascii_isspace (*p)) ++p;
1612 inode_start = p;
1613 if (!g_ascii_isxdigit (*inode_start)) {
1614 continue;
1616 inode = (guint64)strtol (inode_start, &endp, 10);
1617 p = endp;
1618 if (!g_ascii_isspace (*p)) {
1619 continue;
1622 device = makedev ((int)maj_dev, (int)min_dev);
1623 if ((device == 0) &&
1624 (inode == 0)) {
1625 continue;
1628 while(g_ascii_isspace (*p)) ++p;
1629 /* p now points to the filename */
1631 mod = g_new0 (WapiProcModule, 1);
1632 mod->address_start = address_start;
1633 mod->address_end = address_end;
1634 mod->perms = g_strdup (prot_buf);
1635 mod->address_offset = address_offset;
1636 mod->device = device;
1637 mod->inode = inode;
1638 mod->filename = g_strdup (g_strstrip (p));
1640 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1641 ret = g_slist_prepend (ret, mod);
1642 } else {
1643 free_procmodule (mod);
1647 ret = g_slist_reverse (ret);
1649 return(ret);
1651 #endif
1653 static gboolean match_procname_to_modulename (char *procname, char *modulename)
1655 char* lastsep = NULL;
1656 char* lastsep2 = NULL;
1657 char* pname = NULL;
1658 char* mname = NULL;
1659 gboolean result = FALSE;
1661 if (procname == NULL || modulename == NULL)
1662 return (FALSE);
1664 pname = mono_path_resolve_symlinks (procname);
1665 mname = mono_path_resolve_symlinks (modulename);
1667 if (!strcmp (pname, mname))
1668 result = TRUE;
1670 if (!result) {
1671 lastsep = strrchr (mname, '/');
1672 if (lastsep)
1673 if (!strcmp (lastsep+1, pname))
1674 result = TRUE;
1675 if (!result) {
1676 lastsep2 = strrchr (pname, '/');
1677 if (lastsep2){
1678 if (lastsep) {
1679 if (!strcmp (lastsep+1, lastsep2+1))
1680 result = TRUE;
1681 } else {
1682 if (!strcmp (mname, lastsep2+1))
1683 result = TRUE;
1689 g_free (pname);
1690 g_free (mname);
1692 return result;
1695 #if !defined(__OpenBSD__)
1696 static FILE *
1697 open_process_map (int pid, const char *mode)
1699 FILE *fp = NULL;
1700 const char *proc_path[] = {
1701 "/proc/%d/maps", /* GNU/Linux */
1702 "/proc/%d/map", /* FreeBSD */
1703 NULL
1705 int i;
1706 char *filename;
1708 for (i = 0; fp == NULL && proc_path [i]; i++) {
1709 filename = g_strdup_printf (proc_path[i], pid);
1710 fp = fopen (filename, mode);
1711 g_free (filename);
1714 return fp;
1716 #endif
1718 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1719 guint32 size, guint32 *needed)
1721 WapiHandle_process *process_handle;
1722 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
1723 FILE *fp;
1724 #endif
1725 GSList *mods = NULL;
1726 WapiProcModule *module;
1727 guint32 count, avail = size / sizeof(gpointer);
1728 int i;
1729 pid_t pid;
1730 char *proc_name = NULL;
1732 /* Store modules in an array of pointers (main module as
1733 * modules[0]), using the load address for each module as a
1734 * token. (Use 'NULL' as an alternative for the main module
1735 * so that the simple implementation can just return one item
1736 * for now.) Get the info from /proc/<pid>/maps on linux,
1737 * /proc/<pid>/map on FreeBSD, other systems will have to
1738 * implement /dev/kmem reading or whatever other horrid
1739 * technique is needed.
1741 if (size < sizeof(gpointer))
1742 return FALSE;
1744 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1745 pid = WAPI_HANDLE_TO_PID (process);
1746 } else {
1747 process_handle = lookup_process_handle (process);
1748 if (!process_handle) {
1749 DEBUG ("%s: Can't find process %p", __func__, process);
1751 return FALSE;
1753 pid = process_handle->id;
1754 proc_name = process_handle->proc_name;
1757 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
1758 mods = load_modules ();
1759 if (!proc_name) {
1760 modules[0] = NULL;
1761 *needed = sizeof(gpointer);
1762 return TRUE;
1764 #else
1765 fp = open_process_map (pid, "r");
1766 if (!fp) {
1767 /* No /proc/<pid>/maps so just return the main module
1768 * shortcut for now
1770 modules[0] = NULL;
1771 *needed = sizeof(gpointer);
1772 return TRUE;
1774 mods = load_modules (fp);
1775 fclose (fp);
1776 #endif
1777 count = g_slist_length (mods);
1779 /* count + 1 to leave slot 0 for the main module */
1780 *needed = sizeof(gpointer) * (count + 1);
1783 * Use the NULL shortcut, as the first line in
1784 * /proc/<pid>/maps isn't the executable, and we need
1785 * that first in the returned list. Check the module name
1786 * to see if it ends with the proc name and substitute
1787 * the first entry with it. FIXME if this turns out to
1788 * be a problem.
1790 modules[0] = NULL;
1791 for (i = 0; i < (avail - 1) && i < count; i++) {
1792 module = (WapiProcModule *)g_slist_nth_data (mods, i);
1793 if (modules[0] != NULL)
1794 modules[i] = module->address_start;
1795 else if (match_procname_to_modulename (proc_name, module->filename))
1796 modules[0] = module->address_start;
1797 else
1798 modules[i + 1] = module->address_start;
1801 for (i = 0; i < count; i++) {
1802 free_procmodule (g_slist_nth_data (mods, i));
1804 g_slist_free (mods);
1806 return TRUE;
1809 static char *
1810 get_process_name_from_proc (pid_t pid)
1812 #if defined(__OpenBSD__)
1813 int mib [6];
1814 size_t size;
1815 struct kinfo_proc *pi;
1816 #elif defined(PLATFORM_MACOSX)
1817 #if !(!defined (__mono_ppc__) && defined (TARGET_OSX))
1818 size_t size;
1819 struct kinfo_proc *pi;
1820 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
1821 #endif
1822 #else
1823 FILE *fp;
1824 char *filename = NULL;
1825 #endif
1826 char buf[256];
1827 char *ret = NULL;
1829 #if defined(PLATFORM_SOLARIS)
1830 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
1831 if ((fp = fopen (filename, "r")) != NULL) {
1832 struct psinfo info;
1833 int nread;
1835 nread = fread (&info, sizeof (info), 1, fp);
1836 if (nread == 1) {
1837 ret = g_strdup (info.pr_fname);
1840 fclose (fp);
1842 g_free (filename);
1843 #elif defined(PLATFORM_MACOSX)
1844 #if !defined (__mono_ppc__) && defined (TARGET_OSX)
1845 /* No proc name on OSX < 10.5 nor ppc nor iOS */
1846 memset (buf, '\0', sizeof(buf));
1847 proc_name (pid, buf, sizeof(buf));
1848 if (strlen (buf) > 0)
1849 ret = g_strdup (buf);
1850 #else
1851 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0)
1852 return(ret);
1854 if ((pi = malloc(size)) == NULL)
1855 return(ret);
1857 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
1858 if (errno == ENOMEM) {
1859 free(pi);
1860 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__);
1862 return(ret);
1865 if (strlen (pi->kp_proc.p_comm) > 0)
1866 ret = g_strdup (pi->kp_proc.p_comm);
1868 free(pi);
1869 #endif
1870 #elif defined(__OpenBSD__)
1871 mib [0] = CTL_KERN;
1872 mib [1] = KERN_PROC;
1873 mib [2] = KERN_PROC_PID;
1874 mib [3] = pid;
1875 mib [4] = sizeof(struct kinfo_proc);
1876 mib [5] = 0;
1878 retry:
1879 if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0)
1880 return(ret);
1882 if ((pi = malloc(size)) == NULL)
1883 return(ret);
1885 mib[5] = (int)(size / sizeof(struct kinfo_proc));
1887 if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
1888 (size != sizeof (struct kinfo_proc))) {
1889 if (errno == ENOMEM) {
1890 free(pi);
1891 goto retry;
1893 return(ret);
1896 if (strlen (pi->p_comm) > 0)
1897 ret = g_strdup (pi->p_comm);
1899 free(pi);
1900 #elif defined(__HAIKU__)
1901 image_info imageInfo;
1902 int32 cookie = 0;
1904 if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
1905 ret = g_strdup (imageInfo.name);
1907 #else
1908 memset (buf, '\0', sizeof(buf));
1909 filename = g_strdup_printf ("/proc/%d/exe", pid);
1910 if (readlink (filename, buf, 255) > 0) {
1911 ret = g_strdup (buf);
1913 g_free (filename);
1915 if (ret != NULL) {
1916 return(ret);
1919 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
1920 if ((fp = fopen (filename, "r")) != NULL) {
1921 if (fgets (buf, 256, fp) != NULL) {
1922 ret = g_strdup (buf);
1925 fclose (fp);
1927 g_free (filename);
1929 if (ret != NULL) {
1930 return(ret);
1933 filename = g_strdup_printf ("/proc/%d/stat", pid);
1934 if ((fp = fopen (filename, "r")) != NULL) {
1935 if (fgets (buf, 256, fp) != NULL) {
1936 char *start, *end;
1938 start = strchr (buf, '(');
1939 if (start != NULL) {
1940 end = strchr (start + 1, ')');
1942 if (end != NULL) {
1943 ret = g_strndup (start + 1,
1944 end - start - 1);
1949 fclose (fp);
1951 g_free (filename);
1952 #endif
1954 return ret;
1958 * wapi_process_get_path:
1960 * Return the full path of the executable of the process PID, or NULL if it cannot be determined.
1961 * Returns malloc-ed memory.
1963 char*
1964 wapi_process_get_path (pid_t pid)
1966 #if defined(PLATFORM_MACOSX) && !defined(__mono_ppc__) && defined(TARGET_OSX)
1967 char buf [PROC_PIDPATHINFO_MAXSIZE];
1968 int res;
1970 res = proc_pidpath (pid, buf, sizeof (buf));
1971 if (res <= 0)
1972 return NULL;
1973 if (buf [0] == '\0')
1974 return NULL;
1975 return g_strdup (buf);
1976 #else
1977 return get_process_name_from_proc (pid);
1978 #endif
1982 * wapi_process_set_cli_launcher:
1984 * Set the full path of the runtime executable used to launch managed exe's.
1986 void
1987 wapi_process_set_cli_launcher (char *path)
1989 g_free (cli_launcher);
1990 cli_launcher = path ? g_strdup (path) : NULL;
1993 static guint32
1994 get_module_name (gpointer process, gpointer module,
1995 gunichar2 *basename, guint32 size,
1996 gboolean base)
1998 WapiHandle_process *process_handle;
1999 pid_t pid;
2000 gunichar2 *procname;
2001 char *procname_ext = NULL;
2002 glong len;
2003 gsize bytes;
2004 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2005 FILE *fp;
2006 #endif
2007 GSList *mods = NULL;
2008 WapiProcModule *found_module;
2009 guint32 count;
2010 int i;
2011 char *proc_name = NULL;
2013 DEBUG ("%s: Getting module base name, process handle %p module %p",
2014 __func__, process, module);
2016 size = size * sizeof (gunichar2); /* adjust for unicode characters */
2018 if (basename == NULL || size == 0)
2019 return 0;
2021 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2022 /* This is a pseudo handle */
2023 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2024 proc_name = get_process_name_from_proc (pid);
2025 } else {
2026 process_handle = lookup_process_handle (process);
2027 if (!process_handle) {
2028 DEBUG ("%s: Can't find process %p", __func__,
2029 process);
2031 return 0;
2033 pid = process_handle->id;
2034 proc_name = g_strdup (process_handle->proc_name);
2037 /* Look up the address in /proc/<pid>/maps */
2038 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2039 mods = load_modules ();
2040 #else
2041 fp = open_process_map (pid, "r");
2042 if (fp == NULL) {
2043 if (errno == EACCES && module == NULL && base == TRUE) {
2044 procname_ext = get_process_name_from_proc (pid);
2045 } else {
2046 /* No /proc/<pid>/maps, so just return failure
2047 * for now
2049 g_free (proc_name);
2050 return 0;
2052 } else {
2053 mods = load_modules (fp);
2054 fclose (fp);
2056 #endif
2057 count = g_slist_length (mods);
2059 /* If module != NULL compare the address.
2060 * If module == NULL we are looking for the main module.
2061 * The best we can do for now check it the module name end with the process name.
2063 for (i = 0; i < count; i++) {
2064 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2065 if (procname_ext == NULL &&
2066 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2067 (module != NULL && found_module->address_start == module))) {
2068 if (base)
2069 procname_ext = g_path_get_basename (found_module->filename);
2070 else
2071 procname_ext = g_strdup (found_module->filename);
2074 free_procmodule (found_module);
2077 if (procname_ext == NULL) {
2078 /* If it's *still* null, we might have hit the
2079 * case where reading /proc/$pid/maps gives an
2080 * empty file for this user.
2082 procname_ext = get_process_name_from_proc (pid);
2085 g_slist_free (mods);
2086 g_free (proc_name);
2088 if (procname_ext) {
2089 DEBUG ("%s: Process name is [%s]", __func__,
2090 procname_ext);
2092 procname = mono_unicode_from_external (procname_ext, &bytes);
2093 if (procname == NULL) {
2094 /* bugger */
2095 g_free (procname_ext);
2096 return 0;
2099 len = (bytes / 2);
2101 /* Add the terminator */
2102 bytes += 2;
2104 if (size < bytes) {
2105 DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2107 memcpy (basename, procname, size);
2108 } else {
2109 DEBUG ("%s: Size %d larger than needed (%ld)",
2110 __func__, size, bytes);
2112 memcpy (basename, procname, bytes);
2115 g_free (procname);
2116 g_free (procname_ext);
2118 return len;
2121 return 0;
2124 guint32
2125 GetModuleBaseName (gpointer process, gpointer module,
2126 gunichar2 *basename, guint32 size)
2128 return get_module_name (process, module, basename, size, TRUE);
2131 guint32
2132 GetModuleFileNameEx (gpointer process, gpointer module,
2133 gunichar2 *filename, guint32 size)
2135 return get_module_name (process, module, filename, size, FALSE);
2138 gboolean
2139 GetModuleInformation (gpointer process, gpointer module,
2140 WapiModuleInfo *modinfo, guint32 size)
2142 WapiHandle_process *process_handle;
2143 pid_t pid;
2144 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2145 FILE *fp;
2146 #endif
2147 GSList *mods = NULL;
2148 WapiProcModule *found_module;
2149 guint32 count;
2150 int i;
2151 gboolean ret = FALSE;
2152 char *proc_name = NULL;
2154 DEBUG ("%s: Getting module info, process handle %p module %p",
2155 __func__, process, module);
2157 if (modinfo == NULL || size < sizeof (WapiModuleInfo))
2158 return FALSE;
2160 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2161 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2162 proc_name = get_process_name_from_proc (pid);
2163 } else {
2164 process_handle = lookup_process_handle (process);
2165 if (!process_handle) {
2166 DEBUG ("%s: Can't find process %p", __func__,
2167 process);
2169 return FALSE;
2171 pid = process_handle->id;
2172 proc_name = g_strdup (process_handle->proc_name);
2175 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2176 mods = load_modules ();
2177 #else
2178 /* Look up the address in /proc/<pid>/maps */
2179 if ((fp = open_process_map (pid, "r")) == NULL) {
2180 /* No /proc/<pid>/maps, so just return failure
2181 * for now
2183 g_free (proc_name);
2184 return FALSE;
2186 mods = load_modules (fp);
2187 fclose (fp);
2188 #endif
2189 count = g_slist_length (mods);
2191 /* If module != NULL compare the address.
2192 * If module == NULL we are looking for the main module.
2193 * The best we can do for now check it the module name end with the process name.
2195 for (i = 0; i < count; i++) {
2196 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2197 if (ret == FALSE &&
2198 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2199 (module != NULL && found_module->address_start == module))) {
2200 modinfo->lpBaseOfDll = found_module->address_start;
2201 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2202 modinfo->EntryPoint = found_module->address_offset;
2203 ret = TRUE;
2206 free_procmodule (found_module);
2209 g_slist_free (mods);
2210 g_free (proc_name);
2212 return ret;
2215 gboolean
2216 GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2218 WapiHandle_process *process_handle;
2220 if (min == NULL || max == NULL)
2221 /* Not sure if w32 allows NULLs here or not */
2222 return FALSE;
2224 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2225 /* This is a pseudo handle, so just fail for now */
2226 return FALSE;
2228 process_handle = lookup_process_handle (process);
2229 if (!process_handle) {
2230 DEBUG ("%s: Can't find process %p", __func__, process);
2232 return FALSE;
2235 *min = process_handle->min_working_set;
2236 *max = process_handle->max_working_set;
2238 return TRUE;
2241 gboolean
2242 SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2244 WapiHandle_process *process_handle;
2246 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2247 /* This is a pseudo handle, so just fail for now
2249 return FALSE;
2251 process_handle = lookup_process_handle (process);
2252 if (!process_handle) {
2253 DEBUG ("%s: Can't find process %p", __func__, process);
2255 return FALSE;
2258 process_handle->min_working_set = min;
2259 process_handle->max_working_set = max;
2261 return TRUE;
2265 gboolean
2266 TerminateProcess (gpointer process, gint32 exitCode)
2268 WapiHandle_process *process_handle;
2269 int signo;
2270 int ret;
2271 pid_t pid;
2273 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2274 /* This is a pseudo handle */
2275 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2276 } else {
2277 process_handle = lookup_process_handle (process);
2278 if (!process_handle) {
2279 DEBUG ("%s: Can't find process %p", __func__, process);
2280 SetLastError (ERROR_INVALID_HANDLE);
2281 return FALSE;
2283 pid = process_handle->id;
2286 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2287 ret = kill (pid, signo);
2288 if (ret == -1) {
2289 switch (errno) {
2290 case EINVAL:
2291 SetLastError (ERROR_INVALID_PARAMETER);
2292 break;
2293 case EPERM:
2294 SetLastError (ERROR_ACCESS_DENIED);
2295 break;
2296 case ESRCH:
2297 SetLastError (ERROR_PROC_NOT_FOUND);
2298 break;
2299 default:
2300 SetLastError (ERROR_GEN_FAILURE);
2304 return (ret == 0);
2307 guint32
2308 GetPriorityClass (gpointer process)
2310 #ifdef HAVE_GETPRIORITY
2311 WapiHandle_process *process_handle;
2312 int ret;
2313 pid_t pid;
2315 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2316 /* This is a pseudo handle */
2317 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2318 } else {
2319 process_handle = lookup_process_handle (process);
2320 if (!process_handle) {
2321 SetLastError (ERROR_INVALID_HANDLE);
2322 return FALSE;
2324 pid = process_handle->id;
2327 errno = 0;
2328 ret = getpriority (PRIO_PROCESS, pid);
2329 if (ret == -1 && errno != 0) {
2330 switch (errno) {
2331 case EPERM:
2332 case EACCES:
2333 SetLastError (ERROR_ACCESS_DENIED);
2334 break;
2335 case ESRCH:
2336 SetLastError (ERROR_PROC_NOT_FOUND);
2337 break;
2338 default:
2339 SetLastError (ERROR_GEN_FAILURE);
2341 return FALSE;
2344 if (ret == 0)
2345 return NORMAL_PRIORITY_CLASS;
2346 else if (ret < -15)
2347 return REALTIME_PRIORITY_CLASS;
2348 else if (ret < -10)
2349 return HIGH_PRIORITY_CLASS;
2350 else if (ret < 0)
2351 return ABOVE_NORMAL_PRIORITY_CLASS;
2352 else if (ret > 10)
2353 return IDLE_PRIORITY_CLASS;
2354 else if (ret > 0)
2355 return BELOW_NORMAL_PRIORITY_CLASS;
2357 return NORMAL_PRIORITY_CLASS;
2358 #else
2359 SetLastError (ERROR_NOT_SUPPORTED);
2360 return 0;
2361 #endif
2364 gboolean
2365 SetPriorityClass (gpointer process, guint32 priority_class)
2367 #ifdef HAVE_SETPRIORITY
2368 WapiHandle_process *process_handle;
2369 int ret;
2370 int prio;
2371 pid_t pid;
2373 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2374 /* This is a pseudo handle */
2375 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2376 } else {
2377 process_handle = lookup_process_handle (process);
2378 if (!process_handle) {
2379 SetLastError (ERROR_INVALID_HANDLE);
2380 return FALSE;
2382 pid = process_handle->id;
2385 switch (priority_class) {
2386 case IDLE_PRIORITY_CLASS:
2387 prio = 19;
2388 break;
2389 case BELOW_NORMAL_PRIORITY_CLASS:
2390 prio = 10;
2391 break;
2392 case NORMAL_PRIORITY_CLASS:
2393 prio = 0;
2394 break;
2395 case ABOVE_NORMAL_PRIORITY_CLASS:
2396 prio = -5;
2397 break;
2398 case HIGH_PRIORITY_CLASS:
2399 prio = -11;
2400 break;
2401 case REALTIME_PRIORITY_CLASS:
2402 prio = -20;
2403 break;
2404 default:
2405 SetLastError (ERROR_INVALID_PARAMETER);
2406 return FALSE;
2409 ret = setpriority (PRIO_PROCESS, pid, prio);
2410 if (ret == -1) {
2411 switch (errno) {
2412 case EPERM:
2413 case EACCES:
2414 SetLastError (ERROR_ACCESS_DENIED);
2415 break;
2416 case ESRCH:
2417 SetLastError (ERROR_PROC_NOT_FOUND);
2418 break;
2419 default:
2420 SetLastError (ERROR_GEN_FAILURE);
2424 return ret == 0;
2425 #else
2426 SetLastError (ERROR_NOT_SUPPORTED);
2427 return FALSE;
2428 #endif
2431 static void
2432 mono_processes_cleanup (void)
2434 struct MonoProcess *mp;
2435 struct MonoProcess *prev = NULL;
2436 GSList *finished = NULL;
2437 GSList *l;
2438 gpointer unref_handle;
2440 DEBUG ("%s", __func__);
2442 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2443 if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
2444 return;
2446 for (mp = mono_processes; mp; mp = mp->next) {
2447 if (mp->pid == 0 && mp->handle) {
2448 /* This process has exited and we need to remove the artifical ref
2449 * on the handle */
2450 mono_mutex_lock (&mono_processes_mutex);
2451 unref_handle = mp->handle;
2452 mp->handle = NULL;
2453 mono_mutex_unlock (&mono_processes_mutex);
2454 if (unref_handle)
2455 _wapi_handle_unref (unref_handle);
2460 * Remove processes which exited from the mono_processes list.
2461 * We need to synchronize with the sigchld handler here, which runs
2462 * asynchronously. The handler requires that the mono_processes list
2463 * remain valid.
2465 mono_mutex_lock (&mono_processes_mutex);
2467 mp = mono_processes;
2468 while (mp) {
2469 if (mp->handle_count == 0 && mp->freeable) {
2471 * Unlink the entry.
2472 * This code can run parallel with the sigchld handler, but the
2473 * modifications it makes are safe.
2475 if (mp == mono_processes)
2476 mono_processes = mp->next;
2477 else
2478 prev->next = mp->next;
2479 finished = g_slist_prepend (finished, mp);
2481 mp = mp->next;
2482 } else {
2483 prev = mp;
2484 mp = mp->next;
2488 mono_memory_barrier ();
2490 for (l = finished; l; l = l->next) {
2492 * All the entries in the finished list are unlinked from mono_processes, and
2493 * they have the 'finished' flag set, which means the sigchld handler is done
2494 * accessing them.
2496 mp = l->data;
2497 MONO_SEM_DESTROY (&mp->exit_sem);
2498 g_free (mp);
2500 g_slist_free (finished);
2502 mono_mutex_unlock (&mono_processes_mutex);
2504 DEBUG ("%s done", __func__);
2506 InterlockedDecrement (&mono_processes_cleaning_up);
2509 static void
2510 process_close (gpointer handle, gpointer data)
2512 WapiHandle_process *process_handle;
2514 DEBUG ("%s", __func__);
2516 process_handle = (WapiHandle_process *) data;
2517 g_free (process_handle->proc_name);
2518 process_handle->proc_name = NULL;
2519 if (process_handle->mono_process)
2520 InterlockedDecrement (&process_handle->mono_process->handle_count);
2521 mono_processes_cleanup ();
2524 #if HAVE_SIGACTION
2525 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
2527 int status;
2528 int pid;
2529 struct MonoProcess *p;
2531 DEBUG ("SIG CHILD handler for pid: %i\n", info->si_pid);
2533 do {
2534 do {
2535 pid = waitpid (-1, &status, WNOHANG);
2536 } while (pid == -1 && errno == EINTR);
2538 if (pid <= 0)
2539 break;
2541 DEBUG ("child ended: %i", pid);
2544 * This can run concurrently with the code in the rest of this module.
2546 for (p = mono_processes; p; p = p->next) {
2547 if (p->pid == pid) {
2548 break;
2551 if (p) {
2552 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2553 p->status = status;
2554 MONO_SEM_POST (&p->exit_sem);
2555 mono_memory_barrier ();
2556 /* Mark this as freeable, the pointer becomes invalid afterwards */
2557 p->freeable = TRUE;
2559 } while (1);
2561 DEBUG ("SIG CHILD handler: done looping.");
2564 #endif
2566 static void
2567 process_add_sigchld_handler (void)
2569 #if HAVE_SIGACTION
2570 struct sigaction sa;
2572 sa.sa_sigaction = mono_sigchld_signal_handler;
2573 sigemptyset (&sa.sa_mask);
2574 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2575 g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2576 DEBUG ("Added SIGCHLD handler");
2577 #endif
2580 static guint32
2581 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2583 WapiHandle_process *process_handle;
2584 pid_t pid, ret;
2585 int status;
2586 guint32 start;
2587 guint32 now;
2588 struct MonoProcess *mp;
2590 /* FIXME: We can now easily wait on processes that aren't our own children,
2591 * but WaitFor*Object won't call us for pseudo handles. */
2592 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2594 DEBUG ("%s (%p, %u)", __func__, handle, timeout);
2596 process_handle = lookup_process_handle (handle);
2597 if (!process_handle) {
2598 g_warning ("%s: error looking up process handle %p", __func__, handle);
2599 return WAIT_FAILED;
2602 if (process_handle->exited) {
2603 /* We've already done this one */
2604 DEBUG ("%s (%p, %u): Process already exited", __func__, handle, timeout);
2605 return WAIT_OBJECT_0;
2608 pid = process_handle->id;
2610 DEBUG ("%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2612 /* We don't need to lock mono_processes here, the entry
2613 * has a handle_count > 0 which means it will not be freed. */
2614 mp = process_handle->mono_process;
2615 g_assert (mp);
2617 start = mono_msec_ticks ();
2618 now = start;
2620 while (1) {
2621 if (timeout != INFINITE) {
2622 DEBUG ("%s (%p, %u): waiting on semaphore for %li ms...",
2623 __func__, handle, timeout, (timeout - (now - start)));
2625 ret = MONO_SEM_TIMEDWAIT_ALERTABLE (&mp->exit_sem, (timeout - (now - start)), alertable);
2626 } else {
2627 DEBUG ("%s (%p, %u): waiting on semaphore forever...",
2628 __func__, handle, timeout);
2629 ret = MONO_SEM_WAIT_ALERTABLE (&mp->exit_sem, alertable);
2632 if (ret == -1 && errno != EINTR && errno != ETIMEDOUT) {
2633 DEBUG ("%s (%p, %u): sem_timedwait failure: %s",
2634 __func__, handle, timeout, g_strerror (errno));
2635 /* Should we return a failure here? */
2638 if (ret == 0) {
2639 /* Success, process has exited */
2640 MONO_SEM_POST (&mp->exit_sem);
2641 break;
2644 if (timeout == 0) {
2645 DEBUG ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
2646 return WAIT_TIMEOUT;
2649 now = mono_msec_ticks ();
2650 if (now - start >= timeout) {
2651 DEBUG ("%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
2652 return WAIT_TIMEOUT;
2655 if (alertable && _wapi_thread_cur_apc_pending ()) {
2656 DEBUG ("%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
2657 return WAIT_IO_COMPLETION;
2661 /* Process must have exited */
2662 DEBUG ("%s (%p, %u): Waited successfully", __func__, handle, timeout);
2664 ret = _wapi_handle_lock_shared_handles ();
2665 g_assert (ret == 0);
2667 status = mp ? mp->status : 0;
2668 if (WIFSIGNALED (status))
2669 process_handle->exitstatus = 128 + WTERMSIG (status);
2670 else
2671 process_handle->exitstatus = WEXITSTATUS (status);
2672 _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
2674 process_handle->exited = TRUE;
2676 DEBUG ("%s (%p, %u): Setting pid %d signalled, exit status %d",
2677 __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
2679 _wapi_handle_set_signal_state (handle, TRUE, TRUE);
2681 _wapi_handle_unlock_shared_handles ();
2683 return WAIT_OBJECT_0;
2686 void
2687 wapi_processes_cleanup (void)
2689 g_free (cli_launcher);