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 * Handles > _WAPI_PROCESS_UNHANDLED are pseudo handles which represent processes
103 * not started by the runtime.
105 /* This marks a system process that we don't have a handle on */
106 /* FIXME: Cope with PIDs > sizeof guint */
107 #define _WAPI_PROCESS_UNHANDLED (1 << (8*sizeof(pid_t)-1))
109 #define WAPI_IS_PSEUDO_PROCESS_HANDLE(handle) ((GPOINTER_TO_UINT(handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED)
110 #define WAPI_PID_TO_HANDLE(pid) GINT_TO_POINTER (_WAPI_PROCESS_UNHANDLED + (pid))
111 #define WAPI_HANDLE_TO_PID(handle) (GPOINTER_TO_UINT ((handle)) - _WAPI_PROCESS_UNHANDLED)
114 STARTF_USESHOWWINDOW=0x001,
115 STARTF_USESIZE=0x002,
116 STARTF_USEPOSITION=0x004,
117 STARTF_USECOUNTCHARS=0x008,
118 STARTF_USEFILLATTRIBUTE=0x010,
119 STARTF_RUNFULLSCREEN=0x020,
120 STARTF_FORCEONFEEDBACK=0x040,
121 STARTF_FORCEOFFFEEDBACK=0x080,
122 STARTF_USESTDHANDLES=0x100
132 #if G_BYTE_ORDER == G_BIG_ENDIAN
133 guint32 highDateTime;
137 guint32 highDateTime;
142 * Process describes processes we create.
143 * It contains a semaphore that can be waited on in order to wait
144 * for process termination. It's accessed in our SIGCHLD handler,
145 * when status is updated (and pid cleared, to not clash with
146 * subsequent processes that may get executed).
148 typedef struct _Process {
149 pid_t pid; /* the pid of the process. This value is only valid until the process has exited. */
150 MonoSemType exit_sem; /* this semaphore will be released when the process exits */
151 int status; /* the exit status */
152 gint32 handle_count; /* the number of handles to this process instance */
153 /* we keep a ref to the creating _WapiHandle_process handle until
154 * the process has exited, so that the information there isn't lost.
159 struct _Process *next;
162 /* MonoW32HandleProcess is a structure containing all the required information for process handling. */
166 gpointer main_thread;
170 size_t min_working_set;
171 size_t max_working_set;
174 } MonoW32HandleProcess;
179 * 2 bytes: Length in bytes (this block, and all child blocks. does _not_ include alignment padding between blocks)
180 * 2 bytes: Length in bytes of VS_FIXEDFILEINFO struct
181 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
182 * Variable length unicode string (null terminated): Key (currently "VS_VERSION_INFO")
183 * Variable length padding to align VS_FIXEDFILEINFO on a 32-bit boundary
184 * VS_FIXEDFILEINFO struct
185 * Variable length padding to align Child struct on a 32-bit boundary
186 * Child struct (zero or one StringFileInfo structs, zero or one VarFileInfo structs)
192 * 2 bytes: Length in bytes (includes this block, as well as all Child blocks)
193 * 2 bytes: Value length (always zero)
194 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
195 * Variable length unicode string: Key (currently "StringFileInfo")
196 * Variable length padding to align Child struct on a 32-bit boundary
197 * Child structs ( one or more StringTable structs. Each StringTable struct's Key member indicates the appropriate language and code page for displaying the text in that StringTable struct.)
203 * 2 bytes: Length in bytes (includes this block as well as all Child blocks, but excludes any padding between String blocks)
204 * 2 bytes: Value length (always zero)
205 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
206 * Variable length unicode string: Key. An 8-digit hex number stored as a unicode string. The four most significant digits represent the language identifier. The four least significant digits represent the code page for which the data is formatted.
207 * Variable length padding to align Child struct on a 32-bit boundary
208 * Child structs (an array of one or more String structs (each aligned on a 32-bit boundary)
214 * 2 bytes: Length in bytes (of this block)
215 * 2 bytes: Value length (the length in words of the Value member)
216 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
217 * Variable length unicode string: Key. arbitrary string, identifies data.
218 * Variable length padding to align Value on a 32-bit boundary
219 * Value: Variable length unicode string, holding data.
225 * 2 bytes: Length in bytes (includes this block, as well as all Child blocks)
226 * 2 bytes: Value length (always zero)
227 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
228 * Variable length unicode string: Key (currently "VarFileInfo")
229 * Variable length padding to align Child struct on a 32-bit boundary
230 * Child structs (a Var struct)
236 * 2 bytes: Length in bytes of this block
237 * 2 bytes: Value length in bytes of the Value
238 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
239 * Variable length unicode string: Key ("Translation")
240 * Variable length padding to align Value on a 32-bit boundary
241 * Value: an array of one or more 4 byte values that are language and code page identifier pairs, low-order word containing a language identifier, and the high-order word containing a code page number. Either word can be zero, indicating that the file is language or code page independent.
244 #if G_BYTE_ORDER == G_BIG_ENDIAN
245 #define VS_FFI_SIGNATURE 0xbd04effe
246 #define VS_FFI_STRUCVERSION 0x00000100
248 #define VS_FFI_SIGNATURE 0xfeef04bd
249 #define VS_FFI_STRUCVERSION 0x00010000
252 #define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16
254 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0
255 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1
256 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2
258 #define IMAGE_SIZEOF_SHORT_NAME 8
260 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
261 #define IMAGE_DOS_SIGNATURE 0x4d5a
262 #define IMAGE_NT_SIGNATURE 0x50450000
263 #define IMAGE_NT_OPTIONAL_HDR32_MAGIC 0xb10
264 #define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0xb20
266 #define IMAGE_DOS_SIGNATURE 0x5a4d
267 #define IMAGE_NT_SIGNATURE 0x00004550
268 #define IMAGE_NT_OPTIONAL_HDR32_MAGIC 0x10b
269 #define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b
296 guint16 NumberOfSections;
297 guint32 TimeDateStamp;
298 guint32 PointerToSymbolTable;
299 guint32 NumberOfSymbols;
300 guint16 SizeOfOptionalHeader;
301 guint16 Characteristics;
305 guint32 VirtualAddress;
307 } IMAGE_DATA_DIRECTORY;
311 guint8 MajorLinkerVersion;
312 guint8 MinorLinkerVersion;
314 guint32 SizeOfInitializedData;
315 guint32 SizeOfUninitializedData;
316 guint32 AddressOfEntryPoint;
320 guint32 SectionAlignment;
321 guint32 FileAlignment;
322 guint16 MajorOperatingSystemVersion;
323 guint16 MinorOperatingSystemVersion;
324 guint16 MajorImageVersion;
325 guint16 MinorImageVersion;
326 guint16 MajorSubsystemVersion;
327 guint16 MinorSubsystemVersion;
328 guint32 Win32VersionValue;
330 guint32 SizeOfHeaders;
333 guint16 DllCharacteristics;
334 guint32 SizeOfStackReserve;
335 guint32 SizeOfStackCommit;
336 guint32 SizeOfHeapReserve;
337 guint32 SizeOfHeapCommit;
339 guint32 NumberOfRvaAndSizes;
340 IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
341 } IMAGE_OPTIONAL_HEADER32;
345 guint8 MajorLinkerVersion;
346 guint8 MinorLinkerVersion;
348 guint32 SizeOfInitializedData;
349 guint32 SizeOfUninitializedData;
350 guint32 AddressOfEntryPoint;
353 guint32 SectionAlignment;
354 guint32 FileAlignment;
355 guint16 MajorOperatingSystemVersion;
356 guint16 MinorOperatingSystemVersion;
357 guint16 MajorImageVersion;
358 guint16 MinorImageVersion;
359 guint16 MajorSubsystemVersion;
360 guint16 MinorSubsystemVersion;
361 guint32 Win32VersionValue;
363 guint32 SizeOfHeaders;
366 guint16 DllCharacteristics;
367 guint64 SizeOfStackReserve;
368 guint64 SizeOfStackCommit;
369 guint64 SizeOfHeapReserve;
370 guint64 SizeOfHeapCommit;
372 guint32 NumberOfRvaAndSizes;
373 IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
374 } IMAGE_OPTIONAL_HEADER64;
376 #if SIZEOF_VOID_P == 8
377 typedef IMAGE_OPTIONAL_HEADER64 IMAGE_OPTIONAL_HEADER;
379 typedef IMAGE_OPTIONAL_HEADER32 IMAGE_OPTIONAL_HEADER;
384 IMAGE_FILE_HEADER FileHeader;
385 IMAGE_OPTIONAL_HEADER32 OptionalHeader;
386 } IMAGE_NT_HEADERS32;
390 IMAGE_FILE_HEADER FileHeader;
391 IMAGE_OPTIONAL_HEADER64 OptionalHeader;
392 } IMAGE_NT_HEADERS64;
394 #if SIZEOF_VOID_P == 8
395 typedef IMAGE_NT_HEADERS64 IMAGE_NT_HEADERS;
397 typedef IMAGE_NT_HEADERS32 IMAGE_NT_HEADERS;
401 guint8 Name[IMAGE_SIZEOF_SHORT_NAME];
403 guint32 PhysicalAddress;
406 guint32 VirtualAddress;
407 guint32 SizeOfRawData;
408 guint32 PointerToRawData;
409 guint32 PointerToRelocations;
410 guint32 PointerToLinenumbers;
411 guint16 NumberOfRelocations;
412 guint16 NumberOfLinenumbers;
413 guint32 Characteristics;
414 } IMAGE_SECTION_HEADER;
416 #define IMAGE_FIRST_SECTION32(header) ((IMAGE_SECTION_HEADER *)((gsize)(header) + G_STRUCT_OFFSET (IMAGE_NT_HEADERS32, OptionalHeader) + GUINT16_FROM_LE (((IMAGE_NT_HEADERS32 *)(header))->FileHeader.SizeOfOptionalHeader)))
418 #define RT_CURSOR 0x01
419 #define RT_BITMAP 0x02
422 #define RT_DIALOG 0x05
423 #define RT_STRING 0x06
424 #define RT_FONTDIR 0x07
426 #define RT_ACCELERATOR 0x09
427 #define RT_RCDATA 0x0a
428 #define RT_MESSAGETABLE 0x0b
429 #define RT_GROUP_CURSOR 0x0c
430 #define RT_GROUP_ICON 0x0e
431 #define RT_VERSION 0x10
432 #define RT_DLGINCLUDE 0x11
433 #define RT_PLUGPLAY 0x13
435 #define RT_ANICURSOR 0x15
436 #define RT_ANIICON 0x16
438 #define RT_MANIFEST 0x18
441 guint32 Characteristics;
442 guint32 TimeDateStamp;
443 guint16 MajorVersion;
444 guint16 MinorVersion;
445 guint16 NumberOfNamedEntries;
446 guint16 NumberOfIdEntries;
447 } IMAGE_RESOURCE_DIRECTORY;
452 #if G_BYTE_ORDER == G_BIG_ENDIAN
453 guint32 NameIsString:1;
454 guint32 NameOffset:31;
456 guint32 NameOffset:31;
457 guint32 NameIsString:1;
461 #if G_BYTE_ORDER == G_BIG_ENDIAN
463 guint16 __wapi_big_endian_padding;
471 guint32 OffsetToData;
473 #if G_BYTE_ORDER == G_BIG_ENDIAN
474 guint32 DataIsDirectory:1;
475 guint32 OffsetToDirectory:31;
477 guint32 OffsetToDirectory:31;
478 guint32 DataIsDirectory:1;
482 } IMAGE_RESOURCE_DIRECTORY_ENTRY;
485 guint32 OffsetToData;
489 } IMAGE_RESOURCE_DATA_ENTRY;
491 #define VOS_UNKNOWN 0x00000000
492 #define VOS_DOS 0x00010000
493 #define VOS_OS216 0x00020000
494 #define VOS_OS232 0x00030000
495 #define VOS_NT 0x00040000
496 #define VOS__BASE 0x00000000
497 #define VOS__WINDOWS16 0x00000001
498 #define VOS__PM16 0x00000002
499 #define VOS__PM32 0x00000003
500 #define VOS__WINDOWS32 0x00000004
501 /* Should "embrace and extend" here with some entries for linux etc */
503 #define VOS_DOS_WINDOWS16 0x00010001
504 #define VOS_DOS_WINDOWS32 0x00010004
505 #define VOS_OS216_PM16 0x00020002
506 #define VOS_OS232_PM32 0x00030003
507 #define VOS_NT_WINDOWS32 0x00040004
509 #define VFT_UNKNOWN 0x0000
510 #define VFT_APP 0x0001
511 #define VFT_DLL 0x0002
512 #define VFT_DRV 0x0003
513 #define VFT_FONT 0x0004
514 #define VFT_VXD 0x0005
515 #define VFT_STATIC_LIB 0x0007
517 #define VFT2_UNKNOWN 0x0000
518 #define VFT2_DRV_PRINTER 0x0001
519 #define VFT2_DRV_KEYBOARD 0x0002
520 #define VFT2_DRV_LANGUAGE 0x0003
521 #define VFT2_DRV_DISPLAY 0x0004
522 #define VFT2_DRV_MOUSE 0x0005
523 #define VFT2_DRV_NETWORK 0x0006
524 #define VFT2_DRV_SYSTEM 0x0007
525 #define VFT2_DRV_INSTALLABLE 0x0008
526 #define VFT2_DRV_SOUND 0x0009
527 #define VFT2_DRV_COMM 0x000a
528 #define VFT2_DRV_INPUTMETHOD 0x000b
529 #define VFT2_FONT_RASTER 0x0001
530 #define VFT2_FONT_VECTOR 0x0002
531 #define VFT2_FONT_TRUETYPE 0x0003
533 #define MAKELANGID(primary,secondary) ((guint16)((secondary << 10) | (primary)))
535 #define ALIGN32(ptr) ptr = (gpointer)((char *)ptr + 3); ptr = (gpointer)((char *)ptr - ((gsize)ptr & 3));
538 static mono_lazy_init_t process_sig_chld_once = MONO_LAZY_INIT_STATUS_NOT_INITIALIZED;
541 static gchar *cli_launcher;
543 /* The signal-safe logic to use processes goes like this:
544 * - The list must be safe to traverse for the signal handler at all times.
545 * It's safe to: prepend an entry (which is a single store to 'processes'),
546 * unlink an entry (assuming the unlinked entry isn't freed and doesn't
547 * change its 'next' pointer so that it can still be traversed).
548 * When cleaning up we first unlink an entry, then we verify that
549 * the read lock isn't locked. Then we can free the entry, since
550 * we know that nobody is using the old version of the list (including
551 * the unlinked entry).
552 * We also need to lock when adding and cleaning up so that those two
553 * operations don't mess with eachother. (This lock is not used in the
555 static Process *processes;
556 static mono_mutex_t processes_mutex;
558 static pid_t current_pid;
559 static gpointer current_process;
561 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
562 static const gunichar2 *utf16_space = utf16_space_bytes;
563 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
564 static const gunichar2 *utf16_quote = utf16_quote_bytes;
567 process_details (gpointer data)
569 MonoW32HandleProcess *process_handle = (MonoW32HandleProcess *) data;
570 g_print ("pid: %d, exited: %s, exitstatus: %d",
571 process_handle->pid, process_handle->exited ? "true" : "false", process_handle->exitstatus);
575 process_typename (void)
581 process_typesize (void)
583 return sizeof (MonoW32HandleProcess);
586 static MonoW32HandleWaitRet
587 process_wait (gpointer handle, guint32 timeout, gboolean *alerted)
589 MonoW32HandleProcess *process_handle;
590 pid_t pid G_GNUC_UNUSED, ret;
596 /* FIXME: We can now easily wait on processes that aren't our own children,
597 * but WaitFor*Object won't call us for pseudo handles. */
598 g_assert (!WAPI_IS_PSEUDO_PROCESS_HANDLE (handle));
600 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u)", __func__, handle, timeout);
605 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
607 g_warning ("%s: error looking up process handle %p", __func__, handle);
608 return MONO_W32HANDLE_WAIT_RET_FAILED;
611 if (process_handle->exited) {
612 /* We've already done this one */
613 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): Process already exited", __func__, handle, timeout);
614 return MONO_W32HANDLE_WAIT_RET_SUCCESS_0;
617 pid = process_handle->pid;
619 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
621 /* We don't need to lock processes here, the entry
622 * has a handle_count > 0 which means it will not be freed. */
623 process = process_handle->process;
627 if (pid == mono_process_current_pid ()) {
628 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on current process", __func__, handle, timeout);
629 return MONO_W32HANDLE_WAIT_RET_TIMEOUT;
632 /* This path is used when calling Process.HasExited, so
633 * it is only used to poll the state of the process, not
634 * to actually wait on it to exit */
635 g_assert (timeout == 0);
637 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on non-child process", __func__, handle, timeout);
639 res = waitpid (pid, &status, WNOHANG);
641 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): non-child process wait timeout", __func__, handle, timeout);
642 return MONO_W32HANDLE_WAIT_RET_TIMEOUT;
645 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): non-child process waited successfully", __func__, handle, timeout);
646 return MONO_W32HANDLE_WAIT_RET_SUCCESS_0;
649 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): non-child process wait failed, error : %s (%d))", __func__, handle, timeout, g_strerror (errno), errno);
650 return MONO_W32HANDLE_WAIT_RET_FAILED;
653 start = mono_msec_ticks ();
657 if (timeout != MONO_INFINITE_WAIT) {
658 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on semaphore for %li ms...",
659 __func__, handle, timeout, (long)(timeout - (now - start)));
660 ret = mono_os_sem_timedwait (&process->exit_sem, (timeout - (now - start)), alerted ? MONO_SEM_FLAGS_ALERTABLE : MONO_SEM_FLAGS_NONE);
662 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on semaphore forever...",
663 __func__, handle, timeout);
664 ret = mono_os_sem_wait (&process->exit_sem, alerted ? MONO_SEM_FLAGS_ALERTABLE : MONO_SEM_FLAGS_NONE);
667 if (ret == MONO_SEM_TIMEDWAIT_RET_SUCCESS) {
668 /* Success, process has exited */
669 mono_os_sem_post (&process->exit_sem);
673 if (ret == MONO_SEM_TIMEDWAIT_RET_TIMEDOUT) {
674 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): wait timeout (timeout = 0)", __func__, handle, timeout);
675 return MONO_W32HANDLE_WAIT_RET_TIMEOUT;
678 now = mono_msec_ticks ();
679 if (now - start >= timeout) {
680 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): wait timeout", __func__, handle, timeout);
681 return MONO_W32HANDLE_WAIT_RET_TIMEOUT;
684 if (alerted && ret == MONO_SEM_TIMEDWAIT_RET_ALERTED) {
685 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): wait alerted", __func__, handle, timeout);
687 return MONO_W32HANDLE_WAIT_RET_ALERTED;
691 /* Process must have exited */
692 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): Waited successfully", __func__, handle, timeout);
694 status = process->status;
695 if (WIFSIGNALED (status))
696 process_handle->exitstatus = 128 + WTERMSIG (status);
698 process_handle->exitstatus = WEXITSTATUS (status);
700 process_handle->exit_time = mono_100ns_datetime ();
702 process_handle->exited = TRUE;
704 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): Setting pid %d signalled, exit status %d",
705 __func__, handle, timeout, process_handle->pid, process_handle->exitstatus);
707 mono_w32handle_set_signal_state (handle, TRUE, TRUE);
709 return MONO_W32HANDLE_WAIT_RET_SUCCESS_0;
713 processes_cleanup (void)
715 static gint32 cleaning_up;
717 Process *prev = NULL;
718 GSList *finished = NULL;
721 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s", __func__);
723 /* Ensure we're not in here in multiple threads at once, nor recursive. */
724 if (InterlockedCompareExchange (&cleaning_up, 1, 0) != 0)
727 for (process = processes; process; process = process->next) {
728 if (process->signalled && process->handle) {
729 /* This process has exited and we need to remove the artifical ref
731 mono_w32handle_unref (process->handle);
732 process->handle = NULL;
737 * Remove processes which exited from the processes list.
738 * We need to synchronize with the sigchld handler here, which runs
739 * asynchronously. The handler requires that the processes list
742 mono_os_mutex_lock (&processes_mutex);
744 for (process = processes; process; process = process->next) {
745 if (process->handle_count == 0 && process->freeable) {
748 * This code can run parallel with the sigchld handler, but the
749 * modifications it makes are safe.
751 if (process == processes)
752 processes = process->next;
754 prev->next = process->next;
755 finished = g_slist_prepend (finished, process);
761 mono_memory_barrier ();
763 for (l = finished; l; l = l->next) {
765 * All the entries in the finished list are unlinked from processes, and
766 * they have the 'finished' flag set, which means the sigchld handler is done
769 process = (Process *)l->data;
770 mono_os_sem_destroy (&process->exit_sem);
773 g_slist_free (finished);
775 mono_os_mutex_unlock (&processes_mutex);
777 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s done", __func__);
779 InterlockedExchange (&cleaning_up, 0);
783 process_close (gpointer handle, gpointer data)
785 MonoW32HandleProcess *process_handle;
787 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s", __func__);
789 process_handle = (MonoW32HandleProcess *) data;
790 g_free (process_handle->pname);
791 process_handle->pname = NULL;
792 if (process_handle->process)
793 InterlockedDecrement (&process_handle->process->handle_count);
794 processes_cleanup ();
797 static MonoW32HandleOps process_ops = {
798 process_close, /* close_shared */
802 process_wait, /* special_wait */
804 process_details, /* details */
805 process_typename, /* typename */
806 process_typesize, /* typesize */
810 process_set_defaults (MonoW32HandleProcess *process_handle)
812 /* These seem to be the defaults on w2k */
813 process_handle->min_working_set = 204800;
814 process_handle->max_working_set = 1413120;
816 process_handle->create_time = mono_100ns_datetime ();
820 process_set_name (MonoW32HandleProcess *process_handle)
822 char *progname, *utf8_progname, *slash;
824 progname = g_get_prgname ();
825 utf8_progname = mono_utf8_from_external (progname);
827 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: using [%s] as prog name", __func__, progname);
830 slash = strrchr (utf8_progname, '/');
832 process_handle->pname = g_strdup (slash+1);
834 process_handle->pname = g_strdup (utf8_progname);
835 g_free (utf8_progname);
840 mono_w32process_init (void)
842 MonoW32HandleProcess process_handle;
844 mono_w32handle_register_ops (MONO_W32HANDLE_PROCESS, &process_ops);
846 mono_w32handle_register_capabilities (MONO_W32HANDLE_PROCESS,
847 (MonoW32HandleCapability)(MONO_W32HANDLE_CAP_WAIT | MONO_W32HANDLE_CAP_SPECIAL_WAIT));
849 current_pid = getpid ();
851 memset (&process_handle, 0, sizeof (process_handle));
852 process_handle.pid = current_pid;
853 process_set_defaults (&process_handle);
854 process_set_name (&process_handle);
856 current_process = mono_w32handle_new (MONO_W32HANDLE_PROCESS, &process_handle);
857 g_assert (current_process);
859 mono_os_mutex_init (&processes_mutex);
863 mono_w32process_cleanup (void)
865 g_free (cli_launcher);
868 /* Check if a pid is valid - i.e. if a process exists with this pid. */
870 is_pid_valid (pid_t pid)
872 gboolean result = FALSE;
874 #if defined(HOST_WATCHOS)
875 result = TRUE; // TODO: Rewrite using sysctl
876 #elif defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__)
877 if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
879 #elif defined(__HAIKU__)
881 if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
884 char *dir = g_strdup_printf ("/proc/%d", pid);
885 if (!access (dir, F_OK))
894 len16 (const gunichar2 *str)
905 utf16_concat (const gunichar2 *first, ...)
913 va_start (args, first);
914 total += len16 (first);
915 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *))
919 ret = g_new (gunichar2, total + 1);
925 for (s = first; *s != 0; s++)
927 va_start (args, first);
928 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
929 for (p = s; *p != 0; p++)
938 mono_w32process_get_pid (gpointer handle)
940 MonoW32HandleProcess *process_handle;
943 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle)) {
944 /* This is a pseudo handle */
945 return WAPI_HANDLE_TO_PID (handle);
948 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
950 mono_w32error_set_last (ERROR_INVALID_HANDLE);
954 return process_handle->pid;
960 } GetProcessForeachData;
963 get_process_foreach_callback (gpointer handle, gpointer handle_specific, gpointer user_data)
965 GetProcessForeachData *foreach_data;
966 MonoW32HandleProcess *process_handle;
969 foreach_data = (GetProcessForeachData*) user_data;
971 if (mono_w32handle_get_type (handle) != MONO_W32HANDLE_PROCESS)
974 g_assert (!WAPI_IS_PSEUDO_PROCESS_HANDLE (handle));
976 process_handle = (MonoW32HandleProcess*) handle_specific;
978 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking at process %d", __func__, process_handle->pid);
980 pid = process_handle->pid;
984 /* It's possible to have more than one process handle with the
985 * same pid, but only the one running process can be
987 if (foreach_data->pid != pid)
989 if (mono_w32handle_issignalled (handle))
992 mono_w32handle_ref (handle);
993 foreach_data->handle = handle;
998 ves_icall_System_Diagnostics_Process_GetProcess_internal (guint32 pid)
1000 GetProcessForeachData foreach_data;
1003 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking for process %d", __func__, pid);
1005 memset (&foreach_data, 0, sizeof (foreach_data));
1006 foreach_data.pid = pid;
1007 mono_w32handle_foreach (get_process_foreach_callback, &foreach_data);
1008 handle = foreach_data.handle;
1010 /* get_process_foreach_callback already added a ref */
1014 if (is_pid_valid (pid)) {
1015 /* Return a pseudo handle for processes we don't have handles for */
1016 return WAPI_PID_TO_HANDLE (pid);
1019 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find pid %d", __func__, pid);
1021 mono_w32error_set_last (ERROR_PROC_NOT_FOUND);
1026 match_procname_to_modulename (char *procname, char *modulename)
1028 char* lastsep = NULL;
1029 char* lastsep2 = NULL;
1032 gboolean result = FALSE;
1034 if (procname == NULL || modulename == NULL)
1037 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: procname=\"%s\", modulename=\"%s\"", __func__, procname, modulename);
1038 pname = mono_path_resolve_symlinks (procname);
1039 mname = mono_path_resolve_symlinks (modulename);
1041 if (!strcmp (pname, mname))
1045 lastsep = strrchr (mname, '/');
1047 if (!strcmp (lastsep+1, pname))
1050 lastsep2 = strrchr (pname, '/');
1053 if (!strcmp (lastsep+1, lastsep2+1))
1056 if (!strcmp (mname, lastsep2+1))
1066 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: result is %d", __func__, result);
1071 mono_w32process_try_get_modules (gpointer process, gpointer *modules, guint32 size, guint32 *needed)
1073 MonoW32HandleProcess *process_handle;
1074 GSList *mods = NULL, *mods_iter;
1075 MonoW32ProcessModule *module;
1076 guint32 count, avail = size / sizeof(gpointer);
1082 /* Store modules in an array of pointers (main module as
1083 * modules[0]), using the load address for each module as a
1084 * token. (Use 'NULL' as an alternative for the main module
1085 * so that the simple implementation can just return one item
1086 * for now.) Get the info from /proc/<pid>/maps on linux,
1087 * /proc/<pid>/map on FreeBSD, other systems will have to
1088 * implement /dev/kmem reading or whatever other horrid
1089 * technique is needed.
1091 if (size < sizeof(gpointer))
1094 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1095 pid = WAPI_HANDLE_TO_PID (process);
1096 pname = mono_w32process_get_name (pid);
1098 res = mono_w32handle_lookup (process, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
1100 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
1104 pid = process_handle->pid;
1105 pname = g_strdup (process_handle->pname);
1110 *needed = sizeof(gpointer);
1114 mods = mono_w32process_get_modules (pid);
1117 *needed = sizeof(gpointer);
1125 * Use the NULL shortcut, as the first line in
1126 * /proc/<pid>/maps isn't the executable, and we need
1127 * that first in the returned list. Check the module name
1128 * to see if it ends with the proc name and substitute
1129 * the first entry with it. FIXME if this turns out to
1134 for (i = 0; mods_iter; i++) {
1135 if (i < avail - 1) {
1136 module = (MonoW32ProcessModule *)mods_iter->data;
1137 if (modules[0] != NULL)
1138 modules[i] = module->address_start;
1139 else if (match_procname_to_modulename (pname, module->filename))
1140 modules[0] = module->address_start;
1142 modules[i + 1] = module->address_start;
1144 mono_w32process_module_free ((MonoW32ProcessModule *)mods_iter->data);
1145 mods_iter = g_slist_next (mods_iter);
1149 /* count + 1 to leave slot 0 for the main module */
1150 *needed = sizeof(gpointer) * (count + 1);
1152 g_slist_free (mods);
1159 mono_w32process_module_get_filename (gpointer process, gpointer module, gunichar2 *basename, guint32 size)
1164 gunichar2 *proc_path;
1166 size *= sizeof (gunichar2); /* adjust for unicode characters */
1168 if (basename == NULL || size == 0)
1171 pid = mono_w32process_get_pid (process);
1173 path = mono_w32process_get_path (pid);
1177 proc_path = mono_unicode_from_external (path, &bytes);
1180 if (proc_path == NULL)
1185 /* Add the terminator */
1189 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
1190 memcpy (basename, proc_path, size);
1192 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %d larger than needed (%ld)", __func__, size, bytes);
1193 memcpy (basename, proc_path, bytes);
1202 mono_w32process_module_get_name (gpointer process, gpointer module, gunichar2 *basename, guint32 size)
1204 MonoW32HandleProcess *process_handle;
1206 gunichar2 *procname;
1207 char *procname_ext = NULL;
1210 GSList *mods = NULL, *mods_iter;
1211 MonoW32ProcessModule *found_module;
1215 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Getting module base name, process handle %p module %p",
1216 __func__, process, module);
1218 size = size * sizeof (gunichar2); /* adjust for unicode characters */
1220 if (basename == NULL || size == 0)
1223 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1224 /* This is a pseudo handle */
1225 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
1226 pname = mono_w32process_get_name (pid);
1228 res = mono_w32handle_lookup (process, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
1230 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
1234 pid = process_handle->pid;
1235 pname = g_strdup (process_handle->pname);
1238 mods = mono_w32process_get_modules (pid);
1244 /* If module != NULL compare the address.
1245 * If module == NULL we are looking for the main module.
1246 * The best we can do for now check it the module name end with the process name.
1248 for (mods_iter = mods; mods_iter; mods_iter = g_slist_next (mods_iter)) {
1249 found_module = (MonoW32ProcessModule *)mods_iter->data;
1250 if (procname_ext == NULL &&
1251 ((module == NULL && match_procname_to_modulename (pname, found_module->filename)) ||
1252 (module != NULL && found_module->address_start == module))) {
1253 procname_ext = g_path_get_basename (found_module->filename);
1256 mono_w32process_module_free (found_module);
1259 if (procname_ext == NULL) {
1260 /* If it's *still* null, we might have hit the
1261 * case where reading /proc/$pid/maps gives an
1262 * empty file for this user.
1264 procname_ext = mono_w32process_get_name (pid);
1267 g_slist_free (mods);
1271 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Process name is [%s]", __func__,
1274 procname = mono_unicode_from_external (procname_ext, &bytes);
1275 if (procname == NULL) {
1277 g_free (procname_ext);
1283 /* Add the terminator */
1287 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
1289 memcpy (basename, procname, size);
1291 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %d larger than needed (%ld)",
1292 __func__, size, bytes);
1294 memcpy (basename, procname, bytes);
1298 g_free (procname_ext);
1307 mono_w32process_module_get_information (gpointer process, gpointer module, MODULEINFO *modinfo, guint32 size)
1309 MonoW32HandleProcess *process_handle;
1311 GSList *mods = NULL, *mods_iter;
1312 MonoW32ProcessModule *found_module;
1313 gboolean ret = FALSE;
1317 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Getting module info, process handle %p module %p",
1318 __func__, process, module);
1320 if (modinfo == NULL || size < sizeof (MODULEINFO))
1323 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1324 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
1325 pname = mono_w32process_get_name (pid);
1327 res = mono_w32handle_lookup (process, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
1329 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
1333 pid = process_handle->pid;
1334 pname = g_strdup (process_handle->pname);
1337 mods = mono_w32process_get_modules (pid);
1343 /* If module != NULL compare the address.
1344 * If module == NULL we are looking for the main module.
1345 * The best we can do for now check it the module name end with the process name.
1347 for (mods_iter = mods; mods_iter; mods_iter = g_slist_next (mods_iter)) {
1348 found_module = (MonoW32ProcessModule *)mods_iter->data;
1350 ((module == NULL && match_procname_to_modulename (pname, found_module->filename)) ||
1351 (module != NULL && found_module->address_start == module))) {
1352 modinfo->lpBaseOfDll = found_module->address_start;
1353 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
1354 modinfo->EntryPoint = found_module->address_offset;
1358 mono_w32process_module_free (found_module);
1361 g_slist_free (mods);
1368 switch_dir_separators (char *path)
1370 size_t i, pathLength = strlen(path);
1372 /* Turn all the slashes round the right way, except for \' */
1373 /* There are probably other characters that need to be excluded as well. */
1374 for (i = 0; i < pathLength; i++) {
1375 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' )
1382 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
1390 pid = waitpid (-1, &status, WNOHANG);
1391 } while (pid == -1 && errno == EINTR);
1397 * This can run concurrently with the code in the rest of this module.
1399 for (process = processes; process; process = process->next) {
1400 if (process->pid != pid)
1402 if (process->signalled)
1405 process->signalled = TRUE;
1406 process->status = status;
1407 mono_os_sem_post (&process->exit_sem);
1408 mono_memory_barrier ();
1409 /* Mark this as freeable, the pointer becomes invalid afterwards */
1410 process->freeable = TRUE;
1417 process_add_sigchld_handler (void)
1419 struct sigaction sa;
1421 sa.sa_sigaction = mono_sigchld_signal_handler;
1422 sigemptyset (&sa.sa_mask);
1423 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
1424 g_assert (sigaction (SIGCHLD, &sa, NULL) != -1);
1425 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "Added SIGCHLD handler");
1431 is_readable_or_executable (const char *prog)
1434 int a = access (prog, R_OK);
1435 int b = access (prog, X_OK);
1436 if (a != 0 && b != 0)
1438 if (stat (prog, &buf))
1440 if (S_ISREG (buf.st_mode))
1446 is_executable (const char *prog)
1449 if (access (prog, X_OK) != 0)
1451 if (stat (prog, &buf))
1453 if (S_ISREG (buf.st_mode))
1459 is_managed_binary (const char *filename)
1461 int original_errno = errno;
1462 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
1463 int file = open (filename, O_RDONLY | O_LARGEFILE);
1465 int file = open (filename, O_RDONLY);
1468 unsigned char buffer[8];
1469 off_t file_size, optional_header_offset;
1470 off_t pe_header_offset, clr_header_offset;
1471 gboolean managed = FALSE;
1473 guint32 first_word, second_word, magic_number;
1475 /* If we are unable to open the file, then we definitely
1476 * can't say that it is managed. The child mono process
1477 * probably wouldn't be able to open it anyway.
1480 errno = original_errno;
1484 /* Retrieve the length of the file for future sanity checks. */
1485 file_size = lseek (file, 0, SEEK_END);
1486 lseek (file, 0, SEEK_SET);
1488 /* We know we need to read a header field at offset 60. */
1492 num_read = read (file, buffer, 2);
1494 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
1497 new_offset = lseek (file, 60, SEEK_SET);
1499 if (new_offset != 60)
1502 num_read = read (file, buffer, 4);
1506 pe_header_offset = buffer[0]
1509 | (buffer[3] << 24);
1511 if (pe_header_offset + 24 > file_size)
1514 new_offset = lseek (file, pe_header_offset, SEEK_SET);
1516 if (new_offset != pe_header_offset)
1519 num_read = read (file, buffer, 4);
1521 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
1525 * Verify that the header we want in the optional header data
1526 * is present in this binary.
1528 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
1530 if (new_offset != pe_header_offset + 20)
1533 num_read = read (file, buffer, 2);
1535 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
1538 optional_header_offset = pe_header_offset + 24;
1540 /* Read the PE magic number */
1541 new_offset = lseek (file, optional_header_offset, SEEK_SET);
1543 if (new_offset != optional_header_offset)
1546 num_read = read (file, buffer, 2);
1551 magic_number = (buffer[0] | (buffer[1] << 8));
1553 if (magic_number == 0x10B) // PE32
1554 clr_header_offset = 208;
1555 else if (magic_number == 0x20B) // PE32+
1556 clr_header_offset = 224;
1560 /* Read the CLR header address and size fields. These will be
1561 * zero if the binary is not managed.
1563 new_offset = lseek (file, optional_header_offset + clr_header_offset, SEEK_SET);
1565 if (new_offset != optional_header_offset + clr_header_offset)
1568 num_read = read (file, buffer, 8);
1570 /* We are not concerned with endianness, only with
1571 * whether it is zero or not.
1573 first_word = *(guint32 *)&buffer[0];
1574 second_word = *(guint32 *)&buffer[4];
1576 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
1583 errno = original_errno;
1588 process_create (const gunichar2 *appname, const gunichar2 *cmdline,
1589 const gunichar2 *cwd, StartupHandles *startup_handles, MonoW32ProcessInfo *process_info)
1591 #if defined (HAVE_FORK) && defined (HAVE_EXECVE)
1592 char *cmd = NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL;
1593 char *dir = NULL, **env_strings = NULL, **argv = NULL;
1595 gboolean ret = FALSE;
1596 gpointer handle = NULL;
1597 GError *gerr = NULL;
1598 int in_fd, out_fd, err_fd;
1600 int startup_pipe [2] = {-1, -1};
1605 mono_lazy_initialize (&process_sig_chld_once, process_add_sigchld_handler);
1608 /* appname and cmdline specify the executable and its args:
1610 * If appname is not NULL, it is the name of the executable.
1611 * Otherwise the executable is the first token in cmdline.
1613 * Executable searching:
1615 * If appname is not NULL, it can specify the full path and
1616 * file name, or else a partial name and the current directory
1617 * will be used. There is no additional searching.
1619 * If appname is NULL, the first whitespace-delimited token in
1620 * cmdline is used. If the name does not contain a full
1621 * directory path, the search sequence is:
1623 * 1) The directory containing the current process
1624 * 2) The current working directory
1625 * 3) The windows system directory (Ignored)
1626 * 4) The windows directory (Ignored)
1629 * Just to make things more interesting, tokens can contain
1630 * white space if they are surrounded by quotation marks. I'm
1631 * beginning to understand just why windows apps are generally
1632 * so crap, with an API like this :-(
1634 if (appname != NULL) {
1635 cmd = mono_unicode_to_external (appname);
1637 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL",
1640 mono_w32error_set_last (ERROR_PATH_NOT_FOUND);
1644 switch_dir_separators(cmd);
1647 if (cmdline != NULL) {
1648 args = mono_unicode_to_external (cmdline);
1650 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1652 mono_w32error_set_last (ERROR_PATH_NOT_FOUND);
1658 dir = mono_unicode_to_external (cwd);
1660 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1662 mono_w32error_set_last (ERROR_PATH_NOT_FOUND);
1666 /* Turn all the slashes round the right way */
1667 switch_dir_separators(dir);
1671 /* We can't put off locating the executable any longer :-( */
1674 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
1675 /* Strip off the drive letter. I can't
1676 * believe that CP/M holdover is still
1679 g_memmove (cmd, cmd+2, strlen (cmd)-2);
1680 cmd[strlen (cmd)-2] = '\0';
1683 unquoted = g_shell_unquote (cmd, NULL);
1684 if (unquoted[0] == '/') {
1685 /* Assume full path given */
1686 prog = g_strdup (unquoted);
1688 /* Executable existing ? */
1689 if (!is_readable_or_executable (prog)) {
1690 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s",
1693 mono_w32error_set_last (ERROR_FILE_NOT_FOUND);
1697 /* Search for file named by cmd in the current
1700 char *curdir = g_get_current_dir ();
1702 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
1705 /* And make sure it's readable */
1706 if (!is_readable_or_executable (prog)) {
1707 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s",
1710 mono_w32error_set_last (ERROR_FILE_NOT_FOUND);
1716 args_after_prog = args;
1721 /* Dig out the first token from args, taking quotation
1722 * marks into account
1725 /* First, strip off all leading whitespace */
1726 args = g_strchug (args);
1728 /* args_after_prog points to the contents of args
1729 * after token has been set (otherwise argv[0] is
1732 args_after_prog = args;
1734 /* Assume the opening quote will always be the first
1737 if (args[0] == '\"' || args [0] == '\'') {
1739 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
1740 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
1741 /* We found the first token */
1742 token = g_strndup (args+1, i-1);
1743 args_after_prog = g_strchug (args + i + 1);
1745 /* Quotation mark appeared in the
1746 * middle of the token. Just give the
1747 * whole first token, quotes and all,
1753 if (token == NULL) {
1754 /* No quote mark, or malformed */
1755 for (i = 0; args[i] != '\0'; i++) {
1756 if (g_ascii_isspace (args[i])) {
1757 token = g_strndup (args, i);
1758 args_after_prog = args + i + 1;
1764 if (token == NULL && args[0] != '\0') {
1765 /* Must be just one token in the string */
1766 token = g_strdup (args);
1767 args_after_prog = NULL;
1770 if (token == NULL) {
1772 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find what to exec", __func__);
1774 mono_w32error_set_last (ERROR_PATH_NOT_FOUND);
1778 /* Turn all the slashes round the right way. Only for
1781 switch_dir_separators(token);
1783 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
1784 /* Strip off the drive letter. I can't
1785 * believe that CP/M holdover is still
1788 g_memmove (token, token+2, strlen (token)-2);
1789 token[strlen (token)-2] = '\0';
1792 if (token[0] == '/') {
1793 /* Assume full path given */
1794 prog = g_strdup (token);
1796 /* Executable existing ? */
1797 if (!is_readable_or_executable (prog)) {
1798 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s",
1801 mono_w32error_set_last (ERROR_FILE_NOT_FOUND);
1805 char *curdir = g_get_current_dir ();
1807 /* FIXME: Need to record the directory
1808 * containing the current process, and check
1809 * that for the new executable as the first
1813 prog = g_strdup_printf ("%s/%s", curdir, token);
1816 /* I assume X_OK is the criterion to use,
1819 * X_OK is too strict *if* the target is a CLR binary
1821 if (!is_readable_or_executable (prog)) {
1823 prog = g_find_program_in_path (token);
1825 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s", __func__, token);
1828 mono_w32error_set_last (ERROR_FILE_NOT_FOUND);
1837 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Exec prog [%s] args [%s]",
1838 __func__, prog, args_after_prog);
1840 /* Check for CLR binaries; if found, we will try to invoke
1841 * them using the same mono binary that started us.
1843 if (is_managed_binary (prog)) {
1844 gunichar2 *newapp, *newcmd;
1845 gsize bytes_ignored;
1847 newapp = mono_unicode_from_external (cli_launcher ? cli_launcher : "mono", &bytes_ignored);
1850 newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space, appname, utf16_space, cmdline, NULL);
1852 newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space, cmdline, NULL);
1857 ret = process_create (NULL, newcmd, cwd, startup_handles, process_info);
1865 if (!is_executable (prog)) {
1866 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Executable permisson not set on %s", __func__, prog);
1867 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1872 if (args_after_prog != NULL && *args_after_prog) {
1875 qprog = g_shell_quote (prog);
1876 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
1879 full_prog = g_shell_quote (prog);
1882 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
1884 g_message ("process_create: %s\n", gerr->message);
1885 g_error_free (gerr);
1890 if (startup_handles) {
1891 in_fd = GPOINTER_TO_UINT (startup_handles->input);
1892 out_fd = GPOINTER_TO_UINT (startup_handles->output);
1893 err_fd = GPOINTER_TO_UINT (startup_handles->error);
1895 in_fd = GPOINTER_TO_UINT (mono_w32file_get_console_input ());
1896 out_fd = GPOINTER_TO_UINT (mono_w32file_get_console_output ());
1897 err_fd = GPOINTER_TO_UINT (mono_w32file_get_console_error ());
1901 * process->env_variables is a an array of MonoString*
1903 * If new_environ is not NULL it specifies the entire set of
1904 * environment variables in the new process. Otherwise the
1905 * new process inherits the same environment.
1907 if (process_info->env_variables) {
1908 gint i, str_length, var_length;
1912 /* +2: one for the process handle value, and the last one is NULL */
1913 env_strings = g_new0 (gchar*, mono_array_length (process_info->env_variables) + 2);
1918 /* Copy each environ string into 'strings' turning it into utf8 (or the requested encoding) at the same time */
1919 for (i = 0; i < mono_array_length (process_info->env_variables); ++i) {
1920 var = mono_array_get (process_info->env_variables, MonoString*, i);
1921 var_length = mono_string_length (var);
1923 /* str is a null-terminated copy of var */
1925 if (var_length + 1 > str_length) {
1926 str_length = var_length + 1;
1927 str = g_renew (gunichar2, str, str_length);
1930 memcpy (str, mono_string_chars (var), var_length * sizeof (gunichar2));
1931 str [var_length] = '\0';
1933 env_strings [i] = mono_unicode_to_external (str);
1941 for (i = 0; environ[i] != NULL; i++)
1944 /* +2: one for the process handle value, and the last one is NULL */
1945 env_strings = g_new0 (gchar*, env_count + 2);
1947 /* Copy each environ string into 'strings' turning it into utf8 (or the requested encoding) at the same time */
1948 for (i = 0; i < env_count; i++)
1949 env_strings [i] = g_strdup (environ[i]);
1952 /* Create a pipe to make sure the child doesn't exit before
1953 * we can add the process to the linked list of processes */
1954 if (pipe (startup_pipe) == -1) {
1955 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
1956 * This is just for a very hard to hit race condition in the first place */
1957 startup_pipe [0] = startup_pipe [1] = -1;
1958 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
1961 switch (pid = fork ()) {
1962 case -1: /* Error */ {
1963 mono_w32error_set_last (ERROR_OUTOFMEMORY);
1967 case 0: /* Child */ {
1968 if (startup_pipe [0] != -1) {
1969 /* Wait until the parent has updated it's internal data */
1970 ssize_t _i G_GNUC_UNUSED = read (startup_pipe [0], &dummy, 1);
1971 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: child: parent has completed its setup", __func__);
1972 close (startup_pipe [0]);
1973 close (startup_pipe [1]);
1976 /* should we detach from the process group? */
1978 /* Connect stdin, stdout and stderr */
1983 /* Close all file descriptors */
1984 for (i = mono_w32handle_fd_reserve - 1; i > 2; i--)
1987 #ifdef DEBUG_ENABLED
1988 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1989 dir == NULL?".":dir);
1990 for (i = 0; argv[i] != NULL; i++)
1991 g_message ("arg %d: [%s]", i, argv[i]);
1993 for (i = 0; env_strings[i] != NULL; i++)
1994 g_message ("env %d: [%s]", i, env_strings[i]);
1998 if (dir != NULL && chdir (dir) == -1) {
2004 execve (argv[0], argv, env_strings);
2011 default: /* Parent */ {
2012 MonoW32HandleProcess process_handle;
2014 memset (&process_handle, 0, sizeof (process_handle));
2015 process_handle.pid = pid;
2016 process_handle.pname = g_strdup (prog);
2017 process_set_defaults (&process_handle);
2019 /* Add our process into the linked list of processes */
2020 process = (Process *) g_malloc0 (sizeof (Process));
2022 process->handle_count = 1;
2023 mono_os_sem_init (&process->exit_sem, 0);
2025 process_handle.process = process;
2027 handle = mono_w32handle_new (MONO_W32HANDLE_PROCESS, &process_handle);
2028 if (handle == INVALID_HANDLE_VALUE) {
2029 g_warning ("%s: error creating process handle", __func__);
2031 mono_os_sem_destroy (&process->exit_sem);
2034 mono_w32error_set_last (ERROR_OUTOFMEMORY);
2039 /* Keep the process handle artificially alive until the process
2040 * exits so that the information in the handle isn't lost. */
2041 mono_w32handle_ref (handle);
2042 process->handle = handle;
2044 mono_os_mutex_lock (&processes_mutex);
2045 process->next = processes;
2046 mono_memory_barrier ();
2047 processes = process;
2048 mono_os_mutex_unlock (&processes_mutex);
2050 if (process_info != NULL) {
2051 process_info->process_handle = handle;
2052 process_info->pid = pid;
2054 /* FIXME: we might need to handle the thread info some day */
2055 process_info->thread_handle = INVALID_HANDLE_VALUE;
2056 process_info->tid = 0;
2063 if (startup_pipe [1] != -1) {
2064 /* Write 1 byte, doesn't matter what */
2065 ssize_t _i G_GNUC_UNUSED = write (startup_pipe [1], startup_pipe, 1);
2066 close (startup_pipe [0]);
2067 close (startup_pipe [1]);
2082 g_strfreev (env_strings);
2086 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: returning handle %p for pid %d", __func__, handle, pid);
2088 /* Check if something needs to be cleaned up. */
2089 processes_cleanup ();
2093 mono_w32error_set_last (ERROR_NOT_SUPPORTED);
2095 #endif // defined (HAVE_FORK) && defined (HAVE_EXECVE)
2099 ves_icall_System_Diagnostics_Process_ShellExecuteEx_internal (MonoW32ProcessStartInfo *proc_start_info, MonoW32ProcessInfo *process_info)
2101 const gunichar2 *lpFile;
2102 const gunichar2 *lpParameters;
2103 const gunichar2 *lpDirectory;
2107 if (!proc_start_info->filename) {
2108 /* w2k returns TRUE for this, for some reason. */
2113 lpFile = proc_start_info->filename ? mono_string_chars (proc_start_info->filename) : NULL;
2114 lpParameters = proc_start_info->arguments ? mono_string_chars (proc_start_info->arguments) : NULL;
2115 lpDirectory = proc_start_info->working_directory && mono_string_length (proc_start_info->working_directory) != 0 ?
2116 mono_string_chars (proc_start_info->working_directory) : NULL;
2118 /* Put both executable and parameters into the second argument
2119 * to process_create (), so it searches $PATH. The conversion
2120 * into and back out of utf8 is because there is no
2121 * g_strdup_printf () equivalent for gunichar2 :-(
2123 args = utf16_concat (utf16_quote, lpFile, utf16_quote, lpParameters == NULL ? NULL : utf16_space, lpParameters, NULL);
2125 mono_w32error_set_last (ERROR_INVALID_DATA);
2129 ret = process_create (NULL, args, lpDirectory, NULL, process_info);
2132 if (!ret && mono_w32error_get_last () == ERROR_OUTOFMEMORY)
2136 static char *handler;
2137 static gunichar2 *handler_utf16;
2139 if (handler_utf16 == (gunichar2 *)-1) {
2144 #ifdef PLATFORM_MACOSX
2145 handler = g_strdup ("/usr/bin/open");
2148 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
2149 * if that fails, try to use gnome-open, then kfmclient
2151 handler = g_find_program_in_path ("xdg-open");
2152 if (handler == NULL){
2153 handler = g_find_program_in_path ("gnome-open");
2154 if (handler == NULL){
2155 handler = g_find_program_in_path ("kfmclient");
2156 if (handler == NULL){
2157 handler_utf16 = (gunichar2 *) -1;
2161 /* kfmclient needs exec argument */
2162 char *old = handler;
2163 handler = g_strconcat (old, " exec",
2170 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
2173 /* Put quotes around the filename, in case it's a url
2174 * that contains #'s (process_create() calls
2175 * g_shell_parse_argv(), which deliberately throws
2176 * away anything after an unquoted #). Fixes bug
2179 args = utf16_concat (handler_utf16, utf16_space, utf16_quote, lpFile, utf16_quote,
2180 lpParameters == NULL ? NULL : utf16_space, lpParameters, NULL);
2182 mono_w32error_set_last (ERROR_INVALID_DATA);
2186 ret = process_create (NULL, args, lpDirectory, NULL, process_info);
2189 if (mono_w32error_get_last () != ERROR_OUTOFMEMORY)
2190 mono_w32error_set_last (ERROR_INVALID_DATA);
2194 /* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
2195 mono_w32handle_close (process_info->process_handle);
2196 process_info->process_handle = NULL;
2201 process_info->pid = -mono_w32error_get_last ();
2203 process_info->thread_handle = NULL;
2204 #if !defined(MONO_CROSS_COMPILE)
2205 process_info->pid = mono_w32process_get_pid (process_info->process_handle);
2207 process_info->pid = 0;
2209 process_info->tid = 0;
2215 /* Only used when UseShellExecute is false */
2217 process_get_complete_path (const gunichar2 *appname, gchar **completed)
2222 utf8app = g_utf16_to_utf8 (appname, -1, NULL, NULL, NULL);
2224 if (g_path_is_absolute (utf8app)) {
2225 *completed = g_shell_quote (utf8app);
2230 if (g_file_test (utf8app, G_FILE_TEST_IS_EXECUTABLE) && !g_file_test (utf8app, G_FILE_TEST_IS_DIR)) {
2231 *completed = g_shell_quote (utf8app);
2236 found = g_find_program_in_path (utf8app);
2237 if (found == NULL) {
2243 *completed = g_shell_quote (found);
2250 process_get_shell_arguments (MonoW32ProcessStartInfo *proc_start_info, gunichar2 **shell_path)
2252 gchar *complete_path = NULL;
2256 if (process_get_complete_path (mono_string_chars (proc_start_info->filename), &complete_path)) {
2257 *shell_path = g_utf8_to_utf16 (complete_path, -1, NULL, NULL, NULL);
2258 g_free (complete_path);
2261 return *shell_path != NULL;
2265 ves_icall_System_Diagnostics_Process_CreateProcess_internal (MonoW32ProcessStartInfo *proc_start_info,
2266 HANDLE stdin_handle, HANDLE stdout_handle, HANDLE stderr_handle, MonoW32ProcessInfo *process_info)
2270 StartupHandles startup_handles;
2271 gunichar2 *shell_path = NULL;
2272 gunichar2 *args = NULL;
2274 memset (&startup_handles, 0, sizeof (startup_handles));
2275 startup_handles.input = stdin_handle;
2276 startup_handles.output = stdout_handle;
2277 startup_handles.error = stderr_handle;
2279 if (!process_get_shell_arguments (proc_start_info, &shell_path)) {
2280 process_info->pid = -ERROR_FILE_NOT_FOUND;
2284 args = proc_start_info->arguments && mono_string_length (proc_start_info->arguments) > 0 ?
2285 mono_string_chars (proc_start_info->arguments): NULL;
2287 /* The default dir name is "". Turn that into NULL to mean "current directory" */
2288 dir = proc_start_info->working_directory && mono_string_length (proc_start_info->working_directory) > 0 ?
2289 mono_string_chars (proc_start_info->working_directory) : NULL;
2291 ret = process_create (shell_path, args, dir, &startup_handles, process_info);
2293 if (shell_path != NULL)
2294 g_free (shell_path);
2297 process_info->pid = -mono_w32error_get_last ();
2302 /* Returns an array of pids */
2304 ves_icall_System_Diagnostics_Process_GetProcesses_internal (void)
2311 pidarray = mono_process_list (&count);
2313 mono_set_pending_exception (mono_get_exception_not_supported ("This system does not support EnumProcesses"));
2316 procs = mono_array_new_checked (mono_domain_get (), mono_get_int32_class (), count, &error);
2317 if (mono_error_set_pending_exception (&error)) {
2321 if (sizeof (guint32) == sizeof (gpointer)) {
2322 memcpy (mono_array_addr (procs, guint32, 0), pidarray, count * sizeof (gint32));
2324 for (i = 0; i < count; ++i)
2325 *(mono_array_addr (procs, guint32, i)) = GPOINTER_TO_UINT (pidarray [i]);
2333 mono_w32process_set_cli_launcher (gchar *path)
2335 g_free (cli_launcher);
2336 cli_launcher = g_strdup (path);
2340 ves_icall_Microsoft_Win32_NativeMethods_GetCurrentProcess (void)
2342 mono_w32handle_ref (current_process);
2343 return current_process;
2347 ves_icall_Microsoft_Win32_NativeMethods_GetExitCodeProcess (gpointer handle, gint32 *exitcode)
2349 MonoW32HandleProcess *process_handle;
2356 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle)) {
2357 pid = WAPI_HANDLE_TO_PID (handle);
2358 /* This is a pseudo handle, so we don't know what the exit
2359 * code was, but we can check whether it's alive or not */
2360 if (is_pid_valid (pid)) {
2361 *exitcode = STILL_ACTIVE;
2369 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2371 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2375 if (process_handle->pid == current_pid) {
2376 *exitcode = STILL_ACTIVE;
2380 /* A process handle is only signalled if the process has exited
2381 * and has been waited for. Make sure any process exit has been
2382 * noticed before checking if the process is signalled.
2383 * Fixes bug 325463. */
2384 mono_w32handle_wait_one (handle, 0, TRUE);
2386 *exitcode = mono_w32handle_issignalled (handle) ? process_handle->exitstatus : STILL_ACTIVE;
2391 ves_icall_Microsoft_Win32_NativeMethods_CloseProcess (gpointer handle)
2393 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
2395 return mono_w32handle_close (handle);
2399 ves_icall_Microsoft_Win32_NativeMethods_TerminateProcess (gpointer handle, gint32 exitcode)
2402 MonoW32HandleProcess *process_handle;
2406 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle)) {
2407 /* This is a pseudo handle */
2408 pid = (pid_t)WAPI_HANDLE_TO_PID (handle);
2412 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2414 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2415 mono_w32error_set_last (ERROR_INVALID_HANDLE);
2419 pid = process_handle->pid;
2422 ret = kill (pid, exitcode == -1 ? SIGKILL : SIGTERM);
2427 case EINVAL: mono_w32error_set_last (ERROR_INVALID_PARAMETER); break;
2428 case EPERM: mono_w32error_set_last (ERROR_ACCESS_DENIED); break;
2429 case ESRCH: mono_w32error_set_last (ERROR_PROC_NOT_FOUND); break;
2430 default: mono_w32error_set_last (ERROR_GEN_FAILURE); break;
2435 g_error ("kill() is not supported by this platform");
2440 ves_icall_Microsoft_Win32_NativeMethods_GetProcessWorkingSetSize (gpointer handle, gsize *min, gsize *max)
2442 MonoW32HandleProcess *process_handle;
2448 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
2451 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2453 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2457 *min = process_handle->min_working_set;
2458 *max = process_handle->max_working_set;
2463 ves_icall_Microsoft_Win32_NativeMethods_SetProcessWorkingSetSize (gpointer handle, gsize min, gsize max)
2465 MonoW32HandleProcess *process_handle;
2468 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
2471 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2473 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2477 process_handle->min_working_set = min;
2478 process_handle->max_working_set = max;
2483 ves_icall_Microsoft_Win32_NativeMethods_GetPriorityClass (gpointer handle)
2485 #ifdef HAVE_GETPRIORITY
2486 MonoW32HandleProcess *process_handle;
2490 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle)) {
2491 /* This is a pseudo handle */
2492 pid = (pid_t)WAPI_HANDLE_TO_PID (handle);
2496 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2498 mono_w32error_set_last (ERROR_INVALID_HANDLE);
2502 pid = process_handle->pid;
2506 ret = getpriority (PRIO_PROCESS, pid);
2507 if (ret == -1 && errno != 0) {
2511 mono_w32error_set_last (ERROR_ACCESS_DENIED);
2514 mono_w32error_set_last (ERROR_PROC_NOT_FOUND);
2517 mono_w32error_set_last (ERROR_GEN_FAILURE);
2523 return MONO_W32PROCESS_PRIORITY_CLASS_NORMAL;
2525 return MONO_W32PROCESS_PRIORITY_CLASS_REALTIME;
2527 return MONO_W32PROCESS_PRIORITY_CLASS_HIGH;
2529 return MONO_W32PROCESS_PRIORITY_CLASS_ABOVE_NORMAL;
2531 return MONO_W32PROCESS_PRIORITY_CLASS_IDLE;
2533 return MONO_W32PROCESS_PRIORITY_CLASS_BELOW_NORMAL;
2535 return MONO_W32PROCESS_PRIORITY_CLASS_NORMAL;
2537 mono_w32error_set_last (ERROR_NOT_SUPPORTED);
2543 ves_icall_Microsoft_Win32_NativeMethods_SetPriorityClass (gpointer handle, gint32 priorityClass)
2545 #ifdef HAVE_SETPRIORITY
2546 MonoW32HandleProcess *process_handle;
2551 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle)) {
2552 /* This is a pseudo handle */
2553 pid = (pid_t)WAPI_HANDLE_TO_PID (handle);
2557 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2559 mono_w32error_set_last (ERROR_INVALID_HANDLE);
2563 pid = process_handle->pid;
2566 switch (priorityClass) {
2567 case MONO_W32PROCESS_PRIORITY_CLASS_IDLE:
2570 case MONO_W32PROCESS_PRIORITY_CLASS_BELOW_NORMAL:
2573 case MONO_W32PROCESS_PRIORITY_CLASS_NORMAL:
2576 case MONO_W32PROCESS_PRIORITY_CLASS_ABOVE_NORMAL:
2579 case MONO_W32PROCESS_PRIORITY_CLASS_HIGH:
2582 case MONO_W32PROCESS_PRIORITY_CLASS_REALTIME:
2586 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
2590 ret = setpriority (PRIO_PROCESS, pid, prio);
2595 mono_w32error_set_last (ERROR_ACCESS_DENIED);
2598 mono_w32error_set_last (ERROR_PROC_NOT_FOUND);
2601 mono_w32error_set_last (ERROR_GEN_FAILURE);
2607 mono_w32error_set_last (ERROR_NOT_SUPPORTED);
2613 ticks_to_processtime (guint64 ticks, ProcessTime *processtime)
2615 processtime->lowDateTime = ticks & 0xFFFFFFFF;
2616 processtime->highDateTime = ticks >> 32;
2620 ves_icall_Microsoft_Win32_NativeMethods_GetProcessTimes (gpointer handle, gint64 *creation_time, gint64 *exit_time, gint64 *kernel_time, gint64 *user_time)
2622 MonoW32HandleProcess *process_handle;
2623 ProcessTime *creation_processtime, *exit_processtime, *kernel_processtime, *user_processtime;
2626 if (!creation_time || !exit_time || !kernel_time || !user_time) {
2627 /* Not sure if w32 allows NULLs here or not */
2631 creation_processtime = (ProcessTime*) creation_time;
2632 exit_processtime = (ProcessTime*) exit_time;
2633 kernel_processtime = (ProcessTime*) kernel_time;
2634 user_processtime = (ProcessTime*) user_time;
2636 memset (creation_processtime, 0, sizeof (ProcessTime));
2637 memset (exit_processtime, 0, sizeof (ProcessTime));
2638 memset (kernel_processtime, 0, sizeof (ProcessTime));
2639 memset (user_processtime, 0, sizeof (ProcessTime));
2641 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle)) {
2642 gint64 start_ticks, user_ticks, kernel_ticks;
2644 mono_process_get_times (GINT_TO_POINTER (WAPI_HANDLE_TO_PID (handle)),
2645 &start_ticks, &user_ticks, &kernel_ticks);
2647 ticks_to_processtime (start_ticks, creation_processtime);
2648 ticks_to_processtime (user_ticks, kernel_processtime);
2649 ticks_to_processtime (kernel_ticks, user_processtime);
2653 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2655 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2659 ticks_to_processtime (process_handle->create_time, creation_processtime);
2661 /* A process handle is only signalled if the process has
2662 * exited, otherwise exit_processtime isn't set */
2663 if (mono_w32handle_issignalled (handle))
2664 ticks_to_processtime (process_handle->exit_time, exit_processtime);
2666 #ifdef HAVE_GETRUSAGE
2667 if (process_handle->pid == getpid ()) {
2668 struct rusage time_data;
2669 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
2670 ticks_to_processtime ((guint64)time_data.ru_utime.tv_sec * 10000000 + (guint64)time_data.ru_utime.tv_usec * 10, user_processtime);
2671 ticks_to_processtime ((guint64)time_data.ru_stime.tv_sec * 10000000 + (guint64)time_data.ru_stime.tv_usec * 10, kernel_processtime);
2679 static IMAGE_SECTION_HEADER *
2680 get_enclosing_section_header (guint32 rva, IMAGE_NT_HEADERS32 *nt_headers)
2682 IMAGE_SECTION_HEADER *section = IMAGE_FIRST_SECTION32 (nt_headers);
2685 for (i = 0; i < GUINT16_FROM_LE (nt_headers->FileHeader.NumberOfSections); i++, section++) {
2686 guint32 size = GUINT32_FROM_LE (section->Misc.VirtualSize);
2688 size = GUINT32_FROM_LE (section->SizeOfRawData);
2691 if ((rva >= GUINT32_FROM_LE (section->VirtualAddress)) &&
2692 (rva < (GUINT32_FROM_LE (section->VirtualAddress) + size))) {
2700 /* This works for both 32bit and 64bit files, as the differences are
2701 * all after the section header block
2704 get_ptr_from_rva (guint32 rva, IMAGE_NT_HEADERS32 *ntheaders, gpointer file_map)
2706 IMAGE_SECTION_HEADER *section_header;
2709 section_header = get_enclosing_section_header (rva, ntheaders);
2710 if (section_header == NULL) {
2714 delta = (guint32)(GUINT32_FROM_LE (section_header->VirtualAddress) -
2715 GUINT32_FROM_LE (section_header->PointerToRawData));
2717 return((guint8 *)file_map + rva - delta);
2721 scan_resource_dir (IMAGE_RESOURCE_DIRECTORY *root, IMAGE_NT_HEADERS32 *nt_headers, gpointer file_map,
2722 IMAGE_RESOURCE_DIRECTORY_ENTRY *entry, int level, guint32 res_id, guint32 lang_id, guint32 *size)
2724 IMAGE_RESOURCE_DIRECTORY_ENTRY swapped_entry;
2725 gboolean is_string, is_dir;
2726 guint32 name_offset, dir_offset, data_offset;
2728 swapped_entry.Name = GUINT32_FROM_LE (entry->Name);
2729 swapped_entry.OffsetToData = GUINT32_FROM_LE (entry->OffsetToData);
2731 is_string = swapped_entry.NameIsString;
2732 is_dir = swapped_entry.DataIsDirectory;
2733 name_offset = swapped_entry.NameOffset;
2734 dir_offset = swapped_entry.OffsetToDirectory;
2735 data_offset = swapped_entry.OffsetToData;
2738 /* Normally holds a directory entry for each type of
2741 if ((is_string == FALSE &&
2742 name_offset != res_id) ||
2743 (is_string == TRUE)) {
2746 } else if (level == 1) {
2747 /* Normally holds a directory entry for each resource
2750 } else if (level == 2) {
2751 /* Normally holds a directory entry for each language
2753 if ((is_string == FALSE &&
2754 name_offset != lang_id &&
2756 (is_string == TRUE)) {
2760 g_assert_not_reached ();
2763 if (is_dir == TRUE) {
2764 IMAGE_RESOURCE_DIRECTORY *res_dir = (IMAGE_RESOURCE_DIRECTORY *)((guint8 *)root + dir_offset);
2765 IMAGE_RESOURCE_DIRECTORY_ENTRY *sub_entries = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(res_dir + 1);
2768 entries = GUINT16_FROM_LE (res_dir->NumberOfNamedEntries) + GUINT16_FROM_LE (res_dir->NumberOfIdEntries);
2770 for (i = 0; i < entries; i++) {
2771 IMAGE_RESOURCE_DIRECTORY_ENTRY *sub_entry = &sub_entries[i];
2774 ret = scan_resource_dir (root, nt_headers, file_map,
2775 sub_entry, level + 1, res_id,
2784 IMAGE_RESOURCE_DATA_ENTRY *data_entry = (IMAGE_RESOURCE_DATA_ENTRY *)((guint8 *)root + data_offset);
2785 *size = GUINT32_FROM_LE (data_entry->Size);
2787 return(get_ptr_from_rva (GUINT32_FROM_LE (data_entry->OffsetToData), nt_headers, file_map));
2792 find_pe_file_resources32 (gpointer file_map, guint32 map_size, guint32 res_id, guint32 lang_id, guint32 *size)
2794 IMAGE_DOS_HEADER *dos_header;
2795 IMAGE_NT_HEADERS32 *nt_headers;
2796 IMAGE_RESOURCE_DIRECTORY *resource_dir;
2797 IMAGE_RESOURCE_DIRECTORY_ENTRY *resource_dir_entry;
2798 guint32 resource_rva, entries, i;
2799 gpointer ret = NULL;
2801 dos_header = (IMAGE_DOS_HEADER *)file_map;
2802 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) {
2803 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Bad dos signature 0x%x", __func__, dos_header->e_magic);
2805 mono_w32error_set_last (ERROR_INVALID_DATA);
2809 if (map_size < sizeof(IMAGE_NT_HEADERS32) + GUINT32_FROM_LE (dos_header->e_lfanew)) {
2810 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File is too small: %d", __func__, map_size);
2812 mono_w32error_set_last (ERROR_BAD_LENGTH);
2816 nt_headers = (IMAGE_NT_HEADERS32 *)((guint8 *)file_map + GUINT32_FROM_LE (dos_header->e_lfanew));
2817 if (nt_headers->Signature != IMAGE_NT_SIGNATURE) {
2818 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Bad NT signature 0x%x", __func__, nt_headers->Signature);
2820 mono_w32error_set_last (ERROR_INVALID_DATA);
2824 if (nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
2825 /* Do 64-bit stuff */
2826 resource_rva = GUINT32_FROM_LE (((IMAGE_NT_HEADERS64 *)nt_headers)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
2828 resource_rva = GUINT32_FROM_LE (nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
2831 if (resource_rva == 0) {
2832 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: No resources in file!", __func__);
2834 mono_w32error_set_last (ERROR_INVALID_DATA);
2838 resource_dir = (IMAGE_RESOURCE_DIRECTORY *)get_ptr_from_rva (resource_rva, (IMAGE_NT_HEADERS32 *)nt_headers, file_map);
2839 if (resource_dir == NULL) {
2840 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find resource directory", __func__);
2842 mono_w32error_set_last (ERROR_INVALID_DATA);
2846 entries = GUINT16_FROM_LE (resource_dir->NumberOfNamedEntries) + GUINT16_FROM_LE (resource_dir->NumberOfIdEntries);
2847 resource_dir_entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resource_dir + 1);
2849 for (i = 0; i < entries; i++) {
2850 IMAGE_RESOURCE_DIRECTORY_ENTRY *direntry = &resource_dir_entry[i];
2851 ret = scan_resource_dir (resource_dir,
2852 (IMAGE_NT_HEADERS32 *)nt_headers,
2853 file_map, direntry, 0, res_id,
2864 find_pe_file_resources64 (gpointer file_map, guint32 map_size, guint32 res_id, guint32 lang_id, guint32 *size)
2866 IMAGE_DOS_HEADER *dos_header;
2867 IMAGE_NT_HEADERS64 *nt_headers;
2868 IMAGE_RESOURCE_DIRECTORY *resource_dir;
2869 IMAGE_RESOURCE_DIRECTORY_ENTRY *resource_dir_entry;
2870 guint32 resource_rva, entries, i;
2871 gpointer ret = NULL;
2873 dos_header = (IMAGE_DOS_HEADER *)file_map;
2874 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) {
2875 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Bad dos signature 0x%x", __func__, dos_header->e_magic);
2877 mono_w32error_set_last (ERROR_INVALID_DATA);
2881 if (map_size < sizeof(IMAGE_NT_HEADERS64) + GUINT32_FROM_LE (dos_header->e_lfanew)) {
2882 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File is too small: %d", __func__, map_size);
2884 mono_w32error_set_last (ERROR_BAD_LENGTH);
2888 nt_headers = (IMAGE_NT_HEADERS64 *)((guint8 *)file_map + GUINT32_FROM_LE (dos_header->e_lfanew));
2889 if (nt_headers->Signature != IMAGE_NT_SIGNATURE) {
2890 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Bad NT signature 0x%x", __func__,
2891 nt_headers->Signature);
2893 mono_w32error_set_last (ERROR_INVALID_DATA);
2897 if (nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
2898 /* Do 64-bit stuff */
2899 resource_rva = GUINT32_FROM_LE (((IMAGE_NT_HEADERS64 *)nt_headers)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
2901 resource_rva = GUINT32_FROM_LE (nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
2904 if (resource_rva == 0) {
2905 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: No resources in file!", __func__);
2907 mono_w32error_set_last (ERROR_INVALID_DATA);
2911 resource_dir = (IMAGE_RESOURCE_DIRECTORY *)get_ptr_from_rva (resource_rva, (IMAGE_NT_HEADERS32 *)nt_headers, file_map);
2912 if (resource_dir == NULL) {
2913 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find resource directory", __func__);
2915 mono_w32error_set_last (ERROR_INVALID_DATA);
2919 entries = GUINT16_FROM_LE (resource_dir->NumberOfNamedEntries) + GUINT16_FROM_LE (resource_dir->NumberOfIdEntries);
2920 resource_dir_entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resource_dir + 1);
2922 for (i = 0; i < entries; i++) {
2923 IMAGE_RESOURCE_DIRECTORY_ENTRY *direntry = &resource_dir_entry[i];
2924 ret = scan_resource_dir (resource_dir,
2925 (IMAGE_NT_HEADERS32 *)nt_headers,
2926 file_map, direntry, 0, res_id,
2937 find_pe_file_resources (gpointer file_map, guint32 map_size, guint32 res_id, guint32 lang_id, guint32 *size)
2939 /* Figure this out when we support 64bit PE files */
2941 return find_pe_file_resources32 (file_map, map_size, res_id,
2944 return find_pe_file_resources64 (file_map, map_size, res_id,
2950 map_pe_file (gunichar2 *filename, gint32 *map_size, void **handle)
2952 gchar *filename_ext;
2954 struct stat statbuf;
2957 /* According to the MSDN docs, a search path is applied to
2958 * filename. FIXME: implement this, for now just pass it
2962 filename_ext = mono_unicode_to_external (filename);
2963 if (filename_ext == NULL) {
2964 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2966 mono_w32error_set_last (ERROR_INVALID_NAME);
2970 fd = open (filename_ext, O_RDONLY, 0);
2971 if (fd == -1 && (errno == ENOENT || errno == ENOTDIR) && IS_PORTABILITY_SET) {
2973 gchar *located_filename;
2975 saved_errno = errno;
2977 located_filename = mono_portability_find_file (filename_ext, TRUE);
2978 if (!located_filename) {
2979 errno = saved_errno;
2981 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error opening file %s (1): %s", __func__, filename_ext, strerror (errno));
2983 g_free (filename_ext);
2985 mono_w32error_set_last (mono_w32error_unix_to_win32 (errno));
2989 fd = open (located_filename, O_RDONLY, 0);
2991 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error opening file %s (2): %s", __func__, filename_ext, strerror (errno));
2993 g_free (filename_ext);
2994 g_free (located_filename);
2996 mono_w32error_set_last (mono_w32error_unix_to_win32 (errno));
3000 g_free (located_filename);
3003 if (fstat (fd, &statbuf) == -1) {
3004 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error stat()ing file %s: %s", __func__, filename_ext, strerror (errno));
3006 mono_w32error_set_last (mono_w32error_unix_to_win32 (errno));
3007 g_free (filename_ext);
3011 *map_size = statbuf.st_size;
3013 /* Check basic file size */
3014 if (statbuf.st_size < sizeof(IMAGE_DOS_HEADER)) {
3015 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File %s is too small: %lld", __func__, filename_ext, statbuf.st_size);
3017 mono_w32error_set_last (ERROR_BAD_LENGTH);
3018 g_free (filename_ext);
3023 file_map = mono_file_map (statbuf.st_size, MONO_MMAP_READ | MONO_MMAP_PRIVATE, fd, 0, handle);
3024 if (file_map == NULL) {
3025 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error mmap()int file %s: %s", __func__, filename_ext, strerror (errno));
3027 mono_w32error_set_last (mono_w32error_unix_to_win32 (errno));
3028 g_free (filename_ext);
3033 /* Don't need the fd any more */
3035 g_free (filename_ext);
3041 unmap_pe_file (gpointer file_map, void *handle)
3043 mono_file_unmap (file_map, handle);
3047 unicode_chars (const gunichar2 *str)
3052 if (str[len] == '\0') {
3060 unicode_compare (const gunichar2 *str1, const gunichar2 *str2)
3062 while (*str1 && *str2) {
3063 if (*str1 != *str2) {
3070 return(*str1 == *str2);
3073 /* compare a little-endian null-terminated utf16 string and a normal string.
3074 * Can be used only for ascii or latin1 chars.
3077 unicode_string_equals (const gunichar2 *str1, const gchar *str2)
3079 while (*str1 && *str2) {
3080 if (GUINT16_TO_LE (*str1) != *str2) {
3087 return(*str1 == *str2);
3097 /* Returns a pointer to the value data, because there's no way to know
3098 * how big that data is (value_len is set to zero for most blocks :-( )
3100 static gconstpointer
3101 get_versioninfo_block (gconstpointer data, version_data *block)
3103 block->data_len = GUINT16_FROM_LE (*((guint16 *)data));
3104 data = (char *)data + sizeof(guint16);
3105 block->value_len = GUINT16_FROM_LE (*((guint16 *)data));
3106 data = (char *)data + sizeof(guint16);
3108 /* No idea what the type is supposed to indicate */
3109 block->type = GUINT16_FROM_LE (*((guint16 *)data));
3110 data = (char *)data + sizeof(guint16);
3111 block->key = ((gunichar2 *)data);
3113 /* Skip over the key (including the terminator) */
3114 data = ((gunichar2 *)data) + (unicode_chars (block->key) + 1);
3116 /* align on a 32-bit boundary */
3122 static gconstpointer
3123 get_fixedfileinfo_block (gconstpointer data, version_data *block)
3125 gconstpointer data_ptr;
3126 VS_FIXEDFILEINFO *ffi;
3128 data_ptr = get_versioninfo_block (data, block);
3130 if (block->value_len != sizeof(VS_FIXEDFILEINFO)) {
3131 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: FIXEDFILEINFO size mismatch", __func__);
3135 if (!unicode_string_equals (block->key, "VS_VERSION_INFO")) {
3136 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: VS_VERSION_INFO mismatch", __func__);
3141 ffi = ((VS_FIXEDFILEINFO *)data_ptr);
3142 if ((ffi->dwSignature != VS_FFI_SIGNATURE) ||
3143 (ffi->dwStrucVersion != VS_FFI_STRUCVERSION)) {
3144 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: FIXEDFILEINFO bad signature", __func__);
3152 static gconstpointer
3153 get_varfileinfo_block (gconstpointer data_ptr, version_data *block)
3155 /* data is pointing at a Var block
3157 data_ptr = get_versioninfo_block (data_ptr, block);
3162 static gconstpointer
3163 get_string_block (gconstpointer data_ptr, const gunichar2 *string_key, gpointer *string_value,
3164 guint32 *string_value_len, version_data *block)
3166 guint16 data_len = block->data_len;
3167 guint16 string_len = 28; /* Length of the StringTable block */
3168 char *orig_data_ptr = (char *)data_ptr - 28;
3170 /* data_ptr is pointing at an array of one or more String blocks
3171 * with total length (not including alignment padding) of
3174 while (((char *)data_ptr - (char *)orig_data_ptr) < data_len) {
3175 /* align on a 32-bit boundary */
3178 data_ptr = get_versioninfo_block (data_ptr, block);
3179 if (block->data_len == 0) {
3180 /* We must have hit padding, so give up
3183 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3188 string_len = string_len + block->data_len;
3190 if (string_key != NULL &&
3191 string_value != NULL &&
3192 string_value_len != NULL &&
3193 unicode_compare (string_key, block->key) == TRUE) {
3194 *string_value = (gpointer)data_ptr;
3195 *string_value_len = block->value_len;
3198 /* Skip over the value */
3199 data_ptr = ((gunichar2 *)data_ptr) + block->value_len;
3205 /* Returns a pointer to the byte following the Stringtable block, or
3206 * NULL if the data read hits padding. We can't recover from this
3207 * because the data length does not include padding bytes, so it's not
3208 * possible to just return the start position + length
3210 * If lang == NULL it means we're just stepping through this block
3212 static gconstpointer
3213 get_stringtable_block (gconstpointer data_ptr, gchar *lang, const gunichar2 *string_key, gpointer *string_value,
3214 guint32 *string_value_len, version_data *block)
3216 guint16 data_len = block->data_len;
3217 guint16 string_len = 36; /* length of the StringFileInfo block */
3219 gchar *lowercase_lang;
3221 /* data_ptr is pointing at an array of StringTable blocks,
3222 * with total length (not including alignment padding) of
3226 while(string_len < data_len) {
3227 /* align on a 32-bit boundary */
3230 data_ptr = get_versioninfo_block (data_ptr, block);
3231 if (block->data_len == 0) {
3232 /* We must have hit padding, so give up
3235 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3239 string_len = string_len + block->data_len;
3241 found_lang = g_utf16_to_utf8 (block->key, 8, NULL, NULL, NULL);
3242 if (found_lang == NULL) {
3243 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't find a valid language key, giving up", __func__);
3247 lowercase_lang = g_utf8_strdown (found_lang, -1);
3248 g_free (found_lang);
3249 found_lang = lowercase_lang;
3250 lowercase_lang = NULL;
3252 if (lang != NULL && !strcmp (found_lang, lang)) {
3253 /* Got the one we're interested in */
3254 data_ptr = get_string_block (data_ptr, string_key,
3256 string_value_len, block);
3258 data_ptr = get_string_block (data_ptr, NULL, NULL,
3262 g_free (found_lang);
3264 if (data_ptr == NULL) {
3265 /* Child block hit padding */
3266 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Child block hit 0-length block, giving up", __func__);
3274 #if G_BYTE_ORDER == G_BIG_ENDIAN
3275 static gconstpointer
3276 big_up_string_block (gconstpointer data_ptr, version_data *block)
3278 guint16 data_len = block->data_len;
3279 guint16 string_len = 28; /* Length of the StringTable block */
3281 char *orig_data_ptr = (char *)data_ptr - 28;
3283 /* data_ptr is pointing at an array of one or more String
3284 * blocks with total length (not including alignment padding)
3287 while (((char *)data_ptr - (char *)orig_data_ptr) < data_len) {
3288 /* align on a 32-bit boundary */
3291 data_ptr = get_versioninfo_block (data_ptr, block);
3292 if (block->data_len == 0) {
3293 /* We must have hit padding, so give up
3296 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3300 string_len = string_len + block->data_len;
3302 big_value = g_convert ((gchar *)block->key,
3303 unicode_chars (block->key) * 2,
3304 "UTF-16BE", "UTF-16LE", NULL, NULL,
3306 if (big_value == NULL) {
3307 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't find a valid string, giving up", __func__);
3311 /* The swapped string should be exactly the same
3312 * length as the original little-endian one, but only
3313 * copy the number of original chars just to be on the
3316 memcpy (block->key, big_value, unicode_chars (block->key) * 2);
3319 big_value = g_convert ((gchar *)data_ptr,
3320 unicode_chars (data_ptr) * 2,
3321 "UTF-16BE", "UTF-16LE", NULL, NULL,
3323 if (big_value == NULL) {
3324 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't find a valid data string, giving up", __func__);
3327 memcpy ((gpointer)data_ptr, big_value,
3328 unicode_chars (data_ptr) * 2);
3331 data_ptr = ((gunichar2 *)data_ptr) + block->value_len;
3337 /* Returns a pointer to the byte following the Stringtable block, or
3338 * NULL if the data read hits padding. We can't recover from this
3339 * because the data length does not include padding bytes, so it's not
3340 * possible to just return the start position + length
3342 static gconstpointer
3343 big_up_stringtable_block (gconstpointer data_ptr, version_data *block)
3345 guint16 data_len = block->data_len;
3346 guint16 string_len = 36; /* length of the StringFileInfo block */
3349 /* data_ptr is pointing at an array of StringTable blocks,
3350 * with total length (not including alignment padding) of
3354 while(string_len < data_len) {
3355 /* align on a 32-bit boundary */
3358 data_ptr = get_versioninfo_block (data_ptr, block);
3359 if (block->data_len == 0) {
3360 /* We must have hit padding, so give up
3363 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3367 string_len = string_len + block->data_len;
3369 big_value = g_convert ((gchar *)block->key, 16, "UTF-16BE",
3370 "UTF-16LE", NULL, NULL, NULL);
3371 if (big_value == NULL) {
3372 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't find a valid string, giving up", __func__);
3376 memcpy (block->key, big_value, 16);
3379 data_ptr = big_up_string_block (data_ptr, block);
3381 if (data_ptr == NULL) {
3382 /* Child block hit padding */
3383 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Child block hit 0-length block, giving up", __func__);
3391 /* Follows the data structures and turns all UTF-16 strings from the
3392 * LE found in the resource section into UTF-16BE
3395 big_up (gconstpointer datablock, guint32 size)
3397 gconstpointer data_ptr;
3398 gint32 data_len; /* signed to guard against underflow */
3401 data_ptr = get_fixedfileinfo_block (datablock, &block);
3402 if (data_ptr != NULL) {
3403 VS_FIXEDFILEINFO *ffi = (VS_FIXEDFILEINFO *)data_ptr;
3405 /* Byteswap all the fields */
3406 ffi->dwFileVersionMS = GUINT32_SWAP_LE_BE (ffi->dwFileVersionMS);
3407 ffi->dwFileVersionLS = GUINT32_SWAP_LE_BE (ffi->dwFileVersionLS);
3408 ffi->dwProductVersionMS = GUINT32_SWAP_LE_BE (ffi->dwProductVersionMS);
3409 ffi->dwProductVersionLS = GUINT32_SWAP_LE_BE (ffi->dwProductVersionLS);
3410 ffi->dwFileFlagsMask = GUINT32_SWAP_LE_BE (ffi->dwFileFlagsMask);
3411 ffi->dwFileFlags = GUINT32_SWAP_LE_BE (ffi->dwFileFlags);
3412 ffi->dwFileOS = GUINT32_SWAP_LE_BE (ffi->dwFileOS);
3413 ffi->dwFileType = GUINT32_SWAP_LE_BE (ffi->dwFileType);
3414 ffi->dwFileSubtype = GUINT32_SWAP_LE_BE (ffi->dwFileSubtype);
3415 ffi->dwFileDateMS = GUINT32_SWAP_LE_BE (ffi->dwFileDateMS);
3416 ffi->dwFileDateLS = GUINT32_SWAP_LE_BE (ffi->dwFileDateLS);
3418 /* The FFI and header occupies the first 92 bytes
3420 data_ptr = (char *)data_ptr + sizeof(VS_FIXEDFILEINFO);
3421 data_len = block.data_len - 92;
3423 /* There now follow zero or one StringFileInfo blocks
3424 * and zero or one VarFileInfo blocks
3426 while (data_len > 0) {
3427 /* align on a 32-bit boundary */
3430 data_ptr = get_versioninfo_block (data_ptr, &block);
3431 if (block.data_len == 0) {
3432 /* We must have hit padding, so give
3435 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3439 data_len = data_len - block.data_len;
3441 if (unicode_string_equals (block.key, "VarFileInfo")) {
3442 data_ptr = get_varfileinfo_block (data_ptr,
3444 data_ptr = ((guchar *)data_ptr) + block.value_len;
3445 } else if (unicode_string_equals (block.key,
3446 "StringFileInfo")) {
3447 data_ptr = big_up_stringtable_block (data_ptr,
3451 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Not a valid VERSIONINFO child block", __func__);
3455 if (data_ptr == NULL) {
3456 /* Child block hit padding */
3457 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Child block hit 0-length block, giving up", __func__);
3466 mono_w32process_get_fileversion_info_size (gunichar2 *filename, guint32 *handle)
3469 gpointer versioninfo;
3474 /* This value is unused, but set to zero */
3477 file_map = map_pe_file (filename, &map_size, &map_handle);
3478 if (file_map == NULL) {
3482 versioninfo = find_pe_file_resources (file_map, map_size, RT_VERSION, 0, &size);
3483 if (versioninfo == NULL) {
3484 /* Didn't find the resource, so set the return value
3490 unmap_pe_file (file_map, map_handle);
3496 mono_w32process_get_fileversion_info (gunichar2 *filename, guint32 handle G_GNUC_UNUSED, guint32 len, gpointer data)
3499 gpointer versioninfo;
3503 gboolean ret = FALSE;
3505 file_map = map_pe_file (filename, &map_size, &map_handle);
3506 if (file_map == NULL) {
3510 versioninfo = find_pe_file_resources (file_map, map_size, RT_VERSION,
3512 if (versioninfo != NULL) {
3513 /* This could probably process the data so that
3514 * mono_w32process_ver_query_value() doesn't have to follow the data
3515 * blocks every time. But hey, these functions aren't
3516 * likely to appear in many profiles.
3518 memcpy (data, versioninfo, len < size?len:size);
3521 #if G_BYTE_ORDER == G_BIG_ENDIAN
3522 big_up (data, size);
3526 unmap_pe_file (file_map, map_handle);
3532 mono_w32process_ver_query_value (gconstpointer datablock, const gunichar2 *subblock, gpointer *buffer, guint32 *len)
3534 gchar *subblock_utf8, *lang_utf8 = NULL;
3535 gboolean ret = FALSE;
3537 gconstpointer data_ptr;
3538 gint32 data_len; /* signed to guard against underflow */
3539 gboolean want_var = FALSE;
3540 gboolean want_string = FALSE;
3542 const gunichar2 *string_key = NULL;
3543 gpointer string_value = NULL;
3544 guint32 string_value_len = 0;
3545 gchar *lowercase_lang;
3547 subblock_utf8 = g_utf16_to_utf8 (subblock, -1, NULL, NULL, NULL);
3548 if (subblock_utf8 == NULL) {
3552 if (!strcmp (subblock_utf8, "\\VarFileInfo\\Translation")) {
3554 } else if (!strncmp (subblock_utf8, "\\StringFileInfo\\", 16)) {
3556 memcpy (lang, subblock + 16, 8 * sizeof(gunichar2));
3557 lang_utf8 = g_utf16_to_utf8 (lang, 8, NULL, NULL, NULL);
3558 lowercase_lang = g_utf8_strdown (lang_utf8, -1);
3560 lang_utf8 = lowercase_lang;
3561 lowercase_lang = NULL;
3562 string_key = subblock + 25;
3565 if (!strcmp (subblock_utf8, "\\")) {
3566 data_ptr = get_fixedfileinfo_block (datablock, &block);
3567 if (data_ptr != NULL) {
3568 *buffer = (gpointer)data_ptr;
3569 *len = block.value_len;
3573 } else if (want_var || want_string) {
3574 data_ptr = get_fixedfileinfo_block (datablock, &block);
3575 if (data_ptr != NULL) {
3576 /* The FFI and header occupies the first 92
3579 data_ptr = (char *)data_ptr + sizeof(VS_FIXEDFILEINFO);
3580 data_len = block.data_len - 92;
3582 /* There now follow zero or one StringFileInfo
3583 * blocks and zero or one VarFileInfo blocks
3585 while (data_len > 0) {
3586 /* align on a 32-bit boundary */
3589 data_ptr = get_versioninfo_block (data_ptr,
3591 if (block.data_len == 0) {
3592 /* We must have hit padding,
3593 * so give up processing now
3595 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3599 data_len = data_len - block.data_len;
3601 if (unicode_string_equals (block.key, "VarFileInfo")) {
3602 data_ptr = get_varfileinfo_block (data_ptr, &block);
3604 *buffer = (gpointer)data_ptr;
3605 *len = block.value_len;
3609 /* Skip over the Var block */
3610 data_ptr = ((guchar *)data_ptr) + block.value_len;
3612 } else if (unicode_string_equals (block.key, "StringFileInfo")) {
3613 data_ptr = get_stringtable_block (data_ptr, lang_utf8, string_key, &string_value, &string_value_len, &block);
3615 string_value != NULL &&
3616 string_value_len != 0) {
3617 *buffer = string_value;
3618 *len = unicode_chars ((const gunichar2 *)string_value) + 1; /* Include trailing null */
3624 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Not a valid VERSIONINFO child block", __func__);
3628 if (data_ptr == NULL) {
3629 /* Child block hit padding */
3630 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Child block hit 0-length block, giving up", __func__);
3642 g_free (subblock_utf8);
3647 copy_lang (gunichar2 *lang_out, guint32 lang_len, const gchar *text)
3650 int chars = strlen (text);
3653 unitext = g_utf8_to_utf16 (text, -1, NULL, NULL, NULL);
3654 g_assert (unitext != NULL);
3656 if (chars < (lang_len - 1)) {
3657 memcpy (lang_out, (gpointer)unitext, chars * 2);
3658 lang_out[chars] = '\0';
3661 memcpy (lang_out, (gpointer)unitext, (lang_len - 1) * 2);
3662 lang_out[lang_len] = '\0';
3672 mono_w32process_ver_language_name (guint32 lang, gunichar2 *lang_out, guint32 lang_len)
3674 int primary, secondary;
3675 const char *name = NULL;
3677 primary = lang & 0x3FF;
3678 secondary = (lang >> 10) & 0x3F;
3682 switch (secondary) {
3683 case 0x01: name = "Process Default Language"; break;
3687 switch (secondary) {
3689 case 0x01: name = "Arabic (Saudi Arabia)"; break;
3690 case 0x02: name = "Arabic (Iraq)"; break;
3691 case 0x03: name = "Arabic (Egypt)"; break;
3692 case 0x04: name = "Arabic (Libya)"; break;
3693 case 0x05: name = "Arabic (Algeria)"; break;
3694 case 0x06: name = "Arabic (Morocco)"; break;
3695 case 0x07: name = "Arabic (Tunisia)"; break;
3696 case 0x08: name = "Arabic (Oman)"; break;
3697 case 0x09: name = "Arabic (Yemen)"; break;
3698 case 0x0a: name = "Arabic (Syria)"; break;
3699 case 0x0b: name = "Arabic (Jordan)"; break;
3700 case 0x0c: name = "Arabic (Lebanon)"; break;
3701 case 0x0d: name = "Arabic (Kuwait)"; break;
3702 case 0x0e: name = "Arabic (U.A.E.)"; break;
3703 case 0x0f: name = "Arabic (Bahrain)"; break;
3704 case 0x10: name = "Arabic (Qatar)"; break;
3708 switch (secondary) {
3709 case 0x00: name = "Bulgarian (Bulgaria)"; break;
3710 case 0x01: name = "Bulgarian"; break;
3714 switch (secondary) {
3715 case 0x00: name = "Catalan (Spain)"; break;
3716 case 0x01: name = "Catalan"; break;
3720 switch (secondary) {
3722 case 0x01: name = "Chinese (Taiwan)"; break;
3723 case 0x02: name = "Chinese (PRC)"; break;
3724 case 0x03: name = "Chinese (Hong Kong S.A.R.)"; break;
3725 case 0x04: name = "Chinese (Singapore)"; break;
3726 case 0x05: name = "Chinese (Macau S.A.R.)"; break;
3730 switch (secondary) {
3731 case 0x00: name = "Czech (Czech Republic)"; break;
3732 case 0x01: name = "Czech"; break;
3736 switch (secondary) {
3737 case 0x00: name = "Danish (Denmark)"; break;
3738 case 0x01: name = "Danish"; break;
3742 switch (secondary) {
3744 case 0x01: name = "German (Germany)"; break;
3745 case 0x02: name = "German (Switzerland)"; break;
3746 case 0x03: name = "German (Austria)"; break;
3747 case 0x04: name = "German (Luxembourg)"; break;
3748 case 0x05: name = "German (Liechtenstein)"; break;
3752 switch (secondary) {
3753 case 0x00: name = "Greek (Greece)"; break;
3754 case 0x01: name = "Greek"; break;
3758 switch (secondary) {
3760 case 0x01: name = "English (United States)"; break;
3761 case 0x02: name = "English (United Kingdom)"; break;
3762 case 0x03: name = "English (Australia)"; break;
3763 case 0x04: name = "English (Canada)"; break;
3764 case 0x05: name = "English (New Zealand)"; break;
3765 case 0x06: name = "English (Ireland)"; break;
3766 case 0x07: name = "English (South Africa)"; break;
3767 case 0x08: name = "English (Jamaica)"; break;
3768 case 0x09: name = "English (Caribbean)"; break;
3769 case 0x0a: name = "English (Belize)"; break;
3770 case 0x0b: name = "English (Trinidad and Tobago)"; break;
3771 case 0x0c: name = "English (Zimbabwe)"; break;
3772 case 0x0d: name = "English (Philippines)"; break;
3773 case 0x10: name = "English (India)"; break;
3774 case 0x11: name = "English (Malaysia)"; break;
3775 case 0x12: name = "English (Singapore)"; break;
3779 switch (secondary) {
3780 case 0x00: name = "Spanish (Spain)"; break;
3781 case 0x01: name = "Spanish (Traditional Sort)"; break;
3782 case 0x02: name = "Spanish (Mexico)"; break;
3783 case 0x03: name = "Spanish (International Sort)"; break;
3784 case 0x04: name = "Spanish (Guatemala)"; break;
3785 case 0x05: name = "Spanish (Costa Rica)"; break;
3786 case 0x06: name = "Spanish (Panama)"; break;
3787 case 0x07: name = "Spanish (Dominican Republic)"; break;
3788 case 0x08: name = "Spanish (Venezuela)"; break;
3789 case 0x09: name = "Spanish (Colombia)"; break;
3790 case 0x0a: name = "Spanish (Peru)"; break;
3791 case 0x0b: name = "Spanish (Argentina)"; break;
3792 case 0x0c: name = "Spanish (Ecuador)"; break;
3793 case 0x0d: name = "Spanish (Chile)"; break;
3794 case 0x0e: name = "Spanish (Uruguay)"; break;
3795 case 0x0f: name = "Spanish (Paraguay)"; break;
3796 case 0x10: name = "Spanish (Bolivia)"; break;
3797 case 0x11: name = "Spanish (El Salvador)"; break;
3798 case 0x12: name = "Spanish (Honduras)"; break;
3799 case 0x13: name = "Spanish (Nicaragua)"; break;
3800 case 0x14: name = "Spanish (Puerto Rico)"; break;
3801 case 0x15: name = "Spanish (United States)"; break;
3805 switch (secondary) {
3806 case 0x00: name = "Finnish (Finland)"; break;
3807 case 0x01: name = "Finnish"; break;
3811 switch (secondary) {
3813 case 0x01: name = "French (France)"; break;
3814 case 0x02: name = "French (Belgium)"; break;
3815 case 0x03: name = "French (Canada)"; break;
3816 case 0x04: name = "French (Switzerland)"; break;
3817 case 0x05: name = "French (Luxembourg)"; break;
3818 case 0x06: name = "French (Monaco)"; break;
3822 switch (secondary) {
3823 case 0x00: name = "Hebrew (Israel)"; break;
3824 case 0x01: name = "Hebrew"; break;
3828 switch (secondary) {
3829 case 0x00: name = "Hungarian (Hungary)"; break;
3830 case 0x01: name = "Hungarian"; break;
3834 switch (secondary) {
3835 case 0x00: name = "Icelandic (Iceland)"; break;
3836 case 0x01: name = "Icelandic"; break;
3840 switch (secondary) {
3842 case 0x01: name = "Italian (Italy)"; break;
3843 case 0x02: name = "Italian (Switzerland)"; break;
3847 switch (secondary) {
3848 case 0x00: name = "Japanese (Japan)"; break;
3849 case 0x01: name = "Japanese"; break;
3853 switch (secondary) {
3854 case 0x00: name = "Korean (Korea)"; break;
3855 case 0x01: name = "Korean"; break;
3859 switch (secondary) {
3861 case 0x01: name = "Dutch (Netherlands)"; break;
3862 case 0x02: name = "Dutch (Belgium)"; break;
3866 switch (secondary) {
3868 case 0x01: name = "Norwegian (Bokmal)"; break;
3869 case 0x02: name = "Norwegian (Nynorsk)"; break;
3873 switch (secondary) {
3874 case 0x00: name = "Polish (Poland)"; break;
3875 case 0x01: name = "Polish"; break;
3879 switch (secondary) {
3881 case 0x01: name = "Portuguese (Brazil)"; break;
3882 case 0x02: name = "Portuguese (Portugal)"; break;
3886 switch (secondary) {
3887 case 0x01: name = "Romansh (Switzerland)"; break;
3891 switch (secondary) {
3892 case 0x00: name = "Romanian (Romania)"; break;
3893 case 0x01: name = "Romanian"; break;
3897 switch (secondary) {
3898 case 0x00: name = "Russian (Russia)"; break;
3899 case 0x01: name = "Russian"; break;
3903 switch (secondary) {
3904 case 0x00: name = "Croatian (Croatia)"; break;
3905 case 0x01: name = "Croatian"; break;
3906 case 0x02: name = "Serbian (Latin)"; break;
3907 case 0x03: name = "Serbian (Cyrillic)"; break;
3908 case 0x04: name = "Croatian (Bosnia and Herzegovina)"; break;
3909 case 0x05: name = "Bosnian (Latin, Bosnia and Herzegovina)"; break;
3910 case 0x06: name = "Serbian (Latin, Bosnia and Herzegovina)"; break;
3911 case 0x07: name = "Serbian (Cyrillic, Bosnia and Herzegovina)"; break;
3912 case 0x08: name = "Bosnian (Cyrillic, Bosnia and Herzegovina)"; break;
3916 switch (secondary) {
3917 case 0x00: name = "Slovak (Slovakia)"; break;
3918 case 0x01: name = "Slovak"; break;
3922 switch (secondary) {
3923 case 0x00: name = "Albanian (Albania)"; break;
3924 case 0x01: name = "Albanian"; break;
3928 switch (secondary) {
3929 case 0x00: name = "Swedish (Sweden)"; break;
3930 case 0x01: name = "Swedish"; break;
3931 case 0x02: name = "Swedish (Finland)"; break;
3935 switch (secondary) {
3936 case 0x00: name = "Thai (Thailand)"; break;
3937 case 0x01: name = "Thai"; break;
3941 switch (secondary) {
3942 case 0x00: name = "Turkish (Turkey)"; break;
3943 case 0x01: name = "Turkish"; break;
3947 switch (secondary) {
3948 case 0x00: name = "Urdu (Islamic Republic of Pakistan)"; break;
3949 case 0x01: name = "Urdu"; break;
3953 switch (secondary) {
3954 case 0x00: name = "Indonesian (Indonesia)"; break;
3955 case 0x01: name = "Indonesian"; break;
3959 switch (secondary) {
3960 case 0x00: name = "Ukrainian (Ukraine)"; break;
3961 case 0x01: name = "Ukrainian"; break;
3965 switch (secondary) {
3966 case 0x00: name = "Belarusian (Belarus)"; break;
3967 case 0x01: name = "Belarusian"; break;
3971 switch (secondary) {
3972 case 0x00: name = "Slovenian (Slovenia)"; break;
3973 case 0x01: name = "Slovenian"; break;
3977 switch (secondary) {
3978 case 0x00: name = "Estonian (Estonia)"; break;
3979 case 0x01: name = "Estonian"; break;
3983 switch (secondary) {
3984 case 0x00: name = "Latvian (Latvia)"; break;
3985 case 0x01: name = "Latvian"; break;
3989 switch (secondary) {
3990 case 0x00: name = "Lithuanian (Lithuania)"; break;
3991 case 0x01: name = "Lithuanian"; break;
3995 switch (secondary) {
3996 case 0x01: name = "Tajik (Tajikistan)"; break;
4000 switch (secondary) {
4001 case 0x00: name = "Farsi (Iran)"; break;
4002 case 0x01: name = "Farsi"; break;
4006 switch (secondary) {
4007 case 0x00: name = "Vietnamese (Viet Nam)"; break;
4008 case 0x01: name = "Vietnamese"; break;
4012 switch (secondary) {
4013 case 0x00: name = "Armenian (Armenia)"; break;
4014 case 0x01: name = "Armenian"; break;
4018 switch (secondary) {
4019 case 0x00: name = "Azeri (Latin) (Azerbaijan)"; break;
4020 case 0x01: name = "Azeri (Latin)"; break;
4021 case 0x02: name = "Azeri (Cyrillic)"; break;
4025 switch (secondary) {
4026 case 0x00: name = "Basque (Spain)"; break;
4027 case 0x01: name = "Basque"; break;
4031 switch (secondary) {
4032 case 0x01: name = "Upper Sorbian (Germany)"; break;
4033 case 0x02: name = "Lower Sorbian (Germany)"; break;
4037 switch (secondary) {
4038 case 0x00: name = "FYRO Macedonian (Former Yugoslav Republic of Macedonia)"; break;
4039 case 0x01: name = "FYRO Macedonian"; break;
4043 switch (secondary) {
4044 case 0x00: name = "Tswana (South Africa)"; break;
4045 case 0x01: name = "Tswana"; break;
4049 switch (secondary) {
4050 case 0x00: name = "Xhosa (South Africa)"; break;
4051 case 0x01: name = "Xhosa"; break;
4055 switch (secondary) {
4056 case 0x00: name = "Zulu (South Africa)"; break;
4057 case 0x01: name = "Zulu"; break;
4061 switch (secondary) {
4062 case 0x00: name = "Afrikaans (South Africa)"; break;
4063 case 0x01: name = "Afrikaans"; break;
4067 switch (secondary) {
4068 case 0x00: name = "Georgian (Georgia)"; break;
4069 case 0x01: name = "Georgian"; break;
4073 switch (secondary) {
4074 case 0x00: name = "Faroese (Faroe Islands)"; break;
4075 case 0x01: name = "Faroese"; break;
4079 switch (secondary) {
4080 case 0x00: name = "Hindi (India)"; break;
4081 case 0x01: name = "Hindi"; break;
4085 switch (secondary) {
4086 case 0x00: name = "Maltese (Malta)"; break;
4087 case 0x01: name = "Maltese"; break;
4091 switch (secondary) {
4092 case 0x00: name = "Sami (Northern) (Norway)"; break;
4093 case 0x01: name = "Sami, Northern (Norway)"; break;
4094 case 0x02: name = "Sami, Northern (Sweden)"; break;
4095 case 0x03: name = "Sami, Northern (Finland)"; break;
4096 case 0x04: name = "Sami, Lule (Norway)"; break;
4097 case 0x05: name = "Sami, Lule (Sweden)"; break;
4098 case 0x06: name = "Sami, Southern (Norway)"; break;
4099 case 0x07: name = "Sami, Southern (Sweden)"; break;
4100 case 0x08: name = "Sami, Skolt (Finland)"; break;
4101 case 0x09: name = "Sami, Inari (Finland)"; break;
4105 switch (secondary) {
4106 case 0x02: name = "Irish (Ireland)"; break;
4110 switch (secondary) {
4112 case 0x01: name = "Malay (Malaysia)"; break;
4113 case 0x02: name = "Malay (Brunei Darussalam)"; break;
4117 switch (secondary) {
4118 case 0x00: name = "Kazakh (Kazakhstan)"; break;
4119 case 0x01: name = "Kazakh"; break;
4123 switch (secondary) {
4124 case 0x00: name = "Kyrgyz (Kyrgyzstan)"; break;
4125 case 0x01: name = "Kyrgyz (Cyrillic)"; break;
4129 switch (secondary) {
4130 case 0x00: name = "Swahili (Kenya)"; break;
4131 case 0x01: name = "Swahili"; break;
4135 switch (secondary) {
4136 case 0x01: name = "Turkmen (Turkmenistan)"; break;
4140 switch (secondary) {
4141 case 0x00: name = "Uzbek (Latin) (Uzbekistan)"; break;
4142 case 0x01: name = "Uzbek (Latin)"; break;
4143 case 0x02: name = "Uzbek (Cyrillic)"; break;
4147 switch (secondary) {
4148 case 0x00: name = "Tatar (Russia)"; break;
4149 case 0x01: name = "Tatar"; break;
4153 switch (secondary) {
4155 case 0x01: name = "Bengali (India)"; break;
4159 switch (secondary) {
4160 case 0x00: name = "Punjabi (India)"; break;
4161 case 0x01: name = "Punjabi"; break;
4165 switch (secondary) {
4166 case 0x00: name = "Gujarati (India)"; break;
4167 case 0x01: name = "Gujarati"; break;
4171 switch (secondary) {
4172 case 0x00: name = "Tamil (India)"; break;
4173 case 0x01: name = "Tamil"; break;
4177 switch (secondary) {
4178 case 0x00: name = "Telugu (India)"; break;
4179 case 0x01: name = "Telugu"; break;
4183 switch (secondary) {
4184 case 0x00: name = "Kannada (India)"; break;
4185 case 0x01: name = "Kannada"; break;
4189 switch (secondary) {
4191 case 0x01: name = "Malayalam (India)"; break;
4195 switch (secondary) {
4196 case 0x01: name = "Assamese (India)"; break;
4200 switch (secondary) {
4201 case 0x00: name = "Marathi (India)"; break;
4202 case 0x01: name = "Marathi"; break;
4206 switch (secondary) {
4207 case 0x00: name = "Sanskrit (India)"; break;
4208 case 0x01: name = "Sanskrit"; break;
4212 switch (secondary) {
4213 case 0x00: name = "Mongolian (Mongolia)"; break;
4214 case 0x01: name = "Mongolian (Cyrillic)"; break;
4215 case 0x02: name = "Mongolian (PRC)"; break;
4219 switch (secondary) {
4220 case 0x01: name = "Tibetan (PRC)"; break;
4221 case 0x02: name = "Tibetan (Bhutan)"; break;
4225 switch (secondary) {
4226 case 0x00: name = "Welsh (United Kingdom)"; break;
4227 case 0x01: name = "Welsh"; break;
4231 switch (secondary) {
4232 case 0x01: name = "Khmer (Cambodia)"; break;
4236 switch (secondary) {
4237 case 0x01: name = "Lao (Lao PDR)"; break;
4241 switch (secondary) {
4242 case 0x00: name = "Galician (Spain)"; break;
4243 case 0x01: name = "Galician"; break;
4247 switch (secondary) {
4248 case 0x00: name = "Konkani (India)"; break;
4249 case 0x01: name = "Konkani"; break;
4253 switch (secondary) {
4254 case 0x00: name = "Syriac (Syria)"; break;
4255 case 0x01: name = "Syriac"; break;
4259 switch (secondary) {
4260 case 0x01: name = "Sinhala (Sri Lanka)"; break;
4264 switch (secondary) {
4265 case 0x01: name = "Inuktitut (Syllabics, Canada)"; break;
4266 case 0x02: name = "Inuktitut (Latin, Canada)"; break;
4270 switch (secondary) {
4271 case 0x01: name = "Amharic (Ethiopia)"; break;
4275 switch (secondary) {
4276 case 0x02: name = "Tamazight (Algeria, Latin)"; break;
4280 switch (secondary) {
4281 case 0x01: name = "Nepali (Nepal)"; break;
4285 switch (secondary) {
4286 case 0x01: name = "Frisian (Netherlands)"; break;
4290 switch (secondary) {
4291 case 0x01: name = "Pashto (Afghanistan)"; break;
4295 switch (secondary) {
4296 case 0x01: name = "Filipino (Philippines)"; break;
4300 switch (secondary) {
4301 case 0x00: name = "Divehi (Maldives)"; break;
4302 case 0x01: name = "Divehi"; break;
4306 switch (secondary) {
4307 case 0x01: name = "Hausa (Nigeria, Latin)"; break;
4311 switch (secondary) {
4312 case 0x01: name = "Yoruba (Nigeria)"; break;
4316 switch (secondary) {
4318 case 0x01: name = "Quechua (Bolivia)"; break;
4319 case 0x02: name = "Quechua (Ecuador)"; break;
4320 case 0x03: name = "Quechua (Peru)"; break;
4324 switch (secondary) {
4325 case 0x00: name = "Northern Sotho (South Africa)"; break;
4326 case 0x01: name = "Northern Sotho"; break;
4330 switch (secondary) {
4331 case 0x01: name = "Bashkir (Russia)"; break;
4335 switch (secondary) {
4336 case 0x01: name = "Luxembourgish (Luxembourg)"; break;
4340 switch (secondary) {
4341 case 0x01: name = "Greenlandic (Greenland)"; break;
4345 switch (secondary) {
4346 case 0x01: name = "Yi (PRC)"; break;
4350 switch (secondary) {
4351 case 0x01: name = "Mapudungun (Chile)"; break;
4355 switch (secondary) {
4356 case 0x01: name = "Mohawk (Mohawk)"; break;
4360 switch (secondary) {
4361 case 0x01: name = "Breton (France)"; break;
4365 switch (secondary) {
4366 case 0x00: name = "Invariant Language (Invariant Country)"; break;
4370 switch (secondary) {
4371 case 0x01: name = "Uighur (PRC)"; break;
4375 switch (secondary) {
4376 case 0x00: name = "Maori (New Zealand)"; break;
4377 case 0x01: name = "Maori"; break;
4381 switch (secondary) {
4382 case 0x01: name = "Corsican (France)"; break;
4386 switch (secondary) {
4387 case 0x01: name = "Alsatian (France)"; break;
4391 switch (secondary) {
4392 case 0x01: name = "Yakut (Russia)"; break;
4396 switch (secondary) {
4397 case 0x01: name = "K'iche (Guatemala)"; break;
4401 switch (secondary) {
4402 case 0x01: name = "Kinyarwanda (Rwanda)"; break;
4406 switch (secondary) {
4407 case 0x01: name = "Wolof (Senegal)"; break;
4411 switch (secondary) {
4412 case 0x01: name = "Dari (Afghanistan)"; break;
4417 name = "Language Neutral";
4422 name = "Language Neutral";
4424 return copy_lang (lang_out, lang_len, name);