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