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