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