2008-11-05 Zoltan Varga <vargaz@gmail.com>
[mono-project.git] / mono / io-layer / processes.c
blob5df9a14157d7541db46b09695d47115f350315c7
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 <stdio.h>
13 #include <string.h>
14 #include <pthread.h>
15 #include <sched.h>
16 #include <sys/time.h>
17 #include <errno.h>
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <unistd.h>
21 #include <signal.h>
22 #include <sys/wait.h>
23 #include <sys/time.h>
24 #include <sys/resource.h>
25 #include <fcntl.h>
26 #include <sys/param.h>
27 #include <ctype.h>
29 #ifdef HAVE_SYS_MKDEV_H
30 #include <sys/mkdev.h>
31 #endif
33 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
34 #ifdef __APPLE__
35 #include <sys/resource.h>
36 #endif
38 #include <mono/io-layer/wapi.h>
39 #include <mono/io-layer/wapi-private.h>
40 #include <mono/io-layer/handles-private.h>
41 #include <mono/io-layer/misc-private.h>
42 #include <mono/io-layer/mono-mutex.h>
43 #include <mono/io-layer/process-private.h>
44 #include <mono/io-layer/threads.h>
45 #include <mono/utils/strenc.h>
46 #include <mono/io-layer/timefuncs-private.h>
48 /* The process' environment strings */
49 #ifdef __APPLE__
50 /* Apple defines this in crt_externs.h but doesn't provide that header for
51 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
52 * in fact exist on all implementations (so far)
54 gchar ***_NSGetEnviron();
55 #define environ (*_NSGetEnviron())
56 #else
57 extern char **environ;
58 #endif
60 #undef DEBUG
62 static guint32 process_wait (gpointer handle, guint32 timeout);
64 struct _WapiHandleOps _wapi_process_ops = {
65 NULL, /* close_shared */
66 NULL, /* signal */
67 NULL, /* own */
68 NULL, /* is_owned */
69 process_wait, /* special_wait */
70 NULL /* prewait */
73 static mono_once_t process_current_once=MONO_ONCE_INIT;
74 static gpointer current_process=NULL;
76 static mono_once_t process_ops_once=MONO_ONCE_INIT;
78 static void process_ops_init (void)
80 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
81 WAPI_HANDLE_CAP_WAIT |
82 WAPI_HANDLE_CAP_SPECIAL_WAIT);
85 static gboolean process_set_termination_details (gpointer handle, int status)
87 struct _WapiHandle_process *process_handle;
88 gboolean ok;
89 int thr_ret;
91 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
93 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
94 (gpointer *)&process_handle);
95 if (ok == FALSE) {
96 g_warning ("%s: error looking up process handle %p",
97 __func__, handle);
98 return(FALSE);
101 thr_ret = _wapi_handle_lock_shared_handles ();
102 g_assert (thr_ret == 0);
104 if (WIFSIGNALED(status)) {
105 process_handle->exitstatus = 128 + WTERMSIG(status);
106 } else {
107 process_handle->exitstatus = WEXITSTATUS(status);
109 _wapi_time_t_to_filetime (time(NULL), &process_handle->exit_time);
111 /* Don't set process_handle->waited here, it needs to only
112 * happen in the parent when wait() has been called.
115 #ifdef DEBUG
116 g_message ("%s: Setting handle %p pid %d signalled, exit status %d",
117 __func__, handle, process_handle->id,
118 process_handle->exitstatus);
119 #endif
121 _wapi_shared_handle_set_signal_state (handle, TRUE);
123 _wapi_handle_unlock_shared_handles ();
125 /* Drop the reference we hold so we have somewhere to store
126 * the exit details, now the process has in fact exited
128 _wapi_handle_unref (handle);
130 return (ok);
133 /* See if any child processes have terminated and wait() for them,
134 * updating process handle info. This function is called from the
135 * collection thread every few seconds.
137 static gboolean waitfor_pid (gpointer test, gpointer user_data)
139 struct _WapiHandle_process *process;
140 gboolean ok;
141 int status;
142 pid_t ret;
144 g_assert ((GPOINTER_TO_UINT (test) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
146 ok = _wapi_lookup_handle (test, WAPI_HANDLE_PROCESS,
147 (gpointer *)&process);
148 if (ok == FALSE) {
149 /* The handle must have been too old and was reaped */
150 return (FALSE);
153 if (process->waited) {
154 /* We've already done this one */
155 return(FALSE);
158 do {
159 ret = waitpid (process->id, &status, WNOHANG);
160 } while (errno == EINTR);
162 if (ret <= 0) {
163 /* Process not ready for wait */
164 #ifdef DEBUG
165 g_message ("%s: Process %d not ready for waiting for: %s",
166 __func__, process->id, g_strerror (errno));
167 #endif
169 return (FALSE);
172 #ifdef DEBUG
173 g_message ("%s: Process %d finished", __func__, ret);
174 #endif
176 process->waited = TRUE;
178 *(int *)user_data = status;
180 return (TRUE);
183 void _wapi_process_reap (void)
185 gpointer proc;
186 int status;
188 #ifdef DEBUG
189 g_message ("%s: Reaping child processes", __func__);
190 #endif
192 do {
193 proc = _wapi_search_handle (WAPI_HANDLE_PROCESS, waitfor_pid,
194 &status, NULL, FALSE);
195 if (proc != NULL) {
196 #ifdef DEBUG
197 g_message ("%s: process handle %p exit code %d",
198 __func__, proc, status);
199 #endif
201 process_set_termination_details (proc, status);
203 /* _wapi_search_handle adds a reference, so
204 * drop it here
206 _wapi_handle_unref (proc);
208 } while (proc != NULL);
211 /* Limitations: This can only wait for processes that are our own
212 * children. Fixing this means resurrecting a daemon helper to manage
213 * processes.
215 static guint32 process_wait (gpointer handle, guint32 timeout)
217 struct _WapiHandle_process *process_handle;
218 gboolean ok;
219 pid_t pid, ret;
220 int status;
222 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
224 #ifdef DEBUG
225 g_message ("%s: Waiting for process %p", __func__, handle);
226 #endif
228 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
229 (gpointer *)&process_handle);
230 if (ok == FALSE) {
231 g_warning ("%s: error looking up process handle %p", __func__,
232 handle);
233 return(WAIT_FAILED);
236 if (process_handle->waited) {
237 /* We've already done this one */
238 #ifdef DEBUG
239 g_message ("%s: Process %p already signalled", __func__,
240 handle);
241 #endif
243 return (WAIT_OBJECT_0);
246 pid = process_handle->id;
248 #ifdef DEBUG
249 g_message ("%s: PID is %d, timeout %d", __func__, pid, timeout);
250 #endif
252 if (timeout == INFINITE) {
253 if (pid == _wapi_getpid ()) {
254 do {
255 Sleep (10000);
256 } while(1);
257 } else {
258 while ((ret = waitpid (pid, &status, 0)) != pid) {
259 if (ret == (pid_t)-1 && errno != EINTR) {
260 return(WAIT_FAILED);
264 } else if (timeout == 0) {
265 /* Just poll */
266 ret = waitpid (pid, &status, WNOHANG);
267 if (ret != pid) {
268 return (WAIT_TIMEOUT);
270 } else {
271 /* Poll in a loop */
272 if (pid == _wapi_getpid ()) {
273 Sleep (timeout);
274 return(WAIT_TIMEOUT);
275 } else {
276 do {
277 ret = waitpid (pid, &status, WNOHANG);
278 #ifdef DEBUG
279 g_message ("%s: waitpid returns: %d, timeout is %d", __func__, ret, timeout);
280 #endif
282 if (ret == pid) {
283 break;
284 } else if (ret == (pid_t)-1 &&
285 errno != EINTR) {
286 #ifdef DEBUG
287 g_message ("%s: waitpid failure: %s",
288 __func__,
289 g_strerror (errno));
290 #endif
292 if (errno == ECHILD &&
293 process_handle->waited) {
294 /* The background
295 * process reaper must
296 * have got this one
298 #ifdef DEBUG
299 g_message ("%s: Process %p already reaped", __func__, handle);
300 #endif
302 return(WAIT_OBJECT_0);
303 } else {
304 return(WAIT_FAILED);
308 _wapi_handle_spin (100);
309 timeout -= 100;
310 } while (timeout > 0);
313 if (timeout <= 0) {
314 return(WAIT_TIMEOUT);
318 /* Process must have exited */
319 #ifdef DEBUG
320 g_message ("%s: Wait done, status %d", __func__, status);
321 #endif
323 ok = process_set_termination_details (handle, status);
324 if (ok == FALSE) {
325 SetLastError (ERROR_OUTOFMEMORY);
326 return (WAIT_FAILED);
328 process_handle->waited = TRUE;
330 return(WAIT_OBJECT_0);
333 void _wapi_process_signal_self ()
335 if (current_process != NULL) {
336 process_set_termination_details (current_process, 0);
340 static void process_set_defaults (struct _WapiHandle_process *process_handle)
342 /* These seem to be the defaults on w2k */
343 process_handle->min_working_set = 204800;
344 process_handle->max_working_set = 1413120;
346 process_handle->waited = FALSE;
348 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
351 static int
352 len16 (const gunichar2 *str)
354 int len = 0;
356 while (*str++ != 0)
357 len++;
359 return len;
362 static gunichar2 *
363 utf16_concat (const gunichar2 *first, ...)
365 va_list args;
366 int total = 0, i;
367 const gunichar2 *s;
368 gunichar2 *ret;
370 va_start (args, first);
371 total += len16 (first);
372 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
373 total += len16 (s);
375 va_end (args);
377 ret = g_new (gunichar2, total + 1);
378 if (ret == NULL)
379 return NULL;
381 ret [total] = 0;
382 i = 0;
383 for (s = first; *s != 0; s++)
384 ret [i++] = *s;
385 va_start (args, first);
386 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
387 const gunichar2 *p;
389 for (p = s; *p != 0; p++)
390 ret [i++] = *p;
392 va_end (args);
394 return ret;
397 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
398 static const gunichar2 *utf16_space = utf16_space_bytes;
399 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
400 static const gunichar2 *utf16_quote = utf16_quote_bytes;
402 /* Implemented as just a wrapper around CreateProcess () */
403 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
405 gboolean ret;
406 WapiProcessInformation process_info;
407 gunichar2 *args;
409 if (sei == NULL) {
410 /* w2k just segfaults here, but we can do better than
411 * that
413 SetLastError (ERROR_INVALID_PARAMETER);
414 return (FALSE);
417 if (sei->lpFile == NULL) {
418 /* w2k returns TRUE for this, for some reason. */
419 return (TRUE);
422 /* Put both executable and parameters into the second argument
423 * to CreateProcess (), so it searches $PATH. The conversion
424 * into and back out of utf8 is because there is no
425 * g_strdup_printf () equivalent for gunichar2 :-(
427 args = utf16_concat (sei->lpFile, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
428 if (args == NULL){
429 SetLastError (ERROR_INVALID_DATA);
430 return (FALSE);
432 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
433 CREATE_UNICODE_ENVIRONMENT, NULL,
434 sei->lpDirectory, NULL, &process_info);
435 g_free (args);
437 if (!ret) {
438 static char *handler;
439 static gunichar2 *handler_utf16;
441 if (handler_utf16 == (gunichar2 *)-1)
442 return FALSE;
444 #ifdef PLATFORM_MACOSX
445 handler = g_strdup ("/usr/bin/open -W");
446 #else
448 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
449 * if that fails, try to use gnome-open, then kfmclient
451 handler = g_find_program_in_path ("xdg-open");
452 if (handler == NULL){
453 handler = g_find_program_in_path ("gnome-open");
454 if (handler == NULL){
455 handler = g_find_program_in_path ("kfmclient");
456 if (handler == NULL){
457 handler_utf16 = (gunichar2 *) -1;
458 return (FALSE);
459 } else {
460 /* kfmclient needs exec argument */
461 char *old = handler;
462 handler = g_strconcat (old, " exec",
463 NULL);
464 g_free (old);
468 #endif
469 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
470 g_free (handler);
472 /* Put quotes around the filename, in case it's a url
473 * that contains #'s (CreateProcess() calls
474 * g_shell_parse_argv(), which deliberately throws
475 * away anything after an unquoted #). Fixes bug
476 * 371567.
478 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
479 sei->lpFile, utf16_quote,
480 sei->lpParameters == NULL ? NULL : utf16_space,
481 sei->lpParameters, NULL);
482 if (args == NULL){
483 SetLastError (ERROR_INVALID_DATA);
484 return FALSE;
486 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
487 CREATE_UNICODE_ENVIRONMENT, NULL,
488 sei->lpDirectory, NULL, &process_info);
489 g_free (args);
490 if (!ret){
491 SetLastError (ERROR_INVALID_DATA);
492 return FALSE;
496 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
497 sei->hProcess = process_info.hProcess;
498 } else {
499 CloseHandle (process_info.hProcess);
502 return (ret);
505 static gboolean
506 is_managed_binary (const gchar *filename)
508 int original_errno = errno;
509 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
510 int file = open (filename, O_RDONLY | O_LARGEFILE);
511 #else
512 int file = open (filename, O_RDONLY);
513 #endif
514 off_t new_offset;
515 unsigned char buffer[8];
516 off_t file_size, optional_header_offset;
517 off_t pe_header_offset;
518 gboolean managed = FALSE;
519 int num_read;
520 guint32 first_word, second_word;
522 /* If we are unable to open the file, then we definitely
523 * can't say that it is managed. The child mono process
524 * probably wouldn't be able to open it anyway.
526 if (file < 0) {
527 errno = original_errno;
528 return FALSE;
531 /* Retrieve the length of the file for future sanity checks. */
532 file_size = lseek (file, 0, SEEK_END);
533 lseek (file, 0, SEEK_SET);
535 /* We know we need to read a header field at offset 60. */
536 if (file_size < 64)
537 goto leave;
539 num_read = read (file, buffer, 2);
541 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
542 goto leave;
544 new_offset = lseek (file, 60, SEEK_SET);
546 if (new_offset != 60)
547 goto leave;
549 num_read = read (file, buffer, 4);
551 if (num_read != 4)
552 goto leave;
553 pe_header_offset = buffer[0]
554 | (buffer[1] << 8)
555 | (buffer[2] << 16)
556 | (buffer[3] << 24);
558 if (pe_header_offset + 24 > file_size)
559 goto leave;
561 new_offset = lseek (file, pe_header_offset, SEEK_SET);
563 if (new_offset != pe_header_offset)
564 goto leave;
566 num_read = read (file, buffer, 4);
568 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
569 goto leave;
572 * Verify that the header we want in the optional header data
573 * is present in this binary.
575 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
577 if (new_offset != pe_header_offset + 20)
578 goto leave;
580 num_read = read (file, buffer, 2);
582 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
583 goto leave;
585 /* Read the CLR header address and size fields. These will be
586 * zero if the binary is not managed.
588 optional_header_offset = pe_header_offset + 24;
589 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
591 if (new_offset != optional_header_offset + 208)
592 goto leave;
594 num_read = read (file, buffer, 8);
596 /* We are not concerned with endianness, only with
597 * whether it is zero or not.
599 first_word = *(guint32 *)&buffer[0];
600 second_word = *(guint32 *)&buffer[4];
602 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
603 goto leave;
605 managed = TRUE;
607 leave:
608 close (file);
609 errno = original_errno;
610 return managed;
613 gboolean CreateProcessWithLogonW (const gunichar2 *username,
614 const gunichar2 *domain,
615 const gunichar2 *password,
616 const guint32 logonFlags,
617 const gunichar2 *appname,
618 const gunichar2 *cmdline,
619 guint32 create_flags,
620 gpointer env,
621 const gunichar2 *cwd,
622 WapiStartupInfo *startup,
623 WapiProcessInformation *process_info)
625 /* FIXME: use user information */
626 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
629 static gboolean
630 is_executable (const char *prog)
632 struct stat buf;
633 if (access (prog, X_OK) != 0)
634 return FALSE;
635 if (stat (prog, &buf))
636 return FALSE;
637 if (S_ISREG (buf.st_mode))
638 return TRUE;
639 return FALSE;
642 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
643 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
644 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
645 gboolean inherit_handles, guint32 create_flags,
646 gpointer new_environ, const gunichar2 *cwd,
647 WapiStartupInfo *startup,
648 WapiProcessInformation *process_info)
650 gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
651 guint32 i, env_count = 0;
652 gboolean ret = FALSE;
653 gpointer handle;
654 struct _WapiHandle_process process_handle = {0}, *process_handle_data;
655 GError *gerr = NULL;
656 int in_fd, out_fd, err_fd;
657 pid_t pid;
658 int thr_ret;
660 mono_once (&process_ops_once, process_ops_init);
662 /* appname and cmdline specify the executable and its args:
664 * If appname is not NULL, it is the name of the executable.
665 * Otherwise the executable is the first token in cmdline.
667 * Executable searching:
669 * If appname is not NULL, it can specify the full path and
670 * file name, or else a partial name and the current directory
671 * will be used. There is no additional searching.
673 * If appname is NULL, the first whitespace-delimited token in
674 * cmdline is used. If the name does not contain a full
675 * directory path, the search sequence is:
677 * 1) The directory containing the current process
678 * 2) The current working directory
679 * 3) The windows system directory (Ignored)
680 * 4) The windows directory (Ignored)
681 * 5) $PATH
683 * Just to make things more interesting, tokens can contain
684 * white space if they are surrounded by quotation marks. I'm
685 * beginning to understand just why windows apps are generally
686 * so crap, with an API like this :-(
688 if (appname != NULL) {
689 cmd = mono_unicode_to_external (appname);
690 if (cmd == NULL) {
691 #ifdef DEBUG
692 g_message ("%s: unicode conversion returned NULL",
693 __func__);
694 #endif
696 SetLastError (ERROR_PATH_NOT_FOUND);
697 goto free_strings;
700 /* Turn all the slashes round the right way */
701 for (i = 0; i < strlen (cmd); i++) {
702 if (cmd[i] == '\\') {
703 cmd[i] = '/';
708 if (cmdline != NULL) {
709 args = mono_unicode_to_external (cmdline);
710 if (args == NULL) {
711 #ifdef DEBUG
712 g_message ("%s: unicode conversion returned NULL", __func__);
713 #endif
715 SetLastError (ERROR_PATH_NOT_FOUND);
716 goto free_strings;
720 if (cwd != NULL) {
721 dir = mono_unicode_to_external (cwd);
722 if (dir == NULL) {
723 #ifdef DEBUG
724 g_message ("%s: unicode conversion returned NULL", __func__);
725 #endif
727 SetLastError (ERROR_PATH_NOT_FOUND);
728 goto free_strings;
731 /* Turn all the slashes round the right way */
732 for (i = 0; i < strlen (dir); i++) {
733 if (dir[i] == '\\') {
734 dir[i] = '/';
740 /* We can't put off locating the executable any longer :-( */
741 if (cmd != NULL) {
742 gchar *unquoted;
743 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
744 /* Strip off the drive letter. I can't
745 * believe that CP/M holdover is still
746 * visible...
748 g_memmove (cmd, cmd+2, strlen (cmd)-2);
749 cmd[strlen (cmd)-2] = '\0';
752 unquoted = g_shell_unquote (cmd, NULL);
753 if (unquoted[0] == '/') {
754 /* Assume full path given */
755 prog = g_strdup (unquoted);
757 /* Executable existing ? */
758 if (!is_executable (prog)) {
759 #ifdef DEBUG
760 g_message ("%s: Couldn't find executable %s",
761 __func__, prog);
762 #endif
763 g_free (unquoted);
764 SetLastError (ERROR_FILE_NOT_FOUND);
765 goto free_strings;
767 } else {
768 /* Search for file named by cmd in the current
769 * directory
771 char *curdir = g_get_current_dir ();
773 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
774 g_free (curdir);
776 /* And make sure it's executable */
777 if (!is_executable (prog)) {
778 #ifdef DEBUG
779 g_message ("%s: Couldn't find executable %s",
780 __func__, prog);
781 #endif
782 g_free (unquoted);
783 SetLastError (ERROR_FILE_NOT_FOUND);
784 goto free_strings;
787 g_free (unquoted);
789 args_after_prog = args;
790 } else {
791 gchar *token = NULL;
792 char quote;
794 /* Dig out the first token from args, taking quotation
795 * marks into account
798 /* First, strip off all leading whitespace */
799 args = g_strchug (args);
801 /* args_after_prog points to the contents of args
802 * after token has been set (otherwise argv[0] is
803 * duplicated)
805 args_after_prog = args;
807 /* Assume the opening quote will always be the first
808 * character
810 if (args[0] == '\"' || args [0] == '\'') {
811 quote = args [0];
812 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
813 if (g_ascii_isspace (args[i+1])) {
814 /* We found the first token */
815 token = g_strndup (args+1, i-1);
816 args_after_prog = args + i;
817 } else {
818 /* Quotation mark appeared in the
819 * middle of the token. Just give the
820 * whole first token, quotes and all,
821 * to exec.
826 if (token == NULL) {
827 /* No quote mark, or malformed */
828 for (i = 0; args[i] != '\0'; i++) {
829 if (g_ascii_isspace (args[i])) {
830 token = g_strndup (args, i);
831 args_after_prog = args + i + 1;
832 break;
837 if (token == NULL && args[0] != '\0') {
838 /* Must be just one token in the string */
839 token = g_strdup (args);
840 args_after_prog = NULL;
843 if (token == NULL) {
844 /* Give up */
845 #ifdef DEBUG
846 g_message ("%s: Couldn't find what to exec", __func__);
847 #endif
849 SetLastError (ERROR_PATH_NOT_FOUND);
850 goto free_strings;
853 /* Turn all the slashes round the right way. Only for
854 * the prg. name
856 for (i = 0; i < strlen (token); i++) {
857 if (token[i] == '\\') {
858 token[i] = '/';
862 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
863 /* Strip off the drive letter. I can't
864 * believe that CP/M holdover is still
865 * visible...
867 g_memmove (token, token+2, strlen (token)-2);
868 token[strlen (token)-2] = '\0';
871 if (token[0] == '/') {
872 /* Assume full path given */
873 prog = g_strdup (token);
875 /* Executable existing ? */
876 if (!is_executable (prog)) {
877 #ifdef DEBUG
878 g_message ("%s: Couldn't find executable %s",
879 __func__, token);
880 #endif
881 g_free (token);
882 SetLastError (ERROR_FILE_NOT_FOUND);
883 goto free_strings;
886 } else {
887 char *curdir = g_get_current_dir ();
889 /* FIXME: Need to record the directory
890 * containing the current process, and check
891 * that for the new executable as the first
892 * place to look
895 prog = g_strdup_printf ("%s/%s", curdir, token);
896 g_free (curdir);
898 /* I assume X_OK is the criterion to use,
899 * rather than F_OK
901 if (!is_executable (prog)) {
902 g_free (prog);
903 prog = g_find_program_in_path (token);
904 if (prog == NULL) {
905 #ifdef DEBUG
906 g_message ("%s: Couldn't find executable %s", __func__, token);
907 #endif
909 g_free (token);
910 SetLastError (ERROR_FILE_NOT_FOUND);
911 goto free_strings;
916 g_free (token);
919 #ifdef DEBUG
920 g_message ("%s: Exec prog [%s] args [%s]", __func__, prog,
921 args_after_prog);
922 #endif
924 /* Check for CLR binaries; if found, we will try to invoke
925 * them using the same mono binary that started us.
927 if (is_managed_binary (prog)) {
928 gunichar2 *newapp, *newcmd;
929 gsize bytes_ignored;
931 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
933 if (newapp != NULL) {
934 if (appname != NULL) {
935 newcmd = utf16_concat (newapp, utf16_space,
936 appname, utf16_space,
937 cmdline, NULL);
938 } else {
939 newcmd = utf16_concat (newapp, utf16_space,
940 cmdline, NULL);
943 g_free ((gunichar2 *)newapp);
945 if (newcmd != NULL) {
946 ret = CreateProcess (NULL, newcmd,
947 process_attrs,
948 thread_attrs,
949 inherit_handles,
950 create_flags, new_environ,
951 cwd, startup,
952 process_info);
954 g_free ((gunichar2 *)newcmd);
956 goto free_strings;
961 if (args_after_prog != NULL && *args_after_prog) {
962 gchar *qprog;
964 qprog = g_shell_quote (prog);
965 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
966 g_free (qprog);
967 } else {
968 full_prog = g_shell_quote (prog);
971 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
972 if (ret == FALSE) {
973 /* FIXME: Could do something with the GError here
977 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
978 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
979 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
980 err_fd = GPOINTER_TO_UINT (startup->hStdError);
981 } else {
982 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
983 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
984 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
987 g_strlcpy (process_handle.proc_name, prog,
988 _WAPI_PROC_NAME_MAX_LEN - 1);
990 process_set_defaults (&process_handle);
992 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
993 if (handle == _WAPI_HANDLE_INVALID) {
994 g_warning ("%s: error creating process handle", __func__);
996 SetLastError (ERROR_PATH_NOT_FOUND);
997 goto free_strings;
1000 /* Hold another reference so the process has somewhere to
1001 * store its exit data even if we drop this handle
1003 _wapi_handle_ref (handle);
1005 /* new_environ is a block of NULL-terminated strings, which
1006 * is itself NULL-terminated. Of course, passing an array of
1007 * string pointers would have made things too easy :-(
1009 * If new_environ is not NULL it specifies the entire set of
1010 * environment variables in the new process. Otherwise the
1011 * new process inherits the same environment.
1013 if (new_environ != NULL) {
1014 gunichar2 *new_environp;
1016 /* Count the number of strings */
1017 for (new_environp = (gunichar2 *)new_environ; *new_environp;
1018 new_environp++) {
1019 env_count++;
1020 while (*new_environp) {
1021 new_environp++;
1025 /* +2: one for the process handle value, and the last
1026 * one is NULL
1028 env_strings = g_new0 (gchar *, env_count + 2);
1030 /* Copy each environ string into 'strings' turning it
1031 * into utf8 (or the requested encoding) at the same
1032 * time
1034 env_count = 0;
1035 for (new_environp = (gunichar2 *)new_environ; *new_environp;
1036 new_environp++) {
1037 env_strings[env_count] = mono_unicode_to_external (new_environp);
1038 env_count++;
1039 while (*new_environp) {
1040 new_environp++;
1043 } else {
1044 for (i = 0; environ[i] != NULL; i++) {
1045 env_count++;
1048 /* +2: one for the process handle value, and the last
1049 * one is NULL
1051 env_strings = g_new0 (gchar *, env_count + 2);
1053 /* Copy each environ string into 'strings' turning it
1054 * into utf8 (or the requested encoding) at the same
1055 * time
1057 env_count = 0;
1058 for (i = 0; environ[i] != NULL; i++) {
1059 env_strings[env_count] = g_strdup (environ[i]);
1060 env_count++;
1063 /* pass process handle info to the child, so it doesn't have
1064 * to do an expensive search over the whole list
1066 if (env_strings != NULL) {
1067 struct _WapiHandleUnshared *handle_data;
1068 struct _WapiHandle_shared_ref *ref;
1070 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
1071 ref = &handle_data->u.shared;
1073 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
1076 thr_ret = _wapi_handle_lock_shared_handles ();
1077 g_assert (thr_ret == 0);
1079 pid = fork ();
1080 if (pid == -1) {
1081 /* Error */
1082 SetLastError (ERROR_OUTOFMEMORY);
1083 _wapi_handle_unref (handle);
1084 goto cleanup;
1085 } else if (pid == 0) {
1086 /* Child */
1088 if (_wapi_shm_disabled == FALSE) {
1089 /* Wait for the parent to finish setting up
1090 * the handle. The semaphore lock is safe
1091 * because the sem_undo structures of a
1092 * semaphore aren't inherited across a fork
1093 * (), but we can't do this if we're not using
1094 * the shared memory
1096 thr_ret = _wapi_handle_lock_shared_handles ();
1097 g_assert (thr_ret == 0);
1099 _wapi_handle_unlock_shared_handles ();
1102 /* should we detach from the process group? */
1104 /* Connect stdin, stdout and stderr */
1105 dup2 (in_fd, 0);
1106 dup2 (out_fd, 1);
1107 dup2 (err_fd, 2);
1109 if (inherit_handles != TRUE) {
1110 /* FIXME: do something here */
1113 /* Close all file descriptors */
1114 for (i = getdtablesize () - 1; i > 2; i--) {
1115 close (i);
1118 #ifdef DEBUG
1119 g_message ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1120 dir==NULL?".":dir);
1121 for (i = 0; argv[i] != NULL; i++) {
1122 g_message ("arg %d: [%s]", i, argv[i]);
1125 for (i = 0; env_strings[i] != NULL; i++) {
1126 g_message ("env %d: [%s]", i, env_strings[i]);
1128 #endif
1130 /* set cwd */
1131 if (dir != NULL && chdir (dir) == -1) {
1132 /* set error */
1133 _exit (-1);
1136 /* exec */
1137 execve (argv[0], argv, env_strings);
1139 /* set error */
1140 _exit (-1);
1142 /* parent */
1144 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1145 (gpointer *)&process_handle_data);
1146 if (ret == FALSE) {
1147 g_warning ("%s: error looking up process handle %p", __func__,
1148 handle);
1149 _wapi_handle_unref (handle);
1150 goto cleanup;
1153 process_handle_data->id = pid;
1155 if (process_info != NULL) {
1156 process_info->hProcess = handle;
1157 process_info->dwProcessId = pid;
1159 /* FIXME: we might need to handle the thread info some
1160 * day
1162 process_info->hThread = INVALID_HANDLE_VALUE;
1163 process_info->dwThreadId = 0;
1166 cleanup:
1167 _wapi_handle_unlock_shared_handles ();
1169 free_strings:
1170 if (cmd != NULL) {
1171 g_free (cmd);
1173 if (full_prog != NULL) {
1174 g_free (full_prog);
1176 if (prog != NULL) {
1177 g_free (prog);
1179 if (args != NULL) {
1180 g_free (args);
1182 if (dir != NULL) {
1183 g_free (dir);
1185 if(env_strings != NULL) {
1186 g_strfreev (env_strings);
1188 if (argv != NULL) {
1189 g_strfreev (argv);
1192 #ifdef DEBUG
1193 g_message ("%s: returning handle %p for pid %d", __func__, handle,
1194 pid);
1195 #endif
1197 return(ret);
1200 static void process_set_name (struct _WapiHandle_process *process_handle)
1202 gchar *progname, *utf8_progname, *slash;
1204 progname=g_get_prgname ();
1205 utf8_progname=mono_utf8_from_external (progname);
1207 #ifdef DEBUG
1208 g_message ("%s: using [%s] as prog name", __func__, progname);
1209 #endif
1211 if(utf8_progname!=NULL) {
1212 slash=strrchr (utf8_progname, '/');
1213 if(slash!=NULL) {
1214 g_strlcpy (process_handle->proc_name, slash+1,
1215 _WAPI_PROC_NAME_MAX_LEN - 1);
1216 } else {
1217 g_strlcpy (process_handle->proc_name, utf8_progname,
1218 _WAPI_PROC_NAME_MAX_LEN - 1);
1221 g_free (utf8_progname);
1225 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
1227 #if !GLIB_CHECK_VERSION (2,4,0)
1228 #define g_setenv(a,b,c) setenv(a,b,c)
1229 #define g_unsetenv(a) unsetenv(a)
1230 #endif
1232 static void process_set_current (void)
1234 pid_t pid = _wapi_getpid ();
1235 const char *handle_env;
1236 struct _WapiHandle_process process_handle = {0};
1238 mono_once (&process_ops_once, process_ops_init);
1240 handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1241 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1243 if (handle_env != NULL) {
1244 struct _WapiHandle_process *process_handlep;
1245 gchar *procname = NULL;
1246 gboolean ok;
1248 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
1250 #ifdef DEBUG
1251 g_message ("%s: Found my process handle: %p (offset %d 0x%x)",
1252 __func__, current_process, atoi (handle_env),
1253 atoi (handle_env));
1254 #endif
1256 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
1257 (gpointer *)&process_handlep);
1258 if (ok) {
1259 /* This test will probably break on linuxthreads, but
1260 * that should be ancient history on all distros we
1261 * care about by now
1263 if (process_handlep->id == pid) {
1264 procname = process_handlep->proc_name;
1265 if (!strcmp (procname, "mono")) {
1266 /* Set a better process name */
1267 #ifdef DEBUG
1268 g_message ("%s: Setting better process name", __func__);
1269 #endif
1271 process_set_name (process_handlep);
1272 } else {
1273 #ifdef DEBUG
1274 g_message ("%s: Leaving process name: %s", __func__, procname);
1275 #endif
1278 return;
1281 /* Wrong pid, so drop this handle and fall through to
1282 * create a new one
1284 _wapi_handle_unref (current_process);
1288 /* We get here if the handle wasn't specified in the
1289 * environment, or if the process ID was wrong, or if the
1290 * handle lookup failed (eg if the parent process forked and
1291 * quit immediately, and deleted the shared data before the
1292 * child got a chance to attach it.)
1295 #ifdef DEBUG
1296 g_message ("%s: Need to create my own process handle", __func__);
1297 #endif
1299 process_handle.id = pid;
1301 process_set_defaults (&process_handle);
1302 process_set_name (&process_handle);
1304 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1305 &process_handle);
1306 if (current_process == _WAPI_HANDLE_INVALID) {
1307 g_warning ("%s: error creating process handle", __func__);
1308 return;
1312 gpointer _wapi_process_duplicate ()
1314 mono_once (&process_current_once, process_set_current);
1316 _wapi_handle_ref (current_process);
1318 return(current_process);
1321 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1322 gpointer GetCurrentProcess (void)
1324 mono_once (&process_current_once, process_set_current);
1326 return(_WAPI_PROCESS_CURRENT);
1329 guint32 GetProcessId (gpointer handle)
1331 struct _WapiHandle_process *process_handle;
1332 gboolean ok;
1334 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1335 /* This is a pseudo handle */
1336 return(GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
1339 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1340 (gpointer *)&process_handle);
1341 if (ok == FALSE) {
1342 SetLastError (ERROR_INVALID_HANDLE);
1343 return (0);
1346 return (process_handle->id);
1349 guint32 GetCurrentProcessId (void)
1351 mono_once (&process_current_once, process_set_current);
1353 return (GetProcessId (current_process));
1356 /* Returns the process id as a convenience to the functions that call this */
1357 static pid_t signal_process_if_gone (gpointer handle)
1359 struct _WapiHandle_process *process_handle;
1360 gboolean ok;
1362 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
1364 /* Make sure the process is signalled if it has exited - if
1365 * the parent process didn't wait for it then it won't be
1367 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1368 (gpointer *)&process_handle);
1369 if (ok == FALSE) {
1370 /* It's possible that the handle has vanished during
1371 * the _wapi_search_handle before it gets here, so
1372 * don't spam the console with warnings.
1374 /* g_warning ("%s: error looking up process handle %p",
1375 __func__, handle);*/
1377 return (0);
1380 #ifdef DEBUG
1381 g_message ("%s: looking at process %d", __func__, process_handle->id);
1382 #endif
1384 if (kill (process_handle->id, 0) == -1 &&
1385 (errno == ESRCH ||
1386 errno == EPERM)) {
1387 /* The process is dead, (EPERM tells us a new process
1388 * has that ID, but as it's owned by someone else it
1389 * can't be the one listed in our shared memory file)
1391 _wapi_shared_handle_set_signal_state (handle, TRUE);
1394 return (process_handle->id);
1397 #ifdef UNUSED_CODE
1398 static gboolean process_enum (gpointer handle, gpointer user_data)
1400 GArray *processes=user_data;
1401 pid_t pid = signal_process_if_gone (handle);
1402 int i;
1404 if (pid == 0) {
1405 return (FALSE);
1408 /* Ignore processes that have already exited (ie they are signalled) */
1409 if (_wapi_handle_issignalled (handle) == FALSE) {
1410 #ifdef DEBUG
1411 g_message ("%s: process %d added to array", __func__, pid);
1412 #endif
1414 /* This ensures that duplicates aren't returned (see
1415 * the comment above _wapi_search_handle () for why
1416 * it's needed
1418 for (i = 0; i < processes->len; i++) {
1419 if (g_array_index (processes, pid_t, i) == pid) {
1420 /* We've already got this one, return
1421 * FALSE to keep searching
1423 return (FALSE);
1427 g_array_append_val (processes, pid);
1430 /* Return false to keep searching */
1431 return(FALSE);
1433 #endif /* UNUSED_CODE */
1435 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1437 GArray *processes = g_array_new (FALSE, FALSE, sizeof(pid_t));
1438 guint32 fit, i, j;
1439 DIR *dir;
1440 struct dirent *entry;
1442 mono_once (&process_current_once, process_set_current);
1444 dir = opendir ("/proc");
1445 if (dir == NULL) {
1446 return(FALSE);
1448 while((entry = readdir (dir)) != NULL) {
1449 if (isdigit (entry->d_name[0])) {
1450 char *endptr;
1451 pid_t pid = (pid_t)strtol (entry->d_name, &endptr, 10);
1453 if (*endptr == '\0') {
1454 /* Name was entirely numeric, so was a
1455 * process ID
1457 g_array_append_val (processes, pid);
1461 closedir (dir);
1463 fit=len/sizeof(guint32);
1464 for (i = 0, j = 0; j < fit && i < processes->len; i++) {
1465 pids[j++] = g_array_index (processes, pid_t, i);
1468 g_array_free (processes, TRUE);
1470 *needed = j * sizeof(guint32);
1472 return(TRUE);
1475 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1477 pid_t wanted_pid;
1478 pid_t checking_pid = signal_process_if_gone (handle);
1480 if (checking_pid == 0) {
1481 return(FALSE);
1484 wanted_pid = GPOINTER_TO_UINT (user_data);
1486 /* It's possible to have more than one process handle with the
1487 * same pid, but only the one running process can be
1488 * unsignalled
1490 if (checking_pid == wanted_pid &&
1491 _wapi_handle_issignalled (handle) == FALSE) {
1492 /* If the handle is blown away in the window between
1493 * returning TRUE here and _wapi_search_handle pinging
1494 * the timestamp, the search will continue
1496 return(TRUE);
1497 } else {
1498 return(FALSE);
1502 gpointer OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1504 /* Find the process handle that corresponds to pid */
1505 gpointer handle;
1507 mono_once (&process_current_once, process_set_current);
1509 #ifdef DEBUG
1510 g_message ("%s: looking for process %d", __func__, pid);
1511 #endif
1513 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1514 process_open_compare,
1515 GUINT_TO_POINTER (pid), NULL, TRUE);
1516 if (handle == 0) {
1517 gchar *dir = g_strdup_printf ("/proc/%d", pid);
1518 if (!access (dir, F_OK)) {
1519 /* Return a pseudo handle for processes we
1520 * don't have handles for
1522 return((gpointer)(_WAPI_PROCESS_UNHANDLED + pid));
1523 } else {
1524 #ifdef DEBUG
1525 g_message ("%s: Can't find pid %d", __func__, pid);
1526 #endif
1528 SetLastError (ERROR_PROC_NOT_FOUND);
1530 return(NULL);
1534 _wapi_handle_ref (handle);
1536 return(handle);
1539 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1541 struct _WapiHandle_process *process_handle;
1542 gboolean ok;
1544 mono_once (&process_current_once, process_set_current);
1546 if(code==NULL) {
1547 return(FALSE);
1550 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1551 /* This is a pseudo handle, so we don't know what the
1552 * exit code was
1554 return(FALSE);
1557 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1558 (gpointer *)&process_handle);
1559 if(ok==FALSE) {
1560 #ifdef DEBUG
1561 g_message ("%s: Can't find process %p", __func__, process);
1562 #endif
1564 return(FALSE);
1567 /* A process handle is only signalled if the process has exited
1568 * and has been waited for */
1570 /* Make sure any process exit has been noticed, before
1571 * checking if the process is signalled. Fixes bug 325463.
1573 process_wait (process, 0);
1575 if (_wapi_handle_issignalled (process) == TRUE) {
1576 *code = process_handle->exitstatus;
1577 } else {
1578 *code = STILL_ACTIVE;
1581 return(TRUE);
1584 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1585 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1586 WapiFileTime *user_time)
1588 struct _WapiHandle_process *process_handle;
1589 gboolean ok;
1590 gboolean ku_times_set = FALSE;
1592 mono_once (&process_current_once, process_set_current);
1594 if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1595 user_time==NULL) {
1596 /* Not sure if w32 allows NULLs here or not */
1597 return(FALSE);
1600 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1601 /* This is a pseudo handle, so just fail for now
1603 return(FALSE);
1606 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1607 (gpointer *)&process_handle);
1608 if(ok==FALSE) {
1609 #ifdef DEBUG
1610 g_message ("%s: Can't find process %p", __func__, process);
1611 #endif
1613 return(FALSE);
1616 *create_time=process_handle->create_time;
1618 /* A process handle is only signalled if the process has
1619 * exited. Otherwise exit_time isn't set
1621 if(_wapi_handle_issignalled (process)==TRUE) {
1622 *exit_time=process_handle->exit_time;
1625 #ifdef HAVE_GETRUSAGE
1626 if (process_handle->id == getpid ()) {
1627 struct rusage time_data;
1628 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1629 gint64 tick_val;
1630 gint64 *tick_val_ptr;
1631 ku_times_set = TRUE;
1632 tick_val = time_data.ru_utime.tv_sec * 10000000 + time_data.ru_utime.tv_usec * 10;
1633 tick_val_ptr = (gint64*)user_time;
1634 *tick_val_ptr = tick_val;
1635 tick_val = time_data.ru_stime.tv_sec * 10000000 + time_data.ru_stime.tv_usec * 10;
1636 tick_val_ptr = (gint64*)kernel_time;
1637 *tick_val_ptr = tick_val;
1640 #endif
1641 if (!ku_times_set) {
1642 memset (kernel_time, 0, sizeof (WapiFileTime));
1643 memset (user_time, 0, sizeof (WapiFileTime));
1646 return(TRUE);
1649 typedef struct
1651 gpointer address_start;
1652 gpointer address_end;
1653 gchar *perms;
1654 gpointer address_offset;
1655 dev_t device;
1656 ino_t inode;
1657 gchar *filename;
1658 } WapiProcModule;
1660 static void free_procmodule (WapiProcModule *mod)
1662 if (mod->perms != NULL) {
1663 g_free (mod->perms);
1665 if (mod->filename != NULL) {
1666 g_free (mod->filename);
1668 g_free (mod);
1671 static gint find_procmodule (gconstpointer a, gconstpointer b)
1673 WapiProcModule *want = (WapiProcModule *)a;
1674 WapiProcModule *compare = (WapiProcModule *)b;
1676 if ((want->device == compare->device) &&
1677 (want->inode == compare->inode)) {
1678 return(0);
1679 } else {
1680 return(1);
1684 static GSList *load_modules (FILE *fp)
1686 GSList *ret = NULL;
1687 WapiProcModule *mod;
1688 gchar buf[MAXPATHLEN + 1], *p, *endp;
1689 gchar *start_start, *end_start, *prot_start, *offset_start;
1690 gchar *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1691 gpointer address_start, address_end, address_offset;
1692 guint32 maj_dev, min_dev;
1693 ino_t inode;
1694 dev_t device;
1696 while (fgets (buf, sizeof(buf), fp)) {
1697 p = buf;
1698 while (g_ascii_isspace (*p)) ++p;
1699 start_start = p;
1700 if (!g_ascii_isxdigit (*start_start)) {
1701 continue;
1703 address_start = (gpointer)strtoul (start_start, &endp, 16);
1704 p = endp;
1705 if (*p != '-') {
1706 continue;
1709 ++p;
1710 end_start = p;
1711 if (!g_ascii_isxdigit (*end_start)) {
1712 continue;
1714 address_end = (gpointer)strtoul (end_start, &endp, 16);
1715 p = endp;
1716 if (!g_ascii_isspace (*p)) {
1717 continue;
1720 while (g_ascii_isspace (*p)) ++p;
1721 prot_start = p;
1722 if (*prot_start != 'r' && *prot_start != '-') {
1723 continue;
1725 memcpy (prot_buf, prot_start, 4);
1726 prot_buf[4] = '\0';
1727 while (!g_ascii_isspace (*p)) ++p;
1729 while (g_ascii_isspace (*p)) ++p;
1730 offset_start = p;
1731 if (!g_ascii_isxdigit (*offset_start)) {
1732 continue;
1734 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1735 p = endp;
1736 if (!g_ascii_isspace (*p)) {
1737 continue;
1740 while(g_ascii_isspace (*p)) ++p;
1741 maj_dev_start = p;
1742 if (!g_ascii_isxdigit (*maj_dev_start)) {
1743 continue;
1745 maj_dev = strtoul (maj_dev_start, &endp, 16);
1746 p = endp;
1747 if (*p != ':') {
1748 continue;
1751 ++p;
1752 min_dev_start = p;
1753 if (!g_ascii_isxdigit (*min_dev_start)) {
1754 continue;
1756 min_dev = strtoul (min_dev_start, &endp, 16);
1757 p = endp;
1758 if (!g_ascii_isspace (*p)) {
1759 continue;
1762 while (g_ascii_isspace (*p)) ++p;
1763 inode_start = p;
1764 if (!g_ascii_isxdigit (*inode_start)) {
1765 continue;
1767 inode = (ino_t)strtol (inode_start, &endp, 10);
1768 p = endp;
1769 if (!g_ascii_isspace (*p)) {
1770 continue;
1773 device = makedev ((int)maj_dev, (int)min_dev);
1774 if ((device == 0) &&
1775 (inode == 0)) {
1776 continue;
1779 while(g_ascii_isspace (*p)) ++p;
1780 /* p now points to the filename */
1782 mod = g_new0 (WapiProcModule, 1);
1783 mod->address_start = address_start;
1784 mod->address_end = address_end;
1785 mod->perms = g_strdup (prot_buf);
1786 mod->address_offset = address_offset;
1787 mod->device = device;
1788 mod->inode = inode;
1789 mod->filename = g_strdup (g_strstrip (p));
1791 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1792 ret = g_slist_prepend (ret, mod);
1793 } else {
1794 free_procmodule (mod);
1798 ret = g_slist_reverse (ret);
1800 return(ret);
1803 static gboolean match_procname_to_modulename (gchar *procname, gchar *modulename)
1805 char* lastsep = NULL;
1807 if (procname == NULL || modulename == NULL)
1808 return (FALSE);
1810 if (!strcmp (procname, modulename))
1811 return (TRUE);
1813 lastsep = strrchr (modulename, '/');
1814 if (lastsep) {
1815 if (!strcmp (lastsep+1, procname))
1816 return (TRUE);
1817 return (FALSE);
1820 return (FALSE);
1823 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1824 guint32 size, guint32 *needed)
1826 struct _WapiHandle_process *process_handle;
1827 gboolean ok;
1828 gchar *filename;
1829 FILE *fp;
1830 GSList *mods = NULL;
1831 WapiProcModule *module;
1832 guint32 count, avail = size / sizeof(gpointer);
1833 int i;
1834 pid_t pid;
1835 gchar *proc_name = NULL;
1837 /* Store modules in an array of pointers (main module as
1838 * modules[0]), using the load address for each module as a
1839 * token. (Use 'NULL' as an alternative for the main module
1840 * so that the simple implementation can just return one item
1841 * for now.) Get the info from /proc/<pid>/maps on linux,
1842 * other systems will have to implement /dev/kmem reading or
1843 * whatever other horrid technique is needed.
1845 if (size < sizeof(gpointer)) {
1846 return(FALSE);
1849 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1850 /* This is a pseudo handle */
1851 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
1852 } else {
1853 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1854 (gpointer *)&process_handle);
1855 if (ok == FALSE) {
1856 #ifdef DEBUG
1857 g_message ("%s: Can't find process %p", __func__, process);
1858 #endif
1860 return(FALSE);
1862 pid = process_handle->id;
1863 proc_name = process_handle->proc_name;
1866 filename = g_strdup_printf ("/proc/%d/maps", pid);
1867 if ((fp = fopen (filename, "r")) == NULL) {
1868 /* No /proc/<pid>/maps so just return the main module
1869 * shortcut for now
1871 modules[0] = NULL;
1872 *needed = sizeof(gpointer);
1873 } else {
1874 mods = load_modules (fp);
1875 fclose (fp);
1876 count = g_slist_length (mods);
1878 /* count + 1 to leave slot 0 for the main module */
1879 *needed = sizeof(gpointer) * (count + 1);
1881 /* Use the NULL shortcut, as the first line in
1882 * /proc/<pid>/maps isn't the executable, and we need
1883 * that first in the returned list. Check the module name
1884 * to see if it ends with the proc name and substitute
1885 * the first entry with it. FIXME if this turns out to
1886 * be a problem.
1888 modules[0] = NULL;
1889 for (i = 0; i < (avail - 1) && i < count; i++) {
1890 module = (WapiProcModule *)g_slist_nth_data (mods, i);
1891 if (modules[0] != NULL)
1892 modules[i] = module->address_start;
1893 else if (match_procname_to_modulename (proc_name, module->filename))
1894 modules[0] = module->address_start;
1895 else
1896 modules[i + 1] = module->address_start;
1899 for (i = 0; i < count; i++) {
1900 free_procmodule (g_slist_nth_data (mods, i));
1902 g_slist_free (mods);
1905 g_free (filename);
1907 return(TRUE);
1910 static gchar *get_process_name_from_proc (pid_t pid)
1912 gchar *filename;
1913 gchar *ret = NULL;
1914 gchar buf[256];
1915 FILE *fp;
1917 memset (buf, '\0', sizeof(buf));
1919 filename = g_strdup_printf ("/proc/%d/exe", pid);
1920 if (readlink (filename, buf, 255) > 0) {
1921 ret = g_strdup (buf);
1923 g_free (filename);
1925 if (ret != NULL) {
1926 return(ret);
1929 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
1930 if ((fp = fopen (filename, "r")) != NULL) {
1931 if (fgets (buf, 256, fp) != NULL) {
1932 ret = g_strdup (buf);
1935 fclose (fp);
1937 g_free (filename);
1939 if (ret != NULL) {
1940 return(ret);
1943 filename = g_strdup_printf ("/proc/%d/stat", pid);
1944 if ((fp = fopen (filename, "r")) != NULL) {
1945 if (fgets (buf, 256, fp) != NULL) {
1946 gchar *start, *end;
1948 start = strchr (buf, '(');
1949 if (start != NULL) {
1950 end = strchr (start + 1, ')');
1952 if (end != NULL) {
1953 ret = g_strndup (start + 1,
1954 end - start - 1);
1959 fclose (fp);
1961 g_free (filename);
1963 if (ret != NULL) {
1964 return(ret);
1967 return(NULL);
1970 static guint32 get_module_name (gpointer process, gpointer module,
1971 gunichar2 *basename, guint32 size,
1972 gboolean base)
1974 struct _WapiHandle_process *process_handle;
1975 gboolean ok;
1976 pid_t pid;
1977 gunichar2 *procname;
1978 gchar *procname_ext = NULL;
1979 glong len;
1980 gsize bytes;
1981 gchar *filename;
1982 FILE *fp;
1983 GSList *mods = NULL;
1984 WapiProcModule *found_module;
1985 guint32 count;
1986 int i;
1987 gchar *proc_name = NULL;
1989 mono_once (&process_current_once, process_set_current);
1991 #ifdef DEBUG
1992 g_message ("%s: Getting module base name, process handle %p module %p",
1993 __func__, process, module);
1994 #endif
1996 if (basename == NULL || size == 0) {
1997 return(0);
2000 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2001 /* This is a pseudo handle */
2002 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2003 proc_name = get_process_name_from_proc (pid);
2004 } else {
2005 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2006 (gpointer *)&process_handle);
2007 if (ok == FALSE) {
2008 #ifdef DEBUG
2009 g_message ("%s: Can't find process %p", __func__,
2010 process);
2011 #endif
2013 return(0);
2015 pid = process_handle->id;
2016 proc_name = g_strdup (process_handle->proc_name);
2019 /* Look up the address in /proc/<pid>/maps */
2020 filename = g_strdup_printf ("/proc/%d/maps", pid);
2021 if ((fp = fopen (filename, "r")) == NULL) {
2022 if (errno == EACCES && module == NULL && base == TRUE) {
2023 procname_ext = get_process_name_from_proc (pid);
2024 } else {
2025 /* No /proc/<pid>/maps, so just return failure
2026 * for now
2028 g_free (proc_name);
2029 g_free (filename);
2030 return(0);
2032 } else {
2033 mods = load_modules (fp);
2034 fclose (fp);
2035 count = g_slist_length (mods);
2037 /* If module != NULL compare the address.
2038 * If module == NULL we are looking for the main module.
2039 * The best we can do for now check it the module name end with the process name.
2041 for (i = 0; i < count; i++) {
2042 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2043 if (procname_ext == NULL &&
2044 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2045 (module != NULL && found_module->address_start == module))) {
2046 if (base) {
2047 procname_ext = g_path_get_basename (found_module->filename);
2048 } else {
2049 procname_ext = g_strdup (found_module->filename);
2053 free_procmodule (found_module);
2056 if (procname_ext == NULL)
2058 /* If it's *still* null, we might have hit the
2059 * case where reading /proc/$pid/maps gives an
2060 * empty file for this user.
2062 procname_ext = get_process_name_from_proc (pid);
2065 g_slist_free (mods);
2066 g_free (filename);
2067 g_free (proc_name);
2070 if (procname_ext != NULL) {
2071 #ifdef DEBUG
2072 g_message ("%s: Process name is [%s]", __func__,
2073 procname_ext);
2074 #endif
2076 procname = mono_unicode_from_external (procname_ext, &bytes);
2077 if (procname == NULL) {
2078 /* bugger */
2079 g_free (procname_ext);
2080 return(0);
2083 len = (bytes / 2);
2085 /* Add the terminator */
2086 bytes += 2;
2088 if (size < bytes) {
2089 #ifdef DEBUG
2090 g_message ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2091 #endif
2093 memcpy (basename, procname, size);
2094 } else {
2095 #ifdef DEBUG
2096 g_message ("%s: Size %d larger than needed (%ld)",
2097 __func__, size, bytes);
2098 #endif
2100 memcpy (basename, procname, bytes);
2103 g_free (procname);
2104 g_free (procname_ext);
2106 return(len);
2109 return(0);
2112 guint32 GetModuleBaseName (gpointer process, gpointer module,
2113 gunichar2 *basename, guint32 size)
2115 return(get_module_name (process, module, basename, size, TRUE));
2118 guint32 GetModuleFileNameEx (gpointer process, gpointer module,
2119 gunichar2 *filename, guint32 size)
2121 return(get_module_name (process, module, filename, size, FALSE));
2124 gboolean GetModuleInformation (gpointer process, gpointer module,
2125 WapiModuleInfo *modinfo, guint32 size)
2127 struct _WapiHandle_process *process_handle;
2128 gboolean ok;
2129 pid_t pid;
2130 gchar *filename;
2131 FILE *fp;
2132 GSList *mods = NULL;
2133 WapiProcModule *found_module;
2134 guint32 count;
2135 int i;
2136 gboolean ret = FALSE;
2137 gchar *proc_name = NULL;
2139 mono_once (&process_current_once, process_set_current);
2141 #ifdef DEBUG
2142 g_message ("%s: Getting module info, process handle %p module %p",
2143 __func__, process, module);
2144 #endif
2146 if (modinfo == NULL || size < sizeof(WapiModuleInfo)) {
2147 return(FALSE);
2150 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2151 /* This is a pseudo handle */
2152 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2153 proc_name = get_process_name_from_proc (pid);
2154 } else {
2155 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2156 (gpointer *)&process_handle);
2157 if (ok == FALSE) {
2158 #ifdef DEBUG
2159 g_message ("%s: Can't find process %p", __func__,
2160 process);
2161 #endif
2163 return(FALSE);
2165 pid = process_handle->id;
2166 proc_name = g_strdup (process_handle->proc_name);
2169 /* Look up the address in /proc/<pid>/maps */
2170 filename = g_strdup_printf ("/proc/%d/maps", pid);
2171 if ((fp = fopen (filename, "r")) == NULL) {
2172 /* No /proc/<pid>/maps, so just return failure
2173 * for now
2175 g_free (proc_name);
2176 g_free (filename);
2177 return(FALSE);
2178 } else {
2179 mods = load_modules (fp);
2180 fclose (fp);
2181 count = g_slist_length (mods);
2183 /* If module != NULL compare the address.
2184 * If module == NULL we are looking for the main module.
2185 * The best we can do for now check it the module name end with the process name.
2187 for (i = 0; i < count; i++) {
2188 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2189 if ( ret == FALSE &&
2190 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2191 (module != NULL && found_module->address_start == module))) {
2192 modinfo->lpBaseOfDll = found_module->address_start;
2193 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2194 modinfo->EntryPoint = found_module->address_offset;
2195 ret = TRUE;
2198 free_procmodule (found_module);
2201 g_slist_free (mods);
2202 g_free (filename);
2203 g_free (proc_name);
2206 return(ret);
2209 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2211 struct _WapiHandle_process *process_handle;
2212 gboolean ok;
2214 mono_once (&process_current_once, process_set_current);
2216 if(min==NULL || max==NULL) {
2217 /* Not sure if w32 allows NULLs here or not */
2218 return(FALSE);
2221 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2222 /* This is a pseudo handle, so just fail for now
2224 return(FALSE);
2227 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2228 (gpointer *)&process_handle);
2229 if(ok==FALSE) {
2230 #ifdef DEBUG
2231 g_message ("%s: Can't find process %p", __func__, process);
2232 #endif
2234 return(FALSE);
2237 *min=process_handle->min_working_set;
2238 *max=process_handle->max_working_set;
2240 return(TRUE);
2243 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2245 struct _WapiHandle_process *process_handle;
2246 gboolean ok;
2248 mono_once (&process_current_once, process_set_current);
2250 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2251 /* This is a pseudo handle, so just fail for now
2253 return(FALSE);
2256 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2257 (gpointer *)&process_handle);
2258 if(ok==FALSE) {
2259 #ifdef DEBUG
2260 g_message ("%s: Can't find process %p", __func__, process);
2261 #endif
2263 return(FALSE);
2266 process_handle->min_working_set=min;
2267 process_handle->max_working_set=max;
2269 return(TRUE);
2273 gboolean
2274 TerminateProcess (gpointer process, gint32 exitCode)
2276 struct _WapiHandle_process *process_handle;
2277 gboolean ok;
2278 int signo;
2279 int ret;
2280 pid_t pid;
2282 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2283 /* This is a pseudo handle */
2284 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2285 } else {
2286 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2287 (gpointer *) &process_handle);
2289 if (ok == FALSE) {
2290 #ifdef DEBUG
2291 g_message ("%s: Can't find process %p", __func__,
2292 process);
2293 #endif
2294 SetLastError (ERROR_INVALID_HANDLE);
2295 return FALSE;
2297 pid = process_handle->id;
2300 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2301 ret = kill (pid, signo);
2302 if (ret == -1) {
2303 switch (errno) {
2304 case EINVAL:
2305 SetLastError (ERROR_INVALID_PARAMETER);
2306 break;
2307 case EPERM:
2308 SetLastError (ERROR_ACCESS_DENIED);
2309 break;
2310 case ESRCH:
2311 SetLastError (ERROR_PROC_NOT_FOUND);
2312 break;
2313 default:
2314 SetLastError (ERROR_GEN_FAILURE);
2318 return (ret == 0);
2321 guint32
2322 GetPriorityClass (gpointer process)
2324 #ifdef HAVE_GETPRIORITY
2325 struct _WapiHandle_process *process_handle;
2326 gboolean ok;
2327 int ret;
2328 pid_t pid;
2330 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2331 /* This is a pseudo handle */
2332 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2333 } else {
2334 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2335 (gpointer *) &process_handle);
2337 if (!ok) {
2338 SetLastError (ERROR_INVALID_HANDLE);
2339 return FALSE;
2341 pid = process_handle->id;
2344 errno = 0;
2345 ret = getpriority (PRIO_PROCESS, pid);
2346 if (ret == -1 && errno != 0) {
2347 switch (errno) {
2348 case EPERM:
2349 case EACCES:
2350 SetLastError (ERROR_ACCESS_DENIED);
2351 break;
2352 case ESRCH:
2353 SetLastError (ERROR_PROC_NOT_FOUND);
2354 break;
2355 default:
2356 SetLastError (ERROR_GEN_FAILURE);
2358 return FALSE;
2361 if (ret == 0)
2362 return NORMAL_PRIORITY_CLASS;
2363 else if (ret < -15)
2364 return REALTIME_PRIORITY_CLASS;
2365 else if (ret < -10)
2366 return HIGH_PRIORITY_CLASS;
2367 else if (ret < 0)
2368 return ABOVE_NORMAL_PRIORITY_CLASS;
2369 else if (ret > 10)
2370 return IDLE_PRIORITY_CLASS;
2371 else if (ret > 0)
2372 return BELOW_NORMAL_PRIORITY_CLASS;
2374 return NORMAL_PRIORITY_CLASS;
2375 #else
2376 SetLastError (ERROR_NOT_SUPPORTED);
2377 return 0;
2378 #endif
2381 gboolean
2382 SetPriorityClass (gpointer process, guint32 priority_class)
2384 #ifdef HAVE_SETPRIORITY
2385 struct _WapiHandle_process *process_handle;
2386 gboolean ok;
2387 int ret;
2388 int prio;
2389 pid_t pid;
2391 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2392 /* This is a pseudo handle */
2393 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2394 } else {
2395 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2396 (gpointer *) &process_handle);
2398 if (!ok) {
2399 SetLastError (ERROR_INVALID_HANDLE);
2400 return FALSE;
2402 pid = process_handle->id;
2405 switch (priority_class) {
2406 case IDLE_PRIORITY_CLASS:
2407 prio = 19;
2408 break;
2409 case BELOW_NORMAL_PRIORITY_CLASS:
2410 prio = 10;
2411 break;
2412 case NORMAL_PRIORITY_CLASS:
2413 prio = 0;
2414 break;
2415 case ABOVE_NORMAL_PRIORITY_CLASS:
2416 prio = -5;
2417 break;
2418 case HIGH_PRIORITY_CLASS:
2419 prio = -11;
2420 break;
2421 case REALTIME_PRIORITY_CLASS:
2422 prio = -20;
2423 break;
2424 default:
2425 SetLastError (ERROR_INVALID_PARAMETER);
2426 return FALSE;
2429 ret = setpriority (PRIO_PROCESS, pid, prio);
2430 if (ret == -1) {
2431 switch (errno) {
2432 case EPERM:
2433 case EACCES:
2434 SetLastError (ERROR_ACCESS_DENIED);
2435 break;
2436 case ESRCH:
2437 SetLastError (ERROR_PROC_NOT_FOUND);
2438 break;
2439 default:
2440 SetLastError (ERROR_GEN_FAILURE);
2444 return ret == 0;
2445 #else
2446 SetLastError (ERROR_NOT_SUPPORTED);
2447 return FALSE;
2448 #endif