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