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