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