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