Merge pull request #3755 from kumpera/async-reader-hardering-2
[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
493         stash_system_assembly (this_obj);
494
495         if (GetProcessId (process) == mono_process_current_pid ()) {
496                 assemblies = get_domain_assemblies (mono_domain_get ());
497                 assembly_count = assemblies->len;
498         }
499
500         if (EnumProcessModules (process, mods, sizeof(mods), &needed)) {
501                 module_count += needed / sizeof(HMODULE);
502         }
503
504         count = module_count + assembly_count; 
505         temp_arr = mono_array_new_checked (mono_domain_get (), mono_class_get_process_module_class (), count, &error);
506         if (mono_error_set_pending_exception (&error))
507                 return NULL;
508
509         for (i = 0; i < module_count; i++) {
510                 if (GetModuleBaseName (process, mods[i], modname, MAX_PATH) &&
511                                 GetModuleFileNameEx (process, mods[i], filename, MAX_PATH)) {
512                         MonoObject *module = process_add_module (process, mods[i],
513                                                                                                          filename, modname, mono_class_get_process_module_class (), &error);
514                         if (!mono_error_ok (&error)) {
515                                 mono_error_set_pending_exception (&error);
516                                 return NULL;
517                         }
518                         mono_array_setref (temp_arr, num_added++, module);
519                 }
520         }
521
522         if (assemblies) {
523                 for (i = 0; i < assembly_count; i++) {
524                         MonoAssembly *ass = (MonoAssembly *)g_ptr_array_index (assemblies, i);
525                         MonoObject *module = get_process_module (ass, mono_class_get_process_module_class (), &error);
526                         if (!mono_error_ok (&error)) {
527                                 mono_error_set_pending_exception (&error);
528                                 return NULL;
529                         }
530                         mono_array_setref (temp_arr, num_added++, module);
531                 }
532                 g_ptr_array_free (assemblies, TRUE);
533         }
534
535         if (count == num_added) {
536                 arr = temp_arr;
537         } else {
538                 /* shorter version of the array */
539                 arr = mono_array_new_checked (mono_domain_get (), mono_class_get_process_module_class (), num_added, &error);
540                 if (mono_error_set_pending_exception (&error))
541                         return NULL;
542
543                 for (i = 0; i < num_added; i++)
544                         mono_array_setref (arr, i, mono_array_get (temp_arr, MonoObject*, i));
545         }
546
547         return arr;
548 }
549
550 void
551 ves_icall_System_Diagnostics_FileVersionInfo_GetVersionInfo_internal (MonoObject *this_obj, MonoString *filename)
552 {
553         MonoError error;
554
555         stash_system_assembly (this_obj);
556         
557         process_get_fileversion (this_obj, mono_string_chars (filename), &error);
558         if (!mono_error_ok (&error)) {
559                 mono_error_set_pending_exception (&error);
560                 return;
561         }
562         process_set_field_string (this_obj, "filename",
563                                                           mono_string_chars (filename),
564                                                           mono_string_length (filename), &error);
565         if (!mono_error_ok (&error)) {
566                 mono_error_set_pending_exception (&error);
567                 return;
568         }
569 }
570
571 /* Only used when UseShellExecute is false */
572 static gchar *
573 quote_path (const gchar *path)
574 {
575         gchar *res = g_shell_quote (path);
576 #ifdef TARGET_WIN32
577         {
578         gchar *q = res;
579         while (*q) {
580                 if (*q == '\'')
581                         *q = '\"';
582                 q++;
583         }
584         }
585 #endif
586         return res;
587 }
588
589 /* Only used when UseShellExecute is false */
590 static gboolean
591 complete_path (const gunichar2 *appname, gchar **completed)
592 {
593         gchar *utf8app, *utf8appmemory;
594         gchar *found;
595
596         utf8appmemory = utf8app = g_utf16_to_utf8 (appname, -1, NULL, NULL, NULL);
597 #ifdef TARGET_WIN32 // Should this happen on all platforms? 
598         {
599                 // remove the quotes around utf8app.
600                 size_t len;
601                 len = strlen (utf8app);
602                 if (len) {
603                         if (utf8app[len-1] == '\"')
604                                 utf8app[len-1] = '\0';
605                         if (utf8app[0] == '\"')
606                                 utf8app++;
607                 }
608         }
609 #endif
610
611         if (g_path_is_absolute (utf8app)) {
612                 *completed = quote_path (utf8app);
613                 g_free (utf8appmemory);
614                 return TRUE;
615         }
616
617         if (g_file_test (utf8app, G_FILE_TEST_IS_EXECUTABLE) && !g_file_test (utf8app, G_FILE_TEST_IS_DIR)) {
618                 *completed = quote_path (utf8app);
619                 g_free (utf8appmemory);
620                 return TRUE;
621         }
622         
623         found = g_find_program_in_path (utf8app);
624         if (found == NULL) {
625                 *completed = NULL;
626                 g_free (utf8appmemory);
627                 return FALSE;
628         }
629
630         *completed = quote_path (found);
631         g_free (found);
632         g_free (utf8appmemory);
633         return TRUE;
634 }
635
636 MonoBoolean
637 ves_icall_System_Diagnostics_Process_ShellExecuteEx_internal (MonoProcessStartInfo *proc_start_info, MonoProcInfo *process_info)
638 {
639         SHELLEXECUTEINFO shellex = {0};
640         gboolean ret;
641
642         shellex.cbSize = sizeof(SHELLEXECUTEINFO);
643         shellex.fMask = (gulong)(SEE_MASK_FLAG_DDEWAIT | SEE_MASK_NOCLOSEPROCESS | SEE_MASK_UNICODE);
644         shellex.nShow = (gulong)proc_start_info->window_style;
645         shellex.nShow = (gulong)((shellex.nShow == 0) ? 1 : (shellex.nShow == 1 ? 0 : shellex.nShow));
646
647         if (proc_start_info->filename != NULL) {
648                 shellex.lpFile = mono_string_chars (proc_start_info->filename);
649         }
650
651         if (proc_start_info->arguments != NULL) {
652                 shellex.lpParameters = mono_string_chars (proc_start_info->arguments);
653         }
654
655         if (proc_start_info->verb != NULL &&
656             mono_string_length (proc_start_info->verb) != 0) {
657                 shellex.lpVerb = mono_string_chars (proc_start_info->verb);
658         }
659
660         if (proc_start_info->working_directory != NULL &&
661             mono_string_length (proc_start_info->working_directory) != 0) {
662                 shellex.lpDirectory = mono_string_chars (proc_start_info->working_directory);
663         }
664
665         if (proc_start_info->error_dialog) {    
666                 shellex.hwnd = proc_start_info->error_dialog_parent_handle;
667         } else {
668                 shellex.fMask = (gulong)(shellex.fMask | SEE_MASK_FLAG_NO_UI);
669         }
670
671         ret = ShellExecuteEx (&shellex);
672         if (ret == FALSE) {
673                 process_info->pid = -GetLastError ();
674         } else {
675                 process_info->process_handle = shellex.hProcess;
676                 process_info->thread_handle = NULL;
677 #if !defined(MONO_CROSS_COMPILE)
678                 process_info->pid = GetProcessId (shellex.hProcess);
679 #else
680                 process_info->pid = 0;
681 #endif
682                 process_info->tid = 0;
683         }
684
685         return ret;
686 }
687
688 MonoBoolean
689 ves_icall_System_Diagnostics_Process_CreateProcess_internal (MonoProcessStartInfo *proc_start_info, HANDLE stdin_handle, HANDLE stdout_handle, HANDLE stderr_handle, MonoProcInfo *process_info)
690 {
691         MonoError error G_GNUC_UNUSED;
692         gboolean ret;
693         gunichar2 *dir;
694         STARTUPINFO startinfo={0};
695         PROCESS_INFORMATION procinfo;
696         gunichar2 *shell_path = NULL;
697         gchar *env_vars = NULL;
698         gboolean free_shell_path = TRUE;
699         gchar *spath = NULL;
700         MonoString *cmd = proc_start_info->arguments;
701         guint32 creation_flags, logon_flags;
702         
703         startinfo.cb = sizeof(STARTUPINFO);
704         startinfo.dwFlags = STARTF_USESTDHANDLES;
705         startinfo.hStdInput = stdin_handle;
706         startinfo.hStdOutput = stdout_handle;
707         startinfo.hStdError = stderr_handle;
708
709         creation_flags = CREATE_UNICODE_ENVIRONMENT;
710         if (proc_start_info->create_no_window)
711                 creation_flags |= CREATE_NO_WINDOW;
712         
713         shell_path = mono_string_chars (proc_start_info->filename);
714         complete_path (shell_path, &spath);
715         if (spath == NULL) {
716                 process_info->pid = -ERROR_FILE_NOT_FOUND;
717                 return FALSE;
718         }
719 #ifdef TARGET_WIN32
720         /* Seems like our CreateProcess does not work as the windows one.
721          * This hack is needed to deal with paths containing spaces */
722         shell_path = NULL;
723         free_shell_path = FALSE;
724         if (cmd) {
725                 gchar *newcmd, *tmp;
726                 tmp = mono_string_to_utf8_checked (cmd, &error);
727                 if (mono_error_set_pending_exception (&error)) {
728                         g_free (spath);
729                         return NULL;
730                 }
731                 newcmd = g_strdup_printf ("%s %s", spath, tmp);
732                 cmd = mono_string_new_wrapper (newcmd);
733                 g_free (tmp);
734                 g_free (newcmd);
735         }
736         else {
737                 cmd = mono_string_new_wrapper (spath);
738         }
739 #else
740         shell_path = g_utf8_to_utf16 (spath, -1, NULL, NULL, NULL);
741 #endif
742         g_free (spath);
743
744         if (process_info->env_keys) {
745                 gint i, len; 
746                 MonoString *ms;
747                 MonoString *key, *value;
748                 gunichar2 *str, *ptr;
749                 gunichar2 *equals16;
750
751                 for (len = 0, i = 0; i < mono_array_length (process_info->env_keys); i++) {
752                         ms = mono_array_get (process_info->env_values, MonoString *, i);
753                         if (ms == NULL)
754                                 continue;
755
756                         len += mono_string_length (ms) * sizeof (gunichar2);
757                         ms = mono_array_get (process_info->env_keys, MonoString *, i);
758                         len += mono_string_length (ms) * sizeof (gunichar2);
759                         len += 2 * sizeof (gunichar2);
760                 }
761
762                 equals16 = g_utf8_to_utf16 ("=", 1, NULL, NULL, NULL);
763                 ptr = str = g_new0 (gunichar2, len + 1);
764                 for (i = 0; i < mono_array_length (process_info->env_keys); i++) {
765                         value = mono_array_get (process_info->env_values, MonoString *, i);
766                         if (value == NULL)
767                                 continue;
768
769                         key = mono_array_get (process_info->env_keys, MonoString *, i);
770                         memcpy (ptr, mono_string_chars (key), mono_string_length (key) * sizeof (gunichar2));
771                         ptr += mono_string_length (key);
772
773                         memcpy (ptr, equals16, sizeof (gunichar2));
774                         ptr++;
775
776                         memcpy (ptr, mono_string_chars (value), mono_string_length (value) * sizeof (gunichar2));
777                         ptr += mono_string_length (value);
778                         ptr++;
779                 }
780
781                 g_free (equals16);
782                 env_vars = (gchar *) str;
783         }
784         
785         /* The default dir name is "".  Turn that into NULL to mean
786          * "current directory"
787          */
788         if (proc_start_info->working_directory == NULL || mono_string_length (proc_start_info->working_directory) == 0)
789                 dir = NULL;
790         else
791                 dir = mono_string_chars (proc_start_info->working_directory);
792
793         if (process_info->username) {
794                 logon_flags = process_info->load_user_profile ? LOGON_WITH_PROFILE : 0;
795                 ret = CreateProcessWithLogonW (
796                         mono_string_chars (process_info->username),
797                         process_info->domain ? mono_string_chars (process_info->domain) : NULL,
798                         (const gunichar2 *)process_info->password, logon_flags, shell_path,
799                         cmd ? mono_string_chars (cmd) : NULL,
800                         creation_flags, env_vars, dir, &startinfo, &procinfo);
801         } else {
802                 ret = CreateProcess (shell_path, cmd ? mono_string_chars (cmd): NULL, NULL, NULL, TRUE, creation_flags, env_vars, dir, &startinfo, &procinfo);
803         }
804
805         g_free (env_vars);
806         if (free_shell_path)
807                 g_free (shell_path);
808
809         if (ret) {
810                 process_info->process_handle = procinfo.hProcess;
811                 /*process_info->thread_handle=procinfo.hThread;*/
812                 process_info->thread_handle = NULL;
813                 if (procinfo.hThread != NULL && procinfo.hThread != INVALID_HANDLE_VALUE)
814                         CloseHandle (procinfo.hThread);
815                 process_info->pid = procinfo.dwProcessId;
816                 process_info->tid = procinfo.dwThreadId;
817         } else {
818                 process_info->pid = -GetLastError ();
819         }
820         
821         return ret;
822 }
823
824 MonoString *
825 ves_icall_System_Diagnostics_Process_ProcessName_internal (HANDLE process)
826 {
827         MonoError error;
828         MonoString *string;
829         gboolean ok;
830         HMODULE mod;
831         gunichar2 name[MAX_PATH];
832         DWORD needed;
833         guint32 len;
834         
835         ok = EnumProcessModules (process, &mod, sizeof(mod), &needed);
836         if (!ok)
837                 return NULL;
838         
839         len = GetModuleBaseName (process, mod, name, MAX_PATH);
840         if (len == 0)
841                 return NULL;
842         
843         LOGDEBUG (g_message ("%s: process name is [%s]", __func__, g_utf16_to_utf8 (name, -1, NULL, NULL, NULL)));
844         
845         string = mono_string_new_utf16_checked (mono_domain_get (), name, len, &error);
846         if (!mono_error_ok (&error))
847                 mono_error_set_pending_exception (&error);
848         
849         return string;
850 }
851
852 /* Returns an array of pids */
853 MonoArray *
854 ves_icall_System_Diagnostics_Process_GetProcesses_internal (void)
855 {
856 #if !defined(HOST_WIN32)
857         MonoError error;
858         MonoArray *procs;
859         gpointer *pidarray;
860         int i, count;
861
862         pidarray = mono_process_list (&count);
863         if (!pidarray) {
864                 mono_set_pending_exception (mono_get_exception_not_supported ("This system does not support EnumProcesses"));
865                 return NULL;
866         }
867         procs = mono_array_new_checked (mono_domain_get (), mono_get_int32_class (), count, &error);
868         if (mono_error_set_pending_exception (&error)) {
869                 g_free (pidarray);
870                 return NULL;
871         }
872         if (sizeof (guint32) == sizeof (gpointer)) {
873                 memcpy (mono_array_addr (procs, guint32, 0), pidarray, count * sizeof (gint32));
874         } else {
875                 for (i = 0; i < count; ++i)
876                         *(mono_array_addr (procs, guint32, i)) = GPOINTER_TO_UINT (pidarray [i]);
877         }
878         g_free (pidarray);
879
880         return procs;
881 #else
882         MonoError error;
883         MonoArray *procs;
884         gboolean ret;
885         DWORD needed;
886         int count;
887         guint32 *pids;
888
889         count = 512;
890         do {
891                 pids = g_new0 (guint32, count);
892                 ret = EnumProcesses (pids, count * sizeof (guint32), &needed);
893                 if (ret == FALSE) {
894                         MonoException *exc;
895
896                         g_free (pids);
897                         pids = NULL;
898                         exc = mono_get_exception_not_supported ("This system does not support EnumProcesses");
899                         mono_set_pending_exception (exc);
900                         return NULL;
901                 }
902                 if (needed < (count * sizeof (guint32)))
903                         break;
904                 g_free (pids);
905                 pids = NULL;
906                 count = (count * 3) / 2;
907         } while (TRUE);
908
909         count = needed / sizeof (guint32);
910         procs = mono_array_new_checked (mono_domain_get (), mono_get_int32_class (), count, &error);
911         if (mono_error_set_pending_exception (&error)) {
912                 g_free (pids);
913                 return NULL;
914         }
915
916         memcpy (mono_array_addr (procs, guint32, 0), pids, needed);
917         g_free (pids);
918         pids = NULL;
919         
920         return procs;
921 #endif
922 }
923
924 gint64
925 ves_icall_System_Diagnostics_Process_GetProcessData (int pid, gint32 data_type, gint32 *error)
926 {
927         MonoProcessError perror;
928         guint64 res;
929
930         res = mono_process_get_data_with_error (GINT_TO_POINTER (pid), (MonoProcessData)data_type, &perror);
931         if (error)
932                 *error = perror;
933         return res;
934 }