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