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/.
26 * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
32 #include "gutilsprivate.h"
39 #include <ctype.h> /* For tolower() */
41 #include <sys/types.h>
47 #include <sys/types.h>
48 #ifdef HAVE_SYS_PARAM_H
49 #include <sys/param.h>
51 #ifdef HAVE_CRT_EXTERNS_H
52 #include <crt_externs.h> /* for _NSGetEnviron */
54 #ifdef HAVE_SYS_AUXV_H
58 #include "glib-init.h"
59 #include "glib-private.h"
61 #include "gfileutils.h"
65 #include "gtestutils.h"
67 #include "gstrfuncs.h"
72 #ifdef G_PLATFORM_WIN32
80 * @title: Miscellaneous Utility Functions
81 * @short_description: a selection of portable utility functions
83 * These are portable utility functions.
86 #ifdef G_PLATFORM_WIN32
88 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
89 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
90 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
92 # include <lmcons.h> /* For UNLEN */
93 #endif /* G_PLATFORM_WIN32 */
102 #include <langinfo.h>
105 #ifdef G_PLATFORM_WIN32
108 _glib_get_dll_directory (void)
112 wchar_t wc_fn[MAX_PATH];
115 if (glib_dll == NULL)
119 /* This code is different from that in
120 * g_win32_get_package_installation_directory_of_module() in that
121 * here we return the actual folder where the GLib DLL is. We don't
122 * do the check for it being in a "bin" or "lib" subfolder and then
123 * returning the parent of that.
125 * In a statically built GLib, glib_dll will be NULL and we will
126 * thus look up the application's .exe file's location.
128 if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
131 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
133 p = strrchr (retval, G_DIR_SEPARATOR);
148 * @dest: the destination address to copy the bytes to.
149 * @src: the source address to copy the bytes from.
150 * @len: the number of bytes to copy.
152 * Copies a block of memory @len bytes long, from @src to @dest.
153 * The source and destination areas may overlap.
155 * Deprecated:2.40: Just use memmove().
164 * @func: (scope async): the function to call on normal program termination.
166 * Specifies a function to be called at normal program termination.
168 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
169 * macro that maps to a call to the atexit() function in the C
170 * library. This means that in case the code that calls g_atexit(),
171 * i.e. atexit(), is in a DLL, the function will be called when the
172 * DLL is detached from the program. This typically makes more sense
173 * than that the function is called when the GLib DLL is detached,
174 * which happened earlier when g_atexit() was a function in the GLib
177 * The behaviour of atexit() in the context of dynamically loaded
178 * modules is not formally specified and varies wildly.
180 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
181 * loaded module which is unloaded before the program terminates might
182 * well cause a crash at program exit.
184 * Some POSIX systems implement atexit() like Windows, and have each
185 * dynamically loaded module maintain an own atexit chain that is
186 * called when the module is unloaded.
188 * On other POSIX systems, before a dynamically loaded module is
189 * unloaded, the registered atexit functions (if any) residing in that
190 * module are called, regardless where the code that registered them
191 * resided. This is presumably the most robust approach.
193 * As can be seen from the above, for portability it's best to avoid
194 * calling g_atexit() (or atexit()) except in the main executable of a
197 * Deprecated:2.32: It is best to avoid g_atexit().
199 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
201 g_atexit (GVoidFunc func)
206 result = atexit ((void (*)(void)) func);
210 g_error ("Could not register atexit() function: %s",
214 G_GNUC_END_IGNORE_DEPRECATIONS
216 /* Based on execvp() from GNU Libc.
217 * Some of this code is cut-and-pasted into gspawn.c
221 my_strchrnul (const gchar *str,
224 gchar *p = (gchar*)str;
225 while (*p && (*p != c))
233 static gchar *inner_find_program_in_path (const gchar *program);
236 g_find_program_in_path (const gchar *program)
238 const gchar *last_dot = strrchr (program, '.');
240 if (last_dot == NULL ||
241 strchr (last_dot, '\\') != NULL ||
242 strchr (last_dot, '/') != NULL)
244 const gint program_length = strlen (program);
245 gchar *pathext = g_build_path (";",
246 ".exe;.cmd;.bat;.com",
247 g_getenv ("PATHEXT"),
250 gchar *decorated_program;
256 gchar *q = my_strchrnul (p, ';');
258 decorated_program = g_malloc (program_length + (q-p) + 1);
259 memcpy (decorated_program, program, program_length);
260 memcpy (decorated_program+program_length, p, q-p);
261 decorated_program [program_length + (q-p)] = '\0';
263 retval = inner_find_program_in_path (decorated_program);
264 g_free (decorated_program);
272 } while (*p++ != '\0');
277 return inner_find_program_in_path (program);
283 * g_find_program_in_path:
284 * @program: (type filename): a program name in the GLib file name encoding
286 * Locates the first executable named @program in the user's path, in the
287 * same way that execvp() would locate it. Returns an allocated string
288 * with the absolute path name, or %NULL if the program is not found in
289 * the path. If @program is already an absolute path, returns a copy of
290 * @program if @program exists and is executable, and %NULL otherwise.
292 * On Windows, if @program does not have a file type suffix, tries
293 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
294 * the `PATHEXT` environment variable.
296 * On Windows, it looks for the file in the same way as CreateProcess()
297 * would. This means first in the directory where the executing
298 * program was loaded from, then in the current directory, then in the
299 * Windows 32-bit system directory, then in the Windows directory, and
300 * finally in the directories in the `PATH` environment variable. If
301 * the program is found, the return value contains the full name
302 * including the type suffix.
304 * Returns: (type filename): a newly-allocated string with the absolute path,
309 inner_find_program_in_path (const gchar *program)
312 g_find_program_in_path (const gchar *program)
315 const gchar *path, *p;
316 gchar *name, *freeme;
318 const gchar *path_copy;
319 gchar *filename = NULL, *appdir = NULL;
320 gchar *sysdir = NULL, *windir = NULL;
322 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
328 g_return_val_if_fail (program != NULL, NULL);
330 /* If it is an absolute path, or a relative path including subdirectories,
331 * don't look in PATH.
333 if (g_path_is_absolute (program)
334 || strchr (program, G_DIR_SEPARATOR) != NULL
336 || strchr (program, '/') != NULL
340 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
341 !g_file_test (program, G_FILE_TEST_IS_DIR))
342 return g_strdup (program);
347 path = g_getenv ("PATH");
348 #if defined(G_OS_UNIX)
351 /* There is no 'PATH' in the environment. The default
352 * search path in GNU libc is the current directory followed by
353 * the path 'confstr' returns for '_CS_PATH'.
356 /* In GLib we put . last, for security, and don't use the
357 * unportable confstr(); UNIX98 does not actually specify
358 * what to search if PATH is unset. POSIX may, dunno.
361 path = "/bin:/usr/bin:.";
364 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
365 if (n > 0 && n < MAXPATHLEN)
366 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
368 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
369 if (n > 0 && n < MAXPATHLEN)
370 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
372 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
373 if (n > 0 && n < MAXPATHLEN)
374 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
378 appdir = g_path_get_dirname (filename);
382 path = g_strdup (path);
386 const gchar *tem = path;
387 path = g_strconcat (windir, ";", path, NULL);
388 g_free ((gchar *) tem);
394 const gchar *tem = path;
395 path = g_strconcat (sysdir, ";", path, NULL);
396 g_free ((gchar *) tem);
401 const gchar *tem = path;
402 path = g_strconcat (".;", path, NULL);
403 g_free ((gchar *) tem);
408 const gchar *tem = path;
409 path = g_strconcat (appdir, ";", path, NULL);
410 g_free ((gchar *) tem);
417 len = strlen (program) + 1;
418 pathlen = strlen (path);
419 freeme = name = g_malloc (pathlen + len + 1);
421 /* Copy the file name at the top, including '\0' */
422 memcpy (name + pathlen + 1, program, len);
423 name = name + pathlen;
424 /* And add the slash before the filename */
425 *name = G_DIR_SEPARATOR;
433 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
436 /* Two adjacent colons, or a colon at the beginning or the end
437 * of 'PATH' means to search the current directory.
441 startp = memcpy (name - (p - path), path, p - path);
443 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
444 !g_file_test (startp, G_FILE_TEST_IS_DIR))
447 ret = g_strdup (startp);
450 g_free ((gchar *) path_copy);
455 while (*p++ != '\0');
459 g_free ((gchar *) path_copy);
465 /* The functions below are defined this way for compatibility reasons.
466 * See the note in gutils.h.
471 * @mask: a #gulong containing flags
472 * @nth_bit: the index of the bit to start the search from
474 * Find the position of the first bit set in @mask, searching
475 * from (but not including) @nth_bit upwards. Bits are numbered
476 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
477 * usually). To start searching from the 0th bit, set @nth_bit to -1.
479 * Returns: the index of the first bit set which is higher than @nth_bit, or -1
480 * if no higher bits are set
483 (g_bit_nth_lsf) (gulong mask,
486 return g_bit_nth_lsf_impl (mask, nth_bit);
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 downwards. Bits are numbered
496 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
497 * usually). To start searching from the last bit, set @nth_bit to
498 * -1 or GLIB_SIZEOF_LONG * 8.
500 * Returns: the index of the first bit set which is lower than @nth_bit, or -1
501 * if no lower bits are set
504 (g_bit_nth_msf) (gulong mask,
507 return g_bit_nth_msf_impl (mask, nth_bit);
515 * Gets the number of bits used to hold @number,
516 * e.g. if @number is 4, 3 bits are needed.
518 * Returns: the number of bits used to hold @number
521 (g_bit_storage) (gulong number)
523 return g_bit_storage_impl (number);
526 G_LOCK_DEFINE_STATIC (g_utils_global);
535 /* These must all be read/written with @g_utils_global held. */
536 static gchar *g_user_data_dir = NULL;
537 static gchar **g_system_data_dirs = NULL;
538 static gchar *g_user_cache_dir = NULL;
539 static gchar *g_user_config_dir = NULL;
540 static gchar *g_user_runtime_dir = NULL;
541 static gchar **g_system_config_dirs = NULL;
542 static gchar **g_user_special_dirs = NULL;
544 /* fifteen minutes of fame for everybody */
545 #define G_USER_DIRS_EXPIRE 15 * 60
550 get_special_folder (int csidl)
552 wchar_t path[MAX_PATH+1];
554 LPITEMIDLIST pidl = NULL;
556 gchar *retval = NULL;
558 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
561 b = SHGetPathFromIDListW (pidl, path);
563 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
564 CoTaskMemFree (pidl);
570 get_windows_directory_root (void)
572 wchar_t wwindowsdir[MAX_PATH];
574 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
576 /* Usually X:\Windows, but in terminal server environments
577 * might be an UNC path, AFAIK.
579 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
582 if (windowsdir == NULL)
583 return g_strdup ("C:\\");
585 p = (char *) g_path_skip_root (windowsdir);
586 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
592 return g_strdup ("C:\\");
597 /* HOLDS: g_utils_global_lock */
598 static UserDatabaseEntry *
599 g_get_user_database_entry (void)
601 static UserDatabaseEntry *entry;
603 if (g_once_init_enter (&entry))
605 static UserDatabaseEntry e;
609 struct passwd *pw = NULL;
610 gpointer buffer = NULL;
614 # if defined (HAVE_GETPWUID_R)
616 # ifdef _SC_GETPW_R_SIZE_MAX
617 /* This reurns the maximum length */
618 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
622 # else /* _SC_GETPW_R_SIZE_MAX */
624 # endif /* _SC_GETPW_R_SIZE_MAX */
626 logname = (gchar *) g_getenv ("LOGNAME");
631 /* we allocate 6 extra bytes to work around a bug in
632 * Mac OS < 10.3. See #156446
634 buffer = g_malloc (bufsize + 6);
638 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
639 if (!pw || (pw->pw_uid != getuid ())) {
640 /* LOGNAME is lying, fall back to looking up the uid */
641 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
644 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
646 error = error < 0 ? errno : error;
650 /* we bail out prematurely if the user id can't be found
651 * (should be pretty rare case actually), or if the buffer
652 * should be sufficiently big and lookups are still not
655 if (error == 0 || error == ENOENT)
657 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
661 if (bufsize > 32 * 1024)
663 g_warning ("getpwuid_r(): failed due to: %s.",
672 # endif /* HAVE_GETPWUID_R */
676 pw = getpwuid (getuid ());
680 e.user_name = g_strdup (pw->pw_name);
683 if (pw->pw_gecos && *pw->pw_gecos != '\0')
685 gchar **gecos_fields;
688 /* split the gecos field and substitute '&' */
689 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
690 name_parts = g_strsplit (gecos_fields[0], "&", 0);
691 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
692 e.real_name = g_strjoinv (pw->pw_name, name_parts);
693 g_strfreev (gecos_fields);
694 g_strfreev (name_parts);
699 e.home_dir = g_strdup (pw->pw_dir);
704 #endif /* G_OS_UNIX */
709 wchar_t buffer[UNLEN+1];
711 if (GetUserNameW (buffer, (LPDWORD) &len))
713 e.user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
714 e.real_name = g_strdup (e.user_name);
717 #endif /* G_OS_WIN32 */
720 e.user_name = g_strdup ("somebody");
722 e.real_name = g_strdup ("Unknown");
724 g_once_init_leave (&entry, &e);
733 * Gets the user name of the current user. The encoding of the returned
734 * string is system-defined. On UNIX, it might be the preferred file name
735 * encoding, or something else, and there is no guarantee that it is even
736 * consistent on a machine. On Windows, it is always UTF-8.
738 * Returns: (type filename): the user name of the current user.
741 g_get_user_name (void)
743 UserDatabaseEntry *entry;
745 entry = g_get_user_database_entry ();
747 return entry->user_name;
753 * Gets the real name of the user. This usually comes from the user's
754 * entry in the `passwd` file. The encoding of the returned string is
755 * system-defined. (On Windows, it is, however, always UTF-8.) If the
756 * real user name cannot be determined, the string "Unknown" is
759 * Returns: (type filename): the user's real name.
762 g_get_real_name (void)
764 UserDatabaseEntry *entry;
766 entry = g_get_user_database_entry ();
768 return entry->real_name;
771 /* Protected by @g_utils_global_lock. */
772 static gchar *g_home_dir = NULL; /* (owned) (nullable before initialised) */
775 g_build_home_dir (void)
779 /* We first check HOME and use it if it is set */
780 home_dir = g_strdup (g_getenv ("HOME"));
783 /* Only believe HOME if it is an absolute path and exists.
785 * We only do this check on Windows for a couple of reasons.
786 * Historically, we only did it there because we used to ignore $HOME
787 * on UNIX. There are concerns about enabling it now on UNIX because
788 * of things like autofs. In short, if the user has a bogus value in
789 * $HOME then they get what they pay for...
791 if (home_dir != NULL)
793 if (!(g_path_is_absolute (home_dir) &&
794 g_file_test (home_dir, G_FILE_TEST_IS_DIR)))
795 g_clear_pointer (&home_dir, g_free);
798 /* In case HOME is Unix-style (it happens), convert it to
801 if (home_dir != NULL)
804 while ((p = strchr (home_dir, '/')) != NULL)
808 if (home_dir == NULL)
810 /* USERPROFILE is probably the closest equivalent to $HOME? */
811 if (g_getenv ("USERPROFILE") != NULL)
812 home_dir = g_strdup (g_getenv ("USERPROFILE"));
815 if (home_dir == NULL)
816 home_dir = get_special_folder (CSIDL_PROFILE);
818 if (home_dir == NULL)
819 home_dir = get_windows_directory_root ();
820 #endif /* G_OS_WIN32 */
822 if (home_dir == NULL)
824 /* If we didn't get it from any of those methods, we will have
825 * to read the user database entry.
827 UserDatabaseEntry *entry = g_get_user_database_entry ();
828 home_dir = g_strdup (entry->home_dir);
831 /* If we have been denied access to /etc/passwd (for example, by an
832 * overly-zealous LSM), make up a junk value. The return value at this
833 * point is explicitly documented as ‘undefined’. */
834 if (home_dir == NULL)
836 g_warning ("Could not find home directory: $HOME is not set, and "
837 "user database could not be read.");
838 home_dir = g_strdup ("/");
841 return g_steal_pointer (&home_dir);
847 * Gets the current user's home directory.
849 * As with most UNIX tools, this function will return the value of the
850 * `HOME` environment variable if it is set to an existing absolute path
851 * name, falling back to the `passwd` file in the case that it is unset.
853 * If the path given in `HOME` is non-absolute, does not exist, or is
854 * not a directory, the result is undefined.
856 * Before version 2.36 this function would ignore the `HOME` environment
857 * variable, taking the value from the `passwd` database instead. This was
858 * changed to increase the compatibility of GLib with other programs (and
859 * the XDG basedir specification) and to increase testability of programs
860 * based on GLib (by making it easier to run them from test frameworks).
862 * If your program has a strong requirement for either the new or the
863 * old behaviour (and if you don't wish to increase your GLib
864 * dependency to ensure that the new behaviour is in effect) then you
865 * should either directly check the `HOME` environment variable yourself
866 * or unset it before calling any functions in GLib.
868 * Returns: (type filename): the current user's home directory
871 g_get_home_dir (void)
873 const gchar *home_dir;
875 G_LOCK (g_utils_global);
877 if (g_home_dir == NULL)
878 g_home_dir = g_build_home_dir ();
879 home_dir = g_home_dir;
881 G_UNLOCK (g_utils_global);
889 * Gets the directory to use for temporary files.
891 * On UNIX, this is taken from the `TMPDIR` environment variable.
892 * If the variable is not set, `P_tmpdir` is
893 * used, as defined by the system C library. Failing that, a
894 * hard-coded default of "/tmp" is returned.
896 * On Windows, the `TEMP` environment variable is used, with the
897 * root directory of the Windows installation (eg: "C:\") used
900 * The encoding of the returned string is system-defined. On Windows,
901 * it is always UTF-8. The return value is never %NULL or the empty
904 * Returns: (type filename): the directory to use for temporary files.
909 static gchar *tmp_dir;
911 if (g_once_init_enter (&tmp_dir))
916 tmp = g_strdup (g_getenv ("TEMP"));
918 if (tmp == NULL || *tmp == '\0')
921 tmp = get_windows_directory_root ();
923 #else /* G_OS_WIN32 */
924 tmp = g_strdup (g_getenv ("TMPDIR"));
927 if (tmp == NULL || *tmp == '\0')
931 tmp = g_strdup (P_tmpdir);
933 if (k > 1 && G_IS_DIR_SEPARATOR (tmp[k - 1]))
936 #endif /* P_tmpdir */
938 if (tmp == NULL || *tmp == '\0')
941 tmp = g_strdup ("/tmp");
943 #endif /* !G_OS_WIN32 */
945 g_once_init_leave (&tmp_dir, tmp);
954 * Return a name for the machine.
956 * The returned name is not necessarily a fully-qualified domain name,
957 * or even present in DNS or some other name service at all. It need
958 * not even be unique on your local network or site, but usually it
959 * is. Callers should not rely on the return value having any specific
960 * properties like uniqueness for security purposes. Even if the name
961 * of the machine is changed while an application is running, the
962 * return value from this function does not change. The returned
963 * string is owned by GLib and should not be modified or freed. If no
964 * name can be determined, a default fixed string "localhost" is
967 * The encoding of the returned string is UTF-8.
969 * Returns: the host name of the machine.
974 g_get_host_name (void)
976 static gchar *hostname;
978 if (g_once_init_enter (&hostname))
986 /* The number 256 * 256 is taken from the value of _POSIX_HOST_NAME_MAX,
987 * which is 255. Since we use _POSIX_HOST_NAME_MAX + 1 (= 256) in the
988 * fallback case, we pick 256 * 256 as the size of the larger buffer here.
989 * It should be large enough. It doesn't looks reasonable to name a host
990 * with a string that is longer than 64 KiB.
992 const gsize size_large = (gsize) 256 * 256;
995 max = sysconf (_SC_HOST_NAME_MAX);
996 if (max > 0 && max <= G_MAXSIZE - 1)
997 size = (gsize) max + 1;
1000 size = HOST_NAME_MAX + 1;
1002 size = _POSIX_HOST_NAME_MAX + 1;
1005 tmp = g_malloc (size);
1006 failed = (gethostname (tmp, size) == -1);
1007 if (failed && size < size_large)
1009 /* Try again with a larger buffer if 'size' may be too small. */
1011 tmp = g_malloc (size_large);
1012 failed = (gethostname (tmp, size_large) == -1);
1016 g_clear_pointer (&tmp, g_free);
1019 wchar_t tmp[MAX_COMPUTERNAME_LENGTH + 1];
1020 DWORD size = sizeof (tmp) / sizeof (tmp[0]);
1021 failed = (!GetComputerNameW (tmp, &size));
1023 utmp = g_utf16_to_utf8 (tmp, size, NULL, NULL, NULL);
1028 g_once_init_leave (&hostname, failed ? g_strdup ("localhost") : utmp);
1034 G_LOCK_DEFINE_STATIC (g_prgname);
1035 static gchar *g_prgname = NULL;
1040 * Gets the name of the program. This name should not be localized,
1041 * in contrast to g_get_application_name().
1043 * If you are using #GApplication the program name is set in
1044 * g_application_run(). In case of GDK or GTK+ it is set in
1045 * gdk_init(), which is called by gtk_init() and the
1046 * #GtkApplication::startup handler. The program name is found by
1047 * taking the last component of @argv[0].
1049 * Returns: (nullable): the name of the program, or %NULL if it has not been
1050 * set yet. The returned string belongs
1051 * to GLib and must not be modified or freed.
1054 g_get_prgname (void)
1060 G_UNLOCK (g_prgname);
1067 * @prgname: the name of the program.
1069 * Sets the name of the program. This name should not be localized,
1070 * in contrast to g_set_application_name().
1072 * If you are using #GApplication the program name is set in
1073 * g_application_run(). In case of GDK or GTK+ it is set in
1074 * gdk_init(), which is called by gtk_init() and the
1075 * #GtkApplication::startup handler. The program name is found by
1076 * taking the last component of @argv[0].
1078 * Note that for thread-safety reasons this function can only be called once.
1081 g_set_prgname (const gchar *prgname)
1085 g_prgname = g_strdup (prgname);
1086 G_UNLOCK (g_prgname);
1089 G_LOCK_DEFINE_STATIC (g_application_name);
1090 static gchar *g_application_name = NULL;
1093 * g_get_application_name:
1095 * Gets a human-readable name for the application, as set by
1096 * g_set_application_name(). This name should be localized if
1097 * possible, and is intended for display to the user. Contrast with
1098 * g_get_prgname(), which gets a non-localized name. If
1099 * g_set_application_name() has not been called, returns the result of
1100 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1103 * Returns: human-readable application name. may return %NULL
1108 g_get_application_name (void)
1112 G_LOCK (g_application_name);
1113 retval = g_application_name;
1114 G_UNLOCK (g_application_name);
1117 return g_get_prgname ();
1123 * g_set_application_name:
1124 * @application_name: localized name of the application
1126 * Sets a human-readable name for the application. This name should be
1127 * localized if possible, and is intended for display to the user.
1128 * Contrast with g_set_prgname(), which sets a non-localized name.
1129 * g_set_prgname() will be called automatically by gtk_init(),
1130 * but g_set_application_name() will not.
1132 * Note that for thread safety reasons, this function can only
1135 * The application name will be used in contexts such as error messages,
1136 * or when displaying an application's name in the task list.
1141 g_set_application_name (const gchar *application_name)
1143 gboolean already_set = FALSE;
1145 G_LOCK (g_application_name);
1146 if (g_application_name)
1149 g_application_name = g_strdup (application_name);
1150 G_UNLOCK (g_application_name);
1153 g_warning ("g_set_application_name() called multiple times");
1156 /* Set @global_str to a copy of @new_value if it’s currently unset or has a
1157 * different value. If its current value matches @new_value, do nothing. If
1158 * replaced, we have to leak the old value as client code could still have
1159 * pointers to it. */
1161 set_str_if_different (gchar **global_str,
1163 const gchar *new_value)
1165 if (*global_str == NULL ||
1166 !g_str_equal (new_value, *global_str))
1168 g_debug ("g_set_user_dirs: Setting %s to %s", type, new_value);
1170 /* We have to leak the old value, as user code could be retaining pointers
1172 *global_str = g_strdup (new_value);
1177 set_strv_if_different (gchar ***global_strv,
1179 const gchar * const *new_value)
1181 if (*global_strv == NULL ||
1182 !g_strv_equal (new_value, (const gchar * const *) *global_strv))
1184 gchar *new_value_str = g_strjoinv (":", (gchar **) new_value);
1185 g_debug ("g_set_user_dirs: Setting %s to %s", type, new_value_str);
1186 g_free (new_value_str);
1188 /* We have to leak the old value, as user code could be retaining pointers
1190 *global_strv = g_strdupv ((gchar **) new_value);
1196 * @first_dir_type: Type of the first directory to set
1197 * @...: Value to set the first directory to, followed by additional type/value
1198 * pairs, followed by %NULL
1200 * Set one or more ‘user’ directories to custom values. This is intended to be
1201 * used by test code (particularly with the %G_TEST_OPTION_ISOLATE_DIRS option)
1202 * to override the values returned by the following functions, so that test
1203 * code can be run without touching an installed system and user data:
1205 * - g_get_home_dir() — use type `HOME`, pass a string
1206 * - g_get_user_cache_dir() — use type `XDG_CACHE_HOME`, pass a string
1207 * - g_get_system_config_dirs() — use type `XDG_CONFIG_DIRS`, pass a
1208 * %NULL-terminated string array
1209 * - g_get_user_config_dir() — use type `XDG_CONFIG_HOME`, pass a string
1210 * - g_get_system_data_dirs() — use type `XDG_DATA_DIRS`, pass a
1211 * %NULL-terminated string array
1212 * - g_get_user_data_dir() — use type `XDG_DATA_HOME`, pass a string
1213 * - g_get_user_runtime_dir() — use type `XDG_RUNTIME_DIR`, pass a string
1215 * The list must be terminated with a %NULL type. All of the values must be
1216 * non-%NULL — passing %NULL as a value won’t reset a directory. If a reference
1217 * to a directory from the calling environment needs to be kept, copy it before
1218 * the first call to g_set_user_dirs(). g_set_user_dirs() can be called multiple
1225 g_set_user_dirs (const gchar *first_dir_type,
1229 const gchar *dir_type;
1231 G_LOCK (g_utils_global);
1233 va_start (args, first_dir_type);
1235 for (dir_type = first_dir_type; dir_type != NULL; dir_type = va_arg (args, const gchar *))
1237 gconstpointer dir_value = va_arg (args, gconstpointer);
1238 g_assert (dir_value != NULL);
1240 if (g_str_equal (dir_type, "HOME"))
1241 set_str_if_different (&g_home_dir, dir_type, dir_value);
1242 else if (g_str_equal (dir_type, "XDG_CACHE_HOME"))
1243 set_str_if_different (&g_user_cache_dir, dir_type, dir_value);
1244 else if (g_str_equal (dir_type, "XDG_CONFIG_DIRS"))
1245 set_strv_if_different (&g_system_config_dirs, dir_type, dir_value);
1246 else if (g_str_equal (dir_type, "XDG_CONFIG_HOME"))
1247 set_str_if_different (&g_user_config_dir, dir_type, dir_value);
1248 else if (g_str_equal (dir_type, "XDG_DATA_DIRS"))
1249 set_strv_if_different (&g_system_data_dirs, dir_type, dir_value);
1250 else if (g_str_equal (dir_type, "XDG_DATA_HOME"))
1251 set_str_if_different (&g_user_data_dir, dir_type, dir_value);
1252 else if (g_str_equal (dir_type, "XDG_RUNTIME_DIR"))
1253 set_str_if_different (&g_user_runtime_dir, dir_type, dir_value);
1255 g_assert_not_reached ();
1260 G_UNLOCK (g_utils_global);
1264 g_build_user_data_dir (void)
1266 gchar *data_dir = NULL;
1267 const gchar *data_dir_env = g_getenv ("XDG_DATA_HOME");
1269 if (data_dir_env && data_dir_env[0])
1270 data_dir = g_strdup (data_dir_env);
1273 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1275 if (!data_dir || !data_dir[0])
1277 gchar *home_dir = g_build_home_dir ();
1278 data_dir = g_build_filename (home_dir, ".local", "share", NULL);
1282 return g_steal_pointer (&data_dir);
1286 * g_get_user_data_dir:
1288 * Returns a base directory in which to access application data such
1289 * as icons that is customized for a particular user.
1291 * On UNIX platforms this is determined using the mechanisms described
1293 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1294 * In this case the directory retrieved will be `XDG_DATA_HOME`.
1296 * On Windows it follows XDG Base Directory Specification if `XDG_DATA_HOME`
1297 * is defined. If `XDG_DATA_HOME` is undefined, the folder to use for local (as
1298 * opposed to roaming) application data is used instead. See the
1299 * [documentation for `CSIDL_LOCAL_APPDATA`](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx#csidl_local_appdata).
1300 * Note that in this case on Windows it will be the same
1301 * as what g_get_user_config_dir() returns.
1303 * Returns: (type filename): a string owned by GLib that must not be modified
1308 g_get_user_data_dir (void)
1310 const gchar *user_data_dir;
1312 G_LOCK (g_utils_global);
1314 if (g_user_data_dir == NULL)
1315 g_user_data_dir = g_build_user_data_dir ();
1316 user_data_dir = g_user_data_dir;
1318 G_UNLOCK (g_utils_global);
1320 return user_data_dir;
1324 g_build_user_config_dir (void)
1326 gchar *config_dir = NULL;
1327 const gchar *config_dir_env = g_getenv ("XDG_CONFIG_HOME");
1329 if (config_dir_env && config_dir_env[0])
1330 config_dir = g_strdup (config_dir_env);
1333 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1335 if (!config_dir || !config_dir[0])
1337 gchar *home_dir = g_build_home_dir ();
1338 config_dir = g_build_filename (home_dir, ".config", NULL);
1342 return g_steal_pointer (&config_dir);
1346 * g_get_user_config_dir:
1348 * Returns a base directory in which to store user-specific application
1349 * configuration information such as user preferences and settings.
1351 * On UNIX platforms this is determined using the mechanisms described
1353 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1354 * In this case the directory retrieved will be `XDG_CONFIG_HOME`.
1356 * On Windows it follows XDG Base Directory Specification if `XDG_CONFIG_HOME` is defined.
1357 * If `XDG_CONFIG_HOME` is undefined, the folder to use for local (as opposed
1358 * to roaming) application data is used instead. See the
1359 * [documentation for `CSIDL_LOCAL_APPDATA`](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx#csidl_local_appdata).
1360 * Note that in this case on Windows it will be the same
1361 * as what g_get_user_data_dir() returns.
1363 * Returns: (type filename): a string owned by GLib that must not be modified
1368 g_get_user_config_dir (void)
1370 const gchar *user_config_dir;
1372 G_LOCK (g_utils_global);
1374 if (g_user_config_dir == NULL)
1375 g_user_config_dir = g_build_user_config_dir ();
1376 user_config_dir = g_user_config_dir;
1378 G_UNLOCK (g_utils_global);
1380 return user_config_dir;
1384 g_build_user_cache_dir (void)
1386 gchar *cache_dir = NULL;
1387 const gchar *cache_dir_env = g_getenv ("XDG_CACHE_HOME");
1389 if (cache_dir_env && cache_dir_env[0])
1390 cache_dir = g_strdup (cache_dir_env);
1393 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE);
1395 if (!cache_dir || !cache_dir[0])
1397 gchar *home_dir = g_build_home_dir ();
1398 cache_dir = g_build_filename (home_dir, ".cache", NULL);
1402 return g_steal_pointer (&cache_dir);
1406 * g_get_user_cache_dir:
1408 * Returns a base directory in which to store non-essential, cached
1409 * data specific to particular user.
1411 * On UNIX platforms this is determined using the mechanisms described
1413 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1414 * In this case the directory retrieved will be `XDG_CACHE_HOME`.
1416 * On Windows it follows XDG Base Directory Specification if `XDG_CACHE_HOME` is defined.
1417 * If `XDG_CACHE_HOME` is undefined, the directory that serves as a common
1418 * repository for temporary Internet files is used instead. A typical path is
1419 * `C:\Documents and Settings\username\Local Settings\Temporary Internet Files`.
1420 * 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).
1422 * Returns: (type filename): a string owned by GLib that must not be modified
1427 g_get_user_cache_dir (void)
1429 const gchar *user_cache_dir;
1431 G_LOCK (g_utils_global);
1433 if (g_user_cache_dir == NULL)
1434 g_user_cache_dir = g_build_user_cache_dir ();
1435 user_cache_dir = g_user_cache_dir;
1437 G_UNLOCK (g_utils_global);
1439 return user_cache_dir;
1443 g_build_user_runtime_dir (void)
1445 gchar *runtime_dir = NULL;
1446 const gchar *runtime_dir_env = g_getenv ("XDG_RUNTIME_DIR");
1448 if (runtime_dir_env && runtime_dir_env[0])
1449 runtime_dir = g_strdup (runtime_dir_env);
1452 runtime_dir = g_build_user_cache_dir ();
1454 /* The user should be able to rely on the directory existing
1455 * when the function returns. Probably it already does, but
1456 * let's make sure. Just do mkdir() directly since it will be
1457 * no more expensive than a stat() in the case that the
1458 * directory already exists and is a lot easier.
1460 * $XDG_CACHE_HOME is probably ~/.cache/ so as long as $HOME
1461 * exists this will work. If the user changed $XDG_CACHE_HOME
1462 * then they can make sure that it exists...
1464 (void) g_mkdir (runtime_dir, 0700);
1467 return g_steal_pointer (&runtime_dir);
1471 * g_get_user_runtime_dir:
1473 * Returns a directory that is unique to the current user on the local
1476 * This is determined using the mechanisms described
1478 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1479 * This is the directory
1480 * specified in the `XDG_RUNTIME_DIR` environment variable.
1481 * In the case that this variable is not set, we return the value of
1482 * g_get_user_cache_dir(), after verifying that it exists.
1484 * Returns: (type filename): a string owned by GLib that must not be
1485 * modified or freed.
1490 g_get_user_runtime_dir (void)
1492 const gchar *user_runtime_dir;
1494 G_LOCK (g_utils_global);
1496 if (g_user_runtime_dir == NULL)
1497 g_user_runtime_dir = g_build_user_runtime_dir ();
1498 user_runtime_dir = g_user_runtime_dir;
1500 G_UNLOCK (g_utils_global);
1502 return user_runtime_dir;
1507 /* Implemented in gutils-macos.m */
1508 void load_user_special_dirs_macos (gchar **table);
1511 load_user_special_dirs (void)
1513 load_user_special_dirs_macos (g_user_special_dirs);
1516 #elif defined(G_OS_WIN32)
1519 load_user_special_dirs (void)
1521 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1525 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
1527 static const GUID FOLDERID_Downloads =
1528 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1529 static const GUID FOLDERID_Public =
1530 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1534 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
1535 "SHGetKnownFolderPath");
1537 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1538 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
1540 if (p_SHGetKnownFolderPath == NULL)
1542 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1547 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1550 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1551 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
1552 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1553 CoTaskMemFree (wcp);
1556 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1559 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
1560 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
1562 if (p_SHGetKnownFolderPath == NULL)
1565 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1570 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
1573 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1574 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
1575 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1576 CoTaskMemFree (wcp);
1579 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1582 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
1583 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
1586 #else /* default is unix */
1588 /* adapted from xdg-user-dir-lookup.c
1590 * Copyright (C) 2007 Red Hat Inc.
1592 * Permission is hereby granted, free of charge, to any person
1593 * obtaining a copy of this software and associated documentation files
1594 * (the "Software"), to deal in the Software without restriction,
1595 * including without limitation the rights to use, copy, modify, merge,
1596 * publish, distribute, sublicense, and/or sell copies of the Software,
1597 * and to permit persons to whom the Software is furnished to do so,
1598 * subject to the following conditions:
1600 * The above copyright notice and this permission notice shall be
1601 * included in all copies or substantial portions of the Software.
1603 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1604 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1605 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1606 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1607 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1608 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1609 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1613 load_user_special_dirs (void)
1615 gchar *config_dir = NULL;
1621 config_dir = g_build_user_config_dir ();
1622 config_file = g_build_filename (config_dir,
1625 g_free (config_dir);
1627 if (!g_file_get_contents (config_file, &data, NULL, NULL))
1629 g_free (config_file);
1633 lines = g_strsplit (data, "\n", -1);
1634 n_lines = g_strv_length (lines);
1637 for (i = 0; i < n_lines; i++)
1639 gchar *buffer = lines[i];
1642 gboolean is_relative = FALSE;
1643 GUserDirectory directory;
1645 /* Remove newline at end */
1646 len = strlen (buffer);
1647 if (len > 0 && buffer[len - 1] == '\n')
1648 buffer[len - 1] = 0;
1651 while (*p == ' ' || *p == '\t')
1654 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
1656 directory = G_USER_DIRECTORY_DESKTOP;
1657 p += strlen ("XDG_DESKTOP_DIR");
1659 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
1661 directory = G_USER_DIRECTORY_DOCUMENTS;
1662 p += strlen ("XDG_DOCUMENTS_DIR");
1664 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
1666 directory = G_USER_DIRECTORY_DOWNLOAD;
1667 p += strlen ("XDG_DOWNLOAD_DIR");
1669 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
1671 directory = G_USER_DIRECTORY_MUSIC;
1672 p += strlen ("XDG_MUSIC_DIR");
1674 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
1676 directory = G_USER_DIRECTORY_PICTURES;
1677 p += strlen ("XDG_PICTURES_DIR");
1679 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
1681 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
1682 p += strlen ("XDG_PUBLICSHARE_DIR");
1684 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
1686 directory = G_USER_DIRECTORY_TEMPLATES;
1687 p += strlen ("XDG_TEMPLATES_DIR");
1689 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
1691 directory = G_USER_DIRECTORY_VIDEOS;
1692 p += strlen ("XDG_VIDEOS_DIR");
1697 while (*p == ' ' || *p == '\t')
1704 while (*p == ' ' || *p == '\t')
1711 if (strncmp (p, "$HOME", 5) == 0)
1719 d = strrchr (p, '"');
1726 /* remove trailing slashes */
1728 if (d[len - 1] == '/')
1733 gchar *home_dir = g_build_home_dir ();
1734 g_user_special_dirs[directory] = g_build_filename (home_dir, d, NULL);
1738 g_user_special_dirs[directory] = g_strdup (d);
1742 g_free (config_file);
1745 #endif /* platform-specific load_user_special_dirs implementations */
1749 * g_reload_user_special_dirs_cache:
1751 * Resets the cache used for g_get_user_special_dir(), so
1752 * that the latest on-disk version is used. Call this only
1753 * if you just changed the data on disk yourself.
1755 * Due to thread safety issues this may cause leaking of strings
1756 * that were previously returned from g_get_user_special_dir()
1757 * that can't be freed. We ensure to only leak the data for
1758 * the directories that actually changed value though.
1763 g_reload_user_special_dirs_cache (void)
1767 G_LOCK (g_utils_global);
1769 if (g_user_special_dirs != NULL)
1771 /* save a copy of the pointer, to check if some memory can be preserved */
1772 char **old_g_user_special_dirs = g_user_special_dirs;
1775 /* recreate and reload our cache */
1776 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1777 load_user_special_dirs ();
1779 /* only leak changed directories */
1780 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
1782 old_val = old_g_user_special_dirs[i];
1783 if (g_user_special_dirs[i] == NULL)
1785 g_user_special_dirs[i] = old_val;
1787 else if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
1790 g_free (g_user_special_dirs[i]);
1791 g_user_special_dirs[i] = old_val;
1797 /* free the old array */
1798 g_free (old_g_user_special_dirs);
1801 G_UNLOCK (g_utils_global);
1805 * g_get_user_special_dir:
1806 * @directory: the logical id of special directory
1808 * Returns the full path of a special directory using its logical id.
1810 * On UNIX this is done using the XDG special user directories.
1811 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
1812 * falls back to `$HOME/Desktop` when XDG special user directories have
1815 * Depending on the platform, the user might be able to change the path
1816 * of the special directory without requiring the session to restart; GLib
1817 * will not reflect any change once the special directories are loaded.
1819 * Returns: (type filename): the path to the specified special directory, or
1820 * %NULL if the logical id was not found. The returned string is owned by
1821 * GLib and should not be modified or freed.
1826 g_get_user_special_dir (GUserDirectory directory)
1828 const gchar *user_special_dir;
1830 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
1831 directory < G_USER_N_DIRECTORIES, NULL);
1833 G_LOCK (g_utils_global);
1835 if (G_UNLIKELY (g_user_special_dirs == NULL))
1837 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1839 load_user_special_dirs ();
1841 /* Special-case desktop for historical compatibility */
1842 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
1844 gchar *home_dir = g_build_home_dir ();
1845 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = g_build_filename (home_dir, "Desktop", NULL);
1849 user_special_dir = g_user_special_dirs[directory];
1851 G_UNLOCK (g_utils_global);
1853 return user_special_dir;
1858 #undef g_get_system_data_dirs
1861 get_module_for_address (gconstpointer address)
1863 /* Holds the g_utils_global lock */
1865 static gboolean beenhere = FALSE;
1866 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
1867 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
1868 HMODULE hmodule = NULL;
1875 p_GetModuleHandleExA =
1876 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1877 "GetModuleHandleExA");
1881 if (p_GetModuleHandleExA == NULL ||
1882 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
1883 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
1886 MEMORY_BASIC_INFORMATION mbi;
1887 VirtualQuery (address, &mbi, sizeof (mbi));
1888 hmodule = (HMODULE) mbi.AllocationBase;
1895 get_module_share_dir (gconstpointer address)
1901 hmodule = get_module_for_address (address);
1902 if (hmodule == NULL)
1905 filename = g_win32_get_package_installation_directory_of_module (hmodule);
1906 retval = g_build_filename (filename, "share", NULL);
1912 static const gchar * const *
1913 g_win32_get_system_data_dirs_for_module_real (void (*address_of_function)(void))
1917 static GHashTable *per_module_data_dirs = NULL;
1923 if (address_of_function)
1925 G_LOCK (g_utils_global);
1926 hmodule = get_module_for_address (address_of_function);
1927 if (hmodule != NULL)
1929 if (per_module_data_dirs == NULL)
1930 per_module_data_dirs = g_hash_table_new (NULL, NULL);
1933 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
1937 G_UNLOCK (g_utils_global);
1938 return (const gchar * const *) retval;
1944 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
1946 /* Documents and Settings\All Users\Application Data */
1947 p = get_special_folder (CSIDL_COMMON_APPDATA);
1949 g_array_append_val (data_dirs, p);
1951 /* Documents and Settings\All Users\Documents */
1952 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1954 g_array_append_val (data_dirs, p);
1956 /* Using the above subfolders of Documents and Settings perhaps
1957 * makes sense from a Windows perspective.
1959 * But looking at the actual use cases of this function in GTK+
1960 * and GNOME software, what we really want is the "share"
1961 * subdirectory of the installation directory for the package
1962 * our caller is a part of.
1964 * The address_of_function parameter, if non-NULL, points to a
1965 * function in the calling module. Use that to determine that
1966 * module's installation folder, and use its "share" subfolder.
1968 * Additionally, also use the "share" subfolder of the installation
1969 * locations of GLib and the .exe file being run.
1971 * To guard against none of the above being what is really wanted,
1972 * callers of this function should have Win32-specific code to look
1973 * up their installation folder themselves, and handle a subfolder
1974 * "share" of it in the same way as the folders returned from this
1978 p = get_module_share_dir (address_of_function);
1980 g_array_append_val (data_dirs, p);
1982 if (glib_dll != NULL)
1984 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
1985 p = g_build_filename (glib_root, "share", NULL);
1987 g_array_append_val (data_dirs, p);
1991 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
1992 p = g_build_filename (exe_root, "share", NULL);
1994 g_array_append_val (data_dirs, p);
1997 retval = (gchar **) g_array_free (data_dirs, FALSE);
1999 if (address_of_function)
2001 if (hmodule != NULL)
2002 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2003 G_UNLOCK (g_utils_global);
2006 return (const gchar * const *) retval;
2009 const gchar * const *
2010 g_win32_get_system_data_dirs_for_module (void (*address_of_function)(void))
2012 gboolean should_call_g_get_system_data_dirs;
2014 should_call_g_get_system_data_dirs = TRUE;
2015 /* These checks are the same as the ones that g_build_system_data_dirs() does.
2016 * Please keep them in sync.
2018 G_LOCK (g_utils_global);
2020 if (!g_system_data_dirs)
2022 const gchar *data_dirs = g_getenv ("XDG_DATA_DIRS");
2024 if (!data_dirs || !data_dirs[0])
2025 should_call_g_get_system_data_dirs = FALSE;
2028 G_UNLOCK (g_utils_global);
2030 /* There is a subtle difference between g_win32_get_system_data_dirs_for_module (NULL),
2031 * which is what GLib code can normally call,
2032 * and g_win32_get_system_data_dirs_for_module (&_g_win32_get_system_data_dirs),
2033 * which is what the inline function used by non-GLib code calls.
2034 * The former gets prefix relative to currently-running executable,
2035 * the latter - relative to the module that calls _g_win32_get_system_data_dirs()
2036 * (disguised as g_get_system_data_dirs()), which could be an executable or
2037 * a DLL that is located somewhere else.
2038 * This is why that inline function in gutils.h exists, and why we can't just
2039 * call g_get_system_data_dirs() from there - because we need to get the address
2040 * local to the non-GLib caller-module.
2044 * g_get_system_data_dirs() will fall back to calling
2045 * g_win32_get_system_data_dirs_for_module_real(NULL) if XDG_DATA_DIRS is NULL
2046 * or an empty string. The checks above ensure that we do not call it in such
2047 * cases and use the address_of_function that we've been given by the inline function.
2048 * The reason we're calling g_get_system_data_dirs /at all/ is to give
2049 * XDG_DATA_DIRS precedence (if it is set).
2051 if (should_call_g_get_system_data_dirs)
2052 return g_get_system_data_dirs ();
2054 return g_win32_get_system_data_dirs_for_module_real (address_of_function);
2060 g_build_system_data_dirs (void)
2062 gchar **data_dir_vector = NULL;
2063 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2065 /* These checks are the same as the ones that g_win32_get_system_data_dirs_for_module()
2066 * does. Please keep them in sync.
2069 if (!data_dirs || !data_dirs[0])
2070 data_dirs = "/usr/local/share/:/usr/share/";
2072 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2074 if (!data_dirs || !data_dirs[0])
2075 data_dir_vector = g_strdupv ((gchar **) g_win32_get_system_data_dirs_for_module_real (NULL));
2077 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2080 return g_steal_pointer (&data_dir_vector);
2084 * g_get_system_data_dirs:
2086 * Returns an ordered list of base directories in which to access
2087 * system-wide application data.
2089 * On UNIX platforms this is determined using the mechanisms described
2091 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec)
2092 * In this case the list of directories retrieved will be `XDG_DATA_DIRS`.
2094 * On Windows it follows XDG Base Directory Specification if `XDG_DATA_DIRS` is defined.
2095 * If `XDG_DATA_DIRS` is undefined,
2096 * the first elements in the list are the Application Data
2097 * and Documents folders for All Users. (These can be determined only
2098 * on Windows 2000 or later and are not present in the list on other
2099 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2100 * CSIDL_COMMON_DOCUMENTS.
2102 * Then follows the "share" subfolder in the installation folder for
2103 * the package containing the DLL that calls this function, if it can
2106 * Finally the list contains the "share" subfolder in the installation
2107 * folder for GLib, and in the installation folder for the package the
2108 * application's .exe file belongs to.
2110 * The installation folders above are determined by looking up the
2111 * folder where the module (DLL or EXE) in question is located. If the
2112 * folder's name is "bin", its parent is used, otherwise the folder
2115 * Note that on Windows the returned list can vary depending on where
2116 * this function is called.
2118 * Returns: (array zero-terminated=1) (element-type filename) (transfer none):
2119 * a %NULL-terminated array of strings owned by GLib that must not be
2120 * modified or freed.
2124 const gchar * const *
2125 g_get_system_data_dirs (void)
2127 const gchar * const *system_data_dirs;
2129 G_LOCK (g_utils_global);
2131 if (g_system_data_dirs == NULL)
2132 g_system_data_dirs = g_build_system_data_dirs ();
2133 system_data_dirs = (const gchar * const *) g_system_data_dirs;
2135 G_UNLOCK (g_utils_global);
2137 return system_data_dirs;
2141 g_build_system_config_dirs (void)
2143 gchar **conf_dir_vector = NULL;
2144 const gchar *conf_dirs = g_getenv ("XDG_CONFIG_DIRS");
2148 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2152 gchar *special_conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2154 if (special_conf_dirs)
2155 conf_dir_vector = g_strsplit (special_conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2157 /* Return empty list */
2158 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2160 g_free (special_conf_dirs);
2163 if (!conf_dirs || !conf_dirs[0])
2164 conf_dirs = "/etc/xdg";
2166 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2169 return g_steal_pointer (&conf_dir_vector);
2173 * g_get_system_config_dirs:
2175 * Returns an ordered list of base directories in which to access
2176 * system-wide configuration information.
2178 * On UNIX platforms this is determined using the mechanisms described
2180 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2181 * In this case the list of directories retrieved will be `XDG_CONFIG_DIRS`.
2183 * On Windows it follows XDG Base Directory Specification if `XDG_CONFIG_DIRS` is defined.
2184 * If `XDG_CONFIG_DIRS` is undefined, the directory that contains application
2185 * data for all users is used instead. A typical path is
2186 * `C:\Documents and Settings\All Users\Application Data`.
2187 * This folder is used for application data
2188 * that is not user specific. For example, an application can store
2189 * a spell-check dictionary, a database of clip art, or a log file in the
2190 * CSIDL_COMMON_APPDATA folder. This information will not roam and is available
2191 * to anyone using the computer.
2193 * Returns: (array zero-terminated=1) (element-type filename) (transfer none):
2194 * a %NULL-terminated array of strings owned by GLib that must not be
2195 * modified or freed.
2199 const gchar * const *
2200 g_get_system_config_dirs (void)
2202 const gchar * const *system_config_dirs;
2204 G_LOCK (g_utils_global);
2206 if (g_system_config_dirs == NULL)
2207 g_system_config_dirs = g_build_system_config_dirs ();
2208 system_config_dirs = (const gchar * const *) g_system_config_dirs;
2210 G_UNLOCK (g_utils_global);
2212 return system_config_dirs;
2216 * g_nullify_pointer:
2217 * @nullify_location: (not nullable): the memory address of the pointer.
2219 * Set the pointer at the specified location to %NULL.
2222 g_nullify_pointer (gpointer *nullify_location)
2224 g_return_if_fail (nullify_location != NULL);
2226 *nullify_location = NULL;
2229 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2230 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2231 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2232 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2233 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2234 #define EXABYTE_FACTOR (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2236 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2237 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2238 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2239 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2240 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2241 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2245 * @size: a size in bytes
2247 * Formats a size (for example the size of a file) into a human readable
2248 * string. Sizes are rounded to the nearest size prefix (kB, MB, GB)
2249 * and are displayed rounded to the nearest tenth. E.g. the file size
2250 * 3292528 bytes will be converted into the string "3.2 MB". The returned string
2251 * is UTF-8, and may use a non-breaking space to separate the number and units,
2252 * to ensure they aren’t separated when line wrapped.
2254 * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2256 * This string should be freed with g_free() when not needed any longer.
2258 * See g_format_size_full() for more options about how the size might be
2261 * Returns: a newly-allocated formatted string containing a human readable
2267 g_format_size (guint64 size)
2269 return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2274 * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2275 * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2276 * of the returned string. For example, "45.6 kB (45,612 bytes)".
2277 * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2278 * suffixes. IEC units should only be used for reporting things with
2279 * a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2280 * Network and storage sizes should be reported in the normal SI units.
2281 * @G_FORMAT_SIZE_BITS: set the size as a quantity in bits, rather than
2282 * bytes, and return units in bits. For example, ‘Mb’ rather than ‘MB’.
2284 * Flags to modify the format of the string returned by g_format_size_full().
2287 #pragma GCC diagnostic push
2288 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
2291 * g_format_size_full:
2292 * @size: a size in bytes
2293 * @flags: #GFormatSizeFlags to modify the output
2297 * This function is similar to g_format_size() but allows for flags
2298 * that modify the output. See #GFormatSizeFlags.
2300 * Returns: a newly-allocated formatted string containing a human
2301 * readable file size
2306 g_format_size_full (guint64 size,
2307 GFormatSizeFlags flags)
2323 const struct Format formats[4][6] = {
2325 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2326 { KILOBYTE_FACTOR, N_("%.1f kB") },
2327 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2328 { MEGABYTE_FACTOR, N_("%.1f MB") },
2329 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2330 { GIGABYTE_FACTOR, N_("%.1f GB") },
2331 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2332 { TERABYTE_FACTOR, N_("%.1f TB") },
2333 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2334 { PETABYTE_FACTOR, N_("%.1f PB") },
2335 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2336 { EXABYTE_FACTOR, N_("%.1f EB") }
2339 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2340 { KIBIBYTE_FACTOR, N_("%.1f KiB") },
2341 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2342 { MEBIBYTE_FACTOR, N_("%.1f MiB") },
2343 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2344 { GIBIBYTE_FACTOR, N_("%.1f GiB") },
2345 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2346 { TEBIBYTE_FACTOR, N_("%.1f TiB") },
2347 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2348 { PEBIBYTE_FACTOR, N_("%.1f PiB") },
2349 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2350 { EXBIBYTE_FACTOR, N_("%.1f EiB") }
2353 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2354 { KILOBYTE_FACTOR, N_("%.1f kb") },
2355 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2356 { MEGABYTE_FACTOR, N_("%.1f Mb") },
2357 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2358 { GIGABYTE_FACTOR, N_("%.1f Gb") },
2359 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2360 { TERABYTE_FACTOR, N_("%.1f Tb") },
2361 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2362 { PETABYTE_FACTOR, N_("%.1f Pb") },
2363 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2364 { EXABYTE_FACTOR, N_("%.1f Eb") }
2367 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2368 { KIBIBYTE_FACTOR, N_("%.1f Kib") },
2369 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2370 { MEBIBYTE_FACTOR, N_("%.1f Mib") },
2371 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2372 { GIBIBYTE_FACTOR, N_("%.1f Gib") },
2373 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2374 { TEBIBYTE_FACTOR, N_("%.1f Tib") },
2375 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2376 { PEBIBYTE_FACTOR, N_("%.1f Pib") },
2377 /* Translators: Keep the no-break space between %.1f and the unit symbol */
2378 { EXBIBYTE_FACTOR, N_("%.1f Eib") }
2385 string = g_string_new (NULL);
2387 switch (flags & ~G_FORMAT_SIZE_LONG_FORMAT)
2389 case G_FORMAT_SIZE_DEFAULT:
2390 index = FORMAT_BYTES;
2392 case (G_FORMAT_SIZE_DEFAULT | G_FORMAT_SIZE_IEC_UNITS):
2393 index = FORMAT_BYTES_IEC;
2395 case G_FORMAT_SIZE_BITS:
2396 index = FORMAT_BITS;
2398 case (G_FORMAT_SIZE_BITS | G_FORMAT_SIZE_IEC_UNITS):
2399 index = FORMAT_BITS_IEC;
2402 g_assert_not_reached ();
2406 if (size < formats[index][0].factor)
2408 const char * format;
2410 if (index == FORMAT_BYTES || index == FORMAT_BYTES_IEC)
2412 format = g_dngettext (GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size);
2416 format = g_dngettext (GETTEXT_PACKAGE, "%u bit", "%u bits", (guint) size);
2419 g_string_printf (string, format, (guint) size);
2421 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2425 const gsize n = G_N_ELEMENTS (formats[index]);
2429 * Point the last format (the highest unit) by default
2430 * and then then scan all formats, starting with the 2nd one
2431 * because the 1st is already managed by with the plural form
2433 const struct Format * f = &formats[index][n - 1];
2435 for (i = 1; i < n; i++)
2437 if (size < formats[index][i].factor)
2439 f = &formats[index][i - 1];
2444 g_string_printf (string, _(f->string), (gdouble) size / (gdouble) f->factor);
2447 if (flags & G_FORMAT_SIZE_LONG_FORMAT)
2449 /* First problem: we need to use the number of bytes to decide on
2450 * the plural form that is used for display, but the number of
2451 * bytes potentially exceeds the size of a guint (which is what
2452 * ngettext() takes).
2454 * From a pragmatic standpoint, it seems that all known languages
2455 * base plural forms on one or both of the following:
2457 * - the lowest digits of the number
2459 * - if the number if greater than some small value
2461 * Here's how we fake it: Draw an arbitrary line at one thousand.
2462 * If the number is below that, then fine. If it is above it,
2463 * then we take the modulus of the number by one thousand (in
2464 * order to keep the lowest digits) and add one thousand to that
2465 * (in order to ensure that 1001 is not treated the same as 1).
2467 guint plural_form = size < 1000 ? size : size % 1000 + 1000;
2469 /* Second problem: we need to translate the string "%u byte/bit" and
2470 * "%u bytes/bits" for pluralisation, but the correct number format to
2471 * use for a gsize is different depending on which architecture
2474 * Solution: format the number separately and use "%s bytes/bits" on
2477 const gchar *translated_format;
2478 gchar *formatted_number;
2480 if (index == FORMAT_BYTES || index == FORMAT_BYTES_IEC)
2482 /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2483 translated_format = g_dngettext (GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
2487 /* Translators: the %s in "%s bits" will always be replaced by a number. */
2488 translated_format = g_dngettext (GETTEXT_PACKAGE, "%s bit", "%s bits", plural_form);
2490 formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2492 g_string_append (string, " (");
2493 g_string_append_printf (string, translated_format, formatted_number);
2494 g_free (formatted_number);
2495 g_string_append (string, ")");
2498 return g_string_free (string, FALSE);
2501 #pragma GCC diagnostic pop
2504 * g_format_size_for_display:
2505 * @size: a size in bytes
2507 * Formats a size (for example the size of a file) into a human
2508 * readable string. Sizes are rounded to the nearest size prefix
2509 * (KB, MB, GB) and are displayed rounded to the nearest tenth.
2510 * E.g. the file size 3292528 bytes will be converted into the
2513 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2515 * This string should be freed with g_free() when not needed any longer.
2517 * Returns: a newly-allocated formatted string containing a human
2518 * readable file size
2522 * Deprecated:2.30: This function is broken due to its use of SI
2523 * suffixes to denote IEC units. Use g_format_size() instead.
2526 g_format_size_for_display (goffset size)
2528 if (size < (goffset) KIBIBYTE_FACTOR)
2529 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
2532 gdouble displayed_size;
2534 if (size < (goffset) MEBIBYTE_FACTOR)
2536 displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
2537 /* Translators: this is from the deprecated function g_format_size_for_display() which uses 'KB' to
2538 * mean 1024 bytes. I am aware that 'KB' is not correct, but it has been preserved for reasons of
2539 * compatibility. Users will not see this string unless a program is using this deprecated function.
2540 * Please translate as literally as possible.
2542 return g_strdup_printf (_("%.1f KB"), displayed_size);
2544 else if (size < (goffset) GIBIBYTE_FACTOR)
2546 displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
2547 return g_strdup_printf (_("%.1f MB"), displayed_size);
2549 else if (size < (goffset) TEBIBYTE_FACTOR)
2551 displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
2552 return g_strdup_printf (_("%.1f GB"), displayed_size);
2554 else if (size < (goffset) PEBIBYTE_FACTOR)
2556 displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
2557 return g_strdup_printf (_("%.1f TB"), displayed_size);
2559 else if (size < (goffset) EXBIBYTE_FACTOR)
2561 displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
2562 return g_strdup_printf (_("%.1f PB"), displayed_size);
2566 displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
2567 return g_strdup_printf (_("%.1f EB"), displayed_size);
2572 #if defined (G_OS_WIN32) && !defined (_WIN64)
2574 /* Binary compatibility versions. Not for newly compiled code. */
2576 _GLIB_EXTERN const gchar *g_get_user_name_utf8 (void);
2577 _GLIB_EXTERN const gchar *g_get_real_name_utf8 (void);
2578 _GLIB_EXTERN const gchar *g_get_home_dir_utf8 (void);
2579 _GLIB_EXTERN const gchar *g_get_tmp_dir_utf8 (void);
2580 _GLIB_EXTERN gchar *g_find_program_in_path_utf8 (const gchar *program);
2583 g_find_program_in_path_utf8 (const gchar *program)
2585 return g_find_program_in_path (program);
2588 const gchar *g_get_user_name_utf8 (void) { return g_get_user_name (); }
2589 const gchar *g_get_real_name_utf8 (void) { return g_get_real_name (); }
2590 const gchar *g_get_home_dir_utf8 (void) { return g_get_home_dir (); }
2591 const gchar *g_get_tmp_dir_utf8 (void) { return g_get_tmp_dir (); }
2597 * Returns %TRUE if the current process was executed as setuid
2600 g_check_setuid (void)
2602 #if defined(HAVE_SYS_AUXV_H) && defined(HAVE_GETAUXVAL) && defined(AT_SECURE)
2603 unsigned long value;
2607 value = getauxval (AT_SECURE);
2610 g_error ("getauxval () failed: %s", g_strerror (errsv));
2612 #elif defined(HAVE_ISSETUGID) && !defined(__BIONIC__)
2613 /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
2615 /* Android had it in older versions but the new 64 bit ABI does not
2616 * have it anymore, and some versions of the 32 bit ABI neither.
2617 * https://code.google.com/p/android-developer-preview/issues/detail?id=168
2619 return issetugid ();
2620 #elif defined(G_OS_UNIX)
2621 uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
2622 gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
2624 static gsize check_setuid_initialised;
2625 static gboolean is_setuid;
2627 if (g_once_init_enter (&check_setuid_initialised))
2629 #ifdef HAVE_GETRESUID
2630 /* These aren't in the header files, so we prototype them here.
2632 int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
2633 int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);
2635 if (getresuid (&ruid, &euid, &suid) != 0 ||
2636 getresgid (&rgid, &egid, &sgid) != 0)
2637 #endif /* HAVE_GETRESUID */
2639 suid = ruid = getuid ();
2640 sgid = rgid = getgid ();
2645 is_setuid = (ruid != euid || ruid != suid ||
2646 rgid != egid || rgid != sgid);
2648 g_once_init_leave (&check_setuid_initialised, 1);
2660 * A wrapper for the POSIX abort() function.
2662 * On Windows it is a function that makes extra effort (including a call
2663 * to abort()) to ensure that a debugger-catchable exception is thrown
2664 * before the program terminates.
2666 * See your C library manual for more details about abort().
2673 /* One call to break the debugger */
2675 /* One call in case CRT does get saner about abort() behaviour */
2677 /* And one call to bind them all and terminate the program for sure */