Clarify documentation of GValueTransform
[glib.git] / glib / gutils.c
blobeb44f179fa94883ca0c8514524bb0cc3e2cd6296
1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1998 Peter Mattis, Spencer Kimball and Josh MacDonald
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.
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.
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/>.
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/.
25 /*
26 * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
29 #include "config.h"
31 #include "gutils.h"
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
54 #include "glib-init.h"
55 #include "glib-private.h"
56 #include "genviron.h"
57 #include "gfileutils.h"
58 #include "ggettext.h"
59 #include "ghash.h"
60 #include "gthread.h"
61 #include "gtestutils.h"
62 #include "gunicode.h"
63 #include "gstrfuncs.h"
64 #include "garray.h"
65 #include "glibintl.h"
66 #include "gstdio.h"
68 #ifdef G_PLATFORM_WIN32
69 #include "gconvert.h"
70 #include "gwin32.h"
71 #endif
74 /**
75 * SECTION:misc_utils
76 * @title: Miscellaneous Utility Functions
77 * @short_description: a selection of portable utility functions
79 * These are portable utility functions.
82 #ifdef G_PLATFORM_WIN32
83 # include <windows.h>
84 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
85 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
86 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
87 # endif
88 # include <lmcons.h> /* For UNLEN */
89 #endif /* G_PLATFORM_WIN32 */
91 #ifdef G_OS_WIN32
92 # include <direct.h>
93 # include <shlobj.h>
94 /* older SDK (e.g. msvc 5.0) does not have these*/
95 # ifndef CSIDL_MYMUSIC
96 # define CSIDL_MYMUSIC 13
97 # endif
98 # ifndef CSIDL_MYVIDEO
99 # define CSIDL_MYVIDEO 14
100 # endif
101 # ifndef CSIDL_INTERNET_CACHE
102 # define CSIDL_INTERNET_CACHE 32
103 # endif
104 # ifndef CSIDL_COMMON_APPDATA
105 # define CSIDL_COMMON_APPDATA 35
106 # endif
107 # ifndef CSIDL_MYPICTURES
108 # define CSIDL_MYPICTURES 0x27
109 # endif
110 # ifndef CSIDL_COMMON_DOCUMENTS
111 # define CSIDL_COMMON_DOCUMENTS 46
112 # endif
113 # ifndef CSIDL_PROFILE
114 # define CSIDL_PROFILE 40
115 # endif
116 # include <process.h>
117 #endif
119 #ifdef HAVE_CARBON
120 #include <CoreServices/CoreServices.h>
121 #endif
123 #ifdef HAVE_CODESET
124 #include <langinfo.h>
125 #endif
127 #ifdef G_PLATFORM_WIN32
129 gchar *
130 _glib_get_dll_directory (void)
132 gchar *retval;
133 gchar *p;
134 wchar_t wc_fn[MAX_PATH];
136 #ifdef DLL_EXPORT
137 if (glib_dll == NULL)
138 return NULL;
139 #endif
141 /* This code is different from that in
142 * g_win32_get_package_installation_directory_of_module() in that
143 * here we return the actual folder where the GLib DLL is. We don't
144 * do the check for it being in a "bin" or "lib" subfolder and then
145 * returning the parent of that.
147 * In a statically built GLib, glib_dll will be NULL and we will
148 * thus look up the application's .exe file's location.
150 if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
151 return NULL;
153 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
155 p = strrchr (retval, G_DIR_SEPARATOR);
156 if (p == NULL)
158 /* Wtf? */
159 return NULL;
161 *p = '\0';
163 return retval;
166 #endif
169 * g_memmove:
170 * @dest: the destination address to copy the bytes to.
171 * @src: the source address to copy the bytes from.
172 * @len: the number of bytes to copy.
174 * Copies a block of memory @len bytes long, from @src to @dest.
175 * The source and destination areas may overlap.
177 * Deprecated:2.40: Just use memmove().
180 #ifdef G_OS_WIN32
181 #undef g_atexit
182 #endif
185 * g_atexit:
186 * @func: (scope async): the function to call on normal program termination.
188 * Specifies a function to be called at normal program termination.
190 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
191 * macro that maps to a call to the atexit() function in the C
192 * library. This means that in case the code that calls g_atexit(),
193 * i.e. atexit(), is in a DLL, the function will be called when the
194 * DLL is detached from the program. This typically makes more sense
195 * than that the function is called when the GLib DLL is detached,
196 * which happened earlier when g_atexit() was a function in the GLib
197 * DLL.
199 * The behaviour of atexit() in the context of dynamically loaded
200 * modules is not formally specified and varies wildly.
202 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
203 * loaded module which is unloaded before the program terminates might
204 * well cause a crash at program exit.
206 * Some POSIX systems implement atexit() like Windows, and have each
207 * dynamically loaded module maintain an own atexit chain that is
208 * called when the module is unloaded.
210 * On other POSIX systems, before a dynamically loaded module is
211 * unloaded, the registered atexit functions (if any) residing in that
212 * module are called, regardless where the code that registered them
213 * resided. This is presumably the most robust approach.
215 * As can be seen from the above, for portability it's best to avoid
216 * calling g_atexit() (or atexit()) except in the main executable of a
217 * program.
219 * Deprecated:2.32: It is best to avoid g_atexit().
221 void
222 g_atexit (GVoidFunc func)
224 gint result;
225 int errsv;
227 result = atexit ((void (*)(void)) func);
228 errsv = errno;
229 if (result)
231 g_error ("Could not register atexit() function: %s",
232 g_strerror (errsv));
236 /* Based on execvp() from GNU Libc.
237 * Some of this code is cut-and-pasted into gspawn.c
240 static gchar*
241 my_strchrnul (const gchar *str,
242 gchar c)
244 gchar *p = (gchar*)str;
245 while (*p && (*p != c))
246 ++p;
248 return p;
251 #ifdef G_OS_WIN32
253 static gchar *inner_find_program_in_path (const gchar *program);
255 gchar*
256 g_find_program_in_path (const gchar *program)
258 const gchar *last_dot = strrchr (program, '.');
260 if (last_dot == NULL ||
261 strchr (last_dot, '\\') != NULL ||
262 strchr (last_dot, '/') != NULL)
264 const gint program_length = strlen (program);
265 gchar *pathext = g_build_path (";",
266 ".exe;.cmd;.bat;.com",
267 g_getenv ("PATHEXT"),
268 NULL);
269 gchar *p;
270 gchar *decorated_program;
271 gchar *retval;
273 p = pathext;
276 gchar *q = my_strchrnul (p, ';');
278 decorated_program = g_malloc (program_length + (q-p) + 1);
279 memcpy (decorated_program, program, program_length);
280 memcpy (decorated_program+program_length, p, q-p);
281 decorated_program [program_length + (q-p)] = '\0';
283 retval = inner_find_program_in_path (decorated_program);
284 g_free (decorated_program);
286 if (retval != NULL)
288 g_free (pathext);
289 return retval;
291 p = q;
292 } while (*p++ != '\0');
293 g_free (pathext);
294 return NULL;
296 else
297 return inner_find_program_in_path (program);
300 #endif
303 * g_find_program_in_path:
304 * @program: (type filename): a program name in the GLib file name encoding
306 * Locates the first executable named @program in the user's path, in the
307 * same way that execvp() would locate it. Returns an allocated string
308 * with the absolute path name, or %NULL if the program is not found in
309 * the path. If @program is already an absolute path, returns a copy of
310 * @program if @program exists and is executable, and %NULL otherwise.
312 * On Windows, if @program does not have a file type suffix, tries
313 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
314 * the `PATHEXT` environment variable.
316 * On Windows, it looks for the file in the same way as CreateProcess()
317 * would. This means first in the directory where the executing
318 * program was loaded from, then in the current directory, then in the
319 * Windows 32-bit system directory, then in the Windows directory, and
320 * finally in the directories in the `PATH` environment variable. If
321 * the program is found, the return value contains the full name
322 * including the type suffix.
324 * Returns: (type filename): a newly-allocated string with the absolute path,
325 * or %NULL
327 #ifdef G_OS_WIN32
328 static gchar *
329 inner_find_program_in_path (const gchar *program)
330 #else
331 gchar*
332 g_find_program_in_path (const gchar *program)
333 #endif
335 const gchar *path, *p;
336 gchar *name, *freeme;
337 #ifdef G_OS_WIN32
338 const gchar *path_copy;
339 gchar *filename = NULL, *appdir = NULL;
340 gchar *sysdir = NULL, *windir = NULL;
341 int n;
342 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
343 wwindir[MAXPATHLEN];
344 #endif
345 gsize len;
346 gsize pathlen;
348 g_return_val_if_fail (program != NULL, NULL);
350 /* If it is an absolute path, or a relative path including subdirectories,
351 * don't look in PATH.
353 if (g_path_is_absolute (program)
354 || strchr (program, G_DIR_SEPARATOR) != NULL
355 #ifdef G_OS_WIN32
356 || strchr (program, '/') != NULL
357 #endif
360 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
361 !g_file_test (program, G_FILE_TEST_IS_DIR))
362 return g_strdup (program);
363 else
364 return NULL;
367 path = g_getenv ("PATH");
368 #if defined(G_OS_UNIX)
369 if (path == NULL)
371 /* There is no 'PATH' in the environment. The default
372 * search path in GNU libc is the current directory followed by
373 * the path 'confstr' returns for '_CS_PATH'.
376 /* In GLib we put . last, for security, and don't use the
377 * unportable confstr(); UNIX98 does not actually specify
378 * what to search if PATH is unset. POSIX may, dunno.
381 path = "/bin:/usr/bin:.";
383 #else
384 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
385 if (n > 0 && n < MAXPATHLEN)
386 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
388 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
389 if (n > 0 && n < MAXPATHLEN)
390 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
392 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
393 if (n > 0 && n < MAXPATHLEN)
394 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
396 if (filename)
398 appdir = g_path_get_dirname (filename);
399 g_free (filename);
402 path = g_strdup (path);
404 if (windir)
406 const gchar *tem = path;
407 path = g_strconcat (windir, ";", path, NULL);
408 g_free ((gchar *) tem);
409 g_free (windir);
412 if (sysdir)
414 const gchar *tem = path;
415 path = g_strconcat (sysdir, ";", path, NULL);
416 g_free ((gchar *) tem);
417 g_free (sysdir);
421 const gchar *tem = path;
422 path = g_strconcat (".;", path, NULL);
423 g_free ((gchar *) tem);
426 if (appdir)
428 const gchar *tem = path;
429 path = g_strconcat (appdir, ";", path, NULL);
430 g_free ((gchar *) tem);
431 g_free (appdir);
434 path_copy = path;
435 #endif
437 len = strlen (program) + 1;
438 pathlen = strlen (path);
439 freeme = name = g_malloc (pathlen + len + 1);
441 /* Copy the file name at the top, including '\0' */
442 memcpy (name + pathlen + 1, program, len);
443 name = name + pathlen;
444 /* And add the slash before the filename */
445 *name = G_DIR_SEPARATOR;
447 p = path;
450 char *startp;
452 path = p;
453 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
455 if (p == path)
456 /* Two adjacent colons, or a colon at the beginning or the end
457 * of 'PATH' means to search the current directory.
459 startp = name + 1;
460 else
461 startp = memcpy (name - (p - path), path, p - path);
463 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
464 !g_file_test (startp, G_FILE_TEST_IS_DIR))
466 gchar *ret;
467 ret = g_strdup (startp);
468 g_free (freeme);
469 #ifdef G_OS_WIN32
470 g_free ((gchar *) path_copy);
471 #endif
472 return ret;
475 while (*p++ != '\0');
477 g_free (freeme);
478 #ifdef G_OS_WIN32
479 g_free ((gchar *) path_copy);
480 #endif
482 return NULL;
485 /* The functions below are defined this way for compatibility reasons.
486 * See the note in gutils.h.
490 * g_bit_nth_lsf:
491 * @mask: a #gulong containing flags
492 * @nth_bit: the index of the bit to start the search from
494 * Find the position of the first bit set in @mask, searching
495 * from (but not including) @nth_bit upwards. Bits are numbered
496 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
497 * usually). To start searching from the 0th bit, set @nth_bit to -1.
499 * Returns: the index of the first bit set which is higher than @nth_bit, or -1
500 * if no higher bits are set
502 gint
503 (g_bit_nth_lsf) (gulong mask,
504 gint nth_bit)
506 return g_bit_nth_lsf_impl (mask, nth_bit);
510 * g_bit_nth_msf:
511 * @mask: a #gulong containing flags
512 * @nth_bit: the index of the bit to start the search from
514 * Find the position of the first bit set in @mask, searching
515 * from (but not including) @nth_bit downwards. Bits are numbered
516 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
517 * usually). To start searching from the last bit, set @nth_bit to
518 * -1 or GLIB_SIZEOF_LONG * 8.
520 * Returns: the index of the first bit set which is lower than @nth_bit, or -1
521 * if no lower bits are set
523 gint
524 (g_bit_nth_msf) (gulong mask,
525 gint nth_bit)
527 return g_bit_nth_msf_impl (mask, nth_bit);
532 * g_bit_storage:
533 * @number: a #guint
535 * Gets the number of bits used to hold @number,
536 * e.g. if @number is 4, 3 bits are needed.
538 * Returns: the number of bits used to hold @number
540 guint
541 (g_bit_storage) (gulong number)
543 return g_bit_storage_impl (number);
546 G_LOCK_DEFINE_STATIC (g_utils_global);
548 typedef struct
550 gchar *user_name;
551 gchar *real_name;
552 gchar *home_dir;
553 } UserDatabaseEntry;
555 static gchar *g_user_data_dir = NULL;
556 static gchar **g_system_data_dirs = NULL;
557 static gchar *g_user_cache_dir = NULL;
558 static gchar *g_user_config_dir = NULL;
559 static gchar **g_system_config_dirs = NULL;
561 static gchar **g_user_special_dirs = NULL;
563 /* fifteen minutes of fame for everybody */
564 #define G_USER_DIRS_EXPIRE 15 * 60
566 #ifdef G_OS_WIN32
568 static gchar *
569 get_special_folder (int csidl)
571 wchar_t path[MAX_PATH+1];
572 HRESULT hr;
573 LPITEMIDLIST pidl = NULL;
574 BOOL b;
575 gchar *retval = NULL;
577 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
578 if (hr == S_OK)
580 b = SHGetPathFromIDListW (pidl, path);
581 if (b)
582 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
583 CoTaskMemFree (pidl);
585 return retval;
588 static char *
589 get_windows_directory_root (void)
591 wchar_t wwindowsdir[MAX_PATH];
593 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
595 /* Usually X:\Windows, but in terminal server environments
596 * might be an UNC path, AFAIK.
598 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
599 char *p;
601 if (windowsdir == NULL)
602 return g_strdup ("C:\\");
604 p = (char *) g_path_skip_root (windowsdir);
605 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
606 p--;
607 *p = '\0';
608 return windowsdir;
610 else
611 return g_strdup ("C:\\");
614 #endif
616 /* HOLDS: g_utils_global_lock */
617 static UserDatabaseEntry *
618 g_get_user_database_entry (void)
620 static UserDatabaseEntry *entry;
622 if (g_once_init_enter (&entry))
624 static UserDatabaseEntry e;
626 #ifdef G_OS_UNIX
628 struct passwd *pw = NULL;
629 gpointer buffer = NULL;
630 gint error;
631 gchar *logname;
633 # if defined (HAVE_GETPWUID_R)
634 struct passwd pwd;
635 # ifdef _SC_GETPW_R_SIZE_MAX
636 /* This reurns the maximum length */
637 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
639 if (bufsize < 0)
640 bufsize = 64;
641 # else /* _SC_GETPW_R_SIZE_MAX */
642 glong bufsize = 64;
643 # endif /* _SC_GETPW_R_SIZE_MAX */
645 logname = (gchar *) g_getenv ("LOGNAME");
649 g_free (buffer);
650 /* we allocate 6 extra bytes to work around a bug in
651 * Mac OS < 10.3. See #156446
653 buffer = g_malloc (bufsize + 6);
654 errno = 0;
656 if (logname) {
657 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
658 if (!pw || (pw->pw_uid != getuid ())) {
659 /* LOGNAME is lying, fall back to looking up the uid */
660 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
662 } else {
663 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
665 error = error < 0 ? errno : error;
667 if (!pw)
669 /* we bail out prematurely if the user id can't be found
670 * (should be pretty rare case actually), or if the buffer
671 * should be sufficiently big and lookups are still not
672 * successful.
674 if (error == 0 || error == ENOENT)
676 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
677 (gulong) getuid ());
678 break;
680 if (bufsize > 32 * 1024)
682 g_warning ("getpwuid_r(): failed due to: %s.",
683 g_strerror (error));
684 break;
687 bufsize *= 2;
690 while (!pw);
691 # endif /* HAVE_GETPWUID_R */
693 if (!pw)
695 pw = getpwuid (getuid ());
697 if (pw)
699 e.user_name = g_strdup (pw->pw_name);
701 #ifndef __BIONIC__
702 if (pw->pw_gecos && *pw->pw_gecos != '\0')
704 gchar **gecos_fields;
705 gchar **name_parts;
707 /* split the gecos field and substitute '&' */
708 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
709 name_parts = g_strsplit (gecos_fields[0], "&", 0);
710 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
711 e.real_name = g_strjoinv (pw->pw_name, name_parts);
712 g_strfreev (gecos_fields);
713 g_strfreev (name_parts);
715 #endif
717 if (!e.home_dir)
718 e.home_dir = g_strdup (pw->pw_dir);
720 g_free (buffer);
723 #endif /* G_OS_UNIX */
725 #ifdef G_OS_WIN32
727 guint len = UNLEN+1;
728 wchar_t buffer[UNLEN+1];
730 if (GetUserNameW (buffer, (LPDWORD) &len))
732 e.user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
733 e.real_name = g_strdup (e.user_name);
736 #endif /* G_OS_WIN32 */
738 if (!e.user_name)
739 e.user_name = g_strdup ("somebody");
740 if (!e.real_name)
741 e.real_name = g_strdup ("Unknown");
743 g_once_init_leave (&entry, &e);
746 return entry;
750 * g_get_user_name:
752 * Gets the user name of the current user. The encoding of the returned
753 * string is system-defined. On UNIX, it might be the preferred file name
754 * encoding, or something else, and there is no guarantee that it is even
755 * consistent on a machine. On Windows, it is always UTF-8.
757 * Returns: (type filename): the user name of the current user.
759 const gchar *
760 g_get_user_name (void)
762 UserDatabaseEntry *entry;
764 entry = g_get_user_database_entry ();
766 return entry->user_name;
770 * g_get_real_name:
772 * Gets the real name of the user. This usually comes from the user's
773 * entry in the `passwd` file. The encoding of the returned string is
774 * system-defined. (On Windows, it is, however, always UTF-8.) If the
775 * real user name cannot be determined, the string "Unknown" is
776 * returned.
778 * Returns: (type filename): the user's real name.
780 const gchar *
781 g_get_real_name (void)
783 UserDatabaseEntry *entry;
785 entry = g_get_user_database_entry ();
787 return entry->real_name;
791 * g_get_home_dir:
793 * Gets the current user's home directory.
795 * As with most UNIX tools, this function will return the value of the
796 * `HOME` environment variable if it is set to an existing absolute path
797 * name, falling back to the `passwd` file in the case that it is unset.
799 * If the path given in `HOME` is non-absolute, does not exist, or is
800 * not a directory, the result is undefined.
802 * Before version 2.36 this function would ignore the `HOME` environment
803 * variable, taking the value from the `passwd` database instead. This was
804 * changed to increase the compatibility of GLib with other programs (and
805 * the XDG basedir specification) and to increase testability of programs
806 * based on GLib (by making it easier to run them from test frameworks).
808 * If your program has a strong requirement for either the new or the
809 * old behaviour (and if you don't wish to increase your GLib
810 * dependency to ensure that the new behaviour is in effect) then you
811 * should either directly check the `HOME` environment variable yourself
812 * or unset it before calling any functions in GLib.
814 * Returns: (type filename): the current user's home directory
816 const gchar *
817 g_get_home_dir (void)
819 static gchar *home_dir;
821 if (g_once_init_enter (&home_dir))
823 gchar *tmp;
825 /* We first check HOME and use it if it is set */
826 tmp = g_strdup (g_getenv ("HOME"));
828 #ifdef G_OS_WIN32
829 /* Only believe HOME if it is an absolute path and exists.
831 * We only do this check on Windows for a couple of reasons.
832 * Historically, we only did it there because we used to ignore $HOME
833 * on UNIX. There are concerns about enabling it now on UNIX because
834 * of things like autofs. In short, if the user has a bogus value in
835 * $HOME then they get what they pay for...
837 if (tmp)
839 if (!(g_path_is_absolute (tmp) &&
840 g_file_test (tmp, G_FILE_TEST_IS_DIR)))
842 g_free (tmp);
843 tmp = NULL;
847 /* In case HOME is Unix-style (it happens), convert it to
848 * Windows style.
850 if (tmp)
852 gchar *p;
853 while ((p = strchr (tmp, '/')) != NULL)
854 *p = '\\';
857 if (!tmp)
859 /* USERPROFILE is probably the closest equivalent to $HOME? */
860 if (g_getenv ("USERPROFILE") != NULL)
861 tmp = g_strdup (g_getenv ("USERPROFILE"));
864 if (!tmp)
865 tmp = get_special_folder (CSIDL_PROFILE);
867 if (!tmp)
868 tmp = get_windows_directory_root ();
869 #endif /* G_OS_WIN32 */
871 if (!tmp)
873 /* If we didn't get it from any of those methods, we will have
874 * to read the user database entry.
876 UserDatabaseEntry *entry;
878 entry = g_get_user_database_entry ();
880 /* Strictly speaking, we should copy this, but we know that
881 * neither will ever be freed, so don't bother...
883 tmp = entry->home_dir;
886 g_once_init_leave (&home_dir, tmp);
889 return home_dir;
893 * g_get_tmp_dir:
895 * Gets the directory to use for temporary files.
897 * On UNIX, this is taken from the `TMPDIR` environment variable.
898 * If the variable is not set, `P_tmpdir` is
899 * used, as defined by the system C library. Failing that, a
900 * hard-coded default of "/tmp" is returned.
902 * On Windows, the `TEMP` environment variable is used, with the
903 * root directory of the Windows installation (eg: "C:\") used
904 * as a default.
906 * The encoding of the returned string is system-defined. On Windows,
907 * it is always UTF-8. The return value is never %NULL or the empty
908 * string.
910 * Returns: (type filename): the directory to use for temporary files.
912 const gchar *
913 g_get_tmp_dir (void)
915 static gchar *tmp_dir;
917 if (g_once_init_enter (&tmp_dir))
919 gchar *tmp;
921 #ifdef G_OS_WIN32
922 tmp = g_strdup (g_getenv ("TEMP"));
924 if (tmp == NULL || *tmp == '\0')
926 g_free (tmp);
927 tmp = get_windows_directory_root ();
929 #else /* G_OS_WIN32 */
930 tmp = g_strdup (g_getenv ("TMPDIR"));
932 #ifdef P_tmpdir
933 if (tmp == NULL || *tmp == '\0')
935 gsize k;
936 g_free (tmp);
937 tmp = g_strdup (P_tmpdir);
938 k = strlen (tmp);
939 if (k > 1 && G_IS_DIR_SEPARATOR (tmp[k - 1]))
940 tmp[k - 1] = '\0';
942 #endif /* P_tmpdir */
944 if (tmp == NULL || *tmp == '\0')
946 g_free (tmp);
947 tmp = g_strdup ("/tmp");
949 #endif /* !G_OS_WIN32 */
951 g_once_init_leave (&tmp_dir, tmp);
954 return tmp_dir;
958 * g_get_host_name:
960 * Return a name for the machine.
962 * The returned name is not necessarily a fully-qualified domain name,
963 * or even present in DNS or some other name service at all. It need
964 * not even be unique on your local network or site, but usually it
965 * is. Callers should not rely on the return value having any specific
966 * properties like uniqueness for security purposes. Even if the name
967 * of the machine is changed while an application is running, the
968 * return value from this function does not change. The returned
969 * string is owned by GLib and should not be modified or freed. If no
970 * name can be determined, a default fixed string "localhost" is
971 * returned.
973 * Returns: the host name of the machine.
975 * Since: 2.8
977 const gchar *
978 g_get_host_name (void)
980 static gchar *hostname;
982 if (g_once_init_enter (&hostname))
984 gboolean failed;
985 gchar tmp[100];
987 #ifndef G_OS_WIN32
988 failed = (gethostname (tmp, sizeof (tmp)) == -1);
989 #else
990 DWORD size = sizeof (tmp);
991 failed = (!GetComputerName (tmp, &size));
992 #endif
994 g_once_init_leave (&hostname, g_strdup (failed ? "localhost" : tmp));
997 return hostname;
1000 G_LOCK_DEFINE_STATIC (g_prgname);
1001 static gchar *g_prgname = NULL;
1004 * g_get_prgname:
1006 * Gets the name of the program. This name should not be localized,
1007 * in contrast to g_get_application_name().
1009 * If you are using #GApplication the program name is set in
1010 * g_application_run(). In case of GDK or GTK+ it is set in
1011 * gdk_init(), which is called by gtk_init() and the
1012 * #GtkApplication::startup handler. The program name is found by
1013 * taking the last component of @argv[0].
1015 * Returns: the name of the program. The returned string belongs
1016 * to GLib and must not be modified or freed.
1018 const gchar*
1019 g_get_prgname (void)
1021 gchar* retval;
1023 G_LOCK (g_prgname);
1024 #ifdef G_OS_WIN32
1025 if (g_prgname == NULL)
1027 static gboolean beenhere = FALSE;
1029 if (!beenhere)
1031 gchar *utf8_buf = NULL;
1032 wchar_t buf[MAX_PATH+1];
1034 beenhere = TRUE;
1035 if (GetModuleFileNameW (GetModuleHandle (NULL),
1036 buf, G_N_ELEMENTS (buf)) > 0)
1037 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1039 if (utf8_buf)
1041 g_prgname = g_path_get_basename (utf8_buf);
1042 g_free (utf8_buf);
1046 #endif
1047 retval = g_prgname;
1048 G_UNLOCK (g_prgname);
1050 return retval;
1054 * g_set_prgname:
1055 * @prgname: the name of the program.
1057 * Sets the name of the program. This name should not be localized,
1058 * in contrast to g_set_application_name().
1060 * If you are using #GApplication the program name is set in
1061 * g_application_run(). In case of GDK or GTK+ it is set in
1062 * gdk_init(), which is called by gtk_init() and the
1063 * #GtkApplication::startup handler. The program name is found by
1064 * taking the last component of @argv[0].
1066 * Note that for thread-safety reasons this function can only be called once.
1068 void
1069 g_set_prgname (const gchar *prgname)
1071 G_LOCK (g_prgname);
1072 g_free (g_prgname);
1073 g_prgname = g_strdup (prgname);
1074 G_UNLOCK (g_prgname);
1077 G_LOCK_DEFINE_STATIC (g_application_name);
1078 static gchar *g_application_name = NULL;
1081 * g_get_application_name:
1083 * Gets a human-readable name for the application, as set by
1084 * g_set_application_name(). This name should be localized if
1085 * possible, and is intended for display to the user. Contrast with
1086 * g_get_prgname(), which gets a non-localized name. If
1087 * g_set_application_name() has not been called, returns the result of
1088 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1089 * been called).
1091 * Returns: human-readable application name. may return %NULL
1093 * Since: 2.2
1095 const gchar *
1096 g_get_application_name (void)
1098 gchar* retval;
1100 G_LOCK (g_application_name);
1101 retval = g_application_name;
1102 G_UNLOCK (g_application_name);
1104 if (retval == NULL)
1105 return g_get_prgname ();
1107 return retval;
1111 * g_set_application_name:
1112 * @application_name: localized name of the application
1114 * Sets a human-readable name for the application. This name should be
1115 * localized if possible, and is intended for display to the user.
1116 * Contrast with g_set_prgname(), which sets a non-localized name.
1117 * g_set_prgname() will be called automatically by gtk_init(),
1118 * but g_set_application_name() will not.
1120 * Note that for thread safety reasons, this function can only
1121 * be called once.
1123 * The application name will be used in contexts such as error messages,
1124 * or when displaying an application's name in the task list.
1126 * Since: 2.2
1128 void
1129 g_set_application_name (const gchar *application_name)
1131 gboolean already_set = FALSE;
1133 G_LOCK (g_application_name);
1134 if (g_application_name)
1135 already_set = TRUE;
1136 else
1137 g_application_name = g_strdup (application_name);
1138 G_UNLOCK (g_application_name);
1140 if (already_set)
1141 g_warning ("g_set_application_name() called multiple times");
1145 * g_get_user_data_dir:
1147 * Returns a base directory in which to access application data such
1148 * as icons that is customized for a particular user.
1150 * On UNIX platforms this is determined using the mechanisms described
1151 * in the
1152 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1153 * In this case the directory retrieved will be `XDG_DATA_HOME`.
1155 * On Windows it follows XDG Base Directory Specification if `XDG_DATA_HOME`
1156 * is defined. If `XDG_DATA_HOME` is undefined, the folder to use for local (as
1157 * opposed to roaming) application data is used instead. See the
1158 * [documentation for `CSIDL_LOCAL_APPDATA`](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx#csidl_local_appdata).
1159 * Note that in this case on Windows it will be the same
1160 * as what g_get_user_config_dir() returns.
1162 * Returns: (type filename): a string owned by GLib that must not be modified
1163 * or freed.
1164 * Since: 2.6
1166 const gchar *
1167 g_get_user_data_dir (void)
1169 gchar *data_dir = NULL;
1171 G_LOCK (g_utils_global);
1173 if (!g_user_data_dir)
1175 const gchar *data_dir_env = g_getenv ("XDG_DATA_HOME");
1177 if (data_dir_env && data_dir_env[0])
1178 data_dir = g_strdup (data_dir_env);
1179 #ifdef G_OS_WIN32
1180 else
1181 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1182 #endif
1183 if (!data_dir || !data_dir[0])
1185 const gchar *home_dir = g_get_home_dir ();
1187 if (home_dir)
1188 data_dir = g_build_filename (home_dir, ".local", "share", NULL);
1189 else
1190 data_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".local", "share", NULL);
1193 g_user_data_dir = data_dir;
1195 else
1196 data_dir = g_user_data_dir;
1198 G_UNLOCK (g_utils_global);
1200 return data_dir;
1203 static void
1204 g_init_user_config_dir (void)
1206 gchar *config_dir = NULL;
1208 if (!g_user_config_dir)
1210 const gchar *config_dir_env = g_getenv ("XDG_CONFIG_HOME");
1212 if (config_dir_env && config_dir_env[0])
1213 config_dir = g_strdup (config_dir_env);
1214 #ifdef G_OS_WIN32
1215 else
1216 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1217 #endif
1218 if (!config_dir || !config_dir[0])
1220 const gchar *home_dir = g_get_home_dir ();
1222 if (home_dir)
1223 config_dir = g_build_filename (home_dir, ".config", NULL);
1224 else
1225 config_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".config", NULL);
1228 g_user_config_dir = config_dir;
1233 * g_get_user_config_dir:
1235 * Returns a base directory in which to store user-specific application
1236 * configuration information such as user preferences and settings.
1238 * On UNIX platforms this is determined using the mechanisms described
1239 * in the
1240 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1241 * In this case the directory retrieved will be `XDG_CONFIG_HOME`.
1243 * On Windows it follows XDG Base Directory Specification if `XDG_CONFIG_HOME` is defined.
1244 * If `XDG_CONFIG_HOME` is undefined, the folder to use for local (as opposed
1245 * to roaming) application data is used instead. See the
1246 * [documentation for `CSIDL_LOCAL_APPDATA`](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx#csidl_local_appdata).
1247 * Note that in this case on Windows it will be the same
1248 * as what g_get_user_data_dir() returns.
1250 * Returns: (type filename): a string owned by GLib that must not be modified
1251 * or freed.
1252 * Since: 2.6
1254 const gchar *
1255 g_get_user_config_dir (void)
1257 G_LOCK (g_utils_global);
1259 g_init_user_config_dir ();
1261 G_UNLOCK (g_utils_global);
1263 return g_user_config_dir;
1267 * g_get_user_cache_dir:
1269 * Returns a base directory in which to store non-essential, cached
1270 * data specific to particular user.
1272 * On UNIX platforms this is determined using the mechanisms described
1273 * in the
1274 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1275 * In this case the directory retrieved will be `XDG_CACHE_HOME`.
1277 * On Windows it follows XDG Base Directory Specification if `XDG_CACHE_HOME` is defined.
1278 * If `XDG_CACHE_HOME` is undefined, the directory that serves as a common
1279 * repository for temporary Internet files is used instead. A typical path is
1280 * `C:\Documents and Settings\username\Local Settings\Temporary Internet Files`.
1281 * See the [documentation for `CSIDL_INTERNET_CACHE`](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx#csidl_internet_cache).
1283 * Returns: (type filename): a string owned by GLib that must not be modified
1284 * or freed.
1285 * Since: 2.6
1287 const gchar *
1288 g_get_user_cache_dir (void)
1290 gchar *cache_dir = NULL;
1292 G_LOCK (g_utils_global);
1294 if (!g_user_cache_dir)
1296 const gchar *cache_dir_env = g_getenv ("XDG_CACHE_HOME");
1298 if (cache_dir_env && cache_dir_env[0])
1299 cache_dir = g_strdup (cache_dir_env);
1300 #ifdef G_OS_WIN32
1301 else
1302 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE);
1303 #endif
1304 if (!cache_dir || !cache_dir[0])
1306 const gchar *home_dir = g_get_home_dir ();
1308 if (home_dir)
1309 cache_dir = g_build_filename (home_dir, ".cache", NULL);
1310 else
1311 cache_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".cache", NULL);
1313 g_user_cache_dir = cache_dir;
1315 else
1316 cache_dir = g_user_cache_dir;
1318 G_UNLOCK (g_utils_global);
1320 return cache_dir;
1324 * g_get_user_runtime_dir:
1326 * Returns a directory that is unique to the current user on the local
1327 * system.
1329 * This is determined using the mechanisms described
1330 * in the
1331 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1332 * This is the directory
1333 * specified in the `XDG_RUNTIME_DIR` environment variable.
1334 * In the case that this variable is not set, we return the value of
1335 * g_get_user_cache_dir(), after verifying that it exists.
1337 * Returns: (type filename): a string owned by GLib that must not be
1338 * modified or freed.
1340 * Since: 2.28
1342 const gchar *
1343 g_get_user_runtime_dir (void)
1345 static const gchar *runtime_dir;
1347 if (g_once_init_enter (&runtime_dir))
1349 const gchar *dir;
1351 dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
1353 if (dir == NULL)
1355 /* No need to strdup this one since it is valid forever. */
1356 dir = g_get_user_cache_dir ();
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.
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...
1368 (void) g_mkdir (dir, 0700);
1371 g_assert (dir != NULL);
1373 g_once_init_leave (&runtime_dir, dir);
1376 return runtime_dir;
1379 #ifdef HAVE_CARBON
1381 static gchar *
1382 find_folder (OSType type)
1384 gchar *filename = NULL;
1385 FSRef found;
1387 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
1389 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
1391 if (url)
1393 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
1395 if (path)
1397 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
1399 if (! filename)
1401 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
1403 CFStringGetCString (path, filename,
1404 CFStringGetLength (path) * 3 + 1,
1405 kCFStringEncodingUTF8);
1408 CFRelease (path);
1411 CFRelease (url);
1415 return filename;
1418 static void
1419 load_user_special_dirs (void)
1421 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
1422 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
1423 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
1424 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
1425 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
1426 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
1427 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
1428 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
1431 #elif defined(G_OS_WIN32)
1433 static void
1434 load_user_special_dirs (void)
1436 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1437 DWORD dwFlags,
1438 HANDLE hToken,
1439 PWSTR *ppszPath);
1440 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
1442 static const GUID FOLDERID_Downloads =
1443 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1444 static const GUID FOLDERID_Public =
1445 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1447 wchar_t *wcp;
1449 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
1450 "SHGetKnownFolderPath");
1452 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1453 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
1455 if (p_SHGetKnownFolderPath == NULL)
1457 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1459 else
1461 wcp = NULL;
1462 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1463 if (wcp)
1465 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1466 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
1467 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1468 CoTaskMemFree (wcp);
1470 else
1471 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1474 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
1475 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
1477 if (p_SHGetKnownFolderPath == NULL)
1479 /* XXX */
1480 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1482 else
1484 wcp = NULL;
1485 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
1486 if (wcp)
1488 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1489 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
1490 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1491 CoTaskMemFree (wcp);
1493 else
1494 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1497 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
1498 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
1501 #else /* default is unix */
1503 /* adapted from xdg-user-dir-lookup.c
1505 * Copyright (C) 2007 Red Hat Inc.
1507 * Permission is hereby granted, free of charge, to any person
1508 * obtaining a copy of this software and associated documentation files
1509 * (the "Software"), to deal in the Software without restriction,
1510 * including without limitation the rights to use, copy, modify, merge,
1511 * publish, distribute, sublicense, and/or sell copies of the Software,
1512 * and to permit persons to whom the Software is furnished to do so,
1513 * subject to the following conditions:
1515 * The above copyright notice and this permission notice shall be
1516 * included in all copies or substantial portions of the Software.
1518 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1519 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1520 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1521 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1522 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1523 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1524 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1525 * SOFTWARE.
1527 static void
1528 load_user_special_dirs (void)
1530 gchar *config_file;
1531 gchar *data;
1532 gchar **lines;
1533 gint n_lines, i;
1535 g_init_user_config_dir ();
1536 config_file = g_build_filename (g_user_config_dir,
1537 "user-dirs.dirs",
1538 NULL);
1540 if (!g_file_get_contents (config_file, &data, NULL, NULL))
1542 g_free (config_file);
1543 return;
1546 lines = g_strsplit (data, "\n", -1);
1547 n_lines = g_strv_length (lines);
1548 g_free (data);
1550 for (i = 0; i < n_lines; i++)
1552 gchar *buffer = lines[i];
1553 gchar *d, *p;
1554 gint len;
1555 gboolean is_relative = FALSE;
1556 GUserDirectory directory;
1558 /* Remove newline at end */
1559 len = strlen (buffer);
1560 if (len > 0 && buffer[len - 1] == '\n')
1561 buffer[len - 1] = 0;
1563 p = buffer;
1564 while (*p == ' ' || *p == '\t')
1565 p++;
1567 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
1569 directory = G_USER_DIRECTORY_DESKTOP;
1570 p += strlen ("XDG_DESKTOP_DIR");
1572 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
1574 directory = G_USER_DIRECTORY_DOCUMENTS;
1575 p += strlen ("XDG_DOCUMENTS_DIR");
1577 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
1579 directory = G_USER_DIRECTORY_DOWNLOAD;
1580 p += strlen ("XDG_DOWNLOAD_DIR");
1582 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
1584 directory = G_USER_DIRECTORY_MUSIC;
1585 p += strlen ("XDG_MUSIC_DIR");
1587 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
1589 directory = G_USER_DIRECTORY_PICTURES;
1590 p += strlen ("XDG_PICTURES_DIR");
1592 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
1594 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
1595 p += strlen ("XDG_PUBLICSHARE_DIR");
1597 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
1599 directory = G_USER_DIRECTORY_TEMPLATES;
1600 p += strlen ("XDG_TEMPLATES_DIR");
1602 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
1604 directory = G_USER_DIRECTORY_VIDEOS;
1605 p += strlen ("XDG_VIDEOS_DIR");
1607 else
1608 continue;
1610 while (*p == ' ' || *p == '\t')
1611 p++;
1613 if (*p != '=')
1614 continue;
1615 p++;
1617 while (*p == ' ' || *p == '\t')
1618 p++;
1620 if (*p != '"')
1621 continue;
1622 p++;
1624 if (strncmp (p, "$HOME", 5) == 0)
1626 p += 5;
1627 is_relative = TRUE;
1629 else if (*p != '/')
1630 continue;
1632 d = strrchr (p, '"');
1633 if (!d)
1634 continue;
1635 *d = 0;
1637 d = p;
1639 /* remove trailing slashes */
1640 len = strlen (d);
1641 if (d[len - 1] == '/')
1642 d[len - 1] = 0;
1644 if (is_relative)
1646 g_user_special_dirs[directory] = g_build_filename (g_get_home_dir (), d, NULL);
1648 else
1649 g_user_special_dirs[directory] = g_strdup (d);
1652 g_strfreev (lines);
1653 g_free (config_file);
1656 #endif /* platform-specific load_user_special_dirs implementations */
1660 * g_reload_user_special_dirs_cache:
1662 * Resets the cache used for g_get_user_special_dir(), so
1663 * that the latest on-disk version is used. Call this only
1664 * if you just changed the data on disk yourself.
1666 * Due to threadsafety issues this may cause leaking of strings
1667 * that were previously returned from g_get_user_special_dir()
1668 * that can't be freed. We ensure to only leak the data for
1669 * the directories that actually changed value though.
1671 * Since: 2.22
1673 void
1674 g_reload_user_special_dirs_cache (void)
1676 int i;
1678 G_LOCK (g_utils_global);
1680 if (g_user_special_dirs != NULL)
1682 /* save a copy of the pointer, to check if some memory can be preserved */
1683 char **old_g_user_special_dirs = g_user_special_dirs;
1684 char *old_val;
1686 /* recreate and reload our cache */
1687 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1688 load_user_special_dirs ();
1690 /* only leak changed directories */
1691 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
1693 old_val = old_g_user_special_dirs[i];
1694 if (g_user_special_dirs[i] == NULL)
1696 g_user_special_dirs[i] = old_val;
1698 else if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
1700 /* don't leak */
1701 g_free (g_user_special_dirs[i]);
1702 g_user_special_dirs[i] = old_val;
1704 else
1705 g_free (old_val);
1708 /* free the old array */
1709 g_free (old_g_user_special_dirs);
1712 G_UNLOCK (g_utils_global);
1716 * g_get_user_special_dir:
1717 * @directory: the logical id of special directory
1719 * Returns the full path of a special directory using its logical id.
1721 * On UNIX this is done using the XDG special user directories.
1722 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
1723 * falls back to `$HOME/Desktop` when XDG special user directories have
1724 * not been set up.
1726 * Depending on the platform, the user might be able to change the path
1727 * of the special directory without requiring the session to restart; GLib
1728 * will not reflect any change once the special directories are loaded.
1730 * Returns: (type filename): the path to the specified special directory, or
1731 * %NULL if the logical id was not found. The returned string is owned by
1732 * GLib and should not be modified or freed.
1734 * Since: 2.14
1736 const gchar *
1737 g_get_user_special_dir (GUserDirectory directory)
1739 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
1740 directory < G_USER_N_DIRECTORIES, NULL);
1742 G_LOCK (g_utils_global);
1744 if (G_UNLIKELY (g_user_special_dirs == NULL))
1746 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1748 load_user_special_dirs ();
1750 /* Special-case desktop for historical compatibility */
1751 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
1752 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = g_build_filename (g_get_home_dir (), "Desktop", NULL);
1755 G_UNLOCK (g_utils_global);
1757 return g_user_special_dirs[directory];
1760 #ifdef G_OS_WIN32
1762 #undef g_get_system_data_dirs
1764 static HMODULE
1765 get_module_for_address (gconstpointer address)
1767 /* Holds the g_utils_global lock */
1769 static gboolean beenhere = FALSE;
1770 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
1771 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
1772 HMODULE hmodule = NULL;
1774 if (!address)
1775 return NULL;
1777 if (!beenhere)
1779 p_GetModuleHandleExA =
1780 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1781 "GetModuleHandleExA");
1782 beenhere = TRUE;
1785 if (p_GetModuleHandleExA == NULL ||
1786 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
1787 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
1788 address, &hmodule))
1790 MEMORY_BASIC_INFORMATION mbi;
1791 VirtualQuery (address, &mbi, sizeof (mbi));
1792 hmodule = (HMODULE) mbi.AllocationBase;
1795 return hmodule;
1798 static gchar *
1799 get_module_share_dir (gconstpointer address)
1801 HMODULE hmodule;
1802 gchar *filename;
1803 gchar *retval;
1805 hmodule = get_module_for_address (address);
1806 if (hmodule == NULL)
1807 return NULL;
1809 filename = g_win32_get_package_installation_directory_of_module (hmodule);
1810 retval = g_build_filename (filename, "share", NULL);
1811 g_free (filename);
1813 return retval;
1816 static const gchar * const *
1817 g_win32_get_system_data_dirs_for_module_real (void (*address_of_function)(void))
1819 GArray *data_dirs;
1820 HMODULE hmodule;
1821 static GHashTable *per_module_data_dirs = NULL;
1822 gchar **retval;
1823 gchar *p;
1824 gchar *exe_root;
1826 hmodule = NULL;
1827 if (address_of_function)
1829 G_LOCK (g_utils_global);
1830 hmodule = get_module_for_address (address_of_function);
1831 if (hmodule != NULL)
1833 if (per_module_data_dirs == NULL)
1834 per_module_data_dirs = g_hash_table_new (NULL, NULL);
1835 else
1837 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
1839 if (retval != NULL)
1841 G_UNLOCK (g_utils_global);
1842 return (const gchar * const *) retval;
1848 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
1850 /* Documents and Settings\All Users\Application Data */
1851 p = get_special_folder (CSIDL_COMMON_APPDATA);
1852 if (p)
1853 g_array_append_val (data_dirs, p);
1855 /* Documents and Settings\All Users\Documents */
1856 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1857 if (p)
1858 g_array_append_val (data_dirs, p);
1860 /* Using the above subfolders of Documents and Settings perhaps
1861 * makes sense from a Windows perspective.
1863 * But looking at the actual use cases of this function in GTK+
1864 * and GNOME software, what we really want is the "share"
1865 * subdirectory of the installation directory for the package
1866 * our caller is a part of.
1868 * The address_of_function parameter, if non-NULL, points to a
1869 * function in the calling module. Use that to determine that
1870 * module's installation folder, and use its "share" subfolder.
1872 * Additionally, also use the "share" subfolder of the installation
1873 * locations of GLib and the .exe file being run.
1875 * To guard against none of the above being what is really wanted,
1876 * callers of this function should have Win32-specific code to look
1877 * up their installation folder themselves, and handle a subfolder
1878 * "share" of it in the same way as the folders returned from this
1879 * function.
1882 p = get_module_share_dir (address_of_function);
1883 if (p)
1884 g_array_append_val (data_dirs, p);
1886 if (glib_dll != NULL)
1888 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
1889 p = g_build_filename (glib_root, "share", NULL);
1890 if (p)
1891 g_array_append_val (data_dirs, p);
1892 g_free (glib_root);
1895 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
1896 p = g_build_filename (exe_root, "share", NULL);
1897 if (p)
1898 g_array_append_val (data_dirs, p);
1899 g_free (exe_root);
1901 retval = (gchar **) g_array_free (data_dirs, FALSE);
1903 if (address_of_function)
1905 if (hmodule != NULL)
1906 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
1907 G_UNLOCK (g_utils_global);
1910 return (const gchar * const *) retval;
1913 const gchar * const *
1914 g_win32_get_system_data_dirs_for_module (void (*address_of_function)(void))
1916 gboolean should_call_g_get_system_data_dirs;
1918 should_call_g_get_system_data_dirs = TRUE;
1919 /* These checks are the same as the ones that g_get_system_data_dirs() does.
1920 * Please keep them in sync.
1922 G_LOCK (g_utils_global);
1924 if (!g_system_data_dirs)
1926 const gchar *data_dirs = g_getenv ("XDG_DATA_DIRS");
1928 if (!data_dirs || !data_dirs[0])
1929 should_call_g_get_system_data_dirs = FALSE;
1932 G_UNLOCK (g_utils_global);
1934 /* There is a subtle difference between g_win32_get_system_data_dirs_for_module (NULL),
1935 * which is what GLib code can normally call,
1936 * and g_win32_get_system_data_dirs_for_module (&_g_win32_get_system_data_dirs),
1937 * which is what the inline function used by non-GLib code calls.
1938 * The former gets prefix relative to currently-running executable,
1939 * the latter - relative to the module that calls _g_win32_get_system_data_dirs()
1940 * (disguised as g_get_system_data_dirs()), which could be an executable or
1941 * a DLL that is located somewhere else.
1942 * This is why that inline function in gutils.h exists, and why we can't just
1943 * call g_get_system_data_dirs() from there - because we need to get the address
1944 * local to the non-GLib caller-module.
1948 * g_get_system_data_dirs() will fall back to calling
1949 * g_win32_get_system_data_dirs_for_module_real(NULL) if XDG_DATA_DIRS is NULL
1950 * or an empty string. The checks above ensure that we do not call it in such
1951 * cases and use the address_of_function that we've been given by the inline function.
1952 * The reason we're calling g_get_system_data_dirs /at all/ is to give
1953 * XDG_DATA_DIRS precedence (if it is set).
1955 if (should_call_g_get_system_data_dirs)
1956 return g_get_system_data_dirs ();
1958 return g_win32_get_system_data_dirs_for_module_real (address_of_function);
1961 #endif
1964 * g_get_system_data_dirs:
1966 * Returns an ordered list of base directories in which to access
1967 * system-wide application data.
1969 * On UNIX platforms this is determined using the mechanisms described
1970 * in the
1971 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec)
1972 * In this case the list of directories retrieved will be `XDG_DATA_DIRS`.
1974 * On Windows it follows XDG Base Directory Specification if `XDG_DATA_DIRS` is defined.
1975 * If `XDG_DATA_DIRS` is undefined,
1976 * the first elements in the list are the Application Data
1977 * and Documents folders for All Users. (These can be determined only
1978 * on Windows 2000 or later and are not present in the list on other
1979 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
1980 * CSIDL_COMMON_DOCUMENTS.
1982 * Then follows the "share" subfolder in the installation folder for
1983 * the package containing the DLL that calls this function, if it can
1984 * be determined.
1986 * Finally the list contains the "share" subfolder in the installation
1987 * folder for GLib, and in the installation folder for the package the
1988 * application's .exe file belongs to.
1990 * The installation folders above are determined by looking up the
1991 * folder where the module (DLL or EXE) in question is located. If the
1992 * folder's name is "bin", its parent is used, otherwise the folder
1993 * itself.
1995 * Note that on Windows the returned list can vary depending on where
1996 * this function is called.
1998 * Returns: (array zero-terminated=1) (element-type filename) (transfer none):
1999 * a %NULL-terminated array of strings owned by GLib that must not be
2000 * modified or freed.
2002 * Since: 2.6
2004 const gchar * const *
2005 g_get_system_data_dirs (void)
2007 gchar **data_dir_vector;
2009 /* These checks are the same as the ones that g_win32_get_system_data_dirs_for_module()
2010 * does. Please keep them in sync.
2012 G_LOCK (g_utils_global);
2014 if (!g_system_data_dirs)
2016 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2018 #ifndef G_OS_WIN32
2019 if (!data_dirs || !data_dirs[0])
2020 data_dirs = "/usr/local/share/:/usr/share/";
2022 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2023 #else
2024 if (!data_dirs || !data_dirs[0])
2025 data_dir_vector = g_strdupv ((gchar **) g_win32_get_system_data_dirs_for_module_real (NULL));
2026 else
2027 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2028 #endif
2030 g_system_data_dirs = data_dir_vector;
2032 else
2033 data_dir_vector = g_system_data_dirs;
2035 G_UNLOCK (g_utils_global);
2037 return (const gchar * const *) data_dir_vector;
2041 * g_get_system_config_dirs:
2043 * Returns an ordered list of base directories in which to access
2044 * system-wide configuration information.
2046 * On UNIX platforms this is determined using the mechanisms described
2047 * in the
2048 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2049 * In this case the list of directories retrieved will be `XDG_CONFIG_DIRS`.
2051 * On Windows it follows XDG Base Directory Specification if `XDG_CONFIG_DIRS` is defined.
2052 * If `XDG_CONFIG_DIRS` is undefined, the directory that contains application
2053 * data for all users is used instead. A typical path is
2054 * `C:\Documents and Settings\All Users\Application Data`.
2055 * This folder is used for application data
2056 * that is not user specific. For example, an application can store
2057 * a spell-check dictionary, a database of clip art, or a log file in the
2058 * CSIDL_COMMON_APPDATA folder. This information will not roam and is available
2059 * to anyone using the computer.
2061 * Returns: (array zero-terminated=1) (element-type filename) (transfer none):
2062 * a %NULL-terminated array of strings owned by GLib that must not be
2063 * modified or freed.
2065 * Since: 2.6
2067 const gchar * const *
2068 g_get_system_config_dirs (void)
2070 gchar **conf_dir_vector;
2072 G_LOCK (g_utils_global);
2074 if (!g_system_config_dirs)
2076 const gchar *conf_dirs = g_getenv ("XDG_CONFIG_DIRS");
2077 #ifdef G_OS_WIN32
2078 if (conf_dirs)
2080 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2082 else
2084 gchar *special_conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2086 if (special_conf_dirs)
2087 conf_dir_vector = g_strsplit (special_conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2088 else
2089 /* Return empty list */
2090 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2092 g_free (special_conf_dirs);
2094 #else
2095 if (!conf_dirs || !conf_dirs[0])
2096 conf_dirs = "/etc/xdg";
2098 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2099 #endif
2101 g_system_config_dirs = conf_dir_vector;
2103 else
2104 conf_dir_vector = g_system_config_dirs;
2105 G_UNLOCK (g_utils_global);
2107 return (const gchar * const *) conf_dir_vector;
2111 * g_nullify_pointer:
2112 * @nullify_location: (not nullable): the memory address of the pointer.
2114 * Set the pointer at the specified location to %NULL.
2116 void
2117 g_nullify_pointer (gpointer *nullify_location)
2119 g_return_if_fail (nullify_location != NULL);
2121 *nullify_location = NULL;
2124 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2125 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2126 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2127 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2128 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2129 #define EXABYTE_FACTOR (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2131 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2132 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2133 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2134 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2135 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2136 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2139 * g_format_size:
2140 * @size: a size in bytes
2142 * Formats a size (for example the size of a file) into a human readable
2143 * string. Sizes are rounded to the nearest size prefix (kB, MB, GB)
2144 * and are displayed rounded to the nearest tenth. E.g. the file size
2145 * 3292528 bytes will be converted into the string "3.2 MB".
2147 * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2149 * This string should be freed with g_free() when not needed any longer.
2151 * See g_format_size_full() for more options about how the size might be
2152 * formatted.
2154 * Returns: a newly-allocated formatted string containing a human readable
2155 * file size
2157 * Since: 2.30
2159 gchar *
2160 g_format_size (guint64 size)
2162 return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2166 * GFormatSizeFlags:
2167 * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2168 * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2169 * of the returned string. For example, "45.6 kB (45,612 bytes)".
2170 * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2171 * suffixes. IEC units should only be used for reporting things with
2172 * a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2173 * Network and storage sizes should be reported in the normal SI units.
2175 * Flags to modify the format of the string returned by g_format_size_full().
2178 #pragma GCC diagnostic push
2179 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
2182 * g_format_size_full:
2183 * @size: a size in bytes
2184 * @flags: #GFormatSizeFlags to modify the output
2186 * Formats a size.
2188 * This function is similar to g_format_size() but allows for flags
2189 * that modify the output. See #GFormatSizeFlags.
2191 * Returns: a newly-allocated formatted string containing a human
2192 * readable file size
2194 * Since: 2.30
2196 gchar *
2197 g_format_size_full (guint64 size,
2198 GFormatSizeFlags flags)
2200 GString *string;
2202 string = g_string_new (NULL);
2204 if (flags & G_FORMAT_SIZE_IEC_UNITS)
2206 if (size < KIBIBYTE_FACTOR)
2208 g_string_printf (string,
2209 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2210 (guint) size);
2211 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2214 else if (size < MEBIBYTE_FACTOR)
2215 g_string_printf (string, _("%.1f KiB"), (gdouble) size / (gdouble) KIBIBYTE_FACTOR);
2216 else if (size < GIBIBYTE_FACTOR)
2217 g_string_printf (string, _("%.1f MiB"), (gdouble) size / (gdouble) MEBIBYTE_FACTOR);
2219 else if (size < TEBIBYTE_FACTOR)
2220 g_string_printf (string, _("%.1f GiB"), (gdouble) size / (gdouble) GIBIBYTE_FACTOR);
2222 else if (size < PEBIBYTE_FACTOR)
2223 g_string_printf (string, _("%.1f TiB"), (gdouble) size / (gdouble) TEBIBYTE_FACTOR);
2225 else if (size < EXBIBYTE_FACTOR)
2226 g_string_printf (string, _("%.1f PiB"), (gdouble) size / (gdouble) PEBIBYTE_FACTOR);
2228 else
2229 g_string_printf (string, _("%.1f EiB"), (gdouble) size / (gdouble) EXBIBYTE_FACTOR);
2231 else
2233 if (size < KILOBYTE_FACTOR)
2235 g_string_printf (string,
2236 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2237 (guint) size);
2238 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2241 else if (size < MEGABYTE_FACTOR)
2242 g_string_printf (string, _("%.1f kB"), (gdouble) size / (gdouble) KILOBYTE_FACTOR);
2244 else if (size < GIGABYTE_FACTOR)
2245 g_string_printf (string, _("%.1f MB"), (gdouble) size / (gdouble) MEGABYTE_FACTOR);
2247 else if (size < TERABYTE_FACTOR)
2248 g_string_printf (string, _("%.1f GB"), (gdouble) size / (gdouble) GIGABYTE_FACTOR);
2249 else if (size < PETABYTE_FACTOR)
2250 g_string_printf (string, _("%.1f TB"), (gdouble) size / (gdouble) TERABYTE_FACTOR);
2252 else if (size < EXABYTE_FACTOR)
2253 g_string_printf (string, _("%.1f PB"), (gdouble) size / (gdouble) PETABYTE_FACTOR);
2255 else
2256 g_string_printf (string, _("%.1f EB"), (gdouble) size / (gdouble) EXABYTE_FACTOR);
2259 if (flags & G_FORMAT_SIZE_LONG_FORMAT)
2261 /* First problem: we need to use the number of bytes to decide on
2262 * the plural form that is used for display, but the number of
2263 * bytes potentially exceeds the size of a guint (which is what
2264 * ngettext() takes).
2266 * From a pragmatic standpoint, it seems that all known languages
2267 * base plural forms on one or both of the following:
2269 * - the lowest digits of the number
2271 * - if the number if greater than some small value
2273 * Here's how we fake it: Draw an arbitrary line at one thousand.
2274 * If the number is below that, then fine. If it is above it,
2275 * then we take the modulus of the number by one thousand (in
2276 * order to keep the lowest digits) and add one thousand to that
2277 * (in order to ensure that 1001 is not treated the same as 1).
2279 guint plural_form = size < 1000 ? size : size % 1000 + 1000;
2281 /* Second problem: we need to translate the string "%u byte" and
2282 * "%u bytes" for pluralisation, but the correct number format to
2283 * use for a gsize is different depending on which architecture
2284 * we're on.
2286 * Solution: format the number separately and use "%s bytes" on
2287 * all platforms.
2289 const gchar *translated_format;
2290 gchar *formatted_number;
2292 /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2293 translated_format = g_dngettext(GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
2294 /* XXX: Windows doesn't support the "'" format modifier, so we
2295 * must not use it there. Instead, just display the number
2296 * without separation. Bug #655336 is open until a solution is
2297 * found.
2299 #ifndef G_OS_WIN32
2300 formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2301 #else
2302 formatted_number = g_strdup_printf ("%"G_GUINT64_FORMAT, size);
2303 #endif
2305 g_string_append (string, " (");
2306 g_string_append_printf (string, translated_format, formatted_number);
2307 g_free (formatted_number);
2308 g_string_append (string, ")");
2311 return g_string_free (string, FALSE);
2314 #pragma GCC diagnostic pop
2317 * g_format_size_for_display:
2318 * @size: a size in bytes
2320 * Formats a size (for example the size of a file) into a human
2321 * readable string. Sizes are rounded to the nearest size prefix
2322 * (KB, MB, GB) and are displayed rounded to the nearest tenth.
2323 * E.g. the file size 3292528 bytes will be converted into the
2324 * string "3.1 MB".
2326 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2328 * This string should be freed with g_free() when not needed any longer.
2330 * Returns: a newly-allocated formatted string containing a human
2331 * readable file size
2333 * Since: 2.16
2335 * Deprecated:2.30: This function is broken due to its use of SI
2336 * suffixes to denote IEC units. Use g_format_size() instead.
2338 gchar *
2339 g_format_size_for_display (goffset size)
2341 if (size < (goffset) KIBIBYTE_FACTOR)
2342 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
2343 else
2345 gdouble displayed_size;
2347 if (size < (goffset) MEBIBYTE_FACTOR)
2349 displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
2350 /* Translators: this is from the deprecated function g_format_size_for_display() which uses 'KB' to
2351 * mean 1024 bytes. I am aware that 'KB' is not correct, but it has been preserved for reasons of
2352 * compatibility. Users will not see this string unless a program is using this deprecated function.
2353 * Please translate as literally as possible.
2355 return g_strdup_printf (_("%.1f KB"), displayed_size);
2357 else if (size < (goffset) GIBIBYTE_FACTOR)
2359 displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
2360 return g_strdup_printf (_("%.1f MB"), displayed_size);
2362 else if (size < (goffset) TEBIBYTE_FACTOR)
2364 displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
2365 return g_strdup_printf (_("%.1f GB"), displayed_size);
2367 else if (size < (goffset) PEBIBYTE_FACTOR)
2369 displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
2370 return g_strdup_printf (_("%.1f TB"), displayed_size);
2372 else if (size < (goffset) EXBIBYTE_FACTOR)
2374 displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
2375 return g_strdup_printf (_("%.1f PB"), displayed_size);
2377 else
2379 displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
2380 return g_strdup_printf (_("%.1f EB"), displayed_size);
2385 #if defined (G_OS_WIN32) && !defined (_WIN64)
2387 /* Binary compatibility versions. Not for newly compiled code. */
2389 _GLIB_EXTERN const gchar *g_get_user_name_utf8 (void);
2390 _GLIB_EXTERN const gchar *g_get_real_name_utf8 (void);
2391 _GLIB_EXTERN const gchar *g_get_home_dir_utf8 (void);
2392 _GLIB_EXTERN const gchar *g_get_tmp_dir_utf8 (void);
2393 _GLIB_EXTERN gchar *g_find_program_in_path_utf8 (const gchar *program);
2395 gchar *
2396 g_find_program_in_path_utf8 (const gchar *program)
2398 return g_find_program_in_path (program);
2401 const gchar *g_get_user_name_utf8 (void) { return g_get_user_name (); }
2402 const gchar *g_get_real_name_utf8 (void) { return g_get_real_name (); }
2403 const gchar *g_get_home_dir_utf8 (void) { return g_get_home_dir (); }
2404 const gchar *g_get_tmp_dir_utf8 (void) { return g_get_tmp_dir (); }
2406 #endif
2408 /* Private API:
2410 * Returns %TRUE if the current process was executed as setuid (or an
2411 * equivalent __libc_enable_secure is available). See:
2412 * http://osdir.com/ml/linux.lfs.hardened/2007-04/msg00032.html
2414 gboolean
2415 g_check_setuid (void)
2417 /* TODO: get __libc_enable_secure exported from glibc.
2418 * See http://www.openwall.com/lists/owl-dev/2012/08/14/1
2420 #if 0 && defined(HAVE_LIBC_ENABLE_SECURE)
2422 /* See glibc/include/unistd.h */
2423 extern int __libc_enable_secure;
2424 return __libc_enable_secure;
2426 #elif defined(HAVE_ISSETUGID) && !defined(__BIONIC__)
2427 /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
2429 /* Android had it in older versions but the new 64 bit ABI does not
2430 * have it anymore, and some versions of the 32 bit ABI neither.
2431 * https://code.google.com/p/android-developer-preview/issues/detail?id=168
2433 return issetugid ();
2434 #elif defined(G_OS_UNIX)
2435 uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
2436 gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
2438 static gsize check_setuid_initialised;
2439 static gboolean is_setuid;
2441 if (g_once_init_enter (&check_setuid_initialised))
2443 #ifdef HAVE_GETRESUID
2444 /* These aren't in the header files, so we prototype them here.
2446 int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
2447 int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);
2449 if (getresuid (&ruid, &euid, &suid) != 0 ||
2450 getresgid (&rgid, &egid, &sgid) != 0)
2451 #endif /* HAVE_GETRESUID */
2453 suid = ruid = getuid ();
2454 sgid = rgid = getgid ();
2455 euid = geteuid ();
2456 egid = getegid ();
2459 is_setuid = (ruid != euid || ruid != suid ||
2460 rgid != egid || rgid != sgid);
2462 g_once_init_leave (&check_setuid_initialised, 1);
2464 return is_setuid;
2465 #else
2466 return FALSE;
2467 #endif
2470 #ifdef G_OS_WIN32
2472 * g_abort:
2474 * A wrapper for the POSIX abort() function.
2476 * On Windows it is a function that makes extra effort (including a call
2477 * to abort()) to ensure that a debugger-catchable exception is thrown
2478 * before the program terminates.
2480 * See your C library manual for more details about abort().
2482 * Since: 2.50
2484 void
2485 g_abort (void)
2487 /* One call to break the debugger */
2488 DebugBreak ();
2489 /* One call in case CRT does get saner about abort() behaviour */
2490 abort ();
2491 /* And one call to bind them all and terminate the program for sure */
2492 ExitProcess (127);
2494 #endif