1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1998 Peter Mattis, Spencer Kimball and Josh MacDonald
3 * Copyright (C) 1998-1999 Tor Lillqvist
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
21 * file for a list of people on the GLib Team. See the ChangeLog
22 * files for a list of changes. These files are distributed with
23 * GLib at ftp://ftp.gtk.org/pub/gtk/.
27 * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
32 #include "glibconfig.h"
41 #define STRICT /* Strict typing, please */
49 #if defined(_MSC_VER) || defined(__DMC__)
51 #endif /* _MSC_VER || __DMC__ */
53 #define MODERN_API_FAMILY 2
55 #if WINAPI_FAMILY == MODERN_API_FAMILY
56 /* This is for modern UI Builds, where we can't use LoadLibraryW()/GetProcAddress() */
57 /* ntddk.h is found in the WDK, and MinGW */
61 #pragma comment (lib, "ntoskrnl.lib")
63 #elif defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
64 /* mingw-w64 must use winternl.h, but not MinGW */
71 #include "gthreadprivate.h"
72 #include "glib-init.h"
75 #include <sys/cygwin.h>
81 g_win32_ftruncate (gint fd
,
84 return _chsize (fd
, size
);
92 * The setlocale() function in the Microsoft C library uses locale
93 * names of the form "English_United States.1252" etc. We want the
94 * UNIXish standard form "en_US", "zh_TW" etc. This function gets the
95 * current thread locale from Windows - without any encoding info -
96 * and returns it as a string of the above form for use in forming
97 * file names etc. The returned string should be deallocated with
100 * Returns: newly-allocated locale name.
103 #ifndef SUBLANG_SERBIAN_LATIN_BA
104 #define SUBLANG_SERBIAN_LATIN_BA 0x06
108 g_win32_getlocale (void)
116 const gchar
*script
= NULL
;
118 /* Let the user override the system settings through environment
119 * variables, as on POSIX systems. Note that in GTK+ applications
120 * since GTK+ 2.10.7 setting either LC_ALL or LANG also sets the
121 * Win32 locale and C library locale through code in gtkmain.c.
123 if (((ev
= getenv ("LC_ALL")) != NULL
&& ev
[0] != '\0')
124 || ((ev
= getenv ("LC_MESSAGES")) != NULL
&& ev
[0] != '\0')
125 || ((ev
= getenv ("LANG")) != NULL
&& ev
[0] != '\0'))
126 return g_strdup (ev
);
128 lcid
= GetThreadLocale ();
130 if (!GetLocaleInfo (lcid
, LOCALE_SISO639LANGNAME
, iso639
, sizeof (iso639
)) ||
131 !GetLocaleInfo (lcid
, LOCALE_SISO3166CTRYNAME
, iso3166
, sizeof (iso3166
)))
132 return g_strdup ("C");
134 /* Strip off the sorting rules, keep only the language part. */
135 langid
= LANGIDFROMLCID (lcid
);
137 /* Split into language and territory part. */
138 primary
= PRIMARYLANGID (langid
);
139 sub
= SUBLANGID (langid
);
141 /* Handle special cases */
147 case SUBLANG_AZERI_LATIN
:
150 case SUBLANG_AZERI_CYRILLIC
:
155 case LANG_SERBIAN
: /* LANG_CROATIAN == LANG_SERBIAN */
158 case SUBLANG_SERBIAN_LATIN
:
159 case 0x06: /* Serbian (Latin) - Bosnia and Herzegovina */
167 case SUBLANG_UZBEK_LATIN
:
170 case SUBLANG_UZBEK_CYRILLIC
:
176 return g_strconcat (iso639
, "_", iso3166
, script
, NULL
);
180 * g_win32_error_message:
181 * @error: error code.
183 * Translate a Win32 error code (as returned by GetLastError() or
184 * WSAGetLastError()) into the corresponding message. The message is
185 * either language neutral, or in the thread's language, or the user's
186 * language, the system's language, or US English (see docs for
187 * FormatMessage()). The returned string is in UTF-8. It should be
188 * deallocated with g_free().
190 * Returns: newly-allocated error message
193 g_win32_error_message (gint error
)
199 FormatMessageW (FORMAT_MESSAGE_ALLOCATE_BUFFER
200 |FORMAT_MESSAGE_IGNORE_INSERTS
201 |FORMAT_MESSAGE_FROM_SYSTEM
,
203 (LPWSTR
) &msg
, 0, NULL
);
206 nchars
= wcslen (msg
);
208 if (nchars
>= 2 && msg
[nchars
-1] == L
'\n' && msg
[nchars
-2] == L
'\r')
209 msg
[nchars
-2] = L
'\0';
211 retval
= g_utf16_to_utf8 (msg
, -1, NULL
, NULL
, NULL
);
216 retval
= g_strdup ("");
222 * g_win32_get_package_installation_directory_of_module:
223 * @hmodule: (nullable): The Win32 handle for a DLL loaded into the current process, or %NULL
225 * This function tries to determine the installation directory of a
226 * software package based on the location of a DLL of the software
229 * @hmodule should be the handle of a loaded DLL or %NULL. The
230 * function looks up the directory that DLL was loaded from. If
231 * @hmodule is NULL, the directory the main executable of the current
232 * process is looked up. If that directory's last component is "bin"
233 * or "lib", its parent directory is returned, otherwise the directory
236 * It thus makes sense to pass only the handle to a "public" DLL of a
237 * software package to this function, as such DLLs typically are known
238 * to be installed in a "bin" or occasionally "lib" subfolder of the
239 * installation folder. DLLs that are of the dynamically loaded module
240 * or plugin variety are often located in more private locations
241 * deeper down in the tree, from which it is impossible for GLib to
242 * deduce the root of the package installation.
244 * The typical use case for this function is to have a DllMain() that
245 * saves the handle for the DLL. Then when code in the DLL needs to
246 * construct names of files in the installation tree it calls this
247 * function passing the DLL handle.
249 * Returns: a string containing the guessed installation directory for
250 * the software package @hmodule is from. The string is in the GLib
251 * file name encoding, i.e. UTF-8. The return value should be freed
252 * with g_free() when not needed any longer. If the function fails
258 g_win32_get_package_installation_directory_of_module (gpointer hmodule
)
263 wchar_t wc_fn
[MAX_PATH
];
265 /* NOTE: it relies that GetModuleFileNameW returns only canonical paths */
266 if (!GetModuleFileNameW (hmodule
, wc_fn
, MAX_PATH
))
269 filename
= g_utf16_to_utf8 (wc_fn
, -1, NULL
, NULL
, NULL
);
271 if ((p
= strrchr (filename
, G_DIR_SEPARATOR
)) != NULL
)
274 retval
= g_strdup (filename
);
278 p
= strrchr (retval
, G_DIR_SEPARATOR
);
284 if (g_ascii_strcasecmp (p
+ 1, "bin") == 0 ||
285 g_ascii_strcasecmp (p
+ 1, "lib") == 0)
299 /* In Cygwin we need to have POSIX paths */
303 cygwin_conv_to_posix_path (retval
, tmp
);
305 retval
= g_strdup (tmp
);
313 get_package_directory_from_module (const gchar
*module_name
)
315 static GHashTable
*module_dirs
= NULL
;
316 G_LOCK_DEFINE_STATIC (module_dirs
);
317 HMODULE hmodule
= NULL
;
320 G_LOCK (module_dirs
);
322 if (module_dirs
== NULL
)
323 module_dirs
= g_hash_table_new (g_str_hash
, g_str_equal
);
325 fn
= g_hash_table_lookup (module_dirs
, module_name
? module_name
: "");
329 G_UNLOCK (module_dirs
);
330 return g_strdup (fn
);
335 wchar_t *wc_module_name
= g_utf8_to_utf16 (module_name
, -1, NULL
, NULL
, NULL
);
336 hmodule
= GetModuleHandleW (wc_module_name
);
337 g_free (wc_module_name
);
341 G_UNLOCK (module_dirs
);
346 fn
= g_win32_get_package_installation_directory_of_module (hmodule
);
350 G_UNLOCK (module_dirs
);
354 g_hash_table_insert (module_dirs
, module_name
? g_strdup (module_name
) : "", fn
);
356 G_UNLOCK (module_dirs
);
358 return g_strdup (fn
);
362 * g_win32_get_package_installation_directory:
363 * @package: (nullable): You should pass %NULL for this.
364 * @dll_name: (nullable): The name of a DLL that a package provides in UTF-8, or %NULL.
366 * Try to determine the installation directory for a software package.
368 * This function is deprecated. Use
369 * g_win32_get_package_installation_directory_of_module() instead.
371 * The use of @package is deprecated. You should always pass %NULL. A
372 * warning is printed if non-NULL is passed as @package.
374 * The original intended use of @package was for a short identifier of
375 * the package, typically the same identifier as used for
376 * `GETTEXT_PACKAGE` in software configured using GNU
377 * autotools. The function first looks in the Windows Registry for the
378 * value `#InstallationDirectory` in the key
379 * `#HKLM\Software\@package`, and if that value
380 * exists and is a string, returns that.
382 * It is strongly recommended that packagers of GLib-using libraries
383 * for Windows do not store installation paths in the Registry to be
384 * used by this function as that interfers with having several
385 * parallel installations of the library. Enabling multiple
386 * installations of different versions of some GLib-using library, or
387 * GLib itself, is desirable for various reasons.
389 * For this reason it is recommeded to always pass %NULL as
390 * @package to this function, to avoid the temptation to use the
391 * Registry. In version 2.20 of GLib the @package parameter
392 * will be ignored and this function won't look in the Registry at all.
394 * If @package is %NULL, or the above value isn't found in the
395 * Registry, but @dll_name is non-%NULL, it should name a DLL loaded
396 * into the current process. Typically that would be the name of the
397 * DLL calling this function, looking for its installation
398 * directory. The function then asks Windows what directory that DLL
399 * was loaded from. If that directory's last component is "bin" or
400 * "lib", the parent directory is returned, otherwise the directory
401 * itself. If that DLL isn't loaded, the function proceeds as if
402 * @dll_name was %NULL.
404 * If both @package and @dll_name are %NULL, the directory from where
405 * the main executable of the process was loaded is used instead in
406 * the same way as above.
408 * Returns: a string containing the installation directory for
409 * @package. The string is in the GLib file name encoding,
410 * i.e. UTF-8. The return value should be freed with g_free() when not
411 * needed any longer. If the function fails %NULL is returned.
413 * Deprecated: 2.18: Pass the HMODULE of a DLL or EXE to
414 * g_win32_get_package_installation_directory_of_module() instead.
418 g_win32_get_package_installation_directory (const gchar
*package
,
419 const gchar
*dll_name
)
421 gchar
*result
= NULL
;
424 g_warning ("Passing a non-NULL package to g_win32_get_package_installation_directory() is deprecated and it is ignored.");
426 if (dll_name
!= NULL
)
427 result
= get_package_directory_from_module (dll_name
);
430 result
= get_package_directory_from_module (NULL
);
436 * g_win32_get_package_installation_subdirectory:
437 * @package: (nullable): You should pass %NULL for this.
438 * @dll_name: (nullable): The name of a DLL that a package provides, in UTF-8, or %NULL.
439 * @subdir: A subdirectory of the package installation directory, also in UTF-8
441 * This function is deprecated. Use
442 * g_win32_get_package_installation_directory_of_module() and
443 * g_build_filename() instead.
445 * Returns a newly-allocated string containing the path of the
446 * subdirectory @subdir in the return value from calling
447 * g_win32_get_package_installation_directory() with the @package and
448 * @dll_name parameters. See the documentation for
449 * g_win32_get_package_installation_directory() for more details. In
450 * particular, note that it is deprecated to pass anything except NULL
453 * Returns: a string containing the complete path to @subdir inside
454 * the installation directory of @package. The returned string is in
455 * the GLib file name encoding, i.e. UTF-8. The return value should be
456 * freed with g_free() when no longer needed. If something goes wrong,
459 * Deprecated: 2.18: Pass the HMODULE of a DLL or EXE to
460 * g_win32_get_package_installation_directory_of_module() instead, and
461 * then construct a subdirectory pathname with g_build_filename().
465 g_win32_get_package_installation_subdirectory (const gchar
*package
,
466 const gchar
*dll_name
,
472 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
473 prefix
= g_win32_get_package_installation_directory (package
, dll_name
);
474 G_GNUC_END_IGNORE_DEPRECATIONS
476 dirname
= g_build_filename (prefix
, subdir
, NULL
);
483 * g_win32_check_windows_version:
484 * @major: major version of Windows
485 * @minor: minor version of Windows
486 * @spver: Windows Service Pack Level, 0 if none
487 * @os_type: Type of Windows OS
489 * Returns whether the version of the Windows operating system the
490 * code is running on is at least the specified major, minor and
491 * service pack versions. See MSDN documentation for the Operating
492 * System Version. Software that needs even more detailed version and
493 * feature information should use the Win32 API VerifyVersionInfo()
496 * Successive calls of this function can be used for enabling or
497 * disabling features at run-time for a range of Windows versions,
498 * as per the VerifyVersionInfo() API documentation.
500 * Returns: %TRUE if the Windows Version is the same or greater than
501 * the specified major, minor and service pack versions, and
502 * whether the running Windows is a workstation or server edition
503 * of Windows, if specifically specified.
508 g_win32_check_windows_version (const gint major
,
511 const GWin32OSType os_type
)
513 OSVERSIONINFOEXW osverinfo
;
514 gboolean is_ver_checked
= FALSE
;
515 gboolean is_type_checked
= FALSE
;
517 #if WINAPI_FAMILY != MODERN_API_FAMILY
518 /* For non-modern UI Apps, use the LoadLibraryW()/GetProcAddress() thing */
519 typedef NTSTATUS (WINAPI fRtlGetVersion
) (PRTL_OSVERSIONINFOEXW
);
521 fRtlGetVersion
*RtlGetVersion
;
524 /* We Only Support Checking for XP or later */
525 g_return_val_if_fail (major
>= 5 && (major
<=6 || major
== 10), FALSE
);
526 g_return_val_if_fail ((major
>= 5 && minor
>= 1) || major
>= 6, FALSE
);
528 /* Check for Service Pack Version >= 0 */
529 g_return_val_if_fail (spver
>= 0, FALSE
);
531 #if WINAPI_FAMILY != MODERN_API_FAMILY
532 hmodule
= LoadLibraryW (L
"ntdll.dll");
533 g_return_val_if_fail (hmodule
!= NULL
, FALSE
);
535 RtlGetVersion
= (fRtlGetVersion
*) GetProcAddress (hmodule
, "RtlGetVersion");
536 g_return_val_if_fail (RtlGetVersion
!= NULL
, FALSE
);
539 memset (&osverinfo
, 0, sizeof (OSVERSIONINFOEXW
));
540 osverinfo
.dwOSVersionInfoSize
= sizeof (OSVERSIONINFOEXW
);
541 RtlGetVersion (&osverinfo
);
543 /* check the OS and Service Pack Versions */
544 if (osverinfo
.dwMajorVersion
> major
)
545 is_ver_checked
= TRUE
;
546 else if (osverinfo
.dwMajorVersion
== major
)
548 if (osverinfo
.dwMinorVersion
> minor
)
549 is_ver_checked
= TRUE
;
550 else if (osverinfo
.dwMinorVersion
== minor
)
551 if (osverinfo
.wServicePackMajor
>= spver
)
552 is_ver_checked
= TRUE
;
561 is_type_checked
= TRUE
;
563 case G_WIN32_OS_WORKSTATION
:
564 if (osverinfo
.wProductType
== VER_NT_WORKSTATION
)
565 is_type_checked
= TRUE
;
567 case G_WIN32_OS_SERVER
:
568 if (osverinfo
.wProductType
== VER_NT_SERVER
||
569 osverinfo
.wProductType
== VER_NT_DOMAIN_CONTROLLER
)
570 is_type_checked
= TRUE
;
573 /* shouldn't get here normally */
574 g_warning ("Invalid os_type specified");
579 #if WINAPI_FAMILY != MODERN_API_FAMILY
580 FreeLibrary (hmodule
);
583 return is_ver_checked
&& is_type_checked
;
587 * g_win32_get_windows_version:
589 * This function is deprecated. Use
590 * g_win32_check_windows_version() instead.
592 * Returns version information for the Windows operating system the
593 * code is running on. See MSDN documentation for the GetVersion()
594 * function. To summarize, the most significant bit is one on Win9x,
595 * and zero on NT-based systems. Since version 2.14, GLib works only
596 * on NT-based systems, so checking whether your are running on Win9x
597 * in your own software is moot. The least significant byte is 4 on
598 * Windows NT 4, and 5 on Windows XP. Software that needs really
599 * detailed version and feature information should use Win32 API like
600 * GetVersionEx() and VerifyVersionInfo().
602 * Returns: The version information.
604 * Deprecated: 2.44: Be aware that for Windows 8.1 and Windows Server
605 * 2012 R2 and later, this will return 62 unless the application is
606 * manifested for Windows 8.1/Windows Server 2012 R2, for example.
607 * MSDN stated that GetVersion(), which is used here, is subject to
608 * further change or removal after Windows 8.1.
611 g_win32_get_windows_version (void)
613 static gsize windows_version
;
615 if (g_once_init_enter (&windows_version
))
616 g_once_init_leave (&windows_version
, GetVersion ());
618 return windows_version
;
622 * Doesn't use gettext (and gconv), preventing recursive calls when
623 * g_win32_locale_filename_from_utf8() is called during
624 * gettext initialization.
627 special_wchar_to_locale_enoding (wchar_t *wstring
)
632 BOOL not_representable
= FALSE
;
634 sizeof_output
= WideCharToMultiByte (CP_ACP
,
635 WC_NO_BEST_FIT_CHARS
,
641 if (not_representable
||
642 sizeof_output
== 0 ||
643 sizeof_output
> MAX_PATH
)
646 result
= g_malloc0 (sizeof_output
+ 1);
648 wctmb_result
= WideCharToMultiByte (CP_ACP
,
649 WC_NO_BEST_FIT_CHARS
,
651 result
, sizeof_output
+ 1,
655 if (wctmb_result
== sizeof_output
&&
656 not_representable
== FALSE
)
665 * g_win32_locale_filename_from_utf8:
666 * @utf8filename: a UTF-8 encoded filename.
668 * Converts a filename from UTF-8 to the system codepage.
670 * On NT-based Windows, on NTFS file systems, file names are in
671 * Unicode. It is quite possible that Unicode file names contain
672 * characters not representable in the system codepage. (For instance,
673 * Greek or Cyrillic characters on Western European or US Windows
674 * installations, or various less common CJK characters on CJK Windows
677 * In such a case, and if the filename refers to an existing file, and
678 * the file system stores alternate short (8.3) names for directory
679 * entries, the short form of the filename is returned. Note that the
680 * "short" name might in fact be longer than the Unicode name if the
681 * Unicode name has very short pathname components containing
682 * non-ASCII characters. If no system codepage name for the file is
683 * possible, %NULL is returned.
685 * The return value is dynamically allocated and should be freed with
686 * g_free() when no longer needed.
688 * Returns: The converted filename, or %NULL on conversion
689 * failure and lack of short names.
694 g_win32_locale_filename_from_utf8 (const gchar
*utf8filename
)
699 wname
= g_utf8_to_utf16 (utf8filename
, -1, NULL
, NULL
, NULL
);
704 retval
= special_wchar_to_locale_enoding (wname
);
708 /* Conversion failed, so check if there is a 8.3 version, and use that. */
709 wchar_t wshortname
[MAX_PATH
+ 1];
711 if (GetShortPathNameW (wname
, wshortname
, G_N_ELEMENTS (wshortname
)))
712 retval
= special_wchar_to_locale_enoding (wshortname
);
721 * g_win32_get_command_line:
723 * Gets the command line arguments, on Windows, in the GLib filename
724 * encoding (ie: UTF-8).
726 * Normally, on Windows, the command line arguments are passed to main()
727 * in the system codepage encoding. This prevents passing filenames as
728 * arguments if the filenames contain characters that fall outside of
729 * this codepage. If such filenames are passed, then substitutions
730 * will occur (such as replacing some characters with '?').
732 * GLib's policy of using UTF-8 as a filename encoding on Windows was
733 * designed to localise the pain of dealing with filenames outside of
734 * the system codepage to one area: dealing with commandline arguments
737 * As such, most GLib programs should ignore the value of argv passed to
738 * their main() function and call g_win32_get_command_line() instead.
739 * This will get the "full Unicode" commandline arguments using
740 * GetCommandLineW() and convert it to the GLib filename encoding (which
741 * is UTF-8 on Windows).
743 * The strings returned by this function are suitable for use with
744 * functions such as g_open() and g_file_new_for_commandline_arg() but
745 * are not suitable for use with g_option_context_parse(), which assumes
746 * that its input will be in the system codepage. The return value is
747 * suitable for use with g_option_context_parse_strv(), however, which
748 * is a better match anyway because it won't leak memory.
750 * Unlike argv, the returned value is a normal strv and can (and should)
751 * be freed with g_strfreev() when no longer needed.
753 * Returns: (transfer full): the commandline arguments in the GLib
754 * filename encoding (ie: UTF-8)
759 g_win32_get_command_line (void)
765 args
= CommandLineToArgvW (GetCommandLineW(), &n
);
767 result
= g_new (gchar
*, n
+ 1);
768 for (i
= 0; i
< n
; i
++)
769 result
[i
] = g_utf16_to_utf8 (args
[i
], -1, NULL
, NULL
, NULL
);
778 /* Binary compatibility versions. Not for newly compiled code. */
780 _GLIB_EXTERN gchar
*g_win32_get_package_installation_directory_utf8 (const gchar
*package
,
781 const gchar
*dll_name
);
783 _GLIB_EXTERN gchar
*g_win32_get_package_installation_subdirectory_utf8 (const gchar
*package
,
784 const gchar
*dll_name
,
785 const gchar
*subdir
);
788 g_win32_get_package_installation_directory_utf8 (const gchar
*package
,
789 const gchar
*dll_name
)
791 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
792 return g_win32_get_package_installation_directory (package
, dll_name
);
793 G_GNUC_END_IGNORE_DEPRECATIONS
797 g_win32_get_package_installation_subdirectory_utf8 (const gchar
*package
,
798 const gchar
*dll_name
,
801 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
802 return g_win32_get_package_installation_subdirectory (package
,
805 G_GNUC_END_IGNORE_DEPRECATIONS
812 /* This function looks up two environment
813 * variables, G_WIN32_ALLOC_CONSOLE and G_WIN32_ATTACH_CONSOLE.
814 * G_WIN32_ALLOC_CONSOLE, if set to 1, makes the process
815 * call AllocConsole(). This is useful for binaries that
816 * are compiled to run without automatically-allocated console
817 * (like most GUI applications).
818 * G_WIN32_ATTACH_CONSOLE, if set to a comma-separated list
819 * of one or more strings "stdout", "stdin" and "stderr",
820 * makes the process reopen the corresponding standard streams
821 * to ensure that they are attached to the files that
822 * GetStdHandle() returns, which, hopefully, would be
823 * either a file handle or a console handle.
825 * This function is called automatically when glib DLL is
826 * attached to a process, from DllMain().
829 g_console_win32_init (void)
835 const gchar
*stream_name
;
836 DWORD std_handle_type
;
842 { FALSE
, stdin
, "stdin", STD_INPUT_HANDLE
, _O_RDONLY
, "rb" },
843 { FALSE
, stdout
, "stdout", STD_OUTPUT_HANDLE
, 0, "wb" },
844 { FALSE
, stderr
, "stderr", STD_ERROR_HANDLE
, 0, "wb" },
847 const gchar
*attach_envvar
;
851 /* Note: it's not a very good practice to use DllMain()
852 * to call any functions not in Kernel32.dll.
853 * The following only works if there are no weird
854 * circular DLL dependencies that could cause glib DllMain()
855 * to be called before CRT DllMain().
858 if (g_strcmp0 (g_getenv ("G_WIN32_ALLOC_CONSOLE"), "1") == 0)
859 AllocConsole (); /* no error handling, fails if console already exists */
861 attach_envvar
= g_getenv ("G_WIN32_ATTACH_CONSOLE");
863 if (attach_envvar
== NULL
)
866 /* Re-use parent console, if we don't have our own.
867 * If we do, it will fail, so just ignore the error.
869 AttachConsole (ATTACH_PARENT_PROCESS
);
871 attach_strs
= g_strsplit (attach_envvar
, ",", -1);
873 for (i
= 0; attach_strs
[i
]; i
++)
875 if (g_strcmp0 (attach_strs
[i
], "stdout") == 0)
876 streams
[1].redirect
= TRUE
;
877 else if (g_strcmp0 (attach_strs
[i
], "stderr") == 0)
878 streams
[2].redirect
= TRUE
;
879 else if (g_strcmp0 (attach_strs
[i
], "stdin") == 0)
880 streams
[0].redirect
= TRUE
;
882 g_warning ("Unrecognized stream name %s", attach_strs
[i
]);
885 g_strfreev (attach_strs
);
887 for (i
= 0; i
< G_N_ELEMENTS (streams
); i
++)
892 int preferred_fd
= i
;
896 if (!streams
[i
].redirect
)
899 if (ferror (streams
[i
].stream
) != 0)
901 g_warning ("Stream %s is in error state", streams
[i
].stream_name
);
905 std_handle
= GetStdHandle (streams
[i
].std_handle_type
);
907 if (std_handle
== INVALID_HANDLE_VALUE
)
909 DWORD gle
= GetLastError ();
910 g_warning ("Standard handle for %s can't be obtained: %lu",
911 streams
[i
].stream_name
, gle
);
915 old_fd
= fileno (streams
[i
].stream
);
917 /* We need the stream object to be associated with
918 * any valid integer fd for the code to work.
919 * If it isn't, reopen it with NUL (/dev/null) to
924 if (freopen ("NUL", streams
[i
].mode
, streams
[i
].stream
) == NULL
)
927 g_warning ("Failed to redirect %s: %d - %s",
928 streams
[i
].stream_name
,
934 old_fd
= fileno (streams
[i
].stream
);
938 g_warning ("Stream %s does not have a valid fd",
939 streams
[i
].stream_name
);
944 new_fd
= _open_osfhandle ((intptr_t) std_handle
, streams
[i
].flags
);
948 g_warning ("Failed to create new fd for stream %s",
949 streams
[i
].stream_name
);
953 backup_fd
= dup (old_fd
);
956 g_warning ("Failed to backup old fd %d for stream %s",
957 old_fd
, streams
[i
].stream_name
);
961 /* Force old_fd to be associated with the same file
962 * as new_fd, i.e with the standard handle we need
963 * (or, rather, with the same kernel object; handle
964 * value will be different, but the kernel object
967 /* NOTE: MSDN claims that _dup2() returns 0 on success and -1 on error,
968 * POSIX claims that dup2() reurns new FD on success and -1 on error.
969 * The "< 0" check satisfies the error condition for either implementation.
971 if (_dup2 (new_fd
, old_fd
) < 0)
974 g_warning ("Failed to substitute fd %d for stream %s: %d : %s",
975 old_fd
, streams
[i
].stream_name
, errsv
, strerror (errsv
));
984 /* Try to restore old_fd back to its previous
985 * handle, in case the _dup2() call above succeeded partially.
987 if (_dup2 (backup_fd
, old_fd
) < 0)
990 g_warning ("Failed to restore fd %d for stream %s: %d : %s",
991 old_fd
, streams
[i
].stream_name
, errsv
, strerror (errsv
));
999 /* Success, drop the backup */
1003 /* Sadly, there's no way to check that preferred_fd
1004 * is currently valid, so we can't back it up.
1005 * Doing operations on invalid FDs invokes invalid
1006 * parameter handler, which is bad for us.
1008 if (old_fd
!= preferred_fd
)
1009 /* This extra code will also try to ensure that
1010 * the expected file descriptors 0, 1 and 2 are
1011 * associated with the appropriate standard
1014 if (_dup2 (new_fd
, preferred_fd
) < 0)
1015 g_warning ("Failed to dup fd %d into fd %d", new_fd
, preferred_fd
);