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 */
98 /* older SDK (e.g. msvc 5.0) does not have these*/
99 # ifndef CSIDL_MYMUSIC
100 # define CSIDL_MYMUSIC 13
102 # ifndef CSIDL_MYVIDEO
103 # define CSIDL_MYVIDEO 14
105 # ifndef CSIDL_INTERNET_CACHE
106 # define CSIDL_INTERNET_CACHE 32
108 # ifndef CSIDL_COMMON_APPDATA
109 # define CSIDL_COMMON_APPDATA 35
111 # ifndef CSIDL_MYPICTURES
112 # define CSIDL_MYPICTURES 0x27
114 # ifndef CSIDL_COMMON_DOCUMENTS
115 # define CSIDL_COMMON_DOCUMENTS 46
117 # ifndef CSIDL_PROFILE
118 # define CSIDL_PROFILE 40
120 # include <process.h>
124 #include <CoreServices/CoreServices.h>
128 #include <langinfo.h>
131 #ifdef G_PLATFORM_WIN32
134 _glib_get_dll_directory (void)
138 wchar_t wc_fn[MAX_PATH];
141 if (glib_dll == NULL)
145 /* This code is different from that in
146 * g_win32_get_package_installation_directory_of_module() in that
147 * here we return the actual folder where the GLib DLL is. We don't
148 * do the check for it being in a "bin" or "lib" subfolder and then
149 * returning the parent of that.
151 * In a statically built GLib, glib_dll will be NULL and we will
152 * thus look up the application's .exe file's location.
154 if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
157 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
159 p = strrchr (retval, G_DIR_SEPARATOR);
174 * @dest: the destination address to copy the bytes to.
175 * @src: the source address to copy the bytes from.
176 * @len: the number of bytes to copy.
178 * Copies a block of memory @len bytes long, from @src to @dest.
179 * The source and destination areas may overlap.
181 * Deprecated:2.40: Just use memmove().
190 * @func: (scope async): the function to call on normal program termination.
192 * Specifies a function to be called at normal program termination.
194 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
195 * macro that maps to a call to the atexit() function in the C
196 * library. This means that in case the code that calls g_atexit(),
197 * i.e. atexit(), is in a DLL, the function will be called when the
198 * DLL is detached from the program. This typically makes more sense
199 * than that the function is called when the GLib DLL is detached,
200 * which happened earlier when g_atexit() was a function in the GLib
203 * The behaviour of atexit() in the context of dynamically loaded
204 * modules is not formally specified and varies wildly.
206 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
207 * loaded module which is unloaded before the program terminates might
208 * well cause a crash at program exit.
210 * Some POSIX systems implement atexit() like Windows, and have each
211 * dynamically loaded module maintain an own atexit chain that is
212 * called when the module is unloaded.
214 * On other POSIX systems, before a dynamically loaded module is
215 * unloaded, the registered atexit functions (if any) residing in that
216 * module are called, regardless where the code that registered them
217 * resided. This is presumably the most robust approach.
219 * As can be seen from the above, for portability it's best to avoid
220 * calling g_atexit() (or atexit()) except in the main executable of a
223 * Deprecated:2.32: It is best to avoid g_atexit().
226 g_atexit (GVoidFunc func)
231 result = atexit ((void (*)(void)) func);
235 g_error ("Could not register atexit() function: %s",
240 /* Based on execvp() from GNU Libc.
241 * Some of this code is cut-and-pasted into gspawn.c
245 my_strchrnul (const gchar *str,
248 gchar *p = (gchar*)str;
249 while (*p && (*p != c))
257 static gchar *inner_find_program_in_path (const gchar *program);
260 g_find_program_in_path (const gchar *program)
262 const gchar *last_dot = strrchr (program, '.');
264 if (last_dot == NULL ||
265 strchr (last_dot, '\\') != NULL ||
266 strchr (last_dot, '/') != NULL)
268 const gint program_length = strlen (program);
269 gchar *pathext = g_build_path (";",
270 ".exe;.cmd;.bat;.com",
271 g_getenv ("PATHEXT"),
274 gchar *decorated_program;
280 gchar *q = my_strchrnul (p, ';');
282 decorated_program = g_malloc (program_length + (q-p) + 1);
283 memcpy (decorated_program, program, program_length);
284 memcpy (decorated_program+program_length, p, q-p);
285 decorated_program [program_length + (q-p)] = '\0';
287 retval = inner_find_program_in_path (decorated_program);
288 g_free (decorated_program);
296 } while (*p++ != '\0');
301 return inner_find_program_in_path (program);
307 * g_find_program_in_path:
308 * @program: (type filename): a program name in the GLib file name encoding
310 * Locates the first executable named @program in the user's path, in the
311 * same way that execvp() would locate it. Returns an allocated string
312 * with the absolute path name, or %NULL if the program is not found in
313 * the path. If @program is already an absolute path, returns a copy of
314 * @program if @program exists and is executable, and %NULL otherwise.
316 * On Windows, if @program does not have a file type suffix, tries
317 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
318 * the `PATHEXT` environment variable.
320 * On Windows, it looks for the file in the same way as CreateProcess()
321 * would. This means first in the directory where the executing
322 * program was loaded from, then in the current directory, then in the
323 * Windows 32-bit system directory, then in the Windows directory, and
324 * finally in the directories in the `PATH` environment variable. If
325 * the program is found, the return value contains the full name
326 * including the type suffix.
328 * Returns: (type filename): a newly-allocated string with the absolute path,
333 inner_find_program_in_path (const gchar *program)
336 g_find_program_in_path (const gchar *program)
339 const gchar *path, *p;
340 gchar *name, *freeme;
342 const gchar *path_copy;
343 gchar *filename = NULL, *appdir = NULL;
344 gchar *sysdir = NULL, *windir = NULL;
346 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
352 g_return_val_if_fail (program != NULL, NULL);
354 /* If it is an absolute path, or a relative path including subdirectories,
355 * don't look in PATH.
357 if (g_path_is_absolute (program)
358 || strchr (program, G_DIR_SEPARATOR) != NULL
360 || strchr (program, '/') != NULL
364 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
365 !g_file_test (program, G_FILE_TEST_IS_DIR))
366 return g_strdup (program);
371 path = g_getenv ("PATH");
372 #if defined(G_OS_UNIX)
375 /* There is no 'PATH' in the environment. The default
376 * search path in GNU libc is the current directory followed by
377 * the path 'confstr' returns for '_CS_PATH'.
380 /* In GLib we put . last, for security, and don't use the
381 * unportable confstr(); UNIX98 does not actually specify
382 * what to search if PATH is unset. POSIX may, dunno.
385 path = "/bin:/usr/bin:.";
388 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
389 if (n > 0 && n < MAXPATHLEN)
390 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
392 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
393 if (n > 0 && n < MAXPATHLEN)
394 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
396 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
397 if (n > 0 && n < MAXPATHLEN)
398 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
402 appdir = g_path_get_dirname (filename);
406 path = g_strdup (path);
410 const gchar *tem = path;
411 path = g_strconcat (windir, ";", path, NULL);
412 g_free ((gchar *) tem);
418 const gchar *tem = path;
419 path = g_strconcat (sysdir, ";", path, NULL);
420 g_free ((gchar *) tem);
425 const gchar *tem = path;
426 path = g_strconcat (".;", path, NULL);
427 g_free ((gchar *) tem);
432 const gchar *tem = path;
433 path = g_strconcat (appdir, ";", path, NULL);
434 g_free ((gchar *) tem);
441 len = strlen (program) + 1;
442 pathlen = strlen (path);
443 freeme = name = g_malloc (pathlen + len + 1);
445 /* Copy the file name at the top, including '\0' */
446 memcpy (name + pathlen + 1, program, len);
447 name = name + pathlen;
448 /* And add the slash before the filename */
449 *name = G_DIR_SEPARATOR;
457 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
460 /* Two adjacent colons, or a colon at the beginning or the end
461 * of 'PATH' means to search the current directory.
465 startp = memcpy (name - (p - path), path, p - path);
467 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
468 !g_file_test (startp, G_FILE_TEST_IS_DIR))
471 ret = g_strdup (startp);
474 g_free ((gchar *) path_copy);
479 while (*p++ != '\0');
483 g_free ((gchar *) path_copy);
489 /* The functions below are defined this way for compatibility reasons.
490 * See the note in gutils.h.
495 * @mask: a #gulong containing flags
496 * @nth_bit: the index of the bit to start the search from
498 * Find the position of the first bit set in @mask, searching
499 * from (but not including) @nth_bit upwards. Bits are numbered
500 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
501 * usually). To start searching from the 0th bit, set @nth_bit to -1.
503 * Returns: the index of the first bit set which is higher than @nth_bit, or -1
504 * if no higher bits are set
507 (g_bit_nth_lsf) (gulong mask,
510 return g_bit_nth_lsf_impl (mask, nth_bit);
515 * @mask: a #gulong containing flags
516 * @nth_bit: the index of the bit to start the search from
518 * Find the position of the first bit set in @mask, searching
519 * from (but not including) @nth_bit downwards. Bits are numbered
520 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
521 * usually). To start searching from the last bit, set @nth_bit to
522 * -1 or GLIB_SIZEOF_LONG * 8.
524 * Returns: the index of the first bit set which is lower than @nth_bit, or -1
525 * if no lower bits are set
528 (g_bit_nth_msf) (gulong mask,
531 return g_bit_nth_msf_impl (mask, nth_bit);
539 * Gets the number of bits used to hold @number,
540 * e.g. if @number is 4, 3 bits are needed.
542 * Returns: the number of bits used to hold @number
545 (g_bit_storage) (gulong number)
547 return g_bit_storage_impl (number);
550 G_LOCK_DEFINE_STATIC (g_utils_global);
559 /* These must all be read/written with @g_utils_global held. */
560 static gchar *g_user_data_dir = NULL;
561 static gchar **g_system_data_dirs = NULL;
562 static gchar *g_user_cache_dir = NULL;
563 static gchar *g_user_config_dir = NULL;
564 static gchar *g_user_runtime_dir = NULL;
565 static gchar **g_system_config_dirs = NULL;
566 static gchar **g_user_special_dirs = NULL;
568 /* fifteen minutes of fame for everybody */
569 #define G_USER_DIRS_EXPIRE 15 * 60
574 get_special_folder (int csidl)
576 wchar_t path[MAX_PATH+1];
578 LPITEMIDLIST pidl = NULL;
580 gchar *retval = NULL;
582 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
585 b = SHGetPathFromIDListW (pidl, path);
587 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
588 CoTaskMemFree (pidl);
594 get_windows_directory_root (void)
596 wchar_t wwindowsdir[MAX_PATH];
598 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
600 /* Usually X:\Windows, but in terminal server environments
601 * might be an UNC path, AFAIK.
603 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
606 if (windowsdir == NULL)
607 return g_strdup ("C:\\");
609 p = (char *) g_path_skip_root (windowsdir);
610 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
616 return g_strdup ("C:\\");
621 /* HOLDS: g_utils_global_lock */
622 static UserDatabaseEntry *
623 g_get_user_database_entry (void)
625 static UserDatabaseEntry *entry;
627 if (g_once_init_enter (&entry))
629 static UserDatabaseEntry e;
633 struct passwd *pw = NULL;
634 gpointer buffer = NULL;
638 # if defined (HAVE_GETPWUID_R)
640 # ifdef _SC_GETPW_R_SIZE_MAX
641 /* This reurns the maximum length */
642 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
646 # else /* _SC_GETPW_R_SIZE_MAX */
648 # endif /* _SC_GETPW_R_SIZE_MAX */
650 logname = (gchar *) g_getenv ("LOGNAME");
655 /* we allocate 6 extra bytes to work around a bug in
656 * Mac OS < 10.3. See #156446
658 buffer = g_malloc (bufsize + 6);
662 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
663 if (!pw || (pw->pw_uid != getuid ())) {
664 /* LOGNAME is lying, fall back to looking up the uid */
665 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
668 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
670 error = error < 0 ? errno : error;
674 /* we bail out prematurely if the user id can't be found
675 * (should be pretty rare case actually), or if the buffer
676 * should be sufficiently big and lookups are still not
679 if (error == 0 || error == ENOENT)
681 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
685 if (bufsize > 32 * 1024)
687 g_warning ("getpwuid_r(): failed due to: %s.",
696 # endif /* HAVE_GETPWUID_R */
700 pw = getpwuid (getuid ());
704 e.user_name = g_strdup (pw->pw_name);
707 if (pw->pw_gecos && *pw->pw_gecos != '\0')
709 gchar **gecos_fields;
712 /* split the gecos field and substitute '&' */
713 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
714 name_parts = g_strsplit (gecos_fields[0], "&", 0);
715 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
716 e.real_name = g_strjoinv (pw->pw_name, name_parts);
717 g_strfreev (gecos_fields);
718 g_strfreev (name_parts);
723 e.home_dir = g_strdup (pw->pw_dir);
728 #endif /* G_OS_UNIX */
733 wchar_t buffer[UNLEN+1];
735 if (GetUserNameW (buffer, (LPDWORD) &len))
737 e.user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
738 e.real_name = g_strdup (e.user_name);
741 #endif /* G_OS_WIN32 */
744 e.user_name = g_strdup ("somebody");
746 e.real_name = g_strdup ("Unknown");
748 g_once_init_leave (&entry, &e);
757 * Gets the user name of the current user. The encoding of the returned
758 * string is system-defined. On UNIX, it might be the preferred file name
759 * encoding, or something else, and there is no guarantee that it is even
760 * consistent on a machine. On Windows, it is always UTF-8.
762 * Returns: (type filename): the user name of the current user.
765 g_get_user_name (void)
767 UserDatabaseEntry *entry;
769 entry = g_get_user_database_entry ();
771 return entry->user_name;
777 * Gets the real name of the user. This usually comes from the user's
778 * entry in the `passwd` file. The encoding of the returned string is
779 * system-defined. (On Windows, it is, however, always UTF-8.) If the
780 * real user name cannot be determined, the string "Unknown" is
783 * Returns: (type filename): the user's real name.
786 g_get_real_name (void)
788 UserDatabaseEntry *entry;
790 entry = g_get_user_database_entry ();
792 return entry->real_name;
795 /* Protected by @g_utils_global_lock. */
796 static gchar *g_home_dir = NULL; /* (owned) (nullable before initialised) */
799 g_build_home_dir (void)
803 /* We first check HOME and use it if it is set */
804 home_dir = g_strdup (g_getenv ("HOME"));
807 /* Only believe HOME if it is an absolute path and exists.
809 * We only do this check on Windows for a couple of reasons.
810 * Historically, we only did it there because we used to ignore $HOME
811 * on UNIX. There are concerns about enabling it now on UNIX because
812 * of things like autofs. In short, if the user has a bogus value in
813 * $HOME then they get what they pay for...
815 if (home_dir != NULL)
817 if (!(g_path_is_absolute (home_dir) &&
818 g_file_test (home_dir, G_FILE_TEST_IS_DIR)))
819 g_clear_pointer (&home_dir, g_free);
822 /* In case HOME is Unix-style (it happens), convert it to
825 if (home_dir != NULL)
828 while ((p = strchr (home_dir, '/')) != NULL)
832 if (home_dir == NULL)
834 /* USERPROFILE is probably the closest equivalent to $HOME? */
835 if (g_getenv ("USERPROFILE") != NULL)
836 home_dir = g_strdup (g_getenv ("USERPROFILE"));
839 if (home_dir == NULL)
840 home_dir = get_special_folder (CSIDL_PROFILE);
842 if (home_dir == NULL)
843 home_dir = get_windows_directory_root ();
844 #endif /* G_OS_WIN32 */
846 if (home_dir == NULL)
848 /* If we didn't get it from any of those methods, we will have
849 * to read the user database entry.
851 UserDatabaseEntry *entry = g_get_user_database_entry ();
852 home_dir = g_strdup (entry->home_dir);
855 /* If we have been denied access to /etc/passwd (for example, by an
856 * overly-zealous LSM), make up a junk value. The return value at this
857 * point is explicitly documented as ‘undefined’. */
858 if (home_dir == NULL)
860 g_warning ("Could not find home directory: $HOME is not set, and "
861 "user database could not be read.");
862 home_dir = g_strdup ("/");
865 return g_steal_pointer (&home_dir);
871 * Gets the current user's home directory.
873 * As with most UNIX tools, this function will return the value of the
874 * `HOME` environment variable if it is set to an existing absolute path
875 * name, falling back to the `passwd` file in the case that it is unset.
877 * If the path given in `HOME` is non-absolute, does not exist, or is
878 * not a directory, the result is undefined.
880 * Before version 2.36 this function would ignore the `HOME` environment
881 * variable, taking the value from the `passwd` database instead. This was
882 * changed to increase the compatibility of GLib with other programs (and
883 * the XDG basedir specification) and to increase testability of programs
884 * based on GLib (by making it easier to run them from test frameworks).
886 * If your program has a strong requirement for either the new or the
887 * old behaviour (and if you don't wish to increase your GLib
888 * dependency to ensure that the new behaviour is in effect) then you
889 * should either directly check the `HOME` environment variable yourself
890 * or unset it before calling any functions in GLib.
892 * Returns: (type filename): the current user's home directory
895 g_get_home_dir (void)
897 const gchar *home_dir;
899 G_LOCK (g_utils_global);
901 if (g_home_dir == NULL)
902 g_home_dir = g_build_home_dir ();
903 home_dir = g_home_dir;
905 G_UNLOCK (g_utils_global);
913 * Gets the directory to use for temporary files.
915 * On UNIX, this is taken from the `TMPDIR` environment variable.
916 * If the variable is not set, `P_tmpdir` is
917 * used, as defined by the system C library. Failing that, a
918 * hard-coded default of "/tmp" is returned.
920 * On Windows, the `TEMP` environment variable is used, with the
921 * root directory of the Windows installation (eg: "C:\") used
924 * The encoding of the returned string is system-defined. On Windows,
925 * it is always UTF-8. The return value is never %NULL or the empty
928 * Returns: (type filename): the directory to use for temporary files.
933 static gchar *tmp_dir;
935 if (g_once_init_enter (&tmp_dir))
940 tmp = g_strdup (g_getenv ("TEMP"));
942 if (tmp == NULL || *tmp == '\0')
945 tmp = get_windows_directory_root ();
947 #else /* G_OS_WIN32 */
948 tmp = g_strdup (g_getenv ("TMPDIR"));
951 if (tmp == NULL || *tmp == '\0')
955 tmp = g_strdup (P_tmpdir);
957 if (k > 1 && G_IS_DIR_SEPARATOR (tmp[k - 1]))
960 #endif /* P_tmpdir */
962 if (tmp == NULL || *tmp == '\0')
965 tmp = g_strdup ("/tmp");
967 #endif /* !G_OS_WIN32 */
969 g_once_init_leave (&tmp_dir, tmp);
978 * Return a name for the machine.
980 * The returned name is not necessarily a fully-qualified domain name,
981 * or even present in DNS or some other name service at all. It need
982 * not even be unique on your local network or site, but usually it
983 * is. Callers should not rely on the return value having any specific
984 * properties like uniqueness for security purposes. Even if the name
985 * of the machine is changed while an application is running, the
986 * return value from this function does not change. The returned
987 * string is owned by GLib and should not be modified or freed. If no
988 * name can be determined, a default fixed string "localhost" is
991 * The encoding of the returned string is UTF-8.
993 * Returns: the host name of the machine.
998 g_get_host_name (void)
1000 static gchar *hostname;
1002 if (g_once_init_enter (&hostname))
1008 gchar *tmp = g_malloc (sizeof (gchar) * 100);
1009 failed = (gethostname (tmp, sizeof (gchar) * 100) == -1);
1011 g_clear_pointer (&tmp, g_free);
1014 wchar_t tmp[MAX_COMPUTERNAME_LENGTH + 1];
1015 DWORD size = sizeof (tmp) / sizeof (tmp[0]);
1016 failed = (!GetComputerNameW (tmp, &size));
1018 utmp = g_utf16_to_utf8 (tmp, size, NULL, NULL, NULL);
1023 g_once_init_leave (&hostname, failed ? g_strdup ("localhost") : utmp);
1029 G_LOCK_DEFINE_STATIC (g_prgname);
1030 static gchar *g_prgname = NULL;
1035 * Gets the name of the program. This name should not be localized,
1036 * in contrast to g_get_application_name().
1038 * If you are using #GApplication the program name is set in
1039 * g_application_run(). In case of GDK or GTK+ it is set in
1040 * gdk_init(), which is called by gtk_init() and the
1041 * #GtkApplication::startup handler. The program name is found by
1042 * taking the last component of @argv[0].
1044 * Returns: the name of the program. The returned string belongs
1045 * to GLib and must not be modified or freed.
1048 g_get_prgname (void)
1054 if (g_prgname == NULL)
1056 static gboolean beenhere = FALSE;
1060 gchar *utf8_buf = NULL;
1061 wchar_t buf[MAX_PATH+1];
1064 if (GetModuleFileNameW (GetModuleHandle (NULL),
1065 buf, G_N_ELEMENTS (buf)) > 0)
1066 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1070 g_prgname = g_path_get_basename (utf8_buf);
1077 G_UNLOCK (g_prgname);
1084 * @prgname: the name of the program.
1086 * Sets the name of the program. This name should not be localized,
1087 * in contrast to g_set_application_name().
1089 * If you are using #GApplication the program name is set in
1090 * g_application_run(). In case of GDK or GTK+ it is set in
1091 * gdk_init(), which is called by gtk_init() and the
1092 * #GtkApplication::startup handler. The program name is found by
1093 * taking the last component of @argv[0].
1095 * Note that for thread-safety reasons this function can only be called once.
1098 g_set_prgname (const gchar *prgname)
1102 g_prgname = g_strdup (prgname);
1103 G_UNLOCK (g_prgname);
1106 G_LOCK_DEFINE_STATIC (g_application_name);
1107 static gchar *g_application_name = NULL;
1110 * g_get_application_name:
1112 * Gets a human-readable name for the application, as set by
1113 * g_set_application_name(). This name should be localized if
1114 * possible, and is intended for display to the user. Contrast with
1115 * g_get_prgname(), which gets a non-localized name. If
1116 * g_set_application_name() has not been called, returns the result of
1117 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1120 * Returns: human-readable application name. may return %NULL
1125 g_get_application_name (void)
1129 G_LOCK (g_application_name);
1130 retval = g_application_name;
1131 G_UNLOCK (g_application_name);
1134 return g_get_prgname ();
1140 * g_set_application_name:
1141 * @application_name: localized name of the application
1143 * Sets a human-readable name for the application. This name should be
1144 * localized if possible, and is intended for display to the user.
1145 * Contrast with g_set_prgname(), which sets a non-localized name.
1146 * g_set_prgname() will be called automatically by gtk_init(),
1147 * but g_set_application_name() will not.
1149 * Note that for thread safety reasons, this function can only
1152 * The application name will be used in contexts such as error messages,
1153 * or when displaying an application's name in the task list.
1158 g_set_application_name (const gchar *application_name)
1160 gboolean already_set = FALSE;
1162 G_LOCK (g_application_name);
1163 if (g_application_name)
1166 g_application_name = g_strdup (application_name);
1167 G_UNLOCK (g_application_name);
1170 g_warning ("g_set_application_name() called multiple times");
1173 /* Set @global_str to a copy of @new_value if it’s currently unset or has a
1174 * different value. If its current value matches @new_value, do nothing. If
1175 * replaced, we have to leak the old value as client code could still have
1176 * pointers to it. */
1178 set_str_if_different (gchar **global_str,
1180 const gchar *new_value)
1182 if (*global_str == NULL ||
1183 !g_str_equal (new_value, *global_str))
1185 g_debug ("g_set_user_dirs: Setting %s to %s", type, new_value);
1187 /* We have to leak the old value, as user code could be retaining pointers
1189 *global_str = g_strdup (new_value);
1194 set_strv_if_different (gchar ***global_strv,
1196 const gchar * const *new_value)
1198 if (*global_strv == NULL ||
1199 !g_strv_equal (new_value, (const gchar * const *) *global_strv))
1201 gchar *new_value_str = g_strjoinv (":", (gchar **) new_value);
1202 g_debug ("g_set_user_dirs: Setting %s to %s", type, new_value_str);
1203 g_free (new_value_str);
1205 /* We have to leak the old value, as user code could be retaining pointers
1207 *global_strv = g_strdupv ((gchar **) new_value);
1213 * @first_dir_type: Type of the first directory to set
1214 * @...: Value to set the first directory to, followed by additional type/value
1215 * pairs, followed by %NULL
1217 * Set one or more ‘user’ directories to custom values. This is intended to be
1218 * used by test code (particularly with the %G_TEST_OPTION_ISOLATE_DIRS option)
1219 * to override the values returned by the following functions, so that test
1220 * code can be run without touching an installed system and user data:
1222 * - g_get_home_dir() — use type `HOME`, pass a string
1223 * - g_get_user_cache_dir() — use type `XDG_CACHE_HOME`, pass a string
1224 * - g_get_system_config_dirs() — use type `XDG_CONFIG_DIRS`, pass a
1225 * %NULL-terminated string array
1226 * - g_get_user_config_dir() — use type `XDG_CONFIG_HOME`, pass a string
1227 * - g_get_system_data_dirs() — use type `XDG_DATA_DIRS`, pass a
1228 * %NULL-terminated string array
1229 * - g_get_user_data_dir() — use type `XDG_DATA_HOME`, pass a string
1230 * - g_get_user_runtime_dir() — use type `XDG_RUNTIME_DIR`, pass a string
1232 * The list must be terminated with a %NULL type. All of the values must be
1233 * non-%NULL — passing %NULL as a value won’t reset a directory. If a reference
1234 * to a directory from the calling environment needs to be kept, copy it before
1235 * the first call to g_set_user_dirs(). g_set_user_dirs() can be called multiple
1242 g_set_user_dirs (const gchar *first_dir_type,
1246 const gchar *dir_type;
1248 G_LOCK (g_utils_global);
1250 va_start (args, first_dir_type);
1252 for (dir_type = first_dir_type; dir_type != NULL; dir_type = va_arg (args, const gchar *))
1254 gconstpointer dir_value = va_arg (args, gconstpointer);
1255 g_assert (dir_value != NULL);
1257 if (g_str_equal (dir_type, "HOME"))
1258 set_str_if_different (&g_home_dir, dir_type, dir_value);
1259 else if (g_str_equal (dir_type, "XDG_CACHE_HOME"))
1260 set_str_if_different (&g_user_cache_dir, dir_type, dir_value);
1261 else if (g_str_equal (dir_type, "XDG_CONFIG_DIRS"))
1262 set_strv_if_different (&g_system_config_dirs, dir_type, dir_value);
1263 else if (g_str_equal (dir_type, "XDG_CONFIG_HOME"))
1264 set_str_if_different (&g_user_config_dir, dir_type, dir_value);
1265 else if (g_str_equal (dir_type, "XDG_DATA_DIRS"))
1266 set_strv_if_different (&g_system_data_dirs, dir_type, dir_value);
1267 else if (g_str_equal (dir_type, "XDG_DATA_HOME"))
1268 set_str_if_different (&g_user_data_dir, dir_type, dir_value);
1269 else if (g_str_equal (dir_type, "XDG_RUNTIME_DIR"))
1270 set_str_if_different (&g_user_runtime_dir, dir_type, dir_value);
1272 g_assert_not_reached ();
1277 G_UNLOCK (g_utils_global);
1281 g_build_user_data_dir (void)
1283 gchar *data_dir = NULL;
1284 const gchar *data_dir_env = g_getenv ("XDG_DATA_HOME");
1286 if (data_dir_env && data_dir_env[0])
1287 data_dir = g_strdup (data_dir_env);
1290 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1292 if (!data_dir || !data_dir[0])
1294 gchar *home_dir = g_build_home_dir ();
1295 data_dir = g_build_filename (home_dir, ".local", "share", NULL);
1299 return g_steal_pointer (&data_dir);
1303 * g_get_user_data_dir:
1305 * Returns a base directory in which to access application data such
1306 * as icons that is customized for a particular user.
1308 * On UNIX platforms this is determined using the mechanisms described
1310 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1311 * In this case the directory retrieved will be `XDG_DATA_HOME`.
1313 * On Windows it follows XDG Base Directory Specification if `XDG_DATA_HOME`
1314 * is defined. If `XDG_DATA_HOME` is undefined, the folder to use for local (as
1315 * opposed to roaming) application data is used instead. See the
1316 * [documentation for `CSIDL_LOCAL_APPDATA`](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx#csidl_local_appdata).
1317 * Note that in this case on Windows it will be the same
1318 * as what g_get_user_config_dir() returns.
1320 * Returns: (type filename): a string owned by GLib that must not be modified
1325 g_get_user_data_dir (void)
1327 const gchar *user_data_dir;
1329 G_LOCK (g_utils_global);
1331 if (g_user_data_dir == NULL)
1332 g_user_data_dir = g_build_user_data_dir ();
1333 user_data_dir = g_user_data_dir;
1335 G_UNLOCK (g_utils_global);
1337 return user_data_dir;
1341 g_build_user_config_dir (void)
1343 gchar *config_dir = NULL;
1344 const gchar *config_dir_env = g_getenv ("XDG_CONFIG_HOME");
1346 if (config_dir_env && config_dir_env[0])
1347 config_dir = g_strdup (config_dir_env);
1350 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1352 if (!config_dir || !config_dir[0])
1354 gchar *home_dir = g_build_home_dir ();
1355 config_dir = g_build_filename (home_dir, ".config", NULL);
1359 return g_steal_pointer (&config_dir);
1363 * g_get_user_config_dir:
1365 * Returns a base directory in which to store user-specific application
1366 * configuration information such as user preferences and settings.
1368 * On UNIX platforms this is determined using the mechanisms described
1370 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1371 * In this case the directory retrieved will be `XDG_CONFIG_HOME`.
1373 * On Windows it follows XDG Base Directory Specification if `XDG_CONFIG_HOME` is defined.
1374 * If `XDG_CONFIG_HOME` is undefined, the folder to use for local (as opposed
1375 * to roaming) application data is used instead. See the
1376 * [documentation for `CSIDL_LOCAL_APPDATA`](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx#csidl_local_appdata).
1377 * Note that in this case on Windows it will be the same
1378 * as what g_get_user_data_dir() returns.
1380 * Returns: (type filename): a string owned by GLib that must not be modified
1385 g_get_user_config_dir (void)
1387 const gchar *user_config_dir;
1389 G_LOCK (g_utils_global);
1391 if (g_user_config_dir == NULL)
1392 g_user_config_dir = g_build_user_config_dir ();
1393 user_config_dir = g_user_config_dir;
1395 G_UNLOCK (g_utils_global);
1397 return user_config_dir;
1401 g_build_user_cache_dir (void)
1403 gchar *cache_dir = NULL;
1404 const gchar *cache_dir_env = g_getenv ("XDG_CACHE_HOME");
1406 if (cache_dir_env && cache_dir_env[0])
1407 cache_dir = g_strdup (cache_dir_env);
1410 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE);
1412 if (!cache_dir || !cache_dir[0])
1414 gchar *home_dir = g_build_home_dir ();
1415 cache_dir = g_build_filename (home_dir, ".cache", NULL);
1419 return g_steal_pointer (&cache_dir);
1423 * g_get_user_cache_dir:
1425 * Returns a base directory in which to store non-essential, cached
1426 * data specific to particular user.
1428 * On UNIX platforms this is determined using the mechanisms described
1430 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1431 * In this case the directory retrieved will be `XDG_CACHE_HOME`.
1433 * On Windows it follows XDG Base Directory Specification if `XDG_CACHE_HOME` is defined.
1434 * If `XDG_CACHE_HOME` is undefined, the directory that serves as a common
1435 * repository for temporary Internet files is used instead. A typical path is
1436 * `C:\Documents and Settings\username\Local Settings\Temporary Internet Files`.
1437 * 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).
1439 * Returns: (type filename): a string owned by GLib that must not be modified
1444 g_get_user_cache_dir (void)
1446 const gchar *user_cache_dir;
1448 G_LOCK (g_utils_global);
1450 if (g_user_cache_dir == NULL)
1451 g_user_cache_dir = g_build_user_cache_dir ();
1452 user_cache_dir = g_user_cache_dir;
1454 G_UNLOCK (g_utils_global);
1456 return user_cache_dir;
1460 g_build_user_runtime_dir (void)
1462 gchar *runtime_dir = NULL;
1463 const gchar *runtime_dir_env = g_getenv ("XDG_RUNTIME_DIR");
1465 if (runtime_dir_env && runtime_dir_env[0])
1466 runtime_dir = g_strdup (runtime_dir_env);
1469 runtime_dir = g_build_user_cache_dir ();
1471 /* The user should be able to rely on the directory existing
1472 * when the function returns. Probably it already does, but
1473 * let's make sure. Just do mkdir() directly since it will be
1474 * no more expensive than a stat() in the case that the
1475 * directory already exists and is a lot easier.
1477 * $XDG_CACHE_HOME is probably ~/.cache/ so as long as $HOME
1478 * exists this will work. If the user changed $XDG_CACHE_HOME
1479 * then they can make sure that it exists...
1481 (void) g_mkdir (runtime_dir, 0700);
1484 return g_steal_pointer (&runtime_dir);
1488 * g_get_user_runtime_dir:
1490 * Returns a directory that is unique to the current user on the local
1493 * This is determined using the mechanisms described
1495 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1496 * This is the directory
1497 * specified in the `XDG_RUNTIME_DIR` environment variable.
1498 * In the case that this variable is not set, we return the value of
1499 * g_get_user_cache_dir(), after verifying that it exists.
1501 * Returns: (type filename): a string owned by GLib that must not be
1502 * modified or freed.
1507 g_get_user_runtime_dir (void)
1509 const gchar *user_runtime_dir;
1511 G_LOCK (g_utils_global);
1513 if (g_user_runtime_dir == NULL)
1514 g_user_runtime_dir = g_build_user_runtime_dir ();
1515 user_runtime_dir = g_user_runtime_dir;
1517 G_UNLOCK (g_utils_global);
1519 return user_runtime_dir;
1525 find_folder (OSType type)
1527 gchar *filename = NULL;
1530 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
1532 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
1536 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
1540 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
1544 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
1546 CFStringGetCString (path, filename,
1547 CFStringGetLength (path) * 3 + 1,
1548 kCFStringEncodingUTF8);
1562 load_user_special_dirs (void)
1564 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
1565 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
1566 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
1567 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
1568 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
1569 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
1570 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
1571 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
1574 #elif defined(G_OS_WIN32)
1577 load_user_special_dirs (void)
1579 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1583 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
1585 static const GUID FOLDERID_Downloads =
1586 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1587 static const GUID FOLDERID_Public =
1588 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1592 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
1593 "SHGetKnownFolderPath");
1595 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1596 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
1598 if (p_SHGetKnownFolderPath == NULL)
1600 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1605 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1608 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1609 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
1610 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1611 CoTaskMemFree (wcp);
1614 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1617 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
1618 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
1620 if (p_SHGetKnownFolderPath == NULL)
1623 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1628 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
1631 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1632 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
1633 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1634 CoTaskMemFree (wcp);
1637 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1640 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
1641 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
1644 #else /* default is unix */
1646 /* adapted from xdg-user-dir-lookup.c
1648 * Copyright (C) 2007 Red Hat Inc.
1650 * Permission is hereby granted, free of charge, to any person
1651 * obtaining a copy of this software and associated documentation files
1652 * (the "Software"), to deal in the Software without restriction,
1653 * including without limitation the rights to use, copy, modify, merge,
1654 * publish, distribute, sublicense, and/or sell copies of the Software,
1655 * and to permit persons to whom the Software is furnished to do so,
1656 * subject to the following conditions:
1658 * The above copyright notice and this permission notice shall be
1659 * included in all copies or substantial portions of the Software.
1661 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1662 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1663 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1664 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1665 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1666 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1667 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1671 load_user_special_dirs (void)
1673 gchar *config_dir = NULL;
1679 config_dir = g_build_user_config_dir ();
1680 config_file = g_build_filename (config_dir,
1683 g_free (config_dir);
1685 if (!g_file_get_contents (config_file, &data, NULL, NULL))
1687 g_free (config_file);
1691 lines = g_strsplit (data, "\n", -1);
1692 n_lines = g_strv_length (lines);
1695 for (i = 0; i < n_lines; i++)
1697 gchar *buffer = lines[i];
1700 gboolean is_relative = FALSE;
1701 GUserDirectory directory;
1703 /* Remove newline at end */
1704 len = strlen (buffer);
1705 if (len > 0 && buffer[len - 1] == '\n')
1706 buffer[len - 1] = 0;
1709 while (*p == ' ' || *p == '\t')
1712 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
1714 directory = G_USER_DIRECTORY_DESKTOP;
1715 p += strlen ("XDG_DESKTOP_DIR");
1717 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
1719 directory = G_USER_DIRECTORY_DOCUMENTS;
1720 p += strlen ("XDG_DOCUMENTS_DIR");
1722 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
1724 directory = G_USER_DIRECTORY_DOWNLOAD;
1725 p += strlen ("XDG_DOWNLOAD_DIR");
1727 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
1729 directory = G_USER_DIRECTORY_MUSIC;
1730 p += strlen ("XDG_MUSIC_DIR");
1732 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
1734 directory = G_USER_DIRECTORY_PICTURES;
1735 p += strlen ("XDG_PICTURES_DIR");
1737 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
1739 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
1740 p += strlen ("XDG_PUBLICSHARE_DIR");
1742 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
1744 directory = G_USER_DIRECTORY_TEMPLATES;
1745 p += strlen ("XDG_TEMPLATES_DIR");
1747 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
1749 directory = G_USER_DIRECTORY_VIDEOS;
1750 p += strlen ("XDG_VIDEOS_DIR");
1755 while (*p == ' ' || *p == '\t')
1762 while (*p == ' ' || *p == '\t')
1769 if (strncmp (p, "$HOME", 5) == 0)
1777 d = strrchr (p, '"');
1784 /* remove trailing slashes */
1786 if (d[len - 1] == '/')
1791 gchar *home_dir = g_build_home_dir ();
1792 g_user_special_dirs[directory] = g_build_filename (home_dir, d, NULL);
1796 g_user_special_dirs[directory] = g_strdup (d);
1800 g_free (config_file);
1803 #endif /* platform-specific load_user_special_dirs implementations */
1807 * g_reload_user_special_dirs_cache:
1809 * Resets the cache used for g_get_user_special_dir(), so
1810 * that the latest on-disk version is used. Call this only
1811 * if you just changed the data on disk yourself.
1813 * Due to thread safety issues this may cause leaking of strings
1814 * that were previously returned from g_get_user_special_dir()
1815 * that can't be freed. We ensure to only leak the data for
1816 * the directories that actually changed value though.
1821 g_reload_user_special_dirs_cache (void)
1825 G_LOCK (g_utils_global);
1827 if (g_user_special_dirs != NULL)
1829 /* save a copy of the pointer, to check if some memory can be preserved */
1830 char **old_g_user_special_dirs = g_user_special_dirs;
1833 /* recreate and reload our cache */
1834 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1835 load_user_special_dirs ();
1837 /* only leak changed directories */
1838 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
1840 old_val = old_g_user_special_dirs[i];
1841 if (g_user_special_dirs[i] == NULL)
1843 g_user_special_dirs[i] = old_val;
1845 else if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
1848 g_free (g_user_special_dirs[i]);
1849 g_user_special_dirs[i] = old_val;
1855 /* free the old array */
1856 g_free (old_g_user_special_dirs);
1859 G_UNLOCK (g_utils_global);
1863 * g_get_user_special_dir:
1864 * @directory: the logical id of special directory
1866 * Returns the full path of a special directory using its logical id.
1868 * On UNIX this is done using the XDG special user directories.
1869 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
1870 * falls back to `$HOME/Desktop` when XDG special user directories have
1873 * Depending on the platform, the user might be able to change the path
1874 * of the special directory without requiring the session to restart; GLib
1875 * will not reflect any change once the special directories are loaded.
1877 * Returns: (type filename): the path to the specified special directory, or
1878 * %NULL if the logical id was not found. The returned string is owned by
1879 * GLib and should not be modified or freed.
1884 g_get_user_special_dir (GUserDirectory directory)
1886 const gchar *user_special_dir;
1888 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
1889 directory < G_USER_N_DIRECTORIES, NULL);
1891 G_LOCK (g_utils_global);
1893 if (G_UNLIKELY (g_user_special_dirs == NULL))
1895 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1897 load_user_special_dirs ();
1899 /* Special-case desktop for historical compatibility */
1900 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
1902 gchar *home_dir = g_build_home_dir ();
1903 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = g_build_filename (home_dir, "Desktop", NULL);
1907 user_special_dir = g_user_special_dirs[directory];
1909 G_UNLOCK (g_utils_global);
1911 return user_special_dir;
1916 #undef g_get_system_data_dirs
1919 get_module_for_address (gconstpointer address)
1921 /* Holds the g_utils_global lock */
1923 static gboolean beenhere = FALSE;
1924 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
1925 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
1926 HMODULE hmodule = NULL;
1933 p_GetModuleHandleExA =
1934 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1935 "GetModuleHandleExA");
1939 if (p_GetModuleHandleExA == NULL ||
1940 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
1941 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
1944 MEMORY_BASIC_INFORMATION mbi;
1945 VirtualQuery (address, &mbi, sizeof (mbi));
1946 hmodule = (HMODULE) mbi.AllocationBase;
1953 get_module_share_dir (gconstpointer address)
1959 hmodule = get_module_for_address (address);
1960 if (hmodule == NULL)
1963 filename = g_win32_get_package_installation_directory_of_module (hmodule);
1964 retval = g_build_filename (filename, "share", NULL);
1970 static const gchar * const *
1971 g_win32_get_system_data_dirs_for_module_real (void (*address_of_function)(void))
1975 static GHashTable *per_module_data_dirs = NULL;
1981 if (address_of_function)
1983 G_LOCK (g_utils_global);
1984 hmodule = get_module_for_address (address_of_function);
1985 if (hmodule != NULL)
1987 if (per_module_data_dirs == NULL)
1988 per_module_data_dirs = g_hash_table_new (NULL, NULL);
1991 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
1995 G_UNLOCK (g_utils_global);
1996 return (const gchar * const *) retval;
2002 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2004 /* Documents and Settings\All Users\Application Data */
2005 p = get_special_folder (CSIDL_COMMON_APPDATA);
2007 g_array_append_val (data_dirs, p);
2009 /* Documents and Settings\All Users\Documents */
2010 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2012 g_array_append_val (data_dirs, p);
2014 /* Using the above subfolders of Documents and Settings perhaps
2015 * makes sense from a Windows perspective.
2017 * But looking at the actual use cases of this function in GTK+
2018 * and GNOME software, what we really want is the "share"
2019 * subdirectory of the installation directory for the package
2020 * our caller is a part of.
2022 * The address_of_function parameter, if non-NULL, points to a
2023 * function in the calling module. Use that to determine that
2024 * module's installation folder, and use its "share" subfolder.
2026 * Additionally, also use the "share" subfolder of the installation
2027 * locations of GLib and the .exe file being run.
2029 * To guard against none of the above being what is really wanted,
2030 * callers of this function should have Win32-specific code to look
2031 * up their installation folder themselves, and handle a subfolder
2032 * "share" of it in the same way as the folders returned from this
2036 p = get_module_share_dir (address_of_function);
2038 g_array_append_val (data_dirs, p);
2040 if (glib_dll != NULL)
2042 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
2043 p = g_build_filename (glib_root, "share", NULL);
2045 g_array_append_val (data_dirs, p);
2049 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
2050 p = g_build_filename (exe_root, "share", NULL);
2052 g_array_append_val (data_dirs, p);
2055 retval = (gchar **) g_array_free (data_dirs, FALSE);
2057 if (address_of_function)
2059 if (hmodule != NULL)
2060 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2061 G_UNLOCK (g_utils_global);
2064 return (const gchar * const *) retval;
2067 const gchar * const *
2068 g_win32_get_system_data_dirs_for_module (void (*address_of_function)(void))
2070 gboolean should_call_g_get_system_data_dirs;
2072 should_call_g_get_system_data_dirs = TRUE;
2073 /* These checks are the same as the ones that g_build_system_data_dirs() does.
2074 * Please keep them in sync.
2076 G_LOCK (g_utils_global);
2078 if (!g_system_data_dirs)
2080 const gchar *data_dirs = g_getenv ("XDG_DATA_DIRS");
2082 if (!data_dirs || !data_dirs[0])
2083 should_call_g_get_system_data_dirs = FALSE;
2086 G_UNLOCK (g_utils_global);
2088 /* There is a subtle difference between g_win32_get_system_data_dirs_for_module (NULL),
2089 * which is what GLib code can normally call,
2090 * and g_win32_get_system_data_dirs_for_module (&_g_win32_get_system_data_dirs),
2091 * which is what the inline function used by non-GLib code calls.
2092 * The former gets prefix relative to currently-running executable,
2093 * the latter - relative to the module that calls _g_win32_get_system_data_dirs()
2094 * (disguised as g_get_system_data_dirs()), which could be an executable or
2095 * a DLL that is located somewhere else.
2096 * This is why that inline function in gutils.h exists, and why we can't just
2097 * call g_get_system_data_dirs() from there - because we need to get the address
2098 * local to the non-GLib caller-module.
2102 * g_get_system_data_dirs() will fall back to calling
2103 * g_win32_get_system_data_dirs_for_module_real(NULL) if XDG_DATA_DIRS is NULL
2104 * or an empty string. The checks above ensure that we do not call it in such
2105 * cases and use the address_of_function that we've been given by the inline function.
2106 * The reason we're calling g_get_system_data_dirs /at all/ is to give
2107 * XDG_DATA_DIRS precedence (if it is set).
2109 if (should_call_g_get_system_data_dirs)
2110 return g_get_system_data_dirs ();
2112 return g_win32_get_system_data_dirs_for_module_real (address_of_function);
2118 g_build_system_data_dirs (void)
2120 gchar **data_dir_vector = NULL;
2121 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2123 /* These checks are the same as the ones that g_win32_get_system_data_dirs_for_module()
2124 * does. Please keep them in sync.
2127 if (!data_dirs || !data_dirs[0])
2128 data_dirs = "/usr/local/share/:/usr/share/";
2130 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2132 if (!data_dirs || !data_dirs[0])
2133 data_dir_vector = g_strdupv ((gchar **) g_win32_get_system_data_dirs_for_module_real (NULL));
2135 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2138 return g_steal_pointer (&data_dir_vector);
2142 * g_get_system_data_dirs:
2144 * Returns an ordered list of base directories in which to access
2145 * system-wide application data.
2147 * On UNIX platforms this is determined using the mechanisms described
2149 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec)
2150 * In this case the list of directories retrieved will be `XDG_DATA_DIRS`.
2152 * On Windows it follows XDG Base Directory Specification if `XDG_DATA_DIRS` is defined.
2153 * If `XDG_DATA_DIRS` is undefined,
2154 * the first elements in the list are the Application Data
2155 * and Documents folders for All Users. (These can be determined only
2156 * on Windows 2000 or later and are not present in the list on other
2157 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2158 * CSIDL_COMMON_DOCUMENTS.
2160 * Then follows the "share" subfolder in the installation folder for
2161 * the package containing the DLL that calls this function, if it can
2164 * Finally the list contains the "share" subfolder in the installation
2165 * folder for GLib, and in the installation folder for the package the
2166 * application's .exe file belongs to.
2168 * The installation folders above are determined by looking up the
2169 * folder where the module (DLL or EXE) in question is located. If the
2170 * folder's name is "bin", its parent is used, otherwise the folder
2173 * Note that on Windows the returned list can vary depending on where
2174 * this function is called.
2176 * Returns: (array zero-terminated=1) (element-type filename) (transfer none):
2177 * a %NULL-terminated array of strings owned by GLib that must not be
2178 * modified or freed.
2182 const gchar * const *
2183 g_get_system_data_dirs (void)
2185 const gchar * const *system_data_dirs;
2187 G_LOCK (g_utils_global);
2189 if (g_system_data_dirs == NULL)
2190 g_system_data_dirs = g_build_system_data_dirs ();
2191 system_data_dirs = (const gchar * const *) g_system_data_dirs;
2193 G_UNLOCK (g_utils_global);
2195 return system_data_dirs;
2199 g_build_system_config_dirs (void)
2201 gchar **conf_dir_vector = NULL;
2202 const gchar *conf_dirs = g_getenv ("XDG_CONFIG_DIRS");
2206 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2210 gchar *special_conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2212 if (special_conf_dirs)
2213 conf_dir_vector = g_strsplit (special_conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2215 /* Return empty list */
2216 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2218 g_free (special_conf_dirs);
2221 if (!conf_dirs || !conf_dirs[0])
2222 conf_dirs = "/etc/xdg";
2224 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2227 return g_steal_pointer (&conf_dir_vector);
2231 * g_get_system_config_dirs:
2233 * Returns an ordered list of base directories in which to access
2234 * system-wide configuration information.
2236 * On UNIX platforms this is determined using the mechanisms described
2238 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2239 * In this case the list of directories retrieved will be `XDG_CONFIG_DIRS`.
2241 * On Windows it follows XDG Base Directory Specification if `XDG_CONFIG_DIRS` is defined.
2242 * If `XDG_CONFIG_DIRS` is undefined, the directory that contains application
2243 * data for all users is used instead. A typical path is
2244 * `C:\Documents and Settings\All Users\Application Data`.
2245 * This folder is used for application data
2246 * that is not user specific. For example, an application can store
2247 * a spell-check dictionary, a database of clip art, or a log file in the
2248 * CSIDL_COMMON_APPDATA folder. This information will not roam and is available
2249 * to anyone using the computer.
2251 * Returns: (array zero-terminated=1) (element-type filename) (transfer none):
2252 * a %NULL-terminated array of strings owned by GLib that must not be
2253 * modified or freed.
2257 const gchar * const *
2258 g_get_system_config_dirs (void)
2260 const gchar * const *system_config_dirs;
2262 G_LOCK (g_utils_global);
2264 if (g_system_config_dirs == NULL)
2265 g_system_config_dirs = g_build_system_config_dirs ();
2266 system_config_dirs = (const gchar * const *) g_system_config_dirs;
2268 G_UNLOCK (g_utils_global);
2270 return system_config_dirs;
2274 * g_nullify_pointer:
2275 * @nullify_location: (not nullable): the memory address of the pointer.
2277 * Set the pointer at the specified location to %NULL.
2280 g_nullify_pointer (gpointer *nullify_location)
2282 g_return_if_fail (nullify_location != NULL);
2284 *nullify_location = NULL;
2287 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2288 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2289 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2290 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2291 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2292 #define EXABYTE_FACTOR (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2294 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2295 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2296 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2297 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2298 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2299 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2303 * @size: a size in bytes
2305 * Formats a size (for example the size of a file) into a human readable
2306 * string. Sizes are rounded to the nearest size prefix (kB, MB, GB)
2307 * and are displayed rounded to the nearest tenth. E.g. the file size
2308 * 3292528 bytes will be converted into the string "3.2 MB".
2310 * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2312 * This string should be freed with g_free() when not needed any longer.
2314 * See g_format_size_full() for more options about how the size might be
2317 * Returns: a newly-allocated formatted string containing a human readable
2323 g_format_size (guint64 size)
2325 return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2330 * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2331 * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2332 * of the returned string. For example, "45.6 kB (45,612 bytes)".
2333 * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2334 * suffixes. IEC units should only be used for reporting things with
2335 * a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2336 * Network and storage sizes should be reported in the normal SI units.
2337 * @G_FORMAT_SIZE_BITS: set the size as a quantity in bits, rather than
2338 * bytes, and return units in bits. For example, ‘Mb’ rather than ‘MB’.
2340 * Flags to modify the format of the string returned by g_format_size_full().
2343 #pragma GCC diagnostic push
2344 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
2347 * g_format_size_full:
2348 * @size: a size in bytes
2349 * @flags: #GFormatSizeFlags to modify the output
2353 * This function is similar to g_format_size() but allows for flags
2354 * that modify the output. See #GFormatSizeFlags.
2356 * Returns: a newly-allocated formatted string containing a human
2357 * readable file size
2362 g_format_size_full (guint64 size,
2363 GFormatSizeFlags flags)
2379 const struct Format formats[4][6] = {
2381 { KILOBYTE_FACTOR, N_("%.1f kB") },
2382 { MEGABYTE_FACTOR, N_("%.1f MB") },
2383 { GIGABYTE_FACTOR, N_("%.1f GB") },
2384 { TERABYTE_FACTOR, N_("%.1f TB") },
2385 { PETABYTE_FACTOR, N_("%.1f PB") },
2386 { EXABYTE_FACTOR, N_("%.1f EB") }
2389 { KIBIBYTE_FACTOR, N_("%.1f KiB") },
2390 { MEBIBYTE_FACTOR, N_("%.1f MiB") },
2391 { GIBIBYTE_FACTOR, N_("%.1f GiB") },
2392 { TEBIBYTE_FACTOR, N_("%.1f TiB") },
2393 { PEBIBYTE_FACTOR, N_("%.1f PiB") },
2394 { EXBIBYTE_FACTOR, N_("%.1f EiB") }
2397 { KILOBYTE_FACTOR, N_("%.1f kb") },
2398 { MEGABYTE_FACTOR, N_("%.1f Mb") },
2399 { GIGABYTE_FACTOR, N_("%.1f Gb") },
2400 { TERABYTE_FACTOR, N_("%.1f Tb") },
2401 { PETABYTE_FACTOR, N_("%.1f Pb") },
2402 { EXABYTE_FACTOR, N_("%.1f Eb") }
2405 { KIBIBYTE_FACTOR, N_("%.1f Kib") },
2406 { MEBIBYTE_FACTOR, N_("%.1f Mib") },
2407 { GIBIBYTE_FACTOR, N_("%.1f Gib") },
2408 { TEBIBYTE_FACTOR, N_("%.1f Tib") },
2409 { PEBIBYTE_FACTOR, N_("%.1f Pib") },
2410 { EXBIBYTE_FACTOR, N_("%.1f Eib") }
2417 string = g_string_new (NULL);
2419 switch (flags & ~G_FORMAT_SIZE_LONG_FORMAT)
2421 case G_FORMAT_SIZE_DEFAULT:
2422 index = FORMAT_BYTES;
2424 case (G_FORMAT_SIZE_DEFAULT | G_FORMAT_SIZE_IEC_UNITS):
2425 index = FORMAT_BYTES_IEC;
2427 case G_FORMAT_SIZE_BITS:
2428 index = FORMAT_BITS;
2430 case (G_FORMAT_SIZE_BITS | G_FORMAT_SIZE_IEC_UNITS):
2431 index = FORMAT_BITS_IEC;
2434 g_assert_not_reached ();
2438 if (size < formats[index][0].factor)
2440 const char * format;
2442 if (index == FORMAT_BYTES || index == FORMAT_BYTES_IEC)
2444 format = g_dngettext (GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size);
2448 format = g_dngettext (GETTEXT_PACKAGE, "%u bit", "%u bits", (guint) size);
2451 g_string_printf (string, format, (guint) size);
2453 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2457 const gsize n = G_N_ELEMENTS (formats[index]);
2461 * Point the last format (the highest unit) by default
2462 * and then then scan all formats, starting with the 2nd one
2463 * because the 1st is already managed by with the plural form
2465 const struct Format * f = &formats[index][n - 1];
2467 for (i = 1; i < n; i++)
2469 if (size < formats[index][i].factor)
2471 f = &formats[index][i - 1];
2476 g_string_printf (string, _(f->string), (gdouble) size / (gdouble) f->factor);
2479 if (flags & G_FORMAT_SIZE_LONG_FORMAT)
2481 /* First problem: we need to use the number of bytes to decide on
2482 * the plural form that is used for display, but the number of
2483 * bytes potentially exceeds the size of a guint (which is what
2484 * ngettext() takes).
2486 * From a pragmatic standpoint, it seems that all known languages
2487 * base plural forms on one or both of the following:
2489 * - the lowest digits of the number
2491 * - if the number if greater than some small value
2493 * Here's how we fake it: Draw an arbitrary line at one thousand.
2494 * If the number is below that, then fine. If it is above it,
2495 * then we take the modulus of the number by one thousand (in
2496 * order to keep the lowest digits) and add one thousand to that
2497 * (in order to ensure that 1001 is not treated the same as 1).
2499 guint plural_form = size < 1000 ? size : size % 1000 + 1000;
2501 /* Second problem: we need to translate the string "%u byte/bit" and
2502 * "%u bytes/bits" for pluralisation, but the correct number format to
2503 * use for a gsize is different depending on which architecture
2506 * Solution: format the number separately and use "%s bytes/bits" on
2509 const gchar *translated_format;
2510 gchar *formatted_number;
2512 if (index == FORMAT_BYTES || index == FORMAT_BYTES_IEC)
2514 /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2515 translated_format = g_dngettext (GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
2519 /* Translators: the %s in "%s bits" will always be replaced by a number. */
2520 translated_format = g_dngettext (GETTEXT_PACKAGE, "%s bit", "%s bits", plural_form);
2522 /* XXX: Windows doesn't support the "'" format modifier, so we
2523 * must not use it there. Instead, just display the number
2524 * without separation. Bug #655336 is open until a solution is
2528 formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2530 formatted_number = g_strdup_printf ("%"G_GUINT64_FORMAT, size);
2533 g_string_append (string, " (");
2534 g_string_append_printf (string, translated_format, formatted_number);
2535 g_free (formatted_number);
2536 g_string_append (string, ")");
2539 return g_string_free (string, FALSE);
2542 #pragma GCC diagnostic pop
2545 * g_format_size_for_display:
2546 * @size: a size in bytes
2548 * Formats a size (for example the size of a file) into a human
2549 * readable string. Sizes are rounded to the nearest size prefix
2550 * (KB, MB, GB) and are displayed rounded to the nearest tenth.
2551 * E.g. the file size 3292528 bytes will be converted into the
2554 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2556 * This string should be freed with g_free() when not needed any longer.
2558 * Returns: a newly-allocated formatted string containing a human
2559 * readable file size
2563 * Deprecated:2.30: This function is broken due to its use of SI
2564 * suffixes to denote IEC units. Use g_format_size() instead.
2567 g_format_size_for_display (goffset size)
2569 if (size < (goffset) KIBIBYTE_FACTOR)
2570 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
2573 gdouble displayed_size;
2575 if (size < (goffset) MEBIBYTE_FACTOR)
2577 displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
2578 /* Translators: this is from the deprecated function g_format_size_for_display() which uses 'KB' to
2579 * mean 1024 bytes. I am aware that 'KB' is not correct, but it has been preserved for reasons of
2580 * compatibility. Users will not see this string unless a program is using this deprecated function.
2581 * Please translate as literally as possible.
2583 return g_strdup_printf (_("%.1f KB"), displayed_size);
2585 else if (size < (goffset) GIBIBYTE_FACTOR)
2587 displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
2588 return g_strdup_printf (_("%.1f MB"), displayed_size);
2590 else if (size < (goffset) TEBIBYTE_FACTOR)
2592 displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
2593 return g_strdup_printf (_("%.1f GB"), displayed_size);
2595 else if (size < (goffset) PEBIBYTE_FACTOR)
2597 displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
2598 return g_strdup_printf (_("%.1f TB"), displayed_size);
2600 else if (size < (goffset) EXBIBYTE_FACTOR)
2602 displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
2603 return g_strdup_printf (_("%.1f PB"), displayed_size);
2607 displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
2608 return g_strdup_printf (_("%.1f EB"), displayed_size);
2613 #if defined (G_OS_WIN32) && !defined (_WIN64)
2615 /* Binary compatibility versions. Not for newly compiled code. */
2617 _GLIB_EXTERN const gchar *g_get_user_name_utf8 (void);
2618 _GLIB_EXTERN const gchar *g_get_real_name_utf8 (void);
2619 _GLIB_EXTERN const gchar *g_get_home_dir_utf8 (void);
2620 _GLIB_EXTERN const gchar *g_get_tmp_dir_utf8 (void);
2621 _GLIB_EXTERN gchar *g_find_program_in_path_utf8 (const gchar *program);
2624 g_find_program_in_path_utf8 (const gchar *program)
2626 return g_find_program_in_path (program);
2629 const gchar *g_get_user_name_utf8 (void) { return g_get_user_name (); }
2630 const gchar *g_get_real_name_utf8 (void) { return g_get_real_name (); }
2631 const gchar *g_get_home_dir_utf8 (void) { return g_get_home_dir (); }
2632 const gchar *g_get_tmp_dir_utf8 (void) { return g_get_tmp_dir (); }
2638 * Returns %TRUE if the current process was executed as setuid
2641 g_check_setuid (void)
2643 #if defined(HAVE_SYS_AUXV_H) && defined(HAVE_GETAUXVAL) && defined(AT_SECURE)
2644 unsigned long value;
2648 value = getauxval (AT_SECURE);
2651 g_error ("getauxval () failed: %s", g_strerror (errsv));
2653 #elif defined(HAVE_ISSETUGID) && !defined(__BIONIC__)
2654 /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
2656 /* Android had it in older versions but the new 64 bit ABI does not
2657 * have it anymore, and some versions of the 32 bit ABI neither.
2658 * https://code.google.com/p/android-developer-preview/issues/detail?id=168
2660 return issetugid ();
2661 #elif defined(G_OS_UNIX)
2662 uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
2663 gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
2665 static gsize check_setuid_initialised;
2666 static gboolean is_setuid;
2668 if (g_once_init_enter (&check_setuid_initialised))
2670 #ifdef HAVE_GETRESUID
2671 /* These aren't in the header files, so we prototype them here.
2673 int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
2674 int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);
2676 if (getresuid (&ruid, &euid, &suid) != 0 ||
2677 getresgid (&rgid, &egid, &sgid) != 0)
2678 #endif /* HAVE_GETRESUID */
2680 suid = ruid = getuid ();
2681 sgid = rgid = getgid ();
2686 is_setuid = (ruid != euid || ruid != suid ||
2687 rgid != egid || rgid != sgid);
2689 g_once_init_leave (&check_setuid_initialised, 1);
2701 * A wrapper for the POSIX abort() function.
2703 * On Windows it is a function that makes extra effort (including a call
2704 * to abort()) to ensure that a debugger-catchable exception is thrown
2705 * before the program terminates.
2707 * See your C library manual for more details about abort().
2714 /* One call to break the debugger */
2716 /* One call in case CRT does get saner about abort() behaviour */
2718 /* And one call to bind them all and terminate the program for sure */