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