2007-09-02 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / io-layer / processes.c
1 /*
2  * processes.c:  Process handles
3  *
4  * Author:
5  *      Dick Porter (dick@ximian.com)
6  *
7  * (C) 2002-2006 Novell, Inc.
8  */
9
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>
21 #include <sys/time.h>
22 #include <sys/resource.h>
23 #include <fcntl.h>
24
25 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
26 #ifdef __APPLE__
27 #include <sys/resource.h>
28 #endif
29
30 #include <mono/io-layer/wapi.h>
31 #include <mono/io-layer/wapi-private.h>
32 #include <mono/io-layer/handles-private.h>
33 #include <mono/io-layer/misc-private.h>
34 #include <mono/io-layer/mono-mutex.h>
35 #include <mono/io-layer/process-private.h>
36 #include <mono/io-layer/threads.h>
37 #include <mono/utils/strenc.h>
38 #include <mono/io-layer/timefuncs-private.h>
39
40 /* The process' environment strings */
41 extern char **environ;
42
43 #undef DEBUG
44
45 static guint32 process_wait (gpointer handle, guint32 timeout);
46
47 struct _WapiHandleOps _wapi_process_ops = {
48         NULL,                           /* close_shared */
49         NULL,                           /* signal */
50         NULL,                           /* own */
51         NULL,                           /* is_owned */
52         process_wait,                   /* special_wait */
53         NULL                            /* prewait */   
54 };
55
56 static mono_once_t process_current_once=MONO_ONCE_INIT;
57 static gpointer current_process=NULL;
58
59 static mono_once_t process_ops_once=MONO_ONCE_INIT;
60
61 static void process_ops_init (void)
62 {
63         _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
64                                             WAPI_HANDLE_CAP_WAIT |
65                                             WAPI_HANDLE_CAP_SPECIAL_WAIT);
66 }
67
68 static gboolean process_set_termination_details (gpointer handle, int status)
69 {
70         struct _WapiHandle_process *process_handle;
71         gboolean ok;
72         int thr_ret;
73         
74         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
75                                   (gpointer *)&process_handle);
76         if (ok == FALSE) {
77                 g_warning ("%s: error looking up process handle %p",
78                            __func__, handle);
79                 return(FALSE);
80         }
81         
82         thr_ret = _wapi_handle_lock_shared_handles ();
83         g_assert (thr_ret == 0);
84
85         if (WIFSIGNALED(status)) {
86                 process_handle->exitstatus = 128 + WTERMSIG(status);
87         } else {
88                 process_handle->exitstatus = WEXITSTATUS(status);
89         }
90         _wapi_time_t_to_filetime (time(NULL), &process_handle->exit_time);
91
92         /* Don't set process_handle->waited here, it needs to only
93          * happen in the parent when wait() has been called.
94          */
95         
96 #ifdef DEBUG
97         g_message ("%s: Setting handle %p signalled", __func__, handle);
98 #endif
99
100         _wapi_shared_handle_set_signal_state (handle, TRUE);
101
102         _wapi_handle_unlock_shared_handles ();
103
104         /* Drop the reference we hold so we have somewhere to store
105          * the exit details, now the process has in fact exited
106          */
107         _wapi_handle_unref (handle);
108         
109         return (ok);
110 }
111
112 /* See if any child processes have terminated and wait() for them,
113  * updating process handle info.  This function is called from the
114  * collection thread every few seconds.
115  */
116 static gboolean waitfor_pid (gpointer test, gpointer user_data)
117 {
118         struct _WapiHandle_process *process;
119         gboolean ok;
120         int status;
121         pid_t ret;
122         
123         ok = _wapi_lookup_handle (test, WAPI_HANDLE_PROCESS,
124                                   (gpointer *)&process);
125         if (ok == FALSE) {
126                 /* The handle must have been too old and was reaped */
127                 return (FALSE);
128         }
129
130         if (process->waited) {
131                 /* We've already done this one */
132                 return(FALSE);
133         }
134         
135         do {
136                 ret = waitpid (process->id, &status, WNOHANG);
137         } while (errno == EINTR);
138         
139         if (ret <= 0) {
140                 /* Process not ready for wait */
141 #ifdef DEBUG
142                 g_message ("%s: Process %d not ready for waiting for: %s",
143                            __func__, process->id, g_strerror (errno));
144 #endif
145
146                 return (FALSE);
147         }
148         
149 #ifdef DEBUG
150         g_message ("%s: Process %d finished", __func__, ret);
151 #endif
152
153         process->waited = TRUE;
154         
155         *(int *)user_data = status;
156         
157         return (TRUE);
158 }
159
160 void _wapi_process_reap (void)
161 {
162         gpointer proc;
163         int status;
164         
165 #ifdef DEBUG
166         g_message ("%s: Reaping child processes", __func__);
167 #endif
168
169         do {
170                 proc = _wapi_search_handle (WAPI_HANDLE_PROCESS, waitfor_pid,
171                                             &status, NULL, FALSE);
172                 if (proc != NULL) {
173 #ifdef DEBUG
174                         g_message ("%s: process handle %p exit code %d",
175                                    __func__, proc, status);
176 #endif
177                         
178                         process_set_termination_details (proc, status);
179
180                         /* _wapi_search_handle adds a reference, so
181                          * drop it here
182                          */
183                         _wapi_handle_unref (proc);
184                 }
185         } while (proc != NULL);
186 }
187
188 /* Limitations: This can only wait for processes that are our own
189  * children.  Fixing this means resurrecting a daemon helper to manage
190  * processes.
191  */
192 static guint32 process_wait (gpointer handle, guint32 timeout)
193 {
194         struct _WapiHandle_process *process_handle;
195         gboolean ok;
196         pid_t pid, ret;
197         int status;
198         
199 #ifdef DEBUG
200         g_message ("%s: Waiting for process %p", __func__, handle);
201 #endif
202
203         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
204                                   (gpointer *)&process_handle);
205         if (ok == FALSE) {
206                 g_warning ("%s: error looking up process handle %p", __func__,
207                            handle);
208                 return(WAIT_FAILED);
209         }
210         
211         if (process_handle->waited) {
212                 /* We've already done this one */
213 #ifdef DEBUG
214                 g_message ("%s: Process %p already signalled", __func__,
215                            handle);
216 #endif
217
218                 return (WAIT_OBJECT_0);
219         }
220         
221         pid = process_handle->id;
222         
223 #ifdef DEBUG
224         g_message ("%s: PID is %d, timeout %d", __func__, pid, timeout);
225 #endif
226
227         if (timeout == INFINITE) {
228                 if (pid == _wapi_getpid ()) {
229                         do {
230                                 Sleep (10000);
231                         } while(1);
232                 } else {
233                         while ((ret = waitpid (pid, &status, 0)) != pid) {
234                                 if (ret == (pid_t)-1 && errno != EINTR) {
235                                         return(WAIT_FAILED);
236                                 }
237                         }
238                 }
239         } else if (timeout == 0) {
240                 /* Just poll */
241                 ret = waitpid (pid, &status, WNOHANG);
242                 if (ret != pid) {
243                         return (WAIT_TIMEOUT);
244                 }
245         } else {
246                 /* Poll in a loop */
247                 if (pid == _wapi_getpid ()) {
248                         Sleep (timeout);
249                         return(WAIT_TIMEOUT);
250                 } else {
251                         do {
252                                 ret = waitpid (pid, &status, WNOHANG);
253 #ifdef DEBUG
254                                 g_message ("%s: waitpid returns: %d, timeout is %d", __func__, ret, timeout);
255 #endif
256                                 
257                                 if (ret == pid) {
258                                         break;
259                                 } else if (ret == (pid_t)-1 &&
260                                            errno != EINTR) {
261 #ifdef DEBUG
262                                         g_message ("%s: waitpid failure: %s",
263                                                    __func__,
264                                                    g_strerror (errno));
265 #endif
266
267                                         if (errno == ECHILD &&
268                                             process_handle->waited) {
269                                                 /* The background
270                                                  * process reaper must
271                                                  * have got this one
272                                                  */
273 #ifdef DEBUG
274                                                 g_message ("%s: Process %p already reaped", __func__, handle);
275 #endif
276
277                                                 return(WAIT_OBJECT_0);
278                                         } else {
279                                                 return(WAIT_FAILED);
280                                         }
281                                 }
282
283                                 _wapi_handle_spin (100);
284                                 timeout -= 100;
285                         } while (timeout > 0);
286                 }
287                 
288                 if (timeout <= 0) {
289                         return(WAIT_TIMEOUT);
290                 }
291         }
292
293         /* Process must have exited */
294 #ifdef DEBUG
295         g_message ("%s: Wait done, status %d", __func__, status);
296 #endif
297
298         ok = process_set_termination_details (handle, status);
299         if (ok == FALSE) {
300                 SetLastError (ERROR_OUTOFMEMORY);
301                 return (WAIT_FAILED);
302         }
303         process_handle->waited = TRUE;
304         
305         return(WAIT_OBJECT_0);
306 }
307
308 void _wapi_process_signal_self ()
309 {
310         if (current_process != NULL) {
311                 process_set_termination_details (current_process, 0);
312         }
313 }
314         
315 static void process_set_defaults (struct _WapiHandle_process *process_handle)
316 {
317         /* These seem to be the defaults on w2k */
318         process_handle->min_working_set = 204800;
319         process_handle->max_working_set = 1413120;
320
321         process_handle->waited = FALSE;
322         
323         _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
324 }
325
326 static int
327 len16 (const gunichar2 *str)
328 {
329         int len = 0;
330         
331         while (*str++ != 0)
332                 len++;
333
334         return len;
335 }
336
337 static gunichar2 *
338 utf16_concat (const gunichar2 *first, ...)
339 {
340         va_list args;
341         int total = 0, i;
342         const gunichar2 *s;
343         gunichar2 *ret;
344
345         va_start (args, first);
346         total += len16 (first);
347         for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
348                 total += len16 (s);
349         }
350         va_end (args);
351
352         ret = g_new (gunichar2, total + 1);
353         if (ret == NULL)
354                 return NULL;
355
356         ret [total] = 0;
357         i = 0;
358         for (s = first; *s != 0; s++)
359                 ret [i++] = *s;
360         va_start (args, first);
361         for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
362                 const gunichar2 *p;
363                 
364                 for (p = s; *p != 0; p++)
365                         ret [i++] = *p;
366         }
367         va_end (args);
368         
369         return ret;
370 }
371
372 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
373 static const gunichar2 *utf16_space = utf16_space_bytes; 
374
375 /* Implemented as just a wrapper around CreateProcess () */
376 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
377 {
378         gboolean ret;
379         WapiProcessInformation process_info;
380         gunichar2 *args;
381         
382         if (sei == NULL) {
383                 /* w2k just segfaults here, but we can do better than
384                  * that
385                  */
386                 SetLastError (ERROR_INVALID_PARAMETER);
387                 return (FALSE);
388         }
389
390         if (sei->lpFile == NULL) {
391                 /* w2k returns TRUE for this, for some reason. */
392                 return (TRUE);
393         }
394         
395         /* Put both executable and parameters into the second argument
396          * to CreateProcess (), so it searches $PATH.  The conversion
397          * into and back out of utf8 is because there is no
398          * g_strdup_printf () equivalent for gunichar2 :-(
399          */
400         args = utf16_concat (sei->lpFile, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
401         if (args == NULL){
402                 SetLastError (ERROR_INVALID_DATA);
403                 return (FALSE);
404         }
405         ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
406                              CREATE_UNICODE_ENVIRONMENT, NULL,
407                              sei->lpDirectory, NULL, &process_info);
408         g_free (args);
409         
410         if (!ret) {
411                 static char *handler;
412                 static gunichar2 *handler_utf16;
413                 
414                 if (handler_utf16 == (gunichar2 *)-1)
415                         return FALSE;
416
417 #ifdef PLATFORM_MACOSX
418                 handler = "/usr/bin/open";
419 #else
420                 /*
421                  * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
422                  * if that fails, try to use gnome-open, then kfmclient
423                  */
424                 handler = g_find_program_in_path ("xdg-open");
425                 if (handler == NULL){
426                         handler = g_find_program_in_path ("gnome-open");
427                         if (handler == NULL){
428                                 handler = g_find_program_in_path ("kfmclient");
429                                 if (handler == NULL){
430                                         handler_utf16 = (gunichar2 *) -1;
431                                         return (FALSE);
432                                 } else {
433                                         /* kfmclient needs exec argument */
434                                         char *old = handler;
435                                         handler = g_strconcat (old, " exec",
436                                                                NULL);
437                                         g_free (old);
438                                 }
439                         }
440                 }
441 #endif
442                 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
443                 g_free (handler);
444                 args = utf16_concat (handler_utf16, utf16_space, sei->lpFile,
445                                      sei->lpParameters == NULL ? NULL : utf16_space,
446                                      sei->lpParameters, NULL);
447                 if (args == NULL){
448                         SetLastError (ERROR_INVALID_DATA);
449                         return FALSE;
450                 }
451                 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
452                                      CREATE_UNICODE_ENVIRONMENT, NULL,
453                                      sei->lpDirectory, NULL, &process_info);
454                 g_free (args);
455                 if (!ret){
456                         SetLastError (ERROR_INVALID_DATA);
457                         return FALSE;
458                 }
459         }
460         
461         if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
462                 sei->hProcess = process_info.hProcess;
463         } else {
464                 CloseHandle (process_info.hProcess);
465         }
466         
467         return (ret);
468 }
469
470 static gboolean
471 is_managed_binary (const gchar *filename)
472 {
473         int original_errno = errno;
474 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
475         int file = open (filename, O_RDONLY | O_LARGEFILE);
476 #else
477         int file = open (filename, O_RDONLY);
478 #endif
479         off_t new_offset;
480         unsigned char buffer[8];
481         off_t file_size, optional_header_offset;
482         off_t pe_header_offset;
483         gboolean managed = FALSE;
484         int num_read;
485         guint32 first_word, second_word;
486         
487         /* If we are unable to open the file, then we definitely
488          * can't say that it is managed. The child mono process
489          * probably wouldn't be able to open it anyway.
490          */
491         if (file < 0) {
492                 errno = original_errno;
493                 return FALSE;
494         }
495
496         /* Retrieve the length of the file for future sanity checks. */
497         file_size = lseek (file, 0, SEEK_END);
498         lseek (file, 0, SEEK_SET);
499
500         /* We know we need to read a header field at offset 60. */
501         if (file_size < 64)
502                 goto leave;
503
504         num_read = read (file, buffer, 2);
505
506         if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
507                 goto leave;
508
509         new_offset = lseek (file, 60, SEEK_SET);
510
511         if (new_offset != 60)
512                 goto leave;
513         
514         num_read = read (file, buffer, 4);
515
516         if (num_read != 4)
517                 goto leave;
518         pe_header_offset =  buffer[0]
519                 | (buffer[1] <<  8)
520                 | (buffer[2] << 16)
521                 | (buffer[3] << 24);
522         
523         if (pe_header_offset + 24 > file_size)
524                 goto leave;
525
526         new_offset = lseek (file, pe_header_offset, SEEK_SET);
527
528         if (new_offset != pe_header_offset)
529                 goto leave;
530
531         num_read = read (file, buffer, 4);
532
533         if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
534                 goto leave;
535
536         /*
537          * Verify that the header we want in the optional header data
538          * is present in this binary.
539          */
540         new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
541
542         if (new_offset != pe_header_offset + 20)
543                 goto leave;
544
545         num_read = read (file, buffer, 2);
546
547         if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
548                 goto leave;
549
550         /* Read the CLR header address and size fields. These will be
551          * zero if the binary is not managed.
552          */
553         optional_header_offset = pe_header_offset + 24;
554         new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
555
556         if (new_offset != optional_header_offset + 208)
557                 goto leave;
558
559         num_read = read (file, buffer, 8);
560         
561         /* We are not concerned with endianness, only with
562          * whether it is zero or not.
563          */
564         first_word = *(guint32 *)&buffer[0];
565         second_word = *(guint32 *)&buffer[4];
566         
567         if ((num_read != 8) || (first_word == 0) || (second_word == 0))
568                 goto leave;
569         
570         managed = TRUE;
571
572 leave:
573         close (file);
574         errno = original_errno;
575         return managed;
576 }
577
578 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
579                         WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
580                         WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
581                         gboolean inherit_handles, guint32 create_flags,
582                         gpointer new_environ, const gunichar2 *cwd,
583                         WapiStartupInfo *startup,
584                         WapiProcessInformation *process_info)
585 {
586         gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
587         guint32 i, env_count = 0;
588         gboolean ret = FALSE;
589         gpointer handle;
590         struct _WapiHandle_process process_handle = {0}, *process_handle_data;
591         GError *gerr = NULL;
592         int in_fd, out_fd, err_fd;
593         pid_t pid;
594         int thr_ret;
595         
596         mono_once (&process_ops_once, process_ops_init);
597         
598         /* appname and cmdline specify the executable and its args:
599          *
600          * If appname is not NULL, it is the name of the executable.
601          * Otherwise the executable is the first token in cmdline.
602          *
603          * Executable searching:
604          *
605          * If appname is not NULL, it can specify the full path and
606          * file name, or else a partial name and the current directory
607          * will be used.  There is no additional searching.
608          *
609          * If appname is NULL, the first whitespace-delimited token in
610          * cmdline is used.  If the name does not contain a full
611          * directory path, the search sequence is:
612          *
613          * 1) The directory containing the current process
614          * 2) The current working directory
615          * 3) The windows system directory  (Ignored)
616          * 4) The windows directory (Ignored)
617          * 5) $PATH
618          *
619          * Just to make things more interesting, tokens can contain
620          * white space if they are surrounded by quotation marks.  I'm
621          * beginning to understand just why windows apps are generally
622          * so crap, with an API like this :-(
623          */
624         if (appname != NULL) {
625                 cmd = mono_unicode_to_external (appname);
626                 if (cmd == NULL) {
627 #ifdef DEBUG
628                         g_message ("%s: unicode conversion returned NULL",
629                                    __func__);
630 #endif
631
632                         SetLastError (ERROR_PATH_NOT_FOUND);
633                         goto cleanup;
634                 }
635
636                 /* Turn all the slashes round the right way */
637                 for (i = 0; i < strlen (cmd); i++) {
638                         if (cmd[i] == '\\') {
639                                 cmd[i] = '/';
640                         }
641                 }
642         }
643         
644         if (cmdline != NULL) {
645                 args = mono_unicode_to_external (cmdline);
646                 if (args == NULL) {
647 #ifdef DEBUG
648                         g_message ("%s: unicode conversion returned NULL", __func__);
649 #endif
650
651                         SetLastError (ERROR_PATH_NOT_FOUND);
652                         goto cleanup;
653                 }
654         }
655
656         if (cwd != NULL) {
657                 dir = mono_unicode_to_external (cwd);
658                 if (dir == NULL) {
659 #ifdef DEBUG
660                         g_message ("%s: unicode conversion returned NULL", __func__);
661 #endif
662
663                         SetLastError (ERROR_PATH_NOT_FOUND);
664                         goto cleanup;
665                 }
666
667                 /* Turn all the slashes round the right way */
668                 for (i = 0; i < strlen (dir); i++) {
669                         if (dir[i] == '\\') {
670                                 dir[i] = '/';
671                         }
672                 }
673         }
674         
675
676         /* We can't put off locating the executable any longer :-( */
677         if (cmd != NULL) {
678                 gchar *unquoted;
679                 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
680                         /* Strip off the drive letter.  I can't
681                          * believe that CP/M holdover is still
682                          * visible...
683                          */
684                         g_memmove (cmd, cmd+2, strlen (cmd)-2);
685                         cmd[strlen (cmd)-2] = '\0';
686                 }
687
688                 unquoted = g_shell_unquote (cmd, NULL);
689                 if (unquoted[0] == '/') {
690                         /* Assume full path given */
691                         prog = g_strdup (unquoted);
692
693                         /* Executable existing ? */
694                         if (access (prog, X_OK) != 0) {
695 #ifdef DEBUG
696                                 g_message ("%s: Couldn't find executable %s",
697                                            __func__, prog);
698 #endif
699                                 g_free (unquoted);
700                                 SetLastError (ERROR_FILE_NOT_FOUND);
701                                 goto cleanup;
702                         }
703                 } else {
704                         /* Search for file named by cmd in the current
705                          * directory
706                          */
707                         char *curdir = g_get_current_dir ();
708
709                         prog = g_strdup_printf ("%s/%s", curdir, unquoted);
710                         g_free (curdir);
711
712                         /* And make sure it's executable */
713                         if (access (prog, X_OK) != 0) {
714 #ifdef DEBUG
715                                 g_message ("%s: Couldn't find executable %s",
716                                            __func__, prog);
717 #endif
718                                 g_free (unquoted);
719                                 SetLastError (ERROR_FILE_NOT_FOUND);
720                                 goto cleanup;
721                         }
722                 }
723                 g_free (unquoted);
724
725                 args_after_prog = args;
726         } else {
727                 gchar *token = NULL;
728                 char quote;
729                 
730                 /* Dig out the first token from args, taking quotation
731                  * marks into account
732                  */
733
734                 /* First, strip off all leading whitespace */
735                 args = g_strchug (args);
736                 
737                 /* args_after_prog points to the contents of args
738                  * after token has been set (otherwise argv[0] is
739                  * duplicated)
740                  */
741                 args_after_prog = args;
742
743                 /* Assume the opening quote will always be the first
744                  * character
745                  */
746                 if (args[0] == '\"' || args [0] == '\'') {
747                         quote = args [0];
748                         for (i = 1; args[i] != '\0' && args[i] != quote; i++);
749                         if (g_ascii_isspace (args[i+1])) {
750                                 /* We found the first token */
751                                 token = g_strndup (args+1, i-1);
752                                 args_after_prog = args + i;
753                         } else {
754                                 /* Quotation mark appeared in the
755                                  * middle of the token.  Just give the
756                                  * whole first token, quotes and all,
757                                  * to exec.
758                                  */
759                         }
760                 }
761                 
762                 if (token == NULL) {
763                         /* No quote mark, or malformed */
764                         for (i = 0; args[i] != '\0'; i++) {
765                                 if (g_ascii_isspace (args[i])) {
766                                         token = g_strndup (args, i);
767                                         args_after_prog = args + i + 1;
768                                         break;
769                                 }
770                         }
771                 }
772
773                 if (token == NULL && args[0] != '\0') {
774                         /* Must be just one token in the string */
775                         token = g_strdup (args);
776                         args_after_prog = NULL;
777                 }
778                 
779                 if (token == NULL) {
780                         /* Give up */
781 #ifdef DEBUG
782                         g_message ("%s: Couldn't find what to exec", __func__);
783 #endif
784
785                         SetLastError (ERROR_PATH_NOT_FOUND);
786                         goto cleanup;
787                 }
788                 
789                 /* Turn all the slashes round the right way. Only for
790                  * the prg. name
791                  */
792                 for (i = 0; i < strlen (token); i++) {
793                         if (token[i] == '\\') {
794                                 token[i] = '/';
795                         }
796                 }
797
798                 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
799                         /* Strip off the drive letter.  I can't
800                          * believe that CP/M holdover is still
801                          * visible...
802                          */
803                         g_memmove (token, token+2, strlen (token)-2);
804                         token[strlen (token)-2] = '\0';
805                 }
806
807                 if (token[0] == '/') {
808                         /* Assume full path given */
809                         prog = g_strdup (token);
810                         
811                         /* Executable existing ? */
812                         if (access (prog, X_OK) != 0) {
813 #ifdef DEBUG
814                                 g_message ("%s: Couldn't find executable %s",
815                                            __func__, token);
816 #endif
817                                 g_free (token);
818                                 SetLastError (ERROR_FILE_NOT_FOUND);
819                                 goto cleanup;
820                         }
821
822                 } else {
823                         char *curdir = g_get_current_dir ();
824
825                         /* FIXME: Need to record the directory
826                          * containing the current process, and check
827                          * that for the new executable as the first
828                          * place to look
829                          */
830
831                         prog = g_strdup_printf ("%s/%s", curdir, token);
832                         g_free (curdir);
833
834                         /* I assume X_OK is the criterion to use,
835                          * rather than F_OK
836                          */
837                         if (access (prog, X_OK) != 0) {
838                                 g_free (prog);
839                                 prog = g_find_program_in_path (token);
840                                 if (prog == NULL) {
841 #ifdef DEBUG
842                                         g_message ("%s: Couldn't find executable %s", __func__, token);
843 #endif
844
845                                         g_free (token);
846                                         SetLastError (ERROR_FILE_NOT_FOUND);
847                                         goto cleanup;
848                                 }
849                         }
850                 }
851
852                 g_free (token);
853         }
854
855 #ifdef DEBUG
856         g_message ("%s: Exec prog [%s] args [%s]", __func__, prog,
857                    args_after_prog);
858 #endif
859         
860         /* Check for CLR binaries; if found, we will try to invoke
861          * them using the same mono binary that started us.
862          */
863         if (is_managed_binary (prog) && (appname == NULL)) {
864                 gsize bytes_ignored;
865
866                 appname = mono_unicode_from_external ("mono", &bytes_ignored);
867
868                 if (appname != NULL) {
869                         cmdline = utf16_concat (appname, utf16_space, cmdline, NULL);
870                         
871                         g_free ((gunichar2 *)appname);
872                         
873                         if (cmdline != NULL) {
874                                 gboolean return_value = CreateProcess (
875                                         NULL, cmdline, process_attrs,
876                                         thread_attrs, inherit_handles, create_flags, new_environ,
877                                         cwd, startup, process_info);
878                                 
879                                 g_free ((gunichar2 *)cmdline);
880                                 
881                                 return return_value;
882                         }
883                 }
884         }
885
886         if (args_after_prog != NULL && *args_after_prog) {
887                 gchar *qprog;
888
889                 qprog = g_shell_quote (prog);
890                 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
891                 g_free (qprog);
892         } else {
893                 full_prog = g_shell_quote (prog);
894         }
895
896         ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
897         if (ret == FALSE) {
898                 /* FIXME: Could do something with the GError here
899                  */
900         }
901
902         if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
903                 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
904                 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
905                 err_fd = GPOINTER_TO_UINT (startup->hStdError);
906         } else {
907                 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
908                 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
909                 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
910         }
911         
912         g_strlcpy (process_handle.proc_name, prog,
913                    _WAPI_PROC_NAME_MAX_LEN - 1);
914
915         process_set_defaults (&process_handle);
916         
917         handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
918         if (handle == _WAPI_HANDLE_INVALID) {
919                 g_warning ("%s: error creating process handle", __func__);
920
921                 SetLastError (ERROR_PATH_NOT_FOUND);
922                 goto cleanup;
923         }
924
925         /* Hold another reference so the process has somewhere to
926          * store its exit data even if we drop this handle
927          */
928         _wapi_handle_ref (handle);
929         
930         /* new_environ is a block of NULL-terminated strings, which
931          * is itself NULL-terminated. Of course, passing an array of
932          * string pointers would have made things too easy :-(
933          *
934          * If new_environ is not NULL it specifies the entire set of
935          * environment variables in the new process.  Otherwise the
936          * new process inherits the same environment.
937          */
938         if (new_environ != NULL) {
939                 gunichar2 *new_environp;
940
941                 /* Count the number of strings */
942                 for (new_environp = (gunichar2 *)new_environ; *new_environp;
943                      new_environp++) {
944                         env_count++;
945                         while (*new_environp) {
946                                 new_environp++;
947                         }
948                 }
949
950                 /* +2: one for the process handle value, and the last
951                  * one is NULL
952                  */
953                 env_strings = g_new0 (gchar *, env_count + 2);
954                 
955                 /* Copy each environ string into 'strings' turning it
956                  * into utf8 (or the requested encoding) at the same
957                  * time
958                  */
959                 env_count = 0;
960                 for (new_environp = (gunichar2 *)new_environ; *new_environp;
961                      new_environp++) {
962                         env_strings[env_count] = mono_unicode_to_external (new_environp);
963                         env_count++;
964                         while (*new_environp) {
965                                 new_environp++;
966                         }
967                 }
968         } else {
969                 for (i = 0; environ[i] != NULL; i++) {
970                         env_count++;
971                 }
972
973                 /* +2: one for the process handle value, and the last
974                  * one is NULL
975                  */
976                 env_strings = g_new0 (gchar *, env_count + 2);
977                 
978                 /* Copy each environ string into 'strings' turning it
979                  * into utf8 (or the requested encoding) at the same
980                  * time
981                  */
982                 env_count = 0;
983                 for (i = 0; environ[i] != NULL; i++) {
984                         env_strings[env_count] = g_strdup (environ[i]);
985                         env_count++;
986                 }
987         }
988         /* pass process handle info to the child, so it doesn't have
989          * to do an expensive search over the whole list
990          */
991         if (env_strings != NULL) {
992                 struct _WapiHandleUnshared *handle_data;
993                 struct _WapiHandle_shared_ref *ref;
994                 
995                 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
996                 ref = &handle_data->u.shared;
997                 
998                 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
999         }
1000
1001         thr_ret = _wapi_handle_lock_shared_handles ();
1002         g_assert (thr_ret == 0);
1003         
1004         pid = fork ();
1005         if (pid == -1) {
1006                 /* Error */
1007                 SetLastError (ERROR_OUTOFMEMORY);
1008                 _wapi_handle_unref (handle);
1009                 goto cleanup;
1010         } else if (pid == 0) {
1011                 /* Child */
1012                 
1013                 if (_wapi_shm_disabled == FALSE) {
1014                         /* Wait for the parent to finish setting up
1015                          * the handle.  The semaphore lock is safe
1016                          * because the sem_undo structures of a
1017                          * semaphore aren't inherited across a fork
1018                          * (), but we can't do this if we're not using
1019                          * the shared memory
1020                          */
1021                         thr_ret = _wapi_handle_lock_shared_handles ();
1022                         g_assert (thr_ret == 0);
1023         
1024                         _wapi_handle_unlock_shared_handles ();
1025                 }
1026                 
1027                 /* should we detach from the process group? */
1028
1029                 /* Connect stdin, stdout and stderr */
1030                 dup2 (in_fd, 0);
1031                 dup2 (out_fd, 1);
1032                 dup2 (err_fd, 2);
1033
1034                 if (inherit_handles != TRUE) {
1035                         /* FIXME: do something here */
1036                 }
1037                 
1038                 /* Close all file descriptors */
1039                 for (i = getdtablesize () - 1; i > 2; i--) {
1040                         close (i);
1041                 }
1042
1043 #ifdef DEBUG
1044                 g_message ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1045                            dir==NULL?".":dir);
1046                 for (i = 0; argv[i] != NULL; i++) {
1047                         g_message ("arg %d: [%s]", i, argv[i]);
1048                 }
1049                 
1050                 for (i = 0; env_strings[i] != NULL; i++) {
1051                         g_message ("env %d: [%s]", i, env_strings[i]);
1052                 }
1053 #endif
1054
1055                 /* set cwd */
1056                 if (dir != NULL && chdir (dir) == -1) {
1057                         /* set error */
1058                         _exit (-1);
1059                 }
1060                 
1061                 /* exec */
1062                 execve (argv[0], argv, env_strings);
1063                 
1064                 /* set error */
1065                 _exit (-1);
1066         }
1067         /* parent */
1068         
1069         ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1070                                    (gpointer *)&process_handle_data);
1071         if (ret == FALSE) {
1072                 g_warning ("%s: error looking up process handle %p", __func__,
1073                            handle);
1074                 _wapi_handle_unref (handle);
1075                 goto cleanup;
1076         }
1077         
1078         process_handle_data->id = pid;
1079         
1080         if (process_info != NULL) {
1081                 process_info->hProcess = handle;
1082                 process_info->dwProcessId = pid;
1083
1084                 /* FIXME: we might need to handle the thread info some
1085                  * day
1086                  */
1087                 process_info->hThread = INVALID_HANDLE_VALUE;
1088                 process_info->dwThreadId = 0;
1089         }
1090
1091 cleanup:
1092         _wapi_handle_unlock_shared_handles ();
1093
1094         if (cmd != NULL) {
1095                 g_free (cmd);
1096         }
1097         if (full_prog != NULL) {
1098                 g_free (full_prog);
1099         }
1100         if (prog != NULL) {
1101                 g_free (prog);
1102         }
1103         if (args != NULL) {
1104                 g_free (args);
1105         }
1106         if (dir != NULL) {
1107                 g_free (dir);
1108         }
1109         if(env_strings != NULL) {
1110                 g_strfreev (env_strings);
1111         }
1112         if (argv != NULL) {
1113                 g_strfreev (argv);
1114         }
1115         
1116 #ifdef DEBUG
1117         g_message ("%s: returning handle %p for pid %d", __func__, handle,
1118                    pid);
1119 #endif
1120
1121         return(ret);
1122 }
1123                 
1124 static void process_set_name (struct _WapiHandle_process *process_handle)
1125 {
1126         gchar *progname, *utf8_progname, *slash;
1127         
1128         progname=g_get_prgname ();
1129         utf8_progname=mono_utf8_from_external (progname);
1130
1131 #ifdef DEBUG
1132         g_message ("%s: using [%s] as prog name", __func__, progname);
1133 #endif
1134
1135         if(utf8_progname!=NULL) {
1136                 slash=strrchr (utf8_progname, '/');
1137                 if(slash!=NULL) {
1138                         g_strlcpy (process_handle->proc_name, slash+1,
1139                                    _WAPI_PROC_NAME_MAX_LEN - 1);
1140                 } else {
1141                         g_strlcpy (process_handle->proc_name, utf8_progname,
1142                                    _WAPI_PROC_NAME_MAX_LEN - 1);
1143                 }
1144
1145                 g_free (utf8_progname);
1146         }
1147 }
1148
1149 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
1150
1151 #if !GLIB_CHECK_VERSION (2,4,0)
1152 #define g_setenv(a,b,c) setenv(a,b,c)
1153 #define g_unsetenv(a) unsetenv(a)
1154 #endif
1155
1156 static void process_set_current (void)
1157 {
1158         pid_t pid = _wapi_getpid ();
1159         const char *handle_env;
1160         struct _WapiHandle_process process_handle = {0};
1161         
1162         mono_once (&process_ops_once, process_ops_init);
1163         
1164         handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1165         g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1166         
1167         if (handle_env != NULL) {
1168                 struct _WapiHandle_process *process_handlep;
1169                 gchar *procname = NULL;
1170                 gboolean ok;
1171                 
1172                 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
1173                 
1174 #ifdef DEBUG
1175                 g_message ("%s: Found my process handle: %p (offset %d 0x%x)",
1176                            __func__, current_process, atoi (handle_env),
1177                            atoi (handle_env));
1178 #endif
1179
1180                 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
1181                                           (gpointer *)&process_handlep);
1182                 if (ok) {
1183                         /* This test will probably break on linuxthreads, but
1184                          * that should be ancient history on all distros we
1185                          * care about by now
1186                          */
1187                         if (process_handlep->id == pid) {
1188                                 procname = process_handlep->proc_name;
1189                                 if (!strcmp (procname, "mono")) {
1190                                         /* Set a better process name */
1191 #ifdef DEBUG
1192                                         g_message ("%s: Setting better process name", __func__);
1193 #endif
1194                                         
1195                                         process_set_name (process_handlep);
1196                                 } else {
1197 #ifdef DEBUG
1198                                         g_message ("%s: Leaving process name: %s", __func__, procname);
1199 #endif
1200                                 }
1201
1202                                 return;
1203                         }
1204
1205                         /* Wrong pid, so drop this handle and fall through to
1206                          * create a new one
1207                          */
1208                         _wapi_handle_unref (current_process);
1209                 }
1210         }
1211
1212         /* We get here if the handle wasn't specified in the
1213          * environment, or if the process ID was wrong, or if the
1214          * handle lookup failed (eg if the parent process forked and
1215          * quit immediately, and deleted the shared data before the
1216          * child got a chance to attach it.)
1217          */
1218
1219 #ifdef DEBUG
1220         g_message ("%s: Need to create my own process handle", __func__);
1221 #endif
1222
1223         process_handle.id = pid;
1224
1225         process_set_defaults (&process_handle);
1226         process_set_name (&process_handle);
1227
1228         current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1229                                             &process_handle);
1230         if (current_process == _WAPI_HANDLE_INVALID) {
1231                 g_warning ("%s: error creating process handle", __func__);
1232                 return;
1233         }
1234 }
1235
1236 gpointer _wapi_process_duplicate ()
1237 {
1238         mono_once (&process_current_once, process_set_current);
1239         
1240         _wapi_handle_ref (current_process);
1241         
1242         return(current_process);
1243 }
1244
1245 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1246 gpointer GetCurrentProcess (void)
1247 {
1248         mono_once (&process_current_once, process_set_current);
1249                 
1250         return(_WAPI_PROCESS_CURRENT);
1251 }
1252
1253 guint32 GetProcessId (gpointer handle)
1254 {
1255         struct _WapiHandle_process *process_handle;
1256         gboolean ok;
1257         
1258         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1259                                   (gpointer *)&process_handle);
1260         if (ok == FALSE) {
1261                 SetLastError (ERROR_INVALID_HANDLE);
1262                 return (0);
1263         }
1264         
1265         return (process_handle->id);
1266 }
1267
1268 guint32 GetCurrentProcessId (void)
1269 {
1270         mono_once (&process_current_once, process_set_current);
1271                 
1272         return (GetProcessId (current_process));
1273 }
1274
1275 /* Returns the process id as a convenience to the functions that call this */
1276 static pid_t signal_process_if_gone (gpointer handle)
1277 {
1278         struct _WapiHandle_process *process_handle;
1279         gboolean ok;
1280         
1281         /* Make sure the process is signalled if it has exited - if
1282          * the parent process didn't wait for it then it won't be
1283          */
1284         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1285                                   (gpointer *)&process_handle);
1286         if (ok == FALSE) {
1287                 /* It's possible that the handle has vanished during
1288                  * the _wapi_search_handle before it gets here, so
1289                  * don't spam the console with warnings.
1290                  */
1291 /*              g_warning ("%s: error looking up process handle %p",
1292   __func__, handle);*/
1293                 
1294                 return (0);
1295         }
1296         
1297 #ifdef DEBUG
1298         g_message ("%s: looking at process %d", __func__, process_handle->id);
1299 #endif
1300
1301         if (kill (process_handle->id, 0) == -1 &&
1302             (errno == ESRCH ||
1303              errno == EPERM)) {
1304                 /* The process is dead, (EPERM tells us a new process
1305                  * has that ID, but as it's owned by someone else it
1306                  * can't be the one listed in our shared memory file)
1307                  */
1308                 _wapi_shared_handle_set_signal_state (handle, TRUE);
1309         }
1310
1311         return (process_handle->id);
1312 }
1313
1314 static gboolean process_enum (gpointer handle, gpointer user_data)
1315 {
1316         GArray *processes=user_data;
1317         pid_t pid = signal_process_if_gone (handle);
1318         int i;
1319         
1320         if (pid == 0) {
1321                 return (FALSE);
1322         }
1323         
1324         /* Ignore processes that have already exited (ie they are signalled) */
1325         if (_wapi_handle_issignalled (handle) == FALSE) {
1326 #ifdef DEBUG
1327                 g_message ("%s: process %d added to array", __func__, pid);
1328 #endif
1329
1330                 /* This ensures that duplicates aren't returned (see
1331                  * the comment above _wapi_search_handle () for why
1332                  * it's needed
1333                  */
1334                 for (i = 0; i < processes->len; i++) {
1335                         if (g_array_index (processes, pid_t, i) == pid) {
1336                                 /* We've already got this one, return
1337                                  * FALSE to keep searching
1338                                  */
1339                                 return (FALSE);
1340                         }
1341                 }
1342                 
1343                 g_array_append_val (processes, pid);
1344         }
1345         
1346         /* Return false to keep searching */
1347         return(FALSE);
1348 }
1349
1350 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1351 {
1352         GArray *processes = g_array_new (FALSE, FALSE, sizeof(pid_t));
1353         guint32 fit, i, j;
1354         
1355         mono_once (&process_current_once, process_set_current);
1356         
1357         _wapi_search_handle (WAPI_HANDLE_PROCESS, process_enum, processes,
1358                              NULL, TRUE);
1359         
1360         fit=len/sizeof(guint32);
1361         for (i = 0, j = 0; j < fit && i < processes->len; i++) {
1362                 pids[j++] = g_array_index (processes, pid_t, i);
1363         }
1364
1365         g_array_free (processes, TRUE);
1366         
1367         *needed = j * sizeof(guint32);
1368         
1369         return(TRUE);
1370 }
1371
1372 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1373 {
1374         pid_t wanted_pid;
1375         pid_t checking_pid = signal_process_if_gone (handle);
1376
1377         if (checking_pid == 0) {
1378                 return(FALSE);
1379         }
1380         
1381         wanted_pid = GPOINTER_TO_UINT (user_data);
1382
1383         /* It's possible to have more than one process handle with the
1384          * same pid, but only the one running process can be
1385          * unsignalled
1386          */
1387         if (checking_pid == wanted_pid &&
1388             _wapi_handle_issignalled (handle) == FALSE) {
1389                 /* If the handle is blown away in the window between
1390                  * returning TRUE here and _wapi_search_handle pinging
1391                  * the timestamp, the search will continue
1392                  */
1393                 return(TRUE);
1394         } else {
1395                 return(FALSE);
1396         }
1397 }
1398
1399 gpointer OpenProcess (guint32 access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1400 {
1401         /* Find the process handle that corresponds to pid */
1402         gpointer handle;
1403         
1404         mono_once (&process_current_once, process_set_current);
1405
1406 #ifdef DEBUG
1407         g_message ("%s: looking for process %d", __func__, pid);
1408 #endif
1409
1410         handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1411                                       process_open_compare,
1412                                       GUINT_TO_POINTER (pid), NULL, TRUE);
1413         if (handle == 0) {
1414 #ifdef DEBUG
1415                 g_message ("%s: Can't find pid %d", __func__, pid);
1416 #endif
1417
1418                 SetLastError (ERROR_PROC_NOT_FOUND);
1419         
1420                 return(NULL);
1421         }
1422
1423         _wapi_handle_ref (handle);
1424         
1425         return(handle);
1426 }
1427
1428 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1429 {
1430         struct _WapiHandle_process *process_handle;
1431         gboolean ok;
1432         
1433         mono_once (&process_current_once, process_set_current);
1434
1435         if(code==NULL) {
1436                 return(FALSE);
1437         }
1438         
1439         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1440                                 (gpointer *)&process_handle);
1441         if(ok==FALSE) {
1442 #ifdef DEBUG
1443                 g_message ("%s: Can't find process %p", __func__, process);
1444 #endif
1445                 
1446                 return(FALSE);
1447         }
1448         
1449         /* A process handle is only signalled if the process has exited
1450          * and has been waited for */
1451         if (_wapi_handle_issignalled (process) == TRUE ||
1452             process_wait (process, 0) == WAIT_OBJECT_0) {
1453                 *code = process_handle->exitstatus;
1454         } else {
1455                 *code = STILL_ACTIVE;
1456         }
1457         
1458         return(TRUE);
1459 }
1460
1461 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1462                           WapiFileTime *exit_time, WapiFileTime *kernel_time,
1463                           WapiFileTime *user_time)
1464 {
1465         struct _WapiHandle_process *process_handle;
1466         gboolean ok;
1467         gboolean ku_times_set = FALSE;
1468         
1469         mono_once (&process_current_once, process_set_current);
1470
1471         if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1472            user_time==NULL) {
1473                 /* Not sure if w32 allows NULLs here or not */
1474                 return(FALSE);
1475         }
1476         
1477         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1478                                 (gpointer *)&process_handle);
1479         if(ok==FALSE) {
1480 #ifdef DEBUG
1481                 g_message ("%s: Can't find process %p", __func__, process);
1482 #endif
1483                 
1484                 return(FALSE);
1485         }
1486         
1487         *create_time=process_handle->create_time;
1488
1489         /* A process handle is only signalled if the process has
1490          * exited.  Otherwise exit_time isn't set
1491          */
1492         if(_wapi_handle_issignalled (process)==TRUE) {
1493                 *exit_time=process_handle->exit_time;
1494         }
1495
1496 #ifdef HAVE_GETRUSAGE
1497         if (process_handle->id == getpid ()) {
1498                 struct rusage time_data;
1499                 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1500                         gint64 tick_val;
1501                         gint64 *tick_val_ptr;
1502                         ku_times_set = TRUE;
1503                         tick_val = time_data.ru_utime.tv_sec * 10000000 + time_data.ru_utime.tv_usec * 10;
1504                         tick_val_ptr = (gint64*)user_time;
1505                         *tick_val_ptr = tick_val;
1506                         tick_val = time_data.ru_stime.tv_sec * 10000000 + time_data.ru_stime.tv_usec * 10;
1507                         tick_val_ptr = (gint64*)kernel_time;
1508                         *tick_val_ptr = tick_val;
1509                 }
1510         }
1511 #endif
1512         if (!ku_times_set) {
1513                 memset (kernel_time, 0, sizeof (WapiFileTime));
1514                 memset (user_time, 0, sizeof (WapiFileTime));
1515         }
1516
1517         return(TRUE);
1518 }
1519
1520 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1521                              guint32 size, guint32 *needed)
1522 {
1523         /* Store modules in an array of pointers (main module as
1524          * modules[0]), using the load address for each module as a
1525          * token.  (Use 'NULL' as an alternative for the main module
1526          * so that the simple implementation can just return one item
1527          * for now.)  Get the info from /proc/<pid>/maps on linux,
1528          * other systems will have to implement /dev/kmem reading or
1529          * whatever other horrid technique is needed.
1530          */
1531         if(size<sizeof(gpointer)) {
1532                 return(FALSE);
1533         }
1534         
1535 #ifdef linux
1536         modules[0]=NULL;
1537         *needed=sizeof(gpointer);
1538 #else
1539         modules[0]=NULL;
1540         *needed=sizeof(gpointer);
1541 #endif
1542         
1543         return(TRUE);
1544 }
1545
1546 guint32 GetModuleBaseName (gpointer process, gpointer module,
1547                            gunichar2 *basename, guint32 size)
1548 {
1549         struct _WapiHandle_process *process_handle;
1550         gboolean ok;
1551         
1552         mono_once (&process_current_once, process_set_current);
1553
1554 #ifdef DEBUG
1555         g_message ("%s: Getting module base name, process handle %p module %p",
1556                    __func__, process, module);
1557 #endif
1558
1559         if(basename==NULL || size==0) {
1560                 return(FALSE);
1561         }
1562         
1563         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1564                                 (gpointer *)&process_handle);
1565         if(ok==FALSE) {
1566 #ifdef DEBUG
1567                 g_message ("%s: Can't find process %p", __func__, process);
1568 #endif
1569                 
1570                 return(FALSE);
1571         }
1572
1573         if(module==NULL) {
1574                 /* Shorthand for the main module, which has the
1575                  * process name recorded in the handle data
1576                  */
1577                 pid_t pid;
1578                 gunichar2 *procname;
1579                 gchar *procname_utf8 = NULL;
1580                 glong len, bytes;
1581                 
1582 #ifdef DEBUG
1583                 g_message ("%s: Returning main module name", __func__);
1584 #endif
1585
1586                 pid=process_handle->id;
1587                 procname_utf8 = process_handle->proc_name;
1588         
1589 #ifdef DEBUG
1590                 g_message ("%s: Process name is [%s]", __func__,
1591                            procname_utf8);
1592 #endif
1593
1594                 procname = g_utf8_to_utf16 (procname_utf8, -1, NULL, &len,
1595                                             NULL);
1596                 if (procname == NULL) {
1597                         /* bugger */
1598                         return(0);
1599                 }
1600
1601                 /* Add the terminator, and convert chars to bytes */
1602                 bytes = (len + 1) * 2;
1603                 
1604                 if (size < bytes) {
1605 #ifdef DEBUG
1606                         g_message ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
1607 #endif
1608
1609                         memcpy (basename, procname, size);
1610                 } else {
1611 #ifdef DEBUG
1612                         g_message ("%s: Size %d larger than needed (%ld)",
1613                                    __func__, size, bytes);
1614 #endif
1615
1616                         memcpy (basename, procname, bytes);
1617                 }
1618                 
1619                 g_free (procname);
1620
1621                 return(len);
1622         } else {
1623                 /* Look up the address in /proc/<pid>/maps */
1624         }
1625         
1626         return(0);
1627 }
1628
1629 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
1630 {
1631         struct _WapiHandle_process *process_handle;
1632         gboolean ok;
1633         
1634         mono_once (&process_current_once, process_set_current);
1635
1636         if(min==NULL || max==NULL) {
1637                 /* Not sure if w32 allows NULLs here or not */
1638                 return(FALSE);
1639         }
1640         
1641         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1642                                 (gpointer *)&process_handle);
1643         if(ok==FALSE) {
1644 #ifdef DEBUG
1645                 g_message ("%s: Can't find process %p", __func__, process);
1646 #endif
1647                 
1648                 return(FALSE);
1649         }
1650
1651         *min=process_handle->min_working_set;
1652         *max=process_handle->max_working_set;
1653         
1654         return(TRUE);
1655 }
1656
1657 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
1658 {
1659         struct _WapiHandle_process *process_handle;
1660         gboolean ok;
1661
1662         mono_once (&process_current_once, process_set_current);
1663
1664         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1665                                 (gpointer *)&process_handle);
1666         if(ok==FALSE) {
1667 #ifdef DEBUG
1668                 g_message ("%s: Can't find process %p", __func__, process);
1669 #endif
1670                 
1671                 return(FALSE);
1672         }
1673
1674         process_handle->min_working_set=min;
1675         process_handle->max_working_set=max;
1676         
1677         return(TRUE);
1678 }
1679
1680
1681 gboolean
1682 TerminateProcess (gpointer process, gint32 exitCode)
1683 {
1684         struct _WapiHandle_process *process_handle;
1685         gboolean ok;
1686         int signo;
1687         int ret;
1688
1689         ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1690                                   (gpointer *) &process_handle);
1691
1692         if (ok == FALSE) {
1693 #ifdef DEBUG
1694                 g_message ("%s: Can't find process %p", __func__, process);
1695 #endif
1696                 SetLastError (ERROR_INVALID_HANDLE);
1697                 return FALSE;
1698         }
1699
1700         signo = (exitCode == -1) ? SIGKILL : SIGTERM;
1701         ret = kill (process_handle->id, signo);
1702         if (ret == -1) {
1703                 switch (errno) {
1704                 case EINVAL:
1705                         SetLastError (ERROR_INVALID_PARAMETER);
1706                         break;
1707                 case EPERM:
1708                         SetLastError (ERROR_ACCESS_DENIED);
1709                         break;
1710                 case ESRCH:
1711                         SetLastError (ERROR_PROC_NOT_FOUND);
1712                         break;
1713                 default:
1714                         SetLastError (ERROR_GEN_FAILURE);
1715                 }
1716         }
1717         
1718         return (ret == 0);
1719 }
1720
1721 guint32
1722 GetPriorityClass (gpointer process)
1723 {
1724 #ifdef HAVE_GETPRIORITY
1725         struct _WapiHandle_process *process_handle;
1726         gboolean ok;
1727         int ret;
1728
1729         ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1730                                   (gpointer *) &process_handle);
1731
1732         if (!ok) {
1733                 SetLastError (ERROR_INVALID_HANDLE);
1734                 return FALSE;
1735         }
1736
1737         errno = 0;
1738         ret = getpriority (PRIO_PROCESS, process_handle->id);
1739         if (ret == -1 && errno != 0) {
1740                 switch (errno) {
1741                 case EPERM:
1742                 case EACCES:
1743                         SetLastError (ERROR_ACCESS_DENIED);
1744                         break;
1745                 case ESRCH:
1746                         SetLastError (ERROR_PROC_NOT_FOUND);
1747                         break;
1748                 default:
1749                         SetLastError (ERROR_GEN_FAILURE);
1750                 }
1751                 return FALSE;
1752         }
1753
1754         if (ret == 0)
1755                 return NORMAL_PRIORITY_CLASS;
1756         else if (ret < -15)
1757                 return REALTIME_PRIORITY_CLASS;
1758         else if (ret < -10)
1759                 return HIGH_PRIORITY_CLASS;
1760         else if (ret < 0)
1761                 return ABOVE_NORMAL_PRIORITY_CLASS;
1762         else if (ret > 10)
1763                 return IDLE_PRIORITY_CLASS;
1764         else if (ret > 0)
1765                 return BELOW_NORMAL_PRIORITY_CLASS;
1766
1767         return NORMAL_PRIORITY_CLASS;
1768 #else
1769         SetLastError (ERROR_NOT_SUPPORTED);
1770         return 0;
1771 #endif
1772 }
1773
1774 gboolean
1775 SetPriorityClass (gpointer process, guint32  priority_class)
1776 {
1777 #ifdef HAVE_SETPRIORITY
1778         struct _WapiHandle_process *process_handle;
1779         gboolean ok;
1780         int ret;
1781         int prio;
1782
1783         ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1784                                   (gpointer *) &process_handle);
1785
1786         if (!ok) {
1787                 SetLastError (ERROR_INVALID_HANDLE);
1788                 return FALSE;
1789         }
1790
1791         switch (priority_class) {
1792         case IDLE_PRIORITY_CLASS:
1793                 prio = 19;
1794                 break;
1795         case BELOW_NORMAL_PRIORITY_CLASS:
1796                 prio = 10;
1797                 break;
1798         case NORMAL_PRIORITY_CLASS:
1799                 prio = 0;
1800                 break;
1801         case ABOVE_NORMAL_PRIORITY_CLASS:
1802                 prio = -5;
1803                 break;
1804         case HIGH_PRIORITY_CLASS:
1805                 prio = -11;
1806                 break;
1807         case REALTIME_PRIORITY_CLASS:
1808                 prio = -20;
1809                 break;
1810         default:
1811                 SetLastError (ERROR_INVALID_PARAMETER);
1812                 return FALSE;
1813         }
1814
1815         ret = setpriority (PRIO_PROCESS, process_handle->id, prio);
1816         if (ret == -1) {
1817                 switch (errno) {
1818                 case EPERM:
1819                 case EACCES:
1820                         SetLastError (ERROR_ACCESS_DENIED);
1821                         break;
1822                 case ESRCH:
1823                         SetLastError (ERROR_PROC_NOT_FOUND);
1824                         break;
1825                 default:
1826                         SetLastError (ERROR_GEN_FAILURE);
1827                 }
1828         }
1829
1830         return ret == 0;
1831 #else
1832         SetLastError (ERROR_NOT_SUPPORTED);
1833         return FALSE;
1834 #endif
1835 }