• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
4  *
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.
9  *
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.
14  *
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/>.
17  */
18 
19 /*
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/.
24  */
25 
26 /*
27  * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
28  */
29 
30 #include "config.h"
31 
32 #include "glibconfig.h"
33 
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <wchar.h>
38 #include <errno.h>
39 #include <fcntl.h>
40 
41 #define STRICT			/* Strict typing, please */
42 #include <windows.h>
43 #undef STRICT
44 #ifndef G_WITH_CYGWIN
45 #include <direct.h>
46 #endif
47 #include <errno.h>
48 #include <ctype.h>
49 #if defined(_MSC_VER) || defined(__DMC__)
50 #  include <io.h>
51 #endif /* _MSC_VER || __DMC__ */
52 
53 #define MODERN_API_FAMILY 2
54 
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 */
58 #include <ntddk.h>
59 
60 #ifdef _MSC_VER
61 #pragma comment (lib, "ntoskrnl.lib")
62 #endif
63 #elif defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
64 /* mingw-w64 must use winternl.h, but not MinGW */
65 #include <ntdef.h>
66 #else
67 #include <winternl.h>
68 #endif
69 
70 #include "glib.h"
71 #include "gthreadprivate.h"
72 #include "glib-init.h"
73 
74 #ifdef G_WITH_CYGWIN
75 #include <sys/cygwin.h>
76 #endif
77 
78 #ifndef G_WITH_CYGWIN
79 
80 gint
g_win32_ftruncate(gint fd,guint size)81 g_win32_ftruncate (gint  fd,
82 		   guint size)
83 {
84   return _chsize (fd, size);
85 }
86 
87 #endif
88 
89 /**
90  * g_win32_getlocale:
91  *
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
98  * g_free().
99  *
100  * Returns: newly-allocated locale name.
101  **/
102 
103 #ifndef SUBLANG_SERBIAN_LATIN_BA
104 #define SUBLANG_SERBIAN_LATIN_BA 0x06
105 #endif
106 
107 gchar *
g_win32_getlocale(void)108 g_win32_getlocale (void)
109 {
110   gchar *result;
111   LCID lcid;
112   LANGID langid;
113   const gchar *ev;
114   gint primary, sub;
115   WCHAR iso639[10];
116   gchar *iso639_utf8;
117   WCHAR iso3166[10];
118   gchar *iso3166_utf8;
119   const gchar *script = NULL;
120 
121   /* Let the user override the system settings through environment
122    * variables, as on POSIX systems. Note that in GTK+ applications
123    * since GTK+ 2.10.7 setting either LC_ALL or LANG also sets the
124    * Win32 locale and C library locale through code in gtkmain.c.
125    */
126   if (((ev = g_getenv ("LC_ALL")) != NULL && ev[0] != '\0')
127       || ((ev = g_getenv ("LC_MESSAGES")) != NULL && ev[0] != '\0')
128       || ((ev = g_getenv ("LANG")) != NULL && ev[0] != '\0'))
129     return g_strdup (ev);
130 
131   lcid = GetThreadLocale ();
132 
133   if (!GetLocaleInfoW (lcid, LOCALE_SISO639LANGNAME, iso639, sizeof (iso639)) ||
134       !GetLocaleInfoW (lcid, LOCALE_SISO3166CTRYNAME, iso3166, sizeof (iso3166)))
135     return g_strdup ("C");
136 
137   /* Strip off the sorting rules, keep only the language part.  */
138   langid = LANGIDFROMLCID (lcid);
139 
140   /* Split into language and territory part.  */
141   primary = PRIMARYLANGID (langid);
142   sub = SUBLANGID (langid);
143 
144   /* Handle special cases */
145   switch (primary)
146     {
147     case LANG_AZERI:
148       switch (sub)
149 	{
150 	case SUBLANG_AZERI_LATIN:
151 	  script = "@Latn";
152 	  break;
153 	case SUBLANG_AZERI_CYRILLIC:
154 	  script = "@Cyrl";
155 	  break;
156 	}
157       break;
158     case LANG_SERBIAN:		/* LANG_CROATIAN == LANG_SERBIAN */
159       switch (sub)
160 	{
161 	case SUBLANG_SERBIAN_LATIN:
162 	case 0x06: /* Serbian (Latin) - Bosnia and Herzegovina */
163 	  script = "@Latn";
164 	  break;
165 	}
166       break;
167     case LANG_UZBEK:
168       switch (sub)
169 	{
170 	case SUBLANG_UZBEK_LATIN:
171 	  script = "@Latn";
172 	  break;
173 	case SUBLANG_UZBEK_CYRILLIC:
174 	  script = "@Cyrl";
175 	  break;
176 	}
177       break;
178     }
179 
180   iso639_utf8 = g_utf16_to_utf8 (iso639, -1, NULL, NULL, NULL);
181   iso3166_utf8 = g_utf16_to_utf8 (iso3166, -1, NULL, NULL, NULL);
182 
183   result = g_strconcat (iso639_utf8, "_", iso3166_utf8, script, NULL);
184 
185   g_free (iso3166_utf8);
186   g_free (iso639_utf8);
187 
188   return result;
189 }
190 
191 /**
192  * g_win32_error_message:
193  * @error: error code.
194  *
195  * Translate a Win32 error code (as returned by GetLastError() or
196  * WSAGetLastError()) into the corresponding message. The message is
197  * either language neutral, or in the thread's language, or the user's
198  * language, the system's language, or US English (see docs for
199  * FormatMessage()). The returned string is in UTF-8. It should be
200  * deallocated with g_free().
201  *
202  * Returns: newly-allocated error message
203  **/
204 gchar *
g_win32_error_message(gint error)205 g_win32_error_message (gint error)
206 {
207   gchar *retval;
208   wchar_t *msg = NULL;
209   size_t nchars;
210 
211   FormatMessageW (FORMAT_MESSAGE_ALLOCATE_BUFFER
212 		  |FORMAT_MESSAGE_IGNORE_INSERTS
213 		  |FORMAT_MESSAGE_FROM_SYSTEM,
214 		  NULL, error, 0,
215 		  (LPWSTR) &msg, 0, NULL);
216   if (msg != NULL)
217     {
218       nchars = wcslen (msg);
219 
220       if (nchars >= 2 && msg[nchars-1] == L'\n' && msg[nchars-2] == L'\r')
221         msg[nchars-2] = L'\0';
222 
223       retval = g_utf16_to_utf8 (msg, -1, NULL, NULL, NULL);
224 
225       LocalFree (msg);
226     }
227   else
228     retval = g_strdup ("");
229 
230   return retval;
231 }
232 
233 /**
234  * g_win32_get_package_installation_directory_of_module:
235  * @hmodule: (nullable): The Win32 handle for a DLL loaded into the current process, or %NULL
236  *
237  * This function tries to determine the installation directory of a
238  * software package based on the location of a DLL of the software
239  * package.
240  *
241  * @hmodule should be the handle of a loaded DLL or %NULL. The
242  * function looks up the directory that DLL was loaded from. If
243  * @hmodule is NULL, the directory the main executable of the current
244  * process is looked up. If that directory's last component is "bin"
245  * or "lib", its parent directory is returned, otherwise the directory
246  * itself.
247  *
248  * It thus makes sense to pass only the handle to a "public" DLL of a
249  * software package to this function, as such DLLs typically are known
250  * to be installed in a "bin" or occasionally "lib" subfolder of the
251  * installation folder. DLLs that are of the dynamically loaded module
252  * or plugin variety are often located in more private locations
253  * deeper down in the tree, from which it is impossible for GLib to
254  * deduce the root of the package installation.
255  *
256  * The typical use case for this function is to have a DllMain() that
257  * saves the handle for the DLL. Then when code in the DLL needs to
258  * construct names of files in the installation tree it calls this
259  * function passing the DLL handle.
260  *
261  * Returns: a string containing the guessed installation directory for
262  * the software package @hmodule is from. The string is in the GLib
263  * file name encoding, i.e. UTF-8. The return value should be freed
264  * with g_free() when not needed any longer. If the function fails
265  * %NULL is returned.
266  *
267  * Since: 2.16
268  */
269 gchar *
g_win32_get_package_installation_directory_of_module(gpointer hmodule)270 g_win32_get_package_installation_directory_of_module (gpointer hmodule)
271 {
272   gchar *filename;
273   gchar *retval;
274   gchar *p;
275   wchar_t wc_fn[MAX_PATH];
276 
277   /* NOTE: it relies that GetModuleFileNameW returns only canonical paths */
278   if (!GetModuleFileNameW (hmodule, wc_fn, MAX_PATH))
279     return NULL;
280 
281   filename = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
282 
283   if ((p = strrchr (filename, G_DIR_SEPARATOR)) != NULL)
284     *p = '\0';
285 
286   retval = g_strdup (filename);
287 
288   do
289     {
290       p = strrchr (retval, G_DIR_SEPARATOR);
291       if (p == NULL)
292         break;
293 
294       *p = '\0';
295 
296       if (g_ascii_strcasecmp (p + 1, "bin") == 0 ||
297           g_ascii_strcasecmp (p + 1, "lib") == 0)
298         break;
299     }
300   while (p != NULL);
301 
302   if (p == NULL)
303     {
304       g_free (retval);
305       retval = filename;
306     }
307   else
308     g_free (filename);
309 
310 #ifdef G_WITH_CYGWIN
311   /* In Cygwin we need to have POSIX paths */
312   {
313     gchar tmp[MAX_PATH];
314 
315     cygwin_conv_to_posix_path (retval, tmp);
316     g_free (retval);
317     retval = g_strdup (tmp);
318   }
319 #endif
320 
321   return retval;
322 }
323 
324 static gchar *
get_package_directory_from_module(const gchar * module_name)325 get_package_directory_from_module (const gchar *module_name)
326 {
327   static GHashTable *module_dirs = NULL;
328   G_LOCK_DEFINE_STATIC (module_dirs);
329   HMODULE hmodule = NULL;
330   gchar *fn;
331 
332   G_LOCK (module_dirs);
333 
334   if (module_dirs == NULL)
335     module_dirs = g_hash_table_new (g_str_hash, g_str_equal);
336 
337   fn = g_hash_table_lookup (module_dirs, module_name ? module_name : "");
338 
339   if (fn)
340     {
341       G_UNLOCK (module_dirs);
342       return g_strdup (fn);
343     }
344 
345   if (module_name)
346     {
347       wchar_t *wc_module_name = g_utf8_to_utf16 (module_name, -1, NULL, NULL, NULL);
348       hmodule = GetModuleHandleW (wc_module_name);
349       g_free (wc_module_name);
350 
351       if (!hmodule)
352 	{
353 	  G_UNLOCK (module_dirs);
354 	  return NULL;
355 	}
356     }
357 
358   fn = g_win32_get_package_installation_directory_of_module (hmodule);
359 
360   if (fn == NULL)
361     {
362       G_UNLOCK (module_dirs);
363       return NULL;
364     }
365 
366   g_hash_table_insert (module_dirs, module_name ? g_strdup (module_name) : "", fn);
367 
368   G_UNLOCK (module_dirs);
369 
370   return g_strdup (fn);
371 }
372 
373 /**
374  * g_win32_get_package_installation_directory:
375  * @package: (nullable): You should pass %NULL for this.
376  * @dll_name: (nullable): The name of a DLL that a package provides in UTF-8, or %NULL.
377  *
378  * Try to determine the installation directory for a software package.
379  *
380  * This function is deprecated. Use
381  * g_win32_get_package_installation_directory_of_module() instead.
382  *
383  * The use of @package is deprecated. You should always pass %NULL. A
384  * warning is printed if non-NULL is passed as @package.
385  *
386  * The original intended use of @package was for a short identifier of
387  * the package, typically the same identifier as used for
388  * `GETTEXT_PACKAGE` in software configured using GNU
389  * autotools. The function first looks in the Windows Registry for the
390  * value `#InstallationDirectory` in the key
391  * `#HKLM\Software\@package`, and if that value
392  * exists and is a string, returns that.
393  *
394  * It is strongly recommended that packagers of GLib-using libraries
395  * for Windows do not store installation paths in the Registry to be
396  * used by this function as that interfers with having several
397  * parallel installations of the library. Enabling multiple
398  * installations of different versions of some GLib-using library, or
399  * GLib itself, is desirable for various reasons.
400  *
401  * For this reason it is recommended to always pass %NULL as
402  * @package to this function, to avoid the temptation to use the
403  * Registry. In version 2.20 of GLib the @package parameter
404  * will be ignored and this function won't look in the Registry at all.
405  *
406  * If @package is %NULL, or the above value isn't found in the
407  * Registry, but @dll_name is non-%NULL, it should name a DLL loaded
408  * into the current process. Typically that would be the name of the
409  * DLL calling this function, looking for its installation
410  * directory. The function then asks Windows what directory that DLL
411  * was loaded from. If that directory's last component is "bin" or
412  * "lib", the parent directory is returned, otherwise the directory
413  * itself. If that DLL isn't loaded, the function proceeds as if
414  * @dll_name was %NULL.
415  *
416  * If both @package and @dll_name are %NULL, the directory from where
417  * the main executable of the process was loaded is used instead in
418  * the same way as above.
419  *
420  * Returns: a string containing the installation directory for
421  * @package. The string is in the GLib file name encoding,
422  * i.e. UTF-8. The return value should be freed with g_free() when not
423  * needed any longer. If the function fails %NULL is returned.
424  *
425  * Deprecated: 2.18: Pass the HMODULE of a DLL or EXE to
426  * g_win32_get_package_installation_directory_of_module() instead.
427  **/
428 
429 gchar *
g_win32_get_package_installation_directory(const gchar * package,const gchar * dll_name)430 g_win32_get_package_installation_directory (const gchar *package,
431                                             const gchar *dll_name)
432 {
433   gchar *result = NULL;
434 
435   if (package != NULL)
436       g_warning ("Passing a non-NULL package to g_win32_get_package_installation_directory() is deprecated and it is ignored.");
437 
438   if (dll_name != NULL)
439     result = get_package_directory_from_module (dll_name);
440 
441   if (result == NULL)
442     result = get_package_directory_from_module (NULL);
443 
444   return result;
445 }
446 
447 /**
448  * g_win32_get_package_installation_subdirectory:
449  * @package: (nullable): You should pass %NULL for this.
450  * @dll_name: (nullable): The name of a DLL that a package provides, in UTF-8, or %NULL.
451  * @subdir: A subdirectory of the package installation directory, also in UTF-8
452  *
453  * This function is deprecated. Use
454  * g_win32_get_package_installation_directory_of_module() and
455  * g_build_filename() instead.
456  *
457  * Returns a newly-allocated string containing the path of the
458  * subdirectory @subdir in the return value from calling
459  * g_win32_get_package_installation_directory() with the @package and
460  * @dll_name parameters. See the documentation for
461  * g_win32_get_package_installation_directory() for more details. In
462  * particular, note that it is deprecated to pass anything except NULL
463  * as @package.
464  *
465  * Returns: a string containing the complete path to @subdir inside
466  * the installation directory of @package. The returned string is in
467  * the GLib file name encoding, i.e. UTF-8. The return value should be
468  * freed with g_free() when no longer needed. If something goes wrong,
469  * %NULL is returned.
470  *
471  * Deprecated: 2.18: Pass the HMODULE of a DLL or EXE to
472  * g_win32_get_package_installation_directory_of_module() instead, and
473  * then construct a subdirectory pathname with g_build_filename().
474  **/
475 
476 gchar *
g_win32_get_package_installation_subdirectory(const gchar * package,const gchar * dll_name,const gchar * subdir)477 g_win32_get_package_installation_subdirectory (const gchar *package,
478                                                const gchar *dll_name,
479                                                const gchar *subdir)
480 {
481   gchar *prefix;
482   gchar *dirname;
483 
484 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
485   prefix = g_win32_get_package_installation_directory (package, dll_name);
486 G_GNUC_END_IGNORE_DEPRECATIONS
487 
488   dirname = g_build_filename (prefix, subdir, NULL);
489   g_free (prefix);
490 
491   return dirname;
492 }
493 
494 /**
495  * g_win32_check_windows_version:
496  * @major: major version of Windows
497  * @minor: minor version of Windows
498  * @spver: Windows Service Pack Level, 0 if none
499  * @os_type: Type of Windows OS
500  *
501  * Returns whether the version of the Windows operating system the
502  * code is running on is at least the specified major, minor and
503  * service pack versions.  See MSDN documentation for the Operating
504  * System Version.  Software that needs even more detailed version and
505  * feature information should use the Win32 API VerifyVersionInfo()
506  * directly.
507  *
508  * Successive calls of this function can be used for enabling or
509  * disabling features at run-time for a range of Windows versions,
510  * as per the VerifyVersionInfo() API documentation.
511  *
512  * Returns: %TRUE if the Windows Version is the same or greater than
513  *          the specified major, minor and service pack versions, and
514  *          whether the running Windows is a workstation or server edition
515  *          of Windows, if specifically specified.
516  *
517  * Since: 2.44
518  **/
519 gboolean
g_win32_check_windows_version(const gint major,const gint minor,const gint spver,const GWin32OSType os_type)520 g_win32_check_windows_version (const gint major,
521                                const gint minor,
522                                const gint spver,
523                                const GWin32OSType os_type)
524 {
525   OSVERSIONINFOEXW osverinfo;
526   gboolean is_ver_checked = FALSE;
527   gboolean is_type_checked = FALSE;
528 
529 #if WINAPI_FAMILY != MODERN_API_FAMILY
530   /* For non-modern UI Apps, use the LoadLibraryW()/GetProcAddress() thing */
531   typedef NTSTATUS (WINAPI fRtlGetVersion) (PRTL_OSVERSIONINFOEXW);
532 
533   fRtlGetVersion *RtlGetVersion;
534   HMODULE hmodule;
535 #endif
536   /* We Only Support Checking for XP or later */
537   g_return_val_if_fail (major >= 5 && (major <=6 || major == 10), FALSE);
538   g_return_val_if_fail ((major >= 5 && minor >= 1) || major >= 6, FALSE);
539 
540   /* Check for Service Pack Version >= 0 */
541   g_return_val_if_fail (spver >= 0, FALSE);
542 
543 #if WINAPI_FAMILY != MODERN_API_FAMILY
544   hmodule = LoadLibraryW (L"ntdll.dll");
545   g_return_val_if_fail (hmodule != NULL, FALSE);
546 
547   RtlGetVersion = (fRtlGetVersion *) GetProcAddress (hmodule, "RtlGetVersion");
548   g_return_val_if_fail (RtlGetVersion != NULL, FALSE);
549 #endif
550 
551   memset (&osverinfo, 0, sizeof (OSVERSIONINFOEXW));
552   osverinfo.dwOSVersionInfoSize = sizeof (OSVERSIONINFOEXW);
553   RtlGetVersion (&osverinfo);
554 
555   /* check the OS and Service Pack Versions */
556   if (osverinfo.dwMajorVersion > major)
557     is_ver_checked = TRUE;
558   else if (osverinfo.dwMajorVersion == major)
559     {
560       if (osverinfo.dwMinorVersion > minor)
561         is_ver_checked = TRUE;
562       else if (osverinfo.dwMinorVersion == minor)
563         if (osverinfo.wServicePackMajor >= spver)
564           is_ver_checked = TRUE;
565     }
566 
567   /* Check OS Type */
568   if (is_ver_checked)
569     {
570       switch (os_type)
571         {
572           case G_WIN32_OS_ANY:
573             is_type_checked = TRUE;
574             break;
575           case G_WIN32_OS_WORKSTATION:
576             if (osverinfo.wProductType == VER_NT_WORKSTATION)
577               is_type_checked = TRUE;
578             break;
579           case G_WIN32_OS_SERVER:
580             if (osverinfo.wProductType == VER_NT_SERVER ||
581                 osverinfo.wProductType == VER_NT_DOMAIN_CONTROLLER)
582               is_type_checked = TRUE;
583             break;
584           default:
585             /* shouldn't get here normally */
586             g_warning ("Invalid os_type specified");
587             break;
588         }
589     }
590 
591 #if WINAPI_FAMILY != MODERN_API_FAMILY
592   FreeLibrary (hmodule);
593 #endif
594 
595   return is_ver_checked && is_type_checked;
596 }
597 
598 /**
599  * g_win32_get_windows_version:
600  *
601  * This function is deprecated. Use
602  * g_win32_check_windows_version() instead.
603  *
604  * Returns version information for the Windows operating system the
605  * code is running on. See MSDN documentation for the GetVersion()
606  * function. To summarize, the most significant bit is one on Win9x,
607  * and zero on NT-based systems. Since version 2.14, GLib works only
608  * on NT-based systems, so checking whether your are running on Win9x
609  * in your own software is moot. The least significant byte is 4 on
610  * Windows NT 4, and 5 on Windows XP. Software that needs really
611  * detailed version and feature information should use Win32 API like
612  * GetVersionEx() and VerifyVersionInfo().
613  *
614  * Returns: The version information.
615  *
616  * Deprecated: 2.44: Be aware that for Windows 8.1 and Windows Server
617  * 2012 R2 and later, this will return 62 unless the application is
618  * manifested for Windows 8.1/Windows Server 2012 R2, for example.
619  * MSDN stated that GetVersion(), which is used here, is subject to
620  * further change or removal after Windows 8.1.
621  **/
622 guint
g_win32_get_windows_version(void)623 g_win32_get_windows_version (void)
624 {
625   static gsize windows_version;
626 
627   if (g_once_init_enter (&windows_version))
628     g_once_init_leave (&windows_version, GetVersion ());
629 
630   return windows_version;
631 }
632 
633 /*
634  * Doesn't use gettext (and gconv), preventing recursive calls when
635  * g_win32_locale_filename_from_utf8() is called during
636  * gettext initialization.
637  */
638 static gchar *
special_wchar_to_locale_encoding(wchar_t * wstring)639 special_wchar_to_locale_encoding (wchar_t *wstring)
640 {
641   int sizeof_output;
642   int wctmb_result;
643   char *result;
644   BOOL not_representable = FALSE;
645 
646   sizeof_output = WideCharToMultiByte (CP_ACP,
647                                        WC_NO_BEST_FIT_CHARS,
648                                        wstring, -1,
649                                        NULL, 0,
650                                        NULL,
651                                        &not_representable);
652 
653   if (not_representable ||
654       sizeof_output == 0 ||
655       sizeof_output > MAX_PATH)
656     return NULL;
657 
658   result = g_malloc0 (sizeof_output + 1);
659 
660   wctmb_result = WideCharToMultiByte (CP_ACP,
661                                       WC_NO_BEST_FIT_CHARS,
662                                       wstring, -1,
663                                       result, sizeof_output + 1,
664                                       NULL,
665                                       &not_representable);
666 
667   if (wctmb_result == sizeof_output &&
668       not_representable == FALSE)
669     return result;
670 
671   g_free (result);
672 
673   return NULL;
674 }
675 
676 /**
677  * g_win32_locale_filename_from_utf8:
678  * @utf8filename: a UTF-8 encoded filename.
679  *
680  * Converts a filename from UTF-8 to the system codepage.
681  *
682  * On NT-based Windows, on NTFS file systems, file names are in
683  * Unicode. It is quite possible that Unicode file names contain
684  * characters not representable in the system codepage. (For instance,
685  * Greek or Cyrillic characters on Western European or US Windows
686  * installations, or various less common CJK characters on CJK Windows
687  * installations.)
688  *
689  * In such a case, and if the filename refers to an existing file, and
690  * the file system stores alternate short (8.3) names for directory
691  * entries, the short form of the filename is returned. Note that the
692  * "short" name might in fact be longer than the Unicode name if the
693  * Unicode name has very short pathname components containing
694  * non-ASCII characters. If no system codepage name for the file is
695  * possible, %NULL is returned.
696  *
697  * The return value is dynamically allocated and should be freed with
698  * g_free() when no longer needed.
699  *
700  * Returns: The converted filename, or %NULL on conversion
701  * failure and lack of short names.
702  *
703  * Since: 2.8
704  */
705 gchar *
g_win32_locale_filename_from_utf8(const gchar * utf8filename)706 g_win32_locale_filename_from_utf8 (const gchar *utf8filename)
707 {
708   gchar *retval;
709   wchar_t *wname;
710 
711   wname = g_utf8_to_utf16 (utf8filename, -1, NULL, NULL, NULL);
712 
713   if (wname == NULL)
714     return NULL;
715 
716   retval = special_wchar_to_locale_encoding (wname);
717 
718   if (retval == NULL)
719     {
720       /* Conversion failed, so check if there is a 8.3 version, and use that. */
721       wchar_t wshortname[MAX_PATH + 1];
722 
723       if (GetShortPathNameW (wname, wshortname, G_N_ELEMENTS (wshortname)))
724         retval = special_wchar_to_locale_encoding (wshortname);
725     }
726 
727   g_free (wname);
728 
729   return retval;
730 }
731 
732 /**
733  * g_win32_get_command_line:
734  *
735  * Gets the command line arguments, on Windows, in the GLib filename
736  * encoding (ie: UTF-8).
737  *
738  * Normally, on Windows, the command line arguments are passed to main()
739  * in the system codepage encoding.  This prevents passing filenames as
740  * arguments if the filenames contain characters that fall outside of
741  * this codepage.  If such filenames are passed, then substitutions
742  * will occur (such as replacing some characters with '?').
743  *
744  * GLib's policy of using UTF-8 as a filename encoding on Windows was
745  * designed to localise the pain of dealing with filenames outside of
746  * the system codepage to one area: dealing with commandline arguments
747  * in main().
748  *
749  * As such, most GLib programs should ignore the value of argv passed to
750  * their main() function and call g_win32_get_command_line() instead.
751  * This will get the "full Unicode" commandline arguments using
752  * GetCommandLineW() and convert it to the GLib filename encoding (which
753  * is UTF-8 on Windows).
754  *
755  * The strings returned by this function are suitable for use with
756  * functions such as g_open() and g_file_new_for_commandline_arg() but
757  * are not suitable for use with g_option_context_parse(), which assumes
758  * that its input will be in the system codepage.  The return value is
759  * suitable for use with g_option_context_parse_strv(), however, which
760  * is a better match anyway because it won't leak memory.
761  *
762  * Unlike argv, the returned value is a normal strv and can (and should)
763  * be freed with g_strfreev() when no longer needed.
764  *
765  * Returns: (transfer full): the commandline arguments in the GLib
766  *   filename encoding (ie: UTF-8)
767  *
768  * Since: 2.40
769  **/
770 gchar **
g_win32_get_command_line(void)771 g_win32_get_command_line (void)
772 {
773   gchar **result;
774   LPWSTR *args;
775   gint i, n;
776 
777   args = CommandLineToArgvW (GetCommandLineW(), &n);
778 
779   result = g_new (gchar *, n + 1);
780   for (i = 0; i < n; i++)
781     result[i] = g_utf16_to_utf8 (args[i], -1, NULL, NULL, NULL);
782   result[i] = NULL;
783 
784   LocalFree (args);
785   return result;
786 }
787 
788 #ifdef G_OS_WIN32
789 
790 /* Binary compatibility versions. Not for newly compiled code. */
791 
792 _GLIB_EXTERN gchar *g_win32_get_package_installation_directory_utf8    (const gchar *package,
793                                                                         const gchar *dll_name);
794 
795 _GLIB_EXTERN gchar *g_win32_get_package_installation_subdirectory_utf8 (const gchar *package,
796                                                                         const gchar *dll_name,
797                                                                         const gchar *subdir);
798 
799 gchar *
g_win32_get_package_installation_directory_utf8(const gchar * package,const gchar * dll_name)800 g_win32_get_package_installation_directory_utf8 (const gchar *package,
801                                                  const gchar *dll_name)
802 {
803 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
804   return g_win32_get_package_installation_directory (package, dll_name);
805 G_GNUC_END_IGNORE_DEPRECATIONS
806 }
807 
808 gchar *
g_win32_get_package_installation_subdirectory_utf8(const gchar * package,const gchar * dll_name,const gchar * subdir)809 g_win32_get_package_installation_subdirectory_utf8 (const gchar *package,
810                                                     const gchar *dll_name,
811                                                     const gchar *subdir)
812 {
813 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
814   return g_win32_get_package_installation_subdirectory (package,
815                                                         dll_name,
816                                                         subdir);
817 G_GNUC_END_IGNORE_DEPRECATIONS
818 }
819 
820 #endif
821 
822 #ifdef G_OS_WIN32
823 
824 /* This function looks up two environment
825  * variables, G_WIN32_ALLOC_CONSOLE and G_WIN32_ATTACH_CONSOLE.
826  * G_WIN32_ALLOC_CONSOLE, if set to 1, makes the process
827  * call AllocConsole(). This is useful for binaries that
828  * are compiled to run without automatically-allocated console
829  * (like most GUI applications).
830  * G_WIN32_ATTACH_CONSOLE, if set to a comma-separated list
831  * of one or more strings "stdout", "stdin" and "stderr",
832  * makes the process reopen the corresponding standard streams
833  * to ensure that they are attached to the files that
834  * GetStdHandle() returns, which, hopefully, would be
835  * either a file handle or a console handle.
836  *
837  * This function is called automatically when glib DLL is
838  * attached to a process, from DllMain().
839  */
840 void
g_console_win32_init(void)841 g_console_win32_init (void)
842 {
843   struct
844     {
845       gboolean     redirect;
846       FILE        *stream;
847       const gchar *stream_name;
848       DWORD        std_handle_type;
849       int          flags;
850       const gchar *mode;
851     }
852   streams[] =
853     {
854       { FALSE, stdin, "stdin", STD_INPUT_HANDLE, _O_RDONLY, "rb" },
855       { FALSE, stdout, "stdout", STD_OUTPUT_HANDLE, 0, "wb" },
856       { FALSE, stderr, "stderr", STD_ERROR_HANDLE, 0, "wb" },
857     };
858 
859   const gchar  *attach_envvar;
860   guint         i;
861   gchar       **attach_strs;
862 
863   /* Note: it's not a very good practice to use DllMain()
864    * to call any functions not in Kernel32.dll.
865    * The following only works if there are no weird
866    * circular DLL dependencies that could cause glib DllMain()
867    * to be called before CRT DllMain().
868    */
869 
870   if (g_strcmp0 (g_getenv ("G_WIN32_ALLOC_CONSOLE"), "1") == 0)
871     AllocConsole (); /* no error handling, fails if console already exists */
872 
873   attach_envvar = g_getenv ("G_WIN32_ATTACH_CONSOLE");
874 
875   if (attach_envvar == NULL)
876     return;
877 
878   /* Re-use parent console, if we don't have our own.
879    * If we do, it will fail, so just ignore the error.
880    */
881   AttachConsole (ATTACH_PARENT_PROCESS);
882 
883   attach_strs = g_strsplit (attach_envvar, ",", -1);
884 
885   for (i = 0; attach_strs[i]; i++)
886     {
887       if (g_strcmp0 (attach_strs[i], "stdout") == 0)
888         streams[1].redirect = TRUE;
889       else if (g_strcmp0 (attach_strs[i], "stderr") == 0)
890         streams[2].redirect = TRUE;
891       else if (g_strcmp0 (attach_strs[i], "stdin") == 0)
892         streams[0].redirect = TRUE;
893       else
894         g_warning ("Unrecognized stream name %s", attach_strs[i]);
895     }
896 
897   g_strfreev (attach_strs);
898 
899   for (i = 0; i < G_N_ELEMENTS (streams); i++)
900     {
901       int          old_fd;
902       int          backup_fd;
903       int          new_fd;
904       int          preferred_fd = i;
905       HANDLE       std_handle;
906       errno_t      errsv = 0;
907 
908       if (!streams[i].redirect)
909         continue;
910 
911       if (ferror (streams[i].stream) != 0)
912         {
913           g_warning ("Stream %s is in error state", streams[i].stream_name);
914           continue;
915         }
916 
917       std_handle = GetStdHandle (streams[i].std_handle_type);
918 
919       if (std_handle == INVALID_HANDLE_VALUE)
920         {
921           DWORD gle = GetLastError ();
922           g_warning ("Standard handle for %s can't be obtained: %lu",
923                      streams[i].stream_name, gle);
924           continue;
925         }
926 
927       old_fd = fileno (streams[i].stream);
928 
929       /* We need the stream object to be associated with
930        * any valid integer fd for the code to work.
931        * If it isn't, reopen it with NUL (/dev/null) to
932        * ensure that it is.
933        */
934       if (old_fd < 0)
935         {
936           if (freopen ("NUL", streams[i].mode, streams[i].stream) == NULL)
937             {
938               errsv = errno;
939               g_warning ("Failed to redirect %s: %d - %s",
940                          streams[i].stream_name,
941                          errsv,
942                          strerror (errsv));
943               continue;
944             }
945 
946           old_fd = fileno (streams[i].stream);
947 
948           if (old_fd < 0)
949             {
950               g_warning ("Stream %s does not have a valid fd",
951                          streams[i].stream_name);
952               continue;
953             }
954         }
955 
956       new_fd = _open_osfhandle ((intptr_t) std_handle, streams[i].flags);
957 
958       if (new_fd < 0)
959         {
960           g_warning ("Failed to create new fd for stream %s",
961                      streams[i].stream_name);
962           continue;
963         }
964 
965       backup_fd = dup (old_fd);
966 
967       if (backup_fd < 0)
968         g_warning ("Failed to backup old fd %d for stream %s",
969                    old_fd, streams[i].stream_name);
970 
971       errno = 0;
972 
973       /* Force old_fd to be associated with the same file
974        * as new_fd, i.e with the standard handle we need
975        * (or, rather, with the same kernel object; handle
976        * value will be different, but the kernel object
977        * won't be).
978        */
979       /* NOTE: MSDN claims that _dup2() returns 0 on success and -1 on error,
980        * POSIX claims that dup2() reurns new FD on success and -1 on error.
981        * The "< 0" check satisfies the error condition for either implementation.
982        */
983       if (_dup2 (new_fd, old_fd) < 0)
984         {
985           errsv = errno;
986           g_warning ("Failed to substitute fd %d for stream %s: %d : %s",
987                      old_fd, streams[i].stream_name, errsv, strerror (errsv));
988 
989           _close (new_fd);
990 
991           if (backup_fd < 0)
992             continue;
993 
994           errno = 0;
995 
996           /* Try to restore old_fd back to its previous
997            * handle, in case the _dup2() call above succeeded partially.
998            */
999           if (_dup2 (backup_fd, old_fd) < 0)
1000             {
1001               errsv = errno;
1002               g_warning ("Failed to restore fd %d for stream %s: %d : %s",
1003                          old_fd, streams[i].stream_name, errsv, strerror (errsv));
1004             }
1005 
1006           _close (backup_fd);
1007 
1008           continue;
1009         }
1010 
1011       /* Success, drop the backup */
1012       if (backup_fd >= 0)
1013         _close (backup_fd);
1014 
1015       /* Sadly, there's no way to check that preferred_fd
1016        * is currently valid, so we can't back it up.
1017        * Doing operations on invalid FDs invokes invalid
1018        * parameter handler, which is bad for us.
1019        */
1020       if (old_fd != preferred_fd)
1021         /* This extra code will also try to ensure that
1022          * the expected file descriptors 0, 1 and 2 are
1023          * associated with the appropriate standard
1024          * handles.
1025          */
1026         if (_dup2 (new_fd, preferred_fd) < 0)
1027           g_warning ("Failed to dup fd %d into fd %d", new_fd, preferred_fd);
1028 
1029       _close (new_fd);
1030     }
1031 }
1032 
1033 /* This is a handle to the Vectored Exception Handler that
1034  * we install on library initialization. If installed correctly,
1035  * it will be non-NULL. Only used to later de-install the handler
1036  * on library de-initialization.
1037  */
1038 static void *WinVEH_handle = NULL;
1039 
1040 #include "gwin32-private.c"
1041 
1042 /* Handles exceptions (useful for debugging).
1043  * Issues a DebugBreak() call if the process is being debugged (not really
1044  * useful - if the process is being debugged, this handler won't be invoked
1045  * anyway). If it is not, runs a debugger from G_DEBUGGER env var,
1046  * substituting first %p in it for PID, and the first %e for the event handle -
1047  * that event should be set once the debugger attaches itself (otherwise the
1048  * only way out of WaitForSingleObject() is to time out after 1 minute).
1049  * For example, G_DEBUGGER can be set to the following command:
1050  * ```
1051  * gdb.exe -ex "attach %p" -ex "signal-event %e" -ex "bt" -ex "c"
1052  * ```
1053  * This will make GDB attach to the process, signal the event (GDB must be
1054  * recent enough for the signal-event command to be available),
1055  * show the backtrace and resume execution, which should make it catch
1056  * the exception when Windows re-raises it again.
1057  * The command line can't be longer than MAX_PATH (260 characters).
1058  *
1059  * This function will only stop (and run a debugger) on the following exceptions:
1060  * * EXCEPTION_ACCESS_VIOLATION
1061  * * EXCEPTION_STACK_OVERFLOW
1062  * * EXCEPTION_ILLEGAL_INSTRUCTION
1063  * To make it stop at other exceptions one should set the G_VEH_CATCH
1064  * environment variable to a list of comma-separated hexadecimal numbers,
1065  * where each number is the code of an exception that should be caught.
1066  * This is done to prevent GLib from breaking when Windows uses
1067  * exceptions to shuttle information (SetThreadName(), OutputDebugString())
1068  * or for control flow.
1069  *
1070  * This function deliberately avoids calling any GLib code.
1071  */
1072 static LONG __stdcall
g_win32_veh_handler(PEXCEPTION_POINTERS ExceptionInfo)1073 g_win32_veh_handler (PEXCEPTION_POINTERS ExceptionInfo)
1074 {
1075   EXCEPTION_RECORD    *er;
1076   char                 debugger[MAX_PATH + 1];
1077   WCHAR               *debugger_utf16;
1078   const char          *debugger_env = NULL;
1079   const char          *catch_list;
1080   gboolean             catch = FALSE;
1081   STARTUPINFOW         si;
1082   PROCESS_INFORMATION  pi;
1083   HANDLE               event;
1084   SECURITY_ATTRIBUTES  sa;
1085 
1086   if (ExceptionInfo == NULL ||
1087       ExceptionInfo->ExceptionRecord == NULL ||
1088       IsDebuggerPresent ())
1089     return EXCEPTION_CONTINUE_SEARCH;
1090 
1091   er = ExceptionInfo->ExceptionRecord;
1092 
1093   switch (er->ExceptionCode)
1094     {
1095     case EXCEPTION_ACCESS_VIOLATION:
1096     case EXCEPTION_STACK_OVERFLOW:
1097     case EXCEPTION_ILLEGAL_INSTRUCTION:
1098       break;
1099     default:
1100       catch_list = g_getenv ("G_VEH_CATCH");
1101 
1102       while (!catch &&
1103              catch_list != NULL &&
1104              catch_list[0] != 0)
1105         {
1106           unsigned long  catch_code;
1107           char          *end;
1108           errno = 0;
1109           catch_code = strtoul (catch_list, &end, 16);
1110           if (errno != NO_ERROR)
1111             break;
1112           catch_list = end;
1113           if (catch_list != NULL && catch_list[0] == ',')
1114             catch_list++;
1115           if (catch_code == er->ExceptionCode)
1116             catch = TRUE;
1117         }
1118 
1119       if (catch)
1120         break;
1121 
1122       return EXCEPTION_CONTINUE_SEARCH;
1123     }
1124 
1125   fprintf_s (stderr,
1126              "Exception code=0x%lx flags=0x%lx at 0x%p",
1127              er->ExceptionCode,
1128              er->ExceptionFlags,
1129              er->ExceptionAddress);
1130 
1131   switch (er->ExceptionCode)
1132     {
1133     case EXCEPTION_ACCESS_VIOLATION:
1134       fprintf_s (stderr,
1135                  ". Access violation - attempting to %s at address 0x%p\n",
1136                  er->ExceptionInformation[0] == 0 ? "read data" :
1137                  er->ExceptionInformation[0] == 1 ? "write data" :
1138                  er->ExceptionInformation[0] == 8 ? "execute data" :
1139                  "do something bad",
1140                  (void *) er->ExceptionInformation[1]);
1141       break;
1142     case EXCEPTION_IN_PAGE_ERROR:
1143       fprintf_s (stderr,
1144                  ". Page access violation - attempting to %s at address 0x%p with status %Ix\n",
1145                  er->ExceptionInformation[0] == 0 ? "read from an inaccessible page" :
1146                  er->ExceptionInformation[0] == 1 ? "write to an inaccessible page" :
1147                  er->ExceptionInformation[0] == 8 ? "execute data in page" :
1148                  "do something bad with a page",
1149                  (void *) er->ExceptionInformation[1],
1150                  er->ExceptionInformation[2]);
1151       break;
1152     default:
1153       fprintf_s (stderr, "\n");
1154       break;
1155     }
1156 
1157   fflush (stderr);
1158 
1159   debugger_env = g_getenv ("G_DEBUGGER");
1160 
1161   if (debugger_env == NULL)
1162     return EXCEPTION_CONTINUE_SEARCH;
1163 
1164   /* Create an inheritable event */
1165   memset (&si, 0, sizeof (si));
1166   memset (&pi, 0, sizeof (pi));
1167   memset (&sa, 0, sizeof (sa));
1168   si.cb = sizeof (si);
1169   sa.nLength = sizeof (sa);
1170   sa.bInheritHandle = TRUE;
1171   event = CreateEvent (&sa, FALSE, FALSE, NULL);
1172 
1173   /* Put process ID and event handle into debugger commandline */
1174   if (!_g_win32_subst_pid_and_event (debugger, G_N_ELEMENTS (debugger),
1175                                      debugger_env, GetCurrentProcessId (),
1176                                      (guintptr) event))
1177     {
1178       CloseHandle (event);
1179       return EXCEPTION_CONTINUE_SEARCH;
1180     }
1181   debugger[MAX_PATH] = '\0';
1182 
1183   debugger_utf16 = g_utf8_to_utf16 (debugger, -1, NULL, NULL, NULL);
1184 
1185   /* Run the debugger */
1186   if (0 != CreateProcessW (NULL,
1187                            debugger_utf16,
1188                            NULL,
1189                            NULL,
1190                            TRUE,
1191                            g_getenv ("G_DEBUGGER_OLD_CONSOLE") != NULL ? 0 : CREATE_NEW_CONSOLE,
1192                            NULL,
1193                            NULL,
1194                            &si,
1195                            &pi))
1196     {
1197       CloseHandle (pi.hProcess);
1198       CloseHandle (pi.hThread);
1199       /* If successful, wait for 60 seconds on the event
1200        * we passed. The debugger should signal that event.
1201        * 60 second limit is here to prevent us from hanging
1202        * up forever in case the debugger does not support
1203        * event signalling.
1204        */
1205       WaitForSingleObject (event, 60000);
1206     }
1207 
1208   g_free (debugger_utf16);
1209 
1210   CloseHandle (event);
1211 
1212   /* Now the debugger is present, and we can try
1213    * resuming execution, re-triggering the exception,
1214    * which will be caught by debugger this time around.
1215    */
1216   if (IsDebuggerPresent ())
1217     return EXCEPTION_CONTINUE_EXECUTION;
1218 
1219   return EXCEPTION_CONTINUE_SEARCH;
1220 }
1221 
1222 void
g_crash_handler_win32_init(void)1223 g_crash_handler_win32_init (void)
1224 {
1225   if (WinVEH_handle != NULL)
1226     return;
1227 
1228   /* Do not register an exception handler if we're not supposed to catch any
1229    * exceptions. Exception handlers are considered dangerous to use, and can
1230    * break advanced exception handling such as in CLRs like C# or other managed
1231    * code. See: https://blogs.msdn.microsoft.com/jmstall/2006/05/24/beware-of-the-vectored-exception-handler-and-managed-code/
1232    */
1233   if (g_getenv ("G_DEBUGGER") == NULL && g_getenv("G_VEH_CATCH") == NULL)
1234     return;
1235 
1236   WinVEH_handle = AddVectoredExceptionHandler (0, &g_win32_veh_handler);
1237 }
1238 
1239 void
g_crash_handler_win32_deinit(void)1240 g_crash_handler_win32_deinit (void)
1241 {
1242   if (WinVEH_handle != NULL)
1243     RemoveVectoredExceptionHandler (WinVEH_handle);
1244 
1245   WinVEH_handle = NULL;
1246 }
1247 
1248 #endif
1249