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