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