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/class.h>
53 #include <mono/metadata/class-internals.h>
54 #include <mono/metadata/object.h>
55 #include <mono/metadata/object-internals.h>
56 #include <mono/metadata/metadata.h>
57 #include <mono/metadata/metadata-internals.h>
58 #include <mono/metadata/exception.h>
59 #include <mono/io-layer/io-layer.h>
60 #include <mono/metadata/w32handle.h>
61 #include <mono/utils/mono-membar.h>
62 #include <mono/utils/mono-logger-internals.h>
63 #include <mono/utils/strenc.h>
64 #include <mono/utils/mono-proclib.h>
65 #include <mono/utils/mono-path.h>
66 #include <mono/utils/mono-lazy-init.h>
67 #include <mono/utils/mono-signal-handler.h>
68 #include <mono/utils/mono-time.h>
69 #include <mono/utils/mono-mmap.h>
70 #include <mono/utils/strenc.h>
73 #define MAXPATHLEN 242
76 #define STILL_ACTIVE ((int) 0x00000103)
79 /* define LOGDEBUG(...) g_message(__VA_ARGS__) */
81 /* The process' environment strings */
82 #if defined(__APPLE__)
83 #if defined (TARGET_OSX)
84 /* Apple defines this in crt_externs.h but doesn't provide that header for
85 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
86 * in fact exist on all implementations (so far)
88 gchar ***_NSGetEnviron(void);
89 #define environ (*_NSGetEnviron())
91 static char *mono_environ[1] = { NULL };
92 #define environ mono_environ
93 #endif /* defined (TARGET_OSX) */
95 extern char **environ;
99 * Handles > _WAPI_PROCESS_UNHANDLED are pseudo handles which represent processes
100 * not started by the runtime.
102 /* This marks a system process that we don't have a handle on */
103 /* FIXME: Cope with PIDs > sizeof guint */
104 #define _WAPI_PROCESS_UNHANDLED (1 << (8*sizeof(pid_t)-1))
106 #define WAPI_IS_PSEUDO_PROCESS_HANDLE(handle) ((GPOINTER_TO_UINT(handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED)
107 #define WAPI_PID_TO_HANDLE(pid) GINT_TO_POINTER (_WAPI_PROCESS_UNHANDLED + (pid))
108 #define WAPI_HANDLE_TO_PID(handle) (GPOINTER_TO_UINT ((handle)) - _WAPI_PROCESS_UNHANDLED)
111 STARTF_USESHOWWINDOW=0x001,
112 STARTF_USESIZE=0x002,
113 STARTF_USEPOSITION=0x004,
114 STARTF_USECOUNTCHARS=0x008,
115 STARTF_USEFILLATTRIBUTE=0x010,
116 STARTF_RUNFULLSCREEN=0x020,
117 STARTF_FORCEONFEEDBACK=0x040,
118 STARTF_FORCEOFFFEEDBACK=0x080,
119 STARTF_USESTDHANDLES=0x100
129 #if G_BYTE_ORDER == G_BIG_ENDIAN
130 guint32 highDateTime;
134 guint32 highDateTime;
139 * MonoProcess describes processes we create.
140 * It contains a semaphore that can be waited on in order to wait
141 * for process termination. It's accessed in our SIGCHLD handler,
142 * when status is updated (and pid cleared, to not clash with
143 * subsequent processes that may get executed).
145 typedef struct _MonoProcess MonoProcess;
146 struct _MonoProcess {
147 pid_t pid; /* the pid of the process. This value is only valid until the process has exited. */
148 MonoSemType exit_sem; /* this semaphore will be released when the process exits */
149 int status; /* the exit status */
150 gint32 handle_count; /* the number of handles to this mono_process instance */
151 /* we keep a ref to the creating _WapiHandle_process handle until
152 * the process has exited, so that the information there isn't lost.
159 /* MonoW32HandleProcess is a structure containing all the required information for process handling. */
163 gpointer main_thread;
167 size_t min_working_set;
168 size_t max_working_set;
170 MonoProcess *mono_process;
171 } MonoW32HandleProcess;
176 * 2 bytes: Length in bytes (this block, and all child blocks. does _not_ include alignment padding between blocks)
177 * 2 bytes: Length in bytes of VS_FIXEDFILEINFO struct
178 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
179 * Variable length unicode string (null terminated): Key (currently "VS_VERSION_INFO")
180 * Variable length padding to align VS_FIXEDFILEINFO on a 32-bit boundary
181 * VS_FIXEDFILEINFO struct
182 * Variable length padding to align Child struct on a 32-bit boundary
183 * Child struct (zero or one StringFileInfo structs, zero or one VarFileInfo structs)
189 * 2 bytes: Length in bytes (includes this block, as well as all Child blocks)
190 * 2 bytes: Value length (always zero)
191 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
192 * Variable length unicode string: Key (currently "StringFileInfo")
193 * Variable length padding to align Child struct on a 32-bit boundary
194 * Child structs ( one or more StringTable structs. Each StringTable struct's Key member indicates the appropriate language and code page for displaying the text in that StringTable struct.)
200 * 2 bytes: Length in bytes (includes this block as well as all Child blocks, but excludes any padding between String blocks)
201 * 2 bytes: Value length (always zero)
202 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
203 * Variable length unicode string: Key. An 8-digit hex number stored as a unicode string. The four most significant digits represent the language identifier. The four least significant digits represent the code page for which the data is formatted.
204 * Variable length padding to align Child struct on a 32-bit boundary
205 * Child structs (an array of one or more String structs (each aligned on a 32-bit boundary)
211 * 2 bytes: Length in bytes (of this block)
212 * 2 bytes: Value length (the length in words of the Value member)
213 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
214 * Variable length unicode string: Key. arbitrary string, identifies data.
215 * Variable length padding to align Value on a 32-bit boundary
216 * Value: Variable length unicode string, holding data.
222 * 2 bytes: Length in bytes (includes this block, as well as all Child blocks)
223 * 2 bytes: Value length (always zero)
224 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
225 * Variable length unicode string: Key (currently "VarFileInfo")
226 * Variable length padding to align Child struct on a 32-bit boundary
227 * Child structs (a Var struct)
233 * 2 bytes: Length in bytes of this block
234 * 2 bytes: Value length in bytes of the Value
235 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
236 * Variable length unicode string: Key ("Translation")
237 * Variable length padding to align Value on a 32-bit boundary
238 * Value: an array of one or more 4 byte values that are language and code page identifier pairs, low-order word containing a language identifier, and the high-order word containing a code page number. Either word can be zero, indicating that the file is language or code page independent.
241 #if G_BYTE_ORDER == G_BIG_ENDIAN
242 #define VS_FFI_SIGNATURE 0xbd04effe
243 #define VS_FFI_STRUCVERSION 0x00000100
245 #define VS_FFI_SIGNATURE 0xfeef04bd
246 #define VS_FFI_STRUCVERSION 0x00010000
249 #define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16
251 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0
252 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1
253 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2
255 #define IMAGE_SIZEOF_SHORT_NAME 8
257 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
258 #define IMAGE_DOS_SIGNATURE 0x4d5a
259 #define IMAGE_NT_SIGNATURE 0x50450000
260 #define IMAGE_NT_OPTIONAL_HDR32_MAGIC 0xb10
261 #define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0xb20
263 #define IMAGE_DOS_SIGNATURE 0x5a4d
264 #define IMAGE_NT_SIGNATURE 0x00004550
265 #define IMAGE_NT_OPTIONAL_HDR32_MAGIC 0x10b
266 #define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b
293 guint16 NumberOfSections;
294 guint32 TimeDateStamp;
295 guint32 PointerToSymbolTable;
296 guint32 NumberOfSymbols;
297 guint16 SizeOfOptionalHeader;
298 guint16 Characteristics;
302 guint32 VirtualAddress;
304 } IMAGE_DATA_DIRECTORY;
308 guint8 MajorLinkerVersion;
309 guint8 MinorLinkerVersion;
311 guint32 SizeOfInitializedData;
312 guint32 SizeOfUninitializedData;
313 guint32 AddressOfEntryPoint;
317 guint32 SectionAlignment;
318 guint32 FileAlignment;
319 guint16 MajorOperatingSystemVersion;
320 guint16 MinorOperatingSystemVersion;
321 guint16 MajorImageVersion;
322 guint16 MinorImageVersion;
323 guint16 MajorSubsystemVersion;
324 guint16 MinorSubsystemVersion;
325 guint32 Win32VersionValue;
327 guint32 SizeOfHeaders;
330 guint16 DllCharacteristics;
331 guint32 SizeOfStackReserve;
332 guint32 SizeOfStackCommit;
333 guint32 SizeOfHeapReserve;
334 guint32 SizeOfHeapCommit;
336 guint32 NumberOfRvaAndSizes;
337 IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
338 } IMAGE_OPTIONAL_HEADER32;
342 guint8 MajorLinkerVersion;
343 guint8 MinorLinkerVersion;
345 guint32 SizeOfInitializedData;
346 guint32 SizeOfUninitializedData;
347 guint32 AddressOfEntryPoint;
350 guint32 SectionAlignment;
351 guint32 FileAlignment;
352 guint16 MajorOperatingSystemVersion;
353 guint16 MinorOperatingSystemVersion;
354 guint16 MajorImageVersion;
355 guint16 MinorImageVersion;
356 guint16 MajorSubsystemVersion;
357 guint16 MinorSubsystemVersion;
358 guint32 Win32VersionValue;
360 guint32 SizeOfHeaders;
363 guint16 DllCharacteristics;
364 guint64 SizeOfStackReserve;
365 guint64 SizeOfStackCommit;
366 guint64 SizeOfHeapReserve;
367 guint64 SizeOfHeapCommit;
369 guint32 NumberOfRvaAndSizes;
370 IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
371 } IMAGE_OPTIONAL_HEADER64;
373 #if SIZEOF_VOID_P == 8
374 typedef IMAGE_OPTIONAL_HEADER64 IMAGE_OPTIONAL_HEADER;
376 typedef IMAGE_OPTIONAL_HEADER32 IMAGE_OPTIONAL_HEADER;
381 IMAGE_FILE_HEADER FileHeader;
382 IMAGE_OPTIONAL_HEADER32 OptionalHeader;
383 } IMAGE_NT_HEADERS32;
387 IMAGE_FILE_HEADER FileHeader;
388 IMAGE_OPTIONAL_HEADER64 OptionalHeader;
389 } IMAGE_NT_HEADERS64;
391 #if SIZEOF_VOID_P == 8
392 typedef IMAGE_NT_HEADERS64 IMAGE_NT_HEADERS;
394 typedef IMAGE_NT_HEADERS32 IMAGE_NT_HEADERS;
398 guint8 Name[IMAGE_SIZEOF_SHORT_NAME];
400 guint32 PhysicalAddress;
403 guint32 VirtualAddress;
404 guint32 SizeOfRawData;
405 guint32 PointerToRawData;
406 guint32 PointerToRelocations;
407 guint32 PointerToLinenumbers;
408 guint16 NumberOfRelocations;
409 guint16 NumberOfLinenumbers;
410 guint32 Characteristics;
411 } IMAGE_SECTION_HEADER;
413 #define IMAGE_FIRST_SECTION32(header) ((IMAGE_SECTION_HEADER *)((gsize)(header) + G_STRUCT_OFFSET (IMAGE_NT_HEADERS32, OptionalHeader) + GUINT16_FROM_LE (((IMAGE_NT_HEADERS32 *)(header))->FileHeader.SizeOfOptionalHeader)))
415 #define RT_CURSOR 0x01
416 #define RT_BITMAP 0x02
419 #define RT_DIALOG 0x05
420 #define RT_STRING 0x06
421 #define RT_FONTDIR 0x07
423 #define RT_ACCELERATOR 0x09
424 #define RT_RCDATA 0x0a
425 #define RT_MESSAGETABLE 0x0b
426 #define RT_GROUP_CURSOR 0x0c
427 #define RT_GROUP_ICON 0x0e
428 #define RT_VERSION 0x10
429 #define RT_DLGINCLUDE 0x11
430 #define RT_PLUGPLAY 0x13
432 #define RT_ANICURSOR 0x15
433 #define RT_ANIICON 0x16
435 #define RT_MANIFEST 0x18
438 guint32 Characteristics;
439 guint32 TimeDateStamp;
440 guint16 MajorVersion;
441 guint16 MinorVersion;
442 guint16 NumberOfNamedEntries;
443 guint16 NumberOfIdEntries;
444 } IMAGE_RESOURCE_DIRECTORY;
449 #if G_BYTE_ORDER == G_BIG_ENDIAN
450 guint32 NameIsString:1;
451 guint32 NameOffset:31;
453 guint32 NameOffset:31;
454 guint32 NameIsString:1;
458 #if G_BYTE_ORDER == G_BIG_ENDIAN
460 guint16 __wapi_big_endian_padding;
468 guint32 OffsetToData;
470 #if G_BYTE_ORDER == G_BIG_ENDIAN
471 guint32 DataIsDirectory:1;
472 guint32 OffsetToDirectory:31;
474 guint32 OffsetToDirectory:31;
475 guint32 DataIsDirectory:1;
479 } IMAGE_RESOURCE_DIRECTORY_ENTRY;
482 guint32 OffsetToData;
486 } IMAGE_RESOURCE_DATA_ENTRY;
488 #define VOS_UNKNOWN 0x00000000
489 #define VOS_DOS 0x00010000
490 #define VOS_OS216 0x00020000
491 #define VOS_OS232 0x00030000
492 #define VOS_NT 0x00040000
493 #define VOS__BASE 0x00000000
494 #define VOS__WINDOWS16 0x00000001
495 #define VOS__PM16 0x00000002
496 #define VOS__PM32 0x00000003
497 #define VOS__WINDOWS32 0x00000004
498 /* Should "embrace and extend" here with some entries for linux etc */
500 #define VOS_DOS_WINDOWS16 0x00010001
501 #define VOS_DOS_WINDOWS32 0x00010004
502 #define VOS_OS216_PM16 0x00020002
503 #define VOS_OS232_PM32 0x00030003
504 #define VOS_NT_WINDOWS32 0x00040004
506 #define VFT_UNKNOWN 0x0000
507 #define VFT_APP 0x0001
508 #define VFT_DLL 0x0002
509 #define VFT_DRV 0x0003
510 #define VFT_FONT 0x0004
511 #define VFT_VXD 0x0005
512 #define VFT_STATIC_LIB 0x0007
514 #define VFT2_UNKNOWN 0x0000
515 #define VFT2_DRV_PRINTER 0x0001
516 #define VFT2_DRV_KEYBOARD 0x0002
517 #define VFT2_DRV_LANGUAGE 0x0003
518 #define VFT2_DRV_DISPLAY 0x0004
519 #define VFT2_DRV_MOUSE 0x0005
520 #define VFT2_DRV_NETWORK 0x0006
521 #define VFT2_DRV_SYSTEM 0x0007
522 #define VFT2_DRV_INSTALLABLE 0x0008
523 #define VFT2_DRV_SOUND 0x0009
524 #define VFT2_DRV_COMM 0x000a
525 #define VFT2_DRV_INPUTMETHOD 0x000b
526 #define VFT2_FONT_RASTER 0x0001
527 #define VFT2_FONT_VECTOR 0x0002
528 #define VFT2_FONT_TRUETYPE 0x0003
530 #define MAKELANGID(primary,secondary) ((guint16)((secondary << 10) | (primary)))
532 #define ALIGN32(ptr) ptr = (gpointer)((char *)ptr + 3); ptr = (gpointer)((char *)ptr - ((gsize)ptr & 3));
535 static mono_lazy_init_t process_sig_chld_once = MONO_LAZY_INIT_STATUS_NOT_INITIALIZED;
538 static gchar *cli_launcher;
540 /* The signal-safe logic to use processes goes like this:
541 * - The list must be safe to traverse for the signal handler at all times.
542 * It's safe to: prepend an entry (which is a single store to 'processes'),
543 * unlink an entry (assuming the unlinked entry isn't freed and doesn't
544 * change its 'next' pointer so that it can still be traversed).
545 * When cleaning up we first unlink an entry, then we verify that
546 * the read lock isn't locked. Then we can free the entry, since
547 * we know that nobody is using the old version of the list (including
548 * the unlinked entry).
549 * We also need to lock when adding and cleaning up so that those two
550 * operations don't mess with eachother. (This lock is not used in the
552 static MonoProcess *processes;
553 static mono_mutex_t processes_mutex;
555 static gpointer current_process;
557 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
558 static const gunichar2 *utf16_space = utf16_space_bytes;
559 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
560 static const gunichar2 *utf16_quote = utf16_quote_bytes;
563 process_details (gpointer data)
565 MonoW32HandleProcess *process_handle = (MonoW32HandleProcess *) data;
566 g_print ("pid: %d, exited: %s, exitstatus: %d",
567 process_handle->pid, process_handle->exited ? "true" : "false", process_handle->exitstatus);
571 process_typename (void)
577 process_typesize (void)
579 return sizeof (MonoW32HandleProcess);
582 static MonoW32HandleWaitRet
583 process_wait (gpointer handle, guint32 timeout, gboolean *alerted)
585 MonoW32HandleProcess *process_handle;
586 pid_t pid G_GNUC_UNUSED, ret;
592 /* FIXME: We can now easily wait on processes that aren't our own children,
593 * but WaitFor*Object won't call us for pseudo handles. */
594 g_assert (!WAPI_IS_PSEUDO_PROCESS_HANDLE (handle));
596 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u)", __func__, handle, timeout);
601 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
603 g_warning ("%s: error looking up process handle %p", __func__, handle);
604 return MONO_W32HANDLE_WAIT_RET_FAILED;
607 if (process_handle->exited) {
608 /* We've already done this one */
609 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): Process already exited", __func__, handle, timeout);
610 return MONO_W32HANDLE_WAIT_RET_SUCCESS_0;
613 pid = process_handle->pid;
615 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
617 /* We don't need to lock processes here, the entry
618 * has a handle_count > 0 which means it will not be freed. */
619 mp = process_handle->mono_process;
623 if (pid == mono_process_current_pid ()) {
624 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on current process", __func__, handle, timeout);
625 return MONO_W32HANDLE_WAIT_RET_TIMEOUT;
628 /* This path is used when calling Process.HasExited, so
629 * it is only used to poll the state of the process, not
630 * to actually wait on it to exit */
631 g_assert (timeout == 0);
633 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on non-child process", __func__, handle, timeout);
635 res = waitpid (pid, &status, WNOHANG);
637 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): non-child process wait timeout", __func__, handle, timeout);
638 return MONO_W32HANDLE_WAIT_RET_TIMEOUT;
641 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): non-child process waited successfully", __func__, handle, timeout);
642 return MONO_W32HANDLE_WAIT_RET_SUCCESS_0;
645 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): non-child process wait failed, error : %s (%d))", __func__, handle, timeout, g_strerror (errno), errno);
646 return MONO_W32HANDLE_WAIT_RET_FAILED;
649 start = mono_msec_ticks ();
653 if (timeout != MONO_INFINITE_WAIT) {
654 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on semaphore for %li ms...",
655 __func__, handle, timeout, (long)(timeout - (now - start)));
656 ret = mono_os_sem_timedwait (&mp->exit_sem, (timeout - (now - start)), alerted ? MONO_SEM_FLAGS_ALERTABLE : MONO_SEM_FLAGS_NONE);
658 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on semaphore forever...",
659 __func__, handle, timeout);
660 ret = mono_os_sem_wait (&mp->exit_sem, alerted ? MONO_SEM_FLAGS_ALERTABLE : MONO_SEM_FLAGS_NONE);
663 if (ret == MONO_SEM_TIMEDWAIT_RET_SUCCESS) {
664 /* Success, process has exited */
665 mono_os_sem_post (&mp->exit_sem);
669 if (ret == MONO_SEM_TIMEDWAIT_RET_TIMEDOUT) {
670 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): wait timeout (timeout = 0)", __func__, handle, timeout);
671 return MONO_W32HANDLE_WAIT_RET_TIMEOUT;
674 now = mono_msec_ticks ();
675 if (now - start >= timeout) {
676 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): wait timeout", __func__, handle, timeout);
677 return MONO_W32HANDLE_WAIT_RET_TIMEOUT;
680 if (alerted && ret == MONO_SEM_TIMEDWAIT_RET_ALERTED) {
681 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): wait alerted", __func__, handle, timeout);
683 return MONO_W32HANDLE_WAIT_RET_ALERTED;
687 /* Process must have exited */
688 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): Waited successfully", __func__, handle, timeout);
691 if (WIFSIGNALED (status))
692 process_handle->exitstatus = 128 + WTERMSIG (status);
694 process_handle->exitstatus = WEXITSTATUS (status);
696 process_handle->exit_time = mono_100ns_datetime ();
698 process_handle->exited = TRUE;
700 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): Setting pid %d signalled, exit status %d",
701 __func__, handle, timeout, process_handle->pid, process_handle->exitstatus);
703 mono_w32handle_set_signal_state (handle, TRUE, TRUE);
705 return MONO_W32HANDLE_WAIT_RET_SUCCESS_0;
709 processes_cleanup (void)
711 static gint32 cleaning_up;
713 MonoProcess *prev = NULL;
714 GSList *finished = NULL;
716 gpointer unref_handle;
718 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s", __func__);
720 /* Ensure we're not in here in multiple threads at once, nor recursive. */
721 if (InterlockedCompareExchange (&cleaning_up, 1, 0) != 0)
724 for (mp = processes; mp; mp = mp->next) {
725 if (mp->pid == 0 && mp->handle) {
726 /* This process has exited and we need to remove the artifical ref
728 mono_os_mutex_lock (&processes_mutex);
729 unref_handle = mp->handle;
731 mono_os_mutex_unlock (&processes_mutex);
733 mono_w32handle_unref (unref_handle);
738 * Remove processes which exited from the processes list.
739 * We need to synchronize with the sigchld handler here, which runs
740 * asynchronously. The handler requires that the processes list
743 mono_os_mutex_lock (&processes_mutex);
747 if (mp->handle_count == 0 && mp->freeable) {
750 * This code can run parallel with the sigchld handler, but the
751 * modifications it makes are safe.
754 processes = mp->next;
756 prev->next = mp->next;
757 finished = g_slist_prepend (finished, mp);
766 mono_memory_barrier ();
768 for (l = finished; l; l = l->next) {
770 * All the entries in the finished list are unlinked from processes, and
771 * they have the 'finished' flag set, which means the sigchld handler is done
774 mp = (MonoProcess *)l->data;
775 mono_os_sem_destroy (&mp->exit_sem);
778 g_slist_free (finished);
780 mono_os_mutex_unlock (&processes_mutex);
782 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s done", __func__);
784 InterlockedExchange (&cleaning_up, 0);
788 process_close (gpointer handle, gpointer data)
790 MonoW32HandleProcess *process_handle;
792 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s", __func__);
794 process_handle = (MonoW32HandleProcess *) data;
795 g_free (process_handle->pname);
796 process_handle->pname = NULL;
797 if (process_handle->mono_process)
798 InterlockedDecrement (&process_handle->mono_process->handle_count);
799 processes_cleanup ();
802 static MonoW32HandleOps process_ops = {
803 process_close, /* close_shared */
807 process_wait, /* special_wait */
809 process_details, /* details */
810 process_typename, /* typename */
811 process_typesize, /* typesize */
815 process_set_defaults (MonoW32HandleProcess *process_handle)
817 /* These seem to be the defaults on w2k */
818 process_handle->min_working_set = 204800;
819 process_handle->max_working_set = 1413120;
821 process_handle->create_time = mono_100ns_datetime ();
825 process_set_name (MonoW32HandleProcess *process_handle)
827 char *progname, *utf8_progname, *slash;
829 progname = g_get_prgname ();
830 utf8_progname = mono_utf8_from_external (progname);
832 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: using [%s] as prog name", __func__, progname);
835 slash = strrchr (utf8_progname, '/');
837 process_handle->pname = g_strdup (slash+1);
839 process_handle->pname = g_strdup (utf8_progname);
840 g_free (utf8_progname);
845 mono_w32process_init (void)
847 MonoW32HandleProcess process_handle;
849 mono_w32handle_register_ops (MONO_W32HANDLE_PROCESS, &process_ops);
851 mono_w32handle_register_capabilities (MONO_W32HANDLE_PROCESS,
852 (MonoW32HandleCapability)(MONO_W32HANDLE_CAP_WAIT | MONO_W32HANDLE_CAP_SPECIAL_WAIT));
854 memset (&process_handle, 0, sizeof (process_handle));
855 process_handle.pid = wapi_getpid ();
856 process_set_defaults (&process_handle);
857 process_set_name (&process_handle);
859 current_process = mono_w32handle_new (MONO_W32HANDLE_PROCESS, &process_handle);
860 g_assert (current_process);
862 mono_os_mutex_init (&processes_mutex);
866 mono_w32process_cleanup (void)
868 g_free (cli_launcher);
871 /* Check if a pid is valid - i.e. if a process exists with this pid. */
873 is_pid_valid (pid_t pid)
875 gboolean result = FALSE;
877 #if defined(HOST_WATCHOS)
878 result = TRUE; // TODO: Rewrite using sysctl
879 #elif defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__)
880 if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
882 #elif defined(__HAIKU__)
884 if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
887 char *dir = g_strdup_printf ("/proc/%d", pid);
888 if (!access (dir, F_OK))
897 len16 (const gunichar2 *str)
908 utf16_concat (const gunichar2 *first, ...)
916 va_start (args, first);
917 total += len16 (first);
918 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *))
922 ret = g_new (gunichar2, total + 1);
928 for (s = first; *s != 0; s++)
930 va_start (args, first);
931 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
932 for (p = s; *p != 0; p++)
941 mono_w32process_get_pid (gpointer handle)
943 MonoW32HandleProcess *process_handle;
946 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle)) {
947 /* This is a pseudo handle */
948 return WAPI_HANDLE_TO_PID (handle);
951 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
953 SetLastError (ERROR_INVALID_HANDLE);
957 return process_handle->pid;
963 } GetProcessForeachData;
966 get_process_foreach_callback (gpointer handle, gpointer handle_specific, gpointer user_data)
968 GetProcessForeachData *foreach_data;
969 MonoW32HandleProcess *process_handle;
972 foreach_data = (GetProcessForeachData*) user_data;
974 if (mono_w32handle_get_type (handle) != MONO_W32HANDLE_PROCESS)
977 g_assert (!WAPI_IS_PSEUDO_PROCESS_HANDLE (handle));
979 process_handle = (MonoW32HandleProcess*) handle_specific;
981 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking at process %d", __func__, process_handle->pid);
983 pid = process_handle->pid;
987 /* It's possible to have more than one process handle with the
988 * same pid, but only the one running process can be
990 if (foreach_data->pid != pid)
992 if (mono_w32handle_issignalled (handle))
995 mono_w32handle_ref (handle);
996 foreach_data->handle = handle;
1001 ves_icall_System_Diagnostics_Process_GetProcess_internal (guint32 pid)
1003 GetProcessForeachData foreach_data;
1006 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking for process %d", __func__, pid);
1008 memset (&foreach_data, 0, sizeof (foreach_data));
1009 foreach_data.pid = pid;
1010 mono_w32handle_foreach (get_process_foreach_callback, &foreach_data);
1011 handle = foreach_data.handle;
1013 /* get_process_foreach_callback already added a ref */
1017 if (is_pid_valid (pid)) {
1018 /* Return a pseudo handle for processes we don't have handles for */
1019 return WAPI_PID_TO_HANDLE (pid);
1022 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find pid %d", __func__, pid);
1024 SetLastError (ERROR_PROC_NOT_FOUND);
1029 match_procname_to_modulename (char *procname, char *modulename)
1031 char* lastsep = NULL;
1032 char* lastsep2 = NULL;
1035 gboolean result = FALSE;
1037 if (procname == NULL || modulename == NULL)
1040 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: procname=\"%s\", modulename=\"%s\"", __func__, procname, modulename);
1041 pname = mono_path_resolve_symlinks (procname);
1042 mname = mono_path_resolve_symlinks (modulename);
1044 if (!strcmp (pname, mname))
1048 lastsep = strrchr (mname, '/');
1050 if (!strcmp (lastsep+1, pname))
1053 lastsep2 = strrchr (pname, '/');
1056 if (!strcmp (lastsep+1, lastsep2+1))
1059 if (!strcmp (mname, lastsep2+1))
1069 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: result is %d", __func__, result);
1074 mono_w32process_try_get_modules (gpointer process, gpointer *modules, guint32 size, guint32 *needed)
1076 MonoW32HandleProcess *process_handle;
1077 GSList *mods = NULL, *mods_iter;
1078 MonoW32ProcessModule *module;
1079 guint32 count, avail = size / sizeof(gpointer);
1085 /* Store modules in an array of pointers (main module as
1086 * modules[0]), using the load address for each module as a
1087 * token. (Use 'NULL' as an alternative for the main module
1088 * so that the simple implementation can just return one item
1089 * for now.) Get the info from /proc/<pid>/maps on linux,
1090 * /proc/<pid>/map on FreeBSD, other systems will have to
1091 * implement /dev/kmem reading or whatever other horrid
1092 * technique is needed.
1094 if (size < sizeof(gpointer))
1097 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1098 pid = WAPI_HANDLE_TO_PID (process);
1099 pname = mono_w32process_get_name (pid);
1101 res = mono_w32handle_lookup (process, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
1103 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
1107 pid = process_handle->pid;
1108 pname = g_strdup (process_handle->pname);
1113 *needed = sizeof(gpointer);
1117 mods = mono_w32process_get_modules (pid);
1120 *needed = sizeof(gpointer);
1128 * Use the NULL shortcut, as the first line in
1129 * /proc/<pid>/maps isn't the executable, and we need
1130 * that first in the returned list. Check the module name
1131 * to see if it ends with the proc name and substitute
1132 * the first entry with it. FIXME if this turns out to
1137 for (i = 0; mods_iter; i++) {
1138 if (i < avail - 1) {
1139 module = (MonoW32ProcessModule *)mods_iter->data;
1140 if (modules[0] != NULL)
1141 modules[i] = module->address_start;
1142 else if (match_procname_to_modulename (pname, module->filename))
1143 modules[0] = module->address_start;
1145 modules[i + 1] = module->address_start;
1147 mono_w32process_module_free ((MonoW32ProcessModule *)mods_iter->data);
1148 mods_iter = g_slist_next (mods_iter);
1152 /* count + 1 to leave slot 0 for the main module */
1153 *needed = sizeof(gpointer) * (count + 1);
1155 g_slist_free (mods);
1162 mono_w32process_module_get_filename (gpointer process, gpointer module, gunichar2 *basename, guint32 size)
1167 gunichar2 *proc_path;
1169 size *= sizeof (gunichar2); /* adjust for unicode characters */
1171 if (basename == NULL || size == 0)
1174 pid = mono_w32process_get_pid (process);
1176 path = mono_w32process_get_path (pid);
1180 proc_path = mono_unicode_from_external (path, &bytes);
1183 if (proc_path == NULL)
1188 /* Add the terminator */
1192 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
1193 memcpy (basename, proc_path, size);
1195 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %d larger than needed (%ld)", __func__, size, bytes);
1196 memcpy (basename, proc_path, bytes);
1205 mono_w32process_module_get_name (gpointer process, gpointer module, gunichar2 *basename, guint32 size)
1207 MonoW32HandleProcess *process_handle;
1209 gunichar2 *procname;
1210 char *procname_ext = NULL;
1213 GSList *mods = NULL, *mods_iter;
1214 MonoW32ProcessModule *found_module;
1218 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Getting module base name, process handle %p module %p",
1219 __func__, process, module);
1221 size = size * sizeof (gunichar2); /* adjust for unicode characters */
1223 if (basename == NULL || size == 0)
1226 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1227 /* This is a pseudo handle */
1228 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
1229 pname = mono_w32process_get_name (pid);
1231 res = mono_w32handle_lookup (process, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
1233 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
1237 pid = process_handle->pid;
1238 pname = g_strdup (process_handle->pname);
1241 mods = mono_w32process_get_modules (pid);
1247 /* If module != NULL compare the address.
1248 * If module == NULL we are looking for the main module.
1249 * The best we can do for now check it the module name end with the process name.
1251 for (mods_iter = mods; mods_iter; mods_iter = g_slist_next (mods_iter)) {
1252 found_module = (MonoW32ProcessModule *)mods_iter->data;
1253 if (procname_ext == NULL &&
1254 ((module == NULL && match_procname_to_modulename (pname, found_module->filename)) ||
1255 (module != NULL && found_module->address_start == module))) {
1256 procname_ext = g_path_get_basename (found_module->filename);
1259 mono_w32process_module_free (found_module);
1262 if (procname_ext == NULL) {
1263 /* If it's *still* null, we might have hit the
1264 * case where reading /proc/$pid/maps gives an
1265 * empty file for this user.
1267 procname_ext = mono_w32process_get_name (pid);
1270 g_slist_free (mods);
1274 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Process name is [%s]", __func__,
1277 procname = mono_unicode_from_external (procname_ext, &bytes);
1278 if (procname == NULL) {
1280 g_free (procname_ext);
1286 /* Add the terminator */
1290 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
1292 memcpy (basename, procname, size);
1294 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Size %d larger than needed (%ld)",
1295 __func__, size, bytes);
1297 memcpy (basename, procname, bytes);
1301 g_free (procname_ext);
1310 mono_w32process_module_get_information (gpointer process, gpointer module, MODULEINFO *modinfo, guint32 size)
1312 MonoW32HandleProcess *process_handle;
1314 GSList *mods = NULL, *mods_iter;
1315 MonoW32ProcessModule *found_module;
1316 gboolean ret = FALSE;
1320 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Getting module info, process handle %p module %p",
1321 __func__, process, module);
1323 if (modinfo == NULL || size < sizeof (MODULEINFO))
1326 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1327 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
1328 pname = mono_w32process_get_name (pid);
1330 res = mono_w32handle_lookup (process, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
1332 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, process);
1336 pid = process_handle->pid;
1337 pname = g_strdup (process_handle->pname);
1340 mods = mono_w32process_get_modules (pid);
1346 /* If module != NULL compare the address.
1347 * If module == NULL we are looking for the main module.
1348 * The best we can do for now check it the module name end with the process name.
1350 for (mods_iter = mods; mods_iter; mods_iter = g_slist_next (mods_iter)) {
1351 found_module = (MonoW32ProcessModule *)mods_iter->data;
1353 ((module == NULL && match_procname_to_modulename (pname, found_module->filename)) ||
1354 (module != NULL && found_module->address_start == module))) {
1355 modinfo->lpBaseOfDll = found_module->address_start;
1356 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
1357 modinfo->EntryPoint = found_module->address_offset;
1361 mono_w32process_module_free (found_module);
1364 g_slist_free (mods);
1371 switch_dir_separators (char *path)
1373 size_t i, pathLength = strlen(path);
1375 /* Turn all the slashes round the right way, except for \' */
1376 /* There are probably other characters that need to be excluded as well. */
1377 for (i = 0; i < pathLength; i++) {
1378 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' )
1385 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
1393 pid = waitpid (-1, &status, WNOHANG);
1394 } while (pid == -1 && errno == EINTR);
1400 * This can run concurrently with the code in the rest of this module.
1402 for (p = processes; p; p = p->next) {
1406 p->pid = 0; /* this pid doesn't exist anymore, clear it */
1408 mono_os_sem_post (&p->exit_sem);
1409 mono_memory_barrier ();
1410 /* Mark this as freeable, the pointer becomes invalid afterwards */
1418 process_add_sigchld_handler (void)
1420 struct sigaction sa;
1422 sa.sa_sigaction = mono_sigchld_signal_handler;
1423 sigemptyset (&sa.sa_mask);
1424 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
1425 g_assert (sigaction (SIGCHLD, &sa, NULL) != -1);
1426 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "Added SIGCHLD handler");
1432 is_readable_or_executable (const char *prog)
1435 int a = access (prog, R_OK);
1436 int b = access (prog, X_OK);
1437 if (a != 0 && b != 0)
1439 if (stat (prog, &buf))
1441 if (S_ISREG (buf.st_mode))
1447 is_executable (const char *prog)
1450 if (access (prog, X_OK) != 0)
1452 if (stat (prog, &buf))
1454 if (S_ISREG (buf.st_mode))
1460 is_managed_binary (const char *filename)
1462 int original_errno = errno;
1463 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
1464 int file = open (filename, O_RDONLY | O_LARGEFILE);
1466 int file = open (filename, O_RDONLY);
1469 unsigned char buffer[8];
1470 off_t file_size, optional_header_offset;
1471 off_t pe_header_offset, clr_header_offset;
1472 gboolean managed = FALSE;
1474 guint32 first_word, second_word, magic_number;
1476 /* If we are unable to open the file, then we definitely
1477 * can't say that it is managed. The child mono process
1478 * probably wouldn't be able to open it anyway.
1481 errno = original_errno;
1485 /* Retrieve the length of the file for future sanity checks. */
1486 file_size = lseek (file, 0, SEEK_END);
1487 lseek (file, 0, SEEK_SET);
1489 /* We know we need to read a header field at offset 60. */
1493 num_read = read (file, buffer, 2);
1495 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
1498 new_offset = lseek (file, 60, SEEK_SET);
1500 if (new_offset != 60)
1503 num_read = read (file, buffer, 4);
1507 pe_header_offset = buffer[0]
1510 | (buffer[3] << 24);
1512 if (pe_header_offset + 24 > file_size)
1515 new_offset = lseek (file, pe_header_offset, SEEK_SET);
1517 if (new_offset != pe_header_offset)
1520 num_read = read (file, buffer, 4);
1522 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
1526 * Verify that the header we want in the optional header data
1527 * is present in this binary.
1529 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
1531 if (new_offset != pe_header_offset + 20)
1534 num_read = read (file, buffer, 2);
1536 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
1539 optional_header_offset = pe_header_offset + 24;
1541 /* Read the PE magic number */
1542 new_offset = lseek (file, optional_header_offset, SEEK_SET);
1544 if (new_offset != optional_header_offset)
1547 num_read = read (file, buffer, 2);
1552 magic_number = (buffer[0] | (buffer[1] << 8));
1554 if (magic_number == 0x10B) // PE32
1555 clr_header_offset = 208;
1556 else if (magic_number == 0x20B) // PE32+
1557 clr_header_offset = 224;
1561 /* Read the CLR header address and size fields. These will be
1562 * zero if the binary is not managed.
1564 new_offset = lseek (file, optional_header_offset + clr_header_offset, SEEK_SET);
1566 if (new_offset != optional_header_offset + clr_header_offset)
1569 num_read = read (file, buffer, 8);
1571 /* We are not concerned with endianness, only with
1572 * whether it is zero or not.
1574 first_word = *(guint32 *)&buffer[0];
1575 second_word = *(guint32 *)&buffer[4];
1577 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
1584 errno = original_errno;
1589 process_create (const gunichar2 *appname, const gunichar2 *cmdline,
1590 const gunichar2 *cwd, StartupHandles *startup_handles, MonoW32ProcessInfo *process_info)
1592 #if defined (HAVE_FORK) && defined (HAVE_EXECVE)
1593 char *cmd = NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL;
1594 char *dir = NULL, **env_strings = NULL, **argv = NULL;
1596 gboolean ret = FALSE;
1597 gpointer handle = NULL;
1598 GError *gerr = NULL;
1599 int in_fd, out_fd, err_fd;
1601 int startup_pipe [2] = {-1, -1};
1603 MonoProcess *mono_process;
1606 mono_lazy_initialize (&process_sig_chld_once, process_add_sigchld_handler);
1609 /* appname and cmdline specify the executable and its args:
1611 * If appname is not NULL, it is the name of the executable.
1612 * Otherwise the executable is the first token in cmdline.
1614 * Executable searching:
1616 * If appname is not NULL, it can specify the full path and
1617 * file name, or else a partial name and the current directory
1618 * will be used. There is no additional searching.
1620 * If appname is NULL, the first whitespace-delimited token in
1621 * cmdline is used. If the name does not contain a full
1622 * directory path, the search sequence is:
1624 * 1) The directory containing the current process
1625 * 2) The current working directory
1626 * 3) The windows system directory (Ignored)
1627 * 4) The windows directory (Ignored)
1630 * Just to make things more interesting, tokens can contain
1631 * white space if they are surrounded by quotation marks. I'm
1632 * beginning to understand just why windows apps are generally
1633 * so crap, with an API like this :-(
1635 if (appname != NULL) {
1636 cmd = mono_unicode_to_external (appname);
1638 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL",
1641 SetLastError (ERROR_PATH_NOT_FOUND);
1645 switch_dir_separators(cmd);
1648 if (cmdline != NULL) {
1649 args = mono_unicode_to_external (cmdline);
1651 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1653 SetLastError (ERROR_PATH_NOT_FOUND);
1659 dir = mono_unicode_to_external (cwd);
1661 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1663 SetLastError (ERROR_PATH_NOT_FOUND);
1667 /* Turn all the slashes round the right way */
1668 switch_dir_separators(dir);
1672 /* We can't put off locating the executable any longer :-( */
1675 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
1676 /* Strip off the drive letter. I can't
1677 * believe that CP/M holdover is still
1680 g_memmove (cmd, cmd+2, strlen (cmd)-2);
1681 cmd[strlen (cmd)-2] = '\0';
1684 unquoted = g_shell_unquote (cmd, NULL);
1685 if (unquoted[0] == '/') {
1686 /* Assume full path given */
1687 prog = g_strdup (unquoted);
1689 /* Executable existing ? */
1690 if (!is_readable_or_executable (prog)) {
1691 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s",
1694 SetLastError (ERROR_FILE_NOT_FOUND);
1698 /* Search for file named by cmd in the current
1701 char *curdir = g_get_current_dir ();
1703 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
1706 /* And make sure it's readable */
1707 if (!is_readable_or_executable (prog)) {
1708 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s",
1711 SetLastError (ERROR_FILE_NOT_FOUND);
1717 args_after_prog = args;
1722 /* Dig out the first token from args, taking quotation
1723 * marks into account
1726 /* First, strip off all leading whitespace */
1727 args = g_strchug (args);
1729 /* args_after_prog points to the contents of args
1730 * after token has been set (otherwise argv[0] is
1733 args_after_prog = args;
1735 /* Assume the opening quote will always be the first
1738 if (args[0] == '\"' || args [0] == '\'') {
1740 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
1741 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
1742 /* We found the first token */
1743 token = g_strndup (args+1, i-1);
1744 args_after_prog = g_strchug (args + i + 1);
1746 /* Quotation mark appeared in the
1747 * middle of the token. Just give the
1748 * whole first token, quotes and all,
1754 if (token == NULL) {
1755 /* No quote mark, or malformed */
1756 for (i = 0; args[i] != '\0'; i++) {
1757 if (g_ascii_isspace (args[i])) {
1758 token = g_strndup (args, i);
1759 args_after_prog = args + i + 1;
1765 if (token == NULL && args[0] != '\0') {
1766 /* Must be just one token in the string */
1767 token = g_strdup (args);
1768 args_after_prog = NULL;
1771 if (token == NULL) {
1773 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find what to exec", __func__);
1775 SetLastError (ERROR_PATH_NOT_FOUND);
1779 /* Turn all the slashes round the right way. Only for
1782 switch_dir_separators(token);
1784 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
1785 /* Strip off the drive letter. I can't
1786 * believe that CP/M holdover is still
1789 g_memmove (token, token+2, strlen (token)-2);
1790 token[strlen (token)-2] = '\0';
1793 if (token[0] == '/') {
1794 /* Assume full path given */
1795 prog = g_strdup (token);
1797 /* Executable existing ? */
1798 if (!is_readable_or_executable (prog)) {
1799 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s",
1802 SetLastError (ERROR_FILE_NOT_FOUND);
1806 char *curdir = g_get_current_dir ();
1808 /* FIXME: Need to record the directory
1809 * containing the current process, and check
1810 * that for the new executable as the first
1814 prog = g_strdup_printf ("%s/%s", curdir, token);
1817 /* I assume X_OK is the criterion to use,
1820 * X_OK is too strict *if* the target is a CLR binary
1822 if (!is_readable_or_executable (prog)) {
1824 prog = g_find_program_in_path (token);
1826 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s", __func__, token);
1829 SetLastError (ERROR_FILE_NOT_FOUND);
1838 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Exec prog [%s] args [%s]",
1839 __func__, prog, args_after_prog);
1841 /* Check for CLR binaries; if found, we will try to invoke
1842 * them using the same mono binary that started us.
1844 if (is_managed_binary (prog)) {
1845 gunichar2 *newapp, *newcmd;
1846 gsize bytes_ignored;
1848 newapp = mono_unicode_from_external (cli_launcher ? cli_launcher : "mono", &bytes_ignored);
1851 newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space, appname, utf16_space, cmdline, NULL);
1853 newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space, cmdline, NULL);
1858 ret = process_create (NULL, newcmd, cwd, startup_handles, process_info);
1866 if (!is_executable (prog)) {
1867 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Executable permisson not set on %s", __func__, prog);
1868 SetLastError (ERROR_ACCESS_DENIED);
1873 if (args_after_prog != NULL && *args_after_prog) {
1876 qprog = g_shell_quote (prog);
1877 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
1880 full_prog = g_shell_quote (prog);
1883 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
1885 g_message ("process_create: %s\n", gerr->message);
1886 g_error_free (gerr);
1891 if (startup_handles) {
1892 in_fd = GPOINTER_TO_UINT (startup_handles->input);
1893 out_fd = GPOINTER_TO_UINT (startup_handles->output);
1894 err_fd = GPOINTER_TO_UINT (startup_handles->error);
1896 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
1897 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
1898 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
1902 * process->env_variables is a an array of MonoString*
1904 * If new_environ is not NULL it specifies the entire set of
1905 * environment variables in the new process. Otherwise the
1906 * new process inherits the same environment.
1908 if (process_info->env_variables) {
1909 gint i, str_length, var_length;
1913 /* +2: one for the process handle value, and the last one is NULL */
1914 env_strings = g_new0 (gchar*, mono_array_length (process_info->env_variables) + 2);
1919 /* Copy each environ string into 'strings' turning it into utf8 (or the requested encoding) at the same time */
1920 for (i = 0; i < mono_array_length (process_info->env_variables); ++i) {
1921 var = mono_array_get (process_info->env_variables, MonoString*, i);
1922 var_length = mono_string_length (var);
1924 /* str is a null-terminated copy of var */
1926 if (var_length + 1 > str_length) {
1927 str_length = var_length + 1;
1928 str = g_renew (gunichar2, str, str_length);
1931 memcpy (str, mono_string_chars (var), var_length * sizeof (gunichar2));
1932 str [var_length] = '\0';
1934 env_strings [i] = mono_unicode_to_external (str);
1942 for (i = 0; environ[i] != NULL; i++)
1945 /* +2: one for the process handle value, and the last one is NULL */
1946 env_strings = g_new0 (gchar*, env_count + 2);
1948 /* Copy each environ string into 'strings' turning it into utf8 (or the requested encoding) at the same time */
1949 for (i = 0; i < env_count; i++)
1950 env_strings [i] = g_strdup (environ[i]);
1953 /* Create a pipe to make sure the child doesn't exit before
1954 * we can add the process to the linked list of processes */
1955 if (pipe (startup_pipe) == -1) {
1956 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
1957 * This is just for a very hard to hit race condition in the first place */
1958 startup_pipe [0] = startup_pipe [1] = -1;
1959 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
1963 /* FIXME: block SIGCHLD */
1966 switch (pid = fork ()) {
1967 case -1: /* Error */ {
1968 SetLastError (ERROR_OUTOFMEMORY);
1972 case 0: /* Child */ {
1973 if (startup_pipe [0] != -1) {
1974 /* Wait until the parent has updated it's internal data */
1975 ssize_t _i G_GNUC_UNUSED = read (startup_pipe [0], &dummy, 1);
1976 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: child: parent has completed its setup", __func__);
1977 close (startup_pipe [0]);
1978 close (startup_pipe [1]);
1981 /* should we detach from the process group? */
1983 /* Connect stdin, stdout and stderr */
1988 /* Close all file descriptors */
1989 for (i = mono_w32handle_fd_reserve - 1; i > 2; i--)
1992 #ifdef DEBUG_ENABLED
1993 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1994 dir == NULL?".":dir);
1995 for (i = 0; argv[i] != NULL; i++)
1996 g_message ("arg %d: [%s]", i, argv[i]);
1998 for (i = 0; env_strings[i] != NULL; i++)
1999 g_message ("env %d: [%s]", i, env_strings[i]);
2003 if (dir != NULL && chdir (dir) == -1) {
2009 execve (argv[0], argv, env_strings);
2016 default: /* Parent */ {
2017 MonoW32HandleProcess process_handle;
2019 memset (&process_handle, 0, sizeof (process_handle));
2020 process_handle.pid = pid;
2021 process_handle.pname = g_strdup (prog);
2022 process_set_defaults (&process_handle);
2024 /* Add our mono_process into the linked list of processes */
2025 mono_process = (MonoProcess *) g_malloc0 (sizeof (MonoProcess));
2026 mono_process->pid = pid;
2027 mono_process->handle_count = 1;
2028 mono_os_sem_init (&mono_process->exit_sem, 0);
2030 process_handle.mono_process = mono_process;
2032 handle = mono_w32handle_new (MONO_W32HANDLE_PROCESS, &process_handle);
2033 if (handle == INVALID_HANDLE_VALUE) {
2034 g_warning ("%s: error creating process handle", __func__);
2036 mono_os_sem_destroy (&mono_process->exit_sem);
2037 g_free (mono_process);
2039 SetLastError (ERROR_OUTOFMEMORY);
2044 /* Keep the process handle artificially alive until the process
2045 * exits so that the information in the handle isn't lost. */
2046 mono_w32handle_ref (handle);
2047 mono_process->handle = handle;
2049 mono_os_mutex_lock (&processes_mutex);
2050 mono_process->next = processes;
2051 processes = mono_process;
2052 mono_os_mutex_unlock (&processes_mutex);
2054 if (process_info != NULL) {
2055 process_info->process_handle = handle;
2056 process_info->pid = pid;
2058 /* FIXME: we might need to handle the thread info some day */
2059 process_info->thread_handle = INVALID_HANDLE_VALUE;
2060 process_info->tid = 0;
2068 /* FIXME: unblock SIGCHLD */
2071 if (startup_pipe [1] != -1) {
2072 /* Write 1 byte, doesn't matter what */
2073 ssize_t _i G_GNUC_UNUSED = write (startup_pipe [1], startup_pipe, 1);
2074 close (startup_pipe [0]);
2075 close (startup_pipe [1]);
2090 g_strfreev (env_strings);
2094 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: returning handle %p for pid %d", __func__, handle, pid);
2096 /* Check if something needs to be cleaned up. */
2097 processes_cleanup ();
2101 SetLastError (ERROR_NOT_SUPPORTED);
2103 #endif // defined (HAVE_FORK) && defined (HAVE_EXECVE)
2107 ves_icall_System_Diagnostics_Process_ShellExecuteEx_internal (MonoW32ProcessStartInfo *proc_start_info, MonoW32ProcessInfo *process_info)
2109 const gunichar2 *lpFile;
2110 const gunichar2 *lpParameters;
2111 const gunichar2 *lpDirectory;
2115 if (!proc_start_info->filename) {
2116 /* w2k returns TRUE for this, for some reason. */
2121 lpFile = proc_start_info->filename ? mono_string_chars (proc_start_info->filename) : NULL;
2122 lpParameters = proc_start_info->arguments ? mono_string_chars (proc_start_info->arguments) : NULL;
2123 lpDirectory = proc_start_info->working_directory && mono_string_length (proc_start_info->working_directory) != 0 ?
2124 mono_string_chars (proc_start_info->working_directory) : NULL;
2126 /* Put both executable and parameters into the second argument
2127 * to process_create (), so it searches $PATH. The conversion
2128 * into and back out of utf8 is because there is no
2129 * g_strdup_printf () equivalent for gunichar2 :-(
2131 args = utf16_concat (utf16_quote, lpFile, utf16_quote, lpParameters == NULL ? NULL : utf16_space, lpParameters, NULL);
2133 SetLastError (ERROR_INVALID_DATA);
2137 ret = process_create (NULL, args, lpDirectory, NULL, process_info);
2140 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
2144 static char *handler;
2145 static gunichar2 *handler_utf16;
2147 if (handler_utf16 == (gunichar2 *)-1) {
2152 #ifdef PLATFORM_MACOSX
2153 handler = g_strdup ("/usr/bin/open");
2156 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
2157 * if that fails, try to use gnome-open, then kfmclient
2159 handler = g_find_program_in_path ("xdg-open");
2160 if (handler == NULL){
2161 handler = g_find_program_in_path ("gnome-open");
2162 if (handler == NULL){
2163 handler = g_find_program_in_path ("kfmclient");
2164 if (handler == NULL){
2165 handler_utf16 = (gunichar2 *) -1;
2169 /* kfmclient needs exec argument */
2170 char *old = handler;
2171 handler = g_strconcat (old, " exec",
2178 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
2181 /* Put quotes around the filename, in case it's a url
2182 * that contains #'s (process_create() calls
2183 * g_shell_parse_argv(), which deliberately throws
2184 * away anything after an unquoted #). Fixes bug
2187 args = utf16_concat (handler_utf16, utf16_space, utf16_quote, lpFile, utf16_quote,
2188 lpParameters == NULL ? NULL : utf16_space, lpParameters, NULL);
2190 SetLastError (ERROR_INVALID_DATA);
2194 ret = process_create (NULL, args, lpDirectory, NULL, process_info);
2197 if (GetLastError () != ERROR_OUTOFMEMORY)
2198 SetLastError (ERROR_INVALID_DATA);
2202 /* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
2203 CloseHandle (process_info->process_handle);
2204 process_info->process_handle = NULL;
2209 process_info->pid = -GetLastError ();
2211 process_info->thread_handle = NULL;
2212 #if !defined(MONO_CROSS_COMPILE)
2213 process_info->pid = mono_w32process_get_pid (process_info->process_handle);
2215 process_info->pid = 0;
2217 process_info->tid = 0;
2223 /* Only used when UseShellExecute is false */
2225 process_get_complete_path (const gunichar2 *appname, gchar **completed)
2230 utf8app = g_utf16_to_utf8 (appname, -1, NULL, NULL, NULL);
2232 if (g_path_is_absolute (utf8app)) {
2233 *completed = g_shell_quote (utf8app);
2238 if (g_file_test (utf8app, G_FILE_TEST_IS_EXECUTABLE) && !g_file_test (utf8app, G_FILE_TEST_IS_DIR)) {
2239 *completed = g_shell_quote (utf8app);
2244 found = g_find_program_in_path (utf8app);
2245 if (found == NULL) {
2251 *completed = g_shell_quote (found);
2258 process_get_shell_arguments (MonoW32ProcessStartInfo *proc_start_info, gunichar2 **shell_path)
2260 gchar *complete_path = NULL;
2264 if (process_get_complete_path (mono_string_chars (proc_start_info->filename), &complete_path)) {
2265 *shell_path = g_utf8_to_utf16 (complete_path, -1, NULL, NULL, NULL);
2266 g_free (complete_path);
2269 return *shell_path != NULL;
2273 ves_icall_System_Diagnostics_Process_CreateProcess_internal (MonoW32ProcessStartInfo *proc_start_info,
2274 HANDLE stdin_handle, HANDLE stdout_handle, HANDLE stderr_handle, MonoW32ProcessInfo *process_info)
2278 StartupHandles startup_handles;
2279 gunichar2 *shell_path = NULL;
2280 gunichar2 *args = NULL;
2282 memset (&startup_handles, 0, sizeof (startup_handles));
2283 startup_handles.input = stdin_handle;
2284 startup_handles.output = stdout_handle;
2285 startup_handles.error = stderr_handle;
2287 if (!process_get_shell_arguments (proc_start_info, &shell_path)) {
2288 process_info->pid = -ERROR_FILE_NOT_FOUND;
2292 args = proc_start_info->arguments && mono_string_length (proc_start_info->arguments) > 0 ?
2293 mono_string_chars (proc_start_info->arguments): NULL;
2295 /* The default dir name is "". Turn that into NULL to mean "current directory" */
2296 dir = proc_start_info->working_directory && mono_string_length (proc_start_info->working_directory) > 0 ?
2297 mono_string_chars (proc_start_info->working_directory) : NULL;
2299 ret = process_create (shell_path, args, dir, &startup_handles, process_info);
2301 if (shell_path != NULL)
2302 g_free (shell_path);
2305 process_info->pid = -GetLastError ();
2310 /* Returns an array of pids */
2312 ves_icall_System_Diagnostics_Process_GetProcesses_internal (void)
2319 pidarray = mono_process_list (&count);
2321 mono_set_pending_exception (mono_get_exception_not_supported ("This system does not support EnumProcesses"));
2324 procs = mono_array_new_checked (mono_domain_get (), mono_get_int32_class (), count, &error);
2325 if (mono_error_set_pending_exception (&error)) {
2329 if (sizeof (guint32) == sizeof (gpointer)) {
2330 memcpy (mono_array_addr (procs, guint32, 0), pidarray, count * sizeof (gint32));
2332 for (i = 0; i < count; ++i)
2333 *(mono_array_addr (procs, guint32, i)) = GPOINTER_TO_UINT (pidarray [i]);
2341 mono_w32process_set_cli_launcher (gchar *path)
2343 g_free (cli_launcher);
2344 cli_launcher = g_strdup (path);
2348 ves_icall_Microsoft_Win32_NativeMethods_GetCurrentProcess (void)
2350 mono_w32handle_ref (current_process);
2351 return current_process;
2355 ves_icall_Microsoft_Win32_NativeMethods_GetExitCodeProcess (gpointer handle, gint32 *exitcode)
2357 MonoW32HandleProcess *process_handle;
2364 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle)) {
2365 pid = WAPI_HANDLE_TO_PID (handle);
2366 /* This is a pseudo handle, so we don't know what the exit
2367 * code was, but we can check whether it's alive or not */
2368 if (is_pid_valid (pid)) {
2369 *exitcode = STILL_ACTIVE;
2377 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2379 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2383 if (process_handle->pid == wapi_getpid ()) {
2384 *exitcode = STILL_ACTIVE;
2388 /* A process handle is only signalled if the process has exited
2389 * and has been waited for. Make sure any process exit has been
2390 * noticed before checking if the process is signalled.
2391 * Fixes bug 325463. */
2392 mono_w32handle_wait_one (handle, 0, TRUE);
2394 *exitcode = mono_w32handle_issignalled (handle) ? process_handle->exitstatus : STILL_ACTIVE;
2399 ves_icall_Microsoft_Win32_NativeMethods_CloseProcess (gpointer handle)
2401 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
2403 return CloseHandle (handle);
2407 ves_icall_Microsoft_Win32_NativeMethods_TerminateProcess (gpointer handle, gint32 exitcode)
2410 MonoW32HandleProcess *process_handle;
2414 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle)) {
2415 /* This is a pseudo handle */
2416 pid = (pid_t)WAPI_HANDLE_TO_PID (handle);
2420 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2422 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2423 SetLastError (ERROR_INVALID_HANDLE);
2427 pid = process_handle->pid;
2430 ret = kill (pid, exitcode == -1 ? SIGKILL : SIGTERM);
2435 case EINVAL: SetLastError (ERROR_INVALID_PARAMETER); break;
2436 case EPERM: SetLastError (ERROR_ACCESS_DENIED); break;
2437 case ESRCH: SetLastError (ERROR_PROC_NOT_FOUND); break;
2438 default: SetLastError (ERROR_GEN_FAILURE); break;
2443 g_error ("kill() is not supported by this platform");
2448 ves_icall_Microsoft_Win32_NativeMethods_GetProcessWorkingSetSize (gpointer handle, gsize *min, gsize *max)
2450 MonoW32HandleProcess *process_handle;
2456 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
2459 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2461 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2465 *min = process_handle->min_working_set;
2466 *max = process_handle->max_working_set;
2471 ves_icall_Microsoft_Win32_NativeMethods_SetProcessWorkingSetSize (gpointer handle, gsize min, gsize max)
2473 MonoW32HandleProcess *process_handle;
2476 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
2479 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2481 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2485 process_handle->min_working_set = min;
2486 process_handle->max_working_set = max;
2491 ves_icall_Microsoft_Win32_NativeMethods_GetPriorityClass (gpointer handle)
2493 #ifdef HAVE_GETPRIORITY
2494 MonoW32HandleProcess *process_handle;
2498 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle)) {
2499 /* This is a pseudo handle */
2500 pid = (pid_t)WAPI_HANDLE_TO_PID (handle);
2504 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2506 SetLastError (ERROR_INVALID_HANDLE);
2510 pid = process_handle->pid;
2514 ret = getpriority (PRIO_PROCESS, pid);
2515 if (ret == -1 && errno != 0) {
2519 SetLastError (ERROR_ACCESS_DENIED);
2522 SetLastError (ERROR_PROC_NOT_FOUND);
2525 SetLastError (ERROR_GEN_FAILURE);
2531 return MONO_W32PROCESS_PRIORITY_CLASS_NORMAL;
2533 return MONO_W32PROCESS_PRIORITY_CLASS_REALTIME;
2535 return MONO_W32PROCESS_PRIORITY_CLASS_HIGH;
2537 return MONO_W32PROCESS_PRIORITY_CLASS_ABOVE_NORMAL;
2539 return MONO_W32PROCESS_PRIORITY_CLASS_IDLE;
2541 return MONO_W32PROCESS_PRIORITY_CLASS_BELOW_NORMAL;
2543 return MONO_W32PROCESS_PRIORITY_CLASS_NORMAL;
2545 SetLastError (ERROR_NOT_SUPPORTED);
2551 ves_icall_Microsoft_Win32_NativeMethods_SetPriorityClass (gpointer handle, gint32 priorityClass)
2553 #ifdef HAVE_SETPRIORITY
2554 MonoW32HandleProcess *process_handle;
2559 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle)) {
2560 /* This is a pseudo handle */
2561 pid = (pid_t)WAPI_HANDLE_TO_PID (handle);
2565 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2567 SetLastError (ERROR_INVALID_HANDLE);
2571 pid = process_handle->pid;
2574 switch (priorityClass) {
2575 case MONO_W32PROCESS_PRIORITY_CLASS_IDLE:
2578 case MONO_W32PROCESS_PRIORITY_CLASS_BELOW_NORMAL:
2581 case MONO_W32PROCESS_PRIORITY_CLASS_NORMAL:
2584 case MONO_W32PROCESS_PRIORITY_CLASS_ABOVE_NORMAL:
2587 case MONO_W32PROCESS_PRIORITY_CLASS_HIGH:
2590 case MONO_W32PROCESS_PRIORITY_CLASS_REALTIME:
2594 SetLastError (ERROR_INVALID_PARAMETER);
2598 ret = setpriority (PRIO_PROCESS, pid, prio);
2603 SetLastError (ERROR_ACCESS_DENIED);
2606 SetLastError (ERROR_PROC_NOT_FOUND);
2609 SetLastError (ERROR_GEN_FAILURE);
2615 SetLastError (ERROR_NOT_SUPPORTED);
2621 ticks_to_processtime (guint64 ticks, ProcessTime *processtime)
2623 processtime->lowDateTime = ticks & 0xFFFFFFFF;
2624 processtime->highDateTime = ticks >> 32;
2628 ves_icall_Microsoft_Win32_NativeMethods_GetProcessTimes (gpointer handle, gint64 *creation_time, gint64 *exit_time, gint64 *kernel_time, gint64 *user_time)
2630 MonoW32HandleProcess *process_handle;
2631 ProcessTime *creation_processtime, *exit_processtime, *kernel_processtime, *user_processtime;
2634 if (!creation_time || !exit_time || !kernel_time || !user_time) {
2635 /* Not sure if w32 allows NULLs here or not */
2639 creation_processtime = (ProcessTime*) creation_time;
2640 exit_processtime = (ProcessTime*) exit_time;
2641 kernel_processtime = (ProcessTime*) kernel_time;
2642 user_processtime = (ProcessTime*) user_time;
2644 memset (creation_processtime, 0, sizeof (ProcessTime));
2645 memset (exit_processtime, 0, sizeof (ProcessTime));
2646 memset (kernel_processtime, 0, sizeof (ProcessTime));
2647 memset (user_processtime, 0, sizeof (ProcessTime));
2649 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle)) {
2650 gint64 start_ticks, user_ticks, kernel_ticks;
2652 mono_process_get_times (GINT_TO_POINTER (WAPI_HANDLE_TO_PID (handle)),
2653 &start_ticks, &user_ticks, &kernel_ticks);
2655 ticks_to_processtime (start_ticks, creation_processtime);
2656 ticks_to_processtime (user_ticks, kernel_processtime);
2657 ticks_to_processtime (kernel_ticks, user_processtime);
2661 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2663 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2667 ticks_to_processtime (process_handle->create_time, creation_processtime);
2669 /* A process handle is only signalled if the process has
2670 * exited, otherwise exit_processtime isn't set */
2671 if (mono_w32handle_issignalled (handle))
2672 ticks_to_processtime (process_handle->exit_time, exit_processtime);
2674 #ifdef HAVE_GETRUSAGE
2675 if (process_handle->pid == getpid ()) {
2676 struct rusage time_data;
2677 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
2678 ticks_to_processtime ((guint64)time_data.ru_utime.tv_sec * 10000000 + (guint64)time_data.ru_utime.tv_usec * 10, user_processtime);
2679 ticks_to_processtime ((guint64)time_data.ru_stime.tv_sec * 10000000 + (guint64)time_data.ru_stime.tv_usec * 10, kernel_processtime);
2687 static IMAGE_SECTION_HEADER *
2688 get_enclosing_section_header (guint32 rva, IMAGE_NT_HEADERS32 *nt_headers)
2690 IMAGE_SECTION_HEADER *section = IMAGE_FIRST_SECTION32 (nt_headers);
2693 for (i = 0; i < GUINT16_FROM_LE (nt_headers->FileHeader.NumberOfSections); i++, section++) {
2694 guint32 size = GUINT32_FROM_LE (section->Misc.VirtualSize);
2696 size = GUINT32_FROM_LE (section->SizeOfRawData);
2699 if ((rva >= GUINT32_FROM_LE (section->VirtualAddress)) &&
2700 (rva < (GUINT32_FROM_LE (section->VirtualAddress) + size))) {
2708 /* This works for both 32bit and 64bit files, as the differences are
2709 * all after the section header block
2712 get_ptr_from_rva (guint32 rva, IMAGE_NT_HEADERS32 *ntheaders, gpointer file_map)
2714 IMAGE_SECTION_HEADER *section_header;
2717 section_header = get_enclosing_section_header (rva, ntheaders);
2718 if (section_header == NULL) {
2722 delta = (guint32)(GUINT32_FROM_LE (section_header->VirtualAddress) -
2723 GUINT32_FROM_LE (section_header->PointerToRawData));
2725 return((guint8 *)file_map + rva - delta);
2729 scan_resource_dir (IMAGE_RESOURCE_DIRECTORY *root, IMAGE_NT_HEADERS32 *nt_headers, gpointer file_map,
2730 IMAGE_RESOURCE_DIRECTORY_ENTRY *entry, int level, guint32 res_id, guint32 lang_id, guint32 *size)
2732 IMAGE_RESOURCE_DIRECTORY_ENTRY swapped_entry;
2733 gboolean is_string, is_dir;
2734 guint32 name_offset, dir_offset, data_offset;
2736 swapped_entry.Name = GUINT32_FROM_LE (entry->Name);
2737 swapped_entry.OffsetToData = GUINT32_FROM_LE (entry->OffsetToData);
2739 is_string = swapped_entry.NameIsString;
2740 is_dir = swapped_entry.DataIsDirectory;
2741 name_offset = swapped_entry.NameOffset;
2742 dir_offset = swapped_entry.OffsetToDirectory;
2743 data_offset = swapped_entry.OffsetToData;
2746 /* Normally holds a directory entry for each type of
2749 if ((is_string == FALSE &&
2750 name_offset != res_id) ||
2751 (is_string == TRUE)) {
2754 } else if (level == 1) {
2755 /* Normally holds a directory entry for each resource
2758 } else if (level == 2) {
2759 /* Normally holds a directory entry for each language
2761 if ((is_string == FALSE &&
2762 name_offset != lang_id &&
2764 (is_string == TRUE)) {
2768 g_assert_not_reached ();
2771 if (is_dir == TRUE) {
2772 IMAGE_RESOURCE_DIRECTORY *res_dir = (IMAGE_RESOURCE_DIRECTORY *)((guint8 *)root + dir_offset);
2773 IMAGE_RESOURCE_DIRECTORY_ENTRY *sub_entries = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(res_dir + 1);
2776 entries = GUINT16_FROM_LE (res_dir->NumberOfNamedEntries) + GUINT16_FROM_LE (res_dir->NumberOfIdEntries);
2778 for (i = 0; i < entries; i++) {
2779 IMAGE_RESOURCE_DIRECTORY_ENTRY *sub_entry = &sub_entries[i];
2782 ret = scan_resource_dir (root, nt_headers, file_map,
2783 sub_entry, level + 1, res_id,
2792 IMAGE_RESOURCE_DATA_ENTRY *data_entry = (IMAGE_RESOURCE_DATA_ENTRY *)((guint8 *)root + data_offset);
2793 *size = GUINT32_FROM_LE (data_entry->Size);
2795 return(get_ptr_from_rva (GUINT32_FROM_LE (data_entry->OffsetToData), nt_headers, file_map));
2800 find_pe_file_resources32 (gpointer file_map, guint32 map_size, guint32 res_id, guint32 lang_id, guint32 *size)
2802 IMAGE_DOS_HEADER *dos_header;
2803 IMAGE_NT_HEADERS32 *nt_headers;
2804 IMAGE_RESOURCE_DIRECTORY *resource_dir;
2805 IMAGE_RESOURCE_DIRECTORY_ENTRY *resource_dir_entry;
2806 guint32 resource_rva, entries, i;
2807 gpointer ret = NULL;
2809 dos_header = (IMAGE_DOS_HEADER *)file_map;
2810 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) {
2811 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Bad dos signature 0x%x", __func__, dos_header->e_magic);
2813 SetLastError (ERROR_INVALID_DATA);
2817 if (map_size < sizeof(IMAGE_NT_HEADERS32) + GUINT32_FROM_LE (dos_header->e_lfanew)) {
2818 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File is too small: %d", __func__, map_size);
2820 SetLastError (ERROR_BAD_LENGTH);
2824 nt_headers = (IMAGE_NT_HEADERS32 *)((guint8 *)file_map + GUINT32_FROM_LE (dos_header->e_lfanew));
2825 if (nt_headers->Signature != IMAGE_NT_SIGNATURE) {
2826 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Bad NT signature 0x%x", __func__, nt_headers->Signature);
2828 SetLastError (ERROR_INVALID_DATA);
2832 if (nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
2833 /* Do 64-bit stuff */
2834 resource_rva = GUINT32_FROM_LE (((IMAGE_NT_HEADERS64 *)nt_headers)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
2836 resource_rva = GUINT32_FROM_LE (nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
2839 if (resource_rva == 0) {
2840 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: No resources in file!", __func__);
2842 SetLastError (ERROR_INVALID_DATA);
2846 resource_dir = (IMAGE_RESOURCE_DIRECTORY *)get_ptr_from_rva (resource_rva, (IMAGE_NT_HEADERS32 *)nt_headers, file_map);
2847 if (resource_dir == NULL) {
2848 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find resource directory", __func__);
2850 SetLastError (ERROR_INVALID_DATA);
2854 entries = GUINT16_FROM_LE (resource_dir->NumberOfNamedEntries) + GUINT16_FROM_LE (resource_dir->NumberOfIdEntries);
2855 resource_dir_entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resource_dir + 1);
2857 for (i = 0; i < entries; i++) {
2858 IMAGE_RESOURCE_DIRECTORY_ENTRY *direntry = &resource_dir_entry[i];
2859 ret = scan_resource_dir (resource_dir,
2860 (IMAGE_NT_HEADERS32 *)nt_headers,
2861 file_map, direntry, 0, res_id,
2872 find_pe_file_resources64 (gpointer file_map, guint32 map_size, guint32 res_id, guint32 lang_id, guint32 *size)
2874 IMAGE_DOS_HEADER *dos_header;
2875 IMAGE_NT_HEADERS64 *nt_headers;
2876 IMAGE_RESOURCE_DIRECTORY *resource_dir;
2877 IMAGE_RESOURCE_DIRECTORY_ENTRY *resource_dir_entry;
2878 guint32 resource_rva, entries, i;
2879 gpointer ret = NULL;
2881 dos_header = (IMAGE_DOS_HEADER *)file_map;
2882 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) {
2883 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Bad dos signature 0x%x", __func__, dos_header->e_magic);
2885 SetLastError (ERROR_INVALID_DATA);
2889 if (map_size < sizeof(IMAGE_NT_HEADERS64) + GUINT32_FROM_LE (dos_header->e_lfanew)) {
2890 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File is too small: %d", __func__, map_size);
2892 SetLastError (ERROR_BAD_LENGTH);
2896 nt_headers = (IMAGE_NT_HEADERS64 *)((guint8 *)file_map + GUINT32_FROM_LE (dos_header->e_lfanew));
2897 if (nt_headers->Signature != IMAGE_NT_SIGNATURE) {
2898 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Bad NT signature 0x%x", __func__,
2899 nt_headers->Signature);
2901 SetLastError (ERROR_INVALID_DATA);
2905 if (nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
2906 /* Do 64-bit stuff */
2907 resource_rva = GUINT32_FROM_LE (((IMAGE_NT_HEADERS64 *)nt_headers)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
2909 resource_rva = GUINT32_FROM_LE (nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
2912 if (resource_rva == 0) {
2913 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: No resources in file!", __func__);
2915 SetLastError (ERROR_INVALID_DATA);
2919 resource_dir = (IMAGE_RESOURCE_DIRECTORY *)get_ptr_from_rva (resource_rva, (IMAGE_NT_HEADERS32 *)nt_headers, file_map);
2920 if (resource_dir == NULL) {
2921 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find resource directory", __func__);
2923 SetLastError (ERROR_INVALID_DATA);
2927 entries = GUINT16_FROM_LE (resource_dir->NumberOfNamedEntries) + GUINT16_FROM_LE (resource_dir->NumberOfIdEntries);
2928 resource_dir_entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resource_dir + 1);
2930 for (i = 0; i < entries; i++) {
2931 IMAGE_RESOURCE_DIRECTORY_ENTRY *direntry = &resource_dir_entry[i];
2932 ret = scan_resource_dir (resource_dir,
2933 (IMAGE_NT_HEADERS32 *)nt_headers,
2934 file_map, direntry, 0, res_id,
2945 find_pe_file_resources (gpointer file_map, guint32 map_size, guint32 res_id, guint32 lang_id, guint32 *size)
2947 /* Figure this out when we support 64bit PE files */
2949 return find_pe_file_resources32 (file_map, map_size, res_id,
2952 return find_pe_file_resources64 (file_map, map_size, res_id,
2958 map_pe_file (gunichar2 *filename, gint32 *map_size, void **handle)
2960 gchar *filename_ext;
2962 struct stat statbuf;
2965 /* According to the MSDN docs, a search path is applied to
2966 * filename. FIXME: implement this, for now just pass it
2970 filename_ext = mono_unicode_to_external (filename);
2971 if (filename_ext == NULL) {
2972 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2974 SetLastError (ERROR_INVALID_NAME);
2978 fd = _wapi_open (filename_ext, O_RDONLY, 0);
2980 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error opening file %s: %s", __func__, filename_ext, strerror (errno));
2982 SetLastError (_wapi_get_win32_file_error (errno));
2983 g_free (filename_ext);
2988 if (fstat (fd, &statbuf) == -1) {
2989 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error stat()ing file %s: %s", __func__, filename_ext, strerror (errno));
2991 SetLastError (_wapi_get_win32_file_error (errno));
2992 g_free (filename_ext);
2996 *map_size = statbuf.st_size;
2998 /* Check basic file size */
2999 if (statbuf.st_size < sizeof(IMAGE_DOS_HEADER)) {
3000 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File %s is too small: %lld", __func__, filename_ext, statbuf.st_size);
3002 SetLastError (ERROR_BAD_LENGTH);
3003 g_free (filename_ext);
3008 file_map = mono_file_map (statbuf.st_size, MONO_MMAP_READ | MONO_MMAP_PRIVATE, fd, 0, handle);
3009 if (file_map == NULL) {
3010 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error mmap()int file %s: %s", __func__, filename_ext, strerror (errno));
3012 SetLastError (_wapi_get_win32_file_error (errno));
3013 g_free (filename_ext);
3018 /* Don't need the fd any more */
3020 g_free (filename_ext);
3026 unmap_pe_file (gpointer file_map, void *handle)
3028 mono_file_unmap (file_map, handle);
3032 unicode_chars (const gunichar2 *str)
3037 if (str[len] == '\0') {
3045 unicode_compare (const gunichar2 *str1, const gunichar2 *str2)
3047 while (*str1 && *str2) {
3048 if (*str1 != *str2) {
3055 return(*str1 == *str2);
3058 /* compare a little-endian null-terminated utf16 string and a normal string.
3059 * Can be used only for ascii or latin1 chars.
3062 unicode_string_equals (const gunichar2 *str1, const gchar *str2)
3064 while (*str1 && *str2) {
3065 if (GUINT16_TO_LE (*str1) != *str2) {
3072 return(*str1 == *str2);
3082 /* Returns a pointer to the value data, because there's no way to know
3083 * how big that data is (value_len is set to zero for most blocks :-( )
3085 static gconstpointer
3086 get_versioninfo_block (gconstpointer data, version_data *block)
3088 block->data_len = GUINT16_FROM_LE (*((guint16 *)data));
3089 data = (char *)data + sizeof(guint16);
3090 block->value_len = GUINT16_FROM_LE (*((guint16 *)data));
3091 data = (char *)data + sizeof(guint16);
3093 /* No idea what the type is supposed to indicate */
3094 block->type = GUINT16_FROM_LE (*((guint16 *)data));
3095 data = (char *)data + sizeof(guint16);
3096 block->key = ((gunichar2 *)data);
3098 /* Skip over the key (including the terminator) */
3099 data = ((gunichar2 *)data) + (unicode_chars (block->key) + 1);
3101 /* align on a 32-bit boundary */
3107 static gconstpointer
3108 get_fixedfileinfo_block (gconstpointer data, version_data *block)
3110 gconstpointer data_ptr;
3111 VS_FIXEDFILEINFO *ffi;
3113 data_ptr = get_versioninfo_block (data, block);
3115 if (block->value_len != sizeof(VS_FIXEDFILEINFO)) {
3116 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: FIXEDFILEINFO size mismatch", __func__);
3120 if (!unicode_string_equals (block->key, "VS_VERSION_INFO")) {
3121 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: VS_VERSION_INFO mismatch", __func__);
3126 ffi = ((VS_FIXEDFILEINFO *)data_ptr);
3127 if ((ffi->dwSignature != VS_FFI_SIGNATURE) ||
3128 (ffi->dwStrucVersion != VS_FFI_STRUCVERSION)) {
3129 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: FIXEDFILEINFO bad signature", __func__);
3137 static gconstpointer
3138 get_varfileinfo_block (gconstpointer data_ptr, version_data *block)
3140 /* data is pointing at a Var block
3142 data_ptr = get_versioninfo_block (data_ptr, block);
3147 static gconstpointer
3148 get_string_block (gconstpointer data_ptr, const gunichar2 *string_key, gpointer *string_value,
3149 guint32 *string_value_len, version_data *block)
3151 guint16 data_len = block->data_len;
3152 guint16 string_len = 28; /* Length of the StringTable block */
3153 char *orig_data_ptr = (char *)data_ptr - 28;
3155 /* data_ptr is pointing at an array of one or more String blocks
3156 * with total length (not including alignment padding) of
3159 while (((char *)data_ptr - (char *)orig_data_ptr) < data_len) {
3160 /* align on a 32-bit boundary */
3163 data_ptr = get_versioninfo_block (data_ptr, block);
3164 if (block->data_len == 0) {
3165 /* We must have hit padding, so give up
3168 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3173 string_len = string_len + block->data_len;
3175 if (string_key != NULL &&
3176 string_value != NULL &&
3177 string_value_len != NULL &&
3178 unicode_compare (string_key, block->key) == TRUE) {
3179 *string_value = (gpointer)data_ptr;
3180 *string_value_len = block->value_len;
3183 /* Skip over the value */
3184 data_ptr = ((gunichar2 *)data_ptr) + block->value_len;
3190 /* Returns a pointer to the byte following the Stringtable block, or
3191 * NULL if the data read hits padding. We can't recover from this
3192 * because the data length does not include padding bytes, so it's not
3193 * possible to just return the start position + length
3195 * If lang == NULL it means we're just stepping through this block
3197 static gconstpointer
3198 get_stringtable_block (gconstpointer data_ptr, gchar *lang, const gunichar2 *string_key, gpointer *string_value,
3199 guint32 *string_value_len, version_data *block)
3201 guint16 data_len = block->data_len;
3202 guint16 string_len = 36; /* length of the StringFileInfo block */
3204 gchar *lowercase_lang;
3206 /* data_ptr is pointing at an array of StringTable blocks,
3207 * with total length (not including alignment padding) of
3211 while(string_len < data_len) {
3212 /* align on a 32-bit boundary */
3215 data_ptr = get_versioninfo_block (data_ptr, block);
3216 if (block->data_len == 0) {
3217 /* We must have hit padding, so give up
3220 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3224 string_len = string_len + block->data_len;
3226 found_lang = g_utf16_to_utf8 (block->key, 8, NULL, NULL, NULL);
3227 if (found_lang == NULL) {
3228 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't find a valid language key, giving up", __func__);
3232 lowercase_lang = g_utf8_strdown (found_lang, -1);
3233 g_free (found_lang);
3234 found_lang = lowercase_lang;
3235 lowercase_lang = NULL;
3237 if (lang != NULL && !strcmp (found_lang, lang)) {
3238 /* Got the one we're interested in */
3239 data_ptr = get_string_block (data_ptr, string_key,
3241 string_value_len, block);
3243 data_ptr = get_string_block (data_ptr, NULL, NULL,
3247 g_free (found_lang);
3249 if (data_ptr == NULL) {
3250 /* Child block hit padding */
3251 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Child block hit 0-length block, giving up", __func__);
3259 #if G_BYTE_ORDER == G_BIG_ENDIAN
3260 static gconstpointer
3261 big_up_string_block (gconstpointer data_ptr, version_data *block)
3263 guint16 data_len = block->data_len;
3264 guint16 string_len = 28; /* Length of the StringTable block */
3266 char *orig_data_ptr = (char *)data_ptr - 28;
3268 /* data_ptr is pointing at an array of one or more String
3269 * blocks with total length (not including alignment padding)
3272 while (((char *)data_ptr - (char *)orig_data_ptr) < data_len) {
3273 /* align on a 32-bit boundary */
3276 data_ptr = get_versioninfo_block (data_ptr, block);
3277 if (block->data_len == 0) {
3278 /* We must have hit padding, so give up
3281 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3285 string_len = string_len + block->data_len;
3287 big_value = g_convert ((gchar *)block->key,
3288 unicode_chars (block->key) * 2,
3289 "UTF-16BE", "UTF-16LE", NULL, NULL,
3291 if (big_value == NULL) {
3292 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't find a valid string, giving up", __func__);
3296 /* The swapped string should be exactly the same
3297 * length as the original little-endian one, but only
3298 * copy the number of original chars just to be on the
3301 memcpy (block->key, big_value, unicode_chars (block->key) * 2);
3304 big_value = g_convert ((gchar *)data_ptr,
3305 unicode_chars (data_ptr) * 2,
3306 "UTF-16BE", "UTF-16LE", NULL, NULL,
3308 if (big_value == NULL) {
3309 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't find a valid data string, giving up", __func__);
3312 memcpy ((gpointer)data_ptr, big_value,
3313 unicode_chars (data_ptr) * 2);
3316 data_ptr = ((gunichar2 *)data_ptr) + block->value_len;
3322 /* Returns a pointer to the byte following the Stringtable block, or
3323 * NULL if the data read hits padding. We can't recover from this
3324 * because the data length does not include padding bytes, so it's not
3325 * possible to just return the start position + length
3327 static gconstpointer
3328 big_up_stringtable_block (gconstpointer data_ptr, version_data *block)
3330 guint16 data_len = block->data_len;
3331 guint16 string_len = 36; /* length of the StringFileInfo block */
3334 /* data_ptr is pointing at an array of StringTable blocks,
3335 * with total length (not including alignment padding) of
3339 while(string_len < data_len) {
3340 /* align on a 32-bit boundary */
3343 data_ptr = get_versioninfo_block (data_ptr, block);
3344 if (block->data_len == 0) {
3345 /* We must have hit padding, so give up
3348 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3352 string_len = string_len + block->data_len;
3354 big_value = g_convert ((gchar *)block->key, 16, "UTF-16BE",
3355 "UTF-16LE", NULL, NULL, NULL);
3356 if (big_value == NULL) {
3357 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't find a valid string, giving up", __func__);
3361 memcpy (block->key, big_value, 16);
3364 data_ptr = big_up_string_block (data_ptr, block);
3366 if (data_ptr == NULL) {
3367 /* Child block hit padding */
3368 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Child block hit 0-length block, giving up", __func__);
3376 /* Follows the data structures and turns all UTF-16 strings from the
3377 * LE found in the resource section into UTF-16BE
3380 big_up (gconstpointer datablock, guint32 size)
3382 gconstpointer data_ptr;
3383 gint32 data_len; /* signed to guard against underflow */
3386 data_ptr = get_fixedfileinfo_block (datablock, &block);
3387 if (data_ptr != NULL) {
3388 VS_FIXEDFILEINFO *ffi = (VS_FIXEDFILEINFO *)data_ptr;
3390 /* Byteswap all the fields */
3391 ffi->dwFileVersionMS = GUINT32_SWAP_LE_BE (ffi->dwFileVersionMS);
3392 ffi->dwFileVersionLS = GUINT32_SWAP_LE_BE (ffi->dwFileVersionLS);
3393 ffi->dwProductVersionMS = GUINT32_SWAP_LE_BE (ffi->dwProductVersionMS);
3394 ffi->dwProductVersionLS = GUINT32_SWAP_LE_BE (ffi->dwProductVersionLS);
3395 ffi->dwFileFlagsMask = GUINT32_SWAP_LE_BE (ffi->dwFileFlagsMask);
3396 ffi->dwFileFlags = GUINT32_SWAP_LE_BE (ffi->dwFileFlags);
3397 ffi->dwFileOS = GUINT32_SWAP_LE_BE (ffi->dwFileOS);
3398 ffi->dwFileType = GUINT32_SWAP_LE_BE (ffi->dwFileType);
3399 ffi->dwFileSubtype = GUINT32_SWAP_LE_BE (ffi->dwFileSubtype);
3400 ffi->dwFileDateMS = GUINT32_SWAP_LE_BE (ffi->dwFileDateMS);
3401 ffi->dwFileDateLS = GUINT32_SWAP_LE_BE (ffi->dwFileDateLS);
3403 /* The FFI and header occupies the first 92 bytes
3405 data_ptr = (char *)data_ptr + sizeof(VS_FIXEDFILEINFO);
3406 data_len = block.data_len - 92;
3408 /* There now follow zero or one StringFileInfo blocks
3409 * and zero or one VarFileInfo blocks
3411 while (data_len > 0) {
3412 /* align on a 32-bit boundary */
3415 data_ptr = get_versioninfo_block (data_ptr, &block);
3416 if (block.data_len == 0) {
3417 /* We must have hit padding, so give
3420 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3424 data_len = data_len - block.data_len;
3426 if (unicode_string_equals (block.key, "VarFileInfo")) {
3427 data_ptr = get_varfileinfo_block (data_ptr,
3429 data_ptr = ((guchar *)data_ptr) + block.value_len;
3430 } else if (unicode_string_equals (block.key,
3431 "StringFileInfo")) {
3432 data_ptr = big_up_stringtable_block (data_ptr,
3436 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Not a valid VERSIONINFO child block", __func__);
3440 if (data_ptr == NULL) {
3441 /* Child block hit padding */
3442 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Child block hit 0-length block, giving up", __func__);
3451 mono_w32process_get_fileversion_info_size (gunichar2 *filename, guint32 *handle)
3454 gpointer versioninfo;
3459 /* This value is unused, but set to zero */
3462 file_map = map_pe_file (filename, &map_size, &map_handle);
3463 if (file_map == NULL) {
3467 versioninfo = find_pe_file_resources (file_map, map_size, RT_VERSION, 0, &size);
3468 if (versioninfo == NULL) {
3469 /* Didn't find the resource, so set the return value
3475 unmap_pe_file (file_map, map_handle);
3481 mono_w32process_get_fileversion_info (gunichar2 *filename, guint32 handle G_GNUC_UNUSED, guint32 len, gpointer data)
3484 gpointer versioninfo;
3488 gboolean ret = FALSE;
3490 file_map = map_pe_file (filename, &map_size, &map_handle);
3491 if (file_map == NULL) {
3495 versioninfo = find_pe_file_resources (file_map, map_size, RT_VERSION,
3497 if (versioninfo != NULL) {
3498 /* This could probably process the data so that
3499 * mono_w32process_ver_query_value() doesn't have to follow the data
3500 * blocks every time. But hey, these functions aren't
3501 * likely to appear in many profiles.
3503 memcpy (data, versioninfo, len < size?len:size);
3506 #if G_BYTE_ORDER == G_BIG_ENDIAN
3507 big_up (data, size);
3511 unmap_pe_file (file_map, map_handle);
3517 mono_w32process_ver_query_value (gconstpointer datablock, const gunichar2 *subblock, gpointer *buffer, guint32 *len)
3519 gchar *subblock_utf8, *lang_utf8 = NULL;
3520 gboolean ret = FALSE;
3522 gconstpointer data_ptr;
3523 gint32 data_len; /* signed to guard against underflow */
3524 gboolean want_var = FALSE;
3525 gboolean want_string = FALSE;
3527 const gunichar2 *string_key = NULL;
3528 gpointer string_value = NULL;
3529 guint32 string_value_len = 0;
3530 gchar *lowercase_lang;
3532 subblock_utf8 = g_utf16_to_utf8 (subblock, -1, NULL, NULL, NULL);
3533 if (subblock_utf8 == NULL) {
3537 if (!strcmp (subblock_utf8, "\\VarFileInfo\\Translation")) {
3539 } else if (!strncmp (subblock_utf8, "\\StringFileInfo\\", 16)) {
3541 memcpy (lang, subblock + 16, 8 * sizeof(gunichar2));
3542 lang_utf8 = g_utf16_to_utf8 (lang, 8, NULL, NULL, NULL);
3543 lowercase_lang = g_utf8_strdown (lang_utf8, -1);
3545 lang_utf8 = lowercase_lang;
3546 lowercase_lang = NULL;
3547 string_key = subblock + 25;
3550 if (!strcmp (subblock_utf8, "\\")) {
3551 data_ptr = get_fixedfileinfo_block (datablock, &block);
3552 if (data_ptr != NULL) {
3553 *buffer = (gpointer)data_ptr;
3554 *len = block.value_len;
3558 } else if (want_var || want_string) {
3559 data_ptr = get_fixedfileinfo_block (datablock, &block);
3560 if (data_ptr != NULL) {
3561 /* The FFI and header occupies the first 92
3564 data_ptr = (char *)data_ptr + sizeof(VS_FIXEDFILEINFO);
3565 data_len = block.data_len - 92;
3567 /* There now follow zero or one StringFileInfo
3568 * blocks and zero or one VarFileInfo blocks
3570 while (data_len > 0) {
3571 /* align on a 32-bit boundary */
3574 data_ptr = get_versioninfo_block (data_ptr,
3576 if (block.data_len == 0) {
3577 /* We must have hit padding,
3578 * so give up processing now
3580 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3584 data_len = data_len - block.data_len;
3586 if (unicode_string_equals (block.key, "VarFileInfo")) {
3587 data_ptr = get_varfileinfo_block (data_ptr, &block);
3589 *buffer = (gpointer)data_ptr;
3590 *len = block.value_len;
3594 /* Skip over the Var block */
3595 data_ptr = ((guchar *)data_ptr) + block.value_len;
3597 } else if (unicode_string_equals (block.key, "StringFileInfo")) {
3598 data_ptr = get_stringtable_block (data_ptr, lang_utf8, string_key, &string_value, &string_value_len, &block);
3600 string_value != NULL &&
3601 string_value_len != 0) {
3602 *buffer = string_value;
3603 *len = unicode_chars ((const gunichar2 *)string_value) + 1; /* Include trailing null */
3609 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Not a valid VERSIONINFO child block", __func__);
3613 if (data_ptr == NULL) {
3614 /* Child block hit padding */
3615 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Child block hit 0-length block, giving up", __func__);
3627 g_free (subblock_utf8);
3632 copy_lang (gunichar2 *lang_out, guint32 lang_len, const gchar *text)
3635 int chars = strlen (text);
3638 unitext = g_utf8_to_utf16 (text, -1, NULL, NULL, NULL);
3639 g_assert (unitext != NULL);
3641 if (chars < (lang_len - 1)) {
3642 memcpy (lang_out, (gpointer)unitext, chars * 2);
3643 lang_out[chars] = '\0';
3646 memcpy (lang_out, (gpointer)unitext, (lang_len - 1) * 2);
3647 lang_out[lang_len] = '\0';
3657 mono_w32process_ver_language_name (guint32 lang, gunichar2 *lang_out, guint32 lang_len)
3659 int primary, secondary;
3660 const char *name = NULL;
3662 primary = lang & 0x3FF;
3663 secondary = (lang >> 10) & 0x3F;
3667 switch (secondary) {
3668 case 0x01: name = "Process Default Language"; break;
3672 switch (secondary) {
3674 case 0x01: name = "Arabic (Saudi Arabia)"; break;
3675 case 0x02: name = "Arabic (Iraq)"; break;
3676 case 0x03: name = "Arabic (Egypt)"; break;
3677 case 0x04: name = "Arabic (Libya)"; break;
3678 case 0x05: name = "Arabic (Algeria)"; break;
3679 case 0x06: name = "Arabic (Morocco)"; break;
3680 case 0x07: name = "Arabic (Tunisia)"; break;
3681 case 0x08: name = "Arabic (Oman)"; break;
3682 case 0x09: name = "Arabic (Yemen)"; break;
3683 case 0x0a: name = "Arabic (Syria)"; break;
3684 case 0x0b: name = "Arabic (Jordan)"; break;
3685 case 0x0c: name = "Arabic (Lebanon)"; break;
3686 case 0x0d: name = "Arabic (Kuwait)"; break;
3687 case 0x0e: name = "Arabic (U.A.E.)"; break;
3688 case 0x0f: name = "Arabic (Bahrain)"; break;
3689 case 0x10: name = "Arabic (Qatar)"; break;
3693 switch (secondary) {
3694 case 0x00: name = "Bulgarian (Bulgaria)"; break;
3695 case 0x01: name = "Bulgarian"; break;
3699 switch (secondary) {
3700 case 0x00: name = "Catalan (Spain)"; break;
3701 case 0x01: name = "Catalan"; break;
3705 switch (secondary) {
3707 case 0x01: name = "Chinese (Taiwan)"; break;
3708 case 0x02: name = "Chinese (PRC)"; break;
3709 case 0x03: name = "Chinese (Hong Kong S.A.R.)"; break;
3710 case 0x04: name = "Chinese (Singapore)"; break;
3711 case 0x05: name = "Chinese (Macau S.A.R.)"; break;
3715 switch (secondary) {
3716 case 0x00: name = "Czech (Czech Republic)"; break;
3717 case 0x01: name = "Czech"; break;
3721 switch (secondary) {
3722 case 0x00: name = "Danish (Denmark)"; break;
3723 case 0x01: name = "Danish"; break;
3727 switch (secondary) {
3729 case 0x01: name = "German (Germany)"; break;
3730 case 0x02: name = "German (Switzerland)"; break;
3731 case 0x03: name = "German (Austria)"; break;
3732 case 0x04: name = "German (Luxembourg)"; break;
3733 case 0x05: name = "German (Liechtenstein)"; break;
3737 switch (secondary) {
3738 case 0x00: name = "Greek (Greece)"; break;
3739 case 0x01: name = "Greek"; break;
3743 switch (secondary) {
3745 case 0x01: name = "English (United States)"; break;
3746 case 0x02: name = "English (United Kingdom)"; break;
3747 case 0x03: name = "English (Australia)"; break;
3748 case 0x04: name = "English (Canada)"; break;
3749 case 0x05: name = "English (New Zealand)"; break;
3750 case 0x06: name = "English (Ireland)"; break;
3751 case 0x07: name = "English (South Africa)"; break;
3752 case 0x08: name = "English (Jamaica)"; break;
3753 case 0x09: name = "English (Caribbean)"; break;
3754 case 0x0a: name = "English (Belize)"; break;
3755 case 0x0b: name = "English (Trinidad and Tobago)"; break;
3756 case 0x0c: name = "English (Zimbabwe)"; break;
3757 case 0x0d: name = "English (Philippines)"; break;
3758 case 0x10: name = "English (India)"; break;
3759 case 0x11: name = "English (Malaysia)"; break;
3760 case 0x12: name = "English (Singapore)"; break;
3764 switch (secondary) {
3765 case 0x00: name = "Spanish (Spain)"; break;
3766 case 0x01: name = "Spanish (Traditional Sort)"; break;
3767 case 0x02: name = "Spanish (Mexico)"; break;
3768 case 0x03: name = "Spanish (International Sort)"; break;
3769 case 0x04: name = "Spanish (Guatemala)"; break;
3770 case 0x05: name = "Spanish (Costa Rica)"; break;
3771 case 0x06: name = "Spanish (Panama)"; break;
3772 case 0x07: name = "Spanish (Dominican Republic)"; break;
3773 case 0x08: name = "Spanish (Venezuela)"; break;
3774 case 0x09: name = "Spanish (Colombia)"; break;
3775 case 0x0a: name = "Spanish (Peru)"; break;
3776 case 0x0b: name = "Spanish (Argentina)"; break;
3777 case 0x0c: name = "Spanish (Ecuador)"; break;
3778 case 0x0d: name = "Spanish (Chile)"; break;
3779 case 0x0e: name = "Spanish (Uruguay)"; break;
3780 case 0x0f: name = "Spanish (Paraguay)"; break;
3781 case 0x10: name = "Spanish (Bolivia)"; break;
3782 case 0x11: name = "Spanish (El Salvador)"; break;
3783 case 0x12: name = "Spanish (Honduras)"; break;
3784 case 0x13: name = "Spanish (Nicaragua)"; break;
3785 case 0x14: name = "Spanish (Puerto Rico)"; break;
3786 case 0x15: name = "Spanish (United States)"; break;
3790 switch (secondary) {
3791 case 0x00: name = "Finnish (Finland)"; break;
3792 case 0x01: name = "Finnish"; break;
3796 switch (secondary) {
3798 case 0x01: name = "French (France)"; break;
3799 case 0x02: name = "French (Belgium)"; break;
3800 case 0x03: name = "French (Canada)"; break;
3801 case 0x04: name = "French (Switzerland)"; break;
3802 case 0x05: name = "French (Luxembourg)"; break;
3803 case 0x06: name = "French (Monaco)"; break;
3807 switch (secondary) {
3808 case 0x00: name = "Hebrew (Israel)"; break;
3809 case 0x01: name = "Hebrew"; break;
3813 switch (secondary) {
3814 case 0x00: name = "Hungarian (Hungary)"; break;
3815 case 0x01: name = "Hungarian"; break;
3819 switch (secondary) {
3820 case 0x00: name = "Icelandic (Iceland)"; break;
3821 case 0x01: name = "Icelandic"; break;
3825 switch (secondary) {
3827 case 0x01: name = "Italian (Italy)"; break;
3828 case 0x02: name = "Italian (Switzerland)"; break;
3832 switch (secondary) {
3833 case 0x00: name = "Japanese (Japan)"; break;
3834 case 0x01: name = "Japanese"; break;
3838 switch (secondary) {
3839 case 0x00: name = "Korean (Korea)"; break;
3840 case 0x01: name = "Korean"; break;
3844 switch (secondary) {
3846 case 0x01: name = "Dutch (Netherlands)"; break;
3847 case 0x02: name = "Dutch (Belgium)"; break;
3851 switch (secondary) {
3853 case 0x01: name = "Norwegian (Bokmal)"; break;
3854 case 0x02: name = "Norwegian (Nynorsk)"; break;
3858 switch (secondary) {
3859 case 0x00: name = "Polish (Poland)"; break;
3860 case 0x01: name = "Polish"; break;
3864 switch (secondary) {
3866 case 0x01: name = "Portuguese (Brazil)"; break;
3867 case 0x02: name = "Portuguese (Portugal)"; break;
3871 switch (secondary) {
3872 case 0x01: name = "Romansh (Switzerland)"; break;
3876 switch (secondary) {
3877 case 0x00: name = "Romanian (Romania)"; break;
3878 case 0x01: name = "Romanian"; break;
3882 switch (secondary) {
3883 case 0x00: name = "Russian (Russia)"; break;
3884 case 0x01: name = "Russian"; break;
3888 switch (secondary) {
3889 case 0x00: name = "Croatian (Croatia)"; break;
3890 case 0x01: name = "Croatian"; break;
3891 case 0x02: name = "Serbian (Latin)"; break;
3892 case 0x03: name = "Serbian (Cyrillic)"; break;
3893 case 0x04: name = "Croatian (Bosnia and Herzegovina)"; break;
3894 case 0x05: name = "Bosnian (Latin, Bosnia and Herzegovina)"; break;
3895 case 0x06: name = "Serbian (Latin, Bosnia and Herzegovina)"; break;
3896 case 0x07: name = "Serbian (Cyrillic, Bosnia and Herzegovina)"; break;
3897 case 0x08: name = "Bosnian (Cyrillic, Bosnia and Herzegovina)"; break;
3901 switch (secondary) {
3902 case 0x00: name = "Slovak (Slovakia)"; break;
3903 case 0x01: name = "Slovak"; break;
3907 switch (secondary) {
3908 case 0x00: name = "Albanian (Albania)"; break;
3909 case 0x01: name = "Albanian"; break;
3913 switch (secondary) {
3914 case 0x00: name = "Swedish (Sweden)"; break;
3915 case 0x01: name = "Swedish"; break;
3916 case 0x02: name = "Swedish (Finland)"; break;
3920 switch (secondary) {
3921 case 0x00: name = "Thai (Thailand)"; break;
3922 case 0x01: name = "Thai"; break;
3926 switch (secondary) {
3927 case 0x00: name = "Turkish (Turkey)"; break;
3928 case 0x01: name = "Turkish"; break;
3932 switch (secondary) {
3933 case 0x00: name = "Urdu (Islamic Republic of Pakistan)"; break;
3934 case 0x01: name = "Urdu"; break;
3938 switch (secondary) {
3939 case 0x00: name = "Indonesian (Indonesia)"; break;
3940 case 0x01: name = "Indonesian"; break;
3944 switch (secondary) {
3945 case 0x00: name = "Ukrainian (Ukraine)"; break;
3946 case 0x01: name = "Ukrainian"; break;
3950 switch (secondary) {
3951 case 0x00: name = "Belarusian (Belarus)"; break;
3952 case 0x01: name = "Belarusian"; break;
3956 switch (secondary) {
3957 case 0x00: name = "Slovenian (Slovenia)"; break;
3958 case 0x01: name = "Slovenian"; break;
3962 switch (secondary) {
3963 case 0x00: name = "Estonian (Estonia)"; break;
3964 case 0x01: name = "Estonian"; break;
3968 switch (secondary) {
3969 case 0x00: name = "Latvian (Latvia)"; break;
3970 case 0x01: name = "Latvian"; break;
3974 switch (secondary) {
3975 case 0x00: name = "Lithuanian (Lithuania)"; break;
3976 case 0x01: name = "Lithuanian"; break;
3980 switch (secondary) {
3981 case 0x01: name = "Tajik (Tajikistan)"; break;
3985 switch (secondary) {
3986 case 0x00: name = "Farsi (Iran)"; break;
3987 case 0x01: name = "Farsi"; break;
3991 switch (secondary) {
3992 case 0x00: name = "Vietnamese (Viet Nam)"; break;
3993 case 0x01: name = "Vietnamese"; break;
3997 switch (secondary) {
3998 case 0x00: name = "Armenian (Armenia)"; break;
3999 case 0x01: name = "Armenian"; break;
4003 switch (secondary) {
4004 case 0x00: name = "Azeri (Latin) (Azerbaijan)"; break;
4005 case 0x01: name = "Azeri (Latin)"; break;
4006 case 0x02: name = "Azeri (Cyrillic)"; break;
4010 switch (secondary) {
4011 case 0x00: name = "Basque (Spain)"; break;
4012 case 0x01: name = "Basque"; break;
4016 switch (secondary) {
4017 case 0x01: name = "Upper Sorbian (Germany)"; break;
4018 case 0x02: name = "Lower Sorbian (Germany)"; break;
4022 switch (secondary) {
4023 case 0x00: name = "FYRO Macedonian (Former Yugoslav Republic of Macedonia)"; break;
4024 case 0x01: name = "FYRO Macedonian"; break;
4028 switch (secondary) {
4029 case 0x00: name = "Tswana (South Africa)"; break;
4030 case 0x01: name = "Tswana"; break;
4034 switch (secondary) {
4035 case 0x00: name = "Xhosa (South Africa)"; break;
4036 case 0x01: name = "Xhosa"; break;
4040 switch (secondary) {
4041 case 0x00: name = "Zulu (South Africa)"; break;
4042 case 0x01: name = "Zulu"; break;
4046 switch (secondary) {
4047 case 0x00: name = "Afrikaans (South Africa)"; break;
4048 case 0x01: name = "Afrikaans"; break;
4052 switch (secondary) {
4053 case 0x00: name = "Georgian (Georgia)"; break;
4054 case 0x01: name = "Georgian"; break;
4058 switch (secondary) {
4059 case 0x00: name = "Faroese (Faroe Islands)"; break;
4060 case 0x01: name = "Faroese"; break;
4064 switch (secondary) {
4065 case 0x00: name = "Hindi (India)"; break;
4066 case 0x01: name = "Hindi"; break;
4070 switch (secondary) {
4071 case 0x00: name = "Maltese (Malta)"; break;
4072 case 0x01: name = "Maltese"; break;
4076 switch (secondary) {
4077 case 0x00: name = "Sami (Northern) (Norway)"; break;
4078 case 0x01: name = "Sami, Northern (Norway)"; break;
4079 case 0x02: name = "Sami, Northern (Sweden)"; break;
4080 case 0x03: name = "Sami, Northern (Finland)"; break;
4081 case 0x04: name = "Sami, Lule (Norway)"; break;
4082 case 0x05: name = "Sami, Lule (Sweden)"; break;
4083 case 0x06: name = "Sami, Southern (Norway)"; break;
4084 case 0x07: name = "Sami, Southern (Sweden)"; break;
4085 case 0x08: name = "Sami, Skolt (Finland)"; break;
4086 case 0x09: name = "Sami, Inari (Finland)"; break;
4090 switch (secondary) {
4091 case 0x02: name = "Irish (Ireland)"; break;
4095 switch (secondary) {
4097 case 0x01: name = "Malay (Malaysia)"; break;
4098 case 0x02: name = "Malay (Brunei Darussalam)"; break;
4102 switch (secondary) {
4103 case 0x00: name = "Kazakh (Kazakhstan)"; break;
4104 case 0x01: name = "Kazakh"; break;
4108 switch (secondary) {
4109 case 0x00: name = "Kyrgyz (Kyrgyzstan)"; break;
4110 case 0x01: name = "Kyrgyz (Cyrillic)"; break;
4114 switch (secondary) {
4115 case 0x00: name = "Swahili (Kenya)"; break;
4116 case 0x01: name = "Swahili"; break;
4120 switch (secondary) {
4121 case 0x01: name = "Turkmen (Turkmenistan)"; break;
4125 switch (secondary) {
4126 case 0x00: name = "Uzbek (Latin) (Uzbekistan)"; break;
4127 case 0x01: name = "Uzbek (Latin)"; break;
4128 case 0x02: name = "Uzbek (Cyrillic)"; break;
4132 switch (secondary) {
4133 case 0x00: name = "Tatar (Russia)"; break;
4134 case 0x01: name = "Tatar"; break;
4138 switch (secondary) {
4140 case 0x01: name = "Bengali (India)"; break;
4144 switch (secondary) {
4145 case 0x00: name = "Punjabi (India)"; break;
4146 case 0x01: name = "Punjabi"; break;
4150 switch (secondary) {
4151 case 0x00: name = "Gujarati (India)"; break;
4152 case 0x01: name = "Gujarati"; break;
4156 switch (secondary) {
4157 case 0x00: name = "Tamil (India)"; break;
4158 case 0x01: name = "Tamil"; break;
4162 switch (secondary) {
4163 case 0x00: name = "Telugu (India)"; break;
4164 case 0x01: name = "Telugu"; break;
4168 switch (secondary) {
4169 case 0x00: name = "Kannada (India)"; break;
4170 case 0x01: name = "Kannada"; break;
4174 switch (secondary) {
4176 case 0x01: name = "Malayalam (India)"; break;
4180 switch (secondary) {
4181 case 0x01: name = "Assamese (India)"; break;
4185 switch (secondary) {
4186 case 0x00: name = "Marathi (India)"; break;
4187 case 0x01: name = "Marathi"; break;
4191 switch (secondary) {
4192 case 0x00: name = "Sanskrit (India)"; break;
4193 case 0x01: name = "Sanskrit"; break;
4197 switch (secondary) {
4198 case 0x00: name = "Mongolian (Mongolia)"; break;
4199 case 0x01: name = "Mongolian (Cyrillic)"; break;
4200 case 0x02: name = "Mongolian (PRC)"; break;
4204 switch (secondary) {
4205 case 0x01: name = "Tibetan (PRC)"; break;
4206 case 0x02: name = "Tibetan (Bhutan)"; break;
4210 switch (secondary) {
4211 case 0x00: name = "Welsh (United Kingdom)"; break;
4212 case 0x01: name = "Welsh"; break;
4216 switch (secondary) {
4217 case 0x01: name = "Khmer (Cambodia)"; break;
4221 switch (secondary) {
4222 case 0x01: name = "Lao (Lao PDR)"; break;
4226 switch (secondary) {
4227 case 0x00: name = "Galician (Spain)"; break;
4228 case 0x01: name = "Galician"; break;
4232 switch (secondary) {
4233 case 0x00: name = "Konkani (India)"; break;
4234 case 0x01: name = "Konkani"; break;
4238 switch (secondary) {
4239 case 0x00: name = "Syriac (Syria)"; break;
4240 case 0x01: name = "Syriac"; break;
4244 switch (secondary) {
4245 case 0x01: name = "Sinhala (Sri Lanka)"; break;
4249 switch (secondary) {
4250 case 0x01: name = "Inuktitut (Syllabics, Canada)"; break;
4251 case 0x02: name = "Inuktitut (Latin, Canada)"; break;
4255 switch (secondary) {
4256 case 0x01: name = "Amharic (Ethiopia)"; break;
4260 switch (secondary) {
4261 case 0x02: name = "Tamazight (Algeria, Latin)"; break;
4265 switch (secondary) {
4266 case 0x01: name = "Nepali (Nepal)"; break;
4270 switch (secondary) {
4271 case 0x01: name = "Frisian (Netherlands)"; break;
4275 switch (secondary) {
4276 case 0x01: name = "Pashto (Afghanistan)"; break;
4280 switch (secondary) {
4281 case 0x01: name = "Filipino (Philippines)"; break;
4285 switch (secondary) {
4286 case 0x00: name = "Divehi (Maldives)"; break;
4287 case 0x01: name = "Divehi"; break;
4291 switch (secondary) {
4292 case 0x01: name = "Hausa (Nigeria, Latin)"; break;
4296 switch (secondary) {
4297 case 0x01: name = "Yoruba (Nigeria)"; break;
4301 switch (secondary) {
4303 case 0x01: name = "Quechua (Bolivia)"; break;
4304 case 0x02: name = "Quechua (Ecuador)"; break;
4305 case 0x03: name = "Quechua (Peru)"; break;
4309 switch (secondary) {
4310 case 0x00: name = "Northern Sotho (South Africa)"; break;
4311 case 0x01: name = "Northern Sotho"; break;
4315 switch (secondary) {
4316 case 0x01: name = "Bashkir (Russia)"; break;
4320 switch (secondary) {
4321 case 0x01: name = "Luxembourgish (Luxembourg)"; break;
4325 switch (secondary) {
4326 case 0x01: name = "Greenlandic (Greenland)"; break;
4330 switch (secondary) {
4331 case 0x01: name = "Yi (PRC)"; break;
4335 switch (secondary) {
4336 case 0x01: name = "Mapudungun (Chile)"; break;
4340 switch (secondary) {
4341 case 0x01: name = "Mohawk (Mohawk)"; break;
4345 switch (secondary) {
4346 case 0x01: name = "Breton (France)"; break;
4350 switch (secondary) {
4351 case 0x00: name = "Invariant Language (Invariant Country)"; break;
4355 switch (secondary) {
4356 case 0x01: name = "Uighur (PRC)"; break;
4360 switch (secondary) {
4361 case 0x00: name = "Maori (New Zealand)"; break;
4362 case 0x01: name = "Maori"; break;
4366 switch (secondary) {
4367 case 0x01: name = "Corsican (France)"; break;
4371 switch (secondary) {
4372 case 0x01: name = "Alsatian (France)"; break;
4376 switch (secondary) {
4377 case 0x01: name = "Yakut (Russia)"; break;
4381 switch (secondary) {
4382 case 0x01: name = "K'iche (Guatemala)"; break;
4386 switch (secondary) {
4387 case 0x01: name = "Kinyarwanda (Rwanda)"; break;
4391 switch (secondary) {
4392 case 0x01: name = "Wolof (Senegal)"; break;
4396 switch (secondary) {
4397 case 0x01: name = "Dari (Afghanistan)"; break;
4402 name = "Language Neutral";
4407 name = "Language Neutral";
4409 return copy_lang (lang_out, lang_len, name);