2007-03-22 Chris Toshok <toshok@ximian.com>
[mono-project/dkf.git] / mono / io-layer / processes.c
blob647fc35e70219948cc73c5138795675d62c6925c
1 /*
2 * processes.c: Process handles
4 * Author:
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002-2006 Novell, Inc.
8 */
10 #include <config.h>
11 #include <glib.h>
12 #include <string.h>
13 #include <pthread.h>
14 #include <sched.h>
15 #include <sys/time.h>
16 #include <errno.h>
17 #include <sys/types.h>
18 #include <unistd.h>
19 #include <signal.h>
20 #include <sys/wait.h>
22 #include <mono/io-layer/wapi.h>
23 #include <mono/io-layer/wapi-private.h>
24 #include <mono/io-layer/handles-private.h>
25 #include <mono/io-layer/misc-private.h>
26 #include <mono/io-layer/mono-mutex.h>
27 #include <mono/io-layer/process-private.h>
28 #include <mono/io-layer/threads.h>
29 #include <mono/utils/strenc.h>
30 #include <mono/io-layer/timefuncs-private.h>
32 /* The process' environment strings */
33 extern char **environ;
35 #undef DEBUG
37 static guint32 process_wait (gpointer handle, guint32 timeout);
39 struct _WapiHandleOps _wapi_process_ops = {
40 NULL, /* close_shared */
41 NULL, /* signal */
42 NULL, /* own */
43 NULL, /* is_owned */
44 process_wait, /* special_wait */
45 NULL /* prewait */
48 static mono_once_t process_current_once=MONO_ONCE_INIT;
49 static gpointer current_process=NULL;
51 static mono_once_t process_ops_once=MONO_ONCE_INIT;
53 static void process_ops_init (void)
55 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
56 WAPI_HANDLE_CAP_WAIT |
57 WAPI_HANDLE_CAP_SPECIAL_WAIT);
60 static gboolean process_set_termination_details (gpointer handle, int status)
62 struct _WapiHandle_process *process_handle;
63 gboolean ok;
64 int thr_ret;
66 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
67 (gpointer *)&process_handle);
68 if (ok == FALSE) {
69 g_warning ("%s: error looking up process handle %p",
70 __func__, handle);
71 return(FALSE);
74 thr_ret = _wapi_handle_lock_shared_handles ();
75 g_assert (thr_ret == 0);
77 if (WIFSIGNALED(status)) {
78 process_handle->exitstatus = 128 + WTERMSIG(status);
79 } else {
80 process_handle->exitstatus = WEXITSTATUS(status);
82 _wapi_time_t_to_filetime (time(NULL), &process_handle->exit_time);
84 /* Don't set process_handle->waited here, it needs to only
85 * happen in the parent when wait() has been called.
88 #ifdef DEBUG
89 g_message ("%s: Setting handle %p signalled", __func__, handle);
90 #endif
92 _wapi_shared_handle_set_signal_state (handle, TRUE);
94 _wapi_handle_unlock_shared_handles ();
96 /* Drop the reference we hold so we have somewhere to store
97 * the exit details, now the process has in fact exited
99 _wapi_handle_unref (handle);
101 return (ok);
104 /* See if any child processes have terminated and wait() for them,
105 * updating process handle info. This function is called from the
106 * collection thread every few seconds.
108 static gboolean waitfor_pid (gpointer test, gpointer user_data)
110 struct _WapiHandle_process *process;
111 gboolean ok;
112 int status;
113 pid_t ret;
115 ok = _wapi_lookup_handle (test, WAPI_HANDLE_PROCESS,
116 (gpointer *)&process);
117 if (ok == FALSE) {
118 /* The handle must have been too old and was reaped */
119 return (FALSE);
122 if (process->waited) {
123 /* We've already done this one */
124 return(FALSE);
127 do {
128 ret = waitpid (process->id, &status, WNOHANG);
129 } while (errno == EINTR);
131 if (ret <= 0) {
132 /* Process not ready for wait */
133 #ifdef DEBUG
134 g_message ("%s: Process %d not ready for waiting for: %s",
135 __func__, process->id, g_strerror (errno));
136 #endif
138 return (FALSE);
141 #ifdef DEBUG
142 g_message ("%s: Process %d finished", __func__, ret);
143 #endif
145 process->waited = TRUE;
147 *(int *)user_data = status;
149 return (TRUE);
152 void _wapi_process_reap (void)
154 gpointer proc;
155 int status;
157 #ifdef DEBUG
158 g_message ("%s: Reaping child processes", __func__);
159 #endif
161 do {
162 proc = _wapi_search_handle (WAPI_HANDLE_PROCESS, waitfor_pid,
163 &status, NULL, FALSE);
164 if (proc != NULL) {
165 #ifdef DEBUG
166 g_message ("%s: process handle %p exit code %d",
167 __func__, proc, status);
168 #endif
170 process_set_termination_details (proc, status);
172 /* _wapi_search_handle adds a reference, so
173 * drop it here
175 _wapi_handle_unref (proc);
177 } while (proc != NULL);
180 /* Limitations: This can only wait for processes that are our own
181 * children. Fixing this means resurrecting a daemon helper to manage
182 * processes.
184 static guint32 process_wait (gpointer handle, guint32 timeout)
186 struct _WapiHandle_process *process_handle;
187 gboolean ok;
188 pid_t pid, ret;
189 int status;
191 #ifdef DEBUG
192 g_message ("%s: Waiting for process %p", __func__, handle);
193 #endif
195 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
196 (gpointer *)&process_handle);
197 if (ok == FALSE) {
198 g_warning ("%s: error looking up process handle %p", __func__,
199 handle);
200 return(WAIT_FAILED);
203 if (process_handle->waited) {
204 /* We've already done this one */
205 #ifdef DEBUG
206 g_message ("%s: Process %p already signalled", __func__,
207 handle);
208 #endif
210 return (WAIT_OBJECT_0);
213 pid = process_handle->id;
215 #ifdef DEBUG
216 g_message ("%s: PID is %d, timeout %d", __func__, pid, timeout);
217 #endif
219 if (timeout == INFINITE) {
220 if (pid == _wapi_getpid ()) {
221 do {
222 Sleep (10000);
223 } while(1);
224 } else {
225 while ((ret = waitpid (pid, &status, 0)) != pid) {
226 if (ret == (pid_t)-1 && errno != EINTR) {
227 return(WAIT_FAILED);
231 } else if (timeout == 0) {
232 /* Just poll */
233 ret = waitpid (pid, &status, WNOHANG);
234 if (ret != pid) {
235 return (WAIT_TIMEOUT);
237 } else {
238 /* Poll in a loop */
239 if (pid == _wapi_getpid ()) {
240 Sleep (timeout);
241 return(WAIT_TIMEOUT);
242 } else {
243 do {
244 ret = waitpid (pid, &status, WNOHANG);
245 #ifdef DEBUG
246 g_message ("%s: waitpid returns: %d, timeout is %d", __func__, ret, timeout);
247 #endif
249 if (ret == pid) {
250 break;
251 } else if (ret == (pid_t)-1 &&
252 errno != EINTR) {
253 #ifdef DEBUG
254 g_message ("%s: waitpid failure: %s",
255 __func__,
256 g_strerror (errno));
257 #endif
259 if (errno == ECHILD &&
260 process_handle->waited) {
261 /* The background
262 * process reaper must
263 * have got this one
265 #ifdef DEBUG
266 g_message ("%s: Process %p already reaped", __func__, handle);
267 #endif
269 return(WAIT_OBJECT_0);
270 } else {
271 return(WAIT_FAILED);
275 _wapi_handle_spin (100);
276 timeout -= 100;
277 } while (timeout > 0);
280 if (timeout <= 0) {
281 return(WAIT_TIMEOUT);
285 /* Process must have exited */
286 #ifdef DEBUG
287 g_message ("%s: Wait done, status %d", __func__, status);
288 #endif
290 ok = process_set_termination_details (handle, status);
291 if (ok == FALSE) {
292 SetLastError (ERROR_OUTOFMEMORY);
293 return (WAIT_FAILED);
295 process_handle->waited = TRUE;
297 return(WAIT_OBJECT_0);
300 void _wapi_process_signal_self ()
302 if (current_process != NULL) {
303 process_set_termination_details (current_process, 0);
307 static void process_set_defaults (struct _WapiHandle_process *process_handle)
309 /* These seem to be the defaults on w2k */
310 process_handle->min_working_set = 204800;
311 process_handle->max_working_set = 1413120;
313 process_handle->waited = FALSE;
315 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
318 static int
319 len16 (const gunichar2 *str)
321 int len = 0;
323 while (*str++ != 0)
324 len++;
326 return len;
329 static gunichar2 *
330 utf16_concat (const gunichar2 *first, ...)
332 va_list args;
333 int total = 0, i;
334 const gunichar2 *s;
335 gunichar2 *ret;
337 va_start (args, first);
338 total += len16 (first);
339 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
340 total += len16 (s);
342 va_end (args);
344 ret = g_new (gunichar2, total + 1);
345 if (ret == NULL)
346 return NULL;
348 ret [total] = 0;
349 i = 0;
350 for (s = first; *s != 0; s++)
351 ret [i++] = *s;
352 va_start (args, first);
353 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
354 const gunichar2 *p;
356 for (p = s; *p != 0; p++)
357 ret [i++] = *p;
359 va_end (args);
361 return ret;
364 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
365 static const gunichar2 *utf16_space = utf16_space_bytes;
367 /* Implemented as just a wrapper around CreateProcess () */
368 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
370 gboolean ret;
371 WapiProcessInformation process_info;
372 gunichar2 *args;
374 if (sei == NULL) {
375 /* w2k just segfaults here, but we can do better than
376 * that
378 SetLastError (ERROR_INVALID_PARAMETER);
379 return (FALSE);
382 if (sei->lpFile == NULL) {
383 /* w2k returns TRUE for this, for some reason. */
384 return (TRUE);
387 /* Put both executable and parameters into the second argument
388 * to CreateProcess (), so it searches $PATH. The conversion
389 * into and back out of utf8 is because there is no
390 * g_strdup_printf () equivalent for gunichar2 :-(
392 args = utf16_concat (sei->lpFile, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
393 if (args == NULL){
394 SetLastError (ERROR_INVALID_DATA);
395 return (FALSE);
397 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
398 CREATE_UNICODE_ENVIRONMENT, NULL,
399 sei->lpDirectory, NULL, &process_info);
400 g_free (args);
402 if (!ret) {
403 static char *handler;
404 static gunichar2 *handler_utf16;
406 if (handler_utf16 == (gunichar2 *)-1)
407 return FALSE;
409 #ifdef PLATFORM_MACOSX
410 handler = "/usr/bin/open";
411 #else
413 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
414 * if that fails, try to use gnome-open, then kfmclient
416 handler = g_find_program_in_path ("xdg-open");
417 if (handler == NULL){
418 handler = g_find_program_in_path ("gnome-open");
419 if (handler == NULL){
420 handler = g_find_program_in_path ("kfmclient");
421 if (handler == NULL){
422 handler_utf16 = (gunichar2 *) -1;
423 return (FALSE);
424 } else {
425 /* kfmclient needs exec argument */
426 char *old = handler;
427 handler = g_strconcat (old, " exec",
428 NULL);
429 g_free (old);
433 #endif
434 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
435 g_free (handler);
436 args = utf16_concat (handler_utf16, utf16_space, sei->lpFile,
437 sei->lpParameters == NULL ? NULL : utf16_space,
438 sei->lpParameters, NULL);
439 if (args == NULL){
440 SetLastError (ERROR_INVALID_DATA);
441 return FALSE;
443 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
444 CREATE_UNICODE_ENVIRONMENT, NULL,
445 sei->lpDirectory, NULL, &process_info);
446 g_free (args);
447 if (!ret){
448 SetLastError (ERROR_INVALID_DATA);
449 return FALSE;
453 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
454 sei->hProcess = process_info.hProcess;
455 } else {
456 CloseHandle (process_info.hProcess);
459 return (ret);
462 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
463 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
464 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
465 gboolean inherit_handles, guint32 create_flags,
466 gpointer new_environ, const gunichar2 *cwd,
467 WapiStartupInfo *startup,
468 WapiProcessInformation *process_info)
470 gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
471 guint32 i, env_count = 0;
472 gboolean ret = FALSE;
473 gpointer handle;
474 struct _WapiHandle_process process_handle = {0}, *process_handle_data;
475 GError *gerr = NULL;
476 int in_fd, out_fd, err_fd;
477 pid_t pid;
478 int thr_ret;
480 mono_once (&process_ops_once, process_ops_init);
482 /* appname and cmdline specify the executable and its args:
484 * If appname is not NULL, it is the name of the executable.
485 * Otherwise the executable is the first token in cmdline.
487 * Executable searching:
489 * If appname is not NULL, it can specify the full path and
490 * file name, or else a partial name and the current directory
491 * will be used. There is no additional searching.
493 * If appname is NULL, the first whitespace-delimited token in
494 * cmdline is used. If the name does not contain a full
495 * directory path, the search sequence is:
497 * 1) The directory containing the current process
498 * 2) The current working directory
499 * 3) The windows system directory (Ignored)
500 * 4) The windows directory (Ignored)
501 * 5) $PATH
503 * Just to make things more interesting, tokens can contain
504 * white space if they are surrounded by quotation marks. I'm
505 * beginning to understand just why windows apps are generally
506 * so crap, with an API like this :-(
508 if (appname != NULL) {
509 cmd = mono_unicode_to_external (appname);
510 if (cmd == NULL) {
511 #ifdef DEBUG
512 g_message ("%s: unicode conversion returned NULL",
513 __func__);
514 #endif
516 SetLastError (ERROR_PATH_NOT_FOUND);
517 goto cleanup;
520 /* Turn all the slashes round the right way */
521 for (i = 0; i < strlen (cmd); i++) {
522 if (cmd[i] == '\\') {
523 cmd[i] = '/';
528 if (cmdline != NULL) {
529 args = mono_unicode_to_external (cmdline);
530 if (args == NULL) {
531 #ifdef DEBUG
532 g_message ("%s: unicode conversion returned NULL", __func__);
533 #endif
535 SetLastError (ERROR_PATH_NOT_FOUND);
536 goto cleanup;
540 if (cwd != NULL) {
541 dir = mono_unicode_to_external (cwd);
542 if (dir == NULL) {
543 #ifdef DEBUG
544 g_message ("%s: unicode conversion returned NULL", __func__);
545 #endif
547 SetLastError (ERROR_PATH_NOT_FOUND);
548 goto cleanup;
551 /* Turn all the slashes round the right way */
552 for (i = 0; i < strlen (dir); i++) {
553 if (dir[i] == '\\') {
554 dir[i] = '/';
560 /* We can't put off locating the executable any longer :-( */
561 if (cmd != NULL) {
562 gchar *unquoted;
563 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
564 /* Strip off the drive letter. I can't
565 * believe that CP/M holdover is still
566 * visible...
568 g_memmove (cmd, cmd+2, strlen (cmd)-2);
569 cmd[strlen (cmd)-2] = '\0';
572 unquoted = g_shell_unquote (cmd, NULL);
573 if (unquoted[0] == '/') {
574 /* Assume full path given */
575 prog = g_strdup (unquoted);
577 /* Executable existing ? */
578 if (access (prog, X_OK) != 0) {
579 #ifdef DEBUG
580 g_message ("%s: Couldn't find executable %s",
581 __func__, prog);
582 #endif
583 g_free (unquoted);
584 SetLastError (ERROR_FILE_NOT_FOUND);
585 goto cleanup;
587 } else {
588 /* Search for file named by cmd in the current
589 * directory
591 char *curdir = g_get_current_dir ();
593 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
594 g_free (curdir);
596 /* And make sure it's executable */
597 if (access (prog, X_OK) != 0) {
598 #ifdef DEBUG
599 g_message ("%s: Couldn't find executable %s",
600 __func__, prog);
601 #endif
602 g_free (unquoted);
603 SetLastError (ERROR_FILE_NOT_FOUND);
604 goto cleanup;
607 g_free (unquoted);
609 args_after_prog = args;
610 } else {
611 gchar *token = NULL;
612 char quote;
614 /* Dig out the first token from args, taking quotation
615 * marks into account
618 /* First, strip off all leading whitespace */
619 args = g_strchug (args);
621 /* args_after_prog points to the contents of args
622 * after token has been set (otherwise argv[0] is
623 * duplicated)
625 args_after_prog = args;
627 /* Assume the opening quote will always be the first
628 * character
630 if (args[0] == '\"' || args [0] == '\'') {
631 quote = args [0];
632 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
633 if (g_ascii_isspace (args[i+1])) {
634 /* We found the first token */
635 token = g_strndup (args+1, i-1);
636 args_after_prog = args + i;
637 } else {
638 /* Quotation mark appeared in the
639 * middle of the token. Just give the
640 * whole first token, quotes and all,
641 * to exec.
646 if (token == NULL) {
647 /* No quote mark, or malformed */
648 for (i = 0; args[i] != '\0'; i++) {
649 if (g_ascii_isspace (args[i])) {
650 token = g_strndup (args, i);
651 args_after_prog = args + i + 1;
652 break;
657 if (token == NULL && args[0] != '\0') {
658 /* Must be just one token in the string */
659 token = g_strdup (args);
660 args_after_prog = NULL;
663 if (token == NULL) {
664 /* Give up */
665 #ifdef DEBUG
666 g_message ("%s: Couldn't find what to exec", __func__);
667 #endif
669 SetLastError (ERROR_PATH_NOT_FOUND);
670 goto cleanup;
673 /* Turn all the slashes round the right way. Only for
674 * the prg. name
676 for (i = 0; i < strlen (token); i++) {
677 if (token[i] == '\\') {
678 token[i] = '/';
682 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
683 /* Strip off the drive letter. I can't
684 * believe that CP/M holdover is still
685 * visible...
687 g_memmove (token, token+2, strlen (token)-2);
688 token[strlen (token)-2] = '\0';
691 if (token[0] == '/') {
692 /* Assume full path given */
693 prog = g_strdup (token);
695 /* Executable existing ? */
696 if (access (prog, X_OK) != 0) {
697 #ifdef DEBUG
698 g_message ("%s: Couldn't find executable %s",
699 __func__, token);
700 #endif
701 g_free (token);
702 SetLastError (ERROR_FILE_NOT_FOUND);
703 goto cleanup;
706 } else {
707 char *curdir = g_get_current_dir ();
709 /* FIXME: Need to record the directory
710 * containing the current process, and check
711 * that for the new executable as the first
712 * place to look
715 prog = g_strdup_printf ("%s/%s", curdir, token);
716 g_free (curdir);
718 /* I assume X_OK is the criterion to use,
719 * rather than F_OK
721 if (access (prog, X_OK) != 0) {
722 g_free (prog);
723 prog = g_find_program_in_path (token);
724 if (prog == NULL) {
725 #ifdef DEBUG
726 g_message ("%s: Couldn't find executable %s", __func__, token);
727 #endif
729 g_free (token);
730 SetLastError (ERROR_FILE_NOT_FOUND);
731 goto cleanup;
736 g_free (token);
739 #ifdef DEBUG
740 g_message ("%s: Exec prog [%s] args [%s]", __func__, prog,
741 args_after_prog);
742 #endif
744 if (args_after_prog != NULL && *args_after_prog) {
745 gchar *qprog;
747 qprog = g_shell_quote (prog);
748 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
749 g_free (qprog);
750 } else {
751 full_prog = g_shell_quote (prog);
754 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
755 if (ret == FALSE) {
756 /* FIXME: Could do something with the GError here
760 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
761 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
762 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
763 err_fd = GPOINTER_TO_UINT (startup->hStdError);
764 } else {
765 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
766 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
767 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
770 g_strlcpy (process_handle.proc_name, prog,
771 _WAPI_PROC_NAME_MAX_LEN - 1);
773 process_set_defaults (&process_handle);
775 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
776 if (handle == _WAPI_HANDLE_INVALID) {
777 g_warning ("%s: error creating process handle", __func__);
779 SetLastError (ERROR_PATH_NOT_FOUND);
780 goto cleanup;
783 /* Hold another reference so the process has somewhere to
784 * store its exit data even if we drop this handle
786 _wapi_handle_ref (handle);
788 /* new_environ is a block of NULL-terminated strings, which
789 * is itself NULL-terminated. Of course, passing an array of
790 * string pointers would have made things too easy :-(
792 * If new_environ is not NULL it specifies the entire set of
793 * environment variables in the new process. Otherwise the
794 * new process inherits the same environment.
796 if (new_environ != NULL) {
797 gunichar2 *new_environp;
799 /* Count the number of strings */
800 for (new_environp = (gunichar2 *)new_environ; *new_environp;
801 new_environp++) {
802 env_count++;
803 while (*new_environp) {
804 new_environp++;
808 /* +2: one for the process handle value, and the last
809 * one is NULL
811 env_strings = g_new0 (gchar *, env_count + 2);
813 /* Copy each environ string into 'strings' turning it
814 * into utf8 (or the requested encoding) at the same
815 * time
817 env_count = 0;
818 for (new_environp = (gunichar2 *)new_environ; *new_environp;
819 new_environp++) {
820 env_strings[env_count] = mono_unicode_to_external (new_environp);
821 env_count++;
822 while (*new_environp) {
823 new_environp++;
826 } else {
827 for (i = 0; environ[i] != NULL; i++) {
828 env_count++;
831 /* +2: one for the process handle value, and the last
832 * one is NULL
834 env_strings = g_new0 (gchar *, env_count + 2);
836 /* Copy each environ string into 'strings' turning it
837 * into utf8 (or the requested encoding) at the same
838 * time
840 env_count = 0;
841 for (i = 0; environ[i] != NULL; i++) {
842 env_strings[env_count] = g_strdup (environ[i]);
843 env_count++;
846 /* pass process handle info to the child, so it doesn't have
847 * to do an expensive search over the whole list
849 if (env_strings != NULL) {
850 struct _WapiHandleUnshared *handle_data;
851 struct _WapiHandle_shared_ref *ref;
853 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
854 ref = &handle_data->u.shared;
856 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
859 thr_ret = _wapi_handle_lock_shared_handles ();
860 g_assert (thr_ret == 0);
862 pid = fork ();
863 if (pid == -1) {
864 /* Error */
865 SetLastError (ERROR_OUTOFMEMORY);
866 _wapi_handle_unref (handle);
867 goto cleanup;
868 } else if (pid == 0) {
869 /* Child */
871 /* Wait for the parent to finish setting up the
872 * handle. The semaphore lock is safe because the
873 * sem_undo structures of a semaphore aren't inherited
874 * across a fork ()
876 thr_ret = _wapi_handle_lock_shared_handles ();
877 g_assert (thr_ret == 0);
879 _wapi_handle_unlock_shared_handles ();
881 /* should we detach from the process group? */
883 /* Connect stdin, stdout and stderr */
884 dup2 (in_fd, 0);
885 dup2 (out_fd, 1);
886 dup2 (err_fd, 2);
888 if (inherit_handles != TRUE) {
889 /* FIXME: do something here */
892 /* Close all file descriptors */
893 for (i = getdtablesize () - 1; i > 2; i--) {
894 close (i);
897 #ifdef DEBUG
898 g_message ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
899 dir==NULL?".":dir);
900 for (i = 0; argv[i] != NULL; i++) {
901 g_message ("arg %d: [%s]", i, argv[i]);
904 for (i = 0; env_strings[i] != NULL; i++) {
905 g_message ("env %d: [%s]", i, env_strings[i]);
907 #endif
909 /* set cwd */
910 if (dir != NULL && chdir (dir) == -1) {
911 /* set error */
912 _exit (-1);
915 /* exec */
916 execve (argv[0], argv, env_strings);
918 /* set error */
919 _exit (-1);
921 /* parent */
923 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
924 (gpointer *)&process_handle_data);
925 if (ret == FALSE) {
926 g_warning ("%s: error looking up process handle %p", __func__,
927 handle);
928 _wapi_handle_unref (handle);
929 goto cleanup;
932 process_handle_data->id = pid;
934 if (process_info != NULL) {
935 process_info->hProcess = handle;
936 process_info->dwProcessId = pid;
938 /* FIXME: we might need to handle the thread info some
939 * day
941 process_info->hThread = INVALID_HANDLE_VALUE;
942 process_info->dwThreadId = 0;
945 cleanup:
946 _wapi_handle_unlock_shared_handles ();
948 if (cmd != NULL) {
949 g_free (cmd);
951 if (full_prog != NULL) {
952 g_free (full_prog);
954 if (prog != NULL) {
955 g_free (prog);
957 if (args != NULL) {
958 g_free (args);
960 if (dir != NULL) {
961 g_free (dir);
963 if(env_strings != NULL) {
964 g_strfreev (env_strings);
966 if (argv != NULL) {
967 g_strfreev (argv);
970 #ifdef DEBUG
971 g_message ("%s: returning handle %p for pid %d", __func__, handle,
972 pid);
973 #endif
975 return(ret);
978 static void process_set_name (struct _WapiHandle_process *process_handle)
980 gchar *progname, *utf8_progname, *slash;
982 progname=g_get_prgname ();
983 utf8_progname=mono_utf8_from_external (progname);
985 #ifdef DEBUG
986 g_message ("%s: using [%s] as prog name", __func__, progname);
987 #endif
989 if(utf8_progname!=NULL) {
990 slash=strrchr (utf8_progname, '/');
991 if(slash!=NULL) {
992 g_strlcpy (process_handle->proc_name, slash+1,
993 _WAPI_PROC_NAME_MAX_LEN - 1);
994 } else {
995 g_strlcpy (process_handle->proc_name, utf8_progname,
996 _WAPI_PROC_NAME_MAX_LEN - 1);
999 g_free (utf8_progname);
1003 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
1005 #if !GLIB_CHECK_VERSION (2,4,0)
1006 #define g_setenv(a,b,c) setenv(a,b,c)
1007 #define g_unsetenv(a) unsetenv(a)
1008 #endif
1010 static void process_set_current (void)
1012 pid_t pid = _wapi_getpid ();
1013 const char *handle_env;
1014 struct _WapiHandle_process process_handle = {0};
1016 mono_once (&process_ops_once, process_ops_init);
1018 handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1019 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1021 if (handle_env != NULL) {
1022 struct _WapiHandle_process *process_handlep;
1023 gchar *procname = NULL;
1024 gboolean ok;
1026 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
1028 #ifdef DEBUG
1029 g_message ("%s: Found my process handle: %p (offset %d 0x%x)",
1030 __func__, current_process, atoi (handle_env),
1031 atoi (handle_env));
1032 #endif
1034 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
1035 (gpointer *)&process_handlep);
1036 if (ok) {
1037 /* This test will probably break on linuxthreads, but
1038 * that should be ancient history on all distros we
1039 * care about by now
1041 if (process_handlep->id == pid) {
1042 procname = process_handlep->proc_name;
1043 if (!strcmp (procname, "mono")) {
1044 /* Set a better process name */
1045 #ifdef DEBUG
1046 g_message ("%s: Setting better process name", __func__);
1047 #endif
1049 process_set_name (process_handlep);
1050 } else {
1051 #ifdef DEBUG
1052 g_message ("%s: Leaving process name: %s", __func__, procname);
1053 #endif
1056 return;
1059 /* Wrong pid, so drop this handle and fall through to
1060 * create a new one
1062 _wapi_handle_unref (current_process);
1066 /* We get here if the handle wasn't specified in the
1067 * environment, or if the process ID was wrong, or if the
1068 * handle lookup failed (eg if the parent process forked and
1069 * quit immediately, and deleted the shared data before the
1070 * child got a chance to attach it.)
1073 #ifdef DEBUG
1074 g_message ("%s: Need to create my own process handle", __func__);
1075 #endif
1077 process_handle.id = pid;
1079 process_set_defaults (&process_handle);
1080 process_set_name (&process_handle);
1082 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1083 &process_handle);
1084 if (current_process == _WAPI_HANDLE_INVALID) {
1085 g_warning ("%s: error creating process handle", __func__);
1086 return;
1090 gpointer _wapi_process_duplicate ()
1092 mono_once (&process_current_once, process_set_current);
1094 _wapi_handle_ref (current_process);
1096 return(current_process);
1099 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1100 gpointer GetCurrentProcess (void)
1102 mono_once (&process_current_once, process_set_current);
1104 return(_WAPI_PROCESS_CURRENT);
1107 guint32 GetProcessId (gpointer handle)
1109 struct _WapiHandle_process *process_handle;
1110 gboolean ok;
1112 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1113 (gpointer *)&process_handle);
1114 if (ok == FALSE) {
1115 SetLastError (ERROR_INVALID_HANDLE);
1116 return (0);
1119 return (process_handle->id);
1122 guint32 GetCurrentProcessId (void)
1124 mono_once (&process_current_once, process_set_current);
1126 return (GetProcessId (current_process));
1129 /* Returns the process id as a convenience to the functions that call this */
1130 static pid_t signal_process_if_gone (gpointer handle)
1132 struct _WapiHandle_process *process_handle;
1133 gboolean ok;
1135 /* Make sure the process is signalled if it has exited - if
1136 * the parent process didn't wait for it then it won't be
1138 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1139 (gpointer *)&process_handle);
1140 if (ok == FALSE) {
1141 /* It's possible that the handle has vanished during
1142 * the _wapi_search_handle before it gets here, so
1143 * don't spam the console with warnings.
1145 /* g_warning ("%s: error looking up process handle %p",
1146 __func__, handle);*/
1148 return (0);
1151 #ifdef DEBUG
1152 g_message ("%s: looking at process %d", __func__, process_handle->id);
1153 #endif
1155 if (kill (process_handle->id, 0) == -1 &&
1156 (errno == ESRCH ||
1157 errno == EPERM)) {
1158 /* The process is dead, (EPERM tells us a new process
1159 * has that ID, but as it's owned by someone else it
1160 * can't be the one listed in our shared memory file)
1162 _wapi_shared_handle_set_signal_state (handle, TRUE);
1165 return (process_handle->id);
1168 static gboolean process_enum (gpointer handle, gpointer user_data)
1170 GArray *processes=user_data;
1171 pid_t pid = signal_process_if_gone (handle);
1172 int i;
1174 if (pid == 0) {
1175 return (FALSE);
1178 /* Ignore processes that have already exited (ie they are signalled) */
1179 if (_wapi_handle_issignalled (handle) == FALSE) {
1180 #ifdef DEBUG
1181 g_message ("%s: process %d added to array", __func__, pid);
1182 #endif
1184 /* This ensures that duplicates aren't returned (see
1185 * the comment above _wapi_search_handle () for why
1186 * it's needed
1188 for (i = 0; i < processes->len; i++) {
1189 if (g_array_index (processes, pid_t, i) == pid) {
1190 /* We've already got this one, return
1191 * FALSE to keep searching
1193 return (FALSE);
1197 g_array_append_val (processes, pid);
1200 /* Return false to keep searching */
1201 return(FALSE);
1204 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1206 GArray *processes = g_array_new (FALSE, FALSE, sizeof(pid_t));
1207 guint32 fit, i, j;
1209 mono_once (&process_current_once, process_set_current);
1211 _wapi_search_handle (WAPI_HANDLE_PROCESS, process_enum, processes,
1212 NULL, TRUE);
1214 fit=len/sizeof(guint32);
1215 for (i = 0, j = 0; j < fit && i < processes->len; i++) {
1216 pids[j++] = g_array_index (processes, pid_t, i);
1219 g_array_free (processes, TRUE);
1221 *needed = j * sizeof(guint32);
1223 return(TRUE);
1226 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1228 pid_t wanted_pid;
1229 pid_t checking_pid = signal_process_if_gone (handle);
1231 if (checking_pid == 0) {
1232 return(FALSE);
1235 wanted_pid = GPOINTER_TO_UINT (user_data);
1237 /* It's possible to have more than one process handle with the
1238 * same pid, but only the one running process can be
1239 * unsignalled
1241 if (checking_pid == wanted_pid &&
1242 _wapi_handle_issignalled (handle) == FALSE) {
1243 /* If the handle is blown away in the window between
1244 * returning TRUE here and _wapi_search_handle pinging
1245 * the timestamp, the search will continue
1247 return(TRUE);
1248 } else {
1249 return(FALSE);
1253 gpointer OpenProcess (guint32 access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1255 /* Find the process handle that corresponds to pid */
1256 gpointer handle;
1258 mono_once (&process_current_once, process_set_current);
1260 #ifdef DEBUG
1261 g_message ("%s: looking for process %d", __func__, pid);
1262 #endif
1264 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1265 process_open_compare,
1266 GUINT_TO_POINTER (pid), NULL, TRUE);
1267 if (handle == 0) {
1268 #ifdef DEBUG
1269 g_message ("%s: Can't find pid %d", __func__, pid);
1270 #endif
1272 SetLastError (ERROR_PROC_NOT_FOUND);
1274 return(NULL);
1277 _wapi_handle_ref (handle);
1279 return(handle);
1282 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1284 struct _WapiHandle_process *process_handle;
1285 gboolean ok;
1287 mono_once (&process_current_once, process_set_current);
1289 if(code==NULL) {
1290 return(FALSE);
1293 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1294 (gpointer *)&process_handle);
1295 if(ok==FALSE) {
1296 #ifdef DEBUG
1297 g_message ("%s: Can't find process %p", __func__, process);
1298 #endif
1300 return(FALSE);
1303 /* A process handle is only signalled if the process has exited
1304 * and has been waited for */
1305 if (_wapi_handle_issignalled (process) == TRUE ||
1306 process_wait (process, 0) == WAIT_OBJECT_0) {
1307 *code = process_handle->exitstatus;
1308 } else {
1309 *code = STILL_ACTIVE;
1312 return(TRUE);
1315 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1316 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1317 WapiFileTime *user_time)
1319 struct _WapiHandle_process *process_handle;
1320 gboolean ok;
1322 mono_once (&process_current_once, process_set_current);
1324 if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1325 user_time==NULL) {
1326 /* Not sure if w32 allows NULLs here or not */
1327 return(FALSE);
1330 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1331 (gpointer *)&process_handle);
1332 if(ok==FALSE) {
1333 #ifdef DEBUG
1334 g_message ("%s: Can't find process %p", __func__, process);
1335 #endif
1337 return(FALSE);
1340 *create_time=process_handle->create_time;
1342 /* A process handle is only signalled if the process has
1343 * exited. Otherwise exit_time isn't set
1345 if(_wapi_handle_issignalled (process)==TRUE) {
1346 *exit_time=process_handle->exit_time;
1349 return(TRUE);
1352 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1353 guint32 size, guint32 *needed)
1355 /* Store modules in an array of pointers (main module as
1356 * modules[0]), using the load address for each module as a
1357 * token. (Use 'NULL' as an alternative for the main module
1358 * so that the simple implementation can just return one item
1359 * for now.) Get the info from /proc/<pid>/maps on linux,
1360 * other systems will have to implement /dev/kmem reading or
1361 * whatever other horrid technique is needed.
1363 if(size<sizeof(gpointer)) {
1364 return(FALSE);
1367 #ifdef linux
1368 modules[0]=NULL;
1369 *needed=sizeof(gpointer);
1370 #else
1371 modules[0]=NULL;
1372 *needed=sizeof(gpointer);
1373 #endif
1375 return(TRUE);
1378 guint32 GetModuleBaseName (gpointer process, gpointer module,
1379 gunichar2 *basename, guint32 size)
1381 struct _WapiHandle_process *process_handle;
1382 gboolean ok;
1384 mono_once (&process_current_once, process_set_current);
1386 #ifdef DEBUG
1387 g_message ("%s: Getting module base name, process handle %p module %p",
1388 __func__, process, module);
1389 #endif
1391 if(basename==NULL || size==0) {
1392 return(FALSE);
1395 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1396 (gpointer *)&process_handle);
1397 if(ok==FALSE) {
1398 #ifdef DEBUG
1399 g_message ("%s: Can't find process %p", __func__, process);
1400 #endif
1402 return(FALSE);
1405 if(module==NULL) {
1406 /* Shorthand for the main module, which has the
1407 * process name recorded in the handle data
1409 pid_t pid;
1410 gunichar2 *procname;
1411 gchar *procname_utf8 = NULL;
1412 glong len, bytes;
1414 #ifdef DEBUG
1415 g_message ("%s: Returning main module name", __func__);
1416 #endif
1418 pid=process_handle->id;
1419 procname_utf8 = process_handle->proc_name;
1421 #ifdef DEBUG
1422 g_message ("%s: Process name is [%s]", __func__,
1423 procname_utf8);
1424 #endif
1426 procname = g_utf8_to_utf16 (procname_utf8, -1, NULL, &len,
1427 NULL);
1428 if (procname == NULL) {
1429 /* bugger */
1430 return(0);
1433 /* Add the terminator, and convert chars to bytes */
1434 bytes = (len + 1) * 2;
1436 if (size < bytes) {
1437 #ifdef DEBUG
1438 g_message ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
1439 #endif
1441 memcpy (basename, procname, size);
1442 } else {
1443 #ifdef DEBUG
1444 g_message ("%s: Size %d larger than needed (%ld)",
1445 __func__, size, bytes);
1446 #endif
1448 memcpy (basename, procname, bytes);
1451 g_free (procname);
1453 return(len);
1454 } else {
1455 /* Look up the address in /proc/<pid>/maps */
1458 return(0);
1461 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
1463 struct _WapiHandle_process *process_handle;
1464 gboolean ok;
1466 mono_once (&process_current_once, process_set_current);
1468 if(min==NULL || max==NULL) {
1469 /* Not sure if w32 allows NULLs here or not */
1470 return(FALSE);
1473 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1474 (gpointer *)&process_handle);
1475 if(ok==FALSE) {
1476 #ifdef DEBUG
1477 g_message ("%s: Can't find process %p", __func__, process);
1478 #endif
1480 return(FALSE);
1483 *min=process_handle->min_working_set;
1484 *max=process_handle->max_working_set;
1486 return(TRUE);
1489 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
1491 struct _WapiHandle_process *process_handle;
1492 gboolean ok;
1494 mono_once (&process_current_once, process_set_current);
1496 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1497 (gpointer *)&process_handle);
1498 if(ok==FALSE) {
1499 #ifdef DEBUG
1500 g_message ("%s: Can't find process %p", __func__, process);
1501 #endif
1503 return(FALSE);
1506 process_handle->min_working_set=min;
1507 process_handle->max_working_set=max;
1509 return(TRUE);
1513 gboolean
1514 TerminateProcess (gpointer process, gint32 exitCode)
1516 struct _WapiHandle_process *process_handle;
1517 gboolean ok;
1518 int signo;
1519 int ret;
1521 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1522 (gpointer *) &process_handle);
1524 if (ok == FALSE) {
1525 #ifdef DEBUG
1526 g_message ("%s: Can't find process %p", __func__, process);
1527 #endif
1528 SetLastError (ERROR_INVALID_HANDLE);
1529 return FALSE;
1532 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
1533 ret = kill (process_handle->id, signo);
1534 if (ret == -1) {
1535 switch (errno) {
1536 case EINVAL:
1537 SetLastError (ERROR_INVALID_PARAMETER);
1538 break;
1539 case EPERM:
1540 SetLastError (ERROR_ACCESS_DENIED);
1541 break;
1542 case ESRCH:
1543 SetLastError (ERROR_PROC_NOT_FOUND);
1544 break;
1545 default:
1546 SetLastError (ERROR_GEN_FAILURE);
1550 return (ret == 0);