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