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