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