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