Merge pull request #5714 from alexischr/update_bockbuild
[mono.git] / mono / metadata / w32process-unix.c
1 /**
2  * \file
3  * System.Diagnostics.Process support
4  *
5  * Author:
6  *      Dick Porter (dick@ximian.com)
7  *
8  * Copyright 2002 Ximian, Inc.
9  * Copyright 2002-2006 Novell, Inc.
10  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
11  */
12
13 #include <config.h>
14 #include <glib.h>
15
16 #include <stdio.h>
17 #include <string.h>
18 #include <pthread.h>
19 #include <sched.h>
20 #include <sys/time.h>
21 #include <errno.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <unistd.h>
25 #ifdef HAVE_SIGNAL_H
26 #include <signal.h>
27 #endif
28 #include <sys/time.h>
29 #include <fcntl.h>
30 #ifdef HAVE_SYS_PARAM_H
31 #include <sys/param.h>
32 #endif
33 #include <ctype.h>
34
35 #ifdef HAVE_SYS_WAIT_H
36 #include <sys/wait.h>
37 #endif
38 #ifdef HAVE_SYS_RESOURCE_H
39 #include <sys/resource.h>
40 #endif
41
42 #ifdef HAVE_SYS_MKDEV_H
43 #include <sys/mkdev.h>
44 #endif
45
46 #ifdef HAVE_UTIME_H
47 #include <utime.h>
48 #endif
49
50 #include <mono/metadata/w32process.h>
51 #include <mono/metadata/w32process-internals.h>
52 #include <mono/metadata/w32process-unix-internals.h>
53 #include <mono/metadata/w32error.h>
54 #include <mono/metadata/class.h>
55 #include <mono/metadata/class-internals.h>
56 #include <mono/metadata/object.h>
57 #include <mono/metadata/object-internals.h>
58 #include <mono/metadata/metadata.h>
59 #include <mono/metadata/metadata-internals.h>
60 #include <mono/metadata/exception.h>
61 #include <mono/metadata/w32handle.h>
62 #include <mono/metadata/w32file.h>
63 #include <mono/utils/mono-membar.h>
64 #include <mono/utils/mono-logger-internals.h>
65 #include <mono/utils/strenc.h>
66 #include <mono/utils/mono-proclib.h>
67 #include <mono/utils/mono-path.h>
68 #include <mono/utils/mono-lazy-init.h>
69 #include <mono/utils/mono-signal-handler.h>
70 #include <mono/utils/mono-time.h>
71 #include <mono/utils/mono-mmap.h>
72 #include <mono/utils/strenc.h>
73 #include <mono/utils/mono-io-portability.h>
74 #include <mono/utils/w32api.h>
75
76 #ifndef MAXPATHLEN
77 #define MAXPATHLEN 242
78 #endif
79
80 #define STILL_ACTIVE ((int) 0x00000103)
81
82 #define LOGDEBUG(...)
83 /* define LOGDEBUG(...) g_message(__VA_ARGS__)  */
84
85 /* The process' environment strings */
86 #if defined(__APPLE__)
87 #if defined (TARGET_OSX)
88 /* Apple defines this in crt_externs.h but doesn't provide that header for 
89  * arm-apple-darwin9.  We'll manually define the symbol on Apple as it does
90  * in fact exist on all implementations (so far) 
91  */
92 gchar ***_NSGetEnviron(void);
93 #define environ (*_NSGetEnviron())
94 #else
95 static char *mono_environ[1] = { NULL };
96 #define environ mono_environ
97 #endif /* defined (TARGET_OSX) */
98 #else
99 extern char **environ;
100 #endif
101
102 typedef enum {
103         STARTF_USESHOWWINDOW=0x001,
104         STARTF_USESIZE=0x002,
105         STARTF_USEPOSITION=0x004,
106         STARTF_USECOUNTCHARS=0x008,
107         STARTF_USEFILLATTRIBUTE=0x010,
108         STARTF_RUNFULLSCREEN=0x020,
109         STARTF_FORCEONFEEDBACK=0x040,
110         STARTF_FORCEOFFFEEDBACK=0x080,
111         STARTF_USESTDHANDLES=0x100
112 } StartupFlags;
113
114 typedef struct {
115         gpointer input;
116         gpointer output;
117         gpointer error;
118 } StartupHandles;
119
120 typedef struct {
121 #if G_BYTE_ORDER == G_BIG_ENDIAN
122         guint32 highDateTime;
123         guint32 lowDateTime;
124 #else
125         guint32 lowDateTime;
126         guint32 highDateTime;
127 #endif
128 } ProcessTime;
129
130 /*
131  * Process describes processes we create.
132  * It contains a semaphore that can be waited on in order to wait
133  * for process termination.
134  */
135 typedef struct _Process {
136         pid_t pid; /* the pid of the process. This value is only valid until the process has exited. */
137         MonoSemType exit_sem; /* this semaphore will be released when the process exits */
138         int status; /* the exit status */
139         gint32 handle_count; /* the number of handles to this process instance */
140         /* we keep a ref to the creating _WapiHandle_process handle until
141          * the process has exited, so that the information there isn't lost.
142          */
143         gpointer handle;
144         gboolean signalled;
145         struct _Process *next;
146 } Process;
147
148 /* MonoW32HandleProcess is a structure containing all the required information for process handling. */
149 typedef struct {
150         pid_t pid;
151         gboolean child;
152         guint32 exitstatus;
153         gpointer main_thread;
154         guint64 create_time;
155         guint64 exit_time;
156         char *pname;
157         size_t min_working_set;
158         size_t max_working_set;
159         gboolean exited;
160         Process *process;
161 } MonoW32HandleProcess;
162
163 /*
164  * VS_VERSIONINFO:
165  *
166  * 2 bytes: Length in bytes (this block, and all child blocks. does _not_ include alignment padding between blocks)
167  * 2 bytes: Length in bytes of VS_FIXEDFILEINFO struct
168  * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
169  * Variable length unicode string (null terminated): Key (currently "VS_VERSION_INFO")
170  * Variable length padding to align VS_FIXEDFILEINFO on a 32-bit boundary
171  * VS_FIXEDFILEINFO struct
172  * Variable length padding to align Child struct on a 32-bit boundary
173  * Child struct (zero or one StringFileInfo structs, zero or one VarFileInfo structs)
174  */
175
176 /*
177  * StringFileInfo:
178  *
179  * 2 bytes: Length in bytes (includes this block, as well as all Child blocks)
180  * 2 bytes: Value length (always zero)
181  * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
182  * Variable length unicode string: Key (currently "StringFileInfo")
183  * Variable length padding to align Child struct on a 32-bit boundary
184  * Child structs ( one or more StringTable structs.  Each StringTable struct's Key member indicates the appropriate language and code page for displaying the text in that StringTable struct.)
185  */
186
187 /*
188  * StringTable:
189  *
190  * 2 bytes: Length in bytes (includes this block as well as all Child blocks, but excludes any padding between String blocks)
191  * 2 bytes: Value length (always zero)
192  * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
193  * Variable length unicode string: Key. An 8-digit hex number stored as a unicode string.  The four most significant digits represent the language identifier.  The four least significant digits represent the code page for which the data is formatted.
194  * Variable length padding to align Child struct on a 32-bit boundary
195  * Child structs (an array of one or more String structs (each aligned on a 32-bit boundary)
196  */
197
198 /*
199  * String:
200  *
201  * 2 bytes: Length in bytes (of this block)
202  * 2 bytes: Value length (the length in words of the Value member)
203  * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
204  * Variable length unicode string: Key. arbitrary string, identifies data.
205  * Variable length padding to align Value on a 32-bit boundary
206  * Value: Variable length unicode string, holding data.
207  */
208
209 /*
210  * VarFileInfo:
211  *
212  * 2 bytes: Length in bytes (includes this block, as well as all Child blocks)
213  * 2 bytes: Value length (always zero)
214  * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
215  * Variable length unicode string: Key (currently "VarFileInfo")
216  * Variable length padding to align Child struct on a 32-bit boundary
217  * Child structs (a Var struct)
218  */
219
220 /*
221  * Var:
222  *
223  * 2 bytes: Length in bytes of this block
224  * 2 bytes: Value length in bytes of the Value
225  * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
226  * Variable length unicode string: Key ("Translation")
227  * Variable length padding to align Value on a 32-bit boundary
228  * Value: an array of one or more 4 byte values that are language and code page identifier pairs, low-order word containing a language identifier, and the high-order word containing a code page number.  Either word can be zero, indicating that the file is language or code page independent.
229  */
230
231 #if G_BYTE_ORDER == G_BIG_ENDIAN
232 #define VS_FFI_SIGNATURE        0xbd04effe
233 #define VS_FFI_STRUCVERSION     0x00000100
234 #else
235 #define VS_FFI_SIGNATURE        0xfeef04bd
236 #define VS_FFI_STRUCVERSION     0x00010000
237 #endif
238
239 #define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16
240
241 #define IMAGE_DIRECTORY_ENTRY_EXPORT    0
242 #define IMAGE_DIRECTORY_ENTRY_IMPORT    1
243 #define IMAGE_DIRECTORY_ENTRY_RESOURCE  2
244
245 #define IMAGE_SIZEOF_SHORT_NAME 8
246
247 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
248 #define IMAGE_DOS_SIGNATURE     0x4d5a
249 #define IMAGE_NT_SIGNATURE      0x50450000
250 #define IMAGE_NT_OPTIONAL_HDR32_MAGIC   0xb10
251 #define IMAGE_NT_OPTIONAL_HDR64_MAGIC   0xb20
252 #else
253 #define IMAGE_DOS_SIGNATURE     0x5a4d
254 #define IMAGE_NT_SIGNATURE      0x00004550
255 #define IMAGE_NT_OPTIONAL_HDR32_MAGIC   0x10b
256 #define IMAGE_NT_OPTIONAL_HDR64_MAGIC   0x20b
257 #endif
258
259 typedef struct {
260         guint16 e_magic;
261         guint16 e_cblp;
262         guint16 e_cp;
263         guint16 e_crlc;
264         guint16 e_cparhdr;
265         guint16 e_minalloc;
266         guint16 e_maxalloc;
267         guint16 e_ss;
268         guint16 e_sp;
269         guint16 e_csum;
270         guint16 e_ip;
271         guint16 e_cs;
272         guint16 e_lfarlc;
273         guint16 e_ovno;
274         guint16 e_res[4];
275         guint16 e_oemid;
276         guint16 e_oeminfo;
277         guint16 e_res2[10];
278         guint32 e_lfanew;
279 } IMAGE_DOS_HEADER;
280
281 typedef struct {
282         guint16 Machine;
283         guint16 NumberOfSections;
284         guint32 TimeDateStamp;
285         guint32 PointerToSymbolTable;
286         guint32 NumberOfSymbols;
287         guint16 SizeOfOptionalHeader;
288         guint16 Characteristics;
289 } IMAGE_FILE_HEADER;
290
291 typedef struct {
292         guint32 VirtualAddress;
293         guint32 Size;
294 } IMAGE_DATA_DIRECTORY;
295
296 typedef struct {
297         guint16 Magic;
298         guint8 MajorLinkerVersion;
299         guint8 MinorLinkerVersion;
300         guint32 SizeOfCode;
301         guint32 SizeOfInitializedData;
302         guint32 SizeOfUninitializedData;
303         guint32 AddressOfEntryPoint;
304         guint32 BaseOfCode;
305         guint32 BaseOfData;
306         guint32 ImageBase;
307         guint32 SectionAlignment;
308         guint32 FileAlignment;
309         guint16 MajorOperatingSystemVersion;
310         guint16 MinorOperatingSystemVersion;
311         guint16 MajorImageVersion;
312         guint16 MinorImageVersion;
313         guint16 MajorSubsystemVersion;
314         guint16 MinorSubsystemVersion;
315         guint32 Win32VersionValue;
316         guint32 SizeOfImage;
317         guint32 SizeOfHeaders;
318         guint32 CheckSum;
319         guint16 Subsystem;
320         guint16 DllCharacteristics;
321         guint32 SizeOfStackReserve;
322         guint32 SizeOfStackCommit;
323         guint32 SizeOfHeapReserve;
324         guint32 SizeOfHeapCommit;
325         guint32 LoaderFlags;
326         guint32 NumberOfRvaAndSizes;
327         IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
328 } IMAGE_OPTIONAL_HEADER32;
329
330 typedef struct {
331         guint16 Magic;
332         guint8 MajorLinkerVersion;
333         guint8 MinorLinkerVersion;
334         guint32 SizeOfCode;
335         guint32 SizeOfInitializedData;
336         guint32 SizeOfUninitializedData;
337         guint32 AddressOfEntryPoint;
338         guint32 BaseOfCode;
339         guint64 ImageBase;
340         guint32 SectionAlignment;
341         guint32 FileAlignment;
342         guint16 MajorOperatingSystemVersion;
343         guint16 MinorOperatingSystemVersion;
344         guint16 MajorImageVersion;
345         guint16 MinorImageVersion;
346         guint16 MajorSubsystemVersion;
347         guint16 MinorSubsystemVersion;
348         guint32 Win32VersionValue;
349         guint32 SizeOfImage;
350         guint32 SizeOfHeaders;
351         guint32 CheckSum;
352         guint16 Subsystem;
353         guint16 DllCharacteristics;
354         guint64 SizeOfStackReserve;
355         guint64 SizeOfStackCommit;
356         guint64 SizeOfHeapReserve;
357         guint64 SizeOfHeapCommit;
358         guint32 LoaderFlags;
359         guint32 NumberOfRvaAndSizes;
360         IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
361 } IMAGE_OPTIONAL_HEADER64;
362
363 #if SIZEOF_VOID_P == 8
364 typedef IMAGE_OPTIONAL_HEADER64 IMAGE_OPTIONAL_HEADER;
365 #else
366 typedef IMAGE_OPTIONAL_HEADER32 IMAGE_OPTIONAL_HEADER;
367 #endif
368
369 typedef struct {
370         guint32 Signature;
371         IMAGE_FILE_HEADER FileHeader;
372         IMAGE_OPTIONAL_HEADER32 OptionalHeader;
373 } IMAGE_NT_HEADERS32;
374
375 typedef struct {
376         guint32 Signature;
377         IMAGE_FILE_HEADER FileHeader;
378         IMAGE_OPTIONAL_HEADER64 OptionalHeader;
379 } IMAGE_NT_HEADERS64;
380
381 #if SIZEOF_VOID_P == 8
382 typedef IMAGE_NT_HEADERS64 IMAGE_NT_HEADERS;
383 #else
384 typedef IMAGE_NT_HEADERS32 IMAGE_NT_HEADERS;
385 #endif
386
387 typedef struct {
388         guint8 Name[IMAGE_SIZEOF_SHORT_NAME];
389         union {
390                 guint32 PhysicalAddress;
391                 guint32 VirtualSize;
392         } Misc;
393         guint32 VirtualAddress;
394         guint32 SizeOfRawData;
395         guint32 PointerToRawData;
396         guint32 PointerToRelocations;
397         guint32 PointerToLinenumbers;
398         guint16 NumberOfRelocations;
399         guint16 NumberOfLinenumbers;
400         guint32 Characteristics;
401 } IMAGE_SECTION_HEADER;
402
403 #define IMAGE_FIRST_SECTION32(header) ((IMAGE_SECTION_HEADER *)((gsize)(header) + G_STRUCT_OFFSET (IMAGE_NT_HEADERS32, OptionalHeader) + GUINT16_FROM_LE (((IMAGE_NT_HEADERS32 *)(header))->FileHeader.SizeOfOptionalHeader)))
404
405 #define RT_CURSOR       0x01
406 #define RT_BITMAP       0x02
407 #define RT_ICON         0x03
408 #define RT_MENU         0x04
409 #define RT_DIALOG       0x05
410 #define RT_STRING       0x06
411 #define RT_FONTDIR      0x07
412 #define RT_FONT         0x08
413 #define RT_ACCELERATOR  0x09
414 #define RT_RCDATA       0x0a
415 #define RT_MESSAGETABLE 0x0b
416 #define RT_GROUP_CURSOR 0x0c
417 #define RT_GROUP_ICON   0x0e
418 #define RT_VERSION      0x10
419 #define RT_DLGINCLUDE   0x11
420 #define RT_PLUGPLAY     0x13
421 #define RT_VXD          0x14
422 #define RT_ANICURSOR    0x15
423 #define RT_ANIICON      0x16
424 #define RT_HTML         0x17
425 #define RT_MANIFEST     0x18
426
427 typedef struct {
428         guint32 Characteristics;
429         guint32 TimeDateStamp;
430         guint16 MajorVersion;
431         guint16 MinorVersion;
432         guint16 NumberOfNamedEntries;
433         guint16 NumberOfIdEntries;
434 } IMAGE_RESOURCE_DIRECTORY;
435
436 typedef struct {
437         union {
438                 struct {
439 #if G_BYTE_ORDER == G_BIG_ENDIAN
440                         guint32 NameIsString:1;
441                         guint32 NameOffset:31;
442 #else
443                         guint32 NameOffset:31;
444                         guint32 NameIsString:1;
445 #endif
446                 };
447                 guint32 Name;
448 #if G_BYTE_ORDER == G_BIG_ENDIAN
449                 struct {
450                         guint16 __wapi_big_endian_padding;
451                         guint16 Id;
452                 };
453 #else
454                 guint16 Id;
455 #endif
456         };
457         union {
458                 guint32 OffsetToData;
459                 struct {
460 #if G_BYTE_ORDER == G_BIG_ENDIAN
461                         guint32 DataIsDirectory:1;
462                         guint32 OffsetToDirectory:31;
463 #else
464                         guint32 OffsetToDirectory:31;
465                         guint32 DataIsDirectory:1;
466 #endif
467                 };
468         };
469 } IMAGE_RESOURCE_DIRECTORY_ENTRY;
470
471 typedef struct {
472         guint32 OffsetToData;
473         guint32 Size;
474         guint32 CodePage;
475         guint32 Reserved;
476 } IMAGE_RESOURCE_DATA_ENTRY;
477
478 #define VOS_UNKNOWN             0x00000000
479 #define VOS_DOS                 0x00010000
480 #define VOS_OS216               0x00020000
481 #define VOS_OS232               0x00030000
482 #define VOS_NT                  0x00040000
483 #define VOS__BASE               0x00000000
484 #define VOS__WINDOWS16          0x00000001
485 #define VOS__PM16               0x00000002
486 #define VOS__PM32               0x00000003
487 #define VOS__WINDOWS32          0x00000004
488 /* Should "embrace and extend" here with some entries for linux etc */
489
490 #define VOS_DOS_WINDOWS16       0x00010001
491 #define VOS_DOS_WINDOWS32       0x00010004
492 #define VOS_OS216_PM16          0x00020002
493 #define VOS_OS232_PM32          0x00030003
494 #define VOS_NT_WINDOWS32        0x00040004
495
496 #define VFT_UNKNOWN             0x0000
497 #define VFT_APP                 0x0001
498 #define VFT_DLL                 0x0002
499 #define VFT_DRV                 0x0003
500 #define VFT_FONT                0x0004
501 #define VFT_VXD                 0x0005
502 #define VFT_STATIC_LIB          0x0007
503
504 #define VFT2_UNKNOWN            0x0000
505 #define VFT2_DRV_PRINTER        0x0001
506 #define VFT2_DRV_KEYBOARD       0x0002
507 #define VFT2_DRV_LANGUAGE       0x0003
508 #define VFT2_DRV_DISPLAY        0x0004
509 #define VFT2_DRV_MOUSE          0x0005
510 #define VFT2_DRV_NETWORK        0x0006
511 #define VFT2_DRV_SYSTEM         0x0007
512 #define VFT2_DRV_INSTALLABLE    0x0008
513 #define VFT2_DRV_SOUND          0x0009
514 #define VFT2_DRV_COMM           0x000a
515 #define VFT2_DRV_INPUTMETHOD    0x000b
516 #define VFT2_FONT_RASTER        0x0001
517 #define VFT2_FONT_VECTOR        0x0002
518 #define VFT2_FONT_TRUETYPE      0x0003
519
520 #define MAKELANGID(primary,secondary) ((guint16)((secondary << 10) | (primary)))
521
522 #define ALIGN32(ptr) ptr = (gpointer)((char *)ptr + 3); ptr = (gpointer)((char *)ptr - ((gsize)ptr & 3));
523
524 #if HAVE_SIGACTION
525 static mono_lazy_init_t process_sig_chld_once = MONO_LAZY_INIT_STATUS_NOT_INITIALIZED;
526 #endif
527
528 static gchar *cli_launcher;
529
530 static Process *processes;
531 static mono_mutex_t processes_mutex;
532
533 static pid_t current_pid;
534 static gpointer current_process;
535
536 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
537 static const gunichar2 *utf16_space = utf16_space_bytes;
538 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
539 static const gunichar2 *utf16_quote = utf16_quote_bytes;
540
541 /* Check if a pid is valid - i.e. if a process exists with this pid. */
542 static gboolean
543 process_is_alive (pid_t pid)
544 {
545 #if defined(HOST_WATCHOS)
546         return TRUE; // TODO: Rewrite using sysctl
547 #elif defined(HOST_DARWIN) || defined(__OpenBSD__) || defined(__FreeBSD__)
548         if (pid == 0)
549                 return FALSE;
550         if (kill (pid, 0) == 0)
551                 return TRUE;
552         if (errno == EPERM)
553                 return TRUE;
554         return FALSE;
555 #elif defined(__HAIKU__)
556         team_info teamInfo;
557         if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
558                 return TRUE;
559         return FALSE;
560 #else
561         gchar *dir = g_strdup_printf ("/proc/%d", pid);
562         gboolean result = access (dir, F_OK) == 0;
563         g_free (dir);
564         return result;
565 #endif
566 }
567
568 static void
569 process_details (gpointer data)
570 {
571         MonoW32HandleProcess *process_handle = (MonoW32HandleProcess *) data;
572         g_print ("pid: %d, exited: %s, exitstatus: %d",
573                 process_handle->pid, process_handle->exited ? "true" : "false", process_handle->exitstatus);
574 }
575
576 static const gchar*
577 process_typename (void)
578 {
579         return "Process";
580 }
581
582 static gsize
583 process_typesize (void)
584 {
585         return sizeof (MonoW32HandleProcess);
586 }
587
588 static MonoW32HandleWaitRet
589 process_wait (gpointer handle, guint32 timeout, gboolean *alerted)
590 {
591         MonoW32HandleProcess *process_handle;
592         pid_t pid G_GNUC_UNUSED, ret;
593         int status;
594         gint64 start, now;
595         Process *process;
596         gboolean res;
597
598         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %" G_GUINT32_FORMAT ")", __func__, handle, timeout);
599
600         if (alerted)
601                 *alerted = FALSE;
602
603         res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
604         if (!res) {
605                 g_warning ("%s: error looking up process handle %p", __func__, handle);
606                 return MONO_W32HANDLE_WAIT_RET_FAILED;
607         }
608
609         if (process_handle->exited) {
610                 /* We've already done this one */
611                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %" G_GUINT32_FORMAT "): Process already exited", __func__, handle, timeout);
612                 return MONO_W32HANDLE_WAIT_RET_SUCCESS_0;
613         }
614
615         pid = process_handle->pid;
616
617         if (pid == mono_process_current_pid ()) {
618                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %" G_GUINT32_FORMAT "): waiting on current process", __func__, handle, timeout);
619                 return MONO_W32HANDLE_WAIT_RET_TIMEOUT;
620         }
621
622         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %" G_GUINT32_FORMAT "): PID: %d", __func__, handle, timeout, pid);
623
624         if (!process_handle->child) {
625                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %" G_GUINT32_FORMAT "): waiting on non-child process", __func__, handle, timeout);
626
627                 if (!process_is_alive (pid)) {
628                         /* assume the process has exited */
629                         process_handle->exited = TRUE;
630                         process_handle->exitstatus = -1;
631                         mono_w32handle_set_signal_state (handle, TRUE, TRUE);
632
633                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %" G_GUINT32_FORMAT "): non-child process is not alive anymore (2)", __func__, handle, timeout);
634                         return MONO_W32HANDLE_WAIT_RET_SUCCESS_0;
635                 }
636
637                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %" G_GUINT32_FORMAT "): non-child process wait failed, error : %s (%d))", __func__, handle, timeout, g_strerror (errno), errno);
638                 return MONO_W32HANDLE_WAIT_RET_FAILED;
639         }
640
641         /* We don't need to lock processes here, the entry
642          * has a handle_count > 0 which means it will not be freed. */
643         process = process_handle->process;
644         g_assert (process);
645
646         start = mono_msec_ticks ();
647         now = start;
648
649         while (1) {
650                 if (timeout != MONO_INFINITE_WAIT) {
651                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %" G_GUINT32_FORMAT "): waiting on semaphore for %" G_GINT64_FORMAT " ms...",
652                                 __func__, handle, timeout, timeout - (now - start));
653                         ret = mono_os_sem_timedwait (&process->exit_sem, (timeout - (now - start)), alerted ? MONO_SEM_FLAGS_ALERTABLE : MONO_SEM_FLAGS_NONE);
654                 } else {
655                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %" G_GUINT32_FORMAT "): waiting on semaphore forever...",
656                                 __func__, handle, timeout);
657                         ret = mono_os_sem_wait (&process->exit_sem, alerted ? MONO_SEM_FLAGS_ALERTABLE : MONO_SEM_FLAGS_NONE);
658                 }
659
660                 if (ret == MONO_SEM_TIMEDWAIT_RET_SUCCESS) {
661                         /* Success, process has exited */
662                         mono_os_sem_post (&process->exit_sem);
663                         break;
664                 }
665
666                 if (ret == MONO_SEM_TIMEDWAIT_RET_TIMEDOUT) {
667                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %" G_GUINT32_FORMAT "): wait timeout (timeout = 0)", __func__, handle, timeout);
668                         return MONO_W32HANDLE_WAIT_RET_TIMEOUT;
669                 }
670
671                 now = mono_msec_ticks ();
672                 if (now - start >= timeout) {
673                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %" G_GUINT32_FORMAT "): wait timeout", __func__, handle, timeout);
674                         return MONO_W32HANDLE_WAIT_RET_TIMEOUT;
675                 }
676
677                 if (alerted && ret == MONO_SEM_TIMEDWAIT_RET_ALERTED) {
678                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %" G_GUINT32_FORMAT "): wait alerted", __func__, handle, timeout);
679                         *alerted = TRUE;
680                         return MONO_W32HANDLE_WAIT_RET_ALERTED;
681                 }
682         }
683
684         /* Process must have exited */
685         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %" G_GUINT32_FORMAT "): Waited successfully", __func__, handle, timeout);
686
687         status = process->status;
688         if (WIFSIGNALED (status))
689                 process_handle->exitstatus = 128 + WTERMSIG (status);
690         else
691                 process_handle->exitstatus = WEXITSTATUS (status);
692
693         process_handle->exit_time = mono_100ns_datetime ();
694
695         process_handle->exited = TRUE;
696
697         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %" G_GUINT32_FORMAT "): Setting pid %d signalled, exit status %d",
698                    __func__, handle, timeout, process_handle->pid, process_handle->exitstatus);
699
700         mono_w32handle_set_signal_state (handle, TRUE, TRUE);
701
702         return MONO_W32HANDLE_WAIT_RET_SUCCESS_0;
703 }
704
705 static void
706 processes_cleanup (void)
707 {
708         static gint32 cleaning_up;
709         Process *process;
710         Process *prev = NULL;
711
712         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s", __func__);
713
714         /* Ensure we're not in here in multiple threads at once, nor recursive. */
715         if (InterlockedCompareExchange (&cleaning_up, 1, 0) != 0)
716                 return;
717
718         /*
719          * This needs to be done outside the lock but atomically, hence the CAS above.
720          */
721         for (process = processes; process; process = process->next) {
722                 if (process->signalled && process->handle) {
723                         /* This process has exited and we need to remove the artifical ref
724                          * on the handle */
725                         mono_w32handle_close (process->handle);
726                         process->handle = NULL;
727                 }
728         }
729
730         mono_os_mutex_lock (&processes_mutex);
731
732         for (process = processes; process;) {
733                 Process *next = process->next;
734                 if (process->handle_count == 0 && process->signalled) {
735                         /*
736                          * Unlink the entry.
737                          */
738                         if (process == processes)
739                                 processes = process->next;
740                         else
741                                 prev->next = process->next;
742
743                         mono_os_sem_destroy (&process->exit_sem);
744                         g_free (process);
745                 } else {
746                         prev = process;
747                 }
748                 process = next;
749         }
750
751         mono_os_mutex_unlock (&processes_mutex);
752
753         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s done", __func__);
754
755         InterlockedExchange (&cleaning_up, 0);
756 }
757
758 static void
759 process_close (gpointer handle, gpointer data)
760 {
761         MonoW32HandleProcess *process_handle;
762
763         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s", __func__);
764
765         process_handle = (MonoW32HandleProcess *) data;
766         g_free (process_handle->pname);
767         process_handle->pname = NULL;
768         if (process_handle->process)
769                 InterlockedDecrement (&process_handle->process->handle_count);
770         processes_cleanup ();
771 }
772
773 static MonoW32HandleOps process_ops = {
774         process_close,          /* close_shared */
775         NULL,                           /* signal */
776         NULL,                           /* own */
777         NULL,                           /* is_owned */
778         process_wait,                   /* special_wait */
779         NULL,                           /* prewait */
780         process_details,        /* details */
781         process_typename,       /* typename */
782         process_typesize,       /* typesize */
783 };
784
785 static void
786 process_set_defaults (MonoW32HandleProcess *process_handle)
787 {
788         /* These seem to be the defaults on w2k */
789         process_handle->min_working_set = 204800;
790         process_handle->max_working_set = 1413120;
791
792         process_handle->create_time = mono_100ns_datetime ();
793 }
794
795 static void
796 process_set_name (MonoW32HandleProcess *process_handle)
797 {
798         char *progname, *utf8_progname, *slash;
799
800         progname = g_get_prgname ();
801         utf8_progname = mono_utf8_from_external (progname);
802
803         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: using [%s] as prog name", __func__, progname);
804
805         if (utf8_progname) {
806                 slash = strrchr (utf8_progname, '/');
807                 if (slash)
808                         process_handle->pname = g_strdup (slash+1);
809                 else
810                         process_handle->pname = g_strdup (utf8_progname);
811                 g_free (utf8_progname);
812         }
813 }
814
815 void
816 mono_w32process_init (void)
817 {
818         MonoW32HandleProcess process_handle;
819
820         mono_w32handle_register_ops (MONO_W32HANDLE_PROCESS, &process_ops);
821
822         mono_w32handle_register_capabilities (MONO_W32HANDLE_PROCESS,
823                 (MonoW32HandleCapability)(MONO_W32HANDLE_CAP_WAIT | MONO_W32HANDLE_CAP_SPECIAL_WAIT));
824
825         current_pid = getpid ();
826
827         memset (&process_handle, 0, sizeof (process_handle));
828         process_handle.pid = current_pid;
829         process_set_defaults (&process_handle);
830         process_set_name (&process_handle);
831
832         current_process = mono_w32handle_new (MONO_W32HANDLE_PROCESS, &process_handle);
833         g_assert (current_process != INVALID_HANDLE_VALUE);
834
835         mono_os_mutex_init (&processes_mutex);
836 }
837
838 void
839 mono_w32process_cleanup (void)
840 {
841         g_free (cli_launcher);
842 }
843
844 static int
845 len16 (const gunichar2 *str)
846 {
847         int len = 0;
848
849         while (*str++ != 0)
850                 len++;
851
852         return len;
853 }
854
855 static gunichar2 *
856 utf16_concat (const gunichar2 *first, ...)
857 {
858         va_list args;
859         int total = 0, i;
860         const gunichar2 *s;
861         const gunichar2 *p;
862         gunichar2 *ret;
863
864         va_start (args, first);
865         total += len16 (first);
866         for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *))
867                 total += len16 (s);
868         va_end (args);
869
870         ret = g_new (gunichar2, total + 1);
871         if (ret == NULL)
872                 return NULL;
873
874         ret [total] = 0;
875         i = 0;
876         for (s = first; *s != 0; s++)
877                 ret [i++] = *s;
878         va_start (args, first);
879         for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
880                 for (p = s; *p != 0; p++)
881                         ret [i++] = *p;
882         }
883         va_end (args);
884
885         return ret;
886 }
887
888 guint32
889 mono_w32process_get_pid (gpointer handle)
890 {
891         MonoW32HandleProcess *process_handle;
892         gboolean res;
893
894         res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
895         if (!res) {
896                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
897                 return 0;
898         }
899
900         return process_handle->pid;
901 }
902
903 typedef struct {
904         guint32 pid;
905         gpointer handle;
906 } GetProcessForeachData;
907
908 static gboolean
909 get_process_foreach_callback (gpointer handle, gpointer handle_specific, gpointer user_data)
910 {
911         GetProcessForeachData *foreach_data;
912         MonoW32HandleProcess *process_handle;
913         pid_t pid;
914
915         foreach_data = (GetProcessForeachData*) user_data;
916
917         if (mono_w32handle_get_type (handle) != MONO_W32HANDLE_PROCESS)
918                 return FALSE;
919
920         process_handle = (MonoW32HandleProcess*) handle_specific;
921
922         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking at process %d", __func__, process_handle->pid);
923
924         pid = process_handle->pid;
925         if (pid == 0)
926                 return FALSE;
927
928         /* It's possible to have more than one process handle with the
929          * same pid, but only the one running process can be
930          * unsignalled. */
931         if (foreach_data->pid != pid)
932                 return FALSE;
933         if (mono_w32handle_issignalled (handle))
934                 return FALSE;
935
936         foreach_data->handle = mono_w32handle_duplicate (handle);
937         return TRUE;
938 }
939
940 HANDLE
941 ves_icall_System_Diagnostics_Process_GetProcess_internal (guint32 pid)
942 {
943         GetProcessForeachData foreach_data;
944         gpointer handle;
945
946         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking for process %d", __func__, pid);
947
948         memset (&foreach_data, 0, sizeof (foreach_data));
949         foreach_data.pid = pid;
950         mono_w32handle_foreach (get_process_foreach_callback, &foreach_data);
951         handle = foreach_data.handle;
952         if (handle) {
953                 /* get_process_foreach_callback already added a ref */
954                 return handle;
955         }
956
957         if (process_is_alive (pid)) {
958                 /* non-child process */
959                 MonoW32HandleProcess process_handle;
960
961                 memset (&process_handle, 0, sizeof (process_handle));
962                 process_handle.pid = pid;
963                 process_handle.pname = mono_w32process_get_name (pid);
964
965                 handle = mono_w32handle_new (MONO_W32HANDLE_PROCESS, &process_handle);
966                 if (handle == INVALID_HANDLE_VALUE) {
967                         g_warning ("%s: error creating process handle", __func__);
968
969                         mono_w32error_set_last (ERROR_OUTOFMEMORY);
970                         return NULL;
971                 }
972
973                 return handle;
974         }
975
976         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find pid %d", __func__, pid);
977
978         mono_w32error_set_last (ERROR_PROC_NOT_FOUND);
979         return NULL;
980 }
981
982 static gboolean
983 match_procname_to_modulename (char *procname, char *modulename)
984 {
985         char* lastsep = NULL;
986         char* lastsep2 = NULL;
987         char* pname = NULL;
988         char* mname = NULL;
989         gboolean result = FALSE;
990
991         if (procname == NULL || modulename == NULL)
992                 return (FALSE);
993
994         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: procname=\"%s\", modulename=\"%s\"", __func__, procname, modulename);
995         pname = mono_path_resolve_symlinks (procname);
996         mname = mono_path_resolve_symlinks (modulename);
997
998         if (!strcmp (pname, mname))
999                 result = TRUE;
1000
1001         if (!result) {
1002                 lastsep = strrchr (mname, '/');
1003                 if (lastsep)
1004                         if (!strcmp (lastsep+1, pname))
1005                                 result = TRUE;
1006                 if (!result) {
1007                         lastsep2 = strrchr (pname, '/');
1008                         if (lastsep2){
1009                                 if (lastsep) {
1010                                         if (!strcmp (lastsep+1, lastsep2+1))
1011                                                 result = TRUE;
1012                                 } else {
1013                                         if (!strcmp (mname, lastsep2+1))
1014                                                 result = TRUE;
1015                                 }
1016                         }
1017                 }
1018         }
1019
1020         g_free (pname);
1021         g_free (mname);
1022
1023         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: result is %" G_GINT32_FORMAT, __func__, result);
1024         return result;
1025 }
1026
1027 gboolean
1028 mono_w32process_try_get_modules (gpointer process, gpointer *modules, guint32 size, guint32 *needed)
1029 {
1030         MonoW32HandleProcess *process_handle;
1031         GSList *mods = NULL, *mods_iter;
1032         MonoW32ProcessModule *module;
1033         guint32 count, avail = size / sizeof(gpointer);
1034         int i;
1035         pid_t pid;
1036         char *pname = NULL;
1037         gboolean res;
1038
1039         /* Store modules in an array of pointers (main module as
1040          * modules[0]), using the load address for each module as a
1041          * token.  (Use 'NULL' as an alternative for the main module
1042          * so that the simple implementation can just return one item
1043          * for now.)  Get the info from /proc/<pid>/maps on linux,
1044          * /proc/<pid>/map on FreeBSD, other systems will have to
1045          * implement /dev/kmem reading or whatever other horrid
1046          * technique is needed.
1047          */
1048         if (size < sizeof(gpointer))
1049                 return FALSE;
1050
1051         res = mono_w32handle_lookup (process, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
1052         if (!res) {
1053                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
1054                 return FALSE;
1055         }
1056
1057         pid = process_handle->pid;
1058         pname = g_strdup (process_handle->pname);
1059
1060         if (!pname) {
1061                 modules[0] = NULL;
1062                 *needed = sizeof(gpointer);
1063                 return TRUE;
1064         }
1065
1066         mods = mono_w32process_get_modules (pid);
1067         if (!mods) {
1068                 modules[0] = NULL;
1069                 *needed = sizeof(gpointer);
1070                 g_free (pname);
1071                 return TRUE;
1072         }
1073
1074         count = 0;
1075
1076         /*
1077          * Use the NULL shortcut, as the first line in
1078          * /proc/<pid>/maps isn't the executable, and we need
1079          * that first in the returned list. Check the module name
1080          * to see if it ends with the proc name and substitute
1081          * the first entry with it.  FIXME if this turns out to
1082          * be a problem.
1083          */
1084         modules[0] = NULL;
1085         mods_iter = mods;
1086         for (i = 0; mods_iter; i++) {
1087                 if (i < avail - 1) {
1088                         module = (MonoW32ProcessModule *)mods_iter->data;
1089                         if (modules[0] != NULL)
1090                                 modules[i] = module->address_start;
1091                         else if (match_procname_to_modulename (pname, module->filename))
1092                                 modules[0] = module->address_start;
1093                         else
1094                                 modules[i + 1] = module->address_start;
1095                 }
1096                 mono_w32process_module_free ((MonoW32ProcessModule *)mods_iter->data);
1097                 mods_iter = g_slist_next (mods_iter);
1098                 count++;
1099         }
1100
1101         /* count + 1 to leave slot 0 for the main module */
1102         *needed = sizeof(gpointer) * (count + 1);
1103
1104         g_slist_free (mods);
1105         g_free (pname);
1106
1107         return TRUE;
1108 }
1109
1110 guint32
1111 mono_w32process_module_get_filename (gpointer process, gpointer module, gunichar2 *basename, guint32 size)
1112 {
1113         gint pid, len;
1114         gsize bytes;
1115         gchar *path;
1116         gunichar2 *proc_path;
1117
1118         size *= sizeof (gunichar2); /* adjust for unicode characters */
1119
1120         if (basename == NULL || size == 0)
1121                 return 0;
1122
1123         pid = mono_w32process_get_pid (process);
1124
1125         path = mono_w32process_get_path (pid);
1126         if (path == NULL)
1127                 return 0;
1128
1129         proc_path = mono_unicode_from_external (path, &bytes);
1130         g_free (path);
1131
1132         if (proc_path == NULL)
1133                 return 0;
1134
1135         len = (bytes / 2);
1136
1137         /* Add the terminator */
1138         bytes += 2;
1139
1140         if (size < bytes) {
1141                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %" G_GUINT32_FORMAT " smaller than needed (%zd); truncating", __func__, size, bytes);
1142                 memcpy (basename, proc_path, size);
1143         } else {
1144                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %" G_GUINT32_FORMAT " larger than needed (%zd)", __func__, size, bytes);
1145                 memcpy (basename, proc_path, bytes);
1146         }
1147
1148         g_free (proc_path);
1149
1150         return len;
1151 }
1152
1153 guint32
1154 mono_w32process_module_get_name (gpointer process, gpointer module, gunichar2 *basename, guint32 size)
1155 {
1156         MonoW32HandleProcess *process_handle;
1157         pid_t pid;
1158         gunichar2 *procname;
1159         char *procname_ext = NULL;
1160         glong len;
1161         gsize bytes;
1162         GSList *mods = NULL, *mods_iter;
1163         MonoW32ProcessModule *found_module;
1164         char *pname = NULL;
1165         gboolean res;
1166
1167         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Getting module base name, process handle %p module %p basename %p size %" G_GUINT32_FORMAT,
1168                    __func__, process, module, basename, size);
1169
1170         size = size * sizeof (gunichar2); /* adjust for unicode characters */
1171
1172         if (basename == NULL || size == 0)
1173                 return 0;
1174
1175         res = mono_w32handle_lookup (process, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
1176         if (!res) {
1177                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
1178                 return 0;
1179         }
1180
1181         pid = process_handle->pid;
1182         pname = g_strdup (process_handle->pname);
1183
1184         mods = mono_w32process_get_modules (pid);
1185         if (!mods && module != NULL) {
1186                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't get modules %p", __func__, process);
1187                 g_free (pname);
1188                 return 0;
1189         }
1190
1191         /* If module != NULL compare the address.
1192          * If module == NULL we are looking for the main module.
1193          * The best we can do for now check it the module name end with the process name.
1194          */
1195         for (mods_iter = mods; mods_iter; mods_iter = g_slist_next (mods_iter)) {
1196                 found_module = (MonoW32ProcessModule *)mods_iter->data;
1197                 if (procname_ext == NULL &&
1198                         ((module == NULL && match_procname_to_modulename (pname, found_module->filename)) ||
1199                          (module != NULL && found_module->address_start == module))) {
1200                         procname_ext = g_path_get_basename (found_module->filename);
1201                 }
1202
1203                 mono_w32process_module_free (found_module);
1204         }
1205
1206         if (procname_ext == NULL) {
1207                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find procname_ext from procmods %p", __func__, process);
1208                 /* If it's *still* null, we might have hit the
1209                  * case where reading /proc/$pid/maps gives an
1210                  * empty file for this user.
1211                  */
1212                 procname_ext = mono_w32process_get_name (pid);
1213                 if (!procname_ext)
1214                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find procname_ext from proc_get_name %p pid %d", __func__, process, pid);
1215         }
1216
1217         g_slist_free (mods);
1218         g_free (pname);
1219
1220         if (procname_ext) {
1221                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Process name is [%s]", __func__,
1222                            procname_ext);
1223
1224                 procname = mono_unicode_from_external (procname_ext, &bytes);
1225                 if (procname == NULL) {
1226                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't get procname %p", __func__, process);
1227                         /* bugger */
1228                         g_free (procname_ext);
1229                         return 0;
1230                 }
1231
1232                 len = (bytes / 2);
1233
1234                 /* Add the terminator */
1235                 bytes += 2;
1236
1237                 if (size < bytes) {
1238                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %" G_GUINT32_FORMAT " smaller than needed (%zd); truncating", __func__, size, bytes);
1239
1240                         memcpy (basename, procname, size);
1241                 } else {
1242                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %" G_GUINT32_FORMAT " larger than needed (%zd)",
1243                                    __func__, size, bytes);
1244
1245                         memcpy (basename, procname, bytes);
1246                 }
1247
1248                 g_free (procname);
1249                 g_free (procname_ext);
1250
1251                 return len;
1252         }
1253
1254         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find procname_ext %p", __func__, process);
1255         return 0;
1256 }
1257
1258 gboolean
1259 mono_w32process_module_get_information (gpointer process, gpointer module, MODULEINFO *modinfo, guint32 size)
1260 {
1261         MonoW32HandleProcess *process_handle;
1262         pid_t pid;
1263         GSList *mods = NULL, *mods_iter;
1264         MonoW32ProcessModule *found_module;
1265         gboolean ret = FALSE;
1266         char *pname = NULL;
1267         gboolean res;
1268
1269         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Getting module info, process handle %p module %p",
1270                    __func__, process, module);
1271
1272         if (modinfo == NULL || size < sizeof (MODULEINFO))
1273                 return FALSE;
1274
1275         res = mono_w32handle_lookup (process, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
1276         if (!res) {
1277                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
1278                 return FALSE;
1279         }
1280
1281         pid = process_handle->pid;
1282         pname = g_strdup (process_handle->pname);
1283
1284         mods = mono_w32process_get_modules (pid);
1285         if (!mods) {
1286                 g_free (pname);
1287                 return FALSE;
1288         }
1289
1290         /* If module != NULL compare the address.
1291          * If module == NULL we are looking for the main module.
1292          * The best we can do for now check it the module name end with the process name.
1293          */
1294         for (mods_iter = mods; mods_iter; mods_iter = g_slist_next (mods_iter)) {
1295                         found_module = (MonoW32ProcessModule *)mods_iter->data;
1296                         if (ret == FALSE &&
1297                                 ((module == NULL && match_procname_to_modulename (pname, found_module->filename)) ||
1298                                  (module != NULL && found_module->address_start == module))) {
1299                                 modinfo->lpBaseOfDll = found_module->address_start;
1300                                 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
1301                                 modinfo->EntryPoint = found_module->address_offset;
1302                                 ret = TRUE;
1303                         }
1304
1305                         mono_w32process_module_free (found_module);
1306         }
1307
1308         g_slist_free (mods);
1309         g_free (pname);
1310
1311         return ret;
1312 }
1313
1314 static void
1315 switch_dir_separators (char *path)
1316 {
1317         size_t i, pathLength = strlen(path);
1318         
1319         /* Turn all the slashes round the right way, except for \' */
1320         /* There are probably other characters that need to be excluded as well. */
1321         for (i = 0; i < pathLength; i++) {
1322                 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' )
1323                         path[i] = '/';
1324         }
1325 }
1326
1327 #if HAVE_SIGACTION
1328
1329 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
1330 {
1331         /*
1332          * Don't want to do any complicated processing here so just wake up the finalizer thread which will call
1333          * mono_w32process_signal_finished ().
1334          */
1335         int old_errno = errno;
1336
1337         mono_gc_finalize_notify ();
1338
1339         errno = old_errno;
1340 }
1341
1342 static void
1343 process_add_sigchld_handler (void)
1344 {
1345         struct sigaction sa;
1346
1347         sa.sa_sigaction = mono_sigchld_signal_handler;
1348         sigemptyset (&sa.sa_mask);
1349         sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO | SA_RESTART;
1350         g_assert (sigaction (SIGCHLD, &sa, NULL) != -1);
1351         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "Added SIGCHLD handler");
1352 }
1353
1354 #endif
1355
1356 /*
1357  * mono_w32process_signal_finished:
1358  *
1359  *   Signal the exit semaphore for processes which have finished.
1360  */
1361 void
1362 mono_w32process_signal_finished (void)
1363 {
1364         int status;
1365         int pid;
1366         Process *process;
1367
1368         do {
1369                 do {
1370                         pid = waitpid (-1, &status, WNOHANG);
1371                 } while (pid == -1 && errno == EINTR);
1372
1373                 if (pid <= 0)
1374                         break;
1375
1376                 mono_os_mutex_lock (&processes_mutex);
1377
1378                 for (process = processes; process; process = process->next) {
1379                         if (process->pid != pid)
1380                                 continue;
1381                         if (process->signalled)
1382                                 continue;
1383
1384                         process->signalled = TRUE;
1385                         process->status = status;
1386                         mono_os_sem_post (&process->exit_sem);
1387                         break;
1388                 }
1389
1390                 mono_os_mutex_unlock (&processes_mutex);
1391         } while (1);
1392 }
1393
1394 static gboolean
1395 is_readable_or_executable (const char *prog)
1396 {
1397         struct stat buf;
1398         int a = access (prog, R_OK);
1399         int b = access (prog, X_OK);
1400         if (a != 0 && b != 0)
1401                 return FALSE;
1402         if (stat (prog, &buf))
1403                 return FALSE;
1404         if (S_ISREG (buf.st_mode))
1405                 return TRUE;
1406         return FALSE;
1407 }
1408
1409 static gboolean
1410 is_executable (const char *prog)
1411 {
1412         struct stat buf;
1413         if (access (prog, X_OK) != 0)
1414                 return FALSE;
1415         if (stat (prog, &buf))
1416                 return FALSE;
1417         if (S_ISREG (buf.st_mode))
1418                 return TRUE;
1419         return FALSE;
1420 }
1421
1422 static gboolean
1423 is_managed_binary (const char *filename)
1424 {
1425         int original_errno = errno;
1426 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
1427         int file = open (filename, O_RDONLY | O_LARGEFILE);
1428 #else
1429         int file = open (filename, O_RDONLY);
1430 #endif
1431         off_t new_offset;
1432         unsigned char buffer[8];
1433         off_t file_size, optional_header_offset;
1434         off_t pe_header_offset, clr_header_offset;
1435         gboolean managed = FALSE;
1436         int num_read;
1437         guint32 first_word, second_word, magic_number;
1438         
1439         /* If we are unable to open the file, then we definitely
1440          * can't say that it is managed. The child mono process
1441          * probably wouldn't be able to open it anyway.
1442          */
1443         if (file < 0) {
1444                 errno = original_errno;
1445                 return FALSE;
1446         }
1447
1448         /* Retrieve the length of the file for future sanity checks. */
1449         file_size = lseek (file, 0, SEEK_END);
1450         lseek (file, 0, SEEK_SET);
1451
1452         /* We know we need to read a header field at offset 60. */
1453         if (file_size < 64)
1454                 goto leave;
1455
1456         num_read = read (file, buffer, 2);
1457
1458         if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
1459                 goto leave;
1460
1461         new_offset = lseek (file, 60, SEEK_SET);
1462
1463         if (new_offset != 60)
1464                 goto leave;
1465         
1466         num_read = read (file, buffer, 4);
1467
1468         if (num_read != 4)
1469                 goto leave;
1470         pe_header_offset =  buffer[0]
1471                 | (buffer[1] <<  8)
1472                 | (buffer[2] << 16)
1473                 | (buffer[3] << 24);
1474         
1475         if (pe_header_offset + 24 > file_size)
1476                 goto leave;
1477
1478         new_offset = lseek (file, pe_header_offset, SEEK_SET);
1479
1480         if (new_offset != pe_header_offset)
1481                 goto leave;
1482
1483         num_read = read (file, buffer, 4);
1484
1485         if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
1486                 goto leave;
1487
1488         /*
1489          * Verify that the header we want in the optional header data
1490          * is present in this binary.
1491          */
1492         new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
1493
1494         if (new_offset != pe_header_offset + 20)
1495                 goto leave;
1496
1497         num_read = read (file, buffer, 2);
1498
1499         if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
1500                 goto leave;
1501
1502         optional_header_offset = pe_header_offset + 24;
1503
1504         /* Read the PE magic number */
1505         new_offset = lseek (file, optional_header_offset, SEEK_SET);
1506         
1507         if (new_offset != optional_header_offset)
1508                 goto leave;
1509
1510         num_read = read (file, buffer, 2);
1511
1512         if (num_read != 2)
1513                 goto leave;
1514
1515         magic_number = (buffer[0] | (buffer[1] << 8));
1516         
1517         if (magic_number == 0x10B)  // PE32
1518                 clr_header_offset = 208;
1519         else if (magic_number == 0x20B)  // PE32+
1520                 clr_header_offset = 224;
1521         else
1522                 goto leave;
1523
1524         /* Read the CLR header address and size fields. These will be
1525          * zero if the binary is not managed.
1526          */
1527         new_offset = lseek (file, optional_header_offset + clr_header_offset, SEEK_SET);
1528
1529         if (new_offset != optional_header_offset + clr_header_offset)
1530                 goto leave;
1531
1532         num_read = read (file, buffer, 8);
1533         
1534         /* We are not concerned with endianness, only with
1535          * whether it is zero or not.
1536          */
1537         first_word = *(guint32 *)&buffer[0];
1538         second_word = *(guint32 *)&buffer[4];
1539         
1540         if ((num_read != 8) || (first_word == 0) || (second_word == 0))
1541                 goto leave;
1542         
1543         managed = TRUE;
1544
1545 leave:
1546         close (file);
1547         errno = original_errno;
1548         return managed;
1549 }
1550
1551 static gboolean
1552 process_create (const gunichar2 *appname, const gunichar2 *cmdline,
1553         const gunichar2 *cwd, StartupHandles *startup_handles, MonoW32ProcessInfo *process_info)
1554 {
1555 #if defined (HAVE_FORK) && defined (HAVE_EXECVE)
1556         char *cmd = NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL;
1557         char *dir = NULL, **env_strings = NULL, **argv = NULL;
1558         guint32 i;
1559         gboolean ret = FALSE;
1560         gpointer handle = NULL;
1561         GError *gerr = NULL;
1562         int in_fd, out_fd, err_fd;
1563         pid_t pid = 0;
1564         int startup_pipe [2] = {-1, -1};
1565         int dummy;
1566         Process *process;
1567
1568 #if HAVE_SIGACTION
1569         mono_lazy_initialize (&process_sig_chld_once, process_add_sigchld_handler);
1570 #endif
1571
1572         /* appname and cmdline specify the executable and its args:
1573          *
1574          * If appname is not NULL, it is the name of the executable.
1575          * Otherwise the executable is the first token in cmdline.
1576          *
1577          * Executable searching:
1578          *
1579          * If appname is not NULL, it can specify the full path and
1580          * file name, or else a partial name and the current directory
1581          * will be used.  There is no additional searching.
1582          *
1583          * If appname is NULL, the first whitespace-delimited token in
1584          * cmdline is used.  If the name does not contain a full
1585          * directory path, the search sequence is:
1586          *
1587          * 1) The directory containing the current process
1588          * 2) The current working directory
1589          * 3) The windows system directory  (Ignored)
1590          * 4) The windows directory (Ignored)
1591          * 5) $PATH
1592          *
1593          * Just to make things more interesting, tokens can contain
1594          * white space if they are surrounded by quotation marks.  I'm
1595          * beginning to understand just why windows apps are generally
1596          * so crap, with an API like this :-(
1597          */
1598         if (appname != NULL) {
1599                 cmd = mono_unicode_to_external (appname);
1600                 if (cmd == NULL) {
1601                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL",
1602                                    __func__);
1603
1604                         mono_w32error_set_last (ERROR_PATH_NOT_FOUND);
1605                         goto free_strings;
1606                 }
1607
1608                 switch_dir_separators(cmd);
1609         }
1610
1611         if (cmdline != NULL) {
1612                 args = mono_unicode_to_external (cmdline);
1613                 if (args == NULL) {
1614                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1615
1616                         mono_w32error_set_last (ERROR_PATH_NOT_FOUND);
1617                         goto free_strings;
1618                 }
1619         }
1620
1621         if (cwd != NULL) {
1622                 dir = mono_unicode_to_external (cwd);
1623                 if (dir == NULL) {
1624                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1625
1626                         mono_w32error_set_last (ERROR_PATH_NOT_FOUND);
1627                         goto free_strings;
1628                 }
1629
1630                 /* Turn all the slashes round the right way */
1631                 switch_dir_separators(dir);
1632         }
1633
1634
1635         /* We can't put off locating the executable any longer :-( */
1636         if (cmd != NULL) {
1637                 char *unquoted;
1638                 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
1639                         /* Strip off the drive letter.  I can't
1640                          * believe that CP/M holdover is still
1641                          * visible...
1642                          */
1643                         g_memmove (cmd, cmd+2, strlen (cmd)-2);
1644                         cmd[strlen (cmd)-2] = '\0';
1645                 }
1646
1647                 unquoted = g_shell_unquote (cmd, NULL);
1648                 if (unquoted[0] == '/') {
1649                         /* Assume full path given */
1650                         prog = g_strdup (unquoted);
1651
1652                         /* Executable existing ? */
1653                         if (!is_readable_or_executable (prog)) {
1654                                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s",
1655                                            __func__, prog);
1656                                 g_free (unquoted);
1657                                 mono_w32error_set_last (ERROR_FILE_NOT_FOUND);
1658                                 goto free_strings;
1659                         }
1660                 } else {
1661                         /* Search for file named by cmd in the current
1662                          * directory
1663                          */
1664                         char *curdir = g_get_current_dir ();
1665
1666                         prog = g_strdup_printf ("%s/%s", curdir, unquoted);
1667                         g_free (curdir);
1668
1669                         /* And make sure it's readable */
1670                         if (!is_readable_or_executable (prog)) {
1671                                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s",
1672                                            __func__, prog);
1673                                 g_free (unquoted);
1674                                 mono_w32error_set_last (ERROR_FILE_NOT_FOUND);
1675                                 goto free_strings;
1676                         }
1677                 }
1678                 g_free (unquoted);
1679
1680                 args_after_prog = args;
1681         } else {
1682                 char *token = NULL;
1683                 char quote;
1684
1685                 /* Dig out the first token from args, taking quotation
1686                  * marks into account
1687                  */
1688
1689                 /* First, strip off all leading whitespace */
1690                 args = g_strchug (args);
1691
1692                 /* args_after_prog points to the contents of args
1693                  * after token has been set (otherwise argv[0] is
1694                  * duplicated)
1695                  */
1696                 args_after_prog = args;
1697
1698                 /* Assume the opening quote will always be the first
1699                  * character
1700                  */
1701                 if (args[0] == '\"' || args [0] == '\'') {
1702                         quote = args [0];
1703                         for (i = 1; args[i] != '\0' && args[i] != quote; i++);
1704                         if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
1705                                 /* We found the first token */
1706                                 token = g_strndup (args+1, i-1);
1707                                 args_after_prog = g_strchug (args + i + 1);
1708                         } else {
1709                                 /* Quotation mark appeared in the
1710                                  * middle of the token.  Just give the
1711                                  * whole first token, quotes and all,
1712                                  * to exec.
1713                                  */
1714                         }
1715                 }
1716
1717                 if (token == NULL) {
1718                         /* No quote mark, or malformed */
1719                         for (i = 0; args[i] != '\0'; i++) {
1720                                 if (g_ascii_isspace (args[i])) {
1721                                         token = g_strndup (args, i);
1722                                         args_after_prog = args + i + 1;
1723                                         break;
1724                                 }
1725                         }
1726                 }
1727
1728                 if (token == NULL && args[0] != '\0') {
1729                         /* Must be just one token in the string */
1730                         token = g_strdup (args);
1731                         args_after_prog = NULL;
1732                 }
1733
1734                 if (token == NULL) {
1735                         /* Give up */
1736                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find what to exec", __func__);
1737
1738                         mono_w32error_set_last (ERROR_PATH_NOT_FOUND);
1739                         goto free_strings;
1740                 }
1741
1742                 /* Turn all the slashes round the right way. Only for
1743                  * the prg. name
1744                  */
1745                 switch_dir_separators(token);
1746
1747                 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
1748                         /* Strip off the drive letter.  I can't
1749                          * believe that CP/M holdover is still
1750                          * visible...
1751                          */
1752                         g_memmove (token, token+2, strlen (token)-2);
1753                         token[strlen (token)-2] = '\0';
1754                 }
1755
1756                 if (token[0] == '/') {
1757                         /* Assume full path given */
1758                         prog = g_strdup (token);
1759
1760                         /* Executable existing ? */
1761                         if (!is_readable_or_executable (prog)) {
1762                                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s",
1763                                            __func__, token);
1764                                 g_free (token);
1765                                 mono_w32error_set_last (ERROR_FILE_NOT_FOUND);
1766                                 goto free_strings;
1767                         }
1768                 } else {
1769                         char *curdir = g_get_current_dir ();
1770
1771                         /* FIXME: Need to record the directory
1772                          * containing the current process, and check
1773                          * that for the new executable as the first
1774                          * place to look
1775                          */
1776
1777                         prog = g_strdup_printf ("%s/%s", curdir, token);
1778                         g_free (curdir);
1779
1780                         /* I assume X_OK is the criterion to use,
1781                          * rather than F_OK
1782                          *
1783                          * X_OK is too strict *if* the target is a CLR binary
1784                          */
1785                         if (!is_readable_or_executable (prog)) {
1786                                 g_free (prog);
1787                                 prog = g_find_program_in_path (token);
1788                                 if (prog == NULL) {
1789                                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s", __func__, token);
1790
1791                                         g_free (token);
1792                                         mono_w32error_set_last (ERROR_FILE_NOT_FOUND);
1793                                         goto free_strings;
1794                                 }
1795                         }
1796                 }
1797
1798                 g_free (token);
1799         }
1800
1801         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Exec prog [%s] args [%s]",
1802                 __func__, prog, args_after_prog);
1803
1804         /* Check for CLR binaries; if found, we will try to invoke
1805          * them using the same mono binary that started us.
1806          */
1807         if (is_managed_binary (prog)) {
1808                 gunichar2 *newapp, *newcmd;
1809                 gsize bytes_ignored;
1810
1811                 newapp = mono_unicode_from_external (cli_launcher ? cli_launcher : "mono", &bytes_ignored);
1812                 if (newapp) {
1813                         if (appname)
1814                                 newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space, appname, utf16_space, cmdline, NULL);
1815                         else
1816                                 newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space, cmdline, NULL);
1817
1818                         g_free (newapp);
1819
1820                         if (newcmd) {
1821                                 ret = process_create (NULL, newcmd, cwd, startup_handles, process_info);
1822
1823                                 g_free (newcmd);
1824
1825                                 goto free_strings;
1826                         }
1827                 }
1828         } else {
1829                 if (!is_executable (prog)) {
1830                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Executable permisson not set on %s", __func__, prog);
1831                         mono_w32error_set_last (ERROR_ACCESS_DENIED);
1832                         goto free_strings;
1833                 }
1834         }
1835
1836         if (args_after_prog != NULL && *args_after_prog) {
1837                 char *qprog;
1838
1839                 qprog = g_shell_quote (prog);
1840                 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
1841                 g_free (qprog);
1842         } else {
1843                 full_prog = g_shell_quote (prog);
1844         }
1845
1846         ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
1847         if (ret == FALSE) {
1848                 g_message ("process_create: %s\n", gerr->message);
1849                 g_error_free (gerr);
1850                 gerr = NULL;
1851                 goto free_strings;
1852         }
1853
1854         if (startup_handles) {
1855                 in_fd = GPOINTER_TO_UINT (startup_handles->input);
1856                 out_fd = GPOINTER_TO_UINT (startup_handles->output);
1857                 err_fd = GPOINTER_TO_UINT (startup_handles->error);
1858         } else {
1859                 in_fd = GPOINTER_TO_UINT (mono_w32file_get_console_input ());
1860                 out_fd = GPOINTER_TO_UINT (mono_w32file_get_console_output ());
1861                 err_fd = GPOINTER_TO_UINT (mono_w32file_get_console_error ());
1862         }
1863
1864         /*
1865          * process->env_variables is a an array of MonoString*
1866          *
1867          * If new_environ is not NULL it specifies the entire set of
1868          * environment variables in the new process.  Otherwise the
1869          * new process inherits the same environment.
1870          */
1871         if (process_info->env_variables) {
1872                 gint i, str_length, var_length;
1873                 MonoString *var;
1874                 gunichar2 *str;
1875
1876                 /* +2: one for the process handle value, and the last one is NULL */
1877                 env_strings = g_new0 (gchar*, mono_array_length (process_info->env_variables) + 2);
1878
1879                 str = NULL;
1880                 str_length = 0;
1881
1882                 /* Copy each environ string into 'strings' turning it into utf8 (or the requested encoding) at the same time */
1883                 for (i = 0; i < mono_array_length (process_info->env_variables); ++i) {
1884                         var = mono_array_get (process_info->env_variables, MonoString*, i);
1885                         var_length = mono_string_length (var);
1886
1887                         /* str is a null-terminated copy of var */
1888
1889                         if (var_length + 1 > str_length) {
1890                                 str_length = var_length + 1;
1891                                 str = g_renew (gunichar2, str, str_length);
1892                         }
1893
1894                         memcpy (str, mono_string_chars (var), var_length * sizeof (gunichar2));
1895                         str [var_length] = '\0';
1896
1897                         env_strings [i] = mono_unicode_to_external (str);
1898                 }
1899
1900                 g_free (str);
1901         } else {
1902                 guint32 env_count;
1903
1904                 env_count = 0;
1905                 for (i = 0; environ[i] != NULL; i++)
1906                         env_count++;
1907
1908                 /* +2: one for the process handle value, and the last one is NULL */
1909                 env_strings = g_new0 (gchar*, env_count + 2);
1910
1911                 /* Copy each environ string into 'strings' turning it into utf8 (or the requested encoding) at the same time */
1912                 for (i = 0; i < env_count; i++)
1913                         env_strings [i] = g_strdup (environ[i]);
1914         }
1915
1916         /* Create a pipe to make sure the child doesn't exit before
1917          * we can add the process to the linked list of processes */
1918         if (pipe (startup_pipe) == -1) {
1919                 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
1920                  * This is just for a very hard to hit race condition in the first place */
1921                 startup_pipe [0] = startup_pipe [1] = -1;
1922                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
1923         }
1924
1925         switch (pid = fork ()) {
1926         case -1: /* Error */ {
1927                 mono_w32error_set_last (ERROR_OUTOFMEMORY);
1928                 ret = FALSE;
1929                 break;
1930         }
1931         case 0: /* Child */ {
1932                 if (startup_pipe [0] != -1) {
1933                         /* Wait until the parent has updated it's internal data */
1934                         ssize_t _i G_GNUC_UNUSED = read (startup_pipe [0], &dummy, 1);
1935                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: child: parent has completed its setup", __func__);
1936                         close (startup_pipe [0]);
1937                         close (startup_pipe [1]);
1938                 }
1939
1940                 /* should we detach from the process group? */
1941
1942                 /* Connect stdin, stdout and stderr */
1943                 dup2 (in_fd, 0);
1944                 dup2 (out_fd, 1);
1945                 dup2 (err_fd, 2);
1946
1947                 /* Close all file descriptors */
1948                 for (i = eg_getdtablesize() - 1; i > 2; i--)
1949                         close (i);
1950
1951 #ifdef DEBUG_ENABLED
1952                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1953                            dir == NULL?".":dir);
1954                 for (i = 0; argv[i] != NULL; i++)
1955                         g_message ("arg %" G_GUINT32_FORMAT ": [%s]", i, argv[i]);
1956
1957                 for (i = 0; env_strings[i] != NULL; i++)
1958                         g_message ("env %" G_GUINT32_FORMAT ": [%s]", i, env_strings[i]);
1959 #endif
1960
1961                 /* set cwd */
1962                 if (dir != NULL && chdir (dir) == -1) {
1963                         /* set error */
1964                         _exit (-1);
1965                 }
1966
1967                 /* exec */
1968                 execve (argv[0], argv, env_strings);
1969
1970                 /* set error */
1971                 _exit (-1);
1972
1973                 break;
1974         }
1975         default: /* Parent */ {
1976                 MonoW32HandleProcess process_handle;
1977
1978                 memset (&process_handle, 0, sizeof (process_handle));
1979                 process_handle.pid = pid;
1980                 process_handle.child = TRUE;
1981                 process_handle.pname = g_strdup (prog);
1982                 process_set_defaults (&process_handle);
1983
1984                 /* Add our process into the linked list of processes */
1985                 process = (Process *) g_malloc0 (sizeof (Process));
1986                 process->pid = pid;
1987                 process->handle_count = 1;
1988                 mono_os_sem_init (&process->exit_sem, 0);
1989
1990                 process_handle.process = process;
1991
1992                 handle = mono_w32handle_new (MONO_W32HANDLE_PROCESS, &process_handle);
1993                 if (handle == INVALID_HANDLE_VALUE) {
1994                         g_warning ("%s: error creating process handle", __func__);
1995
1996                         mono_os_sem_destroy (&process->exit_sem);
1997                         g_free (process);
1998
1999                         mono_w32error_set_last (ERROR_OUTOFMEMORY);
2000                         ret = FALSE;
2001                         break;
2002                 }
2003
2004                 /* Keep the process handle artificially alive until the process
2005                  * exits so that the information in the handle isn't lost. */
2006                 process->handle = mono_w32handle_duplicate (handle);
2007
2008                 mono_os_mutex_lock (&processes_mutex);
2009                 process->next = processes;
2010                 mono_memory_barrier ();
2011                 processes = process;
2012                 mono_os_mutex_unlock (&processes_mutex);
2013
2014                 if (process_info != NULL) {
2015                         process_info->process_handle = handle;
2016                         process_info->pid = pid;
2017
2018                         /* FIXME: we might need to handle the thread info some day */
2019                         process_info->thread_handle = INVALID_HANDLE_VALUE;
2020                         process_info->tid = 0;
2021                 }
2022
2023                 break;
2024         }
2025         }
2026
2027         if (startup_pipe [1] != -1) {
2028                 /* Write 1 byte, doesn't matter what */
2029                 ssize_t _i G_GNUC_UNUSED = write (startup_pipe [1], startup_pipe, 1);
2030                 close (startup_pipe [0]);
2031                 close (startup_pipe [1]);
2032         }
2033
2034 free_strings:
2035         if (cmd)
2036                 g_free (cmd);
2037         if (full_prog)
2038                 g_free (full_prog);
2039         if (prog)
2040                 g_free (prog);
2041         if (args)
2042                 g_free (args);
2043         if (dir)
2044                 g_free (dir);
2045         if (env_strings)
2046                 g_strfreev (env_strings);
2047         if (argv)
2048                 g_strfreev (argv);
2049
2050         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: returning handle %p for pid %d", __func__, handle, pid);
2051
2052         /* Check if something needs to be cleaned up. */
2053         processes_cleanup ();
2054
2055         return ret;
2056 #else
2057         mono_w32error_set_last (ERROR_NOT_SUPPORTED);
2058         return FALSE;
2059 #endif // defined (HAVE_FORK) && defined (HAVE_EXECVE)
2060 }
2061
2062 MonoBoolean
2063 ves_icall_System_Diagnostics_Process_ShellExecuteEx_internal (MonoW32ProcessStartInfo *proc_start_info, MonoW32ProcessInfo *process_info)
2064 {
2065         const gunichar2 *lpFile;
2066         const gunichar2 *lpParameters;
2067         const gunichar2 *lpDirectory;
2068         gunichar2 *args;
2069         gboolean ret;
2070
2071         if (!proc_start_info->filename) {
2072                 /* w2k returns TRUE for this, for some reason. */
2073                 ret = TRUE;
2074                 goto done;
2075         }
2076
2077         lpFile = proc_start_info->filename ? mono_string_chars (proc_start_info->filename) : NULL;
2078         lpParameters = proc_start_info->arguments ? mono_string_chars (proc_start_info->arguments) : NULL;
2079         lpDirectory = proc_start_info->working_directory && mono_string_length (proc_start_info->working_directory) != 0 ?
2080                 mono_string_chars (proc_start_info->working_directory) : NULL;
2081
2082         /* Put both executable and parameters into the second argument
2083          * to process_create (), so it searches $PATH.  The conversion
2084          * into and back out of utf8 is because there is no
2085          * g_strdup_printf () equivalent for gunichar2 :-(
2086          */
2087         args = utf16_concat (utf16_quote, lpFile, utf16_quote, lpParameters == NULL ? NULL : utf16_space, lpParameters, NULL);
2088         if (args == NULL) {
2089                 mono_w32error_set_last (ERROR_INVALID_DATA);
2090                 ret = FALSE;
2091                 goto done;
2092         }
2093         ret = process_create (NULL, args, lpDirectory, NULL, process_info);
2094         g_free (args);
2095
2096         if (!ret && mono_w32error_get_last () == ERROR_OUTOFMEMORY)
2097                 goto done;
2098
2099         if (!ret) {
2100                 static char *handler;
2101                 static gunichar2 *handler_utf16;
2102
2103                 if (handler_utf16 == (gunichar2 *)-1) {
2104                         ret = FALSE;
2105                         goto done;
2106                 }
2107
2108 #ifdef HOST_DARWIN
2109                 handler = g_strdup ("/usr/bin/open");
2110 #else
2111                 /*
2112                  * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
2113                  * if that fails, try to use gnome-open, then kfmclient
2114                  */
2115                 handler = g_find_program_in_path ("xdg-open");
2116                 if (handler == NULL){
2117                         handler = g_find_program_in_path ("gnome-open");
2118                         if (handler == NULL){
2119                                 handler = g_find_program_in_path ("kfmclient");
2120                                 if (handler == NULL){
2121                                         handler_utf16 = (gunichar2 *) -1;
2122                                         ret = FALSE;
2123                                         goto done;
2124                                 } else {
2125                                         /* kfmclient needs exec argument */
2126                                         char *old = handler;
2127                                         handler = g_strconcat (old, " exec",
2128                                                                NULL);
2129                                         g_free (old);
2130                                 }
2131                         }
2132                 }
2133 #endif
2134                 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
2135                 g_free (handler);
2136
2137                 /* Put quotes around the filename, in case it's a url
2138                  * that contains #'s (process_create() calls
2139                  * g_shell_parse_argv(), which deliberately throws
2140                  * away anything after an unquoted #).  Fixes bug
2141                  * 371567.
2142                  */
2143                 args = utf16_concat (handler_utf16, utf16_space, utf16_quote, lpFile, utf16_quote,
2144                         lpParameters == NULL ? NULL : utf16_space, lpParameters, NULL);
2145                 if (args == NULL) {
2146                         mono_w32error_set_last (ERROR_INVALID_DATA);
2147                         ret = FALSE;
2148                         goto done;
2149                 }
2150                 ret = process_create (NULL, args, lpDirectory, NULL, process_info);
2151                 g_free (args);
2152                 if (!ret) {
2153                         if (mono_w32error_get_last () != ERROR_OUTOFMEMORY)
2154                                 mono_w32error_set_last (ERROR_INVALID_DATA);
2155                         ret = FALSE;
2156                         goto done;
2157                 }
2158                 /* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
2159                 mono_w32handle_close (process_info->process_handle);
2160                 process_info->process_handle = NULL;
2161         }
2162
2163 done:
2164         if (ret == FALSE) {
2165                 process_info->pid = -mono_w32error_get_last ();
2166         } else {
2167                 process_info->thread_handle = NULL;
2168 #if !defined(MONO_CROSS_COMPILE)
2169                 process_info->pid = mono_w32process_get_pid (process_info->process_handle);
2170 #else
2171                 process_info->pid = 0;
2172 #endif
2173                 process_info->tid = 0;
2174         }
2175
2176         return ret;
2177 }
2178
2179 /* Only used when UseShellExecute is false */
2180 static gboolean
2181 process_get_complete_path (const gunichar2 *appname, gchar **completed)
2182 {
2183         gchar *utf8app;
2184         gchar *found;
2185
2186         utf8app = g_utf16_to_utf8 (appname, -1, NULL, NULL, NULL);
2187
2188         if (g_path_is_absolute (utf8app)) {
2189                 *completed = g_shell_quote (utf8app);
2190                 g_free (utf8app);
2191                 return TRUE;
2192         }
2193
2194         if (g_file_test (utf8app, G_FILE_TEST_IS_EXECUTABLE) && !g_file_test (utf8app, G_FILE_TEST_IS_DIR)) {
2195                 *completed = g_shell_quote (utf8app);
2196                 g_free (utf8app);
2197                 return TRUE;
2198         }
2199         
2200         found = g_find_program_in_path (utf8app);
2201         if (found == NULL) {
2202                 *completed = NULL;
2203                 g_free (utf8app);
2204                 return FALSE;
2205         }
2206
2207         *completed = g_shell_quote (found);
2208         g_free (found);
2209         g_free (utf8app);
2210         return TRUE;
2211 }
2212
2213 static gboolean
2214 process_get_shell_arguments (MonoW32ProcessStartInfo *proc_start_info, gunichar2 **shell_path)
2215 {
2216         gchar *complete_path = NULL;
2217
2218         *shell_path = NULL;
2219
2220         if (process_get_complete_path (mono_string_chars (proc_start_info->filename), &complete_path)) {
2221                 *shell_path = g_utf8_to_utf16 (complete_path, -1, NULL, NULL, NULL);
2222                 g_free (complete_path);
2223         }
2224
2225         return *shell_path != NULL;
2226 }
2227
2228 MonoBoolean
2229 ves_icall_System_Diagnostics_Process_CreateProcess_internal (MonoW32ProcessStartInfo *proc_start_info,
2230         HANDLE stdin_handle, HANDLE stdout_handle, HANDLE stderr_handle, MonoW32ProcessInfo *process_info)
2231 {
2232         gboolean ret;
2233         gunichar2 *dir;
2234         StartupHandles startup_handles;
2235         gunichar2 *shell_path = NULL;
2236         gunichar2 *args = NULL;
2237
2238         memset (&startup_handles, 0, sizeof (startup_handles));
2239         startup_handles.input = stdin_handle;
2240         startup_handles.output = stdout_handle;
2241         startup_handles.error = stderr_handle;
2242
2243         if (!process_get_shell_arguments (proc_start_info, &shell_path)) {
2244                 process_info->pid = -ERROR_FILE_NOT_FOUND;
2245                 return FALSE;
2246         }
2247
2248         args = proc_start_info->arguments && mono_string_length (proc_start_info->arguments) > 0 ?
2249                         mono_string_chars (proc_start_info->arguments): NULL;
2250
2251         /* The default dir name is "".  Turn that into NULL to mean "current directory" */
2252         dir = proc_start_info->working_directory && mono_string_length (proc_start_info->working_directory) > 0 ?
2253                         mono_string_chars (proc_start_info->working_directory) : NULL;
2254
2255         ret = process_create (shell_path, args, dir, &startup_handles, process_info);
2256
2257         if (shell_path != NULL)
2258                 g_free (shell_path);
2259
2260         if (!ret)
2261                 process_info->pid = -mono_w32error_get_last ();
2262
2263         return ret;
2264 }
2265
2266 /* Returns an array of pids */
2267 MonoArray *
2268 ves_icall_System_Diagnostics_Process_GetProcesses_internal (void)
2269 {
2270         MonoError error;
2271         MonoArray *procs;
2272         gpointer *pidarray;
2273         int i, count;
2274
2275         pidarray = mono_process_list (&count);
2276         if (!pidarray) {
2277                 mono_set_pending_exception (mono_get_exception_not_supported ("This system does not support EnumProcesses"));
2278                 return NULL;
2279         }
2280         procs = mono_array_new_checked (mono_domain_get (), mono_get_int32_class (), count, &error);
2281         if (mono_error_set_pending_exception (&error)) {
2282                 g_free (pidarray);
2283                 return NULL;
2284         }
2285         if (sizeof (guint32) == sizeof (gpointer)) {
2286                 memcpy (mono_array_addr (procs, guint32, 0), pidarray, count * sizeof (gint32));
2287         } else {
2288                 for (i = 0; i < count; ++i)
2289                         *(mono_array_addr (procs, guint32, i)) = GPOINTER_TO_UINT (pidarray [i]);
2290         }
2291         g_free (pidarray);
2292
2293         return procs;
2294 }
2295
2296 void
2297 mono_w32process_set_cli_launcher (gchar *path)
2298 {
2299         g_free (cli_launcher);
2300         cli_launcher = g_strdup (path);
2301 }
2302
2303 gpointer
2304 ves_icall_Microsoft_Win32_NativeMethods_GetCurrentProcess (void)
2305 {
2306         return current_process;
2307 }
2308
2309 MonoBoolean
2310 ves_icall_Microsoft_Win32_NativeMethods_GetExitCodeProcess (gpointer handle, gint32 *exitcode)
2311 {
2312         MonoW32HandleProcess *process_handle;
2313         gboolean res;
2314
2315         if (!exitcode)
2316                 return FALSE;
2317
2318         res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2319         if (!res) {
2320                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2321                 return FALSE;
2322         }
2323
2324         if (process_handle->pid == current_pid) {
2325                 *exitcode = STILL_ACTIVE;
2326                 return TRUE;
2327         }
2328
2329         /* A process handle is only signalled if the process has exited
2330          * and has been waited for. Make sure any process exit has been
2331          * noticed before checking if the process is signalled.
2332          * Fixes bug 325463. */
2333         mono_w32handle_wait_one (handle, 0, TRUE);
2334
2335         *exitcode = mono_w32handle_issignalled (handle) ? process_handle->exitstatus : STILL_ACTIVE;
2336         return TRUE;
2337 }
2338
2339 MonoBoolean
2340 ves_icall_Microsoft_Win32_NativeMethods_CloseProcess (gpointer handle)
2341 {
2342         return mono_w32handle_close (handle);
2343 }
2344
2345 MonoBoolean
2346 ves_icall_Microsoft_Win32_NativeMethods_TerminateProcess (gpointer handle, gint32 exitcode)
2347 {
2348 #ifdef HAVE_KILL
2349         MonoW32HandleProcess *process_handle;
2350         int ret;
2351         pid_t pid;
2352         gboolean res;
2353
2354         res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2355         if (!res) {
2356                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2357                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
2358                 return FALSE;
2359         }
2360
2361         pid = process_handle->pid;
2362
2363         ret = kill (pid, exitcode == -1 ? SIGKILL : SIGTERM);
2364         if (ret == 0)
2365                 return TRUE;
2366
2367         switch (errno) {
2368         case EINVAL: mono_w32error_set_last (ERROR_INVALID_PARAMETER); break;
2369         case EPERM:  mono_w32error_set_last (ERROR_ACCESS_DENIED);     break;
2370         case ESRCH:  mono_w32error_set_last (ERROR_PROC_NOT_FOUND);    break;
2371         default:     mono_w32error_set_last (ERROR_GEN_FAILURE);       break;
2372         }
2373
2374         return FALSE;
2375 #else
2376         g_error ("kill() is not supported by this platform");
2377 #endif
2378 }
2379
2380 MonoBoolean
2381 ves_icall_Microsoft_Win32_NativeMethods_GetProcessWorkingSetSize (gpointer handle, gsize *min, gsize *max)
2382 {
2383         MonoW32HandleProcess *process_handle;
2384         gboolean res;
2385
2386         if (!min || !max)
2387                 return FALSE;
2388
2389         res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2390         if (!res) {
2391                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2392                 return FALSE;
2393         }
2394
2395         if (!process_handle->child)
2396                 return FALSE;
2397
2398         *min = process_handle->min_working_set;
2399         *max = process_handle->max_working_set;
2400         return TRUE;
2401 }
2402
2403 MonoBoolean
2404 ves_icall_Microsoft_Win32_NativeMethods_SetProcessWorkingSetSize (gpointer handle, gsize min, gsize max)
2405 {
2406         MonoW32HandleProcess *process_handle;
2407         gboolean res;
2408
2409         res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2410         if (!res) {
2411                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2412                 return FALSE;
2413         }
2414
2415         if (!process_handle->child)
2416                 return FALSE;
2417
2418         process_handle->min_working_set = min;
2419         process_handle->max_working_set = max;
2420         return TRUE;
2421 }
2422
2423 gint32
2424 ves_icall_Microsoft_Win32_NativeMethods_GetPriorityClass (gpointer handle)
2425 {
2426 #ifdef HAVE_GETPRIORITY
2427         MonoW32HandleProcess *process_handle;
2428         gint ret;
2429         pid_t pid;
2430         gboolean res;
2431
2432         res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2433         if (!res) {
2434                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
2435                 return 0;
2436         }
2437
2438         pid = process_handle->pid;
2439
2440         errno = 0;
2441         ret = getpriority (PRIO_PROCESS, pid);
2442         if (ret == -1 && errno != 0) {
2443                 switch (errno) {
2444                 case EPERM:
2445                 case EACCES:
2446                         mono_w32error_set_last (ERROR_ACCESS_DENIED);
2447                         break;
2448                 case ESRCH:
2449                         mono_w32error_set_last (ERROR_PROC_NOT_FOUND);
2450                         break;
2451                 default:
2452                         mono_w32error_set_last (ERROR_GEN_FAILURE);
2453                 }
2454                 return 0;
2455         }
2456
2457         if (ret == 0)
2458                 return MONO_W32PROCESS_PRIORITY_CLASS_NORMAL;
2459         else if (ret < -15)
2460                 return MONO_W32PROCESS_PRIORITY_CLASS_REALTIME;
2461         else if (ret < -10)
2462                 return MONO_W32PROCESS_PRIORITY_CLASS_HIGH;
2463         else if (ret < 0)
2464                 return MONO_W32PROCESS_PRIORITY_CLASS_ABOVE_NORMAL;
2465         else if (ret > 10)
2466                 return MONO_W32PROCESS_PRIORITY_CLASS_IDLE;
2467         else if (ret > 0)
2468                 return MONO_W32PROCESS_PRIORITY_CLASS_BELOW_NORMAL;
2469
2470         return MONO_W32PROCESS_PRIORITY_CLASS_NORMAL;
2471 #else
2472         mono_w32error_set_last (ERROR_NOT_SUPPORTED);
2473         return 0;
2474 #endif
2475 }
2476
2477 MonoBoolean
2478 ves_icall_Microsoft_Win32_NativeMethods_SetPriorityClass (gpointer handle, gint32 priorityClass)
2479 {
2480 #ifdef HAVE_SETPRIORITY
2481         MonoW32HandleProcess *process_handle;
2482         int ret;
2483         int prio;
2484         pid_t pid;
2485         gboolean res;
2486
2487         res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2488         if (!res) {
2489                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
2490                 return FALSE;
2491         }
2492
2493         pid = process_handle->pid;
2494
2495         switch (priorityClass) {
2496         case MONO_W32PROCESS_PRIORITY_CLASS_IDLE:
2497                 prio = 19;
2498                 break;
2499         case MONO_W32PROCESS_PRIORITY_CLASS_BELOW_NORMAL:
2500                 prio = 10;
2501                 break;
2502         case MONO_W32PROCESS_PRIORITY_CLASS_NORMAL:
2503                 prio = 0;
2504                 break;
2505         case MONO_W32PROCESS_PRIORITY_CLASS_ABOVE_NORMAL:
2506                 prio = -5;
2507                 break;
2508         case MONO_W32PROCESS_PRIORITY_CLASS_HIGH:
2509                 prio = -11;
2510                 break;
2511         case MONO_W32PROCESS_PRIORITY_CLASS_REALTIME:
2512                 prio = -20;
2513                 break;
2514         default:
2515                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
2516                 return FALSE;
2517         }
2518
2519         ret = setpriority (PRIO_PROCESS, pid, prio);
2520         if (ret == -1) {
2521                 switch (errno) {
2522                 case EPERM:
2523                 case EACCES:
2524                         mono_w32error_set_last (ERROR_ACCESS_DENIED);
2525                         break;
2526                 case ESRCH:
2527                         mono_w32error_set_last (ERROR_PROC_NOT_FOUND);
2528                         break;
2529                 default:
2530                         mono_w32error_set_last (ERROR_GEN_FAILURE);
2531                 }
2532         }
2533
2534         return ret == 0;
2535 #else
2536         mono_w32error_set_last (ERROR_NOT_SUPPORTED);
2537         return FALSE;
2538 #endif
2539 }
2540
2541 static void
2542 ticks_to_processtime (guint64 ticks, ProcessTime *processtime)
2543 {
2544         processtime->lowDateTime = ticks & 0xFFFFFFFF;
2545         processtime->highDateTime = ticks >> 32;
2546 }
2547
2548 MonoBoolean
2549 ves_icall_Microsoft_Win32_NativeMethods_GetProcessTimes (gpointer handle, gint64 *creation_time, gint64 *exit_time, gint64 *kernel_time, gint64 *user_time)
2550 {
2551         MonoW32HandleProcess *process_handle;
2552         ProcessTime *creation_processtime, *exit_processtime, *kernel_processtime, *user_processtime;
2553         gboolean res;
2554
2555         if (!creation_time || !exit_time || !kernel_time || !user_time) {
2556                 /* Not sure if w32 allows NULLs here or not */
2557                 return FALSE;
2558         }
2559
2560         creation_processtime = (ProcessTime*) creation_time;
2561         exit_processtime = (ProcessTime*) exit_time;
2562         kernel_processtime = (ProcessTime*) kernel_time;
2563         user_processtime = (ProcessTime*) user_time;
2564
2565         memset (creation_processtime, 0, sizeof (ProcessTime));
2566         memset (exit_processtime, 0, sizeof (ProcessTime));
2567         memset (kernel_processtime, 0, sizeof (ProcessTime));
2568         memset (user_processtime, 0, sizeof (ProcessTime));
2569
2570         res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2571         if (!res) {
2572                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2573                 return FALSE;
2574         }
2575
2576         if (!process_handle->child) {
2577                 gint64 start_ticks, user_ticks, kernel_ticks;
2578
2579                 mono_process_get_times (GINT_TO_POINTER (process_handle->pid),
2580                         &start_ticks, &user_ticks, &kernel_ticks);
2581
2582                 ticks_to_processtime (start_ticks, creation_processtime);
2583                 ticks_to_processtime (kernel_ticks, kernel_processtime);
2584                 ticks_to_processtime (user_ticks, user_processtime);
2585                 return TRUE;
2586         }
2587
2588         ticks_to_processtime (process_handle->create_time, creation_processtime);
2589
2590         /* A process handle is only signalled if the process has
2591          * exited, otherwise exit_processtime isn't set */
2592         if (mono_w32handle_issignalled (handle))
2593                 ticks_to_processtime (process_handle->exit_time, exit_processtime);
2594
2595 #ifdef HAVE_GETRUSAGE
2596         if (process_handle->pid == getpid ()) {
2597                 struct rusage time_data;
2598                 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
2599                         ticks_to_processtime ((guint64)time_data.ru_utime.tv_sec * 10000000 + (guint64)time_data.ru_utime.tv_usec * 10, user_processtime);
2600                         ticks_to_processtime ((guint64)time_data.ru_stime.tv_sec * 10000000 + (guint64)time_data.ru_stime.tv_usec * 10, kernel_processtime);
2601                 }
2602         }
2603 #endif
2604
2605         return TRUE;
2606 }
2607
2608 static IMAGE_SECTION_HEADER *
2609 get_enclosing_section_header (guint32 rva, IMAGE_NT_HEADERS32 *nt_headers)
2610 {
2611         IMAGE_SECTION_HEADER *section = IMAGE_FIRST_SECTION32 (nt_headers);
2612         guint32 i;
2613
2614         for (i = 0; i < GUINT16_FROM_LE (nt_headers->FileHeader.NumberOfSections); i++, section++) {
2615                 guint32 size = GUINT32_FROM_LE (section->Misc.VirtualSize);
2616                 if (size == 0) {
2617                         size = GUINT32_FROM_LE (section->SizeOfRawData);
2618                 }
2619
2620                 if ((rva >= GUINT32_FROM_LE (section->VirtualAddress)) &&
2621                     (rva < (GUINT32_FROM_LE (section->VirtualAddress) + size))) {
2622                         return(section);
2623                 }
2624         }
2625
2626         return(NULL);
2627 }
2628
2629 /* This works for both 32bit and 64bit files, as the differences are
2630  * all after the section header block
2631  */
2632 static gpointer
2633 get_ptr_from_rva (guint32 rva, IMAGE_NT_HEADERS32 *ntheaders, gpointer file_map)
2634 {
2635         IMAGE_SECTION_HEADER *section_header;
2636         guint32 delta;
2637
2638         section_header = get_enclosing_section_header (rva, ntheaders);
2639         if (section_header == NULL) {
2640                 return(NULL);
2641         }
2642
2643         delta = (guint32)(GUINT32_FROM_LE (section_header->VirtualAddress) -
2644                           GUINT32_FROM_LE (section_header->PointerToRawData));
2645
2646         return((guint8 *)file_map + rva - delta);
2647 }
2648
2649 static gpointer
2650 scan_resource_dir (IMAGE_RESOURCE_DIRECTORY *root, IMAGE_NT_HEADERS32 *nt_headers, gpointer file_map,
2651         IMAGE_RESOURCE_DIRECTORY_ENTRY *entry, int level, guint32 res_id, guint32 lang_id, guint32 *size)
2652 {
2653         IMAGE_RESOURCE_DIRECTORY_ENTRY swapped_entry;
2654         gboolean is_string, is_dir;
2655         guint32 name_offset, dir_offset, data_offset;
2656
2657         swapped_entry.Name = GUINT32_FROM_LE (entry->Name);
2658         swapped_entry.OffsetToData = GUINT32_FROM_LE (entry->OffsetToData);
2659
2660         is_string = swapped_entry.NameIsString;
2661         is_dir = swapped_entry.DataIsDirectory;
2662         name_offset = swapped_entry.NameOffset;
2663         dir_offset = swapped_entry.OffsetToDirectory;
2664         data_offset = swapped_entry.OffsetToData;
2665
2666         if (level == 0) {
2667                 /* Normally holds a directory entry for each type of
2668                  * resource
2669                  */
2670                 if ((is_string == FALSE &&
2671                      name_offset != res_id) ||
2672                     (is_string == TRUE)) {
2673                         return(NULL);
2674                 }
2675         } else if (level == 1) {
2676                 /* Normally holds a directory entry for each resource
2677                  * item
2678                  */
2679         } else if (level == 2) {
2680                 /* Normally holds a directory entry for each language
2681                  */
2682                 if ((is_string == FALSE &&
2683                      name_offset != lang_id &&
2684                      lang_id != 0) ||
2685                     (is_string == TRUE)) {
2686                         return(NULL);
2687                 }
2688         } else {
2689                 g_assert_not_reached ();
2690         }
2691
2692         if (is_dir == TRUE) {
2693                 IMAGE_RESOURCE_DIRECTORY *res_dir = (IMAGE_RESOURCE_DIRECTORY *)((guint8 *)root + dir_offset);
2694                 IMAGE_RESOURCE_DIRECTORY_ENTRY *sub_entries = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(res_dir + 1);
2695                 guint32 entries, i;
2696
2697                 entries = GUINT16_FROM_LE (res_dir->NumberOfNamedEntries) + GUINT16_FROM_LE (res_dir->NumberOfIdEntries);
2698
2699                 for (i = 0; i < entries; i++) {
2700                         IMAGE_RESOURCE_DIRECTORY_ENTRY *sub_entry = &sub_entries[i];
2701                         gpointer ret;
2702
2703                         ret = scan_resource_dir (root, nt_headers, file_map,
2704                                                  sub_entry, level + 1, res_id,
2705                                                  lang_id, size);
2706                         if (ret != NULL) {
2707                                 return(ret);
2708                         }
2709                 }
2710
2711                 return(NULL);
2712         } else {
2713                 IMAGE_RESOURCE_DATA_ENTRY *data_entry = (IMAGE_RESOURCE_DATA_ENTRY *)((guint8 *)root + data_offset);
2714                 *size = GUINT32_FROM_LE (data_entry->Size);
2715
2716                 return(get_ptr_from_rva (GUINT32_FROM_LE (data_entry->OffsetToData), nt_headers, file_map));
2717         }
2718 }
2719
2720 static gpointer
2721 find_pe_file_resources32 (gpointer file_map, guint32 map_size, guint32 res_id, guint32 lang_id, guint32 *size)
2722 {
2723         IMAGE_DOS_HEADER *dos_header;
2724         IMAGE_NT_HEADERS32 *nt_headers;
2725         IMAGE_RESOURCE_DIRECTORY *resource_dir;
2726         IMAGE_RESOURCE_DIRECTORY_ENTRY *resource_dir_entry;
2727         guint32 resource_rva, entries, i;
2728         gpointer ret = NULL;
2729
2730         dos_header = (IMAGE_DOS_HEADER *)file_map;
2731         if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) {
2732                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Bad dos signature 0x%x", __func__, dos_header->e_magic);
2733
2734                 mono_w32error_set_last (ERROR_INVALID_DATA);
2735                 return(NULL);
2736         }
2737
2738         if (map_size < sizeof(IMAGE_NT_HEADERS32) + GUINT32_FROM_LE (dos_header->e_lfanew)) {
2739                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File is too small: %" G_GUINT32_FORMAT, __func__, map_size);
2740
2741                 mono_w32error_set_last (ERROR_BAD_LENGTH);
2742                 return(NULL);
2743         }
2744
2745         nt_headers = (IMAGE_NT_HEADERS32 *)((guint8 *)file_map + GUINT32_FROM_LE (dos_header->e_lfanew));
2746         if (nt_headers->Signature != IMAGE_NT_SIGNATURE) {
2747                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Bad NT signature 0x%x", __func__, nt_headers->Signature);
2748
2749                 mono_w32error_set_last (ERROR_INVALID_DATA);
2750                 return(NULL);
2751         }
2752
2753         if (nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
2754                 /* Do 64-bit stuff */
2755                 resource_rva = GUINT32_FROM_LE (((IMAGE_NT_HEADERS64 *)nt_headers)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
2756         } else {
2757                 resource_rva = GUINT32_FROM_LE (nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
2758         }
2759
2760         if (resource_rva == 0) {
2761                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: No resources in file!", __func__);
2762
2763                 mono_w32error_set_last (ERROR_INVALID_DATA);
2764                 return(NULL);
2765         }
2766
2767         resource_dir = (IMAGE_RESOURCE_DIRECTORY *)get_ptr_from_rva (resource_rva, (IMAGE_NT_HEADERS32 *)nt_headers, file_map);
2768         if (resource_dir == NULL) {
2769                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find resource directory", __func__);
2770
2771                 mono_w32error_set_last (ERROR_INVALID_DATA);
2772                 return(NULL);
2773         }
2774
2775         entries = GUINT16_FROM_LE (resource_dir->NumberOfNamedEntries) + GUINT16_FROM_LE (resource_dir->NumberOfIdEntries);
2776         resource_dir_entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resource_dir + 1);
2777
2778         for (i = 0; i < entries; i++) {
2779                 IMAGE_RESOURCE_DIRECTORY_ENTRY *direntry = &resource_dir_entry[i];
2780                 ret = scan_resource_dir (resource_dir,
2781                                          (IMAGE_NT_HEADERS32 *)nt_headers,
2782                                          file_map, direntry, 0, res_id,
2783                                          lang_id, size);
2784                 if (ret != NULL) {
2785                         return(ret);
2786                 }
2787         }
2788
2789         return(NULL);
2790 }
2791
2792 static gpointer
2793 find_pe_file_resources64 (gpointer file_map, guint32 map_size, guint32 res_id, guint32 lang_id, guint32 *size)
2794 {
2795         IMAGE_DOS_HEADER *dos_header;
2796         IMAGE_NT_HEADERS64 *nt_headers;
2797         IMAGE_RESOURCE_DIRECTORY *resource_dir;
2798         IMAGE_RESOURCE_DIRECTORY_ENTRY *resource_dir_entry;
2799         guint32 resource_rva, entries, i;
2800         gpointer ret = NULL;
2801
2802         dos_header = (IMAGE_DOS_HEADER *)file_map;
2803         if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) {
2804                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Bad dos signature 0x%x", __func__, dos_header->e_magic);
2805
2806                 mono_w32error_set_last (ERROR_INVALID_DATA);
2807                 return(NULL);
2808         }
2809
2810         if (map_size < sizeof(IMAGE_NT_HEADERS64) + GUINT32_FROM_LE (dos_header->e_lfanew)) {
2811                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File is too small: %" G_GUINT32_FORMAT, __func__, map_size);
2812
2813                 mono_w32error_set_last (ERROR_BAD_LENGTH);
2814                 return(NULL);
2815         }
2816
2817         nt_headers = (IMAGE_NT_HEADERS64 *)((guint8 *)file_map + GUINT32_FROM_LE (dos_header->e_lfanew));
2818         if (nt_headers->Signature != IMAGE_NT_SIGNATURE) {
2819                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Bad NT signature 0x%x", __func__,
2820                            nt_headers->Signature);
2821
2822                 mono_w32error_set_last (ERROR_INVALID_DATA);
2823                 return(NULL);
2824         }
2825
2826         if (nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
2827                 /* Do 64-bit stuff */
2828                 resource_rva = GUINT32_FROM_LE (((IMAGE_NT_HEADERS64 *)nt_headers)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
2829         } else {
2830                 resource_rva = GUINT32_FROM_LE (nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
2831         }
2832
2833         if (resource_rva == 0) {
2834                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: No resources in file!", __func__);
2835
2836                 mono_w32error_set_last (ERROR_INVALID_DATA);
2837                 return(NULL);
2838         }
2839
2840         resource_dir = (IMAGE_RESOURCE_DIRECTORY *)get_ptr_from_rva (resource_rva, (IMAGE_NT_HEADERS32 *)nt_headers, file_map);
2841         if (resource_dir == NULL) {
2842                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find resource directory", __func__);
2843
2844                 mono_w32error_set_last (ERROR_INVALID_DATA);
2845                 return(NULL);
2846         }
2847
2848         entries = GUINT16_FROM_LE (resource_dir->NumberOfNamedEntries) + GUINT16_FROM_LE (resource_dir->NumberOfIdEntries);
2849         resource_dir_entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resource_dir + 1);
2850
2851         for (i = 0; i < entries; i++) {
2852                 IMAGE_RESOURCE_DIRECTORY_ENTRY *direntry = &resource_dir_entry[i];
2853                 ret = scan_resource_dir (resource_dir,
2854                                          (IMAGE_NT_HEADERS32 *)nt_headers,
2855                                          file_map, direntry, 0, res_id,
2856                                          lang_id, size);
2857                 if (ret != NULL) {
2858                         return(ret);
2859                 }
2860         }
2861
2862         return(NULL);
2863 }
2864
2865 static gpointer
2866 find_pe_file_resources (gpointer file_map, guint32 map_size, guint32 res_id, guint32 lang_id, guint32 *size)
2867 {
2868         /* Figure this out when we support 64bit PE files */
2869         if (1) {
2870                 return find_pe_file_resources32 (file_map, map_size, res_id,
2871                                                  lang_id, size);
2872         } else {
2873                 return find_pe_file_resources64 (file_map, map_size, res_id,
2874                                                  lang_id, size);
2875         }
2876 }
2877
2878 static gpointer
2879 map_pe_file (gunichar2 *filename, gint32 *map_size, void **handle)
2880 {
2881         gchar *filename_ext;
2882         int fd;
2883         struct stat statbuf;
2884         gpointer file_map;
2885
2886         /* According to the MSDN docs, a search path is applied to
2887          * filename.  FIXME: implement this, for now just pass it
2888          * straight to fopen
2889          */
2890
2891         filename_ext = mono_unicode_to_external (filename);
2892         if (filename_ext == NULL) {
2893                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2894
2895                 mono_w32error_set_last (ERROR_INVALID_NAME);
2896                 return(NULL);
2897         }
2898
2899         fd = open (filename_ext, O_RDONLY, 0);
2900         if (fd == -1 && (errno == ENOENT || errno == ENOTDIR) && IS_PORTABILITY_SET) {
2901                 gint saved_errno;
2902                 gchar *located_filename;
2903
2904                 saved_errno = errno;
2905
2906                 located_filename = mono_portability_find_file (filename_ext, TRUE);
2907                 if (!located_filename) {
2908                         errno = saved_errno;
2909
2910                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error opening file %s (1): %s", __func__, filename_ext, strerror (errno));
2911
2912                         g_free (filename_ext);
2913
2914                         mono_w32error_set_last (mono_w32error_unix_to_win32 (errno));
2915                         return NULL;
2916                 }
2917
2918                 fd = open (located_filename, O_RDONLY, 0);
2919                 if (fd == -1) {
2920                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error opening file %s (2): %s", __func__, filename_ext, strerror (errno));
2921
2922                         g_free (filename_ext);
2923                         g_free (located_filename);
2924
2925                         mono_w32error_set_last (mono_w32error_unix_to_win32 (errno));
2926                         return NULL;
2927                 }
2928
2929                 g_free (located_filename);
2930         }
2931
2932         if (fstat (fd, &statbuf) == -1) {
2933                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error stat()ing file %s: %s", __func__, filename_ext, strerror (errno));
2934
2935                 mono_w32error_set_last (mono_w32error_unix_to_win32 (errno));
2936                 g_free (filename_ext);
2937                 close (fd);
2938                 return(NULL);
2939         }
2940         *map_size = statbuf.st_size;
2941
2942         /* Check basic file size */
2943         if (statbuf.st_size < sizeof(IMAGE_DOS_HEADER)) {
2944                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File %s is too small: %lld", __func__, filename_ext, (long long) statbuf.st_size);
2945
2946                 mono_w32error_set_last (ERROR_BAD_LENGTH);
2947                 g_free (filename_ext);
2948                 close (fd);
2949                 return(NULL);
2950         }
2951
2952         file_map = mono_file_map (statbuf.st_size, MONO_MMAP_READ | MONO_MMAP_PRIVATE, fd, 0, handle);
2953         if (file_map == NULL) {
2954                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error mmap()int file %s: %s", __func__, filename_ext, strerror (errno));
2955
2956                 mono_w32error_set_last (mono_w32error_unix_to_win32 (errno));
2957                 g_free (filename_ext);
2958                 close (fd);
2959                 return(NULL);
2960         }
2961
2962         /* Don't need the fd any more */
2963         close (fd);
2964         g_free (filename_ext);
2965
2966         return(file_map);
2967 }
2968
2969 static void
2970 unmap_pe_file (gpointer file_map, void *handle)
2971 {
2972         mono_file_unmap (file_map, handle);
2973 }
2974
2975 static guint32
2976 unicode_chars (const gunichar2 *str)
2977 {
2978         guint32 len = 0;
2979
2980         do {
2981                 if (str[len] == '\0') {
2982                         return(len);
2983                 }
2984                 len++;
2985         } while(1);
2986 }
2987
2988 static gboolean
2989 unicode_compare (const gunichar2 *str1, const gunichar2 *str2)
2990 {
2991         while (*str1 && *str2) {
2992                 if (*str1 != *str2) {
2993                         return(FALSE);
2994                 }
2995                 ++str1;
2996                 ++str2;
2997         }
2998
2999         return(*str1 == *str2);
3000 }
3001
3002 /* compare a little-endian null-terminated utf16 string and a normal string.
3003  * Can be used only for ascii or latin1 chars.
3004  */
3005 static gboolean
3006 unicode_string_equals (const gunichar2 *str1, const gchar *str2)
3007 {
3008         while (*str1 && *str2) {
3009                 if (GUINT16_TO_LE (*str1) != *str2) {
3010                         return(FALSE);
3011                 }
3012                 ++str1;
3013                 ++str2;
3014         }
3015
3016         return(*str1 == *str2);
3017 }
3018
3019 typedef struct {
3020         guint16 data_len;
3021         guint16 value_len;
3022         guint16 type;
3023         gunichar2 *key;
3024 } version_data;
3025
3026 /* Returns a pointer to the value data, because there's no way to know
3027  * how big that data is (value_len is set to zero for most blocks :-( )
3028  */
3029 static gconstpointer
3030 get_versioninfo_block (gconstpointer data, version_data *block)
3031 {
3032         block->data_len = GUINT16_FROM_LE (*((guint16 *)data));
3033         data = (char *)data + sizeof(guint16);
3034         block->value_len = GUINT16_FROM_LE (*((guint16 *)data));
3035         data = (char *)data + sizeof(guint16);
3036
3037         /* No idea what the type is supposed to indicate */
3038         block->type = GUINT16_FROM_LE (*((guint16 *)data));
3039         data = (char *)data + sizeof(guint16);
3040         block->key = ((gunichar2 *)data);
3041
3042         /* Skip over the key (including the terminator) */
3043         data = ((gunichar2 *)data) + (unicode_chars (block->key) + 1);
3044
3045         /* align on a 32-bit boundary */
3046         ALIGN32 (data);
3047
3048         return(data);
3049 }
3050
3051 static gconstpointer
3052 get_fixedfileinfo_block (gconstpointer data, version_data *block)
3053 {
3054         gconstpointer data_ptr;
3055         VS_FIXEDFILEINFO *ffi;
3056
3057         data_ptr = get_versioninfo_block (data, block);
3058
3059         if (block->value_len != sizeof(VS_FIXEDFILEINFO)) {
3060                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: FIXEDFILEINFO size mismatch", __func__);
3061                 return(NULL);
3062         }
3063
3064         if (!unicode_string_equals (block->key, "VS_VERSION_INFO")) {
3065                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: VS_VERSION_INFO mismatch", __func__);
3066
3067                 return(NULL);
3068         }
3069
3070         ffi = ((VS_FIXEDFILEINFO *)data_ptr);
3071         if ((ffi->dwSignature != VS_FFI_SIGNATURE) ||
3072             (ffi->dwStrucVersion != VS_FFI_STRUCVERSION)) {
3073                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: FIXEDFILEINFO bad signature", __func__);
3074
3075                 return(NULL);
3076         }
3077
3078         return(data_ptr);
3079 }
3080
3081 static gconstpointer
3082 get_varfileinfo_block (gconstpointer data_ptr, version_data *block)
3083 {
3084         /* data is pointing at a Var block
3085          */
3086         data_ptr = get_versioninfo_block (data_ptr, block);
3087
3088         return(data_ptr);
3089 }
3090
3091 static gconstpointer
3092 get_string_block (gconstpointer data_ptr, const gunichar2 *string_key, gpointer *string_value,
3093         guint32 *string_value_len, version_data *block)
3094 {
3095         guint16 data_len = block->data_len;
3096         guint16 string_len = 28; /* Length of the StringTable block */
3097         char *orig_data_ptr = (char *)data_ptr - 28;
3098
3099         /* data_ptr is pointing at an array of one or more String blocks
3100          * with total length (not including alignment padding) of
3101          * data_len
3102          */
3103         while (((char *)data_ptr - (char *)orig_data_ptr) < data_len) {
3104                 /* align on a 32-bit boundary */
3105                 ALIGN32 (data_ptr);
3106
3107                 data_ptr = get_versioninfo_block (data_ptr, block);
3108                 if (block->data_len == 0) {
3109                         /* We must have hit padding, so give up
3110                          * processing now
3111                          */
3112                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3113
3114                         return(NULL);
3115                 }
3116
3117                 string_len = string_len + block->data_len;
3118
3119                 if (string_key != NULL &&
3120                     string_value != NULL &&
3121                     string_value_len != NULL &&
3122                     unicode_compare (string_key, block->key) == TRUE) {
3123                         *string_value = (gpointer)data_ptr;
3124                         *string_value_len = block->value_len;
3125                 }
3126
3127                 /* Skip over the value */
3128                 data_ptr = ((gunichar2 *)data_ptr) + block->value_len;
3129         }
3130
3131         return(data_ptr);
3132 }
3133
3134 /* Returns a pointer to the byte following the Stringtable block, or
3135  * NULL if the data read hits padding.  We can't recover from this
3136  * because the data length does not include padding bytes, so it's not
3137  * possible to just return the start position + length
3138  *
3139  * If lang == NULL it means we're just stepping through this block
3140  */
3141 static gconstpointer
3142 get_stringtable_block (gconstpointer data_ptr, gchar *lang, const gunichar2 *string_key, gpointer *string_value,
3143         guint32 *string_value_len, version_data *block)
3144 {
3145         guint16 data_len = block->data_len;
3146         guint16 string_len = 36; /* length of the StringFileInfo block */
3147         gchar *found_lang;
3148         gchar *lowercase_lang;
3149
3150         /* data_ptr is pointing at an array of StringTable blocks,
3151          * with total length (not including alignment padding) of
3152          * data_len
3153          */
3154
3155         while(string_len < data_len) {
3156                 /* align on a 32-bit boundary */
3157                 ALIGN32 (data_ptr);
3158
3159                 data_ptr = get_versioninfo_block (data_ptr, block);
3160                 if (block->data_len == 0) {
3161                         /* We must have hit padding, so give up
3162                          * processing now
3163                          */
3164                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3165                         return(NULL);
3166                 }
3167
3168                 string_len = string_len + block->data_len;
3169
3170                 found_lang = g_utf16_to_utf8 (block->key, 8, NULL, NULL, NULL);
3171                 if (found_lang == NULL) {
3172                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't find a valid language key, giving up", __func__);
3173                         return(NULL);
3174                 }
3175
3176                 lowercase_lang = g_utf8_strdown (found_lang, -1);
3177                 g_free (found_lang);
3178                 found_lang = lowercase_lang;
3179                 lowercase_lang = NULL;
3180
3181                 if (lang != NULL && !strcmp (found_lang, lang)) {
3182                         /* Got the one we're interested in */
3183                         data_ptr = get_string_block (data_ptr, string_key,
3184                                                      string_value,
3185                                                      string_value_len, block);
3186                 } else {
3187                         data_ptr = get_string_block (data_ptr, NULL, NULL,
3188                                                      NULL, block);
3189                 }
3190
3191                 g_free (found_lang);
3192
3193                 if (data_ptr == NULL) {
3194                         /* Child block hit padding */
3195                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Child block hit 0-length block, giving up", __func__);
3196                         return(NULL);
3197                 }
3198         }
3199
3200         return(data_ptr);
3201 }
3202
3203 #if G_BYTE_ORDER == G_BIG_ENDIAN
3204 static gconstpointer
3205 big_up_string_block (gconstpointer data_ptr, version_data *block)
3206 {
3207         guint16 data_len = block->data_len;
3208         guint16 string_len = 28; /* Length of the StringTable block */
3209         gchar *big_value;
3210         char *orig_data_ptr = (char *)data_ptr - 28;
3211
3212         /* data_ptr is pointing at an array of one or more String
3213          * blocks with total length (not including alignment padding)
3214          * of data_len
3215          */
3216         while (((char *)data_ptr - (char *)orig_data_ptr) < data_len) {
3217                 /* align on a 32-bit boundary */
3218                 ALIGN32 (data_ptr);
3219
3220                 data_ptr = get_versioninfo_block (data_ptr, block);
3221                 if (block->data_len == 0) {
3222                         /* We must have hit padding, so give up
3223                          * processing now
3224                          */
3225                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3226                         return(NULL);
3227                 }
3228
3229                 string_len = string_len + block->data_len;
3230
3231                 big_value = g_convert ((gchar *)block->key,
3232                                        unicode_chars (block->key) * 2,
3233                                        "UTF-16BE", "UTF-16LE", NULL, NULL,
3234                                        NULL);
3235                 if (big_value == NULL) {
3236                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't find a valid string, giving up", __func__);
3237                         return(NULL);
3238                 }
3239
3240                 /* The swapped string should be exactly the same
3241                  * length as the original little-endian one, but only
3242                  * copy the number of original chars just to be on the
3243                  * safe side
3244                  */
3245                 memcpy (block->key, big_value, unicode_chars (block->key) * 2);
3246                 g_free (big_value);
3247
3248                 big_value = g_convert ((gchar *)data_ptr,
3249                                        unicode_chars (data_ptr) * 2,
3250                                        "UTF-16BE", "UTF-16LE", NULL, NULL,
3251                                        NULL);
3252                 if (big_value == NULL) {
3253                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't find a valid data string, giving up", __func__);
3254                         return(NULL);
3255                 }
3256                 memcpy ((gpointer)data_ptr, big_value,
3257                         unicode_chars (data_ptr) * 2);
3258                 g_free (big_value);
3259
3260                 data_ptr = ((gunichar2 *)data_ptr) + block->value_len;
3261         }
3262
3263         return(data_ptr);
3264 }
3265
3266 /* Returns a pointer to the byte following the Stringtable block, or
3267  * NULL if the data read hits padding.  We can't recover from this
3268  * because the data length does not include padding bytes, so it's not
3269  * possible to just return the start position + length
3270  */
3271 static gconstpointer
3272 big_up_stringtable_block (gconstpointer data_ptr, version_data *block)
3273 {
3274         guint16 data_len = block->data_len;
3275         guint16 string_len = 36; /* length of the StringFileInfo block */
3276         gchar *big_value;
3277
3278         /* data_ptr is pointing at an array of StringTable blocks,
3279          * with total length (not including alignment padding) of
3280          * data_len
3281          */
3282
3283         while(string_len < data_len) {
3284                 /* align on a 32-bit boundary */
3285                 ALIGN32 (data_ptr);
3286
3287                 data_ptr = get_versioninfo_block (data_ptr, block);
3288                 if (block->data_len == 0) {
3289                         /* We must have hit padding, so give up
3290                          * processing now
3291                          */
3292                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3293                         return(NULL);
3294                 }
3295
3296                 string_len = string_len + block->data_len;
3297
3298                 big_value = g_convert ((gchar *)block->key, 16, "UTF-16BE",
3299                                        "UTF-16LE", NULL, NULL, NULL);
3300                 if (big_value == NULL) {
3301                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't find a valid string, giving up", __func__);
3302                         return(NULL);
3303                 }
3304
3305                 memcpy (block->key, big_value, 16);
3306                 g_free (big_value);
3307
3308                 data_ptr = big_up_string_block (data_ptr, block);
3309
3310                 if (data_ptr == NULL) {
3311                         /* Child block hit padding */
3312                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Child block hit 0-length block, giving up", __func__);
3313                         return(NULL);
3314                 }
3315         }
3316
3317         return(data_ptr);
3318 }
3319
3320 /* Follows the data structures and turns all UTF-16 strings from the
3321  * LE found in the resource section into UTF-16BE
3322  */
3323 static void
3324 big_up (gconstpointer datablock, guint32 size)
3325 {
3326         gconstpointer data_ptr;
3327         gint32 data_len; /* signed to guard against underflow */
3328         version_data block;
3329
3330         data_ptr = get_fixedfileinfo_block (datablock, &block);
3331         if (data_ptr != NULL) {
3332                 VS_FIXEDFILEINFO *ffi = (VS_FIXEDFILEINFO *)data_ptr;
3333
3334                 /* Byteswap all the fields */
3335                 ffi->dwFileVersionMS = GUINT32_SWAP_LE_BE (ffi->dwFileVersionMS);
3336                 ffi->dwFileVersionLS = GUINT32_SWAP_LE_BE (ffi->dwFileVersionLS);
3337                 ffi->dwProductVersionMS = GUINT32_SWAP_LE_BE (ffi->dwProductVersionMS);
3338                 ffi->dwProductVersionLS = GUINT32_SWAP_LE_BE (ffi->dwProductVersionLS);
3339                 ffi->dwFileFlagsMask = GUINT32_SWAP_LE_BE (ffi->dwFileFlagsMask);
3340                 ffi->dwFileFlags = GUINT32_SWAP_LE_BE (ffi->dwFileFlags);
3341                 ffi->dwFileOS = GUINT32_SWAP_LE_BE (ffi->dwFileOS);
3342                 ffi->dwFileType = GUINT32_SWAP_LE_BE (ffi->dwFileType);
3343                 ffi->dwFileSubtype = GUINT32_SWAP_LE_BE (ffi->dwFileSubtype);
3344                 ffi->dwFileDateMS = GUINT32_SWAP_LE_BE (ffi->dwFileDateMS);
3345                 ffi->dwFileDateLS = GUINT32_SWAP_LE_BE (ffi->dwFileDateLS);
3346
3347                 /* The FFI and header occupies the first 92 bytes
3348                  */
3349                 data_ptr = (char *)data_ptr + sizeof(VS_FIXEDFILEINFO);
3350                 data_len = block.data_len - 92;
3351
3352                 /* There now follow zero or one StringFileInfo blocks
3353                  * and zero or one VarFileInfo blocks
3354                  */
3355                 while (data_len > 0) {
3356                         /* align on a 32-bit boundary */
3357                         ALIGN32 (data_ptr);
3358
3359                         data_ptr = get_versioninfo_block (data_ptr, &block);
3360                         if (block.data_len == 0) {
3361                                 /* We must have hit padding, so give
3362                                  * up processing now
3363                                  */
3364                                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3365                                 return;
3366                         }
3367
3368                         data_len = data_len - block.data_len;
3369
3370                         if (unicode_string_equals (block.key, "VarFileInfo")) {
3371                                 data_ptr = get_varfileinfo_block (data_ptr,
3372                                                                   &block);
3373                                 data_ptr = ((guchar *)data_ptr) + block.value_len;
3374                         } else if (unicode_string_equals (block.key,
3375                                                           "StringFileInfo")) {
3376                                 data_ptr = big_up_stringtable_block (data_ptr,
3377                                                                      &block);
3378                         } else {
3379                                 /* Bogus data */
3380                                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Not a valid VERSIONINFO child block", __func__);
3381                                 return;
3382                         }
3383
3384                         if (data_ptr == NULL) {
3385                                 /* Child block hit padding */
3386                                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Child block hit 0-length block, giving up", __func__);
3387                                 return;
3388                         }
3389                 }
3390         }
3391 }
3392 #endif
3393
3394 guint32
3395 mono_w32process_get_fileversion_info_size (gunichar2 *filename, guint32 *handle)
3396 {
3397         gpointer file_map;
3398         gpointer versioninfo;
3399         void *map_handle;
3400         gint32 map_size;
3401         guint32 size;
3402
3403         /* This value is unused, but set to zero */
3404         *handle = 0;
3405
3406         file_map = map_pe_file (filename, &map_size, &map_handle);
3407         if (file_map == NULL) {
3408                 return(0);
3409         }
3410
3411         versioninfo = find_pe_file_resources (file_map, map_size, RT_VERSION, 0, &size);
3412         if (versioninfo == NULL) {
3413                 /* Didn't find the resource, so set the return value
3414                  * to 0
3415                  */
3416                 size = 0;
3417         }
3418
3419         unmap_pe_file (file_map, map_handle);
3420
3421         return(size);
3422 }
3423
3424 gboolean
3425 mono_w32process_get_fileversion_info (gunichar2 *filename, guint32 handle G_GNUC_UNUSED, guint32 len, gpointer data)
3426 {
3427         gpointer file_map;
3428         gpointer versioninfo;
3429         void *map_handle;
3430         gint32 map_size;
3431         guint32 size;
3432         gboolean ret = FALSE;
3433
3434         file_map = map_pe_file (filename, &map_size, &map_handle);
3435         if (file_map == NULL) {
3436                 return(FALSE);
3437         }
3438
3439         versioninfo = find_pe_file_resources (file_map, map_size, RT_VERSION,
3440                                               0, &size);
3441         if (versioninfo != NULL) {
3442                 /* This could probably process the data so that
3443                  * mono_w32process_ver_query_value() doesn't have to follow the data
3444                  * blocks every time.  But hey, these functions aren't
3445                  * likely to appear in many profiles.
3446                  */
3447                 memcpy (data, versioninfo, len < size?len:size);
3448                 ret = TRUE;
3449
3450 #if G_BYTE_ORDER == G_BIG_ENDIAN
3451                 big_up (data, size);
3452 #endif
3453         }
3454
3455         unmap_pe_file (file_map, map_handle);
3456
3457         return(ret);
3458 }
3459
3460 gboolean
3461 mono_w32process_ver_query_value (gconstpointer datablock, const gunichar2 *subblock, gpointer *buffer, guint32 *len)
3462 {
3463         gchar *subblock_utf8, *lang_utf8 = NULL;
3464         gboolean ret = FALSE;
3465         version_data block;
3466         gconstpointer data_ptr;
3467         gint32 data_len; /* signed to guard against underflow */
3468         gboolean want_var = FALSE;
3469         gboolean want_string = FALSE;
3470         gunichar2 lang[8];
3471         const gunichar2 *string_key = NULL;
3472         gpointer string_value = NULL;
3473         guint32 string_value_len = 0;
3474         gchar *lowercase_lang;
3475
3476         subblock_utf8 = g_utf16_to_utf8 (subblock, -1, NULL, NULL, NULL);
3477         if (subblock_utf8 == NULL) {
3478                 return(FALSE);
3479         }
3480
3481         if (!strcmp (subblock_utf8, "\\VarFileInfo\\Translation")) {
3482                 want_var = TRUE;
3483         } else if (!strncmp (subblock_utf8, "\\StringFileInfo\\", 16)) {
3484                 want_string = TRUE;
3485                 memcpy (lang, subblock + 16, 8 * sizeof(gunichar2));
3486                 lang_utf8 = g_utf16_to_utf8 (lang, 8, NULL, NULL, NULL);
3487                 lowercase_lang = g_utf8_strdown (lang_utf8, -1);
3488                 g_free (lang_utf8);
3489                 lang_utf8 = lowercase_lang;
3490                 lowercase_lang = NULL;
3491                 string_key = subblock + 25;
3492         }
3493
3494         if (!strcmp (subblock_utf8, "\\")) {
3495                 data_ptr = get_fixedfileinfo_block (datablock, &block);
3496                 if (data_ptr != NULL) {
3497                         *buffer = (gpointer)data_ptr;
3498                         *len = block.value_len;
3499
3500                         ret = TRUE;
3501                 }
3502         } else if (want_var || want_string) {
3503                 data_ptr = get_fixedfileinfo_block (datablock, &block);
3504                 if (data_ptr != NULL) {
3505                         /* The FFI and header occupies the first 92
3506                          * bytes
3507                          */
3508                         data_ptr = (char *)data_ptr + sizeof(VS_FIXEDFILEINFO);
3509                         data_len = block.data_len - 92;
3510
3511                         /* There now follow zero or one StringFileInfo
3512                          * blocks and zero or one VarFileInfo blocks
3513                          */
3514                         while (data_len > 0) {
3515                                 /* align on a 32-bit boundary */
3516                                 ALIGN32 (data_ptr);
3517
3518                                 data_ptr = get_versioninfo_block (data_ptr,
3519                                                                   &block);
3520                                 if (block.data_len == 0) {
3521                                         /* We must have hit padding,
3522                                          * so give up processing now
3523                                          */
3524                                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3525                                         goto done;
3526                                 }
3527
3528                                 data_len = data_len - block.data_len;
3529
3530                                 if (unicode_string_equals (block.key, "VarFileInfo")) {
3531                                         data_ptr = get_varfileinfo_block (data_ptr, &block);
3532                                         if (want_var) {
3533                                                 *buffer = (gpointer)data_ptr;
3534                                                 *len = block.value_len;
3535                                                 ret = TRUE;
3536                                                 goto done;
3537                                         } else {
3538                                                 /* Skip over the Var block */
3539                                                 data_ptr = ((guchar *)data_ptr) + block.value_len;
3540                                         }
3541                                 } else if (unicode_string_equals (block.key, "StringFileInfo")) {
3542                                         data_ptr = get_stringtable_block (data_ptr, lang_utf8, string_key, &string_value, &string_value_len, &block);
3543                                         if (want_string &&
3544                                             string_value != NULL &&
3545                                             string_value_len != 0) {
3546                                                 *buffer = string_value;
3547                                                 *len = unicode_chars ((const gunichar2 *)string_value) + 1; /* Include trailing null */
3548                                                 ret = TRUE;
3549                                                 goto done;
3550                                         }
3551                                 } else {
3552                                         /* Bogus data */
3553                                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Not a valid VERSIONINFO child block", __func__);
3554                                         goto done;
3555                                 }
3556
3557                                 if (data_ptr == NULL) {
3558                                         /* Child block hit padding */
3559                                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Child block hit 0-length block, giving up", __func__);
3560                                         goto done;
3561                                 }
3562                         }
3563                 }
3564         }
3565
3566   done:
3567         if (lang_utf8) {
3568                 g_free (lang_utf8);
3569         }
3570
3571         g_free (subblock_utf8);
3572         return(ret);
3573 }
3574
3575 static guint32
3576 copy_lang (gunichar2 *lang_out, guint32 lang_len, const gchar *text)
3577 {
3578         gunichar2 *unitext;
3579         int chars = strlen (text);
3580         int ret;
3581
3582         unitext = g_utf8_to_utf16 (text, -1, NULL, NULL, NULL);
3583         g_assert (unitext != NULL);
3584
3585         if (chars < (lang_len - 1)) {
3586                 memcpy (lang_out, (gpointer)unitext, chars * 2);
3587                 lang_out[chars] = '\0';
3588                 ret = chars;
3589         } else {
3590                 memcpy (lang_out, (gpointer)unitext, (lang_len - 1) * 2);
3591                 lang_out[lang_len] = '\0';
3592                 ret = lang_len;
3593         }
3594
3595         g_free (unitext);
3596
3597         return(ret);
3598 }
3599
3600 guint32
3601 mono_w32process_ver_language_name (guint32 lang, gunichar2 *lang_out, guint32 lang_len)
3602 {
3603         int primary, secondary;
3604         const char *name = NULL;
3605
3606         primary = lang & 0x3FF;
3607         secondary = (lang >> 10) & 0x3F;
3608
3609         switch(primary) {
3610         case 0x00:
3611                 switch (secondary) {
3612                 case 0x01: name = "Process Default Language"; break;
3613                 }
3614                 break;
3615         case 0x01:
3616                 switch (secondary) {
3617                 case 0x00:
3618                 case 0x01: name = "Arabic (Saudi Arabia)"; break;
3619                 case 0x02: name = "Arabic (Iraq)"; break;
3620                 case 0x03: name = "Arabic (Egypt)"; break;
3621                 case 0x04: name = "Arabic (Libya)"; break;
3622                 case 0x05: name = "Arabic (Algeria)"; break;
3623                 case 0x06: name = "Arabic (Morocco)"; break;
3624                 case 0x07: name = "Arabic (Tunisia)"; break;
3625                 case 0x08: name = "Arabic (Oman)"; break;
3626                 case 0x09: name = "Arabic (Yemen)"; break;
3627                 case 0x0a: name = "Arabic (Syria)"; break;
3628                 case 0x0b: name = "Arabic (Jordan)"; break;
3629                 case 0x0c: name = "Arabic (Lebanon)"; break;
3630                 case 0x0d: name = "Arabic (Kuwait)"; break;
3631                 case 0x0e: name = "Arabic (U.A.E.)"; break;
3632                 case 0x0f: name = "Arabic (Bahrain)"; break;
3633                 case 0x10: name = "Arabic (Qatar)"; break;
3634                 }
3635                 break;
3636         case 0x02:
3637                 switch (secondary) {
3638                 case 0x00: name = "Bulgarian (Bulgaria)"; break;
3639                 case 0x01: name = "Bulgarian"; break;
3640                 }
3641                 break;
3642         case 0x03:
3643                 switch (secondary) {
3644                 case 0x00: name = "Catalan (Spain)"; break;
3645                 case 0x01: name = "Catalan"; break;
3646                 }
3647                 break;
3648         case 0x04:
3649                 switch (secondary) {
3650                 case 0x00:
3651                 case 0x01: name = "Chinese (Taiwan)"; break;
3652                 case 0x02: name = "Chinese (PRC)"; break;
3653                 case 0x03: name = "Chinese (Hong Kong S.A.R.)"; break;
3654                 case 0x04: name = "Chinese (Singapore)"; break;
3655                 case 0x05: name = "Chinese (Macau S.A.R.)"; break;
3656                 }
3657                 break;
3658         case 0x05:
3659                 switch (secondary) {
3660                 case 0x00: name = "Czech (Czech Republic)"; break;
3661                 case 0x01: name = "Czech"; break;
3662                 }
3663                 break;
3664         case 0x06:
3665                 switch (secondary) {
3666                 case 0x00: name = "Danish (Denmark)"; break;
3667                 case 0x01: name = "Danish"; break;
3668                 }
3669                 break;
3670         case 0x07:
3671                 switch (secondary) {
3672                 case 0x00:
3673                 case 0x01: name = "German (Germany)"; break;
3674                 case 0x02: name = "German (Switzerland)"; break;
3675                 case 0x03: name = "German (Austria)"; break;
3676                 case 0x04: name = "German (Luxembourg)"; break;
3677                 case 0x05: name = "German (Liechtenstein)"; break;
3678                 }
3679                 break;
3680         case 0x08:
3681                 switch (secondary) {
3682                 case 0x00: name = "Greek (Greece)"; break;
3683                 case 0x01: name = "Greek"; break;
3684                 }
3685                 break;
3686         case 0x09:
3687                 switch (secondary) {
3688                 case 0x00:
3689                 case 0x01: name = "English (United States)"; break;
3690                 case 0x02: name = "English (United Kingdom)"; break;
3691                 case 0x03: name = "English (Australia)"; break;
3692                 case 0x04: name = "English (Canada)"; break;
3693                 case 0x05: name = "English (New Zealand)"; break;
3694                 case 0x06: name = "English (Ireland)"; break;
3695                 case 0x07: name = "English (South Africa)"; break;
3696                 case 0x08: name = "English (Jamaica)"; break;
3697                 case 0x09: name = "English (Caribbean)"; break;
3698                 case 0x0a: name = "English (Belize)"; break;
3699                 case 0x0b: name = "English (Trinidad and Tobago)"; break;
3700                 case 0x0c: name = "English (Zimbabwe)"; break;
3701                 case 0x0d: name = "English (Philippines)"; break;
3702                 case 0x10: name = "English (India)"; break;
3703                 case 0x11: name = "English (Malaysia)"; break;
3704                 case 0x12: name = "English (Singapore)"; break;
3705                 }
3706                 break;
3707         case 0x0a:
3708                 switch (secondary) {
3709                 case 0x00: name = "Spanish (Spain)"; break;
3710                 case 0x01: name = "Spanish (Traditional Sort)"; break;
3711                 case 0x02: name = "Spanish (Mexico)"; break;
3712                 case 0x03: name = "Spanish (International Sort)"; break;
3713                 case 0x04: name = "Spanish (Guatemala)"; break;
3714                 case 0x05: name = "Spanish (Costa Rica)"; break;
3715                 case 0x06: name = "Spanish (Panama)"; break;
3716                 case 0x07: name = "Spanish (Dominican Republic)"; break;
3717                 case 0x08: name = "Spanish (Venezuela)"; break;
3718                 case 0x09: name = "Spanish (Colombia)"; break;
3719                 case 0x0a: name = "Spanish (Peru)"; break;
3720                 case 0x0b: name = "Spanish (Argentina)"; break;
3721                 case 0x0c: name = "Spanish (Ecuador)"; break;
3722                 case 0x0d: name = "Spanish (Chile)"; break;
3723                 case 0x0e: name = "Spanish (Uruguay)"; break;
3724                 case 0x0f: name = "Spanish (Paraguay)"; break;
3725                 case 0x10: name = "Spanish (Bolivia)"; break;
3726                 case 0x11: name = "Spanish (El Salvador)"; break;
3727                 case 0x12: name = "Spanish (Honduras)"; break;
3728                 case 0x13: name = "Spanish (Nicaragua)"; break;
3729                 case 0x14: name = "Spanish (Puerto Rico)"; break;
3730                 case 0x15: name = "Spanish (United States)"; break;
3731                 }
3732                 break;
3733         case 0x0b:
3734                 switch (secondary) {
3735                 case 0x00: name = "Finnish (Finland)"; break;
3736                 case 0x01: name = "Finnish"; break;
3737                 }
3738                 break;
3739         case 0x0c:
3740                 switch (secondary) {
3741                 case 0x00:
3742                 case 0x01: name = "French (France)"; break;
3743                 case 0x02: name = "French (Belgium)"; break;
3744                 case 0x03: name = "French (Canada)"; break;
3745                 case 0x04: name = "French (Switzerland)"; break;
3746                 case 0x05: name = "French (Luxembourg)"; break;
3747                 case 0x06: name = "French (Monaco)"; break;
3748                 }
3749                 break;
3750         case 0x0d:
3751                 switch (secondary) {
3752                 case 0x00: name = "Hebrew (Israel)"; break;
3753                 case 0x01: name = "Hebrew"; break;
3754                 }
3755                 break;
3756         case 0x0e:
3757                 switch (secondary) {
3758                 case 0x00: name = "Hungarian (Hungary)"; break;
3759                 case 0x01: name = "Hungarian"; break;
3760                 }
3761                 break;
3762         case 0x0f:
3763                 switch (secondary) {
3764                 case 0x00: name = "Icelandic (Iceland)"; break;
3765                 case 0x01: name = "Icelandic"; break;
3766                 }
3767                 break;
3768         case 0x10:
3769                 switch (secondary) {
3770                 case 0x00:
3771                 case 0x01: name = "Italian (Italy)"; break;
3772                 case 0x02: name = "Italian (Switzerland)"; break;
3773                 }
3774                 break;
3775         case 0x11:
3776                 switch (secondary) {
3777                 case 0x00: name = "Japanese (Japan)"; break;
3778                 case 0x01: name = "Japanese"; break;
3779                 }
3780                 break;
3781         case 0x12:
3782                 switch (secondary) {
3783                 case 0x00: name = "Korean (Korea)"; break;
3784                 case 0x01: name = "Korean"; break;
3785                 }
3786                 break;
3787         case 0x13:
3788                 switch (secondary) {
3789                 case 0x00:
3790                 case 0x01: name = "Dutch (Netherlands)"; break;
3791                 case 0x02: name = "Dutch (Belgium)"; break;
3792                 }
3793                 break;
3794         case 0x14:
3795                 switch (secondary) {
3796                 case 0x00:
3797                 case 0x01: name = "Norwegian (Bokmal)"; break;
3798                 case 0x02: name = "Norwegian (Nynorsk)"; break;
3799                 }
3800                 break;
3801         case 0x15:
3802                 switch (secondary) {
3803                 case 0x00: name = "Polish (Poland)"; break;
3804                 case 0x01: name = "Polish"; break;
3805                 }
3806                 break;
3807         case 0x16:
3808                 switch (secondary) {
3809                 case 0x00:
3810                 case 0x01: name = "Portuguese (Brazil)"; break;
3811                 case 0x02: name = "Portuguese (Portugal)"; break;
3812                 }
3813                 break;
3814         case 0x17:
3815                 switch (secondary) {
3816                 case 0x01: name = "Romansh (Switzerland)"; break;
3817                 }
3818                 break;
3819         case 0x18:
3820                 switch (secondary) {
3821                 case 0x00: name = "Romanian (Romania)"; break;
3822                 case 0x01: name = "Romanian"; break;
3823                 }
3824                 break;
3825         case 0x19:
3826                 switch (secondary) {
3827                 case 0x00: name = "Russian (Russia)"; break;
3828                 case 0x01: name = "Russian"; break;
3829                 }
3830                 break;
3831         case 0x1a:
3832                 switch (secondary) {
3833                 case 0x00: name = "Croatian (Croatia)"; break;
3834                 case 0x01: name = "Croatian"; break;
3835                 case 0x02: name = "Serbian (Latin)"; break;
3836                 case 0x03: name = "Serbian (Cyrillic)"; break;
3837                 case 0x04: name = "Croatian (Bosnia and Herzegovina)"; break;
3838                 case 0x05: name = "Bosnian (Latin, Bosnia and Herzegovina)"; break;
3839                 case 0x06: name = "Serbian (Latin, Bosnia and Herzegovina)"; break;
3840                 case 0x07: name = "Serbian (Cyrillic, Bosnia and Herzegovina)"; break;
3841                 case 0x08: name = "Bosnian (Cyrillic, Bosnia and Herzegovina)"; break;
3842                 }
3843                 break;
3844         case 0x1b:
3845                 switch (secondary) {
3846                 case 0x00: name = "Slovak (Slovakia)"; break;
3847                 case 0x01: name = "Slovak"; break;
3848                 }
3849                 break;
3850         case 0x1c:
3851                 switch (secondary) {
3852                 case 0x00: name = "Albanian (Albania)"; break;
3853                 case 0x01: name = "Albanian"; break;
3854                 }
3855                 break;
3856         case 0x1d:
3857                 switch (secondary) {
3858                 case 0x00: name = "Swedish (Sweden)"; break;
3859                 case 0x01: name = "Swedish"; break;
3860                 case 0x02: name = "Swedish (Finland)"; break;
3861                 }
3862                 break;
3863         case 0x1e:
3864                 switch (secondary) {
3865                 case 0x00: name = "Thai (Thailand)"; break;
3866                 case 0x01: name = "Thai"; break;
3867                 }
3868                 break;
3869         case 0x1f:
3870                 switch (secondary) {
3871                 case 0x00: name = "Turkish (Turkey)"; break;
3872                 case 0x01: name = "Turkish"; break;
3873                 }
3874                 break;
3875         case 0x20:
3876                 switch (secondary) {
3877                 case 0x00: name = "Urdu (Islamic Republic of Pakistan)"; break;
3878                 case 0x01: name = "Urdu"; break;
3879                 }
3880                 break;
3881         case 0x21:
3882                 switch (secondary) {
3883                 case 0x00: name = "Indonesian (Indonesia)"; break;
3884                 case 0x01: name = "Indonesian"; break;
3885                 }
3886                 break;
3887         case 0x22:
3888                 switch (secondary) {
3889                 case 0x00: name = "Ukrainian (Ukraine)"; break;
3890                 case 0x01: name = "Ukrainian"; break;
3891                 }
3892                 break;
3893         case 0x23:
3894                 switch (secondary) {
3895                 case 0x00: name = "Belarusian (Belarus)"; break;
3896                 case 0x01: name = "Belarusian"; break;
3897                 }
3898                 break;
3899         case 0x24:
3900                 switch (secondary) {
3901                 case 0x00: name = "Slovenian (Slovenia)"; break;
3902                 case 0x01: name = "Slovenian"; break;
3903                 }
3904                 break;
3905         case 0x25:
3906                 switch (secondary) {
3907                 case 0x00: name = "Estonian (Estonia)"; break;
3908                 case 0x01: name = "Estonian"; break;
3909                 }
3910                 break;
3911         case 0x26:
3912                 switch (secondary) {
3913                 case 0x00: name = "Latvian (Latvia)"; break;
3914                 case 0x01: name = "Latvian"; break;
3915                 }
3916                 break;
3917         case 0x27:
3918                 switch (secondary) {
3919                 case 0x00: name = "Lithuanian (Lithuania)"; break;
3920                 case 0x01: name = "Lithuanian"; break;
3921                 }
3922                 break;
3923         case 0x28:
3924                 switch (secondary) {
3925                 case 0x01: name = "Tajik (Tajikistan)"; break;
3926                 }
3927                 break;
3928         case 0x29:
3929                 switch (secondary) {
3930                 case 0x00: name = "Farsi (Iran)"; break;
3931                 case 0x01: name = "Farsi"; break;
3932                 }
3933                 break;
3934         case 0x2a:
3935                 switch (secondary) {
3936                 case 0x00: name = "Vietnamese (Viet Nam)"; break;
3937                 case 0x01: name = "Vietnamese"; break;
3938                 }
3939                 break;
3940         case 0x2b:
3941                 switch (secondary) {
3942                 case 0x00: name = "Armenian (Armenia)"; break;
3943                 case 0x01: name = "Armenian"; break;
3944                 }
3945                 break;
3946         case 0x2c:
3947                 switch (secondary) {
3948                 case 0x00: name = "Azeri (Latin) (Azerbaijan)"; break;
3949                 case 0x01: name = "Azeri (Latin)"; break;
3950                 case 0x02: name = "Azeri (Cyrillic)"; break;
3951                 }
3952                 break;
3953         case 0x2d:
3954                 switch (secondary) {
3955                 case 0x00: name = "Basque (Spain)"; break;
3956                 case 0x01: name = "Basque"; break;
3957                 }
3958                 break;
3959         case 0x2e:
3960                 switch (secondary) {
3961                 case 0x01: name = "Upper Sorbian (Germany)"; break;
3962                 case 0x02: name = "Lower Sorbian (Germany)"; break;
3963                 }
3964                 break;
3965         case 0x2f:
3966                 switch (secondary) {
3967                 case 0x00: name = "FYRO Macedonian (Former Yugoslav Republic of Macedonia)"; break;
3968                 case 0x01: name = "FYRO Macedonian"; break;
3969                 }
3970                 break;
3971         case 0x32:
3972                 switch (secondary) {
3973                 case 0x00: name = "Tswana (South Africa)"; break;
3974                 case 0x01: name = "Tswana"; break;
3975                 }
3976                 break;
3977         case 0x34:
3978                 switch (secondary) {
3979                 case 0x00: name = "Xhosa (South Africa)"; break;
3980                 case 0x01: name = "Xhosa"; break;
3981                 }
3982                 break;
3983         case 0x35:
3984                 switch (secondary) {
3985                 case 0x00: name = "Zulu (South Africa)"; break;
3986                 case 0x01: name = "Zulu"; break;
3987                 }
3988                 break;
3989         case 0x36:
3990                 switch (secondary) {
3991                 case 0x00: name = "Afrikaans (South Africa)"; break;
3992                 case 0x01: name = "Afrikaans"; break;
3993                 }
3994                 break;
3995         case 0x37:
3996                 switch (secondary) {
3997                 case 0x00: name = "Georgian (Georgia)"; break;
3998                 case 0x01: name = "Georgian"; break;
3999                 }
4000                 break;
4001         case 0x38:
4002                 switch (secondary) {
4003                 case 0x00: name = "Faroese (Faroe Islands)"; break;
4004                 case 0x01: name = "Faroese"; break;
4005                 }
4006                 break;
4007         case 0x39:
4008                 switch (secondary) {
4009                 case 0x00: name = "Hindi (India)"; break;
4010                 case 0x01: name = "Hindi"; break;
4011                 }
4012                 break;
4013         case 0x3a:
4014                 switch (secondary) {
4015                 case 0x00: name = "Maltese (Malta)"; break;
4016                 case 0x01: name = "Maltese"; break;
4017                 }
4018                 break;
4019         case 0x3b:
4020                 switch (secondary) {
4021                 case 0x00: name = "Sami (Northern) (Norway)"; break;
4022                 case 0x01: name = "Sami, Northern (Norway)"; break;
4023                 case 0x02: name = "Sami, Northern (Sweden)"; break;
4024                 case 0x03: name = "Sami, Northern (Finland)"; break;
4025                 case 0x04: name = "Sami, Lule (Norway)"; break;
4026                 case 0x05: name = "Sami, Lule (Sweden)"; break;
4027                 case 0x06: name = "Sami, Southern (Norway)"; break;
4028                 case 0x07: name = "Sami, Southern (Sweden)"; break;
4029                 case 0x08: name = "Sami, Skolt (Finland)"; break;
4030                 case 0x09: name = "Sami, Inari (Finland)"; break;
4031                 }
4032                 break;
4033         case 0x3c:
4034                 switch (secondary) {
4035                 case 0x02: name = "Irish (Ireland)"; break;
4036                 }
4037                 break;
4038         case 0x3e:
4039                 switch (secondary) {
4040                 case 0x00:
4041                 case 0x01: name = "Malay (Malaysia)"; break;
4042                 case 0x02: name = "Malay (Brunei Darussalam)"; break;
4043                 }
4044                 break;
4045         case 0x3f:
4046                 switch (secondary) {
4047                 case 0x00: name = "Kazakh (Kazakhstan)"; break;
4048                 case 0x01: name = "Kazakh"; break;
4049                 }
4050                 break;
4051         case 0x40:
4052                 switch (secondary) {
4053                 case 0x00: name = "Kyrgyz (Kyrgyzstan)"; break;
4054                 case 0x01: name = "Kyrgyz (Cyrillic)"; break;
4055                 }
4056                 break;
4057         case 0x41:
4058                 switch (secondary) {
4059                 case 0x00: name = "Swahili (Kenya)"; break;
4060                 case 0x01: name = "Swahili"; break;
4061                 }
4062                 break;
4063         case 0x42:
4064                 switch (secondary) {
4065                 case 0x01: name = "Turkmen (Turkmenistan)"; break;
4066                 }
4067                 break;
4068         case 0x43:
4069                 switch (secondary) {
4070                 case 0x00: name = "Uzbek (Latin) (Uzbekistan)"; break;
4071                 case 0x01: name = "Uzbek (Latin)"; break;
4072                 case 0x02: name = "Uzbek (Cyrillic)"; break;
4073                 }
4074                 break;
4075         case 0x44:
4076                 switch (secondary) {
4077                 case 0x00: name = "Tatar (Russia)"; break;
4078                 case 0x01: name = "Tatar"; break;
4079                 }
4080                 break;
4081         case 0x45:
4082                 switch (secondary) {
4083                 case 0x00:
4084                 case 0x01: name = "Bengali (India)"; break;
4085                 }
4086                 break;
4087         case 0x46:
4088                 switch (secondary) {
4089                 case 0x00: name = "Punjabi (India)"; break;
4090                 case 0x01: name = "Punjabi"; break;
4091                 }
4092                 break;
4093         case 0x47:
4094                 switch (secondary) {
4095                 case 0x00: name = "Gujarati (India)"; break;
4096                 case 0x01: name = "Gujarati"; break;
4097                 }
4098                 break;
4099         case 0x49:
4100                 switch (secondary) {
4101                 case 0x00: name = "Tamil (India)"; break;
4102                 case 0x01: name = "Tamil"; break;
4103                 }
4104                 break;
4105         case 0x4a:
4106                 switch (secondary) {
4107                 case 0x00: name = "Telugu (India)"; break;
4108                 case 0x01: name = "Telugu"; break;
4109                 }
4110                 break;
4111         case 0x4b:
4112                 switch (secondary) {
4113                 case 0x00: name = "Kannada (India)"; break;
4114                 case 0x01: name = "Kannada"; break;
4115                 }
4116                 break;
4117         case 0x4c:
4118                 switch (secondary) {
4119                 case 0x00:
4120                 case 0x01: name = "Malayalam (India)"; break;
4121                 }
4122                 break;
4123         case 0x4d:
4124                 switch (secondary) {
4125                 case 0x01: name = "Assamese (India)"; break;
4126                 }
4127                 break;
4128         case 0x4e:
4129                 switch (secondary) {
4130                 case 0x00: name = "Marathi (India)"; break;
4131                 case 0x01: name = "Marathi"; break;
4132                 }
4133                 break;
4134         case 0x4f:
4135                 switch (secondary) {
4136                 case 0x00: name = "Sanskrit (India)"; break;
4137                 case 0x01: name = "Sanskrit"; break;
4138                 }
4139                 break;
4140         case 0x50:
4141                 switch (secondary) {
4142                 case 0x00: name = "Mongolian (Mongolia)"; break;
4143                 case 0x01: name = "Mongolian (Cyrillic)"; break;
4144                 case 0x02: name = "Mongolian (PRC)"; break;
4145                 }
4146                 break;
4147         case 0x51:
4148                 switch (secondary) {
4149                 case 0x01: name = "Tibetan (PRC)"; break;
4150                 case 0x02: name = "Tibetan (Bhutan)"; break;
4151                 }
4152                 break;
4153         case 0x52:
4154                 switch (secondary) {
4155                 case 0x00: name = "Welsh (United Kingdom)"; break;
4156                 case 0x01: name = "Welsh"; break;
4157                 }
4158                 break;
4159         case 0x53:
4160                 switch (secondary) {
4161                 case 0x01: name = "Khmer (Cambodia)"; break;
4162                 }
4163                 break;
4164         case 0x54:
4165                 switch (secondary) {
4166                 case 0x01: name = "Lao (Lao PDR)"; break;
4167                 }
4168                 break;
4169         case 0x56:
4170                 switch (secondary) {
4171                 case 0x00: name = "Galician (Spain)"; break;
4172                 case 0x01: name = "Galician"; break;
4173                 }
4174                 break;
4175         case 0x57:
4176                 switch (secondary) {
4177                 case 0x00: name = "Konkani (India)"; break;
4178                 case 0x01: name = "Konkani"; break;
4179                 }
4180                 break;
4181         case 0x5a:
4182                 switch (secondary) {
4183                 case 0x00: name = "Syriac (Syria)"; break;
4184                 case 0x01: name = "Syriac"; break;
4185                 }
4186                 break;
4187         case 0x5b:
4188                 switch (secondary) {
4189                 case 0x01: name = "Sinhala (Sri Lanka)"; break;
4190                 }
4191                 break;
4192         case 0x5d:
4193                 switch (secondary) {
4194                 case 0x01: name = "Inuktitut (Syllabics, Canada)"; break;
4195                 case 0x02: name = "Inuktitut (Latin, Canada)"; break;
4196                 }
4197                 break;
4198         case 0x5e:
4199                 switch (secondary) {
4200                 case 0x01: name = "Amharic (Ethiopia)"; break;
4201                 }
4202                 break;
4203         case 0x5f:
4204                 switch (secondary) {
4205                 case 0x02: name = "Tamazight (Algeria, Latin)"; break;
4206                 }
4207                 break;
4208         case 0x61:
4209                 switch (secondary) {
4210                 case 0x01: name = "Nepali (Nepal)"; break;
4211                 }
4212                 break;
4213         case 0x62:
4214                 switch (secondary) {
4215                 case 0x01: name = "Frisian (Netherlands)"; break;
4216                 }
4217                 break;
4218         case 0x63:
4219                 switch (secondary) {
4220                 case 0x01: name = "Pashto (Afghanistan)"; break;
4221                 }
4222                 break;
4223         case 0x64:
4224                 switch (secondary) {
4225                 case 0x01: name = "Filipino (Philippines)"; break;
4226                 }
4227                 break;
4228         case 0x65:
4229                 switch (secondary) {
4230                 case 0x00: name = "Divehi (Maldives)"; break;
4231                 case 0x01: name = "Divehi"; break;
4232                 }
4233                 break;
4234         case 0x68:
4235                 switch (secondary) {
4236                 case 0x01: name = "Hausa (Nigeria, Latin)"; break;
4237                 }
4238                 break;
4239         case 0x6a:
4240                 switch (secondary) {
4241                 case 0x01: name = "Yoruba (Nigeria)"; break;
4242                 }
4243                 break;
4244         case 0x6b:
4245                 switch (secondary) {
4246                 case 0x00:
4247                 case 0x01: name = "Quechua (Bolivia)"; break;
4248                 case 0x02: name = "Quechua (Ecuador)"; break;
4249                 case 0x03: name = "Quechua (Peru)"; break;
4250                 }
4251                 break;
4252         case 0x6c:
4253                 switch (secondary) {
4254                 case 0x00: name = "Northern Sotho (South Africa)"; break;
4255                 case 0x01: name = "Northern Sotho"; break;
4256                 }
4257                 break;
4258         case 0x6d:
4259                 switch (secondary) {
4260                 case 0x01: name = "Bashkir (Russia)"; break;
4261                 }
4262                 break;
4263         case 0x6e:
4264                 switch (secondary) {
4265                 case 0x01: name = "Luxembourgish (Luxembourg)"; break;
4266                 }
4267                 break;
4268         case 0x6f:
4269                 switch (secondary) {
4270                 case 0x01: name = "Greenlandic (Greenland)"; break;
4271                 }
4272                 break;
4273         case 0x78:
4274                 switch (secondary) {
4275                 case 0x01: name = "Yi (PRC)"; break;
4276                 }
4277                 break;
4278         case 0x7a:
4279                 switch (secondary) {
4280                 case 0x01: name = "Mapudungun (Chile)"; break;
4281                 }
4282                 break;
4283         case 0x7c:
4284                 switch (secondary) {
4285                 case 0x01: name = "Mohawk (Mohawk)"; break;
4286                 }
4287                 break;
4288         case 0x7e:
4289                 switch (secondary) {
4290                 case 0x01: name = "Breton (France)"; break;
4291                 }
4292                 break;
4293         case 0x7f:
4294                 switch (secondary) {
4295                 case 0x00: name = "Invariant Language (Invariant Country)"; break;
4296                 }
4297                 break;
4298         case 0x80:
4299                 switch (secondary) {
4300                 case 0x01: name = "Uighur (PRC)"; break;
4301                 }
4302                 break;
4303         case 0x81:
4304                 switch (secondary) {
4305                 case 0x00: name = "Maori (New Zealand)"; break;
4306                 case 0x01: name = "Maori"; break;
4307                 }
4308                 break;
4309         case 0x83:
4310                 switch (secondary) {
4311                 case 0x01: name = "Corsican (France)"; break;
4312                 }
4313                 break;
4314         case 0x84:
4315                 switch (secondary) {
4316                 case 0x01: name = "Alsatian (France)"; break;
4317                 }
4318                 break;
4319         case 0x85:
4320                 switch (secondary) {
4321                 case 0x01: name = "Yakut (Russia)"; break;
4322                 }
4323                 break;
4324         case 0x86:
4325                 switch (secondary) {
4326                 case 0x01: name = "K'iche (Guatemala)"; break;
4327                 }
4328                 break;
4329         case 0x87:
4330                 switch (secondary) {
4331                 case 0x01: name = "Kinyarwanda (Rwanda)"; break;
4332                 }
4333                 break;
4334         case 0x88:
4335                 switch (secondary) {
4336                 case 0x01: name = "Wolof (Senegal)"; break;
4337                 }
4338                 break;
4339         case 0x8c:
4340                 switch (secondary) {
4341                 case 0x01: name = "Dari (Afghanistan)"; break;
4342                 }
4343                 break;
4344
4345         default:
4346                 name = "Language Neutral";
4347
4348         }
4349
4350         if (!name)
4351                 name = "Language Neutral";
4352
4353         return copy_lang (lang_out, lang_len, name);
4354 }