[System] Process.WaitForExit now triggers event Exited.
[mono.git] / mono / metadata / process.c
1 /*
2  * process.c: System.Diagnostics.Process support
3  *
4  * Author:
5  *      Dick Porter (dick@ximian.com)
6  *
7  * Copyright 2002 Ximian, Inc.
8  * Copyright 2002-2006 Novell, Inc.
9  */
10
11 #include <config.h>
12
13 #include <glib.h>
14 #include <string.h>
15
16 #include <mono/metadata/object-internals.h>
17 #include <mono/metadata/process.h>
18 #include <mono/metadata/assembly.h>
19 #include <mono/metadata/appdomain.h>
20 #include <mono/metadata/image.h>
21 #include <mono/metadata/cil-coff.h>
22 #include <mono/metadata/exception.h>
23 #include <mono/utils/strenc.h>
24 #include <mono/utils/mono-proclib.h>
25 #include <mono/io-layer/io-layer.h>
26 /* FIXME: fix this code to not depend so much on the internals */
27 #include <mono/metadata/class-internals.h>
28
29 #define LOGDEBUG(...)  
30 /* define LOGDEBUG(...) g_message(__VA_ARGS__)  */
31
32
33 HANDLE ves_icall_System_Diagnostics_Process_GetProcess_internal (guint32 pid)
34 {
35         HANDLE handle;
36         
37         /* GetCurrentProcess returns a pseudo-handle, so use
38          * OpenProcess instead
39          */
40         handle=OpenProcess (PROCESS_ALL_ACCESS, TRUE, pid);
41         
42         if(handle==NULL) {
43                 /* FIXME: Throw an exception */
44                 return(NULL);
45         }
46         
47         return(handle);
48 }
49
50 guint32
51 ves_icall_System_Diagnostics_Process_GetPid_internal (void)
52 {
53         return mono_process_current_pid ();
54 }
55
56 void ves_icall_System_Diagnostics_Process_Process_free_internal (MonoObject *this,
57                                                                  HANDLE process)
58 {
59 #ifdef THREAD_DEBUG
60         g_message ("%s: Closing process %p, handle %p", __func__, this, process);
61 #endif
62
63 #if defined(TARGET_WIN32) || defined(HOST_WIN32)
64         CloseHandle (process);
65 #else
66         CloseProcess (process);
67 #endif
68 }
69
70 #define STASH_SYS_ASS(this) \
71         if(system_assembly == NULL) { \
72                 system_assembly=this->vtable->klass->image; \
73         }
74
75 static MonoImage *system_assembly=NULL;
76
77 static guint32 unicode_chars (const gunichar2 *str)
78 {
79         guint32 len=0;
80         
81         do {
82                 if(str[len]=='\0') {
83                         return(len);
84                 }
85                 len++;
86         } while(1);
87 }
88
89 static void process_set_field_object (MonoObject *obj, const gchar *fieldname,
90                                       MonoObject *data)
91 {
92         MonoClassField *field;
93
94         LOGDEBUG (g_message ("%s: Setting field %s to object at %p", __func__, fieldname, data));
95
96         field=mono_class_get_field_from_name (mono_object_class (obj),
97                                               fieldname);
98         mono_gc_wbarrier_generic_store (((char *)obj) + field->offset, data);
99 }
100
101 static void process_set_field_string (MonoObject *obj, const gchar *fieldname,
102                                       const gunichar2 *val, guint32 len)
103 {
104         MonoClassField *field;
105         MonoString *string;
106
107         LOGDEBUG (g_message ("%s: Setting field %s to [%s]", __func__, fieldname, g_utf16_to_utf8 (val, len, NULL, NULL, NULL)));
108
109         string=mono_string_new_utf16 (mono_object_domain (obj), val, len);
110         
111         field=mono_class_get_field_from_name (mono_object_class (obj),
112                                               fieldname);
113         mono_gc_wbarrier_generic_store (((char *)obj) + field->offset, (MonoObject*)string);
114 }
115
116 static void process_set_field_int (MonoObject *obj, const gchar *fieldname,
117                                    guint32 val)
118 {
119         MonoClassField *field;
120
121         LOGDEBUG (g_message ("%s: Setting field %s to %d", __func__,fieldname, val));
122         
123         field=mono_class_get_field_from_name (mono_object_class (obj),
124                                               fieldname);
125         *(guint32 *)(((char *)obj) + field->offset)=val;
126 }
127
128 static void process_set_field_intptr (MonoObject *obj, const gchar *fieldname,
129                                       gpointer val)
130 {
131         MonoClassField *field;
132
133         LOGDEBUG (g_message ("%s: Setting field %s to %p", __func__, fieldname, val));
134         
135         field=mono_class_get_field_from_name (mono_object_class (obj),
136                                               fieldname);
137         *(gpointer *)(((char *)obj) + field->offset)=val;
138 }
139
140 static void process_set_field_bool (MonoObject *obj, const gchar *fieldname,
141                                     gboolean val)
142 {
143         MonoClassField *field;
144
145         LOGDEBUG (g_message ("%s: Setting field %s to %s", __func__, fieldname, val?"TRUE":"FALSE"));
146         
147         field=mono_class_get_field_from_name (mono_object_class (obj),
148                                               fieldname);
149         *(guint8 *)(((char *)obj) + field->offset)=val;
150 }
151
152 #define SFI_COMMENTS            "\\StringFileInfo\\%02X%02X%02X%02X\\Comments"
153 #define SFI_COMPANYNAME         "\\StringFileInfo\\%02X%02X%02X%02X\\CompanyName"
154 #define SFI_FILEDESCRIPTION     "\\StringFileInfo\\%02X%02X%02X%02X\\FileDescription"
155 #define SFI_FILEVERSION         "\\StringFileInfo\\%02X%02X%02X%02X\\FileVersion"
156 #define SFI_INTERNALNAME        "\\StringFileInfo\\%02X%02X%02X%02X\\InternalName"
157 #define SFI_LEGALCOPYRIGHT      "\\StringFileInfo\\%02X%02X%02X%02X\\LegalCopyright"
158 #define SFI_LEGALTRADEMARKS     "\\StringFileInfo\\%02X%02X%02X%02X\\LegalTrademarks"
159 #define SFI_ORIGINALFILENAME    "\\StringFileInfo\\%02X%02X%02X%02X\\OriginalFilename"
160 #define SFI_PRIVATEBUILD        "\\StringFileInfo\\%02X%02X%02X%02X\\PrivateBuild"
161 #define SFI_PRODUCTNAME         "\\StringFileInfo\\%02X%02X%02X%02X\\ProductName"
162 #define SFI_PRODUCTVERSION      "\\StringFileInfo\\%02X%02X%02X%02X\\ProductVersion"
163 #define SFI_SPECIALBUILD        "\\StringFileInfo\\%02X%02X%02X%02X\\SpecialBuild"
164 #define EMPTY_STRING            (gunichar2*)"\000\000"
165
166 static void process_module_string_read (MonoObject *filever, gpointer data,
167                                         const gchar *fieldname,
168                                         guchar lang_hi, guchar lang_lo,
169                                         const gchar *key)
170 {
171         gchar *lang_key_utf8;
172         gunichar2 *lang_key, *buffer;
173         UINT chars;
174
175         lang_key_utf8 = g_strdup_printf (key, lang_lo, lang_hi, 0x04, 0xb0);
176
177         LOGDEBUG (g_message ("%s: asking for [%s]", __func__, lang_key_utf8));
178
179         lang_key = g_utf8_to_utf16 (lang_key_utf8, -1, NULL, NULL, NULL);
180
181         if (VerQueryValue (data, lang_key, (gpointer *)&buffer, &chars) && chars > 0) {
182                 LOGDEBUG (g_message ("%s: found %d chars of [%s]", __func__, chars, g_utf16_to_utf8 (buffer, chars, NULL, NULL, NULL)));
183                 /* chars includes trailing null */
184                 process_set_field_string (filever, fieldname, buffer, chars - 1);
185         } else {
186                 process_set_field_string (filever, fieldname, EMPTY_STRING, 0);
187         }
188
189         g_free (lang_key);
190         g_free (lang_key_utf8);
191 }
192
193 static void process_module_stringtable (MonoObject *filever, gpointer data,
194                                         guchar lang_hi, guchar lang_lo)
195 {
196         process_module_string_read (filever, data, "comments", lang_hi, lang_lo,
197                                     SFI_COMMENTS);
198         process_module_string_read (filever, data, "companyname", lang_hi,
199                                     lang_lo, SFI_COMPANYNAME);
200         process_module_string_read (filever, data, "filedescription", lang_hi,
201                                     lang_lo, SFI_FILEDESCRIPTION);
202         process_module_string_read (filever, data, "fileversion", lang_hi,
203                                     lang_lo, SFI_FILEVERSION);
204         process_module_string_read (filever, data, "internalname", lang_hi,
205                                     lang_lo, SFI_INTERNALNAME);
206         process_module_string_read (filever, data, "legalcopyright", lang_hi,
207                                     lang_lo, SFI_LEGALCOPYRIGHT);
208         process_module_string_read (filever, data, "legaltrademarks", lang_hi,
209                                     lang_lo, SFI_LEGALTRADEMARKS);
210         process_module_string_read (filever, data, "originalfilename", lang_hi,
211                                     lang_lo, SFI_ORIGINALFILENAME);
212         process_module_string_read (filever, data, "privatebuild", lang_hi,
213                                     lang_lo, SFI_PRIVATEBUILD);
214         process_module_string_read (filever, data, "productname", lang_hi,
215                                     lang_lo, SFI_PRODUCTNAME);
216         process_module_string_read (filever, data, "productversion", lang_hi,
217                                     lang_lo, SFI_PRODUCTVERSION);
218         process_module_string_read (filever, data, "specialbuild", lang_hi,
219                                     lang_lo, SFI_SPECIALBUILD);
220 }
221
222 static void process_get_fileversion (MonoObject *filever, gunichar2 *filename)
223 {
224         DWORD verinfohandle;
225         VS_FIXEDFILEINFO *ffi;
226         gpointer data;
227         DWORD datalen;
228         guchar *trans_data;
229         gunichar2 *query;
230         UINT ffi_size, trans_size;
231         BOOL ok;
232         gunichar2 lang_buf[128];
233         guint32 lang, lang_count;
234
235         datalen = GetFileVersionInfoSize (filename, &verinfohandle);
236         if (datalen) {
237                 data = g_malloc0 (datalen);
238                 ok = GetFileVersionInfo (filename, verinfohandle, datalen,
239                                          data);
240                 if (ok) {
241                         query = g_utf8_to_utf16 ("\\", -1, NULL, NULL, NULL);
242                         if (query == NULL) {
243                                 g_free (data);
244                                 return;
245                         }
246                         
247                         if (VerQueryValue (data, query, (gpointer *)&ffi,
248                             &ffi_size)) {
249                                 LOGDEBUG (g_message ("%s: recording assembly: FileName [%s] FileVersionInfo [%d.%d.%d.%d]", __func__, g_utf16_to_utf8 (filename, -1, NULL, NULL, NULL), HIWORD (ffi->dwFileVersionMS), LOWORD (ffi->dwFileVersionMS), HIWORD (ffi->dwFileVersionLS), LOWORD (ffi->dwFileVersionLS)));
250         
251                                 process_set_field_int (filever, "filemajorpart", HIWORD (ffi->dwFileVersionMS));
252                                 process_set_field_int (filever, "fileminorpart", LOWORD (ffi->dwFileVersionMS));
253                                 process_set_field_int (filever, "filebuildpart", HIWORD (ffi->dwFileVersionLS));
254                                 process_set_field_int (filever, "fileprivatepart", LOWORD (ffi->dwFileVersionLS));
255
256                                 process_set_field_int (filever, "productmajorpart", HIWORD (ffi->dwProductVersionMS));
257                                 process_set_field_int (filever, "productminorpart", LOWORD (ffi->dwProductVersionMS));
258                                 process_set_field_int (filever, "productbuildpart", HIWORD (ffi->dwProductVersionLS));
259                                 process_set_field_int (filever, "productprivatepart", LOWORD (ffi->dwProductVersionLS));
260
261                                 process_set_field_bool (filever, "isdebug", ((ffi->dwFileFlags & ffi->dwFileFlagsMask) & VS_FF_DEBUG) != 0);
262                                 process_set_field_bool (filever, "isprerelease", ((ffi->dwFileFlags & ffi->dwFileFlagsMask) & VS_FF_PRERELEASE) != 0);
263                                 process_set_field_bool (filever, "ispatched", ((ffi->dwFileFlags & ffi->dwFileFlagsMask) & VS_FF_PATCHED) != 0);
264                                 process_set_field_bool (filever, "isprivatebuild", ((ffi->dwFileFlags & ffi->dwFileFlagsMask) & VS_FF_PRIVATEBUILD) != 0);
265                                 process_set_field_bool (filever, "isspecialbuild", ((ffi->dwFileFlags & ffi->dwFileFlagsMask) & VS_FF_SPECIALBUILD) != 0);
266                         }
267                         g_free (query);
268
269                         query = g_utf8_to_utf16 ("\\VarFileInfo\\Translation", -1, NULL, NULL, NULL);
270                         if (query == NULL) {
271                                 g_free (data);
272                                 return;
273                         }
274                         
275                         if (VerQueryValue (data, query,
276                                            (gpointer *)&trans_data,
277                                            &trans_size)) {
278                                 /* use the first language ID we see
279                                  */
280                                 if (trans_size >= 4) {
281                                         LOGDEBUG (g_message("%s: %s has 0x%0x 0x%0x 0x%0x 0x%0x", __func__, g_utf16_to_utf8 (filename, -1, NULL, NULL, NULL), trans_data[0], trans_data[1], trans_data[2], trans_data[3]));
282                                         lang = (trans_data[0]) |
283                                                 (trans_data[1] << 8) |
284                                                 (trans_data[2] << 16) |
285                                                 (trans_data[3] << 24);
286                                         /* Only give the lower 16 bits
287                                          * to VerLanguageName, as
288                                          * Windows gets confused
289                                          * otherwise
290                                          */
291                                         lang_count = VerLanguageName (lang & 0xFFFF, lang_buf, 128);
292                                         if (lang_count) {
293                                                 process_set_field_string (filever, "language", lang_buf, lang_count);
294                                         }
295                                         process_module_stringtable (filever, data, trans_data[0], trans_data[1]);
296                                 }
297                         } else {
298                                 /* No strings, so set every field to
299                                  * the empty string
300                                  */
301                                 process_set_field_string (filever,
302                                                           "comments",
303                                                           EMPTY_STRING, 0);
304                                 process_set_field_string (filever,
305                                                           "companyname",
306                                                           EMPTY_STRING, 0);
307                                 process_set_field_string (filever,
308                                                           "filedescription",
309                                                           EMPTY_STRING, 0);
310                                 process_set_field_string (filever,
311                                                           "fileversion",
312                                                           EMPTY_STRING, 0);
313                                 process_set_field_string (filever,
314                                                           "internalname",
315                                                           EMPTY_STRING, 0);
316                                 process_set_field_string (filever,
317                                                           "legalcopyright",
318                                                           EMPTY_STRING, 0);
319                                 process_set_field_string (filever,
320                                                           "legaltrademarks",
321                                                           EMPTY_STRING, 0);
322                                 process_set_field_string (filever,
323                                                           "originalfilename",
324                                                           EMPTY_STRING, 0);
325                                 process_set_field_string (filever,
326                                                           "privatebuild",
327                                                           EMPTY_STRING, 0);
328                                 process_set_field_string (filever,
329                                                           "productname",
330                                                           EMPTY_STRING, 0);
331                                 process_set_field_string (filever,
332                                                           "productversion",
333                                                           EMPTY_STRING, 0);
334                                 process_set_field_string (filever,
335                                                           "specialbuild",
336                                                           EMPTY_STRING, 0);
337
338                                 /* And language seems to be set to
339                                  * en_US according to bug 374600
340                                  */
341                                 lang_count = VerLanguageName (0x0409, lang_buf, 128);
342                                 if (lang_count) {
343                                         process_set_field_string (filever, "language", lang_buf, lang_count);
344                                 }
345                         }
346                         
347                         g_free (query);
348                 }
349                 g_free (data);
350         }
351 }
352
353 static MonoObject* process_add_module (HANDLE process, HMODULE mod, gunichar2 *filename, gunichar2 *modulename, MonoClass *proc_class)
354 {
355         MonoClass *filever_class;
356         MonoObject *item, *filever;
357         MonoDomain *domain=mono_domain_get ();
358         MODULEINFO modinfo;
359         BOOL ok;
360         
361         /* Build a System.Diagnostics.ProcessModule with the data.
362          */
363         item=mono_object_new (domain, proc_class);
364
365         filever_class=mono_class_from_name (system_assembly,
366                                             "System.Diagnostics",
367                                             "FileVersionInfo");
368         filever=mono_object_new (domain, filever_class);
369
370         process_get_fileversion (filever, filename);
371
372         process_set_field_string (filever, "filename", filename,
373                                   unicode_chars (filename));
374
375         ok = GetModuleInformation (process, mod, &modinfo, sizeof(MODULEINFO));
376         if (ok) {
377                 process_set_field_intptr (item, "baseaddr",
378                                           modinfo.lpBaseOfDll);
379                 process_set_field_intptr (item, "entryaddr",
380                                           modinfo.EntryPoint);
381                 process_set_field_int (item, "memory_size",
382                                        modinfo.SizeOfImage);
383         }
384         process_set_field_string (item, "filename", filename,
385                                   unicode_chars (filename));
386         process_set_field_string (item, "modulename", modulename,
387                                   unicode_chars (modulename));
388         process_set_field_object (item, "version_info", filever);
389
390         return item;
391 }
392
393 /* Returns an array of System.Diagnostics.ProcessModule */
394 MonoArray *ves_icall_System_Diagnostics_Process_GetModules_internal (MonoObject *this, HANDLE process)
395 {
396         MonoArray *temp_arr = NULL;
397         MonoArray *arr;
398         HMODULE mods[1024];
399         gunichar2 filename[MAX_PATH];
400         gunichar2 modname[MAX_PATH];
401         DWORD needed;
402         guint32 count = 0;
403         guint32 i, num_added = 0;
404         MonoClass *proc_class;
405
406         STASH_SYS_ASS (this);
407
408         if (EnumProcessModules (process, mods, sizeof(mods), &needed)) {
409                 count = needed / sizeof(HMODULE);
410                 proc_class = mono_class_from_name (system_assembly, "System.Diagnostics", "ProcessModule");
411                 temp_arr = mono_array_new (mono_domain_get (), proc_class, count);
412                 for (i = 0; i < count; i++) {
413                         if (GetModuleBaseName (process, mods[i], modname, MAX_PATH) &&
414                                         GetModuleFileNameEx (process, mods[i], filename, MAX_PATH)) {
415                                 MonoObject *module = process_add_module (process, mods[i],
416                                                 filename, modname, proc_class);
417                                 mono_array_setref (temp_arr, num_added++, module);
418                         }
419                 }
420         }
421
422         if (count == num_added) {
423                 arr = temp_arr;
424         } else {
425                 /* shorter version of the array */
426                 arr = mono_array_new (mono_domain_get (), proc_class, num_added);
427
428                 for (i = 0; i < num_added; i++)
429                         mono_array_setref (arr, i, mono_array_get (temp_arr, MonoObject*, i));
430         }
431
432         return arr;
433 }
434
435 void ves_icall_System_Diagnostics_FileVersionInfo_GetVersionInfo_internal (MonoObject *this, MonoString *filename)
436 {
437         STASH_SYS_ASS (this);
438         
439         process_get_fileversion (this, mono_string_chars (filename));
440         process_set_field_string (this, "filename",
441                                   mono_string_chars (filename),
442                                   mono_string_length (filename));
443 }
444
445 /* Only used when UseShellExecute is false */
446 static gchar *
447 quote_path (const gchar *path)
448 {
449         gchar *res = g_shell_quote (path);
450 #ifdef TARGET_WIN32
451         {
452         gchar *q = res;
453         while (*q) {
454                 if (*q == '\'')
455                         *q = '\"';
456                 q++;
457         }
458         }
459 #endif
460         return res;
461 }
462
463 /* Only used when UseShellExecute is false */
464 static gboolean
465 complete_path (const gunichar2 *appname, gchar **completed)
466 {
467         gchar *utf8app, *utf8appmemory;
468         gchar *found;
469
470         utf8appmemory = utf8app = g_utf16_to_utf8 (appname, -1, NULL, NULL, NULL);
471 #ifdef TARGET_WIN32 // Should this happen on all platforms? 
472         {
473                 // remove the quotes around utf8app.
474                 size_t len;
475                 len = strlen (utf8app);
476                 if (len) {
477                         if (utf8app[len-1] == '\"')
478                                 utf8app[len-1] = '\0';
479                         if (utf8app[0] == '\"')
480                                 utf8app++;
481                 }
482         }
483 #endif
484
485         if (g_path_is_absolute (utf8app)) {
486                 *completed = quote_path (utf8app);
487                 g_free (utf8appmemory);
488                 return TRUE;
489         }
490
491         if (g_file_test (utf8app, G_FILE_TEST_IS_EXECUTABLE) && !g_file_test (utf8app, G_FILE_TEST_IS_DIR)) {
492                 *completed = quote_path (utf8app);
493                 g_free (utf8appmemory);
494                 return TRUE;
495         }
496         
497         found = g_find_program_in_path (utf8app);
498         if (found == NULL) {
499                 *completed = NULL;
500                 g_free (utf8appmemory);
501                 return FALSE;
502         }
503
504         *completed = quote_path (found);
505         g_free (found);
506         g_free (utf8appmemory);
507         return TRUE;
508 }
509
510 MonoBoolean ves_icall_System_Diagnostics_Process_ShellExecuteEx_internal (MonoProcessStartInfo *proc_start_info, MonoProcInfo *process_info)
511 {
512         SHELLEXECUTEINFO shellex = {0};
513         gboolean ret;
514
515         shellex.cbSize = sizeof(SHELLEXECUTEINFO);
516         shellex.fMask = SEE_MASK_FLAG_DDEWAIT | SEE_MASK_NOCLOSEPROCESS | SEE_MASK_UNICODE;
517         shellex.nShow = proc_start_info->window_style;
518         shellex.nShow = (shellex.nShow == 0) ? 1 : (shellex.nShow == 1 ? 0 : shellex.nShow);
519         
520         
521         if (proc_start_info->filename != NULL) {
522                 shellex.lpFile = mono_string_chars (proc_start_info->filename);
523         }
524
525         if (proc_start_info->arguments != NULL) {
526                 shellex.lpParameters = mono_string_chars (proc_start_info->arguments);
527         }
528
529         if (proc_start_info->verb != NULL &&
530             mono_string_length (proc_start_info->verb) != 0) {
531                 shellex.lpVerb = mono_string_chars (proc_start_info->verb);
532         }
533
534         if (proc_start_info->working_directory != NULL &&
535             mono_string_length (proc_start_info->working_directory) != 0) {
536                 shellex.lpDirectory = mono_string_chars (proc_start_info->working_directory);
537         }
538
539         if (proc_start_info->error_dialog) {    
540                 shellex.hwnd = proc_start_info->error_dialog_parent_handle;
541         } else {
542                 shellex.fMask |= SEE_MASK_FLAG_NO_UI;
543         }
544
545         ret = ShellExecuteEx (&shellex);
546         if (ret == FALSE) {
547                 process_info->pid = -GetLastError ();
548         } else {
549                 process_info->process_handle = shellex.hProcess;
550                 process_info->thread_handle = NULL;
551                 /* It appears that there's no way to get the pid from a
552                  * process handle before windows xp.  Really.
553                  */
554 #if defined(HAVE_GETPROCESSID) && !defined(MONO_CROSS_COMPILE)
555                 process_info->pid = GetProcessId (shellex.hProcess);
556 #else
557                 process_info->pid = 0;
558 #endif
559                 process_info->tid = 0;
560         }
561
562         return (ret);
563 }
564
565 MonoBoolean ves_icall_System_Diagnostics_Process_CreateProcess_internal (MonoProcessStartInfo *proc_start_info, HANDLE stdin_handle, HANDLE stdout_handle, HANDLE stderr_handle, MonoProcInfo *process_info)
566 {
567         gboolean ret;
568         gunichar2 *dir;
569         STARTUPINFO startinfo={0};
570         PROCESS_INFORMATION procinfo;
571         gunichar2 *shell_path = NULL;
572         gchar *env_vars = NULL;
573         gboolean free_shell_path = TRUE;
574         gchar *spath = NULL;
575         MonoString *cmd = proc_start_info->arguments;
576         guint32 creation_flags, logon_flags;
577         
578         startinfo.cb=sizeof(STARTUPINFO);
579         startinfo.dwFlags=STARTF_USESTDHANDLES;
580         startinfo.hStdInput=stdin_handle;
581         startinfo.hStdOutput=stdout_handle;
582         startinfo.hStdError=stderr_handle;
583
584         creation_flags = CREATE_UNICODE_ENVIRONMENT;
585         if (proc_start_info->create_no_window)
586                 creation_flags |= CREATE_NO_WINDOW;
587         
588         shell_path = mono_string_chars (proc_start_info->filename);
589         complete_path (shell_path, &spath);
590         if (spath == NULL) {
591                 process_info->pid = -ERROR_FILE_NOT_FOUND;
592                 return FALSE;
593         }
594 #ifdef TARGET_WIN32
595         /* Seems like our CreateProcess does not work as the windows one.
596          * This hack is needed to deal with paths containing spaces */
597         shell_path = NULL;
598         free_shell_path = FALSE;
599         if (cmd) {
600                 gchar *newcmd, *tmp;
601                 tmp = mono_string_to_utf8 (cmd);
602                 newcmd = g_strdup_printf ("%s %s", spath, tmp);
603                 cmd = mono_string_new_wrapper (newcmd);
604                 g_free (tmp);
605                 g_free (newcmd);
606         }
607         else {
608                 cmd = mono_string_new_wrapper (spath);
609         }
610 #else
611         shell_path = g_utf8_to_utf16 (spath, -1, NULL, NULL, NULL);
612 #endif
613         g_free (spath);
614
615         if (process_info->env_keys != NULL) {
616                 gint i, len; 
617                 MonoString *ms;
618                 MonoString *key, *value;
619                 gunichar2 *str, *ptr;
620                 gunichar2 *equals16;
621
622                 for (len = 0, i = 0; i < mono_array_length (process_info->env_keys); i++) {
623                         ms = mono_array_get (process_info->env_values, MonoString *, i);
624                         if (ms == NULL)
625                                 continue;
626
627                         len += mono_string_length (ms) * sizeof (gunichar2);
628                         ms = mono_array_get (process_info->env_keys, MonoString *, i);
629                         len += mono_string_length (ms) * sizeof (gunichar2);
630                         len += 2 * sizeof (gunichar2);
631                 }
632
633                 equals16 = g_utf8_to_utf16 ("=", 1, NULL, NULL, NULL);
634                 ptr = str = g_new0 (gunichar2, len + 1);
635                 for (i = 0; i < mono_array_length (process_info->env_keys); i++) {
636                         value = mono_array_get (process_info->env_values, MonoString *, i);
637                         if (value == NULL)
638                                 continue;
639
640                         key = mono_array_get (process_info->env_keys, MonoString *, i);
641                         memcpy (ptr, mono_string_chars (key), mono_string_length (key) * sizeof (gunichar2));
642                         ptr += mono_string_length (key);
643
644                         memcpy (ptr, equals16, sizeof (gunichar2));
645                         ptr++;
646
647                         memcpy (ptr, mono_string_chars (value), mono_string_length (value) * sizeof (gunichar2));
648                         ptr += mono_string_length (value);
649                         ptr++;
650                 }
651
652                 g_free (equals16);
653                 env_vars = (gchar *) str;
654         }
655         
656         /* The default dir name is "".  Turn that into NULL to mean
657          * "current directory"
658          */
659         if(proc_start_info->working_directory == NULL || mono_string_length (proc_start_info->working_directory)==0) {
660                 dir=NULL;
661         } else {
662                 dir=mono_string_chars (proc_start_info->working_directory);
663         }
664
665         if (process_info->username) {
666                 logon_flags = process_info->load_user_profile ? LOGON_WITH_PROFILE : 0;
667                 ret=CreateProcessWithLogonW (mono_string_chars (process_info->username), process_info->domain ? mono_string_chars (process_info->domain) : NULL, process_info->password, logon_flags, shell_path, cmd? mono_string_chars (cmd): NULL, creation_flags, env_vars, dir, &startinfo, &procinfo);
668         } else {
669                 ret=CreateProcess (shell_path, cmd? mono_string_chars (cmd): NULL, NULL, NULL, TRUE, creation_flags, env_vars, dir, &startinfo, &procinfo);
670         }
671
672         g_free (env_vars);
673         if (free_shell_path)
674                 g_free (shell_path);
675
676         if(ret) {
677                 process_info->process_handle=procinfo.hProcess;
678                 /*process_info->thread_handle=procinfo.hThread;*/
679                 process_info->thread_handle=NULL;
680                 if (procinfo.hThread != NULL && procinfo.hThread != INVALID_HANDLE_VALUE)
681                         CloseHandle(procinfo.hThread);
682                 process_info->pid=procinfo.dwProcessId;
683                 process_info->tid=procinfo.dwThreadId;
684         } else {
685                 process_info->pid = -GetLastError ();
686         }
687         
688         return(ret);
689 }
690
691 MonoBoolean ves_icall_System_Diagnostics_Process_WaitForExit_internal (MonoObject *this, HANDLE process, gint32 ms)
692 {
693         guint32 ret;
694         
695         if(ms<0) {
696                 /* Wait forever */
697                 ret=WaitForSingleObjectEx (process, INFINITE, TRUE);
698         } else {
699                 ret=WaitForSingleObjectEx (process, ms, TRUE);
700         }
701         if(ret==WAIT_OBJECT_0) {
702                 return(TRUE);
703         } else {
704                 return(FALSE);
705         }
706 }
707
708 MonoBoolean ves_icall_System_Diagnostics_Process_WaitForInputIdle_internal (MonoObject *this, HANDLE process, gint32 ms)
709 {
710         guint32 ret;
711         
712         if(ms<0) {
713                 /* Wait forever */
714                 ret=WaitForInputIdle (process, INFINITE);
715         } else {
716                 ret=WaitForInputIdle (process, ms);
717         }
718
719         return (ret) ? FALSE : TRUE;
720 }
721
722 static guint64
723 file_time_to_guint64 (FILETIME *time)
724 {
725         return ((guint64)time->dwHighDateTime << 32) | ((guint64)time->dwLowDateTime);
726 }
727
728 gint64 ves_icall_System_Diagnostics_Process_ExitTime_internal (HANDLE process)
729 {
730         gboolean ret;
731         FILETIME create_time, exit_time, kernel_time, user_time;
732         
733         ret = GetProcessTimes (process, &create_time, &exit_time, &kernel_time,
734                                                    &user_time);
735         if (ret)
736                 return file_time_to_guint64 (&exit_time);
737         else
738                 return 0;
739 }
740
741 gint64 ves_icall_System_Diagnostics_Process_StartTime_internal (HANDLE process)
742 {
743         gboolean ret;
744         FILETIME create_time, exit_time, kernel_time, user_time;
745         
746         ret = GetProcessTimes (process, &create_time, &exit_time, &kernel_time,
747                                                    &user_time);
748         if (ret)
749                 return file_time_to_guint64 (&create_time);
750         else
751                 return 0;
752 }
753
754 gint32 ves_icall_System_Diagnostics_Process_ExitCode_internal (HANDLE process)
755 {
756         DWORD code;
757         
758         GetExitCodeProcess (process, &code);
759         
760         LOGDEBUG (g_message ("%s: process exit code is %d", __func__, code));
761         
762         return(code);
763 }
764
765 MonoString *ves_icall_System_Diagnostics_Process_ProcessName_internal (HANDLE process)
766 {
767         MonoString *string;
768         gboolean ok;
769         HMODULE mod;
770         gunichar2 name[MAX_PATH];
771         DWORD needed;
772         guint32 len;
773         
774         ok=EnumProcessModules (process, &mod, sizeof(mod), &needed);
775         if(ok==FALSE) {
776                 return(NULL);
777         }
778         
779         len=GetModuleBaseName (process, mod, name, MAX_PATH);
780         if(len==0) {
781                 return(NULL);
782         }
783         
784         LOGDEBUG (g_message ("%s: process name is [%s]", __func__, g_utf16_to_utf8 (name, -1, NULL, NULL, NULL)));
785         
786         string=mono_string_new_utf16 (mono_domain_get (), name, len);
787         
788         return(string);
789 }
790
791 /* Returns an array of pids */
792 MonoArray *
793 ves_icall_System_Diagnostics_Process_GetProcesses_internal (void)
794 {
795 #if !defined(HOST_WIN32)
796         MonoArray *procs;
797         gpointer *pidarray;
798         int i, count;
799
800         pidarray = mono_process_list (&count);
801         if (!pidarray) {
802                 mono_set_pending_exception (mono_get_exception_not_supported ("This system does not support EnumProcesses"));
803                 return NULL;
804         }
805         procs = mono_array_new (mono_domain_get (), mono_get_int32_class (), count);
806         if (sizeof (guint32) == sizeof (gpointer)) {
807                 memcpy (mono_array_addr (procs, guint32, 0), pidarray, count);
808         } else {
809                 for (i = 0; i < count; ++i)
810                         *(mono_array_addr (procs, guint32, i)) = GPOINTER_TO_UINT (pidarray [i]);
811         }
812         g_free (pidarray);
813
814         return procs;
815 #else
816         MonoArray *procs;
817         gboolean ret;
818         DWORD needed;
819         int count;
820         guint32 *pids;
821
822         count = 512;
823         do {
824                 pids = g_new0 (guint32, count);
825                 ret = EnumProcesses (pids, count * sizeof (guint32), &needed);
826                 if (ret == FALSE) {
827                         MonoException *exc;
828
829                         g_free (pids);
830                         pids = NULL;
831                         exc = mono_get_exception_not_supported ("This system does not support EnumProcesses");
832                         mono_set_pending_exception (exc);
833                         return NULL;
834                 }
835                 if (needed < (count * sizeof (guint32)))
836                         break;
837                 g_free (pids);
838                 pids = NULL;
839                 count = (count * 3) / 2;
840         } while (TRUE);
841
842         count = needed / sizeof (guint32);
843         procs = mono_array_new (mono_domain_get (), mono_get_int32_class (), count);
844         memcpy (mono_array_addr (procs, guint32, 0), pids, needed);
845         g_free (pids);
846         pids = NULL;
847         
848         return procs;
849 #endif
850 }
851
852 MonoBoolean ves_icall_System_Diagnostics_Process_GetWorkingSet_internal (HANDLE process, guint32 *min, guint32 *max)
853 {
854         gboolean ret;
855         SIZE_T ws_min, ws_max;
856         
857         ret=GetProcessWorkingSetSize (process, &ws_min, &ws_max);
858         *min=(guint32)ws_min;
859         *max=(guint32)ws_max;
860         
861         return(ret);
862 }
863
864 MonoBoolean ves_icall_System_Diagnostics_Process_SetWorkingSet_internal (HANDLE process, guint32 min, guint32 max, MonoBoolean use_min)
865 {
866         gboolean ret;
867         SIZE_T ws_min;
868         SIZE_T ws_max;
869         
870         ret=GetProcessWorkingSetSize (process, &ws_min, &ws_max);
871         if(ret==FALSE) {
872                 return(FALSE);
873         }
874         
875         if(use_min==TRUE) {
876                 ws_min=(SIZE_T)min;
877         } else {
878                 ws_max=(SIZE_T)max;
879         }
880         
881         ret=SetProcessWorkingSetSize (process, ws_min, ws_max);
882
883         return(ret);
884 }
885
886 MonoBoolean
887 ves_icall_System_Diagnostics_Process_Kill_internal (HANDLE process, gint32 sig)
888 {
889         /* sig == 1 -> Kill, sig == 2 -> CloseMainWindow */
890
891         return TerminateProcess (process, -sig);
892 }
893
894 gint64
895 ves_icall_System_Diagnostics_Process_Times (HANDLE process, gint32 type)
896 {
897         FILETIME create_time, exit_time, kernel_time, user_time;
898         
899         if (GetProcessTimes (process, &create_time, &exit_time, &kernel_time, &user_time)) {
900                 guint64 ktime = file_time_to_guint64 (&kernel_time);
901                 guint64 utime = file_time_to_guint64 (&user_time);
902
903                 if (type == 0)
904                         return utime;
905                 else if (type == 1)
906                         return ktime;
907                 else
908                         return ktime + utime;
909         }
910         return 0;
911 }
912
913 gint32
914 ves_icall_System_Diagnostics_Process_GetPriorityClass (HANDLE process, gint32 *error)
915 {
916         gint32 ret = GetPriorityClass (process);
917         *error = ret == 0 ? GetLastError () : 0;
918         return ret;
919 }
920
921 MonoBoolean
922 ves_icall_System_Diagnostics_Process_SetPriorityClass (HANDLE process, gint32 priority_class, gint32 *error)
923 {
924         gboolean ret = SetPriorityClass (process, priority_class);
925         *error = ret == 0 ? GetLastError () : 0;
926         return ret;
927 }
928
929 HANDLE
930 ves_icall_System_Diagnostics_Process_ProcessHandle_duplicate (HANDLE process)
931 {
932         HANDLE ret;
933
934         LOGDEBUG (g_message ("%s: Duplicating process handle %p", __func__, process));
935         
936         DuplicateHandle (GetCurrentProcess (), process, GetCurrentProcess (),
937                          &ret, THREAD_ALL_ACCESS, TRUE, 0);
938         
939         return ret;
940 }
941
942 void
943 ves_icall_System_Diagnostics_Process_ProcessHandle_close (HANDLE process)
944 {
945         LOGDEBUG (g_message ("%s: Closing process handle %p", __func__, process));
946
947         CloseHandle (process);
948 }
949
950 gint64
951 ves_icall_System_Diagnostics_Process_GetProcessData (int pid, gint32 data_type, gint32 *error)
952 {
953         MonoProcessError perror;
954         guint64 res;
955
956         res = mono_process_get_data_with_error (GINT_TO_POINTER (pid), data_type, &perror);
957         if (error)
958                 *error = perror;
959         return res;
960 }
961