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