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__);
1962 switch (pid = fork ()) {
1963 case -1: /* Error */ {
1964 SetLastError (ERROR_OUTOFMEMORY);
1968 case 0: /* Child */ {
1969 if (startup_pipe [0] != -1) {
1970 /* Wait until the parent has updated it's internal data */
1971 ssize_t _i G_GNUC_UNUSED = read (startup_pipe [0], &dummy, 1);
1972 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: child: parent has completed its setup", __func__);
1973 close (startup_pipe [0]);
1974 close (startup_pipe [1]);
1977 /* should we detach from the process group? */
1979 /* Connect stdin, stdout and stderr */
1984 /* Close all file descriptors */
1985 for (i = mono_w32handle_fd_reserve - 1; i > 2; i--)
1988 #ifdef DEBUG_ENABLED
1989 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1990 dir == NULL?".":dir);
1991 for (i = 0; argv[i] != NULL; i++)
1992 g_message ("arg %d: [%s]", i, argv[i]);
1994 for (i = 0; env_strings[i] != NULL; i++)
1995 g_message ("env %d: [%s]", i, env_strings[i]);
1999 if (dir != NULL && chdir (dir) == -1) {
2005 execve (argv[0], argv, env_strings);
2012 default: /* Parent */ {
2013 MonoW32HandleProcess process_handle;
2015 memset (&process_handle, 0, sizeof (process_handle));
2016 process_handle.pid = pid;
2017 process_handle.pname = g_strdup (prog);
2018 process_set_defaults (&process_handle);
2020 /* Add our mono_process into the linked list of processes */
2021 mono_process = (MonoProcess *) g_malloc0 (sizeof (MonoProcess));
2022 mono_process->pid = pid;
2023 mono_process->handle_count = 1;
2024 mono_os_sem_init (&mono_process->exit_sem, 0);
2026 process_handle.mono_process = mono_process;
2028 handle = mono_w32handle_new (MONO_W32HANDLE_PROCESS, &process_handle);
2029 if (handle == INVALID_HANDLE_VALUE) {
2030 g_warning ("%s: error creating process handle", __func__);
2032 mono_os_sem_destroy (&mono_process->exit_sem);
2033 g_free (mono_process);
2035 SetLastError (ERROR_OUTOFMEMORY);
2040 /* Keep the process handle artificially alive until the process
2041 * exits so that the information in the handle isn't lost. */
2042 mono_w32handle_ref (handle);
2043 mono_process->handle = handle;
2045 mono_os_mutex_lock (&processes_mutex);
2046 mono_process->next = processes;
2047 processes = mono_process;
2048 mono_os_mutex_unlock (&processes_mutex);
2050 if (process_info != NULL) {
2051 process_info->process_handle = handle;
2052 process_info->pid = pid;
2054 /* FIXME: we might need to handle the thread info some day */
2055 process_info->thread_handle = INVALID_HANDLE_VALUE;
2056 process_info->tid = 0;
2063 if (startup_pipe [1] != -1) {
2064 /* Write 1 byte, doesn't matter what */
2065 ssize_t _i G_GNUC_UNUSED = write (startup_pipe [1], startup_pipe, 1);
2066 close (startup_pipe [0]);
2067 close (startup_pipe [1]);
2082 g_strfreev (env_strings);
2086 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: returning handle %p for pid %d", __func__, handle, pid);
2088 /* Check if something needs to be cleaned up. */
2089 processes_cleanup ();
2093 SetLastError (ERROR_NOT_SUPPORTED);
2095 #endif // defined (HAVE_FORK) && defined (HAVE_EXECVE)
2099 ves_icall_System_Diagnostics_Process_ShellExecuteEx_internal (MonoW32ProcessStartInfo *proc_start_info, MonoW32ProcessInfo *process_info)
2101 const gunichar2 *lpFile;
2102 const gunichar2 *lpParameters;
2103 const gunichar2 *lpDirectory;
2107 if (!proc_start_info->filename) {
2108 /* w2k returns TRUE for this, for some reason. */
2113 lpFile = proc_start_info->filename ? mono_string_chars (proc_start_info->filename) : NULL;
2114 lpParameters = proc_start_info->arguments ? mono_string_chars (proc_start_info->arguments) : NULL;
2115 lpDirectory = proc_start_info->working_directory && mono_string_length (proc_start_info->working_directory) != 0 ?
2116 mono_string_chars (proc_start_info->working_directory) : NULL;
2118 /* Put both executable and parameters into the second argument
2119 * to process_create (), so it searches $PATH. The conversion
2120 * into and back out of utf8 is because there is no
2121 * g_strdup_printf () equivalent for gunichar2 :-(
2123 args = utf16_concat (utf16_quote, lpFile, utf16_quote, lpParameters == NULL ? NULL : utf16_space, lpParameters, NULL);
2125 SetLastError (ERROR_INVALID_DATA);
2129 ret = process_create (NULL, args, lpDirectory, NULL, process_info);
2132 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
2136 static char *handler;
2137 static gunichar2 *handler_utf16;
2139 if (handler_utf16 == (gunichar2 *)-1) {
2144 #ifdef PLATFORM_MACOSX
2145 handler = g_strdup ("/usr/bin/open");
2148 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
2149 * if that fails, try to use gnome-open, then kfmclient
2151 handler = g_find_program_in_path ("xdg-open");
2152 if (handler == NULL){
2153 handler = g_find_program_in_path ("gnome-open");
2154 if (handler == NULL){
2155 handler = g_find_program_in_path ("kfmclient");
2156 if (handler == NULL){
2157 handler_utf16 = (gunichar2 *) -1;
2161 /* kfmclient needs exec argument */
2162 char *old = handler;
2163 handler = g_strconcat (old, " exec",
2170 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
2173 /* Put quotes around the filename, in case it's a url
2174 * that contains #'s (process_create() calls
2175 * g_shell_parse_argv(), which deliberately throws
2176 * away anything after an unquoted #). Fixes bug
2179 args = utf16_concat (handler_utf16, utf16_space, utf16_quote, lpFile, utf16_quote,
2180 lpParameters == NULL ? NULL : utf16_space, lpParameters, NULL);
2182 SetLastError (ERROR_INVALID_DATA);
2186 ret = process_create (NULL, args, lpDirectory, NULL, process_info);
2189 if (GetLastError () != ERROR_OUTOFMEMORY)
2190 SetLastError (ERROR_INVALID_DATA);
2194 /* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
2195 CloseHandle (process_info->process_handle);
2196 process_info->process_handle = NULL;
2201 process_info->pid = -GetLastError ();
2203 process_info->thread_handle = NULL;
2204 #if !defined(MONO_CROSS_COMPILE)
2205 process_info->pid = mono_w32process_get_pid (process_info->process_handle);
2207 process_info->pid = 0;
2209 process_info->tid = 0;
2215 /* Only used when UseShellExecute is false */
2217 process_get_complete_path (const gunichar2 *appname, gchar **completed)
2222 utf8app = g_utf16_to_utf8 (appname, -1, NULL, NULL, NULL);
2224 if (g_path_is_absolute (utf8app)) {
2225 *completed = g_shell_quote (utf8app);
2230 if (g_file_test (utf8app, G_FILE_TEST_IS_EXECUTABLE) && !g_file_test (utf8app, G_FILE_TEST_IS_DIR)) {
2231 *completed = g_shell_quote (utf8app);
2236 found = g_find_program_in_path (utf8app);
2237 if (found == NULL) {
2243 *completed = g_shell_quote (found);
2250 process_get_shell_arguments (MonoW32ProcessStartInfo *proc_start_info, gunichar2 **shell_path)
2252 gchar *complete_path = NULL;
2256 if (process_get_complete_path (mono_string_chars (proc_start_info->filename), &complete_path)) {
2257 *shell_path = g_utf8_to_utf16 (complete_path, -1, NULL, NULL, NULL);
2258 g_free (complete_path);
2261 return *shell_path != NULL;
2265 ves_icall_System_Diagnostics_Process_CreateProcess_internal (MonoW32ProcessStartInfo *proc_start_info,
2266 HANDLE stdin_handle, HANDLE stdout_handle, HANDLE stderr_handle, MonoW32ProcessInfo *process_info)
2270 StartupHandles startup_handles;
2271 gunichar2 *shell_path = NULL;
2272 gunichar2 *args = NULL;
2274 memset (&startup_handles, 0, sizeof (startup_handles));
2275 startup_handles.input = stdin_handle;
2276 startup_handles.output = stdout_handle;
2277 startup_handles.error = stderr_handle;
2279 if (!process_get_shell_arguments (proc_start_info, &shell_path)) {
2280 process_info->pid = -ERROR_FILE_NOT_FOUND;
2284 args = proc_start_info->arguments && mono_string_length (proc_start_info->arguments) > 0 ?
2285 mono_string_chars (proc_start_info->arguments): NULL;
2287 /* The default dir name is "". Turn that into NULL to mean "current directory" */
2288 dir = proc_start_info->working_directory && mono_string_length (proc_start_info->working_directory) > 0 ?
2289 mono_string_chars (proc_start_info->working_directory) : NULL;
2291 ret = process_create (shell_path, args, dir, &startup_handles, process_info);
2293 if (shell_path != NULL)
2294 g_free (shell_path);
2297 process_info->pid = -GetLastError ();
2302 /* Returns an array of pids */
2304 ves_icall_System_Diagnostics_Process_GetProcesses_internal (void)
2311 pidarray = mono_process_list (&count);
2313 mono_set_pending_exception (mono_get_exception_not_supported ("This system does not support EnumProcesses"));
2316 procs = mono_array_new_checked (mono_domain_get (), mono_get_int32_class (), count, &error);
2317 if (mono_error_set_pending_exception (&error)) {
2321 if (sizeof (guint32) == sizeof (gpointer)) {
2322 memcpy (mono_array_addr (procs, guint32, 0), pidarray, count * sizeof (gint32));
2324 for (i = 0; i < count; ++i)
2325 *(mono_array_addr (procs, guint32, i)) = GPOINTER_TO_UINT (pidarray [i]);
2333 mono_w32process_set_cli_launcher (gchar *path)
2335 g_free (cli_launcher);
2336 cli_launcher = g_strdup (path);
2340 ves_icall_Microsoft_Win32_NativeMethods_GetCurrentProcess (void)
2342 mono_w32handle_ref (current_process);
2343 return current_process;
2347 ves_icall_Microsoft_Win32_NativeMethods_GetExitCodeProcess (gpointer handle, gint32 *exitcode)
2349 MonoW32HandleProcess *process_handle;
2356 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle)) {
2357 pid = WAPI_HANDLE_TO_PID (handle);
2358 /* This is a pseudo handle, so we don't know what the exit
2359 * code was, but we can check whether it's alive or not */
2360 if (is_pid_valid (pid)) {
2361 *exitcode = STILL_ACTIVE;
2369 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2371 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2375 if (process_handle->pid == wapi_getpid ()) {
2376 *exitcode = STILL_ACTIVE;
2380 /* A process handle is only signalled if the process has exited
2381 * and has been waited for. Make sure any process exit has been
2382 * noticed before checking if the process is signalled.
2383 * Fixes bug 325463. */
2384 mono_w32handle_wait_one (handle, 0, TRUE);
2386 *exitcode = mono_w32handle_issignalled (handle) ? process_handle->exitstatus : STILL_ACTIVE;
2391 ves_icall_Microsoft_Win32_NativeMethods_CloseProcess (gpointer handle)
2393 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
2395 return CloseHandle (handle);
2399 ves_icall_Microsoft_Win32_NativeMethods_TerminateProcess (gpointer handle, gint32 exitcode)
2402 MonoW32HandleProcess *process_handle;
2406 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle)) {
2407 /* This is a pseudo handle */
2408 pid = (pid_t)WAPI_HANDLE_TO_PID (handle);
2412 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2414 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2415 SetLastError (ERROR_INVALID_HANDLE);
2419 pid = process_handle->pid;
2422 ret = kill (pid, exitcode == -1 ? SIGKILL : SIGTERM);
2427 case EINVAL: SetLastError (ERROR_INVALID_PARAMETER); break;
2428 case EPERM: SetLastError (ERROR_ACCESS_DENIED); break;
2429 case ESRCH: SetLastError (ERROR_PROC_NOT_FOUND); break;
2430 default: SetLastError (ERROR_GEN_FAILURE); break;
2435 g_error ("kill() is not supported by this platform");
2440 ves_icall_Microsoft_Win32_NativeMethods_GetProcessWorkingSetSize (gpointer handle, gsize *min, gsize *max)
2442 MonoW32HandleProcess *process_handle;
2448 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
2451 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2453 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2457 *min = process_handle->min_working_set;
2458 *max = process_handle->max_working_set;
2463 ves_icall_Microsoft_Win32_NativeMethods_SetProcessWorkingSetSize (gpointer handle, gsize min, gsize max)
2465 MonoW32HandleProcess *process_handle;
2468 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
2471 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2473 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2477 process_handle->min_working_set = min;
2478 process_handle->max_working_set = max;
2483 ves_icall_Microsoft_Win32_NativeMethods_GetPriorityClass (gpointer handle)
2485 #ifdef HAVE_GETPRIORITY
2486 MonoW32HandleProcess *process_handle;
2490 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle)) {
2491 /* This is a pseudo handle */
2492 pid = (pid_t)WAPI_HANDLE_TO_PID (handle);
2496 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2498 SetLastError (ERROR_INVALID_HANDLE);
2502 pid = process_handle->pid;
2506 ret = getpriority (PRIO_PROCESS, pid);
2507 if (ret == -1 && errno != 0) {
2511 SetLastError (ERROR_ACCESS_DENIED);
2514 SetLastError (ERROR_PROC_NOT_FOUND);
2517 SetLastError (ERROR_GEN_FAILURE);
2523 return MONO_W32PROCESS_PRIORITY_CLASS_NORMAL;
2525 return MONO_W32PROCESS_PRIORITY_CLASS_REALTIME;
2527 return MONO_W32PROCESS_PRIORITY_CLASS_HIGH;
2529 return MONO_W32PROCESS_PRIORITY_CLASS_ABOVE_NORMAL;
2531 return MONO_W32PROCESS_PRIORITY_CLASS_IDLE;
2533 return MONO_W32PROCESS_PRIORITY_CLASS_BELOW_NORMAL;
2535 return MONO_W32PROCESS_PRIORITY_CLASS_NORMAL;
2537 SetLastError (ERROR_NOT_SUPPORTED);
2543 ves_icall_Microsoft_Win32_NativeMethods_SetPriorityClass (gpointer handle, gint32 priorityClass)
2545 #ifdef HAVE_SETPRIORITY
2546 MonoW32HandleProcess *process_handle;
2551 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle)) {
2552 /* This is a pseudo handle */
2553 pid = (pid_t)WAPI_HANDLE_TO_PID (handle);
2557 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2559 SetLastError (ERROR_INVALID_HANDLE);
2563 pid = process_handle->pid;
2566 switch (priorityClass) {
2567 case MONO_W32PROCESS_PRIORITY_CLASS_IDLE:
2570 case MONO_W32PROCESS_PRIORITY_CLASS_BELOW_NORMAL:
2573 case MONO_W32PROCESS_PRIORITY_CLASS_NORMAL:
2576 case MONO_W32PROCESS_PRIORITY_CLASS_ABOVE_NORMAL:
2579 case MONO_W32PROCESS_PRIORITY_CLASS_HIGH:
2582 case MONO_W32PROCESS_PRIORITY_CLASS_REALTIME:
2586 SetLastError (ERROR_INVALID_PARAMETER);
2590 ret = setpriority (PRIO_PROCESS, pid, prio);
2595 SetLastError (ERROR_ACCESS_DENIED);
2598 SetLastError (ERROR_PROC_NOT_FOUND);
2601 SetLastError (ERROR_GEN_FAILURE);
2607 SetLastError (ERROR_NOT_SUPPORTED);
2613 ticks_to_processtime (guint64 ticks, ProcessTime *processtime)
2615 processtime->lowDateTime = ticks & 0xFFFFFFFF;
2616 processtime->highDateTime = ticks >> 32;
2620 ves_icall_Microsoft_Win32_NativeMethods_GetProcessTimes (gpointer handle, gint64 *creation_time, gint64 *exit_time, gint64 *kernel_time, gint64 *user_time)
2622 MonoW32HandleProcess *process_handle;
2623 ProcessTime *creation_processtime, *exit_processtime, *kernel_processtime, *user_processtime;
2626 if (!creation_time || !exit_time || !kernel_time || !user_time) {
2627 /* Not sure if w32 allows NULLs here or not */
2631 creation_processtime = (ProcessTime*) creation_time;
2632 exit_processtime = (ProcessTime*) exit_time;
2633 kernel_processtime = (ProcessTime*) kernel_time;
2634 user_processtime = (ProcessTime*) user_time;
2636 memset (creation_processtime, 0, sizeof (ProcessTime));
2637 memset (exit_processtime, 0, sizeof (ProcessTime));
2638 memset (kernel_processtime, 0, sizeof (ProcessTime));
2639 memset (user_processtime, 0, sizeof (ProcessTime));
2641 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle)) {
2642 gint64 start_ticks, user_ticks, kernel_ticks;
2644 mono_process_get_times (GINT_TO_POINTER (WAPI_HANDLE_TO_PID (handle)),
2645 &start_ticks, &user_ticks, &kernel_ticks);
2647 ticks_to_processtime (start_ticks, creation_processtime);
2648 ticks_to_processtime (user_ticks, kernel_processtime);
2649 ticks_to_processtime (kernel_ticks, user_processtime);
2653 res = mono_w32handle_lookup (handle, MONO_W32HANDLE_PROCESS, (gpointer*) &process_handle);
2655 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find process %p", __func__, handle);
2659 ticks_to_processtime (process_handle->create_time, creation_processtime);
2661 /* A process handle is only signalled if the process has
2662 * exited, otherwise exit_processtime isn't set */
2663 if (mono_w32handle_issignalled (handle))
2664 ticks_to_processtime (process_handle->exit_time, exit_processtime);
2666 #ifdef HAVE_GETRUSAGE
2667 if (process_handle->pid == getpid ()) {
2668 struct rusage time_data;
2669 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
2670 ticks_to_processtime ((guint64)time_data.ru_utime.tv_sec * 10000000 + (guint64)time_data.ru_utime.tv_usec * 10, user_processtime);
2671 ticks_to_processtime ((guint64)time_data.ru_stime.tv_sec * 10000000 + (guint64)time_data.ru_stime.tv_usec * 10, kernel_processtime);
2679 static IMAGE_SECTION_HEADER *
2680 get_enclosing_section_header (guint32 rva, IMAGE_NT_HEADERS32 *nt_headers)
2682 IMAGE_SECTION_HEADER *section = IMAGE_FIRST_SECTION32 (nt_headers);
2685 for (i = 0; i < GUINT16_FROM_LE (nt_headers->FileHeader.NumberOfSections); i++, section++) {
2686 guint32 size = GUINT32_FROM_LE (section->Misc.VirtualSize);
2688 size = GUINT32_FROM_LE (section->SizeOfRawData);
2691 if ((rva >= GUINT32_FROM_LE (section->VirtualAddress)) &&
2692 (rva < (GUINT32_FROM_LE (section->VirtualAddress) + size))) {
2700 /* This works for both 32bit and 64bit files, as the differences are
2701 * all after the section header block
2704 get_ptr_from_rva (guint32 rva, IMAGE_NT_HEADERS32 *ntheaders, gpointer file_map)
2706 IMAGE_SECTION_HEADER *section_header;
2709 section_header = get_enclosing_section_header (rva, ntheaders);
2710 if (section_header == NULL) {
2714 delta = (guint32)(GUINT32_FROM_LE (section_header->VirtualAddress) -
2715 GUINT32_FROM_LE (section_header->PointerToRawData));
2717 return((guint8 *)file_map + rva - delta);
2721 scan_resource_dir (IMAGE_RESOURCE_DIRECTORY *root, IMAGE_NT_HEADERS32 *nt_headers, gpointer file_map,
2722 IMAGE_RESOURCE_DIRECTORY_ENTRY *entry, int level, guint32 res_id, guint32 lang_id, guint32 *size)
2724 IMAGE_RESOURCE_DIRECTORY_ENTRY swapped_entry;
2725 gboolean is_string, is_dir;
2726 guint32 name_offset, dir_offset, data_offset;
2728 swapped_entry.Name = GUINT32_FROM_LE (entry->Name);
2729 swapped_entry.OffsetToData = GUINT32_FROM_LE (entry->OffsetToData);
2731 is_string = swapped_entry.NameIsString;
2732 is_dir = swapped_entry.DataIsDirectory;
2733 name_offset = swapped_entry.NameOffset;
2734 dir_offset = swapped_entry.OffsetToDirectory;
2735 data_offset = swapped_entry.OffsetToData;
2738 /* Normally holds a directory entry for each type of
2741 if ((is_string == FALSE &&
2742 name_offset != res_id) ||
2743 (is_string == TRUE)) {
2746 } else if (level == 1) {
2747 /* Normally holds a directory entry for each resource
2750 } else if (level == 2) {
2751 /* Normally holds a directory entry for each language
2753 if ((is_string == FALSE &&
2754 name_offset != lang_id &&
2756 (is_string == TRUE)) {
2760 g_assert_not_reached ();
2763 if (is_dir == TRUE) {
2764 IMAGE_RESOURCE_DIRECTORY *res_dir = (IMAGE_RESOURCE_DIRECTORY *)((guint8 *)root + dir_offset);
2765 IMAGE_RESOURCE_DIRECTORY_ENTRY *sub_entries = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(res_dir + 1);
2768 entries = GUINT16_FROM_LE (res_dir->NumberOfNamedEntries) + GUINT16_FROM_LE (res_dir->NumberOfIdEntries);
2770 for (i = 0; i < entries; i++) {
2771 IMAGE_RESOURCE_DIRECTORY_ENTRY *sub_entry = &sub_entries[i];
2774 ret = scan_resource_dir (root, nt_headers, file_map,
2775 sub_entry, level + 1, res_id,
2784 IMAGE_RESOURCE_DATA_ENTRY *data_entry = (IMAGE_RESOURCE_DATA_ENTRY *)((guint8 *)root + data_offset);
2785 *size = GUINT32_FROM_LE (data_entry->Size);
2787 return(get_ptr_from_rva (GUINT32_FROM_LE (data_entry->OffsetToData), nt_headers, file_map));
2792 find_pe_file_resources32 (gpointer file_map, guint32 map_size, guint32 res_id, guint32 lang_id, guint32 *size)
2794 IMAGE_DOS_HEADER *dos_header;
2795 IMAGE_NT_HEADERS32 *nt_headers;
2796 IMAGE_RESOURCE_DIRECTORY *resource_dir;
2797 IMAGE_RESOURCE_DIRECTORY_ENTRY *resource_dir_entry;
2798 guint32 resource_rva, entries, i;
2799 gpointer ret = NULL;
2801 dos_header = (IMAGE_DOS_HEADER *)file_map;
2802 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) {
2803 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Bad dos signature 0x%x", __func__, dos_header->e_magic);
2805 SetLastError (ERROR_INVALID_DATA);
2809 if (map_size < sizeof(IMAGE_NT_HEADERS32) + GUINT32_FROM_LE (dos_header->e_lfanew)) {
2810 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File is too small: %d", __func__, map_size);
2812 SetLastError (ERROR_BAD_LENGTH);
2816 nt_headers = (IMAGE_NT_HEADERS32 *)((guint8 *)file_map + GUINT32_FROM_LE (dos_header->e_lfanew));
2817 if (nt_headers->Signature != IMAGE_NT_SIGNATURE) {
2818 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Bad NT signature 0x%x", __func__, nt_headers->Signature);
2820 SetLastError (ERROR_INVALID_DATA);
2824 if (nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
2825 /* Do 64-bit stuff */
2826 resource_rva = GUINT32_FROM_LE (((IMAGE_NT_HEADERS64 *)nt_headers)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
2828 resource_rva = GUINT32_FROM_LE (nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
2831 if (resource_rva == 0) {
2832 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: No resources in file!", __func__);
2834 SetLastError (ERROR_INVALID_DATA);
2838 resource_dir = (IMAGE_RESOURCE_DIRECTORY *)get_ptr_from_rva (resource_rva, (IMAGE_NT_HEADERS32 *)nt_headers, file_map);
2839 if (resource_dir == NULL) {
2840 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find resource directory", __func__);
2842 SetLastError (ERROR_INVALID_DATA);
2846 entries = GUINT16_FROM_LE (resource_dir->NumberOfNamedEntries) + GUINT16_FROM_LE (resource_dir->NumberOfIdEntries);
2847 resource_dir_entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resource_dir + 1);
2849 for (i = 0; i < entries; i++) {
2850 IMAGE_RESOURCE_DIRECTORY_ENTRY *direntry = &resource_dir_entry[i];
2851 ret = scan_resource_dir (resource_dir,
2852 (IMAGE_NT_HEADERS32 *)nt_headers,
2853 file_map, direntry, 0, res_id,
2864 find_pe_file_resources64 (gpointer file_map, guint32 map_size, guint32 res_id, guint32 lang_id, guint32 *size)
2866 IMAGE_DOS_HEADER *dos_header;
2867 IMAGE_NT_HEADERS64 *nt_headers;
2868 IMAGE_RESOURCE_DIRECTORY *resource_dir;
2869 IMAGE_RESOURCE_DIRECTORY_ENTRY *resource_dir_entry;
2870 guint32 resource_rva, entries, i;
2871 gpointer ret = NULL;
2873 dos_header = (IMAGE_DOS_HEADER *)file_map;
2874 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) {
2875 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Bad dos signature 0x%x", __func__, dos_header->e_magic);
2877 SetLastError (ERROR_INVALID_DATA);
2881 if (map_size < sizeof(IMAGE_NT_HEADERS64) + GUINT32_FROM_LE (dos_header->e_lfanew)) {
2882 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File is too small: %d", __func__, map_size);
2884 SetLastError (ERROR_BAD_LENGTH);
2888 nt_headers = (IMAGE_NT_HEADERS64 *)((guint8 *)file_map + GUINT32_FROM_LE (dos_header->e_lfanew));
2889 if (nt_headers->Signature != IMAGE_NT_SIGNATURE) {
2890 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Bad NT signature 0x%x", __func__,
2891 nt_headers->Signature);
2893 SetLastError (ERROR_INVALID_DATA);
2897 if (nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
2898 /* Do 64-bit stuff */
2899 resource_rva = GUINT32_FROM_LE (((IMAGE_NT_HEADERS64 *)nt_headers)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
2901 resource_rva = GUINT32_FROM_LE (nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
2904 if (resource_rva == 0) {
2905 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: No resources in file!", __func__);
2907 SetLastError (ERROR_INVALID_DATA);
2911 resource_dir = (IMAGE_RESOURCE_DIRECTORY *)get_ptr_from_rva (resource_rva, (IMAGE_NT_HEADERS32 *)nt_headers, file_map);
2912 if (resource_dir == NULL) {
2913 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't find resource directory", __func__);
2915 SetLastError (ERROR_INVALID_DATA);
2919 entries = GUINT16_FROM_LE (resource_dir->NumberOfNamedEntries) + GUINT16_FROM_LE (resource_dir->NumberOfIdEntries);
2920 resource_dir_entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resource_dir + 1);
2922 for (i = 0; i < entries; i++) {
2923 IMAGE_RESOURCE_DIRECTORY_ENTRY *direntry = &resource_dir_entry[i];
2924 ret = scan_resource_dir (resource_dir,
2925 (IMAGE_NT_HEADERS32 *)nt_headers,
2926 file_map, direntry, 0, res_id,
2937 find_pe_file_resources (gpointer file_map, guint32 map_size, guint32 res_id, guint32 lang_id, guint32 *size)
2939 /* Figure this out when we support 64bit PE files */
2941 return find_pe_file_resources32 (file_map, map_size, res_id,
2944 return find_pe_file_resources64 (file_map, map_size, res_id,
2950 map_pe_file (gunichar2 *filename, gint32 *map_size, void **handle)
2952 gchar *filename_ext;
2954 struct stat statbuf;
2957 /* According to the MSDN docs, a search path is applied to
2958 * filename. FIXME: implement this, for now just pass it
2962 filename_ext = mono_unicode_to_external (filename);
2963 if (filename_ext == NULL) {
2964 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2966 SetLastError (ERROR_INVALID_NAME);
2970 fd = _wapi_open (filename_ext, O_RDONLY, 0);
2972 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error opening file %s: %s", __func__, filename_ext, strerror (errno));
2974 SetLastError (_wapi_get_win32_file_error (errno));
2975 g_free (filename_ext);
2980 if (fstat (fd, &statbuf) == -1) {
2981 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error stat()ing file %s: %s", __func__, filename_ext, strerror (errno));
2983 SetLastError (_wapi_get_win32_file_error (errno));
2984 g_free (filename_ext);
2988 *map_size = statbuf.st_size;
2990 /* Check basic file size */
2991 if (statbuf.st_size < sizeof(IMAGE_DOS_HEADER)) {
2992 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File %s is too small: %lld", __func__, filename_ext, statbuf.st_size);
2994 SetLastError (ERROR_BAD_LENGTH);
2995 g_free (filename_ext);
3000 file_map = mono_file_map (statbuf.st_size, MONO_MMAP_READ | MONO_MMAP_PRIVATE, fd, 0, handle);
3001 if (file_map == NULL) {
3002 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error mmap()int file %s: %s", __func__, filename_ext, strerror (errno));
3004 SetLastError (_wapi_get_win32_file_error (errno));
3005 g_free (filename_ext);
3010 /* Don't need the fd any more */
3012 g_free (filename_ext);
3018 unmap_pe_file (gpointer file_map, void *handle)
3020 mono_file_unmap (file_map, handle);
3024 unicode_chars (const gunichar2 *str)
3029 if (str[len] == '\0') {
3037 unicode_compare (const gunichar2 *str1, const gunichar2 *str2)
3039 while (*str1 && *str2) {
3040 if (*str1 != *str2) {
3047 return(*str1 == *str2);
3050 /* compare a little-endian null-terminated utf16 string and a normal string.
3051 * Can be used only for ascii or latin1 chars.
3054 unicode_string_equals (const gunichar2 *str1, const gchar *str2)
3056 while (*str1 && *str2) {
3057 if (GUINT16_TO_LE (*str1) != *str2) {
3064 return(*str1 == *str2);
3074 /* Returns a pointer to the value data, because there's no way to know
3075 * how big that data is (value_len is set to zero for most blocks :-( )
3077 static gconstpointer
3078 get_versioninfo_block (gconstpointer data, version_data *block)
3080 block->data_len = GUINT16_FROM_LE (*((guint16 *)data));
3081 data = (char *)data + sizeof(guint16);
3082 block->value_len = GUINT16_FROM_LE (*((guint16 *)data));
3083 data = (char *)data + sizeof(guint16);
3085 /* No idea what the type is supposed to indicate */
3086 block->type = GUINT16_FROM_LE (*((guint16 *)data));
3087 data = (char *)data + sizeof(guint16);
3088 block->key = ((gunichar2 *)data);
3090 /* Skip over the key (including the terminator) */
3091 data = ((gunichar2 *)data) + (unicode_chars (block->key) + 1);
3093 /* align on a 32-bit boundary */
3099 static gconstpointer
3100 get_fixedfileinfo_block (gconstpointer data, version_data *block)
3102 gconstpointer data_ptr;
3103 VS_FIXEDFILEINFO *ffi;
3105 data_ptr = get_versioninfo_block (data, block);
3107 if (block->value_len != sizeof(VS_FIXEDFILEINFO)) {
3108 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: FIXEDFILEINFO size mismatch", __func__);
3112 if (!unicode_string_equals (block->key, "VS_VERSION_INFO")) {
3113 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: VS_VERSION_INFO mismatch", __func__);
3118 ffi = ((VS_FIXEDFILEINFO *)data_ptr);
3119 if ((ffi->dwSignature != VS_FFI_SIGNATURE) ||
3120 (ffi->dwStrucVersion != VS_FFI_STRUCVERSION)) {
3121 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: FIXEDFILEINFO bad signature", __func__);
3129 static gconstpointer
3130 get_varfileinfo_block (gconstpointer data_ptr, version_data *block)
3132 /* data is pointing at a Var block
3134 data_ptr = get_versioninfo_block (data_ptr, block);
3139 static gconstpointer
3140 get_string_block (gconstpointer data_ptr, const gunichar2 *string_key, gpointer *string_value,
3141 guint32 *string_value_len, version_data *block)
3143 guint16 data_len = block->data_len;
3144 guint16 string_len = 28; /* Length of the StringTable block */
3145 char *orig_data_ptr = (char *)data_ptr - 28;
3147 /* data_ptr is pointing at an array of one or more String blocks
3148 * with total length (not including alignment padding) of
3151 while (((char *)data_ptr - (char *)orig_data_ptr) < data_len) {
3152 /* align on a 32-bit boundary */
3155 data_ptr = get_versioninfo_block (data_ptr, block);
3156 if (block->data_len == 0) {
3157 /* We must have hit padding, so give up
3160 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3165 string_len = string_len + block->data_len;
3167 if (string_key != NULL &&
3168 string_value != NULL &&
3169 string_value_len != NULL &&
3170 unicode_compare (string_key, block->key) == TRUE) {
3171 *string_value = (gpointer)data_ptr;
3172 *string_value_len = block->value_len;
3175 /* Skip over the value */
3176 data_ptr = ((gunichar2 *)data_ptr) + block->value_len;
3182 /* Returns a pointer to the byte following the Stringtable block, or
3183 * NULL if the data read hits padding. We can't recover from this
3184 * because the data length does not include padding bytes, so it's not
3185 * possible to just return the start position + length
3187 * If lang == NULL it means we're just stepping through this block
3189 static gconstpointer
3190 get_stringtable_block (gconstpointer data_ptr, gchar *lang, const gunichar2 *string_key, gpointer *string_value,
3191 guint32 *string_value_len, version_data *block)
3193 guint16 data_len = block->data_len;
3194 guint16 string_len = 36; /* length of the StringFileInfo block */
3196 gchar *lowercase_lang;
3198 /* data_ptr is pointing at an array of StringTable blocks,
3199 * with total length (not including alignment padding) of
3203 while(string_len < data_len) {
3204 /* align on a 32-bit boundary */
3207 data_ptr = get_versioninfo_block (data_ptr, block);
3208 if (block->data_len == 0) {
3209 /* We must have hit padding, so give up
3212 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3216 string_len = string_len + block->data_len;
3218 found_lang = g_utf16_to_utf8 (block->key, 8, NULL, NULL, NULL);
3219 if (found_lang == NULL) {
3220 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't find a valid language key, giving up", __func__);
3224 lowercase_lang = g_utf8_strdown (found_lang, -1);
3225 g_free (found_lang);
3226 found_lang = lowercase_lang;
3227 lowercase_lang = NULL;
3229 if (lang != NULL && !strcmp (found_lang, lang)) {
3230 /* Got the one we're interested in */
3231 data_ptr = get_string_block (data_ptr, string_key,
3233 string_value_len, block);
3235 data_ptr = get_string_block (data_ptr, NULL, NULL,
3239 g_free (found_lang);
3241 if (data_ptr == NULL) {
3242 /* Child block hit padding */
3243 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Child block hit 0-length block, giving up", __func__);
3251 #if G_BYTE_ORDER == G_BIG_ENDIAN
3252 static gconstpointer
3253 big_up_string_block (gconstpointer data_ptr, version_data *block)
3255 guint16 data_len = block->data_len;
3256 guint16 string_len = 28; /* Length of the StringTable block */
3258 char *orig_data_ptr = (char *)data_ptr - 28;
3260 /* data_ptr is pointing at an array of one or more String
3261 * blocks with total length (not including alignment padding)
3264 while (((char *)data_ptr - (char *)orig_data_ptr) < data_len) {
3265 /* align on a 32-bit boundary */
3268 data_ptr = get_versioninfo_block (data_ptr, block);
3269 if (block->data_len == 0) {
3270 /* We must have hit padding, so give up
3273 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3277 string_len = string_len + block->data_len;
3279 big_value = g_convert ((gchar *)block->key,
3280 unicode_chars (block->key) * 2,
3281 "UTF-16BE", "UTF-16LE", NULL, NULL,
3283 if (big_value == NULL) {
3284 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't find a valid string, giving up", __func__);
3288 /* The swapped string should be exactly the same
3289 * length as the original little-endian one, but only
3290 * copy the number of original chars just to be on the
3293 memcpy (block->key, big_value, unicode_chars (block->key) * 2);
3296 big_value = g_convert ((gchar *)data_ptr,
3297 unicode_chars (data_ptr) * 2,
3298 "UTF-16BE", "UTF-16LE", NULL, NULL,
3300 if (big_value == NULL) {
3301 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't find a valid data string, giving up", __func__);
3304 memcpy ((gpointer)data_ptr, big_value,
3305 unicode_chars (data_ptr) * 2);
3308 data_ptr = ((gunichar2 *)data_ptr) + block->value_len;
3314 /* Returns a pointer to the byte following the Stringtable block, or
3315 * NULL if the data read hits padding. We can't recover from this
3316 * because the data length does not include padding bytes, so it's not
3317 * possible to just return the start position + length
3319 static gconstpointer
3320 big_up_stringtable_block (gconstpointer data_ptr, version_data *block)
3322 guint16 data_len = block->data_len;
3323 guint16 string_len = 36; /* length of the StringFileInfo block */
3326 /* data_ptr is pointing at an array of StringTable blocks,
3327 * with total length (not including alignment padding) of
3331 while(string_len < data_len) {
3332 /* align on a 32-bit boundary */
3335 data_ptr = get_versioninfo_block (data_ptr, block);
3336 if (block->data_len == 0) {
3337 /* We must have hit padding, so give up
3340 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3344 string_len = string_len + block->data_len;
3346 big_value = g_convert ((gchar *)block->key, 16, "UTF-16BE",
3347 "UTF-16LE", NULL, NULL, NULL);
3348 if (big_value == NULL) {
3349 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Didn't find a valid string, giving up", __func__);
3353 memcpy (block->key, big_value, 16);
3356 data_ptr = big_up_string_block (data_ptr, block);
3358 if (data_ptr == NULL) {
3359 /* Child block hit padding */
3360 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Child block hit 0-length block, giving up", __func__);
3368 /* Follows the data structures and turns all UTF-16 strings from the
3369 * LE found in the resource section into UTF-16BE
3372 big_up (gconstpointer datablock, guint32 size)
3374 gconstpointer data_ptr;
3375 gint32 data_len; /* signed to guard against underflow */
3378 data_ptr = get_fixedfileinfo_block (datablock, &block);
3379 if (data_ptr != NULL) {
3380 VS_FIXEDFILEINFO *ffi = (VS_FIXEDFILEINFO *)data_ptr;
3382 /* Byteswap all the fields */
3383 ffi->dwFileVersionMS = GUINT32_SWAP_LE_BE (ffi->dwFileVersionMS);
3384 ffi->dwFileVersionLS = GUINT32_SWAP_LE_BE (ffi->dwFileVersionLS);
3385 ffi->dwProductVersionMS = GUINT32_SWAP_LE_BE (ffi->dwProductVersionMS);
3386 ffi->dwProductVersionLS = GUINT32_SWAP_LE_BE (ffi->dwProductVersionLS);
3387 ffi->dwFileFlagsMask = GUINT32_SWAP_LE_BE (ffi->dwFileFlagsMask);
3388 ffi->dwFileFlags = GUINT32_SWAP_LE_BE (ffi->dwFileFlags);
3389 ffi->dwFileOS = GUINT32_SWAP_LE_BE (ffi->dwFileOS);
3390 ffi->dwFileType = GUINT32_SWAP_LE_BE (ffi->dwFileType);
3391 ffi->dwFileSubtype = GUINT32_SWAP_LE_BE (ffi->dwFileSubtype);
3392 ffi->dwFileDateMS = GUINT32_SWAP_LE_BE (ffi->dwFileDateMS);
3393 ffi->dwFileDateLS = GUINT32_SWAP_LE_BE (ffi->dwFileDateLS);
3395 /* The FFI and header occupies the first 92 bytes
3397 data_ptr = (char *)data_ptr + sizeof(VS_FIXEDFILEINFO);
3398 data_len = block.data_len - 92;
3400 /* There now follow zero or one StringFileInfo blocks
3401 * and zero or one VarFileInfo blocks
3403 while (data_len > 0) {
3404 /* align on a 32-bit boundary */
3407 data_ptr = get_versioninfo_block (data_ptr, &block);
3408 if (block.data_len == 0) {
3409 /* We must have hit padding, so give
3412 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3416 data_len = data_len - block.data_len;
3418 if (unicode_string_equals (block.key, "VarFileInfo")) {
3419 data_ptr = get_varfileinfo_block (data_ptr,
3421 data_ptr = ((guchar *)data_ptr) + block.value_len;
3422 } else if (unicode_string_equals (block.key,
3423 "StringFileInfo")) {
3424 data_ptr = big_up_stringtable_block (data_ptr,
3428 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Not a valid VERSIONINFO child block", __func__);
3432 if (data_ptr == NULL) {
3433 /* Child block hit padding */
3434 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Child block hit 0-length block, giving up", __func__);
3443 mono_w32process_get_fileversion_info_size (gunichar2 *filename, guint32 *handle)
3446 gpointer versioninfo;
3451 /* This value is unused, but set to zero */
3454 file_map = map_pe_file (filename, &map_size, &map_handle);
3455 if (file_map == NULL) {
3459 versioninfo = find_pe_file_resources (file_map, map_size, RT_VERSION, 0, &size);
3460 if (versioninfo == NULL) {
3461 /* Didn't find the resource, so set the return value
3467 unmap_pe_file (file_map, map_handle);
3473 mono_w32process_get_fileversion_info (gunichar2 *filename, guint32 handle G_GNUC_UNUSED, guint32 len, gpointer data)
3476 gpointer versioninfo;
3480 gboolean ret = FALSE;
3482 file_map = map_pe_file (filename, &map_size, &map_handle);
3483 if (file_map == NULL) {
3487 versioninfo = find_pe_file_resources (file_map, map_size, RT_VERSION,
3489 if (versioninfo != NULL) {
3490 /* This could probably process the data so that
3491 * mono_w32process_ver_query_value() doesn't have to follow the data
3492 * blocks every time. But hey, these functions aren't
3493 * likely to appear in many profiles.
3495 memcpy (data, versioninfo, len < size?len:size);
3498 #if G_BYTE_ORDER == G_BIG_ENDIAN
3499 big_up (data, size);
3503 unmap_pe_file (file_map, map_handle);
3509 mono_w32process_ver_query_value (gconstpointer datablock, const gunichar2 *subblock, gpointer *buffer, guint32 *len)
3511 gchar *subblock_utf8, *lang_utf8 = NULL;
3512 gboolean ret = FALSE;
3514 gconstpointer data_ptr;
3515 gint32 data_len; /* signed to guard against underflow */
3516 gboolean want_var = FALSE;
3517 gboolean want_string = FALSE;
3519 const gunichar2 *string_key = NULL;
3520 gpointer string_value = NULL;
3521 guint32 string_value_len = 0;
3522 gchar *lowercase_lang;
3524 subblock_utf8 = g_utf16_to_utf8 (subblock, -1, NULL, NULL, NULL);
3525 if (subblock_utf8 == NULL) {
3529 if (!strcmp (subblock_utf8, "\\VarFileInfo\\Translation")) {
3531 } else if (!strncmp (subblock_utf8, "\\StringFileInfo\\", 16)) {
3533 memcpy (lang, subblock + 16, 8 * sizeof(gunichar2));
3534 lang_utf8 = g_utf16_to_utf8 (lang, 8, NULL, NULL, NULL);
3535 lowercase_lang = g_utf8_strdown (lang_utf8, -1);
3537 lang_utf8 = lowercase_lang;
3538 lowercase_lang = NULL;
3539 string_key = subblock + 25;
3542 if (!strcmp (subblock_utf8, "\\")) {
3543 data_ptr = get_fixedfileinfo_block (datablock, &block);
3544 if (data_ptr != NULL) {
3545 *buffer = (gpointer)data_ptr;
3546 *len = block.value_len;
3550 } else if (want_var || want_string) {
3551 data_ptr = get_fixedfileinfo_block (datablock, &block);
3552 if (data_ptr != NULL) {
3553 /* The FFI and header occupies the first 92
3556 data_ptr = (char *)data_ptr + sizeof(VS_FIXEDFILEINFO);
3557 data_len = block.data_len - 92;
3559 /* There now follow zero or one StringFileInfo
3560 * blocks and zero or one VarFileInfo blocks
3562 while (data_len > 0) {
3563 /* align on a 32-bit boundary */
3566 data_ptr = get_versioninfo_block (data_ptr,
3568 if (block.data_len == 0) {
3569 /* We must have hit padding,
3570 * so give up processing now
3572 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hit 0-length block, giving up", __func__);
3576 data_len = data_len - block.data_len;
3578 if (unicode_string_equals (block.key, "VarFileInfo")) {
3579 data_ptr = get_varfileinfo_block (data_ptr, &block);
3581 *buffer = (gpointer)data_ptr;
3582 *len = block.value_len;
3586 /* Skip over the Var block */
3587 data_ptr = ((guchar *)data_ptr) + block.value_len;
3589 } else if (unicode_string_equals (block.key, "StringFileInfo")) {
3590 data_ptr = get_stringtable_block (data_ptr, lang_utf8, string_key, &string_value, &string_value_len, &block);
3592 string_value != NULL &&
3593 string_value_len != 0) {
3594 *buffer = string_value;
3595 *len = unicode_chars ((const gunichar2 *)string_value) + 1; /* Include trailing null */
3601 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Not a valid VERSIONINFO child block", __func__);
3605 if (data_ptr == NULL) {
3606 /* Child block hit padding */
3607 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Child block hit 0-length block, giving up", __func__);
3619 g_free (subblock_utf8);
3624 copy_lang (gunichar2 *lang_out, guint32 lang_len, const gchar *text)
3627 int chars = strlen (text);
3630 unitext = g_utf8_to_utf16 (text, -1, NULL, NULL, NULL);
3631 g_assert (unitext != NULL);
3633 if (chars < (lang_len - 1)) {
3634 memcpy (lang_out, (gpointer)unitext, chars * 2);
3635 lang_out[chars] = '\0';
3638 memcpy (lang_out, (gpointer)unitext, (lang_len - 1) * 2);
3639 lang_out[lang_len] = '\0';
3649 mono_w32process_ver_language_name (guint32 lang, gunichar2 *lang_out, guint32 lang_len)
3651 int primary, secondary;
3652 const char *name = NULL;
3654 primary = lang & 0x3FF;
3655 secondary = (lang >> 10) & 0x3F;
3659 switch (secondary) {
3660 case 0x01: name = "Process Default Language"; break;
3664 switch (secondary) {
3666 case 0x01: name = "Arabic (Saudi Arabia)"; break;
3667 case 0x02: name = "Arabic (Iraq)"; break;
3668 case 0x03: name = "Arabic (Egypt)"; break;
3669 case 0x04: name = "Arabic (Libya)"; break;
3670 case 0x05: name = "Arabic (Algeria)"; break;
3671 case 0x06: name = "Arabic (Morocco)"; break;
3672 case 0x07: name = "Arabic (Tunisia)"; break;
3673 case 0x08: name = "Arabic (Oman)"; break;
3674 case 0x09: name = "Arabic (Yemen)"; break;
3675 case 0x0a: name = "Arabic (Syria)"; break;
3676 case 0x0b: name = "Arabic (Jordan)"; break;
3677 case 0x0c: name = "Arabic (Lebanon)"; break;
3678 case 0x0d: name = "Arabic (Kuwait)"; break;
3679 case 0x0e: name = "Arabic (U.A.E.)"; break;
3680 case 0x0f: name = "Arabic (Bahrain)"; break;
3681 case 0x10: name = "Arabic (Qatar)"; break;
3685 switch (secondary) {
3686 case 0x00: name = "Bulgarian (Bulgaria)"; break;
3687 case 0x01: name = "Bulgarian"; break;
3691 switch (secondary) {
3692 case 0x00: name = "Catalan (Spain)"; break;
3693 case 0x01: name = "Catalan"; break;
3697 switch (secondary) {
3699 case 0x01: name = "Chinese (Taiwan)"; break;
3700 case 0x02: name = "Chinese (PRC)"; break;
3701 case 0x03: name = "Chinese (Hong Kong S.A.R.)"; break;
3702 case 0x04: name = "Chinese (Singapore)"; break;
3703 case 0x05: name = "Chinese (Macau S.A.R.)"; break;
3707 switch (secondary) {
3708 case 0x00: name = "Czech (Czech Republic)"; break;
3709 case 0x01: name = "Czech"; break;
3713 switch (secondary) {
3714 case 0x00: name = "Danish (Denmark)"; break;
3715 case 0x01: name = "Danish"; break;
3719 switch (secondary) {
3721 case 0x01: name = "German (Germany)"; break;
3722 case 0x02: name = "German (Switzerland)"; break;
3723 case 0x03: name = "German (Austria)"; break;
3724 case 0x04: name = "German (Luxembourg)"; break;
3725 case 0x05: name = "German (Liechtenstein)"; break;
3729 switch (secondary) {
3730 case 0x00: name = "Greek (Greece)"; break;
3731 case 0x01: name = "Greek"; break;
3735 switch (secondary) {
3737 case 0x01: name = "English (United States)"; break;
3738 case 0x02: name = "English (United Kingdom)"; break;
3739 case 0x03: name = "English (Australia)"; break;
3740 case 0x04: name = "English (Canada)"; break;
3741 case 0x05: name = "English (New Zealand)"; break;
3742 case 0x06: name = "English (Ireland)"; break;
3743 case 0x07: name = "English (South Africa)"; break;
3744 case 0x08: name = "English (Jamaica)"; break;
3745 case 0x09: name = "English (Caribbean)"; break;
3746 case 0x0a: name = "English (Belize)"; break;
3747 case 0x0b: name = "English (Trinidad and Tobago)"; break;
3748 case 0x0c: name = "English (Zimbabwe)"; break;
3749 case 0x0d: name = "English (Philippines)"; break;
3750 case 0x10: name = "English (India)"; break;
3751 case 0x11: name = "English (Malaysia)"; break;
3752 case 0x12: name = "English (Singapore)"; break;
3756 switch (secondary) {
3757 case 0x00: name = "Spanish (Spain)"; break;
3758 case 0x01: name = "Spanish (Traditional Sort)"; break;
3759 case 0x02: name = "Spanish (Mexico)"; break;
3760 case 0x03: name = "Spanish (International Sort)"; break;
3761 case 0x04: name = "Spanish (Guatemala)"; break;
3762 case 0x05: name = "Spanish (Costa Rica)"; break;
3763 case 0x06: name = "Spanish (Panama)"; break;
3764 case 0x07: name = "Spanish (Dominican Republic)"; break;
3765 case 0x08: name = "Spanish (Venezuela)"; break;
3766 case 0x09: name = "Spanish (Colombia)"; break;
3767 case 0x0a: name = "Spanish (Peru)"; break;
3768 case 0x0b: name = "Spanish (Argentina)"; break;
3769 case 0x0c: name = "Spanish (Ecuador)"; break;
3770 case 0x0d: name = "Spanish (Chile)"; break;
3771 case 0x0e: name = "Spanish (Uruguay)"; break;
3772 case 0x0f: name = "Spanish (Paraguay)"; break;
3773 case 0x10: name = "Spanish (Bolivia)"; break;
3774 case 0x11: name = "Spanish (El Salvador)"; break;
3775 case 0x12: name = "Spanish (Honduras)"; break;
3776 case 0x13: name = "Spanish (Nicaragua)"; break;
3777 case 0x14: name = "Spanish (Puerto Rico)"; break;
3778 case 0x15: name = "Spanish (United States)"; break;
3782 switch (secondary) {
3783 case 0x00: name = "Finnish (Finland)"; break;
3784 case 0x01: name = "Finnish"; break;
3788 switch (secondary) {
3790 case 0x01: name = "French (France)"; break;
3791 case 0x02: name = "French (Belgium)"; break;
3792 case 0x03: name = "French (Canada)"; break;
3793 case 0x04: name = "French (Switzerland)"; break;
3794 case 0x05: name = "French (Luxembourg)"; break;
3795 case 0x06: name = "French (Monaco)"; break;
3799 switch (secondary) {
3800 case 0x00: name = "Hebrew (Israel)"; break;
3801 case 0x01: name = "Hebrew"; break;
3805 switch (secondary) {
3806 case 0x00: name = "Hungarian (Hungary)"; break;
3807 case 0x01: name = "Hungarian"; break;
3811 switch (secondary) {
3812 case 0x00: name = "Icelandic (Iceland)"; break;
3813 case 0x01: name = "Icelandic"; break;
3817 switch (secondary) {
3819 case 0x01: name = "Italian (Italy)"; break;
3820 case 0x02: name = "Italian (Switzerland)"; break;
3824 switch (secondary) {
3825 case 0x00: name = "Japanese (Japan)"; break;
3826 case 0x01: name = "Japanese"; break;
3830 switch (secondary) {
3831 case 0x00: name = "Korean (Korea)"; break;
3832 case 0x01: name = "Korean"; break;
3836 switch (secondary) {
3838 case 0x01: name = "Dutch (Netherlands)"; break;
3839 case 0x02: name = "Dutch (Belgium)"; break;
3843 switch (secondary) {
3845 case 0x01: name = "Norwegian (Bokmal)"; break;
3846 case 0x02: name = "Norwegian (Nynorsk)"; break;
3850 switch (secondary) {
3851 case 0x00: name = "Polish (Poland)"; break;
3852 case 0x01: name = "Polish"; break;
3856 switch (secondary) {
3858 case 0x01: name = "Portuguese (Brazil)"; break;
3859 case 0x02: name = "Portuguese (Portugal)"; break;
3863 switch (secondary) {
3864 case 0x01: name = "Romansh (Switzerland)"; break;
3868 switch (secondary) {
3869 case 0x00: name = "Romanian (Romania)"; break;
3870 case 0x01: name = "Romanian"; break;
3874 switch (secondary) {
3875 case 0x00: name = "Russian (Russia)"; break;
3876 case 0x01: name = "Russian"; break;
3880 switch (secondary) {
3881 case 0x00: name = "Croatian (Croatia)"; break;
3882 case 0x01: name = "Croatian"; break;
3883 case 0x02: name = "Serbian (Latin)"; break;
3884 case 0x03: name = "Serbian (Cyrillic)"; break;
3885 case 0x04: name = "Croatian (Bosnia and Herzegovina)"; break;
3886 case 0x05: name = "Bosnian (Latin, Bosnia and Herzegovina)"; break;
3887 case 0x06: name = "Serbian (Latin, Bosnia and Herzegovina)"; break;
3888 case 0x07: name = "Serbian (Cyrillic, Bosnia and Herzegovina)"; break;
3889 case 0x08: name = "Bosnian (Cyrillic, Bosnia and Herzegovina)"; break;
3893 switch (secondary) {
3894 case 0x00: name = "Slovak (Slovakia)"; break;
3895 case 0x01: name = "Slovak"; break;
3899 switch (secondary) {
3900 case 0x00: name = "Albanian (Albania)"; break;
3901 case 0x01: name = "Albanian"; break;
3905 switch (secondary) {
3906 case 0x00: name = "Swedish (Sweden)"; break;
3907 case 0x01: name = "Swedish"; break;
3908 case 0x02: name = "Swedish (Finland)"; break;
3912 switch (secondary) {
3913 case 0x00: name = "Thai (Thailand)"; break;
3914 case 0x01: name = "Thai"; break;
3918 switch (secondary) {
3919 case 0x00: name = "Turkish (Turkey)"; break;
3920 case 0x01: name = "Turkish"; break;
3924 switch (secondary) {
3925 case 0x00: name = "Urdu (Islamic Republic of Pakistan)"; break;
3926 case 0x01: name = "Urdu"; break;
3930 switch (secondary) {
3931 case 0x00: name = "Indonesian (Indonesia)"; break;
3932 case 0x01: name = "Indonesian"; break;
3936 switch (secondary) {
3937 case 0x00: name = "Ukrainian (Ukraine)"; break;
3938 case 0x01: name = "Ukrainian"; break;
3942 switch (secondary) {
3943 case 0x00: name = "Belarusian (Belarus)"; break;
3944 case 0x01: name = "Belarusian"; break;
3948 switch (secondary) {
3949 case 0x00: name = "Slovenian (Slovenia)"; break;
3950 case 0x01: name = "Slovenian"; break;
3954 switch (secondary) {
3955 case 0x00: name = "Estonian (Estonia)"; break;
3956 case 0x01: name = "Estonian"; break;
3960 switch (secondary) {
3961 case 0x00: name = "Latvian (Latvia)"; break;
3962 case 0x01: name = "Latvian"; break;
3966 switch (secondary) {
3967 case 0x00: name = "Lithuanian (Lithuania)"; break;
3968 case 0x01: name = "Lithuanian"; break;
3972 switch (secondary) {
3973 case 0x01: name = "Tajik (Tajikistan)"; break;
3977 switch (secondary) {
3978 case 0x00: name = "Farsi (Iran)"; break;
3979 case 0x01: name = "Farsi"; break;
3983 switch (secondary) {
3984 case 0x00: name = "Vietnamese (Viet Nam)"; break;
3985 case 0x01: name = "Vietnamese"; break;
3989 switch (secondary) {
3990 case 0x00: name = "Armenian (Armenia)"; break;
3991 case 0x01: name = "Armenian"; break;
3995 switch (secondary) {
3996 case 0x00: name = "Azeri (Latin) (Azerbaijan)"; break;
3997 case 0x01: name = "Azeri (Latin)"; break;
3998 case 0x02: name = "Azeri (Cyrillic)"; break;
4002 switch (secondary) {
4003 case 0x00: name = "Basque (Spain)"; break;
4004 case 0x01: name = "Basque"; break;
4008 switch (secondary) {
4009 case 0x01: name = "Upper Sorbian (Germany)"; break;
4010 case 0x02: name = "Lower Sorbian (Germany)"; break;
4014 switch (secondary) {
4015 case 0x00: name = "FYRO Macedonian (Former Yugoslav Republic of Macedonia)"; break;
4016 case 0x01: name = "FYRO Macedonian"; break;
4020 switch (secondary) {
4021 case 0x00: name = "Tswana (South Africa)"; break;
4022 case 0x01: name = "Tswana"; break;
4026 switch (secondary) {
4027 case 0x00: name = "Xhosa (South Africa)"; break;
4028 case 0x01: name = "Xhosa"; break;
4032 switch (secondary) {
4033 case 0x00: name = "Zulu (South Africa)"; break;
4034 case 0x01: name = "Zulu"; break;
4038 switch (secondary) {
4039 case 0x00: name = "Afrikaans (South Africa)"; break;
4040 case 0x01: name = "Afrikaans"; break;
4044 switch (secondary) {
4045 case 0x00: name = "Georgian (Georgia)"; break;
4046 case 0x01: name = "Georgian"; break;
4050 switch (secondary) {
4051 case 0x00: name = "Faroese (Faroe Islands)"; break;
4052 case 0x01: name = "Faroese"; break;
4056 switch (secondary) {
4057 case 0x00: name = "Hindi (India)"; break;
4058 case 0x01: name = "Hindi"; break;
4062 switch (secondary) {
4063 case 0x00: name = "Maltese (Malta)"; break;
4064 case 0x01: name = "Maltese"; break;
4068 switch (secondary) {
4069 case 0x00: name = "Sami (Northern) (Norway)"; break;
4070 case 0x01: name = "Sami, Northern (Norway)"; break;
4071 case 0x02: name = "Sami, Northern (Sweden)"; break;
4072 case 0x03: name = "Sami, Northern (Finland)"; break;
4073 case 0x04: name = "Sami, Lule (Norway)"; break;
4074 case 0x05: name = "Sami, Lule (Sweden)"; break;
4075 case 0x06: name = "Sami, Southern (Norway)"; break;
4076 case 0x07: name = "Sami, Southern (Sweden)"; break;
4077 case 0x08: name = "Sami, Skolt (Finland)"; break;
4078 case 0x09: name = "Sami, Inari (Finland)"; break;
4082 switch (secondary) {
4083 case 0x02: name = "Irish (Ireland)"; break;
4087 switch (secondary) {
4089 case 0x01: name = "Malay (Malaysia)"; break;
4090 case 0x02: name = "Malay (Brunei Darussalam)"; break;
4094 switch (secondary) {
4095 case 0x00: name = "Kazakh (Kazakhstan)"; break;
4096 case 0x01: name = "Kazakh"; break;
4100 switch (secondary) {
4101 case 0x00: name = "Kyrgyz (Kyrgyzstan)"; break;
4102 case 0x01: name = "Kyrgyz (Cyrillic)"; break;
4106 switch (secondary) {
4107 case 0x00: name = "Swahili (Kenya)"; break;
4108 case 0x01: name = "Swahili"; break;
4112 switch (secondary) {
4113 case 0x01: name = "Turkmen (Turkmenistan)"; break;
4117 switch (secondary) {
4118 case 0x00: name = "Uzbek (Latin) (Uzbekistan)"; break;
4119 case 0x01: name = "Uzbek (Latin)"; break;
4120 case 0x02: name = "Uzbek (Cyrillic)"; break;
4124 switch (secondary) {
4125 case 0x00: name = "Tatar (Russia)"; break;
4126 case 0x01: name = "Tatar"; break;
4130 switch (secondary) {
4132 case 0x01: name = "Bengali (India)"; break;
4136 switch (secondary) {
4137 case 0x00: name = "Punjabi (India)"; break;
4138 case 0x01: name = "Punjabi"; break;
4142 switch (secondary) {
4143 case 0x00: name = "Gujarati (India)"; break;
4144 case 0x01: name = "Gujarati"; break;
4148 switch (secondary) {
4149 case 0x00: name = "Tamil (India)"; break;
4150 case 0x01: name = "Tamil"; break;
4154 switch (secondary) {
4155 case 0x00: name = "Telugu (India)"; break;
4156 case 0x01: name = "Telugu"; break;
4160 switch (secondary) {
4161 case 0x00: name = "Kannada (India)"; break;
4162 case 0x01: name = "Kannada"; break;
4166 switch (secondary) {
4168 case 0x01: name = "Malayalam (India)"; break;
4172 switch (secondary) {
4173 case 0x01: name = "Assamese (India)"; break;
4177 switch (secondary) {
4178 case 0x00: name = "Marathi (India)"; break;
4179 case 0x01: name = "Marathi"; break;
4183 switch (secondary) {
4184 case 0x00: name = "Sanskrit (India)"; break;
4185 case 0x01: name = "Sanskrit"; break;
4189 switch (secondary) {
4190 case 0x00: name = "Mongolian (Mongolia)"; break;
4191 case 0x01: name = "Mongolian (Cyrillic)"; break;
4192 case 0x02: name = "Mongolian (PRC)"; break;
4196 switch (secondary) {
4197 case 0x01: name = "Tibetan (PRC)"; break;
4198 case 0x02: name = "Tibetan (Bhutan)"; break;
4202 switch (secondary) {
4203 case 0x00: name = "Welsh (United Kingdom)"; break;
4204 case 0x01: name = "Welsh"; break;
4208 switch (secondary) {
4209 case 0x01: name = "Khmer (Cambodia)"; break;
4213 switch (secondary) {
4214 case 0x01: name = "Lao (Lao PDR)"; break;
4218 switch (secondary) {
4219 case 0x00: name = "Galician (Spain)"; break;
4220 case 0x01: name = "Galician"; break;
4224 switch (secondary) {
4225 case 0x00: name = "Konkani (India)"; break;
4226 case 0x01: name = "Konkani"; break;
4230 switch (secondary) {
4231 case 0x00: name = "Syriac (Syria)"; break;
4232 case 0x01: name = "Syriac"; break;
4236 switch (secondary) {
4237 case 0x01: name = "Sinhala (Sri Lanka)"; break;
4241 switch (secondary) {
4242 case 0x01: name = "Inuktitut (Syllabics, Canada)"; break;
4243 case 0x02: name = "Inuktitut (Latin, Canada)"; break;
4247 switch (secondary) {
4248 case 0x01: name = "Amharic (Ethiopia)"; break;
4252 switch (secondary) {
4253 case 0x02: name = "Tamazight (Algeria, Latin)"; break;
4257 switch (secondary) {
4258 case 0x01: name = "Nepali (Nepal)"; break;
4262 switch (secondary) {
4263 case 0x01: name = "Frisian (Netherlands)"; break;
4267 switch (secondary) {
4268 case 0x01: name = "Pashto (Afghanistan)"; break;
4272 switch (secondary) {
4273 case 0x01: name = "Filipino (Philippines)"; break;
4277 switch (secondary) {
4278 case 0x00: name = "Divehi (Maldives)"; break;
4279 case 0x01: name = "Divehi"; break;
4283 switch (secondary) {
4284 case 0x01: name = "Hausa (Nigeria, Latin)"; break;
4288 switch (secondary) {
4289 case 0x01: name = "Yoruba (Nigeria)"; break;
4293 switch (secondary) {
4295 case 0x01: name = "Quechua (Bolivia)"; break;
4296 case 0x02: name = "Quechua (Ecuador)"; break;
4297 case 0x03: name = "Quechua (Peru)"; break;
4301 switch (secondary) {
4302 case 0x00: name = "Northern Sotho (South Africa)"; break;
4303 case 0x01: name = "Northern Sotho"; break;
4307 switch (secondary) {
4308 case 0x01: name = "Bashkir (Russia)"; break;
4312 switch (secondary) {
4313 case 0x01: name = "Luxembourgish (Luxembourg)"; break;
4317 switch (secondary) {
4318 case 0x01: name = "Greenlandic (Greenland)"; break;
4322 switch (secondary) {
4323 case 0x01: name = "Yi (PRC)"; break;
4327 switch (secondary) {
4328 case 0x01: name = "Mapudungun (Chile)"; break;
4332 switch (secondary) {
4333 case 0x01: name = "Mohawk (Mohawk)"; break;
4337 switch (secondary) {
4338 case 0x01: name = "Breton (France)"; break;
4342 switch (secondary) {
4343 case 0x00: name = "Invariant Language (Invariant Country)"; break;
4347 switch (secondary) {
4348 case 0x01: name = "Uighur (PRC)"; break;
4352 switch (secondary) {
4353 case 0x00: name = "Maori (New Zealand)"; break;
4354 case 0x01: name = "Maori"; break;
4358 switch (secondary) {
4359 case 0x01: name = "Corsican (France)"; break;
4363 switch (secondary) {
4364 case 0x01: name = "Alsatian (France)"; break;
4368 switch (secondary) {
4369 case 0x01: name = "Yakut (Russia)"; break;
4373 switch (secondary) {
4374 case 0x01: name = "K'iche (Guatemala)"; break;
4378 switch (secondary) {
4379 case 0x01: name = "Kinyarwanda (Rwanda)"; break;
4383 switch (secondary) {
4384 case 0x01: name = "Wolof (Senegal)"; break;
4388 switch (secondary) {
4389 case 0x01: name = "Dari (Afghanistan)"; break;
4394 name = "Language Neutral";
4399 name = "Language Neutral";
4401 return copy_lang (lang_out, lang_len, name);