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