Imported Upstream version 2.56.2
[platform/upstream/glib.git] / glib / gutils.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1998  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
16  */
17
18 /*
19  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
20  * file for a list of people on the GLib Team.  See the ChangeLog
21  * files for a list of changes.  These files are distributed with
22  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
23  */
24
25 /* 
26  * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
27  */
28
29 #include "config.h"
30
31 #include "gutils.h"
32
33 #include <stdarg.h>
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <locale.h>
37 #include <string.h>
38 #include <ctype.h>              /* For tolower() */
39 #include <errno.h>
40 #include <sys/types.h>
41 #include <sys/stat.h>
42 #ifdef G_OS_UNIX
43 #include <pwd.h>
44 #include <unistd.h>
45 #endif
46 #include <sys/types.h>
47 #ifdef HAVE_SYS_PARAM_H
48 #include <sys/param.h>
49 #endif
50 #ifdef HAVE_CRT_EXTERNS_H 
51 #include <crt_externs.h> /* for _NSGetEnviron */
52 #endif
53
54 #include "glib-init.h"
55 #include "glib-private.h"
56 #include "genviron.h"
57 #include "gfileutils.h"
58 #include "ggettext.h"
59 #include "ghash.h"
60 #include "gthread.h"
61 #include "gtestutils.h"
62 #include "gunicode.h"
63 #include "gstrfuncs.h"
64 #include "garray.h"
65 #include "glibintl.h"
66 #include "gstdio.h"
67
68 #ifdef G_PLATFORM_WIN32
69 #include "gconvert.h"
70 #include "gwin32.h"
71 #endif
72
73
74 /**
75  * SECTION:misc_utils
76  * @title: Miscellaneous Utility Functions
77  * @short_description: a selection of portable utility functions
78  *
79  * These are portable utility functions.
80  */
81
82 #ifdef G_PLATFORM_WIN32
83 #  include <windows.h>
84 #  ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
85 #    define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
86 #    define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
87 #  endif
88 #  include <lmcons.h>           /* For UNLEN */
89 #endif /* G_PLATFORM_WIN32 */
90
91 #ifdef G_OS_WIN32
92 #  include <direct.h>
93 #  include <shlobj.h>
94    /* older SDK (e.g. msvc 5.0) does not have these*/
95 #  ifndef CSIDL_MYMUSIC
96 #    define CSIDL_MYMUSIC 13
97 #  endif
98 #  ifndef CSIDL_MYVIDEO
99 #    define CSIDL_MYVIDEO 14
100 #  endif
101 #  ifndef CSIDL_INTERNET_CACHE
102 #    define CSIDL_INTERNET_CACHE 32
103 #  endif
104 #  ifndef CSIDL_COMMON_APPDATA
105 #    define CSIDL_COMMON_APPDATA 35
106 #  endif
107 #  ifndef CSIDL_MYPICTURES
108 #    define CSIDL_MYPICTURES 0x27
109 #  endif
110 #  ifndef CSIDL_COMMON_DOCUMENTS
111 #    define CSIDL_COMMON_DOCUMENTS 46
112 #  endif
113 #  ifndef CSIDL_PROFILE
114 #    define CSIDL_PROFILE 40
115 #  endif
116 #  include <process.h>
117 #endif
118
119 #ifdef HAVE_CARBON
120 #include <CoreServices/CoreServices.h>
121 #endif
122
123 #ifdef HAVE_CODESET
124 #include <langinfo.h>
125 #endif
126
127 #ifdef G_PLATFORM_WIN32
128
129 gchar *
130 _glib_get_dll_directory (void)
131 {
132   gchar *retval;
133   gchar *p;
134   wchar_t wc_fn[MAX_PATH];
135
136 #ifdef DLL_EXPORT
137   if (glib_dll == NULL)
138     return NULL;
139 #endif
140
141   /* This code is different from that in
142    * g_win32_get_package_installation_directory_of_module() in that
143    * here we return the actual folder where the GLib DLL is. We don't
144    * do the check for it being in a "bin" or "lib" subfolder and then
145    * returning the parent of that.
146    *
147    * In a statically built GLib, glib_dll will be NULL and we will
148    * thus look up the application's .exe file's location.
149    */
150   if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
151     return NULL;
152
153   retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
154
155   p = strrchr (retval, G_DIR_SEPARATOR);
156   if (p == NULL)
157     {
158       /* Wtf? */
159       return NULL;
160     }
161   *p = '\0';
162
163   return retval;
164 }
165
166 #endif
167
168 /**
169  * g_memmove: 
170  * @dest: the destination address to copy the bytes to.
171  * @src: the source address to copy the bytes from.
172  * @len: the number of bytes to copy.
173  *
174  * Copies a block of memory @len bytes long, from @src to @dest.
175  * The source and destination areas may overlap.
176  *
177  * Deprecated:2.40: Just use memmove().
178  */
179
180 #ifdef G_OS_WIN32
181 #undef g_atexit
182 #endif
183
184 /**
185  * g_atexit:
186  * @func: (scope async): the function to call on normal program termination.
187  * 
188  * Specifies a function to be called at normal program termination.
189  *
190  * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
191  * macro that maps to a call to the atexit() function in the C
192  * library. This means that in case the code that calls g_atexit(),
193  * i.e. atexit(), is in a DLL, the function will be called when the
194  * DLL is detached from the program. This typically makes more sense
195  * than that the function is called when the GLib DLL is detached,
196  * which happened earlier when g_atexit() was a function in the GLib
197  * DLL.
198  *
199  * The behaviour of atexit() in the context of dynamically loaded
200  * modules is not formally specified and varies wildly.
201  *
202  * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
203  * loaded module which is unloaded before the program terminates might
204  * well cause a crash at program exit.
205  *
206  * Some POSIX systems implement atexit() like Windows, and have each
207  * dynamically loaded module maintain an own atexit chain that is
208  * called when the module is unloaded.
209  *
210  * On other POSIX systems, before a dynamically loaded module is
211  * unloaded, the registered atexit functions (if any) residing in that
212  * module are called, regardless where the code that registered them
213  * resided. This is presumably the most robust approach.
214  *
215  * As can be seen from the above, for portability it's best to avoid
216  * calling g_atexit() (or atexit()) except in the main executable of a
217  * program.
218  *
219  * Deprecated:2.32: It is best to avoid g_atexit().
220  */
221 void
222 g_atexit (GVoidFunc func)
223 {
224   gint result;
225   int errsv;
226
227   result = atexit ((void (*)(void)) func);
228   errsv = errno;
229   if (result)
230     {
231       g_error ("Could not register atexit() function: %s",
232                g_strerror (errsv));
233     }
234 }
235
236 /* Based on execvp() from GNU Libc.
237  * Some of this code is cut-and-pasted into gspawn.c
238  */
239
240 static gchar*
241 my_strchrnul (const gchar *str, 
242               gchar        c)
243 {
244   gchar *p = (gchar*)str;
245   while (*p && (*p != c))
246     ++p;
247
248   return p;
249 }
250
251 #ifdef G_OS_WIN32
252
253 static gchar *inner_find_program_in_path (const gchar *program);
254
255 gchar*
256 g_find_program_in_path (const gchar *program)
257 {
258   const gchar *last_dot = strrchr (program, '.');
259
260   if (last_dot == NULL ||
261       strchr (last_dot, '\\') != NULL ||
262       strchr (last_dot, '/') != NULL)
263     {
264       const gint program_length = strlen (program);
265       gchar *pathext = g_build_path (";",
266                                      ".exe;.cmd;.bat;.com",
267                                      g_getenv ("PATHEXT"),
268                                      NULL);
269       gchar *p;
270       gchar *decorated_program;
271       gchar *retval;
272
273       p = pathext;
274       do
275         {
276           gchar *q = my_strchrnul (p, ';');
277
278           decorated_program = g_malloc (program_length + (q-p) + 1);
279           memcpy (decorated_program, program, program_length);
280           memcpy (decorated_program+program_length, p, q-p);
281           decorated_program [program_length + (q-p)] = '\0';
282           
283           retval = inner_find_program_in_path (decorated_program);
284           g_free (decorated_program);
285
286           if (retval != NULL)
287             {
288               g_free (pathext);
289               return retval;
290             }
291           p = q;
292         } while (*p++ != '\0');
293       g_free (pathext);
294       return NULL;
295     }
296   else
297     return inner_find_program_in_path (program);
298 }
299
300 #endif
301
302 /**
303  * g_find_program_in_path:
304  * @program: (type filename): a program name in the GLib file name encoding
305  * 
306  * Locates the first executable named @program in the user's path, in the
307  * same way that execvp() would locate it. Returns an allocated string
308  * with the absolute path name, or %NULL if the program is not found in
309  * the path. If @program is already an absolute path, returns a copy of
310  * @program if @program exists and is executable, and %NULL otherwise.
311  *  
312  * On Windows, if @program does not have a file type suffix, tries
313  * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
314  * the `PATHEXT` environment variable. 
315  * 
316  * On Windows, it looks for the file in the same way as CreateProcess() 
317  * would. This means first in the directory where the executing
318  * program was loaded from, then in the current directory, then in the
319  * Windows 32-bit system directory, then in the Windows directory, and
320  * finally in the directories in the `PATH` environment variable. If
321  * the program is found, the return value contains the full name
322  * including the type suffix.
323  *
324  * Returns: (type filename): a newly-allocated string with the absolute path,
325  *     or %NULL
326  **/
327 #ifdef G_OS_WIN32
328 static gchar *
329 inner_find_program_in_path (const gchar *program)
330 #else
331 gchar*
332 g_find_program_in_path (const gchar *program)
333 #endif
334 {
335   const gchar *path, *p;
336   gchar *name, *freeme;
337 #ifdef G_OS_WIN32
338   const gchar *path_copy;
339   gchar *filename = NULL, *appdir = NULL;
340   gchar *sysdir = NULL, *windir = NULL;
341   int n;
342   wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
343     wwindir[MAXPATHLEN];
344 #endif
345   gsize len;
346   gsize pathlen;
347
348   g_return_val_if_fail (program != NULL, NULL);
349
350   /* If it is an absolute path, or a relative path including subdirectories,
351    * don't look in PATH.
352    */
353   if (g_path_is_absolute (program)
354       || strchr (program, G_DIR_SEPARATOR) != NULL
355 #ifdef G_OS_WIN32
356       || strchr (program, '/') != NULL
357 #endif
358       )
359     {
360       if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
361           !g_file_test (program, G_FILE_TEST_IS_DIR))
362         return g_strdup (program);
363       else
364         return NULL;
365     }
366   
367   path = g_getenv ("PATH");
368 #if defined(G_OS_UNIX)
369   if (path == NULL)
370     {
371       /* There is no 'PATH' in the environment.  The default
372        * search path in GNU libc is the current directory followed by
373        * the path 'confstr' returns for '_CS_PATH'.
374        */
375       
376       /* In GLib we put . last, for security, and don't use the
377        * unportable confstr(); UNIX98 does not actually specify
378        * what to search if PATH is unset. POSIX may, dunno.
379        */
380       
381       path = "/bin:/usr/bin:.";
382     }
383 #else
384   n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
385   if (n > 0 && n < MAXPATHLEN)
386     filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
387   
388   n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
389   if (n > 0 && n < MAXPATHLEN)
390     sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
391   
392   n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
393   if (n > 0 && n < MAXPATHLEN)
394     windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
395   
396   if (filename)
397     {
398       appdir = g_path_get_dirname (filename);
399       g_free (filename);
400     }
401   
402   path = g_strdup (path);
403
404   if (windir)
405     {
406       const gchar *tem = path;
407       path = g_strconcat (windir, ";", path, NULL);
408       g_free ((gchar *) tem);
409       g_free (windir);
410     }
411   
412   if (sysdir)
413     {
414       const gchar *tem = path;
415       path = g_strconcat (sysdir, ";", path, NULL);
416       g_free ((gchar *) tem);
417       g_free (sysdir);
418     }
419   
420   {
421     const gchar *tem = path;
422     path = g_strconcat (".;", path, NULL);
423     g_free ((gchar *) tem);
424   }
425   
426   if (appdir)
427     {
428       const gchar *tem = path;
429       path = g_strconcat (appdir, ";", path, NULL);
430       g_free ((gchar *) tem);
431       g_free (appdir);
432     }
433
434   path_copy = path;
435 #endif
436   
437   len = strlen (program) + 1;
438   pathlen = strlen (path);
439   freeme = name = g_malloc (pathlen + len + 1);
440   
441   /* Copy the file name at the top, including '\0'  */
442   memcpy (name + pathlen + 1, program, len);
443   name = name + pathlen;
444   /* And add the slash before the filename  */
445   *name = G_DIR_SEPARATOR;
446   
447   p = path;
448   do
449     {
450       char *startp;
451
452       path = p;
453       p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
454
455       if (p == path)
456         /* Two adjacent colons, or a colon at the beginning or the end
457          * of 'PATH' means to search the current directory.
458          */
459         startp = name + 1;
460       else
461         startp = memcpy (name - (p - path), path, p - path);
462
463       if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
464           !g_file_test (startp, G_FILE_TEST_IS_DIR))
465         {
466           gchar *ret;
467           ret = g_strdup (startp);
468           g_free (freeme);
469 #ifdef G_OS_WIN32
470           g_free ((gchar *) path_copy);
471 #endif
472           return ret;
473         }
474     }
475   while (*p++ != '\0');
476   
477   g_free (freeme);
478 #ifdef G_OS_WIN32
479   g_free ((gchar *) path_copy);
480 #endif
481
482   return NULL;
483 }
484
485 /* The functions below are defined this way for compatibility reasons.
486  * See the note in gutils.h.
487  */
488
489 /**
490  * g_bit_nth_lsf:
491  * @mask: a #gulong containing flags
492  * @nth_bit: the index of the bit to start the search from
493  *
494  * Find the position of the first bit set in @mask, searching
495  * from (but not including) @nth_bit upwards. Bits are numbered
496  * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
497  * usually). To start searching from the 0th bit, set @nth_bit to -1.
498  *
499  * Returns: the index of the first bit set which is higher than @nth_bit, or -1
500  *    if no higher bits are set
501  */
502 gint
503 (g_bit_nth_lsf) (gulong mask,
504                  gint   nth_bit)
505 {
506   return g_bit_nth_lsf_impl (mask, nth_bit);
507 }
508
509 /**
510  * g_bit_nth_msf:
511  * @mask: a #gulong containing flags
512  * @nth_bit: the index of the bit to start the search from
513  *
514  * Find the position of the first bit set in @mask, searching
515  * from (but not including) @nth_bit downwards. Bits are numbered
516  * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
517  * usually). To start searching from the last bit, set @nth_bit to
518  * -1 or GLIB_SIZEOF_LONG * 8.
519  *
520  * Returns: the index of the first bit set which is lower than @nth_bit, or -1
521  *    if no lower bits are set
522  */
523 gint
524 (g_bit_nth_msf) (gulong mask,
525                  gint   nth_bit)
526 {
527   return g_bit_nth_msf_impl (mask, nth_bit);
528 }
529
530
531 /**
532  * g_bit_storage:
533  * @number: a #guint
534  *
535  * Gets the number of bits used to hold @number,
536  * e.g. if @number is 4, 3 bits are needed.
537  *
538  * Returns: the number of bits used to hold @number
539  */
540 guint
541 (g_bit_storage) (gulong number)
542 {
543   return g_bit_storage_impl (number);
544 }
545
546 G_LOCK_DEFINE_STATIC (g_utils_global);
547
548 typedef struct
549 {
550   gchar *user_name;
551   gchar *real_name;
552   gchar *home_dir;
553 } UserDatabaseEntry;
554
555 static  gchar   *g_user_data_dir = NULL;
556 static  gchar  **g_system_data_dirs = NULL;
557 static  gchar   *g_user_cache_dir = NULL;
558 static  gchar   *g_user_config_dir = NULL;
559 static  gchar  **g_system_config_dirs = NULL;
560
561 static  gchar  **g_user_special_dirs = NULL;
562
563 /* fifteen minutes of fame for everybody */
564 #define G_USER_DIRS_EXPIRE      15 * 60
565
566 #ifdef G_OS_WIN32
567
568 static gchar *
569 get_special_folder (int csidl)
570 {
571   wchar_t path[MAX_PATH+1];
572   HRESULT hr;
573   LPITEMIDLIST pidl = NULL;
574   BOOL b;
575   gchar *retval = NULL;
576
577   hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
578   if (hr == S_OK)
579     {
580       b = SHGetPathFromIDListW (pidl, path);
581       if (b)
582         retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
583       CoTaskMemFree (pidl);
584     }
585   return retval;
586 }
587
588 static char *
589 get_windows_directory_root (void)
590 {
591   wchar_t wwindowsdir[MAX_PATH];
592
593   if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
594     {
595       /* Usually X:\Windows, but in terminal server environments
596        * might be an UNC path, AFAIK.
597        */
598       char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
599       char *p;
600
601       if (windowsdir == NULL)
602         return g_strdup ("C:\\");
603
604       p = (char *) g_path_skip_root (windowsdir);
605       if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
606         p--;
607       *p = '\0';
608       return windowsdir;
609     }
610   else
611     return g_strdup ("C:\\");
612 }
613
614 #endif
615
616 /* HOLDS: g_utils_global_lock */
617 static UserDatabaseEntry *
618 g_get_user_database_entry (void)
619 {
620   static UserDatabaseEntry *entry;
621
622   if (g_once_init_enter (&entry))
623     {
624       static UserDatabaseEntry e;
625
626 #ifdef G_OS_UNIX
627       {
628         struct passwd *pw = NULL;
629         gpointer buffer = NULL;
630         gint error;
631         gchar *logname;
632
633 #  if defined (HAVE_GETPWUID_R)
634         struct passwd pwd;
635 #    ifdef _SC_GETPW_R_SIZE_MAX
636         /* This reurns the maximum length */
637         glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
638
639         if (bufsize < 0)
640           bufsize = 64;
641 #    else /* _SC_GETPW_R_SIZE_MAX */
642         glong bufsize = 64;
643 #    endif /* _SC_GETPW_R_SIZE_MAX */
644
645         logname = (gchar *) g_getenv ("LOGNAME");
646
647         do
648           {
649             g_free (buffer);
650             /* we allocate 6 extra bytes to work around a bug in
651              * Mac OS < 10.3. See #156446
652              */
653             buffer = g_malloc (bufsize + 6);
654             errno = 0;
655
656             if (logname) {
657               error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
658               if (!pw || (pw->pw_uid != getuid ())) {
659                 /* LOGNAME is lying, fall back to looking up the uid */
660                 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
661               }
662             } else {
663               error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
664             }
665             error = error < 0 ? errno : error;
666
667             if (!pw)
668               {
669                 /* we bail out prematurely if the user id can't be found
670                  * (should be pretty rare case actually), or if the buffer
671                  * should be sufficiently big and lookups are still not
672                  * successful.
673                  */
674                 if (error == 0 || error == ENOENT)
675                   {
676                     g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
677                                (gulong) getuid ());
678                     break;
679                   }
680                 if (bufsize > 32 * 1024)
681                   {
682                     g_warning ("getpwuid_r(): failed due to: %s.",
683                                g_strerror (error));
684                     break;
685                   }
686
687                 bufsize *= 2;
688               }
689           }
690         while (!pw);
691 #  endif /* HAVE_GETPWUID_R */
692
693         if (!pw)
694           {
695             pw = getpwuid (getuid ());
696           }
697         if (pw)
698           {
699             e.user_name = g_strdup (pw->pw_name);
700
701 #ifndef __BIONIC__
702             if (pw->pw_gecos && *pw->pw_gecos != '\0')
703               {
704                 gchar **gecos_fields;
705                 gchar **name_parts;
706
707                 /* split the gecos field and substitute '&' */
708                 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
709                 name_parts = g_strsplit (gecos_fields[0], "&", 0);
710                 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
711                 e.real_name = g_strjoinv (pw->pw_name, name_parts);
712                 g_strfreev (gecos_fields);
713                 g_strfreev (name_parts);
714               }
715 #endif
716
717             if (!e.home_dir)
718               e.home_dir = g_strdup (pw->pw_dir);
719           }
720         g_free (buffer);
721       }
722
723 #endif /* G_OS_UNIX */
724
725 #ifdef G_OS_WIN32
726       {
727         guint len = UNLEN+1;
728         wchar_t buffer[UNLEN+1];
729
730         if (GetUserNameW (buffer, (LPDWORD) &len))
731           {
732             e.user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
733             e.real_name = g_strdup (e.user_name);
734           }
735       }
736 #endif /* G_OS_WIN32 */
737
738       if (!e.user_name)
739         e.user_name = g_strdup ("somebody");
740       if (!e.real_name)
741         e.real_name = g_strdup ("Unknown");
742
743       g_once_init_leave (&entry, &e);
744     }
745
746   return entry;
747 }
748
749 /**
750  * g_get_user_name:
751  *
752  * Gets the user name of the current user. The encoding of the returned
753  * string is system-defined. On UNIX, it might be the preferred file name
754  * encoding, or something else, and there is no guarantee that it is even
755  * consistent on a machine. On Windows, it is always UTF-8.
756  *
757  * Returns: (type filename): the user name of the current user.
758  */
759 const gchar *
760 g_get_user_name (void)
761 {
762   UserDatabaseEntry *entry;
763
764   entry = g_get_user_database_entry ();
765
766   return entry->user_name;
767 }
768
769 /**
770  * g_get_real_name:
771  *
772  * Gets the real name of the user. This usually comes from the user's
773  * entry in the `passwd` file. The encoding of the returned string is
774  * system-defined. (On Windows, it is, however, always UTF-8.) If the
775  * real user name cannot be determined, the string "Unknown" is 
776  * returned.
777  *
778  * Returns: (type filename): the user's real name.
779  */
780 const gchar *
781 g_get_real_name (void)
782 {
783   UserDatabaseEntry *entry;
784
785   entry = g_get_user_database_entry ();
786
787   return entry->real_name;
788 }
789
790 /**
791  * g_get_home_dir:
792  *
793  * Gets the current user's home directory.
794  *
795  * As with most UNIX tools, this function will return the value of the
796  * `HOME` environment variable if it is set to an existing absolute path
797  * name, falling back to the `passwd` file in the case that it is unset.
798  *
799  * If the path given in `HOME` is non-absolute, does not exist, or is
800  * not a directory, the result is undefined.
801  *
802  * Before version 2.36 this function would ignore the `HOME` environment
803  * variable, taking the value from the `passwd` database instead. This was
804  * changed to increase the compatibility of GLib with other programs (and
805  * the XDG basedir specification) and to increase testability of programs
806  * based on GLib (by making it easier to run them from test frameworks).
807  *
808  * If your program has a strong requirement for either the new or the
809  * old behaviour (and if you don't wish to increase your GLib
810  * dependency to ensure that the new behaviour is in effect) then you
811  * should either directly check the `HOME` environment variable yourself
812  * or unset it before calling any functions in GLib.
813  *
814  * Returns: (type filename): the current user's home directory
815  */
816 const gchar *
817 g_get_home_dir (void)
818 {
819   static gchar *home_dir;
820
821   if (g_once_init_enter (&home_dir))
822     {
823       gchar *tmp;
824
825       /* We first check HOME and use it if it is set */
826       tmp = g_strdup (g_getenv ("HOME"));
827
828 #ifdef G_OS_WIN32
829       /* Only believe HOME if it is an absolute path and exists.
830        *
831        * We only do this check on Windows for a couple of reasons.
832        * Historically, we only did it there because we used to ignore $HOME
833        * on UNIX.  There are concerns about enabling it now on UNIX because
834        * of things like autofs.  In short, if the user has a bogus value in
835        * $HOME then they get what they pay for...
836        */
837       if (tmp)
838         {
839           if (!(g_path_is_absolute (tmp) &&
840                 g_file_test (tmp, G_FILE_TEST_IS_DIR)))
841             {
842               g_free (tmp);
843               tmp = NULL;
844             }
845         }
846
847       /* In case HOME is Unix-style (it happens), convert it to
848        * Windows style.
849        */
850       if (tmp)
851         {
852           gchar *p;
853           while ((p = strchr (tmp, '/')) != NULL)
854             *p = '\\';
855         }
856
857       if (!tmp)
858         {
859           /* USERPROFILE is probably the closest equivalent to $HOME? */
860           if (g_getenv ("USERPROFILE") != NULL)
861             tmp = g_strdup (g_getenv ("USERPROFILE"));
862         }
863
864       if (!tmp)
865         tmp = get_special_folder (CSIDL_PROFILE);
866
867       if (!tmp)
868         tmp = get_windows_directory_root ();
869 #endif /* G_OS_WIN32 */
870
871       if (!tmp)
872         {
873           /* If we didn't get it from any of those methods, we will have
874            * to read the user database entry.
875            */
876           UserDatabaseEntry *entry;
877
878           entry = g_get_user_database_entry ();
879
880           /* Strictly speaking, we should copy this, but we know that
881            * neither will ever be freed, so don't bother...
882            */
883           tmp = entry->home_dir;
884         }
885
886       /* If we have been denied access to /etc/passwd (for example, by an
887        * overly-zealous LSM), make up a junk value. The return value at this
888        * point is explicitly documented as â€˜undefined’. Memory management is as
889        * immediately above: strictly this should be copied, but we know not
890        * copying it is OK. */
891       if (tmp == NULL)
892         {
893           g_warning ("Could not find home directory: $HOME is not set, and "
894                      "user database could not be read.");
895           tmp = "/";
896         }
897
898       g_once_init_leave (&home_dir, tmp);
899     }
900
901   return home_dir;
902 }
903
904 /**
905  * g_get_tmp_dir:
906  *
907  * Gets the directory to use for temporary files.
908  *
909  * On UNIX, this is taken from the `TMPDIR` environment variable.
910  * If the variable is not set, `P_tmpdir` is
911  * used, as defined by the system C library. Failing that, a
912  * hard-coded default of "/tmp" is returned.
913  *
914  * On Windows, the `TEMP` environment variable is used, with the
915  * root directory of the Windows installation (eg: "C:\") used
916  * as a default.
917  *
918  * The encoding of the returned string is system-defined. On Windows,
919  * it is always UTF-8. The return value is never %NULL or the empty
920  * string.
921  *
922  * Returns: (type filename): the directory to use for temporary files.
923  */
924 const gchar *
925 g_get_tmp_dir (void)
926 {
927   static gchar *tmp_dir;
928
929   if (g_once_init_enter (&tmp_dir))
930     {
931       gchar *tmp;
932
933 #ifdef G_OS_WIN32
934       tmp = g_strdup (g_getenv ("TEMP"));
935
936       if (tmp == NULL || *tmp == '\0')
937         {
938           g_free (tmp);
939           tmp = get_windows_directory_root ();
940         }
941 #else /* G_OS_WIN32 */
942       tmp = g_strdup (g_getenv ("TMPDIR"));
943
944 #ifdef P_tmpdir
945       if (tmp == NULL || *tmp == '\0')
946         {
947           gsize k;
948           g_free (tmp);
949           tmp = g_strdup (P_tmpdir);
950           k = strlen (tmp);
951           if (k > 1 && G_IS_DIR_SEPARATOR (tmp[k - 1]))
952             tmp[k - 1] = '\0';
953         }
954 #endif /* P_tmpdir */
955
956       if (tmp == NULL || *tmp == '\0')
957         {
958           g_free (tmp);
959           tmp = g_strdup ("/tmp");
960         }
961 #endif /* !G_OS_WIN32 */
962
963       g_once_init_leave (&tmp_dir, tmp);
964     }
965
966   return tmp_dir;
967 }
968
969 /**
970  * g_get_host_name:
971  *
972  * Return a name for the machine. 
973  *
974  * The returned name is not necessarily a fully-qualified domain name,
975  * or even present in DNS or some other name service at all. It need
976  * not even be unique on your local network or site, but usually it
977  * is. Callers should not rely on the return value having any specific
978  * properties like uniqueness for security purposes. Even if the name
979  * of the machine is changed while an application is running, the
980  * return value from this function does not change. The returned
981  * string is owned by GLib and should not be modified or freed. If no
982  * name can be determined, a default fixed string "localhost" is
983  * returned.
984  *
985  * The encoding of the returned string is UTF-8.
986  *
987  * Returns: the host name of the machine.
988  *
989  * Since: 2.8
990  */
991 const gchar *
992 g_get_host_name (void)
993 {
994   static gchar *hostname;
995
996   if (g_once_init_enter (&hostname))
997     {
998       gboolean failed;
999       gchar *utmp;
1000
1001 #ifndef G_OS_WIN32
1002       gchar *tmp = g_malloc (sizeof (gchar) * 100);
1003       failed = (gethostname (tmp, sizeof (gchar) * 100) == -1);
1004       if (failed)
1005         g_clear_pointer (&tmp, g_free);
1006       utmp = tmp;
1007 #else
1008       wchar_t tmp[MAX_COMPUTERNAME_LENGTH + 1];
1009       DWORD size = sizeof (tmp) / sizeof (tmp[0]);
1010       failed = (!GetComputerNameW (tmp, &size));
1011       if (!failed)
1012         utmp = g_utf16_to_utf8 (tmp, size, NULL, NULL, NULL);
1013       if (utmp == NULL)
1014         failed = TRUE;
1015 #endif
1016
1017       g_once_init_leave (&hostname, failed ? g_strdup ("localhost") : utmp);
1018     }
1019
1020   return hostname;
1021 }
1022
1023 G_LOCK_DEFINE_STATIC (g_prgname);
1024 static gchar *g_prgname = NULL;
1025
1026 /**
1027  * g_get_prgname:
1028  *
1029  * Gets the name of the program. This name should not be localized,
1030  * in contrast to g_get_application_name().
1031  *
1032  * If you are using #GApplication the program name is set in
1033  * g_application_run(). In case of GDK or GTK+ it is set in
1034  * gdk_init(), which is called by gtk_init() and the
1035  * #GtkApplication::startup handler. The program name is found by
1036  * taking the last component of @argv[0].
1037  *
1038  * Returns: the name of the program. The returned string belongs 
1039  *     to GLib and must not be modified or freed.
1040  */
1041 const gchar*
1042 g_get_prgname (void)
1043 {
1044   gchar* retval;
1045
1046   G_LOCK (g_prgname);
1047 #ifdef G_OS_WIN32
1048   if (g_prgname == NULL)
1049     {
1050       static gboolean beenhere = FALSE;
1051
1052       if (!beenhere)
1053         {
1054           gchar *utf8_buf = NULL;
1055           wchar_t buf[MAX_PATH+1];
1056
1057           beenhere = TRUE;
1058           if (GetModuleFileNameW (GetModuleHandle (NULL),
1059                                   buf, G_N_ELEMENTS (buf)) > 0)
1060             utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1061
1062           if (utf8_buf)
1063             {
1064               g_prgname = g_path_get_basename (utf8_buf);
1065               g_free (utf8_buf);
1066             }
1067         }
1068     }
1069 #endif
1070   retval = g_prgname;
1071   G_UNLOCK (g_prgname);
1072
1073   return retval;
1074 }
1075
1076 /**
1077  * g_set_prgname:
1078  * @prgname: the name of the program.
1079  *
1080  * Sets the name of the program. This name should not be localized,
1081  * in contrast to g_set_application_name().
1082  *
1083  * If you are using #GApplication the program name is set in
1084  * g_application_run(). In case of GDK or GTK+ it is set in
1085  * gdk_init(), which is called by gtk_init() and the
1086  * #GtkApplication::startup handler. The program name is found by
1087  * taking the last component of @argv[0].
1088  *
1089  * Note that for thread-safety reasons this function can only be called once.
1090  */
1091 void
1092 g_set_prgname (const gchar *prgname)
1093 {
1094   G_LOCK (g_prgname);
1095   g_free (g_prgname);
1096   g_prgname = g_strdup (prgname);
1097   G_UNLOCK (g_prgname);
1098 }
1099
1100 G_LOCK_DEFINE_STATIC (g_application_name);
1101 static gchar *g_application_name = NULL;
1102
1103 /**
1104  * g_get_application_name:
1105  * 
1106  * Gets a human-readable name for the application, as set by
1107  * g_set_application_name(). This name should be localized if
1108  * possible, and is intended for display to the user.  Contrast with
1109  * g_get_prgname(), which gets a non-localized name. If
1110  * g_set_application_name() has not been called, returns the result of
1111  * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1112  * been called).
1113  * 
1114  * Returns: human-readable application name. may return %NULL
1115  *
1116  * Since: 2.2
1117  **/
1118 const gchar *
1119 g_get_application_name (void)
1120 {
1121   gchar* retval;
1122
1123   G_LOCK (g_application_name);
1124   retval = g_application_name;
1125   G_UNLOCK (g_application_name);
1126
1127   if (retval == NULL)
1128     return g_get_prgname ();
1129   
1130   return retval;
1131 }
1132
1133 /**
1134  * g_set_application_name:
1135  * @application_name: localized name of the application
1136  *
1137  * Sets a human-readable name for the application. This name should be
1138  * localized if possible, and is intended for display to the user.
1139  * Contrast with g_set_prgname(), which sets a non-localized name.
1140  * g_set_prgname() will be called automatically by gtk_init(),
1141  * but g_set_application_name() will not.
1142  *
1143  * Note that for thread safety reasons, this function can only
1144  * be called once.
1145  *
1146  * The application name will be used in contexts such as error messages,
1147  * or when displaying an application's name in the task list.
1148  * 
1149  * Since: 2.2
1150  **/
1151 void
1152 g_set_application_name (const gchar *application_name)
1153 {
1154   gboolean already_set = FALSE;
1155         
1156   G_LOCK (g_application_name);
1157   if (g_application_name)
1158     already_set = TRUE;
1159   else
1160     g_application_name = g_strdup (application_name);
1161   G_UNLOCK (g_application_name);
1162
1163   if (already_set)
1164     g_warning ("g_set_application_name() called multiple times");
1165 }
1166
1167 /**
1168  * g_get_user_data_dir:
1169  * 
1170  * Returns a base directory in which to access application data such
1171  * as icons that is customized for a particular user.  
1172  *
1173  * On UNIX platforms this is determined using the mechanisms described
1174  * in the
1175  * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1176  * In this case the directory retrieved will be `XDG_DATA_HOME`.
1177  *
1178  * On Windows it follows XDG Base Directory Specification if `XDG_DATA_HOME`
1179  * is defined. If `XDG_DATA_HOME` is undefined, the folder to use for local (as
1180  * opposed to roaming) application data is used instead. See the
1181  * [documentation for `CSIDL_LOCAL_APPDATA`](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx#csidl_local_appdata).
1182  * Note that in this case on Windows it will be the same
1183  * as what g_get_user_config_dir() returns.
1184  *
1185  * Returns: (type filename): a string owned by GLib that must not be modified
1186  *               or freed.
1187  * Since: 2.6
1188  **/
1189 const gchar *
1190 g_get_user_data_dir (void)
1191 {
1192   gchar *data_dir = NULL;
1193
1194   G_LOCK (g_utils_global);
1195
1196   if (!g_user_data_dir)
1197     {
1198       const gchar *data_dir_env = g_getenv ("XDG_DATA_HOME");
1199
1200       if (data_dir_env && data_dir_env[0])
1201         data_dir = g_strdup (data_dir_env);
1202 #ifdef G_OS_WIN32
1203       else
1204         data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1205 #endif
1206       if (!data_dir || !data_dir[0])
1207         {
1208           const gchar *home_dir = g_get_home_dir ();
1209
1210           if (home_dir)
1211             data_dir = g_build_filename (home_dir, ".local", "share", NULL);
1212           else
1213             data_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".local", "share", NULL);
1214         }
1215
1216       g_user_data_dir = data_dir;
1217     }
1218   else
1219     data_dir = g_user_data_dir;
1220
1221   G_UNLOCK (g_utils_global);
1222
1223   return data_dir;
1224 }
1225
1226 static void
1227 g_init_user_config_dir (void)
1228 {
1229   gchar *config_dir = NULL;
1230
1231   if (!g_user_config_dir)
1232     {
1233       const gchar *config_dir_env = g_getenv ("XDG_CONFIG_HOME");
1234
1235       if (config_dir_env && config_dir_env[0])
1236         config_dir = g_strdup (config_dir_env);
1237 #ifdef G_OS_WIN32
1238       else
1239         config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1240 #endif
1241       if (!config_dir || !config_dir[0])
1242         {
1243           const gchar *home_dir = g_get_home_dir ();
1244
1245           if (home_dir)
1246             config_dir = g_build_filename (home_dir, ".config", NULL);
1247           else
1248             config_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".config", NULL);
1249         }
1250
1251       g_user_config_dir = config_dir;
1252     }
1253 }
1254
1255 /**
1256  * g_get_user_config_dir:
1257  * 
1258  * Returns a base directory in which to store user-specific application 
1259  * configuration information such as user preferences and settings. 
1260  *
1261  * On UNIX platforms this is determined using the mechanisms described
1262  * in the
1263  * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1264  * In this case the directory retrieved will be `XDG_CONFIG_HOME`.
1265  *
1266  * On Windows it follows XDG Base Directory Specification if `XDG_CONFIG_HOME` is defined.
1267  * If `XDG_CONFIG_HOME` is undefined, the folder to use for local (as opposed
1268  * to roaming) application data is used instead. See the
1269  * [documentation for `CSIDL_LOCAL_APPDATA`](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx#csidl_local_appdata).
1270  * Note that in this case on Windows it will be  the same
1271  * as what g_get_user_data_dir() returns.
1272  *
1273  * Returns: (type filename): a string owned by GLib that must not be modified
1274  *               or freed.
1275  * Since: 2.6
1276  **/
1277 const gchar *
1278 g_get_user_config_dir (void)
1279 {
1280   G_LOCK (g_utils_global);
1281
1282   g_init_user_config_dir ();
1283
1284   G_UNLOCK (g_utils_global);
1285
1286   return g_user_config_dir;
1287 }
1288
1289 /**
1290  * g_get_user_cache_dir:
1291  * 
1292  * Returns a base directory in which to store non-essential, cached
1293  * data specific to particular user.
1294  *
1295  * On UNIX platforms this is determined using the mechanisms described
1296  * in the
1297  * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1298  * In this case the directory retrieved will be `XDG_CACHE_HOME`.
1299  *
1300  * On Windows it follows XDG Base Directory Specification if `XDG_CACHE_HOME` is defined.
1301  * If `XDG_CACHE_HOME` is undefined, the directory that serves as a common
1302  * repository for temporary Internet files is used instead. A typical path is
1303  * `C:\Documents and Settings\username\Local Settings\Temporary Internet Files`.
1304  * See the [documentation for `CSIDL_INTERNET_CACHE`](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx#csidl_internet_cache).
1305  *
1306  * Returns: (type filename): a string owned by GLib that must not be modified
1307  *               or freed.
1308  * Since: 2.6
1309  **/
1310 const gchar *
1311 g_get_user_cache_dir (void)
1312 {
1313   gchar *cache_dir = NULL;
1314
1315   G_LOCK (g_utils_global);
1316
1317   if (!g_user_cache_dir)
1318     {
1319       const gchar *cache_dir_env = g_getenv ("XDG_CACHE_HOME");
1320
1321       if (cache_dir_env && cache_dir_env[0])
1322         cache_dir = g_strdup (cache_dir_env);
1323 #ifdef G_OS_WIN32
1324       else
1325         cache_dir = get_special_folder (CSIDL_INTERNET_CACHE);
1326 #endif
1327       if (!cache_dir || !cache_dir[0])
1328         {
1329           const gchar *home_dir = g_get_home_dir ();
1330
1331           if (home_dir)
1332             cache_dir = g_build_filename (home_dir, ".cache", NULL);
1333           else
1334             cache_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".cache", NULL);
1335         }
1336       g_user_cache_dir = cache_dir;
1337     }
1338   else
1339     cache_dir = g_user_cache_dir;
1340
1341   G_UNLOCK (g_utils_global);
1342
1343   return cache_dir;
1344 }
1345
1346 /**
1347  * g_get_user_runtime_dir:
1348  *
1349  * Returns a directory that is unique to the current user on the local
1350  * system.
1351  *
1352  * This is determined using the mechanisms described
1353  * in the 
1354  * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1355  * This is the directory
1356  * specified in the `XDG_RUNTIME_DIR` environment variable.
1357  * In the case that this variable is not set, we return the value of
1358  * g_get_user_cache_dir(), after verifying that it exists.
1359  *
1360  * Returns: (type filename): a string owned by GLib that must not be
1361  *     modified or freed.
1362  *
1363  * Since: 2.28
1364  **/
1365 const gchar *
1366 g_get_user_runtime_dir (void)
1367 {
1368   static const gchar *runtime_dir;
1369
1370   if (g_once_init_enter (&runtime_dir))
1371     {
1372       const gchar *dir;
1373
1374       dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
1375
1376       if (dir == NULL)
1377         {
1378           /* No need to strdup this one since it is valid forever. */
1379           dir = g_get_user_cache_dir ();
1380
1381           /* The user should be able to rely on the directory existing
1382            * when the function returns.  Probably it already does, but
1383            * let's make sure.  Just do mkdir() directly since it will be
1384            * no more expensive than a stat() in the case that the
1385            * directory already exists and is a lot easier.
1386            *
1387            * $XDG_CACHE_HOME is probably ~/.cache/ so as long as $HOME
1388            * exists this will work.  If the user changed $XDG_CACHE_HOME
1389            * then they can make sure that it exists...
1390            */
1391           (void) g_mkdir (dir, 0700);
1392         }
1393
1394       g_assert (dir != NULL);
1395
1396       g_once_init_leave (&runtime_dir, dir);
1397     }
1398
1399   return runtime_dir;
1400 }
1401
1402 #ifdef HAVE_CARBON
1403
1404 static gchar *
1405 find_folder (OSType type)
1406 {
1407   gchar *filename = NULL;
1408   FSRef  found;
1409
1410   if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
1411     {
1412       CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
1413
1414       if (url)
1415         {
1416           CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
1417
1418           if (path)
1419             {
1420               filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
1421
1422               if (! filename)
1423                 {
1424                   filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
1425
1426                   CFStringGetCString (path, filename,
1427                                       CFStringGetLength (path) * 3 + 1,
1428                                       kCFStringEncodingUTF8);
1429                 }
1430
1431               CFRelease (path);
1432             }
1433
1434           CFRelease (url);
1435         }
1436     }
1437
1438   return filename;
1439 }
1440
1441 static void
1442 load_user_special_dirs (void)
1443 {
1444   g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
1445   g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
1446   g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
1447   g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
1448   g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
1449   g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
1450   g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
1451   g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
1452 }
1453
1454 #elif defined(G_OS_WIN32)
1455
1456 static void
1457 load_user_special_dirs (void)
1458 {
1459   typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1460                                                     DWORD dwFlags,
1461                                                     HANDLE hToken,
1462                                                     PWSTR *ppszPath);
1463   t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
1464
1465   static const GUID FOLDERID_Downloads =
1466     { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1467   static const GUID FOLDERID_Public =
1468     { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1469
1470   wchar_t *wcp;
1471
1472   p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
1473                                                                     "SHGetKnownFolderPath");
1474
1475   g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1476   g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
1477
1478   if (p_SHGetKnownFolderPath == NULL)
1479     {
1480       g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1481     }
1482   else
1483     {
1484       wcp = NULL;
1485       (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1486       if (wcp)
1487         {
1488           g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1489           if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
1490               g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1491           CoTaskMemFree (wcp);
1492         }
1493       else
1494           g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1495     }
1496
1497   g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
1498   g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
1499
1500   if (p_SHGetKnownFolderPath == NULL)
1501     {
1502       /* XXX */
1503       g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1504     }
1505   else
1506     {
1507       wcp = NULL;
1508       (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
1509       if (wcp)
1510         {
1511           g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1512           if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
1513               g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1514           CoTaskMemFree (wcp);
1515         }
1516       else
1517           g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1518     }
1519   
1520   g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
1521   g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
1522 }
1523
1524 #else /* default is unix */
1525
1526 /* adapted from xdg-user-dir-lookup.c
1527  *
1528  * Copyright (C) 2007 Red Hat Inc.
1529  *
1530  * Permission is hereby granted, free of charge, to any person
1531  * obtaining a copy of this software and associated documentation files
1532  * (the "Software"), to deal in the Software without restriction,
1533  * including without limitation the rights to use, copy, modify, merge,
1534  * publish, distribute, sublicense, and/or sell copies of the Software,
1535  * and to permit persons to whom the Software is furnished to do so,
1536  * subject to the following conditions: 
1537  *
1538  * The above copyright notice and this permission notice shall be
1539  * included in all copies or substantial portions of the Software. 
1540  *
1541  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1542  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1543  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1544  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1545  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1546  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1547  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1548  * SOFTWARE.
1549  */
1550 static void
1551 load_user_special_dirs (void)
1552 {
1553   gchar *config_file;
1554   gchar *data;
1555   gchar **lines;
1556   gint n_lines, i;
1557   
1558   g_init_user_config_dir ();
1559   config_file = g_build_filename (g_user_config_dir,
1560                                   "user-dirs.dirs",
1561                                   NULL);
1562   
1563   if (!g_file_get_contents (config_file, &data, NULL, NULL))
1564     {
1565       g_free (config_file);
1566       return;
1567     }
1568
1569   lines = g_strsplit (data, "\n", -1);
1570   n_lines = g_strv_length (lines);
1571   g_free (data);
1572   
1573   for (i = 0; i < n_lines; i++)
1574     {
1575       gchar *buffer = lines[i];
1576       gchar *d, *p;
1577       gint len;
1578       gboolean is_relative = FALSE;
1579       GUserDirectory directory;
1580
1581       /* Remove newline at end */
1582       len = strlen (buffer);
1583       if (len > 0 && buffer[len - 1] == '\n')
1584         buffer[len - 1] = 0;
1585       
1586       p = buffer;
1587       while (*p == ' ' || *p == '\t')
1588         p++;
1589       
1590       if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
1591         {
1592           directory = G_USER_DIRECTORY_DESKTOP;
1593           p += strlen ("XDG_DESKTOP_DIR");
1594         }
1595       else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
1596         {
1597           directory = G_USER_DIRECTORY_DOCUMENTS;
1598           p += strlen ("XDG_DOCUMENTS_DIR");
1599         }
1600       else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
1601         {
1602           directory = G_USER_DIRECTORY_DOWNLOAD;
1603           p += strlen ("XDG_DOWNLOAD_DIR");
1604         }
1605       else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
1606         {
1607           directory = G_USER_DIRECTORY_MUSIC;
1608           p += strlen ("XDG_MUSIC_DIR");
1609         }
1610       else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
1611         {
1612           directory = G_USER_DIRECTORY_PICTURES;
1613           p += strlen ("XDG_PICTURES_DIR");
1614         }
1615       else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
1616         {
1617           directory = G_USER_DIRECTORY_PUBLIC_SHARE;
1618           p += strlen ("XDG_PUBLICSHARE_DIR");
1619         }
1620       else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
1621         {
1622           directory = G_USER_DIRECTORY_TEMPLATES;
1623           p += strlen ("XDG_TEMPLATES_DIR");
1624         }
1625       else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
1626         {
1627           directory = G_USER_DIRECTORY_VIDEOS;
1628           p += strlen ("XDG_VIDEOS_DIR");
1629         }
1630       else
1631         continue;
1632
1633       while (*p == ' ' || *p == '\t')
1634         p++;
1635
1636       if (*p != '=')
1637         continue;
1638       p++;
1639
1640       while (*p == ' ' || *p == '\t')
1641         p++;
1642
1643       if (*p != '"')
1644         continue;
1645       p++;
1646
1647       if (strncmp (p, "$HOME", 5) == 0)
1648         {
1649           p += 5;
1650           is_relative = TRUE;
1651         }
1652       else if (*p != '/')
1653         continue;
1654
1655       d = strrchr (p, '"');
1656       if (!d)
1657         continue;
1658       *d = 0;
1659
1660       d = p;
1661       
1662       /* remove trailing slashes */
1663       len = strlen (d);
1664       if (d[len - 1] == '/')
1665         d[len - 1] = 0;
1666       
1667       if (is_relative)
1668         {
1669           g_user_special_dirs[directory] = g_build_filename (g_get_home_dir (), d, NULL);
1670         }
1671       else
1672         g_user_special_dirs[directory] = g_strdup (d);
1673     }
1674
1675   g_strfreev (lines);
1676   g_free (config_file);
1677 }
1678
1679 #endif /* platform-specific load_user_special_dirs implementations */
1680
1681
1682 /**
1683  * g_reload_user_special_dirs_cache:
1684  *
1685  * Resets the cache used for g_get_user_special_dir(), so
1686  * that the latest on-disk version is used. Call this only
1687  * if you just changed the data on disk yourself.
1688  *
1689  * Due to threadsafety issues this may cause leaking of strings
1690  * that were previously returned from g_get_user_special_dir()
1691  * that can't be freed. We ensure to only leak the data for
1692  * the directories that actually changed value though.
1693  *
1694  * Since: 2.22
1695  */
1696 void
1697 g_reload_user_special_dirs_cache (void)
1698 {
1699   int i;
1700
1701   G_LOCK (g_utils_global);
1702
1703   if (g_user_special_dirs != NULL)
1704     {
1705       /* save a copy of the pointer, to check if some memory can be preserved */
1706       char **old_g_user_special_dirs = g_user_special_dirs;
1707       char *old_val;
1708
1709       /* recreate and reload our cache */
1710       g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1711       load_user_special_dirs ();
1712
1713       /* only leak changed directories */
1714       for (i = 0; i < G_USER_N_DIRECTORIES; i++)
1715         {
1716           old_val = old_g_user_special_dirs[i];
1717           if (g_user_special_dirs[i] == NULL)
1718             {
1719               g_user_special_dirs[i] = old_val;
1720             }
1721           else if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
1722             {
1723               /* don't leak */
1724               g_free (g_user_special_dirs[i]);
1725               g_user_special_dirs[i] = old_val;
1726             }
1727           else
1728             g_free (old_val);
1729         }
1730
1731       /* free the old array */
1732       g_free (old_g_user_special_dirs);
1733     }
1734
1735   G_UNLOCK (g_utils_global);
1736 }
1737
1738 /**
1739  * g_get_user_special_dir:
1740  * @directory: the logical id of special directory
1741  *
1742  * Returns the full path of a special directory using its logical id.
1743  *
1744  * On UNIX this is done using the XDG special user directories.
1745  * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
1746  * falls back to `$HOME/Desktop` when XDG special user directories have
1747  * not been set up. 
1748  *
1749  * Depending on the platform, the user might be able to change the path
1750  * of the special directory without requiring the session to restart; GLib
1751  * will not reflect any change once the special directories are loaded.
1752  *
1753  * Returns: (type filename): the path to the specified special directory, or
1754  *   %NULL if the logical id was not found. The returned string is owned by
1755  *   GLib and should not be modified or freed.
1756  *
1757  * Since: 2.14
1758  */
1759 const gchar *
1760 g_get_user_special_dir (GUserDirectory directory)
1761 {
1762   g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
1763                         directory < G_USER_N_DIRECTORIES, NULL);
1764
1765   G_LOCK (g_utils_global);
1766
1767   if (G_UNLIKELY (g_user_special_dirs == NULL))
1768     {
1769       g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1770
1771       load_user_special_dirs ();
1772
1773       /* Special-case desktop for historical compatibility */
1774       if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
1775         g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = g_build_filename (g_get_home_dir (), "Desktop", NULL);
1776     }
1777
1778   G_UNLOCK (g_utils_global);
1779
1780   return g_user_special_dirs[directory];
1781 }
1782
1783 #ifdef G_OS_WIN32
1784
1785 #undef g_get_system_data_dirs
1786
1787 static HMODULE
1788 get_module_for_address (gconstpointer address)
1789 {
1790   /* Holds the g_utils_global lock */
1791
1792   static gboolean beenhere = FALSE;
1793   typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
1794   static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
1795   HMODULE hmodule = NULL;
1796
1797   if (!address)
1798     return NULL;
1799
1800   if (!beenhere)
1801     {
1802       p_GetModuleHandleExA =
1803         (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1804                                                "GetModuleHandleExA");
1805       beenhere = TRUE;
1806     }
1807
1808   if (p_GetModuleHandleExA == NULL ||
1809       !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
1810                                 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
1811                                 address, &hmodule))
1812     {
1813       MEMORY_BASIC_INFORMATION mbi;
1814       VirtualQuery (address, &mbi, sizeof (mbi));
1815       hmodule = (HMODULE) mbi.AllocationBase;
1816     }
1817
1818   return hmodule;
1819 }
1820
1821 static gchar *
1822 get_module_share_dir (gconstpointer address)
1823 {
1824   HMODULE hmodule;
1825   gchar *filename;
1826   gchar *retval;
1827
1828   hmodule = get_module_for_address (address);
1829   if (hmodule == NULL)
1830     return NULL;
1831
1832   filename = g_win32_get_package_installation_directory_of_module (hmodule);
1833   retval = g_build_filename (filename, "share", NULL);
1834   g_free (filename);
1835
1836   return retval;
1837 }
1838
1839 static const gchar * const *
1840 g_win32_get_system_data_dirs_for_module_real (void (*address_of_function)(void))
1841 {
1842   GArray *data_dirs;
1843   HMODULE hmodule;
1844   static GHashTable *per_module_data_dirs = NULL;
1845   gchar **retval;
1846   gchar *p;
1847   gchar *exe_root;
1848
1849   hmodule = NULL;
1850   if (address_of_function)
1851     {
1852       G_LOCK (g_utils_global);
1853       hmodule = get_module_for_address (address_of_function);
1854       if (hmodule != NULL)
1855         {
1856           if (per_module_data_dirs == NULL)
1857             per_module_data_dirs = g_hash_table_new (NULL, NULL);
1858           else
1859             {
1860               retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
1861               
1862               if (retval != NULL)
1863                 {
1864                   G_UNLOCK (g_utils_global);
1865                   return (const gchar * const *) retval;
1866                 }
1867             }
1868         }
1869     }
1870
1871   data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
1872
1873   /* Documents and Settings\All Users\Application Data */
1874   p = get_special_folder (CSIDL_COMMON_APPDATA);
1875   if (p)
1876     g_array_append_val (data_dirs, p);
1877   
1878   /* Documents and Settings\All Users\Documents */
1879   p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1880   if (p)
1881     g_array_append_val (data_dirs, p);
1882         
1883   /* Using the above subfolders of Documents and Settings perhaps
1884    * makes sense from a Windows perspective.
1885    *
1886    * But looking at the actual use cases of this function in GTK+
1887    * and GNOME software, what we really want is the "share"
1888    * subdirectory of the installation directory for the package
1889    * our caller is a part of.
1890    *
1891    * The address_of_function parameter, if non-NULL, points to a
1892    * function in the calling module. Use that to determine that
1893    * module's installation folder, and use its "share" subfolder.
1894    *
1895    * Additionally, also use the "share" subfolder of the installation
1896    * locations of GLib and the .exe file being run.
1897    *
1898    * To guard against none of the above being what is really wanted,
1899    * callers of this function should have Win32-specific code to look
1900    * up their installation folder themselves, and handle a subfolder
1901    * "share" of it in the same way as the folders returned from this
1902    * function.
1903    */
1904
1905   p = get_module_share_dir (address_of_function);
1906   if (p)
1907     g_array_append_val (data_dirs, p);
1908     
1909   if (glib_dll != NULL)
1910     {
1911       gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
1912       p = g_build_filename (glib_root, "share", NULL);
1913       if (p)
1914         g_array_append_val (data_dirs, p);
1915       g_free (glib_root);
1916     }
1917   
1918   exe_root = g_win32_get_package_installation_directory_of_module (NULL);
1919   p = g_build_filename (exe_root, "share", NULL);
1920   if (p)
1921     g_array_append_val (data_dirs, p);
1922   g_free (exe_root);
1923
1924   retval = (gchar **) g_array_free (data_dirs, FALSE);
1925
1926   if (address_of_function)
1927     {
1928       if (hmodule != NULL)
1929         g_hash_table_insert (per_module_data_dirs, hmodule, retval);
1930       G_UNLOCK (g_utils_global);
1931     }
1932
1933   return (const gchar * const *) retval;
1934 }
1935
1936 const gchar * const *
1937 g_win32_get_system_data_dirs_for_module (void (*address_of_function)(void))
1938 {
1939   gboolean should_call_g_get_system_data_dirs;
1940
1941   should_call_g_get_system_data_dirs = TRUE;
1942   /* These checks are the same as the ones that g_get_system_data_dirs() does.
1943    * Please keep them in sync.
1944    */
1945   G_LOCK (g_utils_global);
1946
1947   if (!g_system_data_dirs)
1948     {
1949       const gchar *data_dirs = g_getenv ("XDG_DATA_DIRS");
1950
1951       if (!data_dirs || !data_dirs[0])
1952         should_call_g_get_system_data_dirs = FALSE;
1953     }
1954
1955   G_UNLOCK (g_utils_global);
1956
1957   /* There is a subtle difference between g_win32_get_system_data_dirs_for_module (NULL),
1958    * which is what GLib code can normally call,
1959    * and g_win32_get_system_data_dirs_for_module (&_g_win32_get_system_data_dirs),
1960    * which is what the inline function used by non-GLib code calls.
1961    * The former gets prefix relative to currently-running executable,
1962    * the latter - relative to the module that calls _g_win32_get_system_data_dirs()
1963    * (disguised as g_get_system_data_dirs()), which could be an executable or
1964    * a DLL that is located somewhere else.
1965    * This is why that inline function in gutils.h exists, and why we can't just
1966    * call g_get_system_data_dirs() from there - because we need to get the address
1967    * local to the non-GLib caller-module.
1968    */
1969
1970   /*
1971    * g_get_system_data_dirs() will fall back to calling
1972    * g_win32_get_system_data_dirs_for_module_real(NULL) if XDG_DATA_DIRS is NULL
1973    * or an empty string. The checks above ensure that we do not call it in such
1974    * cases and use the address_of_function that we've been given by the inline function.
1975    * The reason we're calling g_get_system_data_dirs /at all/ is to give
1976    * XDG_DATA_DIRS precedence (if it is set).
1977    */
1978   if (should_call_g_get_system_data_dirs)
1979     return g_get_system_data_dirs ();
1980
1981   return g_win32_get_system_data_dirs_for_module_real (address_of_function);
1982 }
1983
1984 #endif
1985
1986 /**
1987  * g_get_system_data_dirs:
1988  * 
1989  * Returns an ordered list of base directories in which to access 
1990  * system-wide application data.
1991  *
1992  * On UNIX platforms this is determined using the mechanisms described
1993  * in the
1994  * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec)
1995  * In this case the list of directories retrieved will be `XDG_DATA_DIRS`.
1996  *
1997  * On Windows it follows XDG Base Directory Specification if `XDG_DATA_DIRS` is defined.
1998  * If `XDG_DATA_DIRS` is undefined,
1999  * the first elements in the list are the Application Data
2000  * and Documents folders for All Users. (These can be determined only
2001  * on Windows 2000 or later and are not present in the list on other
2002  * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2003  * CSIDL_COMMON_DOCUMENTS.
2004  *
2005  * Then follows the "share" subfolder in the installation folder for
2006  * the package containing the DLL that calls this function, if it can
2007  * be determined.
2008  * 
2009  * Finally the list contains the "share" subfolder in the installation
2010  * folder for GLib, and in the installation folder for the package the
2011  * application's .exe file belongs to.
2012  *
2013  * The installation folders above are determined by looking up the
2014  * folder where the module (DLL or EXE) in question is located. If the
2015  * folder's name is "bin", its parent is used, otherwise the folder
2016  * itself.
2017  *
2018  * Note that on Windows the returned list can vary depending on where
2019  * this function is called.
2020  *
2021  * Returns: (array zero-terminated=1) (element-type filename) (transfer none):
2022  *     a %NULL-terminated array of strings owned by GLib that must not be
2023  *     modified or freed.
2024  * 
2025  * Since: 2.6
2026  **/
2027 const gchar * const * 
2028 g_get_system_data_dirs (void)
2029 {
2030   gchar **data_dir_vector;
2031
2032   /* These checks are the same as the ones that g_win32_get_system_data_dirs_for_module()
2033    * does. Please keep them in sync.
2034    */
2035   G_LOCK (g_utils_global);
2036
2037   if (!g_system_data_dirs)
2038     {
2039       gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2040
2041 #ifndef G_OS_WIN32
2042       if (!data_dirs || !data_dirs[0])
2043           data_dirs = "/usr/local/share/:/usr/share/";
2044
2045       data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2046 #else
2047       if (!data_dirs || !data_dirs[0])
2048         data_dir_vector = g_strdupv ((gchar **) g_win32_get_system_data_dirs_for_module_real (NULL));
2049       else
2050         data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2051 #endif
2052
2053       g_system_data_dirs = data_dir_vector;
2054     }
2055   else
2056     data_dir_vector = g_system_data_dirs;
2057
2058   G_UNLOCK (g_utils_global);
2059
2060   return (const gchar * const *) data_dir_vector;
2061 }
2062
2063 /**
2064  * g_get_system_config_dirs:
2065  * 
2066  * Returns an ordered list of base directories in which to access 
2067  * system-wide configuration information.
2068  *
2069  * On UNIX platforms this is determined using the mechanisms described
2070  * in the
2071  * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2072  * In this case the list of directories retrieved will be `XDG_CONFIG_DIRS`.
2073  *
2074  * On Windows it follows XDG Base Directory Specification if `XDG_CONFIG_DIRS` is defined.
2075  * If `XDG_CONFIG_DIRS` is undefined, the directory that contains application
2076  * data for all users is used instead. A typical path is
2077  * `C:\Documents and Settings\All Users\Application Data`.
2078  * This folder is used for application data
2079  * that is not user specific. For example, an application can store
2080  * a spell-check dictionary, a database of clip art, or a log file in the
2081  * CSIDL_COMMON_APPDATA folder. This information will not roam and is available
2082  * to anyone using the computer.
2083  *
2084  * Returns: (array zero-terminated=1) (element-type filename) (transfer none):
2085  *     a %NULL-terminated array of strings owned by GLib that must not be
2086  *     modified or freed.
2087  * 
2088  * Since: 2.6
2089  **/
2090 const gchar * const *
2091 g_get_system_config_dirs (void)
2092 {
2093   gchar **conf_dir_vector;
2094
2095   G_LOCK (g_utils_global);
2096
2097   if (!g_system_config_dirs)
2098     {
2099       const gchar *conf_dirs = g_getenv ("XDG_CONFIG_DIRS");
2100 #ifdef G_OS_WIN32
2101       if (conf_dirs)
2102         {
2103           conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2104         }
2105       else
2106         {
2107           gchar *special_conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2108
2109           if (special_conf_dirs)
2110             conf_dir_vector = g_strsplit (special_conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2111           else
2112             /* Return empty list */
2113             conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2114
2115           g_free (special_conf_dirs);
2116         }
2117 #else
2118       if (!conf_dirs || !conf_dirs[0])
2119           conf_dirs = "/etc/xdg";
2120
2121       conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2122 #endif
2123
2124       g_system_config_dirs = conf_dir_vector;
2125     }
2126   else
2127     conf_dir_vector = g_system_config_dirs;
2128   G_UNLOCK (g_utils_global);
2129
2130   return (const gchar * const *) conf_dir_vector;
2131 }
2132
2133 /**
2134  * g_nullify_pointer:
2135  * @nullify_location: (not nullable): the memory address of the pointer.
2136  *
2137  * Set the pointer at the specified location to %NULL.
2138  **/
2139 void
2140 g_nullify_pointer (gpointer *nullify_location)
2141 {
2142   g_return_if_fail (nullify_location != NULL);
2143
2144   *nullify_location = NULL;
2145 }
2146
2147 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2148 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2149 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2150 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2151 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2152 #define EXABYTE_FACTOR  (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2153
2154 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2155 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2156 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2157 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2158 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2159 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2160
2161 /**
2162  * g_format_size:
2163  * @size: a size in bytes
2164  *
2165  * Formats a size (for example the size of a file) into a human readable
2166  * string.  Sizes are rounded to the nearest size prefix (kB, MB, GB)
2167  * and are displayed rounded to the nearest tenth. E.g. the file size
2168  * 3292528 bytes will be converted into the string "3.2 MB".
2169  *
2170  * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2171  *
2172  * This string should be freed with g_free() when not needed any longer.
2173  *
2174  * See g_format_size_full() for more options about how the size might be
2175  * formatted.
2176  *
2177  * Returns: a newly-allocated formatted string containing a human readable
2178  *     file size
2179  *
2180  * Since: 2.30
2181  */
2182 gchar *
2183 g_format_size (guint64 size)
2184 {
2185   return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2186 }
2187
2188 /**
2189  * GFormatSizeFlags:
2190  * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2191  * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2192  *     of the returned string.  For example, "45.6 kB (45,612 bytes)".
2193  * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2194  *     suffixes. IEC units should only be used for reporting things with
2195  *     a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2196  *     Network and storage sizes should be reported in the normal SI units.
2197  * @G_FORMAT_SIZE_BITS: set the size as a quantity in bits, rather than
2198  *     bytes, and return units in bits. For example, â€˜Mb’ rather than â€˜MB’.
2199  *
2200  * Flags to modify the format of the string returned by g_format_size_full().
2201  */
2202
2203 #pragma GCC diagnostic push
2204 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
2205
2206 /**
2207  * g_format_size_full:
2208  * @size: a size in bytes
2209  * @flags: #GFormatSizeFlags to modify the output
2210  *
2211  * Formats a size.
2212  *
2213  * This function is similar to g_format_size() but allows for flags
2214  * that modify the output. See #GFormatSizeFlags.
2215  *
2216  * Returns: a newly-allocated formatted string containing a human
2217  *     readable file size
2218  *
2219  * Since: 2.30
2220  */
2221 gchar *
2222 g_format_size_full (guint64          size,
2223                     GFormatSizeFlags flags)
2224 {
2225   struct Format
2226   {
2227     guint64 factor;
2228     char string[9];
2229   };
2230
2231   typedef enum
2232   {
2233     FORMAT_BYTES,
2234     FORMAT_BYTES_IEC,
2235     FORMAT_BITS,
2236     FORMAT_BITS_IEC
2237   } FormatIndex;
2238
2239   const struct Format formats[4][6] = {
2240     {
2241       { KILOBYTE_FACTOR, N_("%.1f kB") },
2242       { MEGABYTE_FACTOR, N_("%.1f MB") },
2243       { GIGABYTE_FACTOR, N_("%.1f GB") },
2244       { TERABYTE_FACTOR, N_("%.1f TB") },
2245       { PETABYTE_FACTOR, N_("%.1f PB") },
2246       { EXABYTE_FACTOR,  N_("%.1f EB") }
2247     },
2248     {
2249       { KIBIBYTE_FACTOR, N_("%.1f KiB") },
2250       { MEBIBYTE_FACTOR, N_("%.1f MiB") },
2251       { GIBIBYTE_FACTOR, N_("%.1f GiB") },
2252       { TEBIBYTE_FACTOR, N_("%.1f TiB") },
2253       { PEBIBYTE_FACTOR, N_("%.1f PiB") },
2254       { EXBIBYTE_FACTOR, N_("%.1f EiB") }
2255     },
2256     {
2257       { KILOBYTE_FACTOR, N_("%.1f kb") },
2258       { MEGABYTE_FACTOR, N_("%.1f Mb") },
2259       { GIGABYTE_FACTOR, N_("%.1f Gb") },
2260       { TERABYTE_FACTOR, N_("%.1f Tb") },
2261       { PETABYTE_FACTOR, N_("%.1f Pb") },
2262       { EXABYTE_FACTOR,  N_("%.1f Eb") }
2263     },
2264     {
2265       { KIBIBYTE_FACTOR, N_("%.1f Kib") },
2266       { MEBIBYTE_FACTOR, N_("%.1f Mib") },
2267       { GIBIBYTE_FACTOR, N_("%.1f Gib") },
2268       { TEBIBYTE_FACTOR, N_("%.1f Tib") },
2269       { PEBIBYTE_FACTOR, N_("%.1f Pib") },
2270       { EXBIBYTE_FACTOR, N_("%.1f Eib") }
2271     }
2272   };
2273
2274   GString *string;
2275   FormatIndex index;
2276
2277   string = g_string_new (NULL);
2278
2279   switch (flags & ~G_FORMAT_SIZE_LONG_FORMAT)
2280     {
2281     case G_FORMAT_SIZE_DEFAULT:
2282       index = FORMAT_BYTES;
2283       break;
2284     case (G_FORMAT_SIZE_DEFAULT | G_FORMAT_SIZE_IEC_UNITS):
2285       index = FORMAT_BYTES_IEC;
2286       break;
2287     case G_FORMAT_SIZE_BITS:
2288       index = FORMAT_BITS;
2289       break;
2290     case (G_FORMAT_SIZE_BITS | G_FORMAT_SIZE_IEC_UNITS):
2291       index = FORMAT_BITS_IEC;
2292       break;
2293     default:
2294       g_assert_not_reached ();
2295     }
2296
2297
2298   if (size < formats[index][0].factor)
2299     {
2300       const char * format;
2301
2302       if (index == FORMAT_BYTES || index == FORMAT_BYTES_IEC)
2303         {
2304           format = g_dngettext (GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size);
2305         }
2306       else
2307         {
2308           format = g_dngettext (GETTEXT_PACKAGE, "%u bit", "%u bits", (guint) size);
2309         }
2310
2311       g_string_printf (string, format, (guint) size);
2312
2313       flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2314     }
2315   else
2316     {
2317       const gsize n = G_N_ELEMENTS (formats[index]);
2318       gsize i;
2319
2320       /*
2321        * Point the last format (the highest unit) by default
2322        * and then then scan all formats, starting with the 2nd one
2323        * because the 1st is already managed by with the plural form
2324        */
2325       const struct Format * f = &formats[index][n - 1];
2326
2327       for (i = 1; i < n; i++)
2328         {
2329           if (size < formats[index][i].factor)
2330             {
2331               f = &formats[index][i - 1];
2332               break;
2333             }
2334         }
2335
2336       g_string_printf (string, _(f->string), (gdouble) size / (gdouble) f->factor);
2337     }
2338
2339   if (flags & G_FORMAT_SIZE_LONG_FORMAT)
2340     {
2341       /* First problem: we need to use the number of bytes to decide on
2342        * the plural form that is used for display, but the number of
2343        * bytes potentially exceeds the size of a guint (which is what
2344        * ngettext() takes).
2345        *
2346        * From a pragmatic standpoint, it seems that all known languages
2347        * base plural forms on one or both of the following:
2348        *
2349        *   - the lowest digits of the number
2350        *
2351        *   - if the number if greater than some small value
2352        *
2353        * Here's how we fake it:  Draw an arbitrary line at one thousand.
2354        * If the number is below that, then fine.  If it is above it,
2355        * then we take the modulus of the number by one thousand (in
2356        * order to keep the lowest digits) and add one thousand to that
2357        * (in order to ensure that 1001 is not treated the same as 1).
2358        */
2359       guint plural_form = size < 1000 ? size : size % 1000 + 1000;
2360
2361       /* Second problem: we need to translate the string "%u byte/bit" and
2362        * "%u bytes/bits" for pluralisation, but the correct number format to
2363        * use for a gsize is different depending on which architecture
2364        * we're on.
2365        *
2366        * Solution: format the number separately and use "%s bytes/bits" on
2367        * all platforms.
2368        */
2369       const gchar *translated_format;
2370       gchar *formatted_number;
2371
2372       if (index == FORMAT_BYTES || index == FORMAT_BYTES_IEC)
2373         {
2374           /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2375           translated_format = g_dngettext (GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
2376         }
2377       else
2378         {
2379           /* Translators: the %s in "%s bits" will always be replaced by a number. */
2380           translated_format = g_dngettext (GETTEXT_PACKAGE, "%s bit", "%s bits", plural_form);
2381         }
2382       /* XXX: Windows doesn't support the "'" format modifier, so we
2383        * must not use it there.  Instead, just display the number
2384        * without separation.  Bug #655336 is open until a solution is
2385        * found.
2386        */
2387 #ifndef G_OS_WIN32
2388       formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2389 #else
2390       formatted_number = g_strdup_printf ("%"G_GUINT64_FORMAT, size);
2391 #endif
2392
2393       g_string_append (string, " (");
2394       g_string_append_printf (string, translated_format, formatted_number);
2395       g_free (formatted_number);
2396       g_string_append (string, ")");
2397     }
2398
2399   return g_string_free (string, FALSE);
2400 }
2401
2402 #pragma GCC diagnostic pop
2403
2404 /**
2405  * g_format_size_for_display:
2406  * @size: a size in bytes
2407  *
2408  * Formats a size (for example the size of a file) into a human
2409  * readable string. Sizes are rounded to the nearest size prefix
2410  * (KB, MB, GB) and are displayed rounded to the nearest tenth.
2411  * E.g. the file size 3292528 bytes will be converted into the
2412  * string "3.1 MB".
2413  *
2414  * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2415  *
2416  * This string should be freed with g_free() when not needed any longer.
2417  *
2418  * Returns: a newly-allocated formatted string containing a human
2419  *     readable file size
2420  *
2421  * Since: 2.16
2422  *
2423  * Deprecated:2.30: This function is broken due to its use of SI
2424  *     suffixes to denote IEC units. Use g_format_size() instead.
2425  */
2426 gchar *
2427 g_format_size_for_display (goffset size)
2428 {
2429   if (size < (goffset) KIBIBYTE_FACTOR)
2430     return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
2431   else
2432     {
2433       gdouble displayed_size;
2434
2435       if (size < (goffset) MEBIBYTE_FACTOR)
2436         {
2437           displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
2438           /* Translators: this is from the deprecated function g_format_size_for_display() which uses 'KB' to
2439            * mean 1024 bytes.  I am aware that 'KB' is not correct, but it has been preserved for reasons of
2440            * compatibility.  Users will not see this string unless a program is using this deprecated function.
2441            * Please translate as literally as possible.
2442            */
2443           return g_strdup_printf (_("%.1f KB"), displayed_size);
2444         }
2445       else if (size < (goffset) GIBIBYTE_FACTOR)
2446         {
2447           displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
2448           return g_strdup_printf (_("%.1f MB"), displayed_size);
2449         }
2450       else if (size < (goffset) TEBIBYTE_FACTOR)
2451         {
2452           displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
2453           return g_strdup_printf (_("%.1f GB"), displayed_size);
2454         }
2455       else if (size < (goffset) PEBIBYTE_FACTOR)
2456         {
2457           displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
2458           return g_strdup_printf (_("%.1f TB"), displayed_size);
2459         }
2460       else if (size < (goffset) EXBIBYTE_FACTOR)
2461         {
2462           displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
2463           return g_strdup_printf (_("%.1f PB"), displayed_size);
2464         }
2465       else
2466         {
2467           displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
2468           return g_strdup_printf (_("%.1f EB"), displayed_size);
2469         }
2470     }
2471 }
2472
2473 #if defined (G_OS_WIN32) && !defined (_WIN64)
2474
2475 /* Binary compatibility versions. Not for newly compiled code. */
2476
2477 _GLIB_EXTERN const gchar *g_get_user_name_utf8        (void);
2478 _GLIB_EXTERN const gchar *g_get_real_name_utf8        (void);
2479 _GLIB_EXTERN const gchar *g_get_home_dir_utf8         (void);
2480 _GLIB_EXTERN const gchar *g_get_tmp_dir_utf8          (void);
2481 _GLIB_EXTERN gchar       *g_find_program_in_path_utf8 (const gchar *program);
2482
2483 gchar *
2484 g_find_program_in_path_utf8 (const gchar *program)
2485 {
2486   return g_find_program_in_path (program);
2487 }
2488
2489 const gchar *g_get_user_name_utf8 (void) { return g_get_user_name (); }
2490 const gchar *g_get_real_name_utf8 (void) { return g_get_real_name (); }
2491 const gchar *g_get_home_dir_utf8 (void) { return g_get_home_dir (); }
2492 const gchar *g_get_tmp_dir_utf8 (void) { return g_get_tmp_dir (); }
2493
2494 #endif
2495
2496 /* Private API:
2497  *
2498  * Returns %TRUE if the current process was executed as setuid (or an
2499  * equivalent __libc_enable_secure is available).  See:
2500  * http://osdir.com/ml/linux.lfs.hardened/2007-04/msg00032.html
2501  */ 
2502 gboolean
2503 g_check_setuid (void)
2504 {
2505   /* TODO: get __libc_enable_secure exported from glibc.
2506    * See http://www.openwall.com/lists/owl-dev/2012/08/14/1
2507    */
2508 #if 0 && defined(HAVE_LIBC_ENABLE_SECURE)
2509   {
2510     /* See glibc/include/unistd.h */
2511     extern int __libc_enable_secure;
2512     return __libc_enable_secure;
2513   }
2514 #elif defined(HAVE_ISSETUGID) && !defined(__BIONIC__)
2515   /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
2516
2517   /* Android had it in older versions but the new 64 bit ABI does not
2518    * have it anymore, and some versions of the 32 bit ABI neither.
2519    * https://code.google.com/p/android-developer-preview/issues/detail?id=168
2520    */
2521   return issetugid ();
2522 #elif defined(G_OS_UNIX)
2523   uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
2524   gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
2525
2526   static gsize check_setuid_initialised;
2527   static gboolean is_setuid;
2528
2529   if (g_once_init_enter (&check_setuid_initialised))
2530     {
2531 #ifdef HAVE_GETRESUID
2532       /* These aren't in the header files, so we prototype them here.
2533        */
2534       int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
2535       int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);
2536       
2537       if (getresuid (&ruid, &euid, &suid) != 0 ||
2538           getresgid (&rgid, &egid, &sgid) != 0)
2539 #endif /* HAVE_GETRESUID */
2540         {
2541           suid = ruid = getuid ();
2542           sgid = rgid = getgid ();
2543           euid = geteuid ();
2544           egid = getegid ();
2545         }
2546
2547       is_setuid = (ruid != euid || ruid != suid ||
2548                    rgid != egid || rgid != sgid);
2549
2550       g_once_init_leave (&check_setuid_initialised, 1);
2551     }
2552   return is_setuid;
2553 #else
2554   return FALSE;
2555 #endif
2556 }
2557
2558 #ifdef G_OS_WIN32
2559 /**
2560  * g_abort:
2561  *
2562  * A wrapper for the POSIX abort() function.
2563  *
2564  * On Windows it is a function that makes extra effort (including a call
2565  * to abort()) to ensure that a debugger-catchable exception is thrown
2566  * before the program terminates.
2567  *
2568  * See your C library manual for more details about abort().
2569  *
2570  * Since: 2.50
2571  */
2572 void
2573 g_abort (void)
2574 {
2575   /* One call to break the debugger */
2576   DebugBreak ();
2577   /* One call in case CRT does get saner about abort() behaviour */
2578   abort ();
2579   /* And one call to bind them all and terminate the program for sure */
2580   ExitProcess (127);
2581 }
2582 #endif