2 * process.c: System.Diagnostics.Process support
5 * Dick Porter (dick@ximian.com)
7 * Copyright 2002 Ximian, Inc.
8 * Copyright 2002-2006 Novell, Inc.
9 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
21 #include <sys/types.h>
29 #ifdef HAVE_SYS_PARAM_H
30 #include <sys/param.h>
34 #ifdef HAVE_SYS_WAIT_H
37 #ifdef HAVE_SYS_RESOURCE_H
38 #include <sys/resource.h>
41 #ifdef HAVE_SYS_MKDEV_H
42 #include <sys/mkdev.h>
49 #include <mono/metadata/w32process.h>
50 #include <mono/metadata/w32process-internals.h>
51 #include <mono/metadata/w32process-unix-internals.h>
52 #include <mono/metadata/w32error.h>
53 #include <mono/metadata/class.h>
54 #include <mono/metadata/class-internals.h>
55 #include <mono/metadata/object.h>
56 #include <mono/metadata/object-internals.h>
57 #include <mono/metadata/metadata.h>
58 #include <mono/metadata/metadata-internals.h>
59 #include <mono/metadata/exception.h>
60 #include <mono/metadata/w32handle.h>
61 #include <mono/metadata/w32file.h>
62 #include <mono/utils/mono-membar.h>
63 #include <mono/utils/mono-logger-internals.h>
64 #include <mono/utils/strenc.h>
65 #include <mono/utils/mono-proclib.h>
66 #include <mono/utils/mono-path.h>
67 #include <mono/utils/mono-lazy-init.h>
68 #include <mono/utils/mono-signal-handler.h>
69 #include <mono/utils/mono-time.h>
70 #include <mono/utils/mono-mmap.h>
71 #include <mono/utils/strenc.h>
72 #include <mono/utils/mono-io-portability.h>
73 #include <mono/utils/w32api.h>
76 #define MAXPATHLEN 242
79 #define STILL_ACTIVE ((int) 0x00000103)
82 /* define LOGDEBUG(...) g_message(__VA_ARGS__) */
84 /* The process' environment strings */
85 #if defined(__APPLE__)
86 #if defined (TARGET_OSX)
87 /* Apple defines this in crt_externs.h but doesn't provide that header for
88 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
89 * in fact exist on all implementations (so far)
91 gchar ***_NSGetEnviron(void);
92 #define environ (*_NSGetEnviron())
94 static char *mono_environ[1] = { NULL };
95 #define environ mono_environ
96 #endif /* defined (TARGET_OSX) */
98 extern char **environ;
102 STARTF_USESHOWWINDOW=0x001,
103 STARTF_USESIZE=0x002,
104 STARTF_USEPOSITION=0x004,
105 STARTF_USECOUNTCHARS=0x008,
106 STARTF_USEFILLATTRIBUTE=0x010,
107 STARTF_RUNFULLSCREEN=0x020,
108 STARTF_FORCEONFEEDBACK=0x040,
109 STARTF_FORCEOFFFEEDBACK=0x080,
110 STARTF_USESTDHANDLES=0x100
120 #if G_BYTE_ORDER == G_BIG_ENDIAN
121 guint32 highDateTime;
125 guint32 highDateTime;
130 * Process describes processes we create.
131 * It contains a semaphore that can be waited on in order to wait
132 * for process termination. It's accessed in our SIGCHLD handler,
133 * when status is updated (and pid cleared, to not clash with
134 * subsequent processes that may get executed).
136 typedef struct _Process {
137 pid_t pid; /* the pid of the process. This value is only valid until the process has exited. */
138 MonoSemType exit_sem; /* this semaphore will be released when the process exits */
139 int status; /* the exit status */
140 gint32 handle_count; /* the number of handles to this process instance */
141 /* we keep a ref to the creating _WapiHandle_process handle until
142 * the process has exited, so that the information there isn't lost.
147 struct _Process *next;
150 /* MonoW32HandleProcess is a structure containing all the required information for process handling. */
155 gpointer main_thread;
159 size_t min_working_set;
160 size_t max_working_set;
163 } MonoW32HandleProcess;
168 * 2 bytes: Length in bytes (this block, and all child blocks. does _not_ include alignment padding between blocks)
169 * 2 bytes: Length in bytes of VS_FIXEDFILEINFO struct
170 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
171 * Variable length unicode string (null terminated): Key (currently "VS_VERSION_INFO")
172 * Variable length padding to align VS_FIXEDFILEINFO on a 32-bit boundary
173 * VS_FIXEDFILEINFO struct
174 * Variable length padding to align Child struct on a 32-bit boundary
175 * Child struct (zero or one StringFileInfo structs, zero or one VarFileInfo structs)
181 * 2 bytes: Length in bytes (includes this block, as well as all Child blocks)
182 * 2 bytes: Value length (always zero)
183 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
184 * Variable length unicode string: Key (currently "StringFileInfo")
185 * Variable length padding to align Child struct on a 32-bit boundary
186 * 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.)
192 * 2 bytes: Length in bytes (includes this block as well as all Child blocks, but excludes any padding between String blocks)
193 * 2 bytes: Value length (always zero)
194 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
195 * Variable length unicode string: Key. 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.
196 * Variable length padding to align Child struct on a 32-bit boundary
197 * Child structs (an array of one or more String structs (each aligned on a 32-bit boundary)
203 * 2 bytes: Length in bytes (of this block)
204 * 2 bytes: Value length (the length in words of the Value member)
205 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
206 * Variable length unicode string: Key. arbitrary string, identifies data.
207 * Variable length padding to align Value on a 32-bit boundary
208 * Value: Variable length unicode string, holding data.
214 * 2 bytes: Length in bytes (includes this block, as well as all Child blocks)
215 * 2 bytes: Value length (always zero)
216 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
217 * Variable length unicode string: Key (currently "VarFileInfo")
218 * Variable length padding to align Child struct on a 32-bit boundary
219 * Child structs (a Var struct)
225 * 2 bytes: Length in bytes of this block
226 * 2 bytes: Value length in bytes of the Value
227 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
228 * Variable length unicode string: Key ("Translation")
229 * Variable length padding to align Value on a 32-bit boundary
230 * 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.
233 #if G_BYTE_ORDER == G_BIG_ENDIAN
234 #define VS_FFI_SIGNATURE 0xbd04effe
235 #define VS_FFI_STRUCVERSION 0x00000100
237 #define VS_FFI_SIGNATURE 0xfeef04bd
238 #define VS_FFI_STRUCVERSION 0x00010000
241 #define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16
243 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0
244 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1
245 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2
247 #define IMAGE_SIZEOF_SHORT_NAME 8
249 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
250 #define IMAGE_DOS_SIGNATURE 0x4d5a
251 #define IMAGE_NT_SIGNATURE 0x50450000
252 #define IMAGE_NT_OPTIONAL_HDR32_MAGIC 0xb10
253 #define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0xb20
255 #define IMAGE_DOS_SIGNATURE 0x5a4d
256 #define IMAGE_NT_SIGNATURE 0x00004550
257 #define IMAGE_NT_OPTIONAL_HDR32_MAGIC 0x10b
258 #define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b
285 guint16 NumberOfSections;
286 guint32 TimeDateStamp;
287 guint32 PointerToSymbolTable;
288 guint32 NumberOfSymbols;
289 guint16 SizeOfOptionalHeader;
290 guint16 Characteristics;
294 guint32 VirtualAddress;
296 } IMAGE_DATA_DIRECTORY;
300 guint8 MajorLinkerVersion;
301 guint8 MinorLinkerVersion;
303 guint32 SizeOfInitializedData;
304 guint32 SizeOfUninitializedData;
305 guint32 AddressOfEntryPoint;
309 guint32 SectionAlignment;
310 guint32 FileAlignment;
311 guint16 MajorOperatingSystemVersion;
312 guint16 MinorOperatingSystemVersion;
313 guint16 MajorImageVersion;
314 guint16 MinorImageVersion;
315 guint16 MajorSubsystemVersion;
316 guint16 MinorSubsystemVersion;
317 guint32 Win32VersionValue;
319 guint32 SizeOfHeaders;
322 guint16 DllCharacteristics;
323 guint32 SizeOfStackReserve;
324 guint32 SizeOfStackCommit;
325 guint32 SizeOfHeapReserve;
326 guint32 SizeOfHeapCommit;
328 guint32 NumberOfRvaAndSizes;
329 IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
330 } IMAGE_OPTIONAL_HEADER32;
334 guint8 MajorLinkerVersion;
335 guint8 MinorLinkerVersion;
337 guint32 SizeOfInitializedData;
338 guint32 SizeOfUninitializedData;
339 guint32 AddressOfEntryPoint;
342 guint32 SectionAlignment;
343 guint32 FileAlignment;
344 guint16 MajorOperatingSystemVersion;
345 guint16 MinorOperatingSystemVersion;
346 guint16 MajorImageVersion;
347 guint16 MinorImageVersion;
348 guint16 MajorSubsystemVersion;
349 guint16 MinorSubsystemVersion;
350 guint32 Win32VersionValue;
352 guint32 SizeOfHeaders;
355 guint16 DllCharacteristics;
356 guint64 SizeOfStackReserve;
357 guint64 SizeOfStackCommit;
358 guint64 SizeOfHeapReserve;
359 guint64 SizeOfHeapCommit;
361 guint32 NumberOfRvaAndSizes;
362 IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
363 } IMAGE_OPTIONAL_HEADER64;
365 #if SIZEOF_VOID_P == 8
366 typedef IMAGE_OPTIONAL_HEADER64 IMAGE_OPTIONAL_HEADER;
368 typedef IMAGE_OPTIONAL_HEADER32 IMAGE_OPTIONAL_HEADER;
373 IMAGE_FILE_HEADER FileHeader;
374 IMAGE_OPTIONAL_HEADER32 OptionalHeader;
375 } IMAGE_NT_HEADERS32;
379 IMAGE_FILE_HEADER FileHeader;
380 IMAGE_OPTIONAL_HEADER64 OptionalHeader;
381 } IMAGE_NT_HEADERS64;
383 #if SIZEOF_VOID_P == 8
384 typedef IMAGE_NT_HEADERS64 IMAGE_NT_HEADERS;
386 typedef IMAGE_NT_HEADERS32 IMAGE_NT_HEADERS;
390 guint8 Name[IMAGE_SIZEOF_SHORT_NAME];
392 guint32 PhysicalAddress;
395 guint32 VirtualAddress;
396 guint32 SizeOfRawData;
397 guint32 PointerToRawData;
398 guint32 PointerToRelocations;
399 guint32 PointerToLinenumbers;
400 guint16 NumberOfRelocations;
401 guint16 NumberOfLinenumbers;
402 guint32 Characteristics;
403 } IMAGE_SECTION_HEADER;
405 #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)))
407 #define RT_CURSOR 0x01
408 #define RT_BITMAP 0x02
411 #define RT_DIALOG 0x05
412 #define RT_STRING 0x06
413 #define RT_FONTDIR 0x07
415 #define RT_ACCELERATOR 0x09
416 #define RT_RCDATA 0x0a
417 #define RT_MESSAGETABLE 0x0b
418 #define RT_GROUP_CURSOR 0x0c
419 #define RT_GROUP_ICON 0x0e
420 #define RT_VERSION 0x10
421 #define RT_DLGINCLUDE 0x11
422 #define RT_PLUGPLAY 0x13
424 #define RT_ANICURSOR 0x15
425 #define RT_ANIICON 0x16
427 #define RT_MANIFEST 0x18
430 guint32 Characteristics;
431 guint32 TimeDateStamp;
432 guint16 MajorVersion;
433 guint16 MinorVersion;
434 guint16 NumberOfNamedEntries;
435 guint16 NumberOfIdEntries;
436 } IMAGE_RESOURCE_DIRECTORY;
441 #if G_BYTE_ORDER == G_BIG_ENDIAN
442 guint32 NameIsString:1;
443 guint32 NameOffset:31;
445 guint32 NameOffset:31;
446 guint32 NameIsString:1;
450 #if G_BYTE_ORDER == G_BIG_ENDIAN
452 guint16 __wapi_big_endian_padding;
460 guint32 OffsetToData;
462 #if G_BYTE_ORDER == G_BIG_ENDIAN
463 guint32 DataIsDirectory:1;
464 guint32 OffsetToDirectory:31;
466 guint32 OffsetToDirectory:31;
467 guint32 DataIsDirectory:1;
471 } IMAGE_RESOURCE_DIRECTORY_ENTRY;
474 guint32 OffsetToData;
478 } IMAGE_RESOURCE_DATA_ENTRY;
480 #define VOS_UNKNOWN 0x00000000
481 #define VOS_DOS 0x00010000
482 #define VOS_OS216 0x00020000
483 #define VOS_OS232 0x00030000
484 #define VOS_NT 0x00040000
485 #define VOS__BASE 0x00000000
486 #define VOS__WINDOWS16 0x00000001
487 #define VOS__PM16 0x00000002
488 #define VOS__PM32 0x00000003
489 #define VOS__WINDOWS32 0x00000004
490 /* Should "embrace and extend" here with some entries for linux etc */
492 #define VOS_DOS_WINDOWS16 0x00010001
493 #define VOS_DOS_WINDOWS32 0x00010004
494 #define VOS_OS216_PM16 0x00020002
495 #define VOS_OS232_PM32 0x00030003
496 #define VOS_NT_WINDOWS32 0x00040004
498 #define VFT_UNKNOWN 0x0000
499 #define VFT_APP 0x0001
500 #define VFT_DLL 0x0002
501 #define VFT_DRV 0x0003
502 #define VFT_FONT 0x0004
503 #define VFT_VXD 0x0005
504 #define VFT_STATIC_LIB 0x0007
506 #define VFT2_UNKNOWN 0x0000
507 #define VFT2_DRV_PRINTER 0x0001
508 #define VFT2_DRV_KEYBOARD 0x0002
509 #define VFT2_DRV_LANGUAGE 0x0003
510 #define VFT2_DRV_DISPLAY 0x0004
511 #define VFT2_DRV_MOUSE 0x0005
512 #define VFT2_DRV_NETWORK 0x0006
513 #define VFT2_DRV_SYSTEM 0x0007
514 #define VFT2_DRV_INSTALLABLE 0x0008
515 #define VFT2_DRV_SOUND 0x0009
516 #define VFT2_DRV_COMM 0x000a
517 #define VFT2_DRV_INPUTMETHOD 0x000b
518 #define VFT2_FONT_RASTER 0x0001
519 #define VFT2_FONT_VECTOR 0x0002
520 #define VFT2_FONT_TRUETYPE 0x0003
522 #define MAKELANGID(primary,secondary) ((guint16)((secondary << 10) | (primary)))
524 #define ALIGN32(ptr) ptr = (gpointer)((char *)ptr + 3); ptr = (gpointer)((char *)ptr - ((gsize)ptr & 3));
527 static mono_lazy_init_t process_sig_chld_once = MONO_LAZY_INIT_STATUS_NOT_INITIALIZED;
530 static gchar *cli_launcher;
532 /* The signal-safe logic to use processes goes like this:
533 * - The list must be safe to traverse for the signal handler at all times.
534 * It's safe to: prepend an entry (which is a single store to 'processes'),
535 * unlink an entry (assuming the unlinked entry isn't freed and doesn't
536 * change its 'next' pointer so that it can still be traversed).
537 * When cleaning up we first unlink an entry, then we verify that
538 * the read lock isn't locked. Then we can free the entry, since
539 * we know that nobody is using the old version of the list (including
540 * the unlinked entry).
541 * We also need to lock when adding and cleaning up so that those two
542 * operations don't mess with eachother. (This lock is not used in the
544 static Process *processes;
545 static mono_mutex_t processes_mutex;
547 static pid_t current_pid;
548 static gpointer current_process;
550 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
551 static const gunichar2 *utf16_space = utf16_space_bytes;
552 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
553 static const gunichar2 *utf16_quote = utf16_quote_bytes;
555 /* Check if a pid is valid - i.e. if a process exists with this pid. */
557 process_is_alive (pid_t pid)
559 #if defined(HOST_WATCHOS)
560 return TRUE; // TODO: Rewrite using sysctl
561 #elif defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__)
564 if (kill (pid, 0) == 0)
569 #elif defined(__HAIKU__)
571 if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
575 gchar *dir = g_strdup_printf ("/proc/%d", pid);
576 gboolean result = access (dir, F_OK) == 0;
583 process_details (gpointer data)
585 MonoW32HandleProcess *process_handle = (MonoW32HandleProcess *) data;
586 g_print ("pid: %d, exited: %s, exitstatus: %d",
587 process_handle->pid, process_handle->exited ? "true" : "false", process_handle->exitstatus);
591 process_typename (void)
597 process_typesize (void)
599 return sizeof (MonoW32HandleProcess);
602 static MonoW32HandleWaitRet
603 process_wait (gpointer handle, guint32 timeout, gboolean *alerted)
605 MonoW32HandleProcess *process_handle;
606 pid_t pid G_GNUC_UNUSED, ret;
612 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u)", __func__, handle, timeout);
617 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
619 g_warning ("%s: error looking up process handle %p", __func__, handle);
620 return MONO_W32HANDLE_WAIT_RET_FAILED;
623 if (process_handle->exited) {
624 /* We've already done this one */
625 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): Process already exited", __func__, handle, timeout);
626 return MONO_W32HANDLE_WAIT_RET_SUCCESS_0;
629 pid = process_handle->pid;
631 if (pid == mono_process_current_pid ()) {
632 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on current process", __func__, handle, timeout);
633 return MONO_W32HANDLE_WAIT_RET_TIMEOUT;
636 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
638 if (!process_handle->child) {
639 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on non-child process", __func__, handle, timeout);
641 if (!process_is_alive (pid)) {
642 /* assume the process has exited */
643 process_handle->exited = TRUE;
644 process_handle->exitstatus = -1;
645 mono_w32handle_set_signal_state (handle, TRUE, TRUE);
647 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): non-child process is not alive anymore (2)", __func__, handle, timeout);
648 return MONO_W32HANDLE_WAIT_RET_SUCCESS_0;
651 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): non-child process wait failed, error : %s (%d))", __func__, handle, timeout, g_strerror (errno), errno);
652 return MONO_W32HANDLE_WAIT_RET_FAILED;
655 /* We don't need to lock processes here, the entry
656 * has a handle_count > 0 which means it will not be freed. */
657 process = process_handle->process;
660 start = mono_msec_ticks ();
664 if (timeout != MONO_INFINITE_WAIT) {
665 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on semaphore for %li ms...",
666 __func__, handle, timeout, (long)(timeout - (now - start)));
667 ret = mono_os_sem_timedwait (&process->exit_sem, (timeout - (now - start)), alerted ? MONO_SEM_FLAGS_ALERTABLE : MONO_SEM_FLAGS_NONE);
669 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on semaphore forever...",
670 __func__, handle, timeout);
671 ret = mono_os_sem_wait (&process->exit_sem, alerted ? MONO_SEM_FLAGS_ALERTABLE : MONO_SEM_FLAGS_NONE);
674 if (ret == MONO_SEM_TIMEDWAIT_RET_SUCCESS) {
675 /* Success, process has exited */
676 mono_os_sem_post (&process->exit_sem);
680 if (ret == MONO_SEM_TIMEDWAIT_RET_TIMEDOUT) {
681 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): wait timeout (timeout = 0)", __func__, handle, timeout);
682 return MONO_W32HANDLE_WAIT_RET_TIMEOUT;
685 now = mono_msec_ticks ();
686 if (now - start >= timeout) {
687 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): wait timeout", __func__, handle, timeout);
688 return MONO_W32HANDLE_WAIT_RET_TIMEOUT;
691 if (alerted && ret == MONO_SEM_TIMEDWAIT_RET_ALERTED) {
692 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): wait alerted", __func__, handle, timeout);
694 return MONO_W32HANDLE_WAIT_RET_ALERTED;
698 /* Process must have exited */
699 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): Waited successfully", __func__, handle, timeout);
701 status = process->status;
702 if (WIFSIGNALED (status))
703 process_handle->exitstatus = 128 + WTERMSIG (status);
705 process_handle->exitstatus = WEXITSTATUS (status);
707 process_handle->exit_time = mono_100ns_datetime ();
709 process_handle->exited = TRUE;
711 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): Setting pid %d signalled, exit status %d",
712 __func__, handle, timeout, process_handle->pid, process_handle->exitstatus);
714 mono_w32handle_set_signal_state (handle, TRUE, TRUE);
716 return MONO_W32HANDLE_WAIT_RET_SUCCESS_0;
720 processes_cleanup (void)
722 static gint32 cleaning_up;
724 Process *prev = NULL;
725 GSList *finished = NULL;
728 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s", __func__);
730 /* Ensure we're not in here in multiple threads at once, nor recursive. */
731 if (InterlockedCompareExchange (&cleaning_up, 1, 0) != 0)
734 for (process = processes; process; process = process->next) {
735 if (process->signalled && process->handle) {
736 /* This process has exited and we need to remove the artifical ref
738 mono_w32handle_unref (process->handle);
739 process->handle = NULL;
744 * Remove processes which exited from the processes list.
745 * We need to synchronize with the sigchld handler here, which runs
746 * asynchronously. The handler requires that the processes list
749 mono_os_mutex_lock (&processes_mutex);
751 for (process = processes; process; process = process->next) {
752 if (process->handle_count == 0 && process->freeable) {
755 * This code can run parallel with the sigchld handler, but the
756 * modifications it makes are safe.
758 if (process == processes)
759 processes = process->next;
761 prev->next = process->next;
762 finished = g_slist_prepend (finished, process);
768 mono_memory_barrier ();
770 for (l = finished; l; l = l->next) {
772 * All the entries in the finished list are unlinked from processes, and
773 * they have the 'finished' flag set, which means the sigchld handler is done
776 process = (Process *)l->data;
777 mono_os_sem_destroy (&process->exit_sem);
780 g_slist_free (finished);
782 mono_os_mutex_unlock (&processes_mutex);
784 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s done", __func__);
786 InterlockedExchange (&cleaning_up, 0);
790 process_close (gpointer handle, gpointer data)
792 MonoW32HandleProcess *process_handle;
794 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s", __func__);
796 process_handle = (MonoW32HandleProcess *) data;
797 g_free (process_handle->pname);
798 process_handle->pname = NULL;
799 if (process_handle->process)
800 InterlockedDecrement (&process_handle->process->handle_count);
801 processes_cleanup ();
804 static MonoW32HandleOps process_ops = {
805 process_close, /* close_shared */
809 process_wait, /* special_wait */
811 process_details, /* details */
812 process_typename, /* typename */
813 process_typesize, /* typesize */
817 process_set_defaults (MonoW32HandleProcess *process_handle)
819 /* These seem to be the defaults on w2k */
820 process_handle->min_working_set = 204800;
821 process_handle->max_working_set = 1413120;
823 process_handle->create_time = mono_100ns_datetime ();
827 process_set_name (MonoW32HandleProcess *process_handle)
829 char *progname, *utf8_progname, *slash;
831 progname = g_get_prgname ();
832 utf8_progname = mono_utf8_from_external (progname);
834 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: using [%s] as prog name", __func__, progname);
837 slash = strrchr (utf8_progname, '/');
839 process_handle->pname = g_strdup (slash+1);
841 process_handle->pname = g_strdup (utf8_progname);
842 g_free (utf8_progname);
847 mono_w32process_init (void)
849 MonoW32HandleProcess process_handle;
851 mono_w32handle_register_ops (MONO_W32HANDLE_PROCESS, &process_ops);
853 mono_w32handle_register_capabilities (MONO_W32HANDLE_PROCESS,
854 (MonoW32HandleCapability)(MONO_W32HANDLE_CAP_WAIT | MONO_W32HANDLE_CAP_SPECIAL_WAIT));
856 current_pid = getpid ();
858 memset (&process_handle, 0, sizeof (process_handle));
859 process_handle.pid = current_pid;
860 process_set_defaults (&process_handle);
861 process_set_name (&process_handle);
863 current_process = mono_w32handle_new (MONO_W32HANDLE_PROCESS, &process_handle);
864 g_assert (current_process);
866 mono_os_mutex_init (&processes_mutex);
870 mono_w32process_cleanup (void)
872 g_free (cli_launcher);
876 len16 (const gunichar2 *str)
887 utf16_concat (const gunichar2 *first, ...)
895 va_start (args, first);
896 total += len16 (first);
897 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *))
901 ret = g_new (gunichar2, total + 1);
907 for (s = first; *s != 0; s++)
909 va_start (args, first);
910 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
911 for (p = s; *p != 0; p++)
920 mono_w32process_get_pid (gpointer handle)
922 MonoW32HandleProcess *process_handle;
925 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
927 mono_w32error_set_last (ERROR_INVALID_HANDLE);
931 return process_handle->pid;
937 } GetProcessForeachData;
940 get_process_foreach_callback (gpointer handle, gpointer handle_specific, gpointer user_data)
942 GetProcessForeachData *foreach_data;
943 MonoW32HandleProcess *process_handle;
946 foreach_data = (GetProcessForeachData*) user_data;
948 if (mono_w32handle_get_type (handle) != MONO_W32HANDLE_PROCESS)
951 process_handle = (MonoW32HandleProcess*) handle_specific;
953 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking at process %d", __func__, process_handle->pid);
955 pid = process_handle->pid;
959 /* It's possible to have more than one process handle with the
960 * same pid, but only the one running process can be
962 if (foreach_data->pid != pid)
964 if (mono_w32handle_issignalled (handle))
967 mono_w32handle_ref (handle);
968 foreach_data->handle = handle;
973 ves_icall_System_Diagnostics_Process_GetProcess_internal (guint32 pid)
975 GetProcessForeachData foreach_data;
978 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking for process %d", __func__, pid);
980 memset (&foreach_data, 0, sizeof (foreach_data));
981 foreach_data.pid = pid;
982 mono_w32handle_foreach (get_process_foreach_callback, &foreach_data);
983 handle = foreach_data.handle;
985 /* get_process_foreach_callback already added a ref */
989 if (process_is_alive (pid)) {
990 /* non-child process */
991 MonoW32HandleProcess process_handle;
993 memset (&process_handle, 0, sizeof (process_handle));
994 process_handle.pid = pid;
995 process_handle.pname = mono_w32process_get_name (pid);
997 handle = mono_w32handle_new (MONO_W32HANDLE_PROCESS, &process_handle);
998 if (handle == INVALID_HANDLE_VALUE) {
999 g_warning ("%s: error creating process handle", __func__);
1001 mono_w32error_set_last (ERROR_OUTOFMEMORY);
1008 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find pid %d", __func__, pid);
1010 mono_w32error_set_last (ERROR_PROC_NOT_FOUND);
1015 match_procname_to_modulename (char *procname, char *modulename)
1017 char* lastsep = NULL;
1018 char* lastsep2 = NULL;
1021 gboolean result = FALSE;
1023 if (procname == NULL || modulename == NULL)
1026 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: procname=\"%s\", modulename=\"%s\"", __func__, procname, modulename);
1027 pname = mono_path_resolve_symlinks (procname);
1028 mname = mono_path_resolve_symlinks (modulename);
1030 if (!strcmp (pname, mname))
1034 lastsep = strrchr (mname, '/');
1036 if (!strcmp (lastsep+1, pname))
1039 lastsep2 = strrchr (pname, '/');
1042 if (!strcmp (lastsep+1, lastsep2+1))
1045 if (!strcmp (mname, lastsep2+1))
1055 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: result is %d", __func__, result);
1060 mono_w32process_try_get_modules (gpointer process, gpointer *modules, guint32 size, guint32 *needed)
1062 MonoW32HandleProcess *process_handle;
1063 GSList *mods = NULL, *mods_iter;
1064 MonoW32ProcessModule *module;
1065 guint32 count, avail = size / sizeof(gpointer);
1071 /* Store modules in an array of pointers (main module as
1072 * modules[0]), using the load address for each module as a
1073 * token. (Use 'NULL' as an alternative for the main module
1074 * so that the simple implementation can just return one item
1075 * for now.) Get the info from /proc/<pid>/maps on linux,
1076 * /proc/<pid>/map on FreeBSD, other systems will have to
1077 * implement /dev/kmem reading or whatever other horrid
1078 * technique is needed.
1080 if (size < sizeof(gpointer))
1083 res = mono_w32handle_lookup (process, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
1085 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
1089 pid = process_handle->pid;
1090 pname = g_strdup (process_handle->pname);
1094 *needed = sizeof(gpointer);
1098 mods = mono_w32process_get_modules (pid);
1101 *needed = sizeof(gpointer);
1109 * Use the NULL shortcut, as the first line in
1110 * /proc/<pid>/maps isn't the executable, and we need
1111 * that first in the returned list. Check the module name
1112 * to see if it ends with the proc name and substitute
1113 * the first entry with it. FIXME if this turns out to
1118 for (i = 0; mods_iter; i++) {
1119 if (i < avail - 1) {
1120 module = (MonoW32ProcessModule *)mods_iter->data;
1121 if (modules[0] != NULL)
1122 modules[i] = module->address_start;
1123 else if (match_procname_to_modulename (pname, module->filename))
1124 modules[0] = module->address_start;
1126 modules[i + 1] = module->address_start;
1128 mono_w32process_module_free ((MonoW32ProcessModule *)mods_iter->data);
1129 mods_iter = g_slist_next (mods_iter);
1133 /* count + 1 to leave slot 0 for the main module */
1134 *needed = sizeof(gpointer) * (count + 1);
1136 g_slist_free (mods);
1143 mono_w32process_module_get_filename (gpointer process, gpointer module, gunichar2 *basename, guint32 size)
1148 gunichar2 *proc_path;
1150 size *= sizeof (gunichar2); /* adjust for unicode characters */
1152 if (basename == NULL || size == 0)
1155 pid = mono_w32process_get_pid (process);
1157 path = mono_w32process_get_path (pid);
1161 proc_path = mono_unicode_from_external (path, &bytes);
1164 if (proc_path == NULL)
1169 /* Add the terminator */
1173 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
1174 memcpy (basename, proc_path, size);
1176 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %d larger than needed (%ld)", __func__, size, bytes);
1177 memcpy (basename, proc_path, bytes);
1186 mono_w32process_module_get_name (gpointer process, gpointer module, gunichar2 *basename, guint32 size)
1188 MonoW32HandleProcess *process_handle;
1190 gunichar2 *procname;
1191 char *procname_ext = NULL;
1194 GSList *mods = NULL, *mods_iter;
1195 MonoW32ProcessModule *found_module;
1199 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Getting module base name, process handle %p module %p",
1200 __func__, process, module);
1202 size = size * sizeof (gunichar2); /* adjust for unicode characters */
1204 if (basename == NULL || size == 0)
1207 res = mono_w32handle_lookup (process, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
1209 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
1213 pid = process_handle->pid;
1214 pname = g_strdup (process_handle->pname);
1216 mods = mono_w32process_get_modules (pid);
1222 /* If module != NULL compare the address.
1223 * If module == NULL we are looking for the main module.
1224 * The best we can do for now check it the module name end with the process name.
1226 for (mods_iter = mods; mods_iter; mods_iter = g_slist_next (mods_iter)) {
1227 found_module = (MonoW32ProcessModule *)mods_iter->data;
1228 if (procname_ext == NULL &&
1229 ((module == NULL && match_procname_to_modulename (pname, found_module->filename)) ||
1230 (module != NULL && found_module->address_start == module))) {
1231 procname_ext = g_path_get_basename (found_module->filename);
1234 mono_w32process_module_free (found_module);
1237 if (procname_ext == NULL) {
1238 /* If it's *still* null, we might have hit the
1239 * case where reading /proc/$pid/maps gives an
1240 * empty file for this user.
1242 procname_ext = mono_w32process_get_name (pid);
1245 g_slist_free (mods);
1249 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Process name is [%s]", __func__,
1252 procname = mono_unicode_from_external (procname_ext, &bytes);
1253 if (procname == NULL) {
1255 g_free (procname_ext);
1261 /* Add the terminator */
1265 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
1267 memcpy (basename, procname, size);
1269 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %d larger than needed (%ld)",
1270 __func__, size, bytes);
1272 memcpy (basename, procname, bytes);
1276 g_free (procname_ext);
1285 mono_w32process_module_get_information (gpointer process, gpointer module, MODULEINFO *modinfo, guint32 size)
1287 MonoW32HandleProcess *process_handle;
1289 GSList *mods = NULL, *mods_iter;
1290 MonoW32ProcessModule *found_module;
1291 gboolean ret = FALSE;
1295 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Getting module info, process handle %p module %p",
1296 __func__, process, module);
1298 if (modinfo == NULL || size < sizeof (MODULEINFO))
1301 res = mono_w32handle_lookup (process, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
1303 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
1307 pid = process_handle->pid;
1308 pname = g_strdup (process_handle->pname);
1310 mods = mono_w32process_get_modules (pid);
1316 /* If module != NULL compare the address.
1317 * If module == NULL we are looking for the main module.
1318 * The best we can do for now check it the module name end with the process name.
1320 for (mods_iter = mods; mods_iter; mods_iter = g_slist_next (mods_iter)) {
1321 found_module = (MonoW32ProcessModule *)mods_iter->data;
1323 ((module == NULL && match_procname_to_modulename (pname, found_module->filename)) ||
1324 (module != NULL && found_module->address_start == module))) {
1325 modinfo->lpBaseOfDll = found_module->address_start;
1326 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
1327 modinfo->EntryPoint = found_module->address_offset;
1331 mono_w32process_module_free (found_module);
1334 g_slist_free (mods);
1341 switch_dir_separators (char *path)
1343 size_t i, pathLength = strlen(path);
1345 /* Turn all the slashes round the right way, except for \' */
1346 /* There are probably other characters that need to be excluded as well. */
1347 for (i = 0; i < pathLength; i++) {
1348 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' )
1355 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
1363 pid = waitpid (-1, &status, WNOHANG);
1364 } while (pid == -1 && errno == EINTR);
1370 * This can run concurrently with the code in the rest of this module.
1372 for (process = processes; process; process = process->next) {
1373 if (process->pid != pid)
1375 if (process->signalled)
1378 process->signalled = TRUE;
1379 process->status = status;
1380 mono_os_sem_post (&process->exit_sem);
1381 mono_memory_barrier ();
1382 /* Mark this as freeable, the pointer becomes invalid afterwards */
1383 process->freeable = TRUE;
1390 process_add_sigchld_handler (void)
1392 struct sigaction sa;
1394 sa.sa_sigaction = mono_sigchld_signal_handler;
1395 sigemptyset (&sa.sa_mask);
1396 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
1397 g_assert (sigaction (SIGCHLD, &sa, NULL) != -1);
1398 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "Added SIGCHLD handler");
1404 is_readable_or_executable (const char *prog)
1407 int a = access (prog, R_OK);
1408 int b = access (prog, X_OK);
1409 if (a != 0 && b != 0)
1411 if (stat (prog, &buf))
1413 if (S_ISREG (buf.st_mode))
1419 is_executable (const char *prog)
1422 if (access (prog, X_OK) != 0)
1424 if (stat (prog, &buf))
1426 if (S_ISREG (buf.st_mode))
1432 is_managed_binary (const char *filename)
1434 int original_errno = errno;
1435 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
1436 int file = open (filename, O_RDONLY | O_LARGEFILE);
1438 int file = open (filename, O_RDONLY);
1441 unsigned char buffer[8];
1442 off_t file_size, optional_header_offset;
1443 off_t pe_header_offset, clr_header_offset;
1444 gboolean managed = FALSE;
1446 guint32 first_word, second_word, magic_number;
1448 /* If we are unable to open the file, then we definitely
1449 * can't say that it is managed. The child mono process
1450 * probably wouldn't be able to open it anyway.
1453 errno = original_errno;
1457 /* Retrieve the length of the file for future sanity checks. */
1458 file_size = lseek (file, 0, SEEK_END);
1459 lseek (file, 0, SEEK_SET);
1461 /* We know we need to read a header field at offset 60. */
1465 num_read = read (file, buffer, 2);
1467 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
1470 new_offset = lseek (file, 60, SEEK_SET);
1472 if (new_offset != 60)
1475 num_read = read (file, buffer, 4);
1479 pe_header_offset = buffer[0]
1482 | (buffer[3] << 24);
1484 if (pe_header_offset + 24 > file_size)
1487 new_offset = lseek (file, pe_header_offset, SEEK_SET);
1489 if (new_offset != pe_header_offset)
1492 num_read = read (file, buffer, 4);
1494 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
1498 * Verify that the header we want in the optional header data
1499 * is present in this binary.
1501 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
1503 if (new_offset != pe_header_offset + 20)
1506 num_read = read (file, buffer, 2);
1508 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
1511 optional_header_offset = pe_header_offset + 24;
1513 /* Read the PE magic number */
1514 new_offset = lseek (file, optional_header_offset, SEEK_SET);
1516 if (new_offset != optional_header_offset)
1519 num_read = read (file, buffer, 2);
1524 magic_number = (buffer[0] | (buffer[1] << 8));
1526 if (magic_number == 0x10B) // PE32
1527 clr_header_offset = 208;
1528 else if (magic_number == 0x20B) // PE32+
1529 clr_header_offset = 224;
1533 /* Read the CLR header address and size fields. These will be
1534 * zero if the binary is not managed.
1536 new_offset = lseek (file, optional_header_offset + clr_header_offset, SEEK_SET);
1538 if (new_offset != optional_header_offset + clr_header_offset)
1541 num_read = read (file, buffer, 8);
1543 /* We are not concerned with endianness, only with
1544 * whether it is zero or not.
1546 first_word = *(guint32 *)&buffer[0];
1547 second_word = *(guint32 *)&buffer[4];
1549 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
1556 errno = original_errno;
1561 process_create (const gunichar2 *appname, const gunichar2 *cmdline,
1562 const gunichar2 *cwd, StartupHandles *startup_handles, MonoW32ProcessInfo *process_info)
1564 #if defined (HAVE_FORK) && defined (HAVE_EXECVE)
1565 char *cmd = NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL;
1566 char *dir = NULL, **env_strings = NULL, **argv = NULL;
1568 gboolean ret = FALSE;
1569 gpointer handle = NULL;
1570 GError *gerr = NULL;
1571 int in_fd, out_fd, err_fd;
1573 int startup_pipe [2] = {-1, -1};
1578 mono_lazy_initialize (&process_sig_chld_once, process_add_sigchld_handler);
1581 /* appname and cmdline specify the executable and its args:
1583 * If appname is not NULL, it is the name of the executable.
1584 * Otherwise the executable is the first token in cmdline.
1586 * Executable searching:
1588 * If appname is not NULL, it can specify the full path and
1589 * file name, or else a partial name and the current directory
1590 * will be used. There is no additional searching.
1592 * If appname is NULL, the first whitespace-delimited token in
1593 * cmdline is used. If the name does not contain a full
1594 * directory path, the search sequence is:
1596 * 1) The directory containing the current process
1597 * 2) The current working directory
1598 * 3) The windows system directory (Ignored)
1599 * 4) The windows directory (Ignored)
1602 * Just to make things more interesting, tokens can contain
1603 * white space if they are surrounded by quotation marks. I'm
1604 * beginning to understand just why windows apps are generally
1605 * so crap, with an API like this :-(
1607 if (appname != NULL) {
1608 cmd = mono_unicode_to_external (appname);
1610 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL",
1613 mono_w32error_set_last (ERROR_PATH_NOT_FOUND);
1617 switch_dir_separators(cmd);
1620 if (cmdline != NULL) {
1621 args = mono_unicode_to_external (cmdline);
1623 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1625 mono_w32error_set_last (ERROR_PATH_NOT_FOUND);
1631 dir = mono_unicode_to_external (cwd);
1633 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1635 mono_w32error_set_last (ERROR_PATH_NOT_FOUND);
1639 /* Turn all the slashes round the right way */
1640 switch_dir_separators(dir);
1644 /* We can't put off locating the executable any longer :-( */
1647 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
1648 /* Strip off the drive letter. I can't
1649 * believe that CP/M holdover is still
1652 g_memmove (cmd, cmd+2, strlen (cmd)-2);
1653 cmd[strlen (cmd)-2] = '\0';
1656 unquoted = g_shell_unquote (cmd, NULL);
1657 if (unquoted[0] == '/') {
1658 /* Assume full path given */
1659 prog = g_strdup (unquoted);
1661 /* Executable existing ? */
1662 if (!is_readable_or_executable (prog)) {
1663 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s",
1666 mono_w32error_set_last (ERROR_FILE_NOT_FOUND);
1670 /* Search for file named by cmd in the current
1673 char *curdir = g_get_current_dir ();
1675 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
1678 /* And make sure it's readable */
1679 if (!is_readable_or_executable (prog)) {
1680 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s",
1683 mono_w32error_set_last (ERROR_FILE_NOT_FOUND);
1689 args_after_prog = args;
1694 /* Dig out the first token from args, taking quotation
1695 * marks into account
1698 /* First, strip off all leading whitespace */
1699 args = g_strchug (args);
1701 /* args_after_prog points to the contents of args
1702 * after token has been set (otherwise argv[0] is
1705 args_after_prog = args;
1707 /* Assume the opening quote will always be the first
1710 if (args[0] == '\"' || args [0] == '\'') {
1712 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
1713 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
1714 /* We found the first token */
1715 token = g_strndup (args+1, i-1);
1716 args_after_prog = g_strchug (args + i + 1);
1718 /* Quotation mark appeared in the
1719 * middle of the token. Just give the
1720 * whole first token, quotes and all,
1726 if (token == NULL) {
1727 /* No quote mark, or malformed */
1728 for (i = 0; args[i] != '\0'; i++) {
1729 if (g_ascii_isspace (args[i])) {
1730 token = g_strndup (args, i);
1731 args_after_prog = args + i + 1;
1737 if (token == NULL && args[0] != '\0') {
1738 /* Must be just one token in the string */
1739 token = g_strdup (args);
1740 args_after_prog = NULL;
1743 if (token == NULL) {
1745 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find what to exec", __func__);
1747 mono_w32error_set_last (ERROR_PATH_NOT_FOUND);
1751 /* Turn all the slashes round the right way. Only for
1754 switch_dir_separators(token);
1756 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
1757 /* Strip off the drive letter. I can't
1758 * believe that CP/M holdover is still
1761 g_memmove (token, token+2, strlen (token)-2);
1762 token[strlen (token)-2] = '\0';
1765 if (token[0] == '/') {
1766 /* Assume full path given */
1767 prog = g_strdup (token);
1769 /* Executable existing ? */
1770 if (!is_readable_or_executable (prog)) {
1771 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s",
1774 mono_w32error_set_last (ERROR_FILE_NOT_FOUND);
1778 char *curdir = g_get_current_dir ();
1780 /* FIXME: Need to record the directory
1781 * containing the current process, and check
1782 * that for the new executable as the first
1786 prog = g_strdup_printf ("%s/%s", curdir, token);
1789 /* I assume X_OK is the criterion to use,
1792 * X_OK is too strict *if* the target is a CLR binary
1794 if (!is_readable_or_executable (prog)) {
1796 prog = g_find_program_in_path (token);
1798 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s", __func__, token);
1801 mono_w32error_set_last (ERROR_FILE_NOT_FOUND);
1810 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Exec prog [%s] args [%s]",
1811 __func__, prog, args_after_prog);
1813 /* Check for CLR binaries; if found, we will try to invoke
1814 * them using the same mono binary that started us.
1816 if (is_managed_binary (prog)) {
1817 gunichar2 *newapp, *newcmd;
1818 gsize bytes_ignored;
1820 newapp = mono_unicode_from_external (cli_launcher ? cli_launcher : "mono", &bytes_ignored);
1823 newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space, appname, utf16_space, cmdline, NULL);
1825 newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space, cmdline, NULL);
1830 ret = process_create (NULL, newcmd, cwd, startup_handles, process_info);
1838 if (!is_executable (prog)) {
1839 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Executable permisson not set on %s", __func__, prog);
1840 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1845 if (args_after_prog != NULL && *args_after_prog) {
1848 qprog = g_shell_quote (prog);
1849 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
1852 full_prog = g_shell_quote (prog);
1855 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
1857 g_message ("process_create: %s\n", gerr->message);
1858 g_error_free (gerr);
1863 if (startup_handles) {
1864 in_fd = GPOINTER_TO_UINT (startup_handles->input);
1865 out_fd = GPOINTER_TO_UINT (startup_handles->output);
1866 err_fd = GPOINTER_TO_UINT (startup_handles->error);
1868 in_fd = GPOINTER_TO_UINT (mono_w32file_get_console_input ());
1869 out_fd = GPOINTER_TO_UINT (mono_w32file_get_console_output ());
1870 err_fd = GPOINTER_TO_UINT (mono_w32file_get_console_error ());
1874 * process->env_variables is a an array of MonoString*
1876 * If new_environ is not NULL it specifies the entire set of
1877 * environment variables in the new process. Otherwise the
1878 * new process inherits the same environment.
1880 if (process_info->env_variables) {
1881 gint i, str_length, var_length;
1885 /* +2: one for the process handle value, and the last one is NULL */
1886 env_strings = g_new0 (gchar*, mono_array_length (process_info->env_variables) + 2);
1891 /* Copy each environ string into 'strings' turning it into utf8 (or the requested encoding) at the same time */
1892 for (i = 0; i < mono_array_length (process_info->env_variables); ++i) {
1893 var = mono_array_get (process_info->env_variables, MonoString*, i);
1894 var_length = mono_string_length (var);
1896 /* str is a null-terminated copy of var */
1898 if (var_length + 1 > str_length) {
1899 str_length = var_length + 1;
1900 str = g_renew (gunichar2, str, str_length);
1903 memcpy (str, mono_string_chars (var), var_length * sizeof (gunichar2));
1904 str [var_length] = '\0';
1906 env_strings [i] = mono_unicode_to_external (str);
1914 for (i = 0; environ[i] != NULL; i++)
1917 /* +2: one for the process handle value, and the last one is NULL */
1918 env_strings = g_new0 (gchar*, env_count + 2);
1920 /* Copy each environ string into 'strings' turning it into utf8 (or the requested encoding) at the same time */
1921 for (i = 0; i < env_count; i++)
1922 env_strings [i] = g_strdup (environ[i]);
1925 /* Create a pipe to make sure the child doesn't exit before
1926 * we can add the process to the linked list of processes */
1927 if (pipe (startup_pipe) == -1) {
1928 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
1929 * This is just for a very hard to hit race condition in the first place */
1930 startup_pipe [0] = startup_pipe [1] = -1;
1931 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
1934 switch (pid = fork ()) {
1935 case -1: /* Error */ {
1936 mono_w32error_set_last (ERROR_OUTOFMEMORY);
1940 case 0: /* Child */ {
1941 if (startup_pipe [0] != -1) {
1942 /* Wait until the parent has updated it's internal data */
1943 ssize_t _i G_GNUC_UNUSED = read (startup_pipe [0], &dummy, 1);
1944 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: child: parent has completed its setup", __func__);
1945 close (startup_pipe [0]);
1946 close (startup_pipe [1]);
1949 /* should we detach from the process group? */
1951 /* Connect stdin, stdout and stderr */
1956 /* Close all file descriptors */
1957 for (i = mono_w32handle_fd_reserve - 1; i > 2; i--)
1960 #ifdef DEBUG_ENABLED
1961 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1962 dir == NULL?".":dir);
1963 for (i = 0; argv[i] != NULL; i++)
1964 g_message ("arg %d: [%s]", i, argv[i]);
1966 for (i = 0; env_strings[i] != NULL; i++)
1967 g_message ("env %d: [%s]", i, env_strings[i]);
1971 if (dir != NULL && chdir (dir) == -1) {
1977 execve (argv[0], argv, env_strings);
1984 default: /* Parent */ {
1985 MonoW32HandleProcess process_handle;
1987 memset (&process_handle, 0, sizeof (process_handle));
1988 process_handle.pid = pid;
1989 process_handle.child = TRUE;
1990 process_handle.pname = g_strdup (prog);
1991 process_set_defaults (&process_handle);
1993 /* Add our process into the linked list of processes */
1994 process = (Process *) g_malloc0 (sizeof (Process));
1996 process->handle_count = 1;
1997 mono_os_sem_init (&process->exit_sem, 0);
1999 process_handle.process = process;
2001 handle = mono_w32handle_new (MONO_W32HANDLE_PROCESS, &process_handle);
2002 if (handle == INVALID_HANDLE_VALUE) {
2003 g_warning ("%s: error creating process handle", __func__);
2005 mono_os_sem_destroy (&process->exit_sem);
2008 mono_w32error_set_last (ERROR_OUTOFMEMORY);
2013 /* Keep the process handle artificially alive until the process
2014 * exits so that the information in the handle isn't lost. */
2015 mono_w32handle_ref (handle);
2016 process->handle = handle;
2018 mono_os_mutex_lock (&processes_mutex);
2019 process->next = processes;
2020 mono_memory_barrier ();
2021 processes = process;
2022 mono_os_mutex_unlock (&processes_mutex);
2024 if (process_info != NULL) {
2025 process_info->process_handle = handle;
2026 process_info->pid = pid;
2028 /* FIXME: we might need to handle the thread info some day */
2029 process_info->thread_handle = INVALID_HANDLE_VALUE;
2030 process_info->tid = 0;
2037 if (startup_pipe [1] != -1) {
2038 /* Write 1 byte, doesn't matter what */
2039 ssize_t _i G_GNUC_UNUSED = write (startup_pipe [1], startup_pipe, 1);
2040 close (startup_pipe [0]);
2041 close (startup_pipe [1]);
2056 g_strfreev (env_strings);
2060 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: returning handle %p for pid %d", __func__, handle, pid);
2062 /* Check if something needs to be cleaned up. */
2063 processes_cleanup ();
2067 mono_w32error_set_last (ERROR_NOT_SUPPORTED);
2069 #endif // defined (HAVE_FORK) && defined (HAVE_EXECVE)
2073 ves_icall_System_Diagnostics_Process_ShellExecuteEx_internal (MonoW32ProcessStartInfo *proc_start_info, MonoW32ProcessInfo *process_info)
2075 const gunichar2 *lpFile;
2076 const gunichar2 *lpParameters;
2077 const gunichar2 *lpDirectory;
2081 if (!proc_start_info->filename) {
2082 /* w2k returns TRUE for this, for some reason. */
2087 lpFile = proc_start_info->filename ? mono_string_chars (proc_start_info->filename) : NULL;
2088 lpParameters = proc_start_info->arguments ? mono_string_chars (proc_start_info->arguments) : NULL;
2089 lpDirectory = proc_start_info->working_directory && mono_string_length (proc_start_info->working_directory) != 0 ?
2090 mono_string_chars (proc_start_info->working_directory) : NULL;
2092 /* Put both executable and parameters into the second argument
2093 * to process_create (), so it searches $PATH. The conversion
2094 * into and back out of utf8 is because there is no
2095 * g_strdup_printf () equivalent for gunichar2 :-(
2097 args = utf16_concat (utf16_quote, lpFile, utf16_quote, lpParameters == NULL ? NULL : utf16_space, lpParameters, NULL);
2099 mono_w32error_set_last (ERROR_INVALID_DATA);
2103 ret = process_create (NULL, args, lpDirectory, NULL, process_info);
2106 if (!ret && mono_w32error_get_last () == ERROR_OUTOFMEMORY)
2110 static char *handler;
2111 static gunichar2 *handler_utf16;
2113 if (handler_utf16 == (gunichar2 *)-1) {
2118 #ifdef PLATFORM_MACOSX
2119 handler = g_strdup ("/usr/bin/open");
2122 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
2123 * if that fails, try to use gnome-open, then kfmclient
2125 handler = g_find_program_in_path ("xdg-open");
2126 if (handler == NULL){
2127 handler = g_find_program_in_path ("gnome-open");
2128 if (handler == NULL){
2129 handler = g_find_program_in_path ("kfmclient");
2130 if (handler == NULL){
2131 handler_utf16 = (gunichar2 *) -1;
2135 /* kfmclient needs exec argument */
2136 char *old = handler;
2137 handler = g_strconcat (old, " exec",
2144 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
2147 /* Put quotes around the filename, in case it's a url
2148 * that contains #'s (process_create() calls
2149 * g_shell_parse_argv(), which deliberately throws
2150 * away anything after an unquoted #). Fixes bug
2153 args = utf16_concat (handler_utf16, utf16_space, utf16_quote, lpFile, utf16_quote,
2154 lpParameters == NULL ? NULL : utf16_space, lpParameters, NULL);
2156 mono_w32error_set_last (ERROR_INVALID_DATA);
2160 ret = process_create (NULL, args, lpDirectory, NULL, process_info);
2163 if (mono_w32error_get_last () != ERROR_OUTOFMEMORY)
2164 mono_w32error_set_last (ERROR_INVALID_DATA);
2168 /* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
2169 mono_w32handle_close (process_info->process_handle);
2170 process_info->process_handle = NULL;
2175 process_info->pid = -mono_w32error_get_last ();
2177 process_info->thread_handle = NULL;
2178 #if !defined(MONO_CROSS_COMPILE)
2179 process_info->pid = mono_w32process_get_pid (process_info->process_handle);
2181 process_info->pid = 0;
2183 process_info->tid = 0;
2189 /* Only used when UseShellExecute is false */
2191 process_get_complete_path (const gunichar2 *appname, gchar **completed)
2196 utf8app = g_utf16_to_utf8 (appname, -1, NULL, NULL, NULL);
2198 if (g_path_is_absolute (utf8app)) {
2199 *completed = g_shell_quote (utf8app);
2204 if (g_file_test (utf8app, G_FILE_TEST_IS_EXECUTABLE) && !g_file_test (utf8app, G_FILE_TEST_IS_DIR)) {
2205 *completed = g_shell_quote (utf8app);
2210 found = g_find_program_in_path (utf8app);
2211 if (found == NULL) {
2217 *completed = g_shell_quote (found);
2224 process_get_shell_arguments (MonoW32ProcessStartInfo *proc_start_info, gunichar2 **shell_path)
2226 gchar *complete_path = NULL;
2230 if (process_get_complete_path (mono_string_chars (proc_start_info->filename), &complete_path)) {
2231 *shell_path = g_utf8_to_utf16 (complete_path, -1, NULL, NULL, NULL);
2232 g_free (complete_path);
2235 return *shell_path != NULL;
2239 ves_icall_System_Diagnostics_Process_CreateProcess_internal (MonoW32ProcessStartInfo *proc_start_info,
2240 HANDLE stdin_handle, HANDLE stdout_handle, HANDLE stderr_handle, MonoW32ProcessInfo *process_info)
2244 StartupHandles startup_handles;
2245 gunichar2 *shell_path = NULL;
2246 gunichar2 *args = NULL;
2248 memset (&startup_handles, 0, sizeof (startup_handles));
2249 startup_handles.input = stdin_handle;
2250 startup_handles.output = stdout_handle;
2251 startup_handles.error = stderr_handle;
2253 if (!process_get_shell_arguments (proc_start_info, &shell_path)) {
2254 process_info->pid = -ERROR_FILE_NOT_FOUND;
2258 args = proc_start_info->arguments && mono_string_length (proc_start_info->arguments) > 0 ?
2259 mono_string_chars (proc_start_info->arguments): NULL;
2261 /* The default dir name is "". Turn that into NULL to mean "current directory" */
2262 dir = proc_start_info->working_directory && mono_string_length (proc_start_info->working_directory) > 0 ?
2263 mono_string_chars (proc_start_info->working_directory) : NULL;
2265 ret = process_create (shell_path, args, dir, &startup_handles, process_info);
2267 if (shell_path != NULL)
2268 g_free (shell_path);
2271 process_info->pid = -mono_w32error_get_last ();
2276 /* Returns an array of pids */
2278 ves_icall_System_Diagnostics_Process_GetProcesses_internal (void)
2285 pidarray = mono_process_list (&count);
2287 mono_set_pending_exception (mono_get_exception_not_supported ("This system does not support EnumProcesses"));
2290 procs = mono_array_new_checked (mono_domain_get (), mono_get_int32_class (), count, &error);
2291 if (mono_error_set_pending_exception (&error)) {
2295 if (sizeof (guint32) == sizeof (gpointer)) {
2296 memcpy (mono_array_addr (procs, guint32, 0), pidarray, count * sizeof (gint32));
2298 for (i = 0; i < count; ++i)
2299 *(mono_array_addr (procs, guint32, i)) = GPOINTER_TO_UINT (pidarray [i]);
2307 mono_w32process_set_cli_launcher (gchar *path)
2309 g_free (cli_launcher);
2310 cli_launcher = g_strdup (path);
2314 ves_icall_Microsoft_Win32_NativeMethods_GetCurrentProcess (void)
2316 mono_w32handle_ref (current_process);
2317 return current_process;
2321 ves_icall_Microsoft_Win32_NativeMethods_GetExitCodeProcess (gpointer handle, gint32 *exitcode)
2323 MonoW32HandleProcess *process_handle;
2329 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2331 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2335 if (process_handle->pid == current_pid) {
2336 *exitcode = STILL_ACTIVE;
2340 /* A process handle is only signalled if the process has exited
2341 * and has been waited for. Make sure any process exit has been
2342 * noticed before checking if the process is signalled.
2343 * Fixes bug 325463. */
2344 mono_w32handle_wait_one (handle, 0, TRUE);
2346 *exitcode = mono_w32handle_issignalled (handle) ? process_handle->exitstatus : STILL_ACTIVE;
2351 ves_icall_Microsoft_Win32_NativeMethods_CloseProcess (gpointer handle)
2353 return mono_w32handle_close (handle);
2357 ves_icall_Microsoft_Win32_NativeMethods_TerminateProcess (gpointer handle, gint32 exitcode)
2360 MonoW32HandleProcess *process_handle;
2365 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2367 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2368 mono_w32error_set_last (ERROR_INVALID_HANDLE);
2372 pid = process_handle->pid;
2374 ret = kill (pid, exitcode == -1 ? SIGKILL : SIGTERM);
2379 case EINVAL: mono_w32error_set_last (ERROR_INVALID_PARAMETER); break;
2380 case EPERM: mono_w32error_set_last (ERROR_ACCESS_DENIED); break;
2381 case ESRCH: mono_w32error_set_last (ERROR_PROC_NOT_FOUND); break;
2382 default: mono_w32error_set_last (ERROR_GEN_FAILURE); break;
2387 g_error ("kill() is not supported by this platform");
2392 ves_icall_Microsoft_Win32_NativeMethods_GetProcessWorkingSetSize (gpointer handle, gsize *min, gsize *max)
2394 MonoW32HandleProcess *process_handle;
2400 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2402 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2406 if (!process_handle->child)
2409 *min = process_handle->min_working_set;
2410 *max = process_handle->max_working_set;
2415 ves_icall_Microsoft_Win32_NativeMethods_SetProcessWorkingSetSize (gpointer handle, gsize min, gsize max)
2417 MonoW32HandleProcess *process_handle;
2420 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2422 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2426 if (!process_handle->child)
2429 process_handle->min_working_set = min;
2430 process_handle->max_working_set = max;
2435 ves_icall_Microsoft_Win32_NativeMethods_GetPriorityClass (gpointer handle)
2437 #ifdef HAVE_GETPRIORITY
2438 MonoW32HandleProcess *process_handle;
2443 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2445 mono_w32error_set_last (ERROR_INVALID_HANDLE);
2449 pid = process_handle->pid;
2452 ret = getpriority (PRIO_PROCESS, pid);
2453 if (ret == -1 && errno != 0) {
2457 mono_w32error_set_last (ERROR_ACCESS_DENIED);
2460 mono_w32error_set_last (ERROR_PROC_NOT_FOUND);
2463 mono_w32error_set_last (ERROR_GEN_FAILURE);
2469 return MONO_W32PROCESS_PRIORITY_CLASS_NORMAL;
2471 return MONO_W32PROCESS_PRIORITY_CLASS_REALTIME;
2473 return MONO_W32PROCESS_PRIORITY_CLASS_HIGH;
2475 return MONO_W32PROCESS_PRIORITY_CLASS_ABOVE_NORMAL;
2477 return MONO_W32PROCESS_PRIORITY_CLASS_IDLE;
2479 return MONO_W32PROCESS_PRIORITY_CLASS_BELOW_NORMAL;
2481 return MONO_W32PROCESS_PRIORITY_CLASS_NORMAL;
2483 mono_w32error_set_last (ERROR_NOT_SUPPORTED);
2489 ves_icall_Microsoft_Win32_NativeMethods_SetPriorityClass (gpointer handle, gint32 priorityClass)
2491 #ifdef HAVE_SETPRIORITY
2492 MonoW32HandleProcess *process_handle;
2498 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2500 mono_w32error_set_last (ERROR_INVALID_HANDLE);
2504 pid = process_handle->pid;
2506 switch (priorityClass) {
2507 case MONO_W32PROCESS_PRIORITY_CLASS_IDLE:
2510 case MONO_W32PROCESS_PRIORITY_CLASS_BELOW_NORMAL:
2513 case MONO_W32PROCESS_PRIORITY_CLASS_NORMAL:
2516 case MONO_W32PROCESS_PRIORITY_CLASS_ABOVE_NORMAL:
2519 case MONO_W32PROCESS_PRIORITY_CLASS_HIGH:
2522 case MONO_W32PROCESS_PRIORITY_CLASS_REALTIME:
2526 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
2530 ret = setpriority (PRIO_PROCESS, pid, prio);
2535 mono_w32error_set_last (ERROR_ACCESS_DENIED);
2538 mono_w32error_set_last (ERROR_PROC_NOT_FOUND);
2541 mono_w32error_set_last (ERROR_GEN_FAILURE);
2547 mono_w32error_set_last (ERROR_NOT_SUPPORTED);
2553 ticks_to_processtime (guint64 ticks, ProcessTime *processtime)
2555 processtime->lowDateTime = ticks & 0xFFFFFFFF;
2556 processtime->highDateTime = ticks >> 32;
2560 ves_icall_Microsoft_Win32_NativeMethods_GetProcessTimes (gpointer handle, gint64 *creation_time, gint64 *exit_time, gint64 *kernel_time, gint64 *user_time)
2562 MonoW32HandleProcess *process_handle;
2563 ProcessTime *creation_processtime, *exit_processtime, *kernel_processtime, *user_processtime;
2566 if (!creation_time || !exit_time || !kernel_time || !user_time) {
2567 /* Not sure if w32 allows NULLs here or not */
2571 creation_processtime = (ProcessTime*) creation_time;
2572 exit_processtime = (ProcessTime*) exit_time;
2573 kernel_processtime = (ProcessTime*) kernel_time;
2574 user_processtime = (ProcessTime*) user_time;
2576 memset (creation_processtime, 0, sizeof (ProcessTime));
2577 memset (exit_processtime, 0, sizeof (ProcessTime));
2578 memset (kernel_processtime, 0, sizeof (ProcessTime));
2579 memset (user_processtime, 0, sizeof (ProcessTime));
2581 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2583 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2587 if (!process_handle->child) {
2588 gint64 start_ticks, user_ticks, kernel_ticks;
2590 mono_process_get_times (GINT_TO_POINTER (process_handle->pid),
2591 &start_ticks, &user_ticks, &kernel_ticks);
2593 ticks_to_processtime (start_ticks, creation_processtime);
2594 ticks_to_processtime (user_ticks, kernel_processtime);
2595 ticks_to_processtime (kernel_ticks, user_processtime);
2599 ticks_to_processtime (process_handle->create_time, creation_processtime);
2601 /* A process handle is only signalled if the process has
2602 * exited, otherwise exit_processtime isn't set */
2603 if (mono_w32handle_issignalled (handle))
2604 ticks_to_processtime (process_handle->exit_time, exit_processtime);
2606 #ifdef HAVE_GETRUSAGE
2607 if (process_handle->pid == getpid ()) {
2608 struct rusage time_data;
2609 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
2610 ticks_to_processtime ((guint64)time_data.ru_utime.tv_sec * 10000000 + (guint64)time_data.ru_utime.tv_usec * 10, user_processtime);
2611 ticks_to_processtime ((guint64)time_data.ru_stime.tv_sec * 10000000 + (guint64)time_data.ru_stime.tv_usec * 10, kernel_processtime);
2619 static IMAGE_SECTION_HEADER *
2620 get_enclosing_section_header (guint32 rva, IMAGE_NT_HEADERS32 *nt_headers)
2622 IMAGE_SECTION_HEADER *section = IMAGE_FIRST_SECTION32 (nt_headers);
2625 for (i = 0; i < GUINT16_FROM_LE (nt_headers->FileHeader.NumberOfSections); i++, section++) {
2626 guint32 size = GUINT32_FROM_LE (section->Misc.VirtualSize);
2628 size = GUINT32_FROM_LE (section->SizeOfRawData);
2631 if ((rva >= GUINT32_FROM_LE (section->VirtualAddress)) &&
2632 (rva < (GUINT32_FROM_LE (section->VirtualAddress) + size))) {
2640 /* This works for both 32bit and 64bit files, as the differences are
2641 * all after the section header block
2644 get_ptr_from_rva (guint32 rva, IMAGE_NT_HEADERS32 *ntheaders, gpointer file_map)
2646 IMAGE_SECTION_HEADER *section_header;
2649 section_header = get_enclosing_section_header (rva, ntheaders);
2650 if (section_header == NULL) {
2654 delta = (guint32)(GUINT32_FROM_LE (section_header->VirtualAddress) -
2655 GUINT32_FROM_LE (section_header->PointerToRawData));
2657 return((guint8 *)file_map + rva - delta);
2661 scan_resource_dir (IMAGE_RESOURCE_DIRECTORY *root, IMAGE_NT_HEADERS32 *nt_headers, gpointer file_map,
2662 IMAGE_RESOURCE_DIRECTORY_ENTRY *entry, int level, guint32 res_id, guint32 lang_id, guint32 *size)
2664 IMAGE_RESOURCE_DIRECTORY_ENTRY swapped_entry;
2665 gboolean is_string, is_dir;
2666 guint32 name_offset, dir_offset, data_offset;
2668 swapped_entry.Name = GUINT32_FROM_LE (entry->Name);
2669 swapped_entry.OffsetToData = GUINT32_FROM_LE (entry->OffsetToData);
2671 is_string = swapped_entry.NameIsString;
2672 is_dir = swapped_entry.DataIsDirectory;
2673 name_offset = swapped_entry.NameOffset;
2674 dir_offset = swapped_entry.OffsetToDirectory;
2675 data_offset = swapped_entry.OffsetToData;
2678 /* Normally holds a directory entry for each type of
2681 if ((is_string == FALSE &&
2682 name_offset != res_id) ||
2683 (is_string == TRUE)) {
2686 } else if (level == 1) {
2687 /* Normally holds a directory entry for each resource
2690 } else if (level == 2) {
2691 /* Normally holds a directory entry for each language
2693 if ((is_string == FALSE &&
2694 name_offset != lang_id &&
2696 (is_string == TRUE)) {
2700 g_assert_not_reached ();
2703 if (is_dir == TRUE) {
2704 IMAGE_RESOURCE_DIRECTORY *res_dir = (IMAGE_RESOURCE_DIRECTORY *)((guint8 *)root + dir_offset);
2705 IMAGE_RESOURCE_DIRECTORY_ENTRY *sub_entries = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(res_dir + 1);
2708 entries = GUINT16_FROM_LE (res_dir->NumberOfNamedEntries) + GUINT16_FROM_LE (res_dir->NumberOfIdEntries);
2710 for (i = 0; i < entries; i++) {
2711 IMAGE_RESOURCE_DIRECTORY_ENTRY *sub_entry = &sub_entries[i];
2714 ret = scan_resource_dir (root, nt_headers, file_map,
2715 sub_entry, level + 1, res_id,
2724 IMAGE_RESOURCE_DATA_ENTRY *data_entry = (IMAGE_RESOURCE_DATA_ENTRY *)((guint8 *)root + data_offset);
2725 *size = GUINT32_FROM_LE (data_entry->Size);
2727 return(get_ptr_from_rva (GUINT32_FROM_LE (data_entry->OffsetToData), nt_headers, file_map));
2732 find_pe_file_resources32 (gpointer file_map, guint32 map_size, guint32 res_id, guint32 lang_id, guint32 *size)
2734 IMAGE_DOS_HEADER *dos_header;
2735 IMAGE_NT_HEADERS32 *nt_headers;
2736 IMAGE_RESOURCE_DIRECTORY *resource_dir;
2737 IMAGE_RESOURCE_DIRECTORY_ENTRY *resource_dir_entry;
2738 guint32 resource_rva, entries, i;
2739 gpointer ret = NULL;
2741 dos_header = (IMAGE_DOS_HEADER *)file_map;
2742 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) {
2743 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Bad dos signature 0x%x", __func__, dos_header->e_magic);
2745 mono_w32error_set_last (ERROR_INVALID_DATA);
2749 if (map_size < sizeof(IMAGE_NT_HEADERS32) + GUINT32_FROM_LE (dos_header->e_lfanew)) {
2750 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File is too small: %d", __func__, map_size);
2752 mono_w32error_set_last (ERROR_BAD_LENGTH);
2756 nt_headers = (IMAGE_NT_HEADERS32 *)((guint8 *)file_map + GUINT32_FROM_LE (dos_header->e_lfanew));
2757 if (nt_headers->Signature != IMAGE_NT_SIGNATURE) {
2758 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Bad NT signature 0x%x", __func__, nt_headers->Signature);
2760 mono_w32error_set_last (ERROR_INVALID_DATA);
2764 if (nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
2765 /* Do 64-bit stuff */
2766 resource_rva = GUINT32_FROM_LE (((IMAGE_NT_HEADERS64 *)nt_headers)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
2768 resource_rva = GUINT32_FROM_LE (nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
2771 if (resource_rva == 0) {
2772 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: No resources in file!", __func__);
2774 mono_w32error_set_last (ERROR_INVALID_DATA);
2778 resource_dir = (IMAGE_RESOURCE_DIRECTORY *)get_ptr_from_rva (resource_rva, (IMAGE_NT_HEADERS32 *)nt_headers, file_map);
2779 if (resource_dir == NULL) {
2780 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find resource directory", __func__);
2782 mono_w32error_set_last (ERROR_INVALID_DATA);
2786 entries = GUINT16_FROM_LE (resource_dir->NumberOfNamedEntries) + GUINT16_FROM_LE (resource_dir->NumberOfIdEntries);
2787 resource_dir_entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resource_dir + 1);
2789 for (i = 0; i < entries; i++) {
2790 IMAGE_RESOURCE_DIRECTORY_ENTRY *direntry = &resource_dir_entry[i];
2791 ret = scan_resource_dir (resource_dir,
2792 (IMAGE_NT_HEADERS32 *)nt_headers,
2793 file_map, direntry, 0, res_id,
2804 find_pe_file_resources64 (gpointer file_map, guint32 map_size, guint32 res_id, guint32 lang_id, guint32 *size)
2806 IMAGE_DOS_HEADER *dos_header;
2807 IMAGE_NT_HEADERS64 *nt_headers;
2808 IMAGE_RESOURCE_DIRECTORY *resource_dir;
2809 IMAGE_RESOURCE_DIRECTORY_ENTRY *resource_dir_entry;
2810 guint32 resource_rva, entries, i;
2811 gpointer ret = NULL;
2813 dos_header = (IMAGE_DOS_HEADER *)file_map;
2814 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) {
2815 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Bad dos signature 0x%x", __func__, dos_header->e_magic);
2817 mono_w32error_set_last (ERROR_INVALID_DATA);
2821 if (map_size < sizeof(IMAGE_NT_HEADERS64) + GUINT32_FROM_LE (dos_header->e_lfanew)) {
2822 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File is too small: %d", __func__, map_size);
2824 mono_w32error_set_last (ERROR_BAD_LENGTH);
2828 nt_headers = (IMAGE_NT_HEADERS64 *)((guint8 *)file_map + GUINT32_FROM_LE (dos_header->e_lfanew));
2829 if (nt_headers->Signature != IMAGE_NT_SIGNATURE) {
2830 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Bad NT signature 0x%x", __func__,
2831 nt_headers->Signature);
2833 mono_w32error_set_last (ERROR_INVALID_DATA);
2837 if (nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
2838 /* Do 64-bit stuff */
2839 resource_rva = GUINT32_FROM_LE (((IMAGE_NT_HEADERS64 *)nt_headers)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
2841 resource_rva = GUINT32_FROM_LE (nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
2844 if (resource_rva == 0) {
2845 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: No resources in file!", __func__);
2847 mono_w32error_set_last (ERROR_INVALID_DATA);
2851 resource_dir = (IMAGE_RESOURCE_DIRECTORY *)get_ptr_from_rva (resource_rva, (IMAGE_NT_HEADERS32 *)nt_headers, file_map);
2852 if (resource_dir == NULL) {
2853 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find resource directory", __func__);
2855 mono_w32error_set_last (ERROR_INVALID_DATA);
2859 entries = GUINT16_FROM_LE (resource_dir->NumberOfNamedEntries) + GUINT16_FROM_LE (resource_dir->NumberOfIdEntries);
2860 resource_dir_entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resource_dir + 1);
2862 for (i = 0; i < entries; i++) {
2863 IMAGE_RESOURCE_DIRECTORY_ENTRY *direntry = &resource_dir_entry[i];
2864 ret = scan_resource_dir (resource_dir,
2865 (IMAGE_NT_HEADERS32 *)nt_headers,
2866 file_map, direntry, 0, res_id,
2877 find_pe_file_resources (gpointer file_map, guint32 map_size, guint32 res_id, guint32 lang_id, guint32 *size)
2879 /* Figure this out when we support 64bit PE files */
2881 return find_pe_file_resources32 (file_map, map_size, res_id,
2884 return find_pe_file_resources64 (file_map, map_size, res_id,
2890 map_pe_file (gunichar2 *filename, gint32 *map_size, void **handle)
2892 gchar *filename_ext;
2894 struct stat statbuf;
2897 /* According to the MSDN docs, a search path is applied to
2898 * filename. FIXME: implement this, for now just pass it
2902 filename_ext = mono_unicode_to_external (filename);
2903 if (filename_ext == NULL) {
2904 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2906 mono_w32error_set_last (ERROR_INVALID_NAME);
2910 fd = open (filename_ext, O_RDONLY, 0);
2911 if (fd == -1 && (errno == ENOENT || errno == ENOTDIR) && IS_PORTABILITY_SET) {
2913 gchar *located_filename;
2915 saved_errno = errno;
2917 located_filename = mono_portability_find_file (filename_ext, TRUE);
2918 if (!located_filename) {
2919 errno = saved_errno;
2921 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error opening file %s (1): %s", __func__, filename_ext, strerror (errno));
2923 g_free (filename_ext);
2925 mono_w32error_set_last (mono_w32error_unix_to_win32 (errno));
2929 fd = open (located_filename, O_RDONLY, 0);
2931 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error opening file %s (2): %s", __func__, filename_ext, strerror (errno));
2933 g_free (filename_ext);
2934 g_free (located_filename);
2936 mono_w32error_set_last (mono_w32error_unix_to_win32 (errno));
2940 g_free (located_filename);
2943 if (fstat (fd, &statbuf) == -1) {
2944 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error stat()ing file %s: %s", __func__, filename_ext, strerror (errno));
2946 mono_w32error_set_last (mono_w32error_unix_to_win32 (errno));
2947 g_free (filename_ext);
2951 *map_size = statbuf.st_size;
2953 /* Check basic file size */
2954 if (statbuf.st_size < sizeof(IMAGE_DOS_HEADER)) {
2955 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File %s is too small: %lld", __func__, filename_ext, statbuf.st_size);
2957 mono_w32error_set_last (ERROR_BAD_LENGTH);
2958 g_free (filename_ext);
2963 file_map = mono_file_map (statbuf.st_size, MONO_MMAP_READ | MONO_MMAP_PRIVATE, fd, 0, handle);
2964 if (file_map == NULL) {
2965 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error mmap()int file %s: %s", __func__, filename_ext, strerror (errno));
2967 mono_w32error_set_last (mono_w32error_unix_to_win32 (errno));
2968 g_free (filename_ext);
2973 /* Don't need the fd any more */
2975 g_free (filename_ext);
2981 unmap_pe_file (gpointer file_map, void *handle)
2983 mono_file_unmap (file_map, handle);
2987 unicode_chars (const gunichar2 *str)
2992 if (str[len] == '\0') {
3000 unicode_compare (const gunichar2 *str1, const gunichar2 *str2)
3002 while (*str1 && *str2) {
3003 if (*str1 != *str2) {
3010 return(*str1 == *str2);
3013 /* compare a little-endian null-terminated utf16 string and a normal string.
3014 * Can be used only for ascii or latin1 chars.
3017 unicode_string_equals (const gunichar2 *str1, const gchar *str2)
3019 while (*str1 && *str2) {
3020 if (GUINT16_TO_LE (*str1) != *str2) {
3027 return(*str1 == *str2);
3037 /* Returns a pointer to the value data, because there's no way to know
3038 * how big that data is (value_len is set to zero for most blocks :-( )
3040 static gconstpointer
3041 get_versioninfo_block (gconstpointer data, version_data *block)
3043 block->data_len = GUINT16_FROM_LE (*((guint16 *)data));
3044 data = (char *)data + sizeof(guint16);
3045 block->value_len = GUINT16_FROM_LE (*((guint16 *)data));
3046 data = (char *)data + sizeof(guint16);
3048 /* No idea what the type is supposed to indicate */
3049 block->type = GUINT16_FROM_LE (*((guint16 *)data));
3050 data = (char *)data + sizeof(guint16);
3051 block->key = ((gunichar2 *)data);
3053 /* Skip over the key (including the terminator) */
3054 data = ((gunichar2 *)data) + (unicode_chars (block->key) + 1);
3056 /* align on a 32-bit boundary */
3062 static gconstpointer
3063 get_fixedfileinfo_block (gconstpointer data, version_data *block)
3065 gconstpointer data_ptr;
3066 VS_FIXEDFILEINFO *ffi;
3068 data_ptr = get_versioninfo_block (data, block);
3070 if (block->value_len != sizeof(VS_FIXEDFILEINFO)) {
3071 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: FIXEDFILEINFO size mismatch", __func__);
3075 if (!unicode_string_equals (block->key, "VS_VERSION_INFO")) {
3076 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: VS_VERSION_INFO mismatch", __func__);
3081 ffi = ((VS_FIXEDFILEINFO *)data_ptr);
3082 if ((ffi->dwSignature != VS_FFI_SIGNATURE) ||
3083 (ffi->dwStrucVersion != VS_FFI_STRUCVERSION)) {
3084 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: FIXEDFILEINFO bad signature", __func__);
3092 static gconstpointer
3093 get_varfileinfo_block (gconstpointer data_ptr, version_data *block)
3095 /* data is pointing at a Var block
3097 data_ptr = get_versioninfo_block (data_ptr, block);
3102 static gconstpointer
3103 get_string_block (gconstpointer data_ptr, const gunichar2 *string_key, gpointer *string_value,
3104 guint32 *string_value_len, version_data *block)
3106 guint16 data_len = block->data_len;
3107 guint16 string_len = 28; /* Length of the StringTable block */
3108 char *orig_data_ptr = (char *)data_ptr - 28;
3110 /* data_ptr is pointing at an array of one or more String blocks
3111 * with total length (not including alignment padding) of
3114 while (((char *)data_ptr - (char *)orig_data_ptr) < data_len) {
3115 /* align on a 32-bit boundary */
3118 data_ptr = get_versioninfo_block (data_ptr, block);
3119 if (block->data_len == 0) {
3120 /* We must have hit padding, so give up
3123 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3128 string_len = string_len + block->data_len;
3130 if (string_key != NULL &&
3131 string_value != NULL &&
3132 string_value_len != NULL &&
3133 unicode_compare (string_key, block->key) == TRUE) {
3134 *string_value = (gpointer)data_ptr;
3135 *string_value_len = block->value_len;
3138 /* Skip over the value */
3139 data_ptr = ((gunichar2 *)data_ptr) + block->value_len;
3145 /* Returns a pointer to the byte following the Stringtable block, or
3146 * NULL if the data read hits padding. We can't recover from this
3147 * because the data length does not include padding bytes, so it's not
3148 * possible to just return the start position + length
3150 * If lang == NULL it means we're just stepping through this block
3152 static gconstpointer
3153 get_stringtable_block (gconstpointer data_ptr, gchar *lang, const gunichar2 *string_key, gpointer *string_value,
3154 guint32 *string_value_len, version_data *block)
3156 guint16 data_len = block->data_len;
3157 guint16 string_len = 36; /* length of the StringFileInfo block */
3159 gchar *lowercase_lang;
3161 /* data_ptr is pointing at an array of StringTable blocks,
3162 * with total length (not including alignment padding) of
3166 while(string_len < data_len) {
3167 /* align on a 32-bit boundary */
3170 data_ptr = get_versioninfo_block (data_ptr, block);
3171 if (block->data_len == 0) {
3172 /* We must have hit padding, so give up
3175 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3179 string_len = string_len + block->data_len;
3181 found_lang = g_utf16_to_utf8 (block->key, 8, NULL, NULL, NULL);
3182 if (found_lang == NULL) {
3183 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't find a valid language key, giving up", __func__);
3187 lowercase_lang = g_utf8_strdown (found_lang, -1);
3188 g_free (found_lang);
3189 found_lang = lowercase_lang;
3190 lowercase_lang = NULL;
3192 if (lang != NULL && !strcmp (found_lang, lang)) {
3193 /* Got the one we're interested in */
3194 data_ptr = get_string_block (data_ptr, string_key,
3196 string_value_len, block);
3198 data_ptr = get_string_block (data_ptr, NULL, NULL,
3202 g_free (found_lang);
3204 if (data_ptr == NULL) {
3205 /* Child block hit padding */
3206 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Child block hit 0-length block, giving up", __func__);
3214 #if G_BYTE_ORDER == G_BIG_ENDIAN
3215 static gconstpointer
3216 big_up_string_block (gconstpointer data_ptr, version_data *block)
3218 guint16 data_len = block->data_len;
3219 guint16 string_len = 28; /* Length of the StringTable block */
3221 char *orig_data_ptr = (char *)data_ptr - 28;
3223 /* data_ptr is pointing at an array of one or more String
3224 * blocks with total length (not including alignment padding)
3227 while (((char *)data_ptr - (char *)orig_data_ptr) < data_len) {
3228 /* align on a 32-bit boundary */
3231 data_ptr = get_versioninfo_block (data_ptr, block);
3232 if (block->data_len == 0) {
3233 /* We must have hit padding, so give up
3236 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3240 string_len = string_len + block->data_len;
3242 big_value = g_convert ((gchar *)block->key,
3243 unicode_chars (block->key) * 2,
3244 "UTF-16BE", "UTF-16LE", NULL, NULL,
3246 if (big_value == NULL) {
3247 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't find a valid string, giving up", __func__);
3251 /* The swapped string should be exactly the same
3252 * length as the original little-endian one, but only
3253 * copy the number of original chars just to be on the
3256 memcpy (block->key, big_value, unicode_chars (block->key) * 2);
3259 big_value = g_convert ((gchar *)data_ptr,
3260 unicode_chars (data_ptr) * 2,
3261 "UTF-16BE", "UTF-16LE", NULL, NULL,
3263 if (big_value == NULL) {
3264 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't find a valid data string, giving up", __func__);
3267 memcpy ((gpointer)data_ptr, big_value,
3268 unicode_chars (data_ptr) * 2);
3271 data_ptr = ((gunichar2 *)data_ptr) + block->value_len;
3277 /* Returns a pointer to the byte following the Stringtable block, or
3278 * NULL if the data read hits padding. We can't recover from this
3279 * because the data length does not include padding bytes, so it's not
3280 * possible to just return the start position + length
3282 static gconstpointer
3283 big_up_stringtable_block (gconstpointer data_ptr, version_data *block)
3285 guint16 data_len = block->data_len;
3286 guint16 string_len = 36; /* length of the StringFileInfo block */
3289 /* data_ptr is pointing at an array of StringTable blocks,
3290 * with total length (not including alignment padding) of
3294 while(string_len < data_len) {
3295 /* align on a 32-bit boundary */
3298 data_ptr = get_versioninfo_block (data_ptr, block);
3299 if (block->data_len == 0) {
3300 /* We must have hit padding, so give up
3303 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3307 string_len = string_len + block->data_len;
3309 big_value = g_convert ((gchar *)block->key, 16, "UTF-16BE",
3310 "UTF-16LE", NULL, NULL, NULL);
3311 if (big_value == NULL) {
3312 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't find a valid string, giving up", __func__);
3316 memcpy (block->key, big_value, 16);
3319 data_ptr = big_up_string_block (data_ptr, block);
3321 if (data_ptr == NULL) {
3322 /* Child block hit padding */
3323 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Child block hit 0-length block, giving up", __func__);
3331 /* Follows the data structures and turns all UTF-16 strings from the
3332 * LE found in the resource section into UTF-16BE
3335 big_up (gconstpointer datablock, guint32 size)
3337 gconstpointer data_ptr;
3338 gint32 data_len; /* signed to guard against underflow */
3341 data_ptr = get_fixedfileinfo_block (datablock, &block);
3342 if (data_ptr != NULL) {
3343 VS_FIXEDFILEINFO *ffi = (VS_FIXEDFILEINFO *)data_ptr;
3345 /* Byteswap all the fields */
3346 ffi->dwFileVersionMS = GUINT32_SWAP_LE_BE (ffi->dwFileVersionMS);
3347 ffi->dwFileVersionLS = GUINT32_SWAP_LE_BE (ffi->dwFileVersionLS);
3348 ffi->dwProductVersionMS = GUINT32_SWAP_LE_BE (ffi->dwProductVersionMS);
3349 ffi->dwProductVersionLS = GUINT32_SWAP_LE_BE (ffi->dwProductVersionLS);
3350 ffi->dwFileFlagsMask = GUINT32_SWAP_LE_BE (ffi->dwFileFlagsMask);
3351 ffi->dwFileFlags = GUINT32_SWAP_LE_BE (ffi->dwFileFlags);
3352 ffi->dwFileOS = GUINT32_SWAP_LE_BE (ffi->dwFileOS);
3353 ffi->dwFileType = GUINT32_SWAP_LE_BE (ffi->dwFileType);
3354 ffi->dwFileSubtype = GUINT32_SWAP_LE_BE (ffi->dwFileSubtype);
3355 ffi->dwFileDateMS = GUINT32_SWAP_LE_BE (ffi->dwFileDateMS);
3356 ffi->dwFileDateLS = GUINT32_SWAP_LE_BE (ffi->dwFileDateLS);
3358 /* The FFI and header occupies the first 92 bytes
3360 data_ptr = (char *)data_ptr + sizeof(VS_FIXEDFILEINFO);
3361 data_len = block.data_len - 92;
3363 /* There now follow zero or one StringFileInfo blocks
3364 * and zero or one VarFileInfo blocks
3366 while (data_len > 0) {
3367 /* align on a 32-bit boundary */
3370 data_ptr = get_versioninfo_block (data_ptr, &block);
3371 if (block.data_len == 0) {
3372 /* We must have hit padding, so give
3375 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3379 data_len = data_len - block.data_len;
3381 if (unicode_string_equals (block.key, "VarFileInfo")) {
3382 data_ptr = get_varfileinfo_block (data_ptr,
3384 data_ptr = ((guchar *)data_ptr) + block.value_len;
3385 } else if (unicode_string_equals (block.key,
3386 "StringFileInfo")) {
3387 data_ptr = big_up_stringtable_block (data_ptr,
3391 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Not a valid VERSIONINFO child block", __func__);
3395 if (data_ptr == NULL) {
3396 /* Child block hit padding */
3397 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Child block hit 0-length block, giving up", __func__);
3406 mono_w32process_get_fileversion_info_size (gunichar2 *filename, guint32 *handle)
3409 gpointer versioninfo;
3414 /* This value is unused, but set to zero */
3417 file_map = map_pe_file (filename, &map_size, &map_handle);
3418 if (file_map == NULL) {
3422 versioninfo = find_pe_file_resources (file_map, map_size, RT_VERSION, 0, &size);
3423 if (versioninfo == NULL) {
3424 /* Didn't find the resource, so set the return value
3430 unmap_pe_file (file_map, map_handle);
3436 mono_w32process_get_fileversion_info (gunichar2 *filename, guint32 handle G_GNUC_UNUSED, guint32 len, gpointer data)
3439 gpointer versioninfo;
3443 gboolean ret = FALSE;
3445 file_map = map_pe_file (filename, &map_size, &map_handle);
3446 if (file_map == NULL) {
3450 versioninfo = find_pe_file_resources (file_map, map_size, RT_VERSION,
3452 if (versioninfo != NULL) {
3453 /* This could probably process the data so that
3454 * mono_w32process_ver_query_value() doesn't have to follow the data
3455 * blocks every time. But hey, these functions aren't
3456 * likely to appear in many profiles.
3458 memcpy (data, versioninfo, len < size?len:size);
3461 #if G_BYTE_ORDER == G_BIG_ENDIAN
3462 big_up (data, size);
3466 unmap_pe_file (file_map, map_handle);
3472 mono_w32process_ver_query_value (gconstpointer datablock, const gunichar2 *subblock, gpointer *buffer, guint32 *len)
3474 gchar *subblock_utf8, *lang_utf8 = NULL;
3475 gboolean ret = FALSE;
3477 gconstpointer data_ptr;
3478 gint32 data_len; /* signed to guard against underflow */
3479 gboolean want_var = FALSE;
3480 gboolean want_string = FALSE;
3482 const gunichar2 *string_key = NULL;
3483 gpointer string_value = NULL;
3484 guint32 string_value_len = 0;
3485 gchar *lowercase_lang;
3487 subblock_utf8 = g_utf16_to_utf8 (subblock, -1, NULL, NULL, NULL);
3488 if (subblock_utf8 == NULL) {
3492 if (!strcmp (subblock_utf8, "\\VarFileInfo\\Translation")) {
3494 } else if (!strncmp (subblock_utf8, "\\StringFileInfo\\", 16)) {
3496 memcpy (lang, subblock + 16, 8 * sizeof(gunichar2));
3497 lang_utf8 = g_utf16_to_utf8 (lang, 8, NULL, NULL, NULL);
3498 lowercase_lang = g_utf8_strdown (lang_utf8, -1);
3500 lang_utf8 = lowercase_lang;
3501 lowercase_lang = NULL;
3502 string_key = subblock + 25;
3505 if (!strcmp (subblock_utf8, "\\")) {
3506 data_ptr = get_fixedfileinfo_block (datablock, &block);
3507 if (data_ptr != NULL) {
3508 *buffer = (gpointer)data_ptr;
3509 *len = block.value_len;
3513 } else if (want_var || want_string) {
3514 data_ptr = get_fixedfileinfo_block (datablock, &block);
3515 if (data_ptr != NULL) {
3516 /* The FFI and header occupies the first 92
3519 data_ptr = (char *)data_ptr + sizeof(VS_FIXEDFILEINFO);
3520 data_len = block.data_len - 92;
3522 /* There now follow zero or one StringFileInfo
3523 * blocks and zero or one VarFileInfo blocks
3525 while (data_len > 0) {
3526 /* align on a 32-bit boundary */
3529 data_ptr = get_versioninfo_block (data_ptr,
3531 if (block.data_len == 0) {
3532 /* We must have hit padding,
3533 * so give up processing now
3535 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3539 data_len = data_len - block.data_len;
3541 if (unicode_string_equals (block.key, "VarFileInfo")) {
3542 data_ptr = get_varfileinfo_block (data_ptr, &block);
3544 *buffer = (gpointer)data_ptr;
3545 *len = block.value_len;
3549 /* Skip over the Var block */
3550 data_ptr = ((guchar *)data_ptr) + block.value_len;
3552 } else if (unicode_string_equals (block.key, "StringFileInfo")) {
3553 data_ptr = get_stringtable_block (data_ptr, lang_utf8, string_key, &string_value, &string_value_len, &block);
3555 string_value != NULL &&
3556 string_value_len != 0) {
3557 *buffer = string_value;
3558 *len = unicode_chars ((const gunichar2 *)string_value) + 1; /* Include trailing null */
3564 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Not a valid VERSIONINFO child block", __func__);
3568 if (data_ptr == NULL) {
3569 /* Child block hit padding */
3570 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Child block hit 0-length block, giving up", __func__);
3582 g_free (subblock_utf8);
3587 copy_lang (gunichar2 *lang_out, guint32 lang_len, const gchar *text)
3590 int chars = strlen (text);
3593 unitext = g_utf8_to_utf16 (text, -1, NULL, NULL, NULL);
3594 g_assert (unitext != NULL);
3596 if (chars < (lang_len - 1)) {
3597 memcpy (lang_out, (gpointer)unitext, chars * 2);
3598 lang_out[chars] = '\0';
3601 memcpy (lang_out, (gpointer)unitext, (lang_len - 1) * 2);
3602 lang_out[lang_len] = '\0';
3612 mono_w32process_ver_language_name (guint32 lang, gunichar2 *lang_out, guint32 lang_len)
3614 int primary, secondary;
3615 const char *name = NULL;
3617 primary = lang & 0x3FF;
3618 secondary = (lang >> 10) & 0x3F;
3622 switch (secondary) {
3623 case 0x01: name = "Process Default Language"; break;
3627 switch (secondary) {
3629 case 0x01: name = "Arabic (Saudi Arabia)"; break;
3630 case 0x02: name = "Arabic (Iraq)"; break;
3631 case 0x03: name = "Arabic (Egypt)"; break;
3632 case 0x04: name = "Arabic (Libya)"; break;
3633 case 0x05: name = "Arabic (Algeria)"; break;
3634 case 0x06: name = "Arabic (Morocco)"; break;
3635 case 0x07: name = "Arabic (Tunisia)"; break;
3636 case 0x08: name = "Arabic (Oman)"; break;
3637 case 0x09: name = "Arabic (Yemen)"; break;
3638 case 0x0a: name = "Arabic (Syria)"; break;
3639 case 0x0b: name = "Arabic (Jordan)"; break;
3640 case 0x0c: name = "Arabic (Lebanon)"; break;
3641 case 0x0d: name = "Arabic (Kuwait)"; break;
3642 case 0x0e: name = "Arabic (U.A.E.)"; break;
3643 case 0x0f: name = "Arabic (Bahrain)"; break;
3644 case 0x10: name = "Arabic (Qatar)"; break;
3648 switch (secondary) {
3649 case 0x00: name = "Bulgarian (Bulgaria)"; break;
3650 case 0x01: name = "Bulgarian"; break;
3654 switch (secondary) {
3655 case 0x00: name = "Catalan (Spain)"; break;
3656 case 0x01: name = "Catalan"; break;
3660 switch (secondary) {
3662 case 0x01: name = "Chinese (Taiwan)"; break;
3663 case 0x02: name = "Chinese (PRC)"; break;
3664 case 0x03: name = "Chinese (Hong Kong S.A.R.)"; break;
3665 case 0x04: name = "Chinese (Singapore)"; break;
3666 case 0x05: name = "Chinese (Macau S.A.R.)"; break;
3670 switch (secondary) {
3671 case 0x00: name = "Czech (Czech Republic)"; break;
3672 case 0x01: name = "Czech"; break;
3676 switch (secondary) {
3677 case 0x00: name = "Danish (Denmark)"; break;
3678 case 0x01: name = "Danish"; break;
3682 switch (secondary) {
3684 case 0x01: name = "German (Germany)"; break;
3685 case 0x02: name = "German (Switzerland)"; break;
3686 case 0x03: name = "German (Austria)"; break;
3687 case 0x04: name = "German (Luxembourg)"; break;
3688 case 0x05: name = "German (Liechtenstein)"; break;
3692 switch (secondary) {
3693 case 0x00: name = "Greek (Greece)"; break;
3694 case 0x01: name = "Greek"; break;
3698 switch (secondary) {
3700 case 0x01: name = "English (United States)"; break;
3701 case 0x02: name = "English (United Kingdom)"; break;
3702 case 0x03: name = "English (Australia)"; break;
3703 case 0x04: name = "English (Canada)"; break;
3704 case 0x05: name = "English (New Zealand)"; break;
3705 case 0x06: name = "English (Ireland)"; break;
3706 case 0x07: name = "English (South Africa)"; break;
3707 case 0x08: name = "English (Jamaica)"; break;
3708 case 0x09: name = "English (Caribbean)"; break;
3709 case 0x0a: name = "English (Belize)"; break;
3710 case 0x0b: name = "English (Trinidad and Tobago)"; break;
3711 case 0x0c: name = "English (Zimbabwe)"; break;
3712 case 0x0d: name = "English (Philippines)"; break;
3713 case 0x10: name = "English (India)"; break;
3714 case 0x11: name = "English (Malaysia)"; break;
3715 case 0x12: name = "English (Singapore)"; break;
3719 switch (secondary) {
3720 case 0x00: name = "Spanish (Spain)"; break;
3721 case 0x01: name = "Spanish (Traditional Sort)"; break;
3722 case 0x02: name = "Spanish (Mexico)"; break;
3723 case 0x03: name = "Spanish (International Sort)"; break;
3724 case 0x04: name = "Spanish (Guatemala)"; break;
3725 case 0x05: name = "Spanish (Costa Rica)"; break;
3726 case 0x06: name = "Spanish (Panama)"; break;
3727 case 0x07: name = "Spanish (Dominican Republic)"; break;
3728 case 0x08: name = "Spanish (Venezuela)"; break;
3729 case 0x09: name = "Spanish (Colombia)"; break;
3730 case 0x0a: name = "Spanish (Peru)"; break;
3731 case 0x0b: name = "Spanish (Argentina)"; break;
3732 case 0x0c: name = "Spanish (Ecuador)"; break;
3733 case 0x0d: name = "Spanish (Chile)"; break;
3734 case 0x0e: name = "Spanish (Uruguay)"; break;
3735 case 0x0f: name = "Spanish (Paraguay)"; break;
3736 case 0x10: name = "Spanish (Bolivia)"; break;
3737 case 0x11: name = "Spanish (El Salvador)"; break;
3738 case 0x12: name = "Spanish (Honduras)"; break;
3739 case 0x13: name = "Spanish (Nicaragua)"; break;
3740 case 0x14: name = "Spanish (Puerto Rico)"; break;
3741 case 0x15: name = "Spanish (United States)"; break;
3745 switch (secondary) {
3746 case 0x00: name = "Finnish (Finland)"; break;
3747 case 0x01: name = "Finnish"; break;
3751 switch (secondary) {
3753 case 0x01: name = "French (France)"; break;
3754 case 0x02: name = "French (Belgium)"; break;
3755 case 0x03: name = "French (Canada)"; break;
3756 case 0x04: name = "French (Switzerland)"; break;
3757 case 0x05: name = "French (Luxembourg)"; break;
3758 case 0x06: name = "French (Monaco)"; break;
3762 switch (secondary) {
3763 case 0x00: name = "Hebrew (Israel)"; break;
3764 case 0x01: name = "Hebrew"; break;
3768 switch (secondary) {
3769 case 0x00: name = "Hungarian (Hungary)"; break;
3770 case 0x01: name = "Hungarian"; break;
3774 switch (secondary) {
3775 case 0x00: name = "Icelandic (Iceland)"; break;
3776 case 0x01: name = "Icelandic"; break;
3780 switch (secondary) {
3782 case 0x01: name = "Italian (Italy)"; break;
3783 case 0x02: name = "Italian (Switzerland)"; break;
3787 switch (secondary) {
3788 case 0x00: name = "Japanese (Japan)"; break;
3789 case 0x01: name = "Japanese"; break;
3793 switch (secondary) {
3794 case 0x00: name = "Korean (Korea)"; break;
3795 case 0x01: name = "Korean"; break;
3799 switch (secondary) {
3801 case 0x01: name = "Dutch (Netherlands)"; break;
3802 case 0x02: name = "Dutch (Belgium)"; break;
3806 switch (secondary) {
3808 case 0x01: name = "Norwegian (Bokmal)"; break;
3809 case 0x02: name = "Norwegian (Nynorsk)"; break;
3813 switch (secondary) {
3814 case 0x00: name = "Polish (Poland)"; break;
3815 case 0x01: name = "Polish"; break;
3819 switch (secondary) {
3821 case 0x01: name = "Portuguese (Brazil)"; break;
3822 case 0x02: name = "Portuguese (Portugal)"; break;
3826 switch (secondary) {
3827 case 0x01: name = "Romansh (Switzerland)"; break;
3831 switch (secondary) {
3832 case 0x00: name = "Romanian (Romania)"; break;
3833 case 0x01: name = "Romanian"; break;
3837 switch (secondary) {
3838 case 0x00: name = "Russian (Russia)"; break;
3839 case 0x01: name = "Russian"; break;
3843 switch (secondary) {
3844 case 0x00: name = "Croatian (Croatia)"; break;
3845 case 0x01: name = "Croatian"; break;
3846 case 0x02: name = "Serbian (Latin)"; break;
3847 case 0x03: name = "Serbian (Cyrillic)"; break;
3848 case 0x04: name = "Croatian (Bosnia and Herzegovina)"; break;
3849 case 0x05: name = "Bosnian (Latin, Bosnia and Herzegovina)"; break;
3850 case 0x06: name = "Serbian (Latin, Bosnia and Herzegovina)"; break;
3851 case 0x07: name = "Serbian (Cyrillic, Bosnia and Herzegovina)"; break;
3852 case 0x08: name = "Bosnian (Cyrillic, Bosnia and Herzegovina)"; break;
3856 switch (secondary) {
3857 case 0x00: name = "Slovak (Slovakia)"; break;
3858 case 0x01: name = "Slovak"; break;
3862 switch (secondary) {
3863 case 0x00: name = "Albanian (Albania)"; break;
3864 case 0x01: name = "Albanian"; break;
3868 switch (secondary) {
3869 case 0x00: name = "Swedish (Sweden)"; break;
3870 case 0x01: name = "Swedish"; break;
3871 case 0x02: name = "Swedish (Finland)"; break;
3875 switch (secondary) {
3876 case 0x00: name = "Thai (Thailand)"; break;
3877 case 0x01: name = "Thai"; break;
3881 switch (secondary) {
3882 case 0x00: name = "Turkish (Turkey)"; break;
3883 case 0x01: name = "Turkish"; break;
3887 switch (secondary) {
3888 case 0x00: name = "Urdu (Islamic Republic of Pakistan)"; break;
3889 case 0x01: name = "Urdu"; break;
3893 switch (secondary) {
3894 case 0x00: name = "Indonesian (Indonesia)"; break;
3895 case 0x01: name = "Indonesian"; break;
3899 switch (secondary) {
3900 case 0x00: name = "Ukrainian (Ukraine)"; break;
3901 case 0x01: name = "Ukrainian"; break;
3905 switch (secondary) {
3906 case 0x00: name = "Belarusian (Belarus)"; break;
3907 case 0x01: name = "Belarusian"; break;
3911 switch (secondary) {
3912 case 0x00: name = "Slovenian (Slovenia)"; break;
3913 case 0x01: name = "Slovenian"; break;
3917 switch (secondary) {
3918 case 0x00: name = "Estonian (Estonia)"; break;
3919 case 0x01: name = "Estonian"; break;
3923 switch (secondary) {
3924 case 0x00: name = "Latvian (Latvia)"; break;
3925 case 0x01: name = "Latvian"; break;
3929 switch (secondary) {
3930 case 0x00: name = "Lithuanian (Lithuania)"; break;
3931 case 0x01: name = "Lithuanian"; break;
3935 switch (secondary) {
3936 case 0x01: name = "Tajik (Tajikistan)"; break;
3940 switch (secondary) {
3941 case 0x00: name = "Farsi (Iran)"; break;
3942 case 0x01: name = "Farsi"; break;
3946 switch (secondary) {
3947 case 0x00: name = "Vietnamese (Viet Nam)"; break;
3948 case 0x01: name = "Vietnamese"; break;
3952 switch (secondary) {
3953 case 0x00: name = "Armenian (Armenia)"; break;
3954 case 0x01: name = "Armenian"; break;
3958 switch (secondary) {
3959 case 0x00: name = "Azeri (Latin) (Azerbaijan)"; break;
3960 case 0x01: name = "Azeri (Latin)"; break;
3961 case 0x02: name = "Azeri (Cyrillic)"; break;
3965 switch (secondary) {
3966 case 0x00: name = "Basque (Spain)"; break;
3967 case 0x01: name = "Basque"; break;
3971 switch (secondary) {
3972 case 0x01: name = "Upper Sorbian (Germany)"; break;
3973 case 0x02: name = "Lower Sorbian (Germany)"; break;
3977 switch (secondary) {
3978 case 0x00: name = "FYRO Macedonian (Former Yugoslav Republic of Macedonia)"; break;
3979 case 0x01: name = "FYRO Macedonian"; break;
3983 switch (secondary) {
3984 case 0x00: name = "Tswana (South Africa)"; break;
3985 case 0x01: name = "Tswana"; break;
3989 switch (secondary) {
3990 case 0x00: name = "Xhosa (South Africa)"; break;
3991 case 0x01: name = "Xhosa"; break;
3995 switch (secondary) {
3996 case 0x00: name = "Zulu (South Africa)"; break;
3997 case 0x01: name = "Zulu"; break;
4001 switch (secondary) {
4002 case 0x00: name = "Afrikaans (South Africa)"; break;
4003 case 0x01: name = "Afrikaans"; break;
4007 switch (secondary) {
4008 case 0x00: name = "Georgian (Georgia)"; break;
4009 case 0x01: name = "Georgian"; break;
4013 switch (secondary) {
4014 case 0x00: name = "Faroese (Faroe Islands)"; break;
4015 case 0x01: name = "Faroese"; break;
4019 switch (secondary) {
4020 case 0x00: name = "Hindi (India)"; break;
4021 case 0x01: name = "Hindi"; break;
4025 switch (secondary) {
4026 case 0x00: name = "Maltese (Malta)"; break;
4027 case 0x01: name = "Maltese"; break;
4031 switch (secondary) {
4032 case 0x00: name = "Sami (Northern) (Norway)"; break;
4033 case 0x01: name = "Sami, Northern (Norway)"; break;
4034 case 0x02: name = "Sami, Northern (Sweden)"; break;
4035 case 0x03: name = "Sami, Northern (Finland)"; break;
4036 case 0x04: name = "Sami, Lule (Norway)"; break;
4037 case 0x05: name = "Sami, Lule (Sweden)"; break;
4038 case 0x06: name = "Sami, Southern (Norway)"; break;
4039 case 0x07: name = "Sami, Southern (Sweden)"; break;
4040 case 0x08: name = "Sami, Skolt (Finland)"; break;
4041 case 0x09: name = "Sami, Inari (Finland)"; break;
4045 switch (secondary) {
4046 case 0x02: name = "Irish (Ireland)"; break;
4050 switch (secondary) {
4052 case 0x01: name = "Malay (Malaysia)"; break;
4053 case 0x02: name = "Malay (Brunei Darussalam)"; break;
4057 switch (secondary) {
4058 case 0x00: name = "Kazakh (Kazakhstan)"; break;
4059 case 0x01: name = "Kazakh"; break;
4063 switch (secondary) {
4064 case 0x00: name = "Kyrgyz (Kyrgyzstan)"; break;
4065 case 0x01: name = "Kyrgyz (Cyrillic)"; break;
4069 switch (secondary) {
4070 case 0x00: name = "Swahili (Kenya)"; break;
4071 case 0x01: name = "Swahili"; break;
4075 switch (secondary) {
4076 case 0x01: name = "Turkmen (Turkmenistan)"; break;
4080 switch (secondary) {
4081 case 0x00: name = "Uzbek (Latin) (Uzbekistan)"; break;
4082 case 0x01: name = "Uzbek (Latin)"; break;
4083 case 0x02: name = "Uzbek (Cyrillic)"; break;
4087 switch (secondary) {
4088 case 0x00: name = "Tatar (Russia)"; break;
4089 case 0x01: name = "Tatar"; break;
4093 switch (secondary) {
4095 case 0x01: name = "Bengali (India)"; break;
4099 switch (secondary) {
4100 case 0x00: name = "Punjabi (India)"; break;
4101 case 0x01: name = "Punjabi"; break;
4105 switch (secondary) {
4106 case 0x00: name = "Gujarati (India)"; break;
4107 case 0x01: name = "Gujarati"; break;
4111 switch (secondary) {
4112 case 0x00: name = "Tamil (India)"; break;
4113 case 0x01: name = "Tamil"; break;
4117 switch (secondary) {
4118 case 0x00: name = "Telugu (India)"; break;
4119 case 0x01: name = "Telugu"; break;
4123 switch (secondary) {
4124 case 0x00: name = "Kannada (India)"; break;
4125 case 0x01: name = "Kannada"; break;
4129 switch (secondary) {
4131 case 0x01: name = "Malayalam (India)"; break;
4135 switch (secondary) {
4136 case 0x01: name = "Assamese (India)"; break;
4140 switch (secondary) {
4141 case 0x00: name = "Marathi (India)"; break;
4142 case 0x01: name = "Marathi"; break;
4146 switch (secondary) {
4147 case 0x00: name = "Sanskrit (India)"; break;
4148 case 0x01: name = "Sanskrit"; break;
4152 switch (secondary) {
4153 case 0x00: name = "Mongolian (Mongolia)"; break;
4154 case 0x01: name = "Mongolian (Cyrillic)"; break;
4155 case 0x02: name = "Mongolian (PRC)"; break;
4159 switch (secondary) {
4160 case 0x01: name = "Tibetan (PRC)"; break;
4161 case 0x02: name = "Tibetan (Bhutan)"; break;
4165 switch (secondary) {
4166 case 0x00: name = "Welsh (United Kingdom)"; break;
4167 case 0x01: name = "Welsh"; break;
4171 switch (secondary) {
4172 case 0x01: name = "Khmer (Cambodia)"; break;
4176 switch (secondary) {
4177 case 0x01: name = "Lao (Lao PDR)"; break;
4181 switch (secondary) {
4182 case 0x00: name = "Galician (Spain)"; break;
4183 case 0x01: name = "Galician"; break;
4187 switch (secondary) {
4188 case 0x00: name = "Konkani (India)"; break;
4189 case 0x01: name = "Konkani"; break;
4193 switch (secondary) {
4194 case 0x00: name = "Syriac (Syria)"; break;
4195 case 0x01: name = "Syriac"; break;
4199 switch (secondary) {
4200 case 0x01: name = "Sinhala (Sri Lanka)"; break;
4204 switch (secondary) {
4205 case 0x01: name = "Inuktitut (Syllabics, Canada)"; break;
4206 case 0x02: name = "Inuktitut (Latin, Canada)"; break;
4210 switch (secondary) {
4211 case 0x01: name = "Amharic (Ethiopia)"; break;
4215 switch (secondary) {
4216 case 0x02: name = "Tamazight (Algeria, Latin)"; break;
4220 switch (secondary) {
4221 case 0x01: name = "Nepali (Nepal)"; break;
4225 switch (secondary) {
4226 case 0x01: name = "Frisian (Netherlands)"; break;
4230 switch (secondary) {
4231 case 0x01: name = "Pashto (Afghanistan)"; break;
4235 switch (secondary) {
4236 case 0x01: name = "Filipino (Philippines)"; break;
4240 switch (secondary) {
4241 case 0x00: name = "Divehi (Maldives)"; break;
4242 case 0x01: name = "Divehi"; break;
4246 switch (secondary) {
4247 case 0x01: name = "Hausa (Nigeria, Latin)"; break;
4251 switch (secondary) {
4252 case 0x01: name = "Yoruba (Nigeria)"; break;
4256 switch (secondary) {
4258 case 0x01: name = "Quechua (Bolivia)"; break;
4259 case 0x02: name = "Quechua (Ecuador)"; break;
4260 case 0x03: name = "Quechua (Peru)"; break;
4264 switch (secondary) {
4265 case 0x00: name = "Northern Sotho (South Africa)"; break;
4266 case 0x01: name = "Northern Sotho"; break;
4270 switch (secondary) {
4271 case 0x01: name = "Bashkir (Russia)"; break;
4275 switch (secondary) {
4276 case 0x01: name = "Luxembourgish (Luxembourg)"; break;
4280 switch (secondary) {
4281 case 0x01: name = "Greenlandic (Greenland)"; break;
4285 switch (secondary) {
4286 case 0x01: name = "Yi (PRC)"; break;
4290 switch (secondary) {
4291 case 0x01: name = "Mapudungun (Chile)"; break;
4295 switch (secondary) {
4296 case 0x01: name = "Mohawk (Mohawk)"; break;
4300 switch (secondary) {
4301 case 0x01: name = "Breton (France)"; break;
4305 switch (secondary) {
4306 case 0x00: name = "Invariant Language (Invariant Country)"; break;
4310 switch (secondary) {
4311 case 0x01: name = "Uighur (PRC)"; break;
4315 switch (secondary) {
4316 case 0x00: name = "Maori (New Zealand)"; break;
4317 case 0x01: name = "Maori"; break;
4321 switch (secondary) {
4322 case 0x01: name = "Corsican (France)"; break;
4326 switch (secondary) {
4327 case 0x01: name = "Alsatian (France)"; break;
4331 switch (secondary) {
4332 case 0x01: name = "Yakut (Russia)"; break;
4336 switch (secondary) {
4337 case 0x01: name = "K'iche (Guatemala)"; break;
4341 switch (secondary) {
4342 case 0x01: name = "Kinyarwanda (Rwanda)"; break;
4346 switch (secondary) {
4347 case 0x01: name = "Wolof (Senegal)"; break;
4351 switch (secondary) {
4352 case 0x01: name = "Dari (Afghanistan)"; break;
4357 name = "Language Neutral";
4362 name = "Language Neutral";
4364 return copy_lang (lang_out, lang_len, name);