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