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