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