[kdbus] sync with kdbus (kdbus.h - commit: 5ae1ecac44cb)
[platform/upstream/glib.git] / glib / gwin32.c
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 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
40 #define STRICT                  /* Strict typing, please */
41 #include <windows.h>
42 #undef STRICT
43 #ifndef G_WITH_CYGWIN
44 #include <direct.h>
45 #endif
46 #include <errno.h>
47 #include <ctype.h>
48 #if defined(_MSC_VER) || defined(__DMC__)
49 #  include <io.h>
50 #endif /* _MSC_VER || __DMC__ */
51
52 #include "glib.h"
53 #include "gthreadprivate.h"
54
55 #ifdef G_WITH_CYGWIN
56 #include <sys/cygwin.h>
57 #endif
58
59 #ifndef G_WITH_CYGWIN
60
61 gint
62 g_win32_ftruncate (gint  fd,
63                    guint size)
64 {
65   return _chsize (fd, size);
66 }
67
68 #endif
69
70 /**
71  * g_win32_getlocale:
72  *
73  * The setlocale() function in the Microsoft C library uses locale
74  * names of the form "English_United States.1252" etc. We want the
75  * UNIXish standard form "en_US", "zh_TW" etc. This function gets the
76  * current thread locale from Windows - without any encoding info -
77  * and returns it as a string of the above form for use in forming
78  * file names etc. The returned string should be deallocated with
79  * g_free().
80  *
81  * Returns: newly-allocated locale name.
82  **/
83
84 #ifndef SUBLANG_SERBIAN_LATIN_BA
85 #define SUBLANG_SERBIAN_LATIN_BA 0x06
86 #endif
87
88 gchar *
89 g_win32_getlocale (void)
90 {
91   LCID lcid;
92   LANGID langid;
93   gchar *ev;
94   gint primary, sub;
95   char iso639[10];
96   char iso3166[10];
97   const gchar *script = NULL;
98
99   /* Let the user override the system settings through environment
100    * variables, as on POSIX systems. Note that in GTK+ applications
101    * since GTK+ 2.10.7 setting either LC_ALL or LANG also sets the
102    * Win32 locale and C library locale through code in gtkmain.c.
103    */
104   if (((ev = getenv ("LC_ALL")) != NULL && ev[0] != '\0')
105       || ((ev = getenv ("LC_MESSAGES")) != NULL && ev[0] != '\0')
106       || ((ev = getenv ("LANG")) != NULL && ev[0] != '\0'))
107     return g_strdup (ev);
108
109   lcid = GetThreadLocale ();
110
111   if (!GetLocaleInfo (lcid, LOCALE_SISO639LANGNAME, iso639, sizeof (iso639)) ||
112       !GetLocaleInfo (lcid, LOCALE_SISO3166CTRYNAME, iso3166, sizeof (iso3166)))
113     return g_strdup ("C");
114   
115   /* Strip off the sorting rules, keep only the language part.  */
116   langid = LANGIDFROMLCID (lcid);
117
118   /* Split into language and territory part.  */
119   primary = PRIMARYLANGID (langid);
120   sub = SUBLANGID (langid);
121
122   /* Handle special cases */
123   switch (primary)
124     {
125     case LANG_AZERI:
126       switch (sub)
127         {
128         case SUBLANG_AZERI_LATIN:
129           script = "@Latn";
130           break;
131         case SUBLANG_AZERI_CYRILLIC:
132           script = "@Cyrl";
133           break;
134         }
135       break;
136     case LANG_SERBIAN:          /* LANG_CROATIAN == LANG_SERBIAN */
137       switch (sub)
138         {
139         case SUBLANG_SERBIAN_LATIN:
140         case 0x06: /* Serbian (Latin) - Bosnia and Herzegovina */
141           script = "@Latn";
142           break;
143         }
144       break;
145     case LANG_UZBEK:
146       switch (sub)
147         {
148         case SUBLANG_UZBEK_LATIN:
149           script = "@Latn";
150           break;
151         case SUBLANG_UZBEK_CYRILLIC:
152           script = "@Cyrl";
153           break;
154         }
155       break;
156     }
157   return g_strconcat (iso639, "_", iso3166, script, NULL);
158 }
159
160 /**
161  * g_win32_error_message:
162  * @error: error code.
163  *
164  * Translate a Win32 error code (as returned by GetLastError() or
165  * WSAGetLastError()) into the corresponding message. The message is
166  * either language neutral, or in the thread's language, or the user's
167  * language, the system's language, or US English (see docs for
168  * FormatMessage()). The returned string is in UTF-8. It should be
169  * deallocated with g_free().
170  *
171  * Returns: newly-allocated error message
172  **/
173 gchar *
174 g_win32_error_message (gint error)
175 {
176   gchar *retval;
177   wchar_t *msg = NULL;
178   int nchars;
179
180   FormatMessageW (FORMAT_MESSAGE_ALLOCATE_BUFFER
181                   |FORMAT_MESSAGE_IGNORE_INSERTS
182                   |FORMAT_MESSAGE_FROM_SYSTEM,
183                   NULL, error, 0,
184                   (LPWSTR) &msg, 0, NULL);
185   if (msg != NULL)
186     {
187       nchars = wcslen (msg);
188       
189       if (nchars > 2 && msg[nchars-1] == '\n' && msg[nchars-2] == '\r')
190         msg[nchars-2] = '\0';
191       
192       retval = g_utf16_to_utf8 (msg, -1, NULL, NULL, NULL);
193       
194       LocalFree (msg);
195     }
196   else
197     retval = g_strdup ("");
198
199   return retval;
200 }
201
202 /**
203  * g_win32_get_package_installation_directory_of_module:
204  * @hmodule: (allow-none): The Win32 handle for a DLL loaded into the current process, or %NULL
205  *
206  * This function tries to determine the installation directory of a
207  * software package based on the location of a DLL of the software
208  * package.
209  *
210  * @hmodule should be the handle of a loaded DLL or %NULL. The
211  * function looks up the directory that DLL was loaded from. If
212  * @hmodule is NULL, the directory the main executable of the current
213  * process is looked up. If that directory's last component is "bin"
214  * or "lib", its parent directory is returned, otherwise the directory
215  * itself.
216  *
217  * It thus makes sense to pass only the handle to a "public" DLL of a
218  * software package to this function, as such DLLs typically are known
219  * to be installed in a "bin" or occasionally "lib" subfolder of the
220  * installation folder. DLLs that are of the dynamically loaded module
221  * or plugin variety are often located in more private locations
222  * deeper down in the tree, from which it is impossible for GLib to
223  * deduce the root of the package installation.
224  *
225  * The typical use case for this function is to have a DllMain() that
226  * saves the handle for the DLL. Then when code in the DLL needs to
227  * construct names of files in the installation tree it calls this
228  * function passing the DLL handle.
229  *
230  * Returns: a string containing the guessed installation directory for
231  * the software package @hmodule is from. The string is in the GLib
232  * file name encoding, i.e. UTF-8. The return value should be freed
233  * with g_free() when not needed any longer. If the function fails
234  * %NULL is returned.
235  *
236  * Since: 2.16
237  */
238 gchar *
239 g_win32_get_package_installation_directory_of_module (gpointer hmodule)
240 {
241   gchar *filename;
242   gchar *retval;
243   gchar *p;
244   wchar_t wc_fn[MAX_PATH];
245
246   /* NOTE: it relies that GetModuleFileNameW returns only canonical paths */
247   if (!GetModuleFileNameW (hmodule, wc_fn, MAX_PATH))
248     return NULL;
249
250   filename = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
251
252   if ((p = strrchr (filename, G_DIR_SEPARATOR)) != NULL)
253     *p = '\0';
254
255   retval = g_strdup (filename);
256
257   do
258     {
259       p = strrchr (retval, G_DIR_SEPARATOR);
260       if (p == NULL)
261         break;
262
263       *p = '\0';
264
265       if (g_ascii_strcasecmp (p + 1, "bin") == 0 ||
266           g_ascii_strcasecmp (p + 1, "lib") == 0)
267         break;
268     }
269   while (p != NULL);
270
271   if (p == NULL)
272     {
273       g_free (retval);
274       retval = filename;
275     }
276   else
277     g_free (filename);
278
279 #ifdef G_WITH_CYGWIN
280   /* In Cygwin we need to have POSIX paths */
281   {
282     gchar tmp[MAX_PATH];
283
284     cygwin_conv_to_posix_path (retval, tmp);
285     g_free (retval);
286     retval = g_strdup (tmp);
287   }
288 #endif
289
290   return retval;
291 }
292
293 static gchar *
294 get_package_directory_from_module (const gchar *module_name)
295 {
296   static GHashTable *module_dirs = NULL;
297   G_LOCK_DEFINE_STATIC (module_dirs);
298   HMODULE hmodule = NULL;
299   gchar *fn;
300
301   G_LOCK (module_dirs);
302
303   if (module_dirs == NULL)
304     module_dirs = g_hash_table_new (g_str_hash, g_str_equal);
305   
306   fn = g_hash_table_lookup (module_dirs, module_name ? module_name : "");
307       
308   if (fn)
309     {
310       G_UNLOCK (module_dirs);
311       return g_strdup (fn);
312     }
313
314   if (module_name)
315     {
316       wchar_t *wc_module_name = g_utf8_to_utf16 (module_name, -1, NULL, NULL, NULL);
317       hmodule = GetModuleHandleW (wc_module_name);
318       g_free (wc_module_name);
319
320       if (!hmodule)
321         {
322           G_UNLOCK (module_dirs);
323           return NULL;
324         }
325     }
326
327   fn = g_win32_get_package_installation_directory_of_module (hmodule);
328
329   if (fn == NULL)
330     {
331       G_UNLOCK (module_dirs);
332       return NULL;
333     }
334   
335   g_hash_table_insert (module_dirs, module_name ? g_strdup (module_name) : "", fn);
336
337   G_UNLOCK (module_dirs);
338
339   return g_strdup (fn);
340 }
341
342 /**
343  * g_win32_get_package_installation_directory:
344  * @package: (allow-none): You should pass %NULL for this.
345  * @dll_name: (allow-none): The name of a DLL that a package provides in UTF-8, or %NULL.
346  *
347  * Try to determine the installation directory for a software package.
348  *
349  * This function is deprecated. Use
350  * g_win32_get_package_installation_directory_of_module() instead.
351  *
352  * The use of @package is deprecated. You should always pass %NULL. A
353  * warning is printed if non-NULL is passed as @package.
354  *
355  * The original intended use of @package was for a short identifier of
356  * the package, typically the same identifier as used for
357  * `GETTEXT_PACKAGE` in software configured using GNU
358  * autotools. The function first looks in the Windows Registry for the
359  * value `#InstallationDirectory` in the key
360  * `#HKLM\Software\@package`, and if that value
361  * exists and is a string, returns that.
362  *
363  * It is strongly recommended that packagers of GLib-using libraries
364  * for Windows do not store installation paths in the Registry to be
365  * used by this function as that interfers with having several
366  * parallel installations of the library. Enabling multiple
367  * installations of different versions of some GLib-using library, or
368  * GLib itself, is desirable for various reasons.
369  *
370  * For this reason it is recommeded to always pass %NULL as
371  * @package to this function, to avoid the temptation to use the
372  * Registry. In version 2.20 of GLib the @package parameter
373  * will be ignored and this function won't look in the Registry at all.
374  *
375  * If @package is %NULL, or the above value isn't found in the
376  * Registry, but @dll_name is non-%NULL, it should name a DLL loaded
377  * into the current process. Typically that would be the name of the
378  * DLL calling this function, looking for its installation
379  * directory. The function then asks Windows what directory that DLL
380  * was loaded from. If that directory's last component is "bin" or
381  * "lib", the parent directory is returned, otherwise the directory
382  * itself. If that DLL isn't loaded, the function proceeds as if
383  * @dll_name was %NULL.
384  *
385  * If both @package and @dll_name are %NULL, the directory from where
386  * the main executable of the process was loaded is used instead in
387  * the same way as above.
388  *
389  * Returns: a string containing the installation directory for
390  * @package. The string is in the GLib file name encoding,
391  * i.e. UTF-8. The return value should be freed with g_free() when not
392  * needed any longer. If the function fails %NULL is returned.
393  *
394  * Deprecated: 2.18: Pass the HMODULE of a DLL or EXE to
395  * g_win32_get_package_installation_directory_of_module() instead.
396  **/
397
398  gchar *
399 g_win32_get_package_installation_directory_utf8 (const gchar *package,
400                                                  const gchar *dll_name)
401 {
402   gchar *result = NULL;
403
404   if (package != NULL)
405       g_warning ("Passing a non-NULL package to g_win32_get_package_installation_directory() is deprecated and it is ignored.");
406
407   if (dll_name != NULL)
408     result = get_package_directory_from_module (dll_name);
409
410   if (result == NULL)
411     result = get_package_directory_from_module (NULL);
412
413   return result;
414 }
415
416 #if !defined (_WIN64)
417
418 /* DLL ABI binary compatibility version that uses system codepage file names */
419
420 gchar *
421 g_win32_get_package_installation_directory (const gchar *package,
422                                             const gchar *dll_name)
423 {
424   gchar *utf8_package = NULL, *utf8_dll_name = NULL;
425   gchar *utf8_retval, *retval;
426
427   if (package != NULL)
428     utf8_package = g_locale_to_utf8 (package, -1, NULL, NULL, NULL);
429
430   if (dll_name != NULL)
431     utf8_dll_name = g_locale_to_utf8 (dll_name, -1, NULL, NULL, NULL);
432
433   utf8_retval =
434     g_win32_get_package_installation_directory_utf8 (utf8_package,
435                                                      utf8_dll_name);
436
437   retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
438
439   g_free (utf8_package);
440   g_free (utf8_dll_name);
441   g_free (utf8_retval);
442
443   return retval;
444 }
445
446 #endif
447
448 /**
449  * g_win32_get_package_installation_subdirectory:
450  * @package: (allow-none): You should pass %NULL for this.
451  * @dll_name: (allow-none): The name of a DLL that a package provides, in UTF-8, or %NULL.
452  * @subdir: A subdirectory of the package installation directory, also in UTF-8
453  *
454  * This function is deprecated. Use
455  * g_win32_get_package_installation_directory_of_module() and
456  * g_build_filename() instead.
457  *
458  * Returns a newly-allocated string containing the path of the
459  * subdirectory @subdir in the return value from calling
460  * g_win32_get_package_installation_directory() with the @package and
461  * @dll_name parameters. See the documentation for
462  * g_win32_get_package_installation_directory() for more details. In
463  * particular, note that it is deprecated to pass anything except NULL
464  * as @package.
465  *
466  * Returns: a string containing the complete path to @subdir inside
467  * the installation directory of @package. The returned string is in
468  * the GLib file name encoding, i.e. UTF-8. The return value should be
469  * freed with g_free() when no longer needed. If something goes wrong,
470  * %NULL is returned.
471  *
472  * Deprecated: 2.18: Pass the HMODULE of a DLL or EXE to
473  * g_win32_get_package_installation_directory_of_module() instead, and
474  * then construct a subdirectory pathname with g_build_filename().
475  **/
476
477 gchar *
478 g_win32_get_package_installation_subdirectory_utf8 (const gchar *package,
479                                                     const gchar *dll_name,
480                                                     const gchar *subdir)
481 {
482   gchar *prefix;
483   gchar *dirname;
484
485 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
486   prefix = g_win32_get_package_installation_directory_utf8 (package, dll_name);
487 G_GNUC_END_IGNORE_DEPRECATIONS
488
489   dirname = g_build_filename (prefix, subdir, NULL);
490   g_free (prefix);
491
492   return dirname;
493 }
494
495 #if !defined (_WIN64)
496
497 /* DLL ABI binary compatibility version that uses system codepage file names */
498
499 gchar *
500 g_win32_get_package_installation_subdirectory (const gchar *package,
501                                                const gchar *dll_name,
502                                                const gchar *subdir)
503 {
504   gchar *prefix;
505   gchar *dirname;
506
507   G_GNUC_BEGIN_IGNORE_DEPRECATIONS
508   prefix = g_win32_get_package_installation_directory (package, dll_name);
509   G_GNUC_END_IGNORE_DEPRECATIONS
510
511   dirname = g_build_filename (prefix, subdir, NULL);
512   g_free (prefix);
513
514   return dirname;
515 }
516
517 #endif
518
519 /**
520  * g_win32_get_windows_version:
521  *
522  * Returns version information for the Windows operating system the
523  * code is running on. See MSDN documentation for the GetVersion()
524  * function. To summarize, the most significant bit is one on Win9x,
525  * and zero on NT-based systems. Since version 2.14, GLib works only
526  * on NT-based systems, so checking whether your are running on Win9x
527  * in your own software is moot. The least significant byte is 4 on
528  * Windows NT 4, and 5 on Windows XP. Software that needs really
529  * detailed version and feature information should use Win32 API like
530  * GetVersionEx() and VerifyVersionInfo().
531  *
532  * Returns: The version information.
533  * 
534  * Since: 2.6
535  **/
536 guint
537 g_win32_get_windows_version (void)
538 {
539   static gsize windows_version;
540
541   if (g_once_init_enter (&windows_version))
542     g_once_init_leave (&windows_version, GetVersion ());
543
544   return windows_version;
545 }
546
547 /**
548  * g_win32_locale_filename_from_utf8:
549  * @utf8filename: a UTF-8 encoded filename.
550  *
551  * Converts a filename from UTF-8 to the system codepage.
552  *
553  * On NT-based Windows, on NTFS file systems, file names are in
554  * Unicode. It is quite possible that Unicode file names contain
555  * characters not representable in the system codepage. (For instance,
556  * Greek or Cyrillic characters on Western European or US Windows
557  * installations, or various less common CJK characters on CJK Windows
558  * installations.)
559  *
560  * In such a case, and if the filename refers to an existing file, and
561  * the file system stores alternate short (8.3) names for directory
562  * entries, the short form of the filename is returned. Note that the
563  * "short" name might in fact be longer than the Unicode name if the
564  * Unicode name has very short pathname components containing
565  * non-ASCII characters. If no system codepage name for the file is
566  * possible, %NULL is returned.
567  *
568  * The return value is dynamically allocated and should be freed with
569  * g_free() when no longer needed.
570  *
571  * Returns: The converted filename, or %NULL on conversion
572  * failure and lack of short names.
573  *
574  * Since: 2.8
575  */
576 gchar *
577 g_win32_locale_filename_from_utf8 (const gchar *utf8filename)
578 {
579   gchar *retval = g_locale_from_utf8 (utf8filename, -1, NULL, NULL, NULL);
580
581   if (retval == NULL)
582     {
583       /* Conversion failed, so convert to wide chars, check if there
584        * is a 8.3 version, and use that.
585        */
586       wchar_t *wname = g_utf8_to_utf16 (utf8filename, -1, NULL, NULL, NULL);
587       if (wname != NULL)
588         {
589           wchar_t wshortname[MAX_PATH + 1];
590           if (GetShortPathNameW (wname, wshortname, G_N_ELEMENTS (wshortname)))
591             {
592               gchar *tem = g_utf16_to_utf8 (wshortname, -1, NULL, NULL, NULL);
593               retval = g_locale_from_utf8 (tem, -1, NULL, NULL, NULL);
594               g_free (tem);
595             }
596           g_free (wname);
597         }
598     }
599   return retval;
600 }
601
602 /**
603  * g_win32_get_command_line:
604  *
605  * Gets the command line arguments, on Windows, in the GLib filename
606  * encoding (ie: UTF-8).
607  *
608  * Normally, on Windows, the command line arguments are passed to main()
609  * in the system codepage encoding.  This prevents passing filenames as
610  * arguments if the filenames contain characters that fall outside of
611  * this codepage.  If such filenames are passed, then substitutions
612  * will occur (such as replacing some characters with '?').
613  *
614  * GLib's policy of using UTF-8 as a filename encoding on Windows was
615  * designed to localise the pain of dealing with filenames outside of
616  * the system codepage to one area: dealing with commandline arguments
617  * in main().
618  *
619  * As such, most GLib programs should ignore the value of argv passed to
620  * their main() function and call g_win32_get_command_line() instead.
621  * This will get the "full Unicode" commandline arguments using
622  * GetCommandLineW() and convert it to the GLib filename encoding (which
623  * is UTF-8 on Windows).
624  *
625  * The strings returned by this function are suitable for use with
626  * functions such as g_open() and g_file_new_for_commandline_arg() but
627  * are not suitable for use with g_option_context_parse(), which assumes
628  * that its input will be in the system codepage.  The return value is
629  * suitable for use with g_option_context_parse_strv(), however, which
630  * is a better match anyway because it won't leak memory.
631  *
632  * Unlike argv, the returned value is a normal strv and can (and should)
633  * be freed with g_strfreev() when no longer needed.
634  *
635  * Returns: (transfer full): the commandline arguments in the GLib
636  *   filename encoding (ie: UTF-8)
637  *
638  * Since: 2.40
639  **/
640 gchar **
641 g_win32_get_command_line (void)
642 {
643   gchar **result;
644   LPWSTR *args;
645   gint i, n;
646
647   args = CommandLineToArgvW (GetCommandLineW(), &n);
648
649   result = g_new (gchar *, n + 1);
650   for (i = 0; i < n; i++)
651     result[i] = g_utf16_to_utf8 (args[i], -1, NULL, NULL, NULL);
652   result[i] = NULL;
653
654   return result;
655 }