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