A few more cases of avoiding work on types with ->byref set.
[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
22 #include <mono/io-layer/wapi.h>
23 #include <mono/io-layer/wapi-private.h>
24 #include <mono/io-layer/handles-private.h>
25 #include <mono/io-layer/misc-private.h>
26 #include <mono/io-layer/mono-mutex.h>
27 #include <mono/io-layer/process-private.h>
28 #include <mono/io-layer/threads.h>
29 #include <mono/utils/strenc.h>
30 #include <mono/io-layer/timefuncs-private.h>
31
32 /* The process' environment strings */
33 extern char **environ;
34
35 #undef DEBUG
36
37 static guint32 process_wait (gpointer handle, guint32 timeout);
38
39 struct _WapiHandleOps _wapi_process_ops = {
40         NULL,                           /* close_shared */
41         NULL,                           /* signal */
42         NULL,                           /* own */
43         NULL,                           /* is_owned */
44         process_wait,                   /* special_wait */
45         NULL                            /* prewait */   
46 };
47
48 static mono_once_t process_current_once=MONO_ONCE_INIT;
49 static gpointer current_process=NULL;
50
51 static mono_once_t process_ops_once=MONO_ONCE_INIT;
52
53 static void process_ops_init (void)
54 {
55         _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
56                                             WAPI_HANDLE_CAP_WAIT |
57                                             WAPI_HANDLE_CAP_SPECIAL_WAIT);
58 }
59
60 static gboolean process_set_termination_details (gpointer handle, int status)
61 {
62         struct _WapiHandle_process *process_handle;
63         gboolean ok;
64         int thr_ret;
65         
66         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
67                                   (gpointer *)&process_handle);
68         if (ok == FALSE) {
69                 g_warning ("%s: error looking up process handle %p",
70                            __func__, handle);
71                 return(FALSE);
72         }
73         
74         thr_ret = _wapi_handle_lock_shared_handles ();
75         g_assert (thr_ret == 0);
76
77         if (WIFSIGNALED(status)) {
78                 process_handle->exitstatus = 128 + WTERMSIG(status);
79         } else {
80                 process_handle->exitstatus = WEXITSTATUS(status);
81         }
82         _wapi_time_t_to_filetime (time(NULL), &process_handle->exit_time);
83         
84 #ifdef DEBUG
85         g_message ("%s: Setting handle %p signalled", __func__, handle);
86 #endif
87
88         _wapi_shared_handle_set_signal_state (handle, TRUE);
89
90         _wapi_handle_unlock_shared_handles ();
91
92         /* Drop the reference we hold so we have somewhere to store
93          * the exit details, now the process has in fact exited
94          */
95         _wapi_handle_unref (handle);
96         
97         return (ok);
98 }
99
100 /* See if any child processes have terminated and wait() for them,
101  * updating process handle info.  This function is called from the
102  * collection thread every few seconds.
103  */
104 static gboolean waitfor_pid (gpointer test, gpointer user_data)
105 {
106         struct _WapiHandle_process *process;
107         gboolean ok;
108         int status;
109         pid_t ret;
110         
111         if (_wapi_handle_issignalled (test)) {
112                 /* We've already done this one */
113                 return (FALSE);
114         }
115         
116         ok = _wapi_lookup_handle (test, WAPI_HANDLE_PROCESS,
117                                   (gpointer *)&process);
118         if (ok == FALSE) {
119                 /* The handle must have been too old and was reaped */
120                 return (FALSE);
121         }
122         
123         do {
124                 ret = waitpid (process->id, &status, WNOHANG);
125         } while (errno == EINTR);
126         
127         if (ret <= 0) {
128                 /* Process not ready for wait */
129 #ifdef DEBUG
130                 g_message ("%s: Process %d not ready for waiting for: %s",
131                            __func__, process->id, g_strerror (errno));
132 #endif
133
134                 return (FALSE);
135         }
136         
137 #ifdef DEBUG
138         g_message ("%s: Process %d finished", __func__, ret);
139 #endif
140
141         *(int *)user_data = status;
142         
143         return (TRUE);
144 }
145
146 void _wapi_process_reap (void)
147 {
148         gpointer proc;
149         int status;
150         
151 #ifdef DEBUG
152         g_message ("%s: Reaping child processes", __func__);
153 #endif
154
155         do {
156                 proc = _wapi_search_handle (WAPI_HANDLE_PROCESS, waitfor_pid,
157                                             &status, NULL, FALSE);
158                 if (proc != NULL) {
159 #ifdef DEBUG
160                         g_message ("%s: process handle %p exit code %d",
161                                    __func__, proc, status);
162 #endif
163                         
164                         process_set_termination_details (proc, status);
165                 }
166         } while (proc != NULL);
167 }
168
169 /* Limitations: This can only wait for processes that are our own
170  * children.  Fixing this means resurrecting a daemon helper to manage
171  * processes.
172  */
173 static guint32 process_wait (gpointer handle, guint32 timeout)
174 {
175         struct _WapiHandle_process *process_handle;
176         gboolean ok;
177         pid_t pid, ret;
178         int status;
179         
180 #ifdef DEBUG
181         g_message ("%s: Waiting for process %p", __func__, handle);
182 #endif
183
184         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
185                                   (gpointer *)&process_handle);
186         if (ok == FALSE) {
187                 g_warning ("%s: error looking up process handle %p", __func__,
188                            handle);
189                 return(WAIT_FAILED);
190         }
191         
192         pid = process_handle->id;
193         
194 #ifdef DEBUG
195         g_message ("%s: PID is %d, timeout %d", __func__, pid, timeout);
196 #endif
197
198         if (timeout == INFINITE) {
199                 while ((ret = waitpid (pid, &status, 0)) != pid) {
200                         if (ret == (pid_t)-1 && errno != EINTR) {
201                                 return(WAIT_FAILED);
202                         }
203                 }
204         } else if (timeout == 0) {
205                 /* Just poll */
206                 ret = waitpid (pid, &status, WNOHANG);
207                 if (ret != pid) {
208                         return (WAIT_TIMEOUT);
209                 }
210         } else {
211                 /* Poll in a loop */
212                 do {
213                         ret = waitpid (pid, &status, WNOHANG);
214                         if (ret == pid) {
215                                 break;
216                         } else if (ret == (pid_t)-1 && errno != EINTR) {
217                                 return(WAIT_FAILED);
218                         }
219
220                         _wapi_handle_spin (100);
221                         timeout -= 100;
222                 } while (timeout > 0);
223
224                 if (timeout <= 0) {
225                         return(WAIT_TIMEOUT);
226                 }
227         }
228
229         /* Process must have exited */
230 #ifdef DEBUG
231         g_message ("%s: Wait done, status %d", __func__, status);
232 #endif
233
234         ok = process_set_termination_details (handle, status);
235         if (ok == FALSE) {
236                 SetLastError (ERROR_OUTOFMEMORY);
237                 return (WAIT_FAILED);
238         }
239
240         return(WAIT_OBJECT_0);
241 }
242
243 void _wapi_process_signal_self ()
244 {
245         if (current_process != NULL) {
246                 process_set_termination_details (current_process, 0);
247         }
248 }
249
250         
251 static void process_set_defaults (struct _WapiHandle_process *process_handle)
252 {
253         /* These seem to be the defaults on w2k */
254         process_handle->min_working_set = 204800;
255         process_handle->max_working_set = 1413120;
256
257         _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
258 }
259
260 /* Implemented as just a wrapper around CreateProcess () */
261 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
262 {
263         gboolean ret;
264         WapiProcessInformation process_info;
265         gunichar2 *args;
266         gchar *u8file, *u8params, *u8args;
267         
268         if (sei == NULL) {
269                 /* w2k just segfaults here, but we can do better than
270                  * that
271                  */
272                 SetLastError (ERROR_INVALID_PARAMETER);
273                 return (FALSE);
274         }
275
276         if (sei->lpFile == NULL) {
277                 /* w2k returns TRUE for this, for some reason. */
278                 return (TRUE);
279         }
280         
281         /* Put both executable and parameters into the second argument
282          * to CreateProcess (), so it searches $PATH.  The conversion
283          * into and back out of utf8 is because there is no
284          * g_strdup_printf () equivalent for gunichar2 :-(
285          */
286         u8file = g_utf16_to_utf8 (sei->lpFile, -1, NULL, NULL, NULL);
287         if (u8file == NULL) {
288                 SetLastError (ERROR_INVALID_DATA);
289                 return (FALSE);
290         }
291         
292         if (sei->lpParameters != NULL) {
293                 u8params = g_utf16_to_utf8 (sei->lpParameters, -1, NULL, NULL, NULL);
294                 if (u8params == NULL) {
295                         SetLastError (ERROR_INVALID_DATA);
296                         g_free (u8file);
297                         return (FALSE);
298                 }
299         
300                 u8args = g_strdup_printf ("%s %s", u8file, u8params);
301                 if (u8args == NULL) {
302                         SetLastError (ERROR_INVALID_DATA);
303                         g_free (u8params);
304                         g_free (u8file);
305                         return (FALSE);
306                 }
307         
308                 args = g_utf8_to_utf16 (u8args, -1, NULL, NULL, NULL);
309         
310                 g_free (u8file);
311                 g_free (u8params);
312                 g_free (u8args);
313         } else {
314                 args = g_utf8_to_utf16 (u8file, -1, NULL, NULL, NULL);
315         }
316                 
317         if (args == NULL) {
318                 SetLastError (ERROR_INVALID_DATA);
319                 return (FALSE);
320         }
321         
322         ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
323                              CREATE_UNICODE_ENVIRONMENT, NULL,
324                              sei->lpDirectory, NULL, &process_info);
325         g_free (args);
326         
327         if (!ret) {
328                 return (FALSE);
329         }
330         
331         if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
332                 sei->hProcess = process_info.hProcess;
333         } else {
334                 CloseHandle (process_info.hProcess);
335         }
336         
337         return (ret);
338 }
339
340 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
341                         WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
342                         WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
343                         gboolean inherit_handles, guint32 create_flags,
344                         gpointer new_environ, const gunichar2 *cwd,
345                         WapiStartupInfo *startup,
346                         WapiProcessInformation *process_info)
347 {
348         gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv;
349         guint32 i, env_count = 0;
350         gboolean ret = FALSE;
351         gpointer handle;
352         struct _WapiHandle_process process_handle = {0}, *process_handle_data;
353         GError *gerr = NULL;
354         int in_fd, out_fd, err_fd;
355         pid_t pid;
356         int thr_ret;
357         
358         mono_once (&process_ops_once, process_ops_init);
359         
360         /* appname and cmdline specify the executable and its args:
361          *
362          * If appname is not NULL, it is the name of the executable.
363          * Otherwise the executable is the first token in cmdline.
364          *
365          * Executable searching:
366          *
367          * If appname is not NULL, it can specify the full path and
368          * file name, or else a partial name and the current directory
369          * will be used.  There is no additional searching.
370          *
371          * If appname is NULL, the first whitespace-delimited token in
372          * cmdline is used.  If the name does not contain a full
373          * directory path, the search sequence is:
374          *
375          * 1) The directory containing the current process
376          * 2) The current working directory
377          * 3) The windows system directory  (Ignored)
378          * 4) The windows directory (Ignored)
379          * 5) $PATH
380          *
381          * Just to make things more interesting, tokens can contain
382          * white space if they are surrounded by quotation marks.  I'm
383          * beginning to understand just why windows apps are generally
384          * so crap, with an API like this :-(
385          */
386         if (appname != NULL) {
387                 cmd = mono_unicode_to_external (appname);
388                 if (cmd == NULL) {
389 #ifdef DEBUG
390                         g_message ("%s: unicode conversion returned NULL",
391                                    __func__);
392 #endif
393
394                         SetLastError (ERROR_PATH_NOT_FOUND);
395                         goto cleanup;
396                 }
397
398                 /* Turn all the slashes round the right way */
399                 for (i = 0; i < strlen (cmd); i++) {
400                         if (cmd[i] == '\\') {
401                                 cmd[i] = '/';
402                         }
403                 }
404         }
405         
406         if (cmdline != NULL) {
407                 args = mono_unicode_to_external (cmdline);
408                 if (args == NULL) {
409 #ifdef DEBUG
410                         g_message ("%s: unicode conversion returned NULL", __func__);
411 #endif
412
413                         SetLastError (ERROR_PATH_NOT_FOUND);
414                         goto cleanup;
415                 }
416         }
417
418         if (cwd != NULL) {
419                 dir = mono_unicode_to_external (cwd);
420                 if (dir == NULL) {
421 #ifdef DEBUG
422                         g_message ("%s: unicode conversion returned NULL", __func__);
423 #endif
424
425                         SetLastError (ERROR_PATH_NOT_FOUND);
426                         goto cleanup;
427                 }
428
429                 /* Turn all the slashes round the right way */
430                 for (i = 0; i < strlen (dir); i++) {
431                         if (dir[i] == '\\') {
432                                 dir[i] = '/';
433                         }
434                 }
435         }
436         
437
438         /* We can't put off locating the executable any longer :-( */
439         if (cmd != NULL) {
440                 gchar *unquoted;
441                 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
442                         /* Strip off the drive letter.  I can't
443                          * believe that CP/M holdover is still
444                          * visible...
445                          */
446                         g_memmove (cmd, cmd+2, strlen (cmd)-2);
447                         cmd[strlen (cmd)-2] = '\0';
448                 }
449
450                 unquoted = g_shell_unquote (cmd, NULL);
451                 if (unquoted[0] == '/') {
452                         /* Assume full path given */
453                         prog = g_strdup (unquoted);
454
455                         /* Executable existing ? */
456                         if (access (prog, X_OK) != 0) {
457 #ifdef DEBUG
458                                 g_message ("%s: Couldn't find executable %s",
459                                            __func__, prog);
460 #endif
461                                 g_free (prog);
462                                 g_free (unquoted);
463                                 SetLastError (ERROR_FILE_NOT_FOUND);
464                                 goto cleanup;
465                         }
466                 } else {
467                         /* Search for file named by cmd in the current
468                          * directory
469                          */
470                         char *curdir = g_get_current_dir ();
471
472                         prog = g_strdup_printf ("%s/%s", curdir, unquoted);
473                         g_free (unquoted);
474                         g_free (curdir);
475
476                         /* And make sure it's executable */
477                         if (access (prog, X_OK) != 0) {
478 #ifdef DEBUG
479                                 g_message ("%s: Couldn't find executable %s",
480                                            __func__, prog);
481 #endif
482                                 g_free (prog);
483                                 SetLastError (ERROR_FILE_NOT_FOUND);
484                                 goto cleanup;
485                         }
486                 }
487
488                 args_after_prog = args;
489         } else {
490                 gchar *token = NULL;
491                 char quote;
492                 
493                 /* Dig out the first token from args, taking quotation
494                  * marks into account
495                  */
496
497                 /* First, strip off all leading whitespace */
498                 args = g_strchug (args);
499                 
500                 /* args_after_prog points to the contents of args
501                  * after token has been set (otherwise argv[0] is
502                  * duplicated)
503                  */
504                 args_after_prog = args;
505
506                 /* Assume the opening quote will always be the first
507                  * character
508                  */
509                 if (args[0] == '\"' || args [0] == '\'') {
510                         quote = args [0];
511                         for (i = 1; args[i] != '\0' && args[i] != quote; i++);
512                         if (g_ascii_isspace (args[i+1])) {
513                                 /* We found the first token */
514                                 token = g_strndup (args+1, i-1);
515                                 args_after_prog = args + i;
516                         } else {
517                                 /* Quotation mark appeared in the
518                                  * middle of the token.  Just give the
519                                  * whole first token, quotes and all,
520                                  * to exec.
521                                  */
522                         }
523                 }
524                 
525                 if (token == NULL) {
526                         /* No quote mark, or malformed */
527                         for (i = 0; args[i] != '\0'; i++) {
528                                 if (g_ascii_isspace (args[i])) {
529                                         token = g_strndup (args, i);
530                                         args_after_prog = args + i + 1;
531                                         break;
532                                 }
533                         }
534                 }
535
536                 if (token == NULL && args[0] != '\0') {
537                         /* Must be just one token in the string */
538                         token = g_strdup (args);
539                         args_after_prog = NULL;
540                 }
541                 
542                 if (token == NULL) {
543                         /* Give up */
544 #ifdef DEBUG
545                         g_message ("%s: Couldn't find what to exec", __func__);
546 #endif
547
548                         SetLastError (ERROR_PATH_NOT_FOUND);
549                         goto cleanup;
550                 }
551                 
552                 /* Turn all the slashes round the right way. Only for
553                  * the prg. name
554                  */
555                 for (i = 0; i < strlen (token); i++) {
556                         if (token[i] == '\\') {
557                                 token[i] = '/';
558                         }
559                 }
560
561                 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
562                         /* Strip off the drive letter.  I can't
563                          * believe that CP/M holdover is still
564                          * visible...
565                          */
566                         g_memmove (token, token+2, strlen (token)-2);
567                         token[strlen (token)-2] = '\0';
568                 }
569
570                 if (token[0] == '/') {
571                         /* Assume full path given */
572                         prog = g_strdup (token);
573                         
574                         /* Executable existing ? */
575                         if (access (prog, X_OK) != 0) {
576                                 g_free (prog);
577 #ifdef DEBUG
578                                 g_message ("%s: Couldn't find executable %s",
579                                            __func__, token);
580 #endif
581                                 g_free (token);
582                                 SetLastError (ERROR_FILE_NOT_FOUND);
583                                 goto cleanup;
584                         }
585
586                 } else {
587                         char *curdir = g_get_current_dir ();
588
589                         /* FIXME: Need to record the directory
590                          * containing the current process, and check
591                          * that for the new executable as the first
592                          * place to look
593                          */
594
595                         prog = g_strdup_printf ("%s/%s", curdir, token);
596                         g_free (curdir);
597
598                         /* I assume X_OK is the criterion to use,
599                          * rather than F_OK
600                          */
601                         if (access (prog, X_OK) != 0) {
602                                 g_free (prog);
603                                 prog = g_find_program_in_path (token);
604                                 if (prog == NULL) {
605 #ifdef DEBUG
606                                         g_message ("%s: Couldn't find executable %s", __func__, token);
607 #endif
608
609                                         g_free (token);
610                                         SetLastError (ERROR_FILE_NOT_FOUND);
611                                         goto cleanup;
612                                 }
613                         }
614                 }
615
616                 g_free (token);
617         }
618
619 #ifdef DEBUG
620         g_message ("%s: Exec prog [%s] args [%s]", __func__, prog,
621                    args_after_prog);
622 #endif
623         
624         if (args_after_prog != NULL && *args_after_prog) {
625                 gchar *qprog;
626
627                 qprog = g_shell_quote (prog);
628                 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
629                 g_free (qprog);
630         } else {
631                 full_prog = g_shell_quote (prog);
632         }
633
634         ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
635         if (ret == FALSE) {
636                 /* FIXME: Could do something with the GError here
637                  */
638         }
639
640         if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
641                 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
642                 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
643                 err_fd = GPOINTER_TO_UINT (startup->hStdError);
644         } else {
645                 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
646                 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
647                 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
648         }
649         
650         g_strlcpy (process_handle.proc_name, prog,
651                    _WAPI_PROC_NAME_MAX_LEN - 1);
652
653         process_set_defaults (&process_handle);
654         
655         handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
656         if (handle == _WAPI_HANDLE_INVALID) {
657                 g_warning ("%s: error creating process handle", __func__);
658
659                 SetLastError (ERROR_PATH_NOT_FOUND);
660                 goto cleanup;
661         }
662
663         /* Hold another reference so the process has somewhere to
664          * store its exit data even if we drop this handle
665          */
666         _wapi_handle_ref (handle);
667         
668         /* new_environ is a block of NULL-terminated strings, which
669          * is itself NULL-terminated. Of course, passing an array of
670          * string pointers would have made things too easy :-(
671          *
672          * If new_environ is not NULL it specifies the entire set of
673          * environment variables in the new process.  Otherwise the
674          * new process inherits the same environment.
675          */
676         if (new_environ != NULL) {
677                 gunichar2 *new_environp;
678
679                 /* Count the number of strings */
680                 for (new_environp = (gunichar2 *)new_environ; *new_environp;
681                      new_environp++) {
682                         env_count++;
683                         while (*new_environp) {
684                                 new_environp++;
685                         }
686                 }
687
688                 /* +2: one for the process handle value, and the last
689                  * one is NULL
690                  */
691                 env_strings = g_new0 (gchar *, env_count + 2);
692                 
693                 /* Copy each environ string into 'strings' turning it
694                  * into utf8 (or the requested encoding) at the same
695                  * time
696                  */
697                 env_count = 0;
698                 for (new_environp = (gunichar2 *)new_environ; *new_environp;
699                      new_environp++) {
700                         env_strings[env_count] = mono_unicode_to_external (new_environp);
701                         env_count++;
702                         while (*new_environp) {
703                                 new_environp++;
704                         }
705                 }
706         } else {
707                 for (i = 0; environ[i] != NULL; i++) {
708                         env_count++;
709                 }
710
711                 /* +2: one for the process handle value, and the last
712                  * one is NULL
713                  */
714                 env_strings = g_new0 (gchar *, env_count + 2);
715                 
716                 /* Copy each environ string into 'strings' turning it
717                  * into utf8 (or the requested encoding) at the same
718                  * time
719                  */
720                 env_count = 0;
721                 for (i = 0; environ[i] != NULL; i++) {
722                         env_strings[env_count] = g_strdup (environ[i]);
723                         env_count++;
724                 }
725         }
726         /* pass process handle info to the child, so it doesn't have
727          * to do an expensive search over the whole list
728          */
729         if (env_strings != NULL) {
730                 struct _WapiHandleUnshared *handle_data;
731                 struct _WapiHandle_shared_ref *ref;
732                 
733                 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
734                 ref = &handle_data->u.shared;
735                 
736                 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
737         }
738
739         thr_ret = _wapi_handle_lock_shared_handles ();
740         g_assert (thr_ret == 0);
741         
742         pid = fork ();
743         if (pid == -1) {
744                 /* Error */
745                 SetLastError (ERROR_OUTOFMEMORY);
746                 _wapi_handle_unref (handle);
747                 goto cleanup;
748         } else if (pid == 0) {
749                 /* Child */
750                 
751                 /* Wait for the parent to finish setting up the
752                  * handle.  The semaphore lock is safe because the
753                  * sem_undo structures of a semaphore aren't inherited
754                  * across a fork ()
755                  */
756                 thr_ret = _wapi_handle_lock_shared_handles ();
757                 g_assert (thr_ret == 0);
758         
759                 _wapi_handle_unlock_shared_handles ();
760                 
761                 /* should we detach from the process group? */
762
763                 /* Connect stdin, stdout and stderr */
764                 dup2 (in_fd, 0);
765                 dup2 (out_fd, 1);
766                 dup2 (err_fd, 2);
767
768                 if (inherit_handles != TRUE) {
769                         /* FIXME: do something here */
770                 }
771                 
772                 /* Close all file descriptors */
773                 for (i = getdtablesize () - 1; i > 2; i--) {
774                         close (i);
775                 }
776
777 #ifdef DEBUG
778                 g_message ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
779                            dir==NULL?".":dir);
780                 for (i = 0; argv[i] != NULL; i++) {
781                         g_message ("arg %d: [%s]", i, argv[i]);
782                 }
783                 
784                 for (i = 0; env_strings[i] != NULL; i++) {
785                         g_message ("env %d: [%s]", i, env_strings[i]);
786                 }
787 #endif
788
789                 /* set cwd */
790                 if (dir != NULL && chdir (dir) == -1) {
791                         /* set error */
792                         _exit (-1);
793                 }
794                 
795                 /* exec */
796                 execve (argv[0], argv, env_strings);
797                 
798                 /* set error */
799                 _exit (-1);
800         }
801         /* parent */
802         
803         ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
804                                    (gpointer *)&process_handle_data);
805         if (ret == FALSE) {
806                 g_warning ("%s: error looking up process handle %p", __func__,
807                            handle);
808                 _wapi_handle_unref (handle);
809                 goto cleanup;
810         }
811         
812         process_handle_data->id = pid;
813         
814         if (process_info != NULL) {
815                 process_info->hProcess = handle;
816                 process_info->dwProcessId = pid;
817
818                 /* FIXME: we might need to handle the thread info some
819                  * day
820                  */
821                 process_info->hThread = NULL;
822                 process_info->dwThreadId = 0;
823         }
824
825 cleanup:
826         _wapi_handle_unlock_shared_handles ();
827
828         if (cmd != NULL) {
829                 g_free (cmd);
830         }
831         if (full_prog != NULL) {
832                 g_free (prog);
833         }
834         if (args != NULL) {
835                 g_free (args);
836         }
837         if (dir != NULL) {
838                 g_free (dir);
839         }
840         if(env_strings != NULL) {
841                 g_strfreev (env_strings);
842         }
843         
844         return(ret);
845 }
846                 
847 static void process_set_name (struct _WapiHandle_process *process_handle)
848 {
849         gchar *progname, *utf8_progname, *slash;
850         
851         progname=g_get_prgname ();
852         utf8_progname=mono_utf8_from_external (progname);
853
854 #ifdef DEBUG
855         g_message ("%s: using [%s] as prog name", __func__, progname);
856 #endif
857
858         if(utf8_progname!=NULL) {
859                 slash=strrchr (utf8_progname, '/');
860                 if(slash!=NULL) {
861                         g_strlcpy (process_handle->proc_name, slash+1,
862                                    _WAPI_PROC_NAME_MAX_LEN - 1);
863                 } else {
864                         g_strlcpy (process_handle->proc_name, utf8_progname,
865                                    _WAPI_PROC_NAME_MAX_LEN - 1);
866                 }
867
868                 g_free (utf8_progname);
869         }
870 }
871
872 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
873
874 #if !GLIB_CHECK_VERSION (2,4,0)
875 #define g_setenv(a,b,c) setenv(a,b,c)
876 #define g_unsetenv(a) unsetenv(a)
877 #endif
878
879 static void process_set_current (void)
880 {
881         pid_t pid = _wapi_getpid ();
882         const char *handle_env;
883         struct _WapiHandle_process process_handle = {0};
884         
885         handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
886         g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
887         
888         if (handle_env != NULL) {
889                 struct _WapiHandle_process *process_handlep;
890                 gchar *procname = NULL;
891                 gboolean ok;
892                 
893                 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
894                 
895 #ifdef DEBUG
896                 g_message ("%s: Found my process handle: %p (offset %d 0x%x)",
897                            __func__, current_process, atoi (handle_env),
898                            atoi (handle_env));
899 #endif
900
901                 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
902                                           (gpointer *)&process_handlep);
903                 if (ok) {
904                         /* This test will probably break on linuxthreads, but
905                          * that should be ancient history on all distros we
906                          * care about by now
907                          */
908                         if (process_handlep->id == pid) {
909                                 procname = process_handlep->proc_name;
910                                 if (!strcmp (procname, "mono")) {
911                                         /* Set a better process name */
912 #ifdef DEBUG
913                                         g_message ("%s: Setting better process name", __func__);
914 #endif
915                                         
916                                         process_set_name (process_handlep);
917                                 } else {
918 #ifdef DEBUG
919                                         g_message ("%s: Leaving process name: %s", __func__, procname);
920 #endif
921                                 }
922
923                                 return;
924                         }
925
926                         /* Wrong pid, so drop this handle and fall through to
927                          * create a new one
928                          */
929                         _wapi_handle_unref (current_process);
930                 }
931         }
932
933         /* We get here if the handle wasn't specified in the
934          * environment, or if the process ID was wrong, or if the
935          * handle lookup failed (eg if the parent process forked and
936          * quit immediately, and deleted the shared data before the
937          * child got a chance to attach it.)
938          */
939
940 #ifdef DEBUG
941         g_message ("%s: Need to create my own process handle", __func__);
942 #endif
943
944         process_handle.id = pid;
945
946         process_set_defaults (&process_handle);
947         process_set_name (&process_handle);
948
949         current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
950                                             &process_handle);
951         if (current_process == _WAPI_HANDLE_INVALID) {
952                 g_warning ("%s: error creating process handle", __func__);
953                 return;
954         }
955 }
956
957 gpointer _wapi_process_duplicate ()
958 {
959         mono_once (&process_current_once, process_set_current);
960         
961         _wapi_handle_ref (current_process);
962         
963         return(current_process);
964 }
965
966 /* Returns a pseudo handle that doesn't need to be closed afterwards */
967 gpointer GetCurrentProcess (void)
968 {
969         mono_once (&process_current_once, process_set_current);
970                 
971         return(_WAPI_PROCESS_CURRENT);
972 }
973
974 guint32 GetProcessId (gpointer handle)
975 {
976         struct _WapiHandle_process *process_handle;
977         gboolean ok;
978         
979         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
980                                   (gpointer *)&process_handle);
981         if (ok == FALSE) {
982                 SetLastError (ERROR_INVALID_HANDLE);
983                 return (0);
984         }
985         
986         return (process_handle->id);
987 }
988
989 guint32 GetCurrentProcessId (void)
990 {
991         mono_once (&process_current_once, process_set_current);
992                 
993         return (GetProcessId (current_process));
994 }
995
996 /* Returns the process id as a convenience to the functions that call this */
997 static pid_t signal_process_if_gone (gpointer handle)
998 {
999         struct _WapiHandle_process *process_handle;
1000         gboolean ok;
1001         
1002         /* Make sure the process is signalled if it has exited - if
1003          * the parent process didn't wait for it then it won't be
1004          */
1005         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1006                                   (gpointer *)&process_handle);
1007         if (ok == FALSE) {
1008                 /* It's possible that the handle has vanished during
1009                  * the _wapi_search_handle before it gets here, so
1010                  * don't spam the console with warnings.
1011                  */
1012 /*              g_warning ("%s: error looking up process handle %p",
1013   __func__, handle);*/
1014                 
1015                 return (0);
1016         }
1017         
1018 #ifdef DEBUG
1019         g_message ("%s: looking at process %d", __func__, process_handle->id);
1020 #endif
1021
1022         if (kill (process_handle->id, 0) == -1 &&
1023             (errno == ESRCH ||
1024              errno == EPERM)) {
1025                 /* The process is dead, (EPERM tells us a new process
1026                  * has that ID, but as it's owned by someone else it
1027                  * can't be the one listed in our shared memory file)
1028                  */
1029                 _wapi_shared_handle_set_signal_state (handle, TRUE);
1030         }
1031
1032         return (process_handle->id);
1033 }
1034
1035 static gboolean process_enum (gpointer handle, gpointer user_data)
1036 {
1037         GArray *processes=user_data;
1038         pid_t pid = signal_process_if_gone (handle);
1039         int i;
1040         
1041         if (pid == 0) {
1042                 return (FALSE);
1043         }
1044         
1045         /* Ignore processes that have already exited (ie they are signalled) */
1046         if (_wapi_handle_issignalled (handle) == FALSE) {
1047 #ifdef DEBUG
1048                 g_message ("%s: process %d added to array", __func__, pid);
1049 #endif
1050
1051                 /* This ensures that duplicates aren't returned (see
1052                  * the comment above _wapi_search_handle () for why
1053                  * it's needed
1054                  */
1055                 for (i = 0; i < processes->len; i++) {
1056                         if (g_array_index (processes, pid_t, i) == pid) {
1057                                 /* We've already got this one, return
1058                                  * FALSE to keep searching
1059                                  */
1060                                 return (FALSE);
1061                         }
1062                 }
1063                 
1064                 g_array_append_val (processes, pid);
1065         }
1066         
1067         /* Return false to keep searching */
1068         return(FALSE);
1069 }
1070
1071 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1072 {
1073         GArray *processes = g_array_new (FALSE, FALSE, sizeof(pid_t));
1074         guint32 fit, i, j;
1075         
1076         mono_once (&process_current_once, process_set_current);
1077         
1078         _wapi_search_handle (WAPI_HANDLE_PROCESS, process_enum, processes,
1079                              NULL, TRUE);
1080         
1081         fit=len/sizeof(guint32);
1082         for (i = 0, j = 0; j < fit && i < processes->len; i++) {
1083                 pids[j++] = g_array_index (processes, pid_t, i);
1084         }
1085
1086         g_array_free (processes, TRUE);
1087         
1088         *needed = j * sizeof(guint32);
1089         
1090         return(TRUE);
1091 }
1092
1093 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1094 {
1095         pid_t wanted_pid;
1096         pid_t checking_pid = signal_process_if_gone (handle);
1097
1098         if (checking_pid == 0) {
1099                 return(FALSE);
1100         }
1101         
1102         wanted_pid = GPOINTER_TO_UINT (user_data);
1103
1104         /* It's possible to have more than one process handle with the
1105          * same pid, but only the one running process can be
1106          * unsignalled
1107          */
1108         if (checking_pid == wanted_pid &&
1109             _wapi_handle_issignalled (handle) == FALSE) {
1110                 /* If the handle is blown away in the window between
1111                  * returning TRUE here and _wapi_search_handle pinging
1112                  * the timestamp, the search will continue
1113                  */
1114                 return(TRUE);
1115         } else {
1116                 return(FALSE);
1117         }
1118 }
1119
1120 gpointer OpenProcess (guint32 access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1121 {
1122         /* Find the process handle that corresponds to pid */
1123         gpointer handle;
1124         
1125         mono_once (&process_current_once, process_set_current);
1126
1127 #ifdef DEBUG
1128         g_message ("%s: looking for process %d", __func__, pid);
1129 #endif
1130
1131         handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1132                                       process_open_compare,
1133                                       GUINT_TO_POINTER (pid), NULL, TRUE);
1134         if (handle == 0) {
1135 #ifdef DEBUG
1136                 g_message ("%s: Can't find pid %d", __func__, pid);
1137 #endif
1138
1139                 SetLastError (ERROR_PROC_NOT_FOUND);
1140         
1141                 return(NULL);
1142         }
1143
1144         _wapi_handle_ref (handle);
1145         
1146         return(handle);
1147 }
1148
1149 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1150 {
1151         struct _WapiHandle_process *process_handle;
1152         gboolean ok;
1153         
1154         mono_once (&process_current_once, process_set_current);
1155
1156         if(code==NULL) {
1157                 return(FALSE);
1158         }
1159         
1160         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1161                                 (gpointer *)&process_handle);
1162         if(ok==FALSE) {
1163 #ifdef DEBUG
1164                 g_message ("%s: Can't find process %p", __func__, process);
1165 #endif
1166                 
1167                 return(FALSE);
1168         }
1169         
1170         /* A process handle is only signalled if the process has exited
1171          * and has been waited for */
1172         if (_wapi_handle_issignalled (process) == TRUE ||
1173             process_wait (process, 0) == WAIT_OBJECT_0) {
1174                 *code = process_handle->exitstatus;
1175         } else {
1176                 *code = STILL_ACTIVE;
1177         }
1178         
1179         return(TRUE);
1180 }
1181
1182 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1183                           WapiFileTime *exit_time, WapiFileTime *kernel_time,
1184                           WapiFileTime *user_time)
1185 {
1186         struct _WapiHandle_process *process_handle;
1187         gboolean ok;
1188         
1189         mono_once (&process_current_once, process_set_current);
1190
1191         if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1192            user_time==NULL) {
1193                 /* Not sure if w32 allows NULLs here or not */
1194                 return(FALSE);
1195         }
1196         
1197         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1198                                 (gpointer *)&process_handle);
1199         if(ok==FALSE) {
1200 #ifdef DEBUG
1201                 g_message ("%s: Can't find process %p", __func__, process);
1202 #endif
1203                 
1204                 return(FALSE);
1205         }
1206         
1207         *create_time=process_handle->create_time;
1208
1209         /* A process handle is only signalled if the process has
1210          * exited.  Otherwise exit_time isn't set
1211          */
1212         if(_wapi_handle_issignalled (process)==TRUE) {
1213                 *exit_time=process_handle->exit_time;
1214         }
1215         
1216         return(TRUE);
1217 }
1218
1219 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1220                              guint32 size, guint32 *needed)
1221 {
1222         /* Store modules in an array of pointers (main module as
1223          * modules[0]), using the load address for each module as a
1224          * token.  (Use 'NULL' as an alternative for the main module
1225          * so that the simple implementation can just return one item
1226          * for now.)  Get the info from /proc/<pid>/maps on linux,
1227          * other systems will have to implement /dev/kmem reading or
1228          * whatever other horrid technique is needed.
1229          */
1230         if(size<sizeof(gpointer)) {
1231                 return(FALSE);
1232         }
1233         
1234 #ifdef linux
1235         modules[0]=NULL;
1236         *needed=sizeof(gpointer);
1237 #else
1238         modules[0]=NULL;
1239         *needed=sizeof(gpointer);
1240 #endif
1241         
1242         return(TRUE);
1243 }
1244
1245 guint32 GetModuleBaseName (gpointer process, gpointer module,
1246                            gunichar2 *basename, guint32 size)
1247 {
1248         struct _WapiHandle_process *process_handle;
1249         gboolean ok;
1250         
1251         mono_once (&process_current_once, process_set_current);
1252
1253 #ifdef DEBUG
1254         g_message ("%s: Getting module base name, process handle %p module %p",
1255                    __func__, process, module);
1256 #endif
1257
1258         if(basename==NULL || size==0) {
1259                 return(FALSE);
1260         }
1261         
1262         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1263                                 (gpointer *)&process_handle);
1264         if(ok==FALSE) {
1265 #ifdef DEBUG
1266                 g_message ("%s: Can't find process %p", __func__, process);
1267 #endif
1268                 
1269                 return(FALSE);
1270         }
1271
1272         if(module==NULL) {
1273                 /* Shorthand for the main module, which has the
1274                  * process name recorded in the handle data
1275                  */
1276                 pid_t pid;
1277                 gunichar2 *procname;
1278                 gchar *procname_utf8 = NULL;
1279                 glong len, bytes;
1280                 
1281 #ifdef DEBUG
1282                 g_message ("%s: Returning main module name", __func__);
1283 #endif
1284
1285                 pid=process_handle->id;
1286                 procname_utf8 = process_handle->proc_name;
1287         
1288 #ifdef DEBUG
1289                 g_message ("%s: Process name is [%s]", __func__,
1290                            procname_utf8);
1291 #endif
1292
1293                 procname = g_utf8_to_utf16 (procname_utf8, -1, NULL, &len,
1294                                             NULL);
1295                 if (procname == NULL) {
1296                         /* bugger */
1297                         return(0);
1298                 }
1299
1300                 /* Add the terminator, and convert chars to bytes */
1301                 bytes = (len + 1) * 2;
1302                 
1303                 if (size < bytes) {
1304 #ifdef DEBUG
1305                         g_message ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
1306 #endif
1307
1308                         memcpy (basename, procname, size);
1309                 } else {
1310 #ifdef DEBUG
1311                         g_message ("%s: Size %d larger than needed (%ld)",
1312                                    __func__, size, bytes);
1313 #endif
1314
1315                         memcpy (basename, procname, bytes);
1316                 }
1317                 
1318                 g_free (procname);
1319
1320                 return(len);
1321         } else {
1322                 /* Look up the address in /proc/<pid>/maps */
1323         }
1324         
1325         return(0);
1326 }
1327
1328 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
1329 {
1330         struct _WapiHandle_process *process_handle;
1331         gboolean ok;
1332         
1333         mono_once (&process_current_once, process_set_current);
1334
1335         if(min==NULL || max==NULL) {
1336                 /* Not sure if w32 allows NULLs here or not */
1337                 return(FALSE);
1338         }
1339         
1340         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1341                                 (gpointer *)&process_handle);
1342         if(ok==FALSE) {
1343 #ifdef DEBUG
1344                 g_message ("%s: Can't find process %p", __func__, process);
1345 #endif
1346                 
1347                 return(FALSE);
1348         }
1349
1350         *min=process_handle->min_working_set;
1351         *max=process_handle->max_working_set;
1352         
1353         return(TRUE);
1354 }
1355
1356 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
1357 {
1358         struct _WapiHandle_process *process_handle;
1359         gboolean ok;
1360
1361         mono_once (&process_current_once, process_set_current);
1362
1363         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1364                                 (gpointer *)&process_handle);
1365         if(ok==FALSE) {
1366 #ifdef DEBUG
1367                 g_message ("%s: Can't find process %p", __func__, process);
1368 #endif
1369                 
1370                 return(FALSE);
1371         }
1372
1373         process_handle->min_working_set=min;
1374         process_handle->max_working_set=max;
1375         
1376         return(TRUE);
1377 }
1378
1379
1380 gboolean
1381 TerminateProcess (gpointer process, gint32 exitCode)
1382 {
1383         struct _WapiHandle_process *process_handle;
1384         gboolean ok;
1385         int signo;
1386         int ret;
1387
1388         ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1389                                   (gpointer *) &process_handle);
1390
1391         if (ok == FALSE) {
1392 #ifdef DEBUG
1393                 g_message ("%s: Can't find process %p", __func__, process);
1394 #endif
1395                 SetLastError (ERROR_INVALID_HANDLE);
1396                 return FALSE;
1397         }
1398
1399         signo = (exitCode == -1) ? SIGKILL : SIGTERM;
1400         ret = kill (process_handle->id, signo);
1401         if (ret == -1) {
1402                 switch (errno) {
1403                 case EINVAL:
1404                         SetLastError (ERROR_INVALID_PARAMETER);
1405                         break;
1406                 case EPERM:
1407                         SetLastError (ERROR_ACCESS_DENIED);
1408                         break;
1409                 case ESRCH:
1410                         SetLastError (ERROR_PROC_NOT_FOUND);
1411                         break;
1412                 default:
1413                         SetLastError (ERROR_GEN_FAILURE);
1414                 }
1415         }
1416         
1417         return (ret == 0);
1418 }
1419