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 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.
30 #include "glibconfig.h"
37 #include <ctype.h> /* For tolower() */
39 #include <sys/types.h>
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_PARAM_H
47 #include <sys/param.h>
49 #ifdef HAVE_CRT_EXTERNS_H
50 #include <crt_externs.h> /* for _NSGetEnviron */
53 /* implement gutils's inline functions
55 #define G_IMPLEMENT_INLINES 1
59 #include "glib-init.h"
60 #include "glib-private.h"
62 #include "gfileutils.h"
66 #include "gtestutils.h"
68 #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)
230 result = atexit ((void (*)(void)) func);
233 g_error ("Could not register atexit() function: %s",
238 /* Based on execvp() from GNU Libc.
239 * Some of this code is cut-and-pasted into gspawn.c
243 my_strchrnul (const gchar *str,
246 gchar *p = (gchar*)str;
247 while (*p && (*p != c))
255 static gchar *inner_find_program_in_path (const gchar *program);
258 g_find_program_in_path (const gchar *program)
260 const gchar *last_dot = strrchr (program, '.');
262 if (last_dot == NULL ||
263 strchr (last_dot, '\\') != NULL ||
264 strchr (last_dot, '/') != NULL)
266 const gint program_length = strlen (program);
267 gchar *pathext = g_build_path (";",
268 ".exe;.cmd;.bat;.com",
269 g_getenv ("PATHEXT"),
272 gchar *decorated_program;
278 gchar *q = my_strchrnul (p, ';');
280 decorated_program = g_malloc (program_length + (q-p) + 1);
281 memcpy (decorated_program, program, program_length);
282 memcpy (decorated_program+program_length, p, q-p);
283 decorated_program [program_length + (q-p)] = '\0';
285 retval = inner_find_program_in_path (decorated_program);
286 g_free (decorated_program);
294 } while (*p++ != '\0');
299 return inner_find_program_in_path (program);
305 * g_find_program_in_path:
306 * @program: a program name in the GLib file name encoding
308 * Locates the first executable named @program in the user's path, in the
309 * same way that execvp() would locate it. Returns an allocated string
310 * with the absolute path name, or %NULL if the program is not found in
311 * the path. If @program is already an absolute path, returns a copy of
312 * @program if @program exists and is executable, and %NULL otherwise.
314 * On Windows, if @program does not have a file type suffix, tries
315 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
316 * the `PATHEXT` environment variable.
318 * On Windows, it looks for the file in the same way as CreateProcess()
319 * would. This means first in the directory where the executing
320 * program was loaded from, then in the current directory, then in the
321 * Windows 32-bit system directory, then in the Windows directory, and
322 * finally in the directories in the `PATH` environment variable. If
323 * the program is found, the return value contains the full name
324 * including the type suffix.
326 * Return value: a newly-allocated string with the absolute path, or %NULL
330 inner_find_program_in_path (const gchar *program)
333 g_find_program_in_path (const gchar *program)
336 const gchar *path, *p;
337 gchar *name, *freeme;
339 const gchar *path_copy;
340 gchar *filename = NULL, *appdir = NULL;
341 gchar *sysdir = NULL, *windir = NULL;
343 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
349 g_return_val_if_fail (program != NULL, NULL);
351 /* If it is an absolute path, or a relative path including subdirectories,
352 * don't look in PATH.
354 if (g_path_is_absolute (program)
355 || strchr (program, G_DIR_SEPARATOR) != NULL
357 || strchr (program, '/') != NULL
361 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
362 !g_file_test (program, G_FILE_TEST_IS_DIR))
363 return g_strdup (program);
368 path = g_getenv ("PATH");
369 #if defined(G_OS_UNIX)
372 /* There is no 'PATH' in the environment. The default
373 * search path in GNU libc is the current directory followed by
374 * the path 'confstr' returns for '_CS_PATH'.
377 /* In GLib we put . last, for security, and don't use the
378 * unportable confstr(); UNIX98 does not actually specify
379 * what to search if PATH is unset. POSIX may, dunno.
382 path = "/bin:/usr/bin:.";
385 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
386 if (n > 0 && n < MAXPATHLEN)
387 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
389 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
390 if (n > 0 && n < MAXPATHLEN)
391 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
393 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
394 if (n > 0 && n < MAXPATHLEN)
395 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
399 appdir = g_path_get_dirname (filename);
403 path = g_strdup (path);
407 const gchar *tem = path;
408 path = g_strconcat (windir, ";", path, NULL);
409 g_free ((gchar *) tem);
415 const gchar *tem = path;
416 path = g_strconcat (sysdir, ";", path, NULL);
417 g_free ((gchar *) tem);
422 const gchar *tem = path;
423 path = g_strconcat (".;", path, NULL);
424 g_free ((gchar *) tem);
429 const gchar *tem = path;
430 path = g_strconcat (appdir, ";", path, NULL);
431 g_free ((gchar *) tem);
438 len = strlen (program) + 1;
439 pathlen = strlen (path);
440 freeme = name = g_malloc (pathlen + len + 1);
442 /* Copy the file name at the top, including '\0' */
443 memcpy (name + pathlen + 1, program, len);
444 name = name + pathlen;
445 /* And add the slash before the filename */
446 *name = G_DIR_SEPARATOR;
454 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
457 /* Two adjacent colons, or a colon at the beginning or the end
458 * of 'PATH' means to search the current directory.
462 startp = memcpy (name - (p - path), path, p - path);
464 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
465 !g_file_test (startp, G_FILE_TEST_IS_DIR))
468 ret = g_strdup (startp);
471 g_free ((gchar *) path_copy);
476 while (*p++ != '\0');
480 g_free ((gchar *) path_copy);
488 * @mask: a #gulong containing flags
489 * @nth_bit: the index of the bit to start the search from
491 * Find the position of the first bit set in @mask, searching
492 * from (but not including) @nth_bit upwards. Bits are numbered
493 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
494 * usually). To start searching from the 0th bit, set @nth_bit to -1.
496 * Returns: the index of the first bit set which is higher than @nth_bit
501 * @mask: a #gulong containing flags
502 * @nth_bit: the index of the bit to start the search from
504 * Find the position of the first bit set in @mask, searching
505 * from (but not including) @nth_bit downwards. Bits are numbered
506 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
507 * usually). To start searching from the last bit, set @nth_bit to
508 * -1 or GLIB_SIZEOF_LONG * 8.
510 * Returns: the index of the first bit set which is lower than @nth_bit
517 * Gets the number of bits used to hold @number,
518 * e.g. if @number is 4, 3 bits are needed.
520 * Returns: the number of bits used to hold @number
523 G_LOCK_DEFINE_STATIC (g_utils_global);
532 static gchar *g_user_data_dir = NULL;
533 static gchar **g_system_data_dirs = NULL;
534 static gchar *g_user_cache_dir = NULL;
535 static gchar *g_user_config_dir = NULL;
536 static gchar **g_system_config_dirs = NULL;
538 static gchar **g_user_special_dirs = NULL;
540 /* fifteen minutes of fame for everybody */
541 #define G_USER_DIRS_EXPIRE 15 * 60
546 get_special_folder (int csidl)
548 wchar_t path[MAX_PATH+1];
550 LPITEMIDLIST pidl = NULL;
552 gchar *retval = NULL;
554 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
557 b = SHGetPathFromIDListW (pidl, path);
559 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
560 CoTaskMemFree (pidl);
566 get_windows_directory_root (void)
568 wchar_t wwindowsdir[MAX_PATH];
570 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
572 /* Usually X:\Windows, but in terminal server environments
573 * might be an UNC path, AFAIK.
575 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
578 if (windowsdir == NULL)
579 return g_strdup ("C:\\");
581 p = (char *) g_path_skip_root (windowsdir);
582 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
588 return g_strdup ("C:\\");
593 /* HOLDS: g_utils_global_lock */
594 static UserDatabaseEntry *
595 g_get_user_database_entry (void)
597 static UserDatabaseEntry *entry;
599 if (g_once_init_enter (&entry))
601 static UserDatabaseEntry e;
605 struct passwd *pw = NULL;
606 gpointer buffer = NULL;
610 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
612 # ifdef _SC_GETPW_R_SIZE_MAX
613 /* This reurns the maximum length */
614 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
618 # else /* _SC_GETPW_R_SIZE_MAX */
620 # endif /* _SC_GETPW_R_SIZE_MAX */
622 logname = (gchar *) g_getenv ("LOGNAME");
627 /* we allocate 6 extra bytes to work around a bug in
628 * Mac OS < 10.3. See #156446
630 buffer = g_malloc (bufsize + 6);
633 # ifdef HAVE_POSIX_GETPWUID_R
635 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
636 if (!pw || (pw->pw_uid != getuid ())) {
637 /* LOGNAME is lying, fall back to looking up the uid */
638 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
641 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
643 error = error < 0 ? errno : error;
644 # else /* HAVE_NONPOSIX_GETPWUID_R */
646 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
647 pw = error == 0 ? &pwd : NULL;
650 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
651 if (!pw || (pw->pw_uid != getuid ())) {
652 /* LOGNAME is lying, fall back to looking up the uid */
653 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
656 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
658 error = pw ? 0 : errno;
660 # endif /* HAVE_NONPOSIX_GETPWUID_R */
664 /* we bail out prematurely if the user id can't be found
665 * (should be pretty rare case actually), or if the buffer
666 * should be sufficiently big and lookups are still not
669 if (error == 0 || error == ENOENT)
671 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
675 if (bufsize > 32 * 1024)
677 g_warning ("getpwuid_r(): failed due to: %s.",
686 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
690 pw = getpwuid (getuid ());
694 e.user_name = g_strdup (pw->pw_name);
697 if (pw->pw_gecos && *pw->pw_gecos != '\0')
699 gchar **gecos_fields;
702 /* split the gecos field and substitute '&' */
703 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
704 name_parts = g_strsplit (gecos_fields[0], "&", 0);
705 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
706 e.real_name = g_strjoinv (pw->pw_name, name_parts);
707 g_strfreev (gecos_fields);
708 g_strfreev (name_parts);
713 e.home_dir = g_strdup (pw->pw_dir);
718 #endif /* G_OS_UNIX */
723 wchar_t buffer[UNLEN+1];
725 if (GetUserNameW (buffer, (LPDWORD) &len))
727 e.user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
728 e.real_name = g_strdup (e.user_name);
731 #endif /* G_OS_WIN32 */
734 e.user_name = g_strdup ("somebody");
736 e.real_name = g_strdup ("Unknown");
738 g_once_init_leave (&entry, &e);
747 * Gets the user name of the current user. The encoding of the returned
748 * string is system-defined. On UNIX, it might be the preferred file name
749 * encoding, or something else, and there is no guarantee that it is even
750 * consistent on a machine. On Windows, it is always UTF-8.
752 * Returns: the user name of the current user.
755 g_get_user_name (void)
757 UserDatabaseEntry *entry;
759 entry = g_get_user_database_entry ();
761 return entry->user_name;
767 * Gets the real name of the user. This usually comes from the user's
768 * entry in the `passwd` file. The encoding of the returned string is
769 * system-defined. (On Windows, it is, however, always UTF-8.) If the
770 * real user name cannot be determined, the string "Unknown" is
773 * Returns: the user's real name.
776 g_get_real_name (void)
778 UserDatabaseEntry *entry;
780 entry = g_get_user_database_entry ();
782 return entry->real_name;
788 * Gets the current user's home directory.
790 * As with most UNIX tools, this function will return the value of the
791 * `HOME` environment variable if it is set to an existing absolute path
792 * name, falling back to the `passwd` file in the case that it is unset.
794 * If the path given in `HOME` is non-absolute, does not exist, or is
795 * not a directory, the result is undefined.
797 * Before version 2.36 this function would ignore the `HOME` environment
798 * variable, taking the value from the `passwd` database instead. This was
799 * changed to increase the compatibility of GLib with other programs (and
800 * the XDG basedir specification) and to increase testability of programs
801 * based on GLib (by making it easier to run them from test frameworks).
803 * If your program has a strong requirement for either the new or the
804 * old behaviour (and if you don't wish to increase your GLib
805 * dependency to ensure that the new behaviour is in effect) then you
806 * should either directly check the `HOME` environment variable yourself
807 * or unset it before calling any functions in GLib.
809 * Returns: the current user's home directory
812 g_get_home_dir (void)
814 static gchar *home_dir;
816 if (g_once_init_enter (&home_dir))
820 /* We first check HOME and use it if it is set */
821 tmp = g_strdup (g_getenv ("HOME"));
824 /* Only believe HOME if it is an absolute path and exists.
826 * We only do this check on Windows for a couple of reasons.
827 * Historically, we only did it there because we used to ignore $HOME
828 * on UNIX. There are concerns about enabling it now on UNIX because
829 * of things like autofs. In short, if the user has a bogus value in
830 * $HOME then they get what they pay for...
834 if (!(g_path_is_absolute (tmp) &&
835 g_file_test (tmp, G_FILE_TEST_IS_DIR)))
842 /* In case HOME is Unix-style (it happens), convert it to
848 while ((p = strchr (tmp, '/')) != NULL)
854 /* USERPROFILE is probably the closest equivalent to $HOME? */
855 if (g_getenv ("USERPROFILE") != NULL)
856 tmp = g_strdup (g_getenv ("USERPROFILE"));
860 tmp = get_special_folder (CSIDL_PROFILE);
863 tmp = get_windows_directory_root ();
864 #endif /* G_OS_WIN32 */
868 /* If we didn't get it from any of those methods, we will have
869 * to read the user database entry.
871 UserDatabaseEntry *entry;
873 entry = g_get_user_database_entry ();
875 /* Strictly speaking, we should copy this, but we know that
876 * neither will ever be freed, so don't bother...
878 tmp = entry->home_dir;
881 g_once_init_leave (&home_dir, tmp);
890 * Gets the directory to use for temporary files.
892 * On UNIX, this is taken from the `TMPDIR` environment variable.
893 * If the variable is not set, <literal>P_tmpdir</literal> is
894 * used, as defined by the system C library. Failing that, a
895 * hard-coded default of "/tmp" is returned.
897 * On Windows, the `TEMP` environment variable is used, with the
898 * root directory of the Windows installation (eg: "C:\") used
901 * The encoding of the returned string is system-defined. On Windows,
902 * it is always UTF-8. The return value is never %NULL or the empty
905 * Returns: the directory to use for temporary files.
910 static gchar *tmp_dir;
912 if (g_once_init_enter (&tmp_dir))
917 tmp = g_strdup (g_getenv ("TEMP"));
919 if (tmp == NULL || *tmp == '\0')
922 tmp = get_windows_directory_root ();
924 #else /* G_OS_WIN32 */
925 tmp = g_strdup (g_getenv ("TMPDIR"));
928 if (tmp == NULL || *tmp == '\0')
932 tmp = g_strdup (P_tmpdir);
934 if (k > 1 && G_IS_DIR_SEPARATOR (tmp[k - 1]))
937 #endif /* P_tmpdir */
939 if (tmp == NULL || *tmp == '\0')
942 tmp = g_strdup ("/tmp");
944 #endif /* !G_OS_WIN32 */
946 g_once_init_leave (&tmp_dir, tmp);
955 * Return a name for the machine.
957 * The returned name is not necessarily a fully-qualified domain name,
958 * or even present in DNS or some other name service at all. It need
959 * not even be unique on your local network or site, but usually it
960 * is. Callers should not rely on the return value having any specific
961 * properties like uniqueness for security purposes. Even if the name
962 * of the machine is changed while an application is running, the
963 * return value from this function does not change. The returned
964 * string is owned by GLib and should not be modified or freed. If no
965 * name can be determined, a default fixed string "localhost" is
968 * Returns: the host name of the machine.
973 g_get_host_name (void)
975 static gchar *hostname;
977 if (g_once_init_enter (&hostname))
983 failed = (gethostname (tmp, sizeof (tmp)) == -1);
985 DWORD size = sizeof (tmp);
986 failed = (!GetComputerName (tmp, &size));
989 g_once_init_leave (&hostname, g_strdup (failed ? "localhost" : tmp));
995 G_LOCK_DEFINE_STATIC (g_prgname);
996 static gchar *g_prgname = NULL;
1001 * Gets the name of the program. This name should not be localized,
1002 * in contrast to g_get_application_name().
1004 * If you are using GDK or GTK+ the program name is set in gdk_init(),
1005 * which is called by gtk_init(). The program name is found by taking
1006 * the last component of @argv[0].
1008 * Returns: the name of the program. The returned string belongs
1009 * to GLib and must not be modified or freed.
1012 g_get_prgname (void)
1018 if (g_prgname == NULL)
1020 static gboolean beenhere = FALSE;
1024 gchar *utf8_buf = NULL;
1025 wchar_t buf[MAX_PATH+1];
1028 if (GetModuleFileNameW (GetModuleHandle (NULL),
1029 buf, G_N_ELEMENTS (buf)) > 0)
1030 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1034 g_prgname = g_path_get_basename (utf8_buf);
1041 G_UNLOCK (g_prgname);
1048 * @prgname: the name of the program.
1050 * Sets the name of the program. This name should not be localized,
1051 * in contrast to g_set_application_name().
1053 * Note that for thread-safety reasons this function can only be called once.
1056 g_set_prgname (const gchar *prgname)
1060 g_prgname = g_strdup (prgname);
1061 G_UNLOCK (g_prgname);
1064 G_LOCK_DEFINE_STATIC (g_application_name);
1065 static gchar *g_application_name = NULL;
1068 * g_get_application_name:
1070 * Gets a human-readable name for the application, as set by
1071 * g_set_application_name(). This name should be localized if
1072 * possible, and is intended for display to the user. Contrast with
1073 * g_get_prgname(), which gets a non-localized name. If
1074 * g_set_application_name() has not been called, returns the result of
1075 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1078 * Return value: human-readable application name. may return %NULL
1083 g_get_application_name (void)
1087 G_LOCK (g_application_name);
1088 retval = g_application_name;
1089 G_UNLOCK (g_application_name);
1092 return g_get_prgname ();
1098 * g_set_application_name:
1099 * @application_name: localized name of the application
1101 * Sets a human-readable name for the application. This name should be
1102 * localized if possible, and is intended for display to the user.
1103 * Contrast with g_set_prgname(), which sets a non-localized name.
1104 * g_set_prgname() will be called automatically by gtk_init(),
1105 * but g_set_application_name() will not.
1107 * Note that for thread safety reasons, this function can only
1110 * The application name will be used in contexts such as error messages,
1111 * or when displaying an application's name in the task list.
1116 g_set_application_name (const gchar *application_name)
1118 gboolean already_set = FALSE;
1120 G_LOCK (g_application_name);
1121 if (g_application_name)
1124 g_application_name = g_strdup (application_name);
1125 G_UNLOCK (g_application_name);
1128 g_warning ("g_set_application_name() called multiple times");
1132 * g_get_user_data_dir:
1134 * Returns a base directory in which to access application data such
1135 * as icons that is customized for a particular user.
1137 * On UNIX platforms this is determined using the mechanisms described in
1138 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1139 * XDG Base Directory Specification</ulink>.
1140 * In this case the directory retrieved will be XDG_DATA_HOME.
1142 * On Windows this is the folder to use for local (as opposed to
1143 * roaming) application data. See documentation for
1144 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1145 * what g_get_user_config_dir() returns.
1147 * Return value: a string owned by GLib that must not be modified
1152 g_get_user_data_dir (void)
1156 G_LOCK (g_utils_global);
1158 if (!g_user_data_dir)
1161 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1163 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1165 if (data_dir && data_dir[0])
1166 data_dir = g_strdup (data_dir);
1168 if (!data_dir || !data_dir[0])
1170 const gchar *home_dir = g_get_home_dir ();
1173 data_dir = g_build_filename (home_dir, ".local", "share", NULL);
1175 data_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".local", "share", NULL);
1178 g_user_data_dir = data_dir;
1181 data_dir = g_user_data_dir;
1183 G_UNLOCK (g_utils_global);
1189 g_init_user_config_dir (void)
1193 if (!g_user_config_dir)
1196 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1198 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1200 if (config_dir && config_dir[0])
1201 config_dir = g_strdup (config_dir);
1203 if (!config_dir || !config_dir[0])
1205 const gchar *home_dir = g_get_home_dir ();
1208 config_dir = g_build_filename (home_dir, ".config", NULL);
1210 config_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".config", NULL);
1213 g_user_config_dir = config_dir;
1218 * g_get_user_config_dir:
1220 * Returns a base directory in which to store user-specific application
1221 * configuration information such as user preferences and settings.
1223 * On UNIX platforms this is determined using the mechanisms described in
1224 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1225 * XDG Base Directory Specification</ulink>.
1226 * In this case the directory retrieved will be XDG_CONFIG_HOME.
1228 * On Windows this is the folder to use for local (as opposed to
1229 * roaming) application data. See documentation for
1230 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1231 * what g_get_user_data_dir() returns.
1233 * Return value: a string owned by GLib that must not be modified
1238 g_get_user_config_dir (void)
1240 G_LOCK (g_utils_global);
1242 g_init_user_config_dir ();
1244 G_UNLOCK (g_utils_global);
1246 return g_user_config_dir;
1250 * g_get_user_cache_dir:
1252 * Returns a base directory in which to store non-essential, cached
1253 * data specific to particular user.
1255 * On UNIX platforms this is determined using the mechanisms described in
1256 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1257 * XDG Base Directory Specification</ulink>.
1258 * In this case the directory retrieved will be XDG_CACHE_HOME.
1260 * On Windows is the directory that serves as a common repository for
1261 * temporary Internet files. A typical path is
1262 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
1263 * See documentation for CSIDL_INTERNET_CACHE.
1265 * Return value: a string owned by GLib that must not be modified
1270 g_get_user_cache_dir (void)
1274 G_LOCK (g_utils_global);
1276 if (!g_user_cache_dir)
1279 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1281 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1283 if (cache_dir && cache_dir[0])
1284 cache_dir = g_strdup (cache_dir);
1286 if (!cache_dir || !cache_dir[0])
1288 const gchar *home_dir = g_get_home_dir ();
1291 cache_dir = g_build_filename (home_dir, ".cache", NULL);
1293 cache_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".cache", NULL);
1295 g_user_cache_dir = cache_dir;
1298 cache_dir = g_user_cache_dir;
1300 G_UNLOCK (g_utils_global);
1306 * g_get_user_runtime_dir:
1308 * Returns a directory that is unique to the current user on the local
1311 * On UNIX platforms this is determined using the mechanisms described in
1312 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1313 * XDG Base Directory Specification</ulink>. This is the directory
1314 * specified in the `XDG_RUNTIME_DIR` environment variable.
1315 * In the case that this variable is not set, GLib will issue a warning
1316 * message to stderr and return the value of g_get_user_cache_dir().
1318 * On Windows this is the folder to use for local (as opposed to
1319 * roaming) application data. See documentation for
1320 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1321 * what g_get_user_config_dir() returns.
1323 * Returns: a string owned by GLib that must not be modified or freed.
1328 g_get_user_runtime_dir (void)
1331 static const gchar *runtime_dir;
1332 static gsize initialised;
1334 if (g_once_init_enter (&initialised))
1336 runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
1338 g_once_init_leave (&initialised, 1);
1344 /* Both fallback for UNIX and the default
1345 * in Windows: use the user cache directory.
1349 return g_get_user_cache_dir ();
1355 find_folder (OSType type)
1357 gchar *filename = NULL;
1360 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
1362 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
1366 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
1370 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
1374 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
1376 CFStringGetCString (path, filename,
1377 CFStringGetLength (path) * 3 + 1,
1378 kCFStringEncodingUTF8);
1392 load_user_special_dirs (void)
1394 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
1395 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
1396 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
1397 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
1398 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
1399 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
1400 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
1401 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
1404 #endif /* HAVE_CARBON */
1406 #if defined(G_OS_WIN32)
1408 load_user_special_dirs (void)
1410 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1414 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
1416 static const GUID FOLDERID_Downloads =
1417 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1418 static const GUID FOLDERID_Public =
1419 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1423 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
1424 "SHGetKnownFolderPath");
1426 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1427 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
1429 if (p_SHGetKnownFolderPath == NULL)
1431 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1436 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1439 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1440 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
1441 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1442 CoTaskMemFree (wcp);
1445 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1448 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
1449 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
1451 if (p_SHGetKnownFolderPath == NULL)
1454 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1459 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
1462 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1463 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
1464 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1465 CoTaskMemFree (wcp);
1468 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1471 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
1472 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
1474 #endif /* G_OS_WIN32 */
1477 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
1479 /* adapted from xdg-user-dir-lookup.c
1481 * Copyright (C) 2007 Red Hat Inc.
1483 * Permission is hereby granted, free of charge, to any person
1484 * obtaining a copy of this software and associated documentation files
1485 * (the "Software"), to deal in the Software without restriction,
1486 * including without limitation the rights to use, copy, modify, merge,
1487 * publish, distribute, sublicense, and/or sell copies of the Software,
1488 * and to permit persons to whom the Software is furnished to do so,
1489 * subject to the following conditions:
1491 * The above copyright notice and this permission notice shall be
1492 * included in all copies or substantial portions of the Software.
1494 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1495 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1496 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1497 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1498 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1499 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1500 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1504 load_user_special_dirs (void)
1511 g_init_user_config_dir ();
1512 config_file = g_build_filename (g_user_config_dir,
1516 if (!g_file_get_contents (config_file, &data, NULL, NULL))
1518 g_free (config_file);
1522 lines = g_strsplit (data, "\n", -1);
1523 n_lines = g_strv_length (lines);
1526 for (i = 0; i < n_lines; i++)
1528 gchar *buffer = lines[i];
1531 gboolean is_relative = FALSE;
1532 GUserDirectory directory;
1534 /* Remove newline at end */
1535 len = strlen (buffer);
1536 if (len > 0 && buffer[len - 1] == '\n')
1537 buffer[len - 1] = 0;
1540 while (*p == ' ' || *p == '\t')
1543 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
1545 directory = G_USER_DIRECTORY_DESKTOP;
1546 p += strlen ("XDG_DESKTOP_DIR");
1548 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
1550 directory = G_USER_DIRECTORY_DOCUMENTS;
1551 p += strlen ("XDG_DOCUMENTS_DIR");
1553 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
1555 directory = G_USER_DIRECTORY_DOWNLOAD;
1556 p += strlen ("XDG_DOWNLOAD_DIR");
1558 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
1560 directory = G_USER_DIRECTORY_MUSIC;
1561 p += strlen ("XDG_MUSIC_DIR");
1563 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
1565 directory = G_USER_DIRECTORY_PICTURES;
1566 p += strlen ("XDG_PICTURES_DIR");
1568 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
1570 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
1571 p += strlen ("XDG_PUBLICSHARE_DIR");
1573 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
1575 directory = G_USER_DIRECTORY_TEMPLATES;
1576 p += strlen ("XDG_TEMPLATES_DIR");
1578 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
1580 directory = G_USER_DIRECTORY_VIDEOS;
1581 p += strlen ("XDG_VIDEOS_DIR");
1586 while (*p == ' ' || *p == '\t')
1593 while (*p == ' ' || *p == '\t')
1600 if (strncmp (p, "$HOME", 5) == 0)
1608 d = strrchr (p, '"');
1615 /* remove trailing slashes */
1617 if (d[len - 1] == '/')
1622 g_user_special_dirs[directory] = g_build_filename (g_get_home_dir (), d, NULL);
1625 g_user_special_dirs[directory] = g_strdup (d);
1629 g_free (config_file);
1632 #endif /* G_OS_UNIX && !HAVE_CARBON */
1636 * g_reload_user_special_dirs_cache:
1638 * Resets the cache used for g_get_user_special_dir(), so
1639 * that the latest on-disk version is used. Call this only
1640 * if you just changed the data on disk yourself.
1642 * Due to threadsafety issues this may cause leaking of strings
1643 * that were previously returned from g_get_user_special_dir()
1644 * that can't be freed. We ensure to only leak the data for
1645 * the directories that actually changed value though.
1650 g_reload_user_special_dirs_cache (void)
1654 G_LOCK (g_utils_global);
1656 if (g_user_special_dirs != NULL)
1658 /* save a copy of the pointer, to check if some memory can be preserved */
1659 char **old_g_user_special_dirs = g_user_special_dirs;
1662 /* recreate and reload our cache */
1663 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1664 load_user_special_dirs ();
1666 /* only leak changed directories */
1667 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
1669 old_val = old_g_user_special_dirs[i];
1670 if (g_user_special_dirs[i] == NULL)
1672 g_user_special_dirs[i] = old_val;
1674 else if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
1677 g_free (g_user_special_dirs[i]);
1678 g_user_special_dirs[i] = old_val;
1684 /* free the old array */
1685 g_free (old_g_user_special_dirs);
1688 G_UNLOCK (g_utils_global);
1692 * g_get_user_special_dir:
1693 * @directory: the logical id of special directory
1695 * Returns the full path of a special directory using its logical id.
1697 * On UNIX this is done using the XDG special user directories.
1698 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
1699 * falls back to `$HOME/Desktop` when XDG special user directories have
1702 * Depending on the platform, the user might be able to change the path
1703 * of the special directory without requiring the session to restart; GLib
1704 * will not reflect any change once the special directories are loaded.
1706 * Return value: the path to the specified special directory, or %NULL
1707 * if the logical id was not found. The returned string is owned by
1708 * GLib and should not be modified or freed.
1713 g_get_user_special_dir (GUserDirectory directory)
1715 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
1716 directory < G_USER_N_DIRECTORIES, NULL);
1718 G_LOCK (g_utils_global);
1720 if (G_UNLIKELY (g_user_special_dirs == NULL))
1722 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1724 load_user_special_dirs ();
1726 /* Special-case desktop for historical compatibility */
1727 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
1728 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = g_build_filename (g_get_home_dir (), "Desktop", NULL);
1731 G_UNLOCK (g_utils_global);
1733 return g_user_special_dirs[directory];
1738 #undef g_get_system_data_dirs
1741 get_module_for_address (gconstpointer address)
1743 /* Holds the g_utils_global lock */
1745 static gboolean beenhere = FALSE;
1746 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
1747 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
1748 HMODULE hmodule = NULL;
1755 p_GetModuleHandleExA =
1756 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1757 "GetModuleHandleExA");
1761 if (p_GetModuleHandleExA == NULL ||
1762 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
1763 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
1766 MEMORY_BASIC_INFORMATION mbi;
1767 VirtualQuery (address, &mbi, sizeof (mbi));
1768 hmodule = (HMODULE) mbi.AllocationBase;
1775 get_module_share_dir (gconstpointer address)
1781 hmodule = get_module_for_address (address);
1782 if (hmodule == NULL)
1785 filename = g_win32_get_package_installation_directory_of_module (hmodule);
1786 retval = g_build_filename (filename, "share", NULL);
1792 const gchar * const *
1793 g_win32_get_system_data_dirs_for_module (void (*address_of_function)(void))
1797 static GHashTable *per_module_data_dirs = NULL;
1802 if (address_of_function)
1804 G_LOCK (g_utils_global);
1805 hmodule = get_module_for_address (address_of_function);
1806 if (hmodule != NULL)
1808 if (per_module_data_dirs == NULL)
1809 per_module_data_dirs = g_hash_table_new (NULL, NULL);
1812 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
1816 G_UNLOCK (g_utils_global);
1817 return (const gchar * const *) retval;
1823 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
1825 /* Documents and Settings\All Users\Application Data */
1826 p = get_special_folder (CSIDL_COMMON_APPDATA);
1828 g_array_append_val (data_dirs, p);
1830 /* Documents and Settings\All Users\Documents */
1831 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1833 g_array_append_val (data_dirs, p);
1835 /* Using the above subfolders of Documents and Settings perhaps
1836 * makes sense from a Windows perspective.
1838 * But looking at the actual use cases of this function in GTK+
1839 * and GNOME software, what we really want is the "share"
1840 * subdirectory of the installation directory for the package
1841 * our caller is a part of.
1843 * The address_of_function parameter, if non-NULL, points to a
1844 * function in the calling module. Use that to determine that
1845 * module's installation folder, and use its "share" subfolder.
1847 * Additionally, also use the "share" subfolder of the installation
1848 * locations of GLib and the .exe file being run.
1850 * To guard against none of the above being what is really wanted,
1851 * callers of this function should have Win32-specific code to look
1852 * up their installation folder themselves, and handle a subfolder
1853 * "share" of it in the same way as the folders returned from this
1857 p = get_module_share_dir (address_of_function);
1859 g_array_append_val (data_dirs, p);
1861 if (glib_dll != NULL)
1863 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
1864 p = g_build_filename (glib_root, "share", NULL);
1866 g_array_append_val (data_dirs, p);
1870 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
1871 p = g_build_filename (exe_root, "share", NULL);
1873 g_array_append_val (data_dirs, p);
1876 retval = (gchar **) g_array_free (data_dirs, FALSE);
1878 if (address_of_function)
1880 if (hmodule != NULL)
1881 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
1882 G_UNLOCK (g_utils_global);
1885 return (const gchar * const *) retval;
1891 * g_get_system_data_dirs:
1893 * Returns an ordered list of base directories in which to access
1894 * system-wide application data.
1896 * On UNIX platforms this is determined using the mechanisms described in
1897 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1898 * XDG Base Directory Specification</ulink>
1899 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
1901 * On Windows the first elements in the list are the Application Data
1902 * and Documents folders for All Users. (These can be determined only
1903 * on Windows 2000 or later and are not present in the list on other
1904 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
1905 * CSIDL_COMMON_DOCUMENTS.
1907 * Then follows the "share" subfolder in the installation folder for
1908 * the package containing the DLL that calls this function, if it can
1911 * Finally the list contains the "share" subfolder in the installation
1912 * folder for GLib, and in the installation folder for the package the
1913 * application's .exe file belongs to.
1915 * The installation folders above are determined by looking up the
1916 * folder where the module (DLL or EXE) in question is located. If the
1917 * folder's name is "bin", its parent is used, otherwise the folder
1920 * Note that on Windows the returned list can vary depending on where
1921 * this function is called.
1923 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
1924 * not be modified or freed.
1927 const gchar * const *
1928 g_get_system_data_dirs (void)
1930 gchar **data_dir_vector;
1932 G_LOCK (g_utils_global);
1934 if (!g_system_data_dirs)
1937 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
1939 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
1941 if (!data_dirs || !data_dirs[0])
1942 data_dirs = "/usr/local/share/:/usr/share/";
1944 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1947 g_system_data_dirs = data_dir_vector;
1950 data_dir_vector = g_system_data_dirs;
1952 G_UNLOCK (g_utils_global);
1954 return (const gchar * const *) data_dir_vector;
1958 * g_get_system_config_dirs:
1960 * Returns an ordered list of base directories in which to access
1961 * system-wide configuration information.
1963 * On UNIX platforms this is determined using the mechanisms described in
1964 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1965 * XDG Base Directory Specification</ulink>.
1966 * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
1968 * On Windows is the directory that contains application data for all users.
1969 * A typical path is C:\Documents and Settings\All Users\Application Data.
1970 * This folder is used for application data that is not user specific.
1971 * For example, an application can store a spell-check dictionary, a database
1972 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
1973 * This information will not roam and is available to anyone using the computer.
1975 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
1976 * not be modified or freed.
1979 const gchar * const *
1980 g_get_system_config_dirs (void)
1982 gchar *conf_dirs, **conf_dir_vector;
1984 G_LOCK (g_utils_global);
1986 if (!g_system_config_dirs)
1989 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
1992 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1997 /* Return empty list */
1998 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2001 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2003 if (!conf_dirs || !conf_dirs[0])
2004 conf_dirs = "/etc/xdg";
2006 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2009 g_system_config_dirs = conf_dir_vector;
2012 conf_dir_vector = g_system_config_dirs;
2013 G_UNLOCK (g_utils_global);
2015 return (const gchar * const *) conf_dir_vector;
2019 * g_nullify_pointer:
2020 * @nullify_location: the memory address of the pointer.
2022 * Set the pointer at the specified location to %NULL.
2025 g_nullify_pointer (gpointer *nullify_location)
2027 g_return_if_fail (nullify_location != NULL);
2029 *nullify_location = NULL;
2032 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2033 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2034 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2035 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2036 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2037 #define EXABYTE_FACTOR (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2039 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2040 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2041 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2042 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2043 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2044 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2048 * @size: a size in bytes
2050 * Formats a size (for example the size of a file) into a human readable
2051 * string. Sizes are rounded to the nearest size prefix (kB, MB, GB)
2052 * and are displayed rounded to the nearest tenth. E.g. the file size
2053 * 3292528 bytes will be converted into the string "3.2 MB".
2055 * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2057 * This string should be freed with g_free() when not needed any longer.
2059 * See g_format_size_full() for more options about how the size might be
2062 * Returns: a newly-allocated formatted string containing a human readable
2068 g_format_size (guint64 size)
2070 return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2075 * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2076 * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2077 * of the returned string. For example, "45.6 kB (45,612 bytes)".
2078 * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2079 * suffixes. IEC units should only be used for reporting things with
2080 * a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2081 * Network and storage sizes should be reported in the normal SI units.
2083 * Flags to modify the format of the string returned by g_format_size_full().
2086 #pragma GCC diagnostic push
2087 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
2090 * g_format_size_full:
2091 * @size: a size in bytes
2092 * @flags: #GFormatSizeFlags to modify the output
2096 * This function is similar to g_format_size() but allows for flags
2097 * that modify the output. See #GFormatSizeFlags.
2099 * Returns: a newly-allocated formatted string containing a human
2100 * readable file size
2105 g_format_size_full (guint64 size,
2106 GFormatSizeFlags flags)
2110 string = g_string_new (NULL);
2112 if (flags & G_FORMAT_SIZE_IEC_UNITS)
2114 if (size < KIBIBYTE_FACTOR)
2116 g_string_printf (string,
2117 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2119 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2122 else if (size < MEBIBYTE_FACTOR)
2123 g_string_printf (string, _("%.1f KiB"), (gdouble) size / (gdouble) KIBIBYTE_FACTOR);
2124 else if (size < GIBIBYTE_FACTOR)
2125 g_string_printf (string, _("%.1f MiB"), (gdouble) size / (gdouble) MEBIBYTE_FACTOR);
2127 else if (size < TEBIBYTE_FACTOR)
2128 g_string_printf (string, _("%.1f GiB"), (gdouble) size / (gdouble) GIBIBYTE_FACTOR);
2130 else if (size < PEBIBYTE_FACTOR)
2131 g_string_printf (string, _("%.1f TiB"), (gdouble) size / (gdouble) TEBIBYTE_FACTOR);
2133 else if (size < EXBIBYTE_FACTOR)
2134 g_string_printf (string, _("%.1f PiB"), (gdouble) size / (gdouble) PEBIBYTE_FACTOR);
2137 g_string_printf (string, _("%.1f EiB"), (gdouble) size / (gdouble) EXBIBYTE_FACTOR);
2141 if (size < KILOBYTE_FACTOR)
2143 g_string_printf (string,
2144 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2146 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2149 else if (size < MEGABYTE_FACTOR)
2150 g_string_printf (string, _("%.1f kB"), (gdouble) size / (gdouble) KILOBYTE_FACTOR);
2152 else if (size < GIGABYTE_FACTOR)
2153 g_string_printf (string, _("%.1f MB"), (gdouble) size / (gdouble) MEGABYTE_FACTOR);
2155 else if (size < TERABYTE_FACTOR)
2156 g_string_printf (string, _("%.1f GB"), (gdouble) size / (gdouble) GIGABYTE_FACTOR);
2157 else if (size < PETABYTE_FACTOR)
2158 g_string_printf (string, _("%.1f TB"), (gdouble) size / (gdouble) TERABYTE_FACTOR);
2160 else if (size < EXABYTE_FACTOR)
2161 g_string_printf (string, _("%.1f PB"), (gdouble) size / (gdouble) PETABYTE_FACTOR);
2164 g_string_printf (string, _("%.1f EB"), (gdouble) size / (gdouble) EXABYTE_FACTOR);
2167 if (flags & G_FORMAT_SIZE_LONG_FORMAT)
2169 /* First problem: we need to use the number of bytes to decide on
2170 * the plural form that is used for display, but the number of
2171 * bytes potentially exceeds the size of a guint (which is what
2172 * ngettext() takes).
2174 * From a pragmatic standpoint, it seems that all known languages
2175 * base plural forms on one or both of the following:
2177 * - the lowest digits of the number
2179 * - if the number if greater than some small value
2181 * Here's how we fake it: Draw an arbitrary line at one thousand.
2182 * If the number is below that, then fine. If it is above it,
2183 * then we take the modulus of the number by one thousand (in
2184 * order to keep the lowest digits) and add one thousand to that
2185 * (in order to ensure that 1001 is not treated the same as 1).
2187 guint plural_form = size < 1000 ? size : size % 1000 + 1000;
2189 /* Second problem: we need to translate the string "%u byte" and
2190 * "%u bytes" for pluralisation, but the correct number format to
2191 * use for a gsize is different depending on which architecture
2194 * Solution: format the number separately and use "%s bytes" on
2197 const gchar *translated_format;
2198 gchar *formatted_number;
2200 /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2201 translated_format = g_dngettext(GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
2202 /* XXX: Windows doesn't support the "'" format modifier, so we
2203 * must not use it there. Instead, just display the number
2204 * without separation. Bug #655336 is open until a solution is
2208 formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2210 formatted_number = g_strdup_printf ("%"G_GUINT64_FORMAT, size);
2213 g_string_append (string, " (");
2214 g_string_append_printf (string, translated_format, formatted_number);
2215 g_free (formatted_number);
2216 g_string_append (string, ")");
2219 return g_string_free (string, FALSE);
2222 #pragma GCC diagnostic pop
2225 * g_format_size_for_display:
2226 * @size: a size in bytes
2228 * Formats a size (for example the size of a file) into a human
2229 * readable string. Sizes are rounded to the nearest size prefix
2230 * (KB, MB, GB) and are displayed rounded to the nearest tenth.
2231 * E.g. the file size 3292528 bytes will be converted into the
2234 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2236 * This string should be freed with g_free() when not needed any longer.
2238 * Returns: a newly-allocated formatted string containing a human
2239 * readable file size
2243 * Deprecated:2.30: This function is broken due to its use of SI
2244 * suffixes to denote IEC units. Use g_format_size() instead.
2247 g_format_size_for_display (goffset size)
2249 if (size < (goffset) KIBIBYTE_FACTOR)
2250 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
2253 gdouble displayed_size;
2255 if (size < (goffset) MEBIBYTE_FACTOR)
2257 displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
2258 /* Translators: this is from the deprecated function g_format_size_for_display() which uses 'KB' to
2259 * mean 1024 bytes. I am aware that 'KB' is not correct, but it has been preserved for reasons of
2260 * compatibility. Users will not see this string unless a program is using this deprecated function.
2261 * Please translate as literally as possible.
2263 return g_strdup_printf (_("%.1f KB"), displayed_size);
2265 else if (size < (goffset) GIBIBYTE_FACTOR)
2267 displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
2268 return g_strdup_printf (_("%.1f MB"), displayed_size);
2270 else if (size < (goffset) TEBIBYTE_FACTOR)
2272 displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
2273 return g_strdup_printf (_("%.1f GB"), displayed_size);
2275 else if (size < (goffset) PEBIBYTE_FACTOR)
2277 displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
2278 return g_strdup_printf (_("%.1f TB"), displayed_size);
2280 else if (size < (goffset) EXBIBYTE_FACTOR)
2282 displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
2283 return g_strdup_printf (_("%.1f PB"), displayed_size);
2287 displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
2288 return g_strdup_printf (_("%.1f EB"), displayed_size);
2293 #if defined (G_OS_WIN32) && !defined (_WIN64)
2295 /* Binary compatibility versions. Not for newly compiled code. */
2297 _GLIB_EXTERN const gchar *g_get_user_name_utf8 (void);
2298 _GLIB_EXTERN const gchar *g_get_real_name_utf8 (void);
2299 _GLIB_EXTERN const gchar *g_get_home_dir_utf8 (void);
2300 _GLIB_EXTERN const gchar *g_get_tmp_dir_utf8 (void);
2301 _GLIB_EXTERN gchar *g_find_program_in_path_utf8 (const gchar *program);
2304 g_find_program_in_path_utf8 (const gchar *program)
2306 return g_find_program_in_path (program);
2309 const gchar *g_get_user_name_utf8 (void) { return g_get_user_name (); }
2310 const gchar *g_get_real_name_utf8 (void) { return g_get_real_name (); }
2311 const gchar *g_get_home_dir_utf8 (void) { return g_get_home_dir (); }
2312 const gchar *g_get_tmp_dir_utf8 (void) { return g_get_tmp_dir (); }
2318 * Returns %TRUE if the current process was executed as setuid (or an
2319 * equivalent __libc_enable_secure is available). See:
2320 * http://osdir.com/ml/linux.lfs.hardened/2007-04/msg00032.html
2323 g_check_setuid (void)
2325 /* TODO: get __libc_enable_secure exported from glibc.
2326 * See http://www.openwall.com/lists/owl-dev/2012/08/14/1
2328 #if 0 && defined(HAVE_LIBC_ENABLE_SECURE)
2330 /* See glibc/include/unistd.h */
2331 extern int __libc_enable_secure;
2332 return __libc_enable_secure;
2334 #elif defined(HAVE_ISSETUGID)
2335 /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
2336 return issetugid ();
2337 #elif defined(G_OS_UNIX)
2338 uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
2339 gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
2341 static gsize check_setuid_initialised;
2342 static gboolean is_setuid;
2344 if (g_once_init_enter (&check_setuid_initialised))
2346 #ifdef HAVE_GETRESUID
2347 /* These aren't in the header files, so we prototype them here.
2349 int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
2350 int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);
2352 if (getresuid (&ruid, &euid, &suid) != 0 ||
2353 getresgid (&rgid, &egid, &sgid) != 0)
2354 #endif /* HAVE_GETRESUID */
2356 suid = ruid = getuid ();
2357 sgid = rgid = getgid ();
2362 is_setuid = (ruid != euid || ruid != suid ||
2363 rgid != egid || rgid != sgid);
2365 g_once_init_leave (&check_setuid_initialised, 1);