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.
38 #include <ctype.h> /* For tolower() */
40 #include <sys/types.h>
46 #include <sys/types.h>
47 #ifdef HAVE_SYS_PARAM_H
48 #include <sys/param.h>
50 #ifdef HAVE_CRT_EXTERNS_H
51 #include <crt_externs.h> /* for _NSGetEnviron */
54 #include "glib-init.h"
55 #include "glib-private.h"
57 #include "gfileutils.h"
61 #include "gtestutils.h"
63 #include "gstrfuncs.h"
67 #ifdef G_PLATFORM_WIN32
75 * @title: Miscellaneous Utility Functions
76 * @short_description: a selection of portable utility functions
78 * These are portable utility functions.
81 #ifdef G_PLATFORM_WIN32
83 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
84 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
85 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
87 # include <lmcons.h> /* For UNLEN */
88 #endif /* G_PLATFORM_WIN32 */
93 /* older SDK (e.g. msvc 5.0) does not have these*/
94 # ifndef CSIDL_MYMUSIC
95 # define CSIDL_MYMUSIC 13
97 # ifndef CSIDL_MYVIDEO
98 # define CSIDL_MYVIDEO 14
100 # ifndef CSIDL_INTERNET_CACHE
101 # define CSIDL_INTERNET_CACHE 32
103 # ifndef CSIDL_COMMON_APPDATA
104 # define CSIDL_COMMON_APPDATA 35
106 # ifndef CSIDL_MYPICTURES
107 # define CSIDL_MYPICTURES 0x27
109 # ifndef CSIDL_COMMON_DOCUMENTS
110 # define CSIDL_COMMON_DOCUMENTS 46
112 # ifndef CSIDL_PROFILE
113 # define CSIDL_PROFILE 40
115 # include <process.h>
119 #include <CoreServices/CoreServices.h>
123 #include <langinfo.h>
126 #ifdef G_PLATFORM_WIN32
129 _glib_get_dll_directory (void)
133 wchar_t wc_fn[MAX_PATH];
136 if (glib_dll == NULL)
140 /* This code is different from that in
141 * g_win32_get_package_installation_directory_of_module() in that
142 * here we return the actual folder where the GLib DLL is. We don't
143 * do the check for it being in a "bin" or "lib" subfolder and then
144 * returning the parent of that.
146 * In a statically built GLib, glib_dll will be NULL and we will
147 * thus look up the application's .exe file's location.
149 if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
152 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
154 p = strrchr (retval, G_DIR_SEPARATOR);
169 * @dest: the destination address to copy the bytes to.
170 * @src: the source address to copy the bytes from.
171 * @len: the number of bytes to copy.
173 * Copies a block of memory @len bytes long, from @src to @dest.
174 * The source and destination areas may overlap.
176 * Deprecated:2.40: Just use memmove().
185 * @func: (scope async): the function to call on normal program termination.
187 * Specifies a function to be called at normal program termination.
189 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
190 * macro that maps to a call to the atexit() function in the C
191 * library. This means that in case the code that calls g_atexit(),
192 * i.e. atexit(), is in a DLL, the function will be called when the
193 * DLL is detached from the program. This typically makes more sense
194 * than that the function is called when the GLib DLL is detached,
195 * which happened earlier when g_atexit() was a function in the GLib
198 * The behaviour of atexit() in the context of dynamically loaded
199 * modules is not formally specified and varies wildly.
201 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
202 * loaded module which is unloaded before the program terminates might
203 * well cause a crash at program exit.
205 * Some POSIX systems implement atexit() like Windows, and have each
206 * dynamically loaded module maintain an own atexit chain that is
207 * called when the module is unloaded.
209 * On other POSIX systems, before a dynamically loaded module is
210 * unloaded, the registered atexit functions (if any) residing in that
211 * module are called, regardless where the code that registered them
212 * resided. This is presumably the most robust approach.
214 * As can be seen from the above, for portability it's best to avoid
215 * calling g_atexit() (or atexit()) except in the main executable of a
218 * Deprecated:2.32: It is best to avoid g_atexit().
221 g_atexit (GVoidFunc func)
226 result = atexit ((void (*)(void)) func);
230 g_error ("Could not register atexit() function: %s",
235 /* Based on execvp() from GNU Libc.
236 * Some of this code is cut-and-pasted into gspawn.c
240 my_strchrnul (const gchar *str,
243 gchar *p = (gchar*)str;
244 while (*p && (*p != c))
252 static gchar *inner_find_program_in_path (const gchar *program);
255 g_find_program_in_path (const gchar *program)
257 const gchar *last_dot = strrchr (program, '.');
259 if (last_dot == NULL ||
260 strchr (last_dot, '\\') != NULL ||
261 strchr (last_dot, '/') != NULL)
263 const gint program_length = strlen (program);
264 gchar *pathext = g_build_path (";",
265 ".exe;.cmd;.bat;.com",
266 g_getenv ("PATHEXT"),
269 gchar *decorated_program;
275 gchar *q = my_strchrnul (p, ';');
277 decorated_program = g_malloc (program_length + (q-p) + 1);
278 memcpy (decorated_program, program, program_length);
279 memcpy (decorated_program+program_length, p, q-p);
280 decorated_program [program_length + (q-p)] = '\0';
282 retval = inner_find_program_in_path (decorated_program);
283 g_free (decorated_program);
291 } while (*p++ != '\0');
296 return inner_find_program_in_path (program);
302 * g_find_program_in_path:
303 * @program: (type filename): a program name in the GLib file name encoding
305 * Locates the first executable named @program in the user's path, in the
306 * same way that execvp() would locate it. Returns an allocated string
307 * with the absolute path name, or %NULL if the program is not found in
308 * the path. If @program is already an absolute path, returns a copy of
309 * @program if @program exists and is executable, and %NULL otherwise.
311 * On Windows, if @program does not have a file type suffix, tries
312 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
313 * the `PATHEXT` environment variable.
315 * On Windows, it looks for the file in the same way as CreateProcess()
316 * would. This means first in the directory where the executing
317 * program was loaded from, then in the current directory, then in the
318 * Windows 32-bit system directory, then in the Windows directory, and
319 * finally in the directories in the `PATH` environment variable. If
320 * the program is found, the return value contains the full name
321 * including the type suffix.
323 * Returns: (type filename): a newly-allocated string with the absolute path,
328 inner_find_program_in_path (const gchar *program)
331 g_find_program_in_path (const gchar *program)
334 const gchar *path, *p;
335 gchar *name, *freeme;
337 const gchar *path_copy;
338 gchar *filename = NULL, *appdir = NULL;
339 gchar *sysdir = NULL, *windir = NULL;
341 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
347 g_return_val_if_fail (program != NULL, NULL);
349 /* If it is an absolute path, or a relative path including subdirectories,
350 * don't look in PATH.
352 if (g_path_is_absolute (program)
353 || strchr (program, G_DIR_SEPARATOR) != NULL
355 || strchr (program, '/') != NULL
359 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
360 !g_file_test (program, G_FILE_TEST_IS_DIR))
361 return g_strdup (program);
366 path = g_getenv ("PATH");
367 #if defined(G_OS_UNIX)
370 /* There is no 'PATH' in the environment. The default
371 * search path in GNU libc is the current directory followed by
372 * the path 'confstr' returns for '_CS_PATH'.
375 /* In GLib we put . last, for security, and don't use the
376 * unportable confstr(); UNIX98 does not actually specify
377 * what to search if PATH is unset. POSIX may, dunno.
380 path = "/bin:/usr/bin:.";
383 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
384 if (n > 0 && n < MAXPATHLEN)
385 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
387 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
388 if (n > 0 && n < MAXPATHLEN)
389 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
391 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
392 if (n > 0 && n < MAXPATHLEN)
393 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
397 appdir = g_path_get_dirname (filename);
401 path = g_strdup (path);
405 const gchar *tem = path;
406 path = g_strconcat (windir, ";", path, NULL);
407 g_free ((gchar *) tem);
413 const gchar *tem = path;
414 path = g_strconcat (sysdir, ";", path, NULL);
415 g_free ((gchar *) tem);
420 const gchar *tem = path;
421 path = g_strconcat (".;", path, NULL);
422 g_free ((gchar *) tem);
427 const gchar *tem = path;
428 path = g_strconcat (appdir, ";", path, NULL);
429 g_free ((gchar *) tem);
436 len = strlen (program) + 1;
437 pathlen = strlen (path);
438 freeme = name = g_malloc (pathlen + len + 1);
440 /* Copy the file name at the top, including '\0' */
441 memcpy (name + pathlen + 1, program, len);
442 name = name + pathlen;
443 /* And add the slash before the filename */
444 *name = G_DIR_SEPARATOR;
452 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
455 /* Two adjacent colons, or a colon at the beginning or the end
456 * of 'PATH' means to search the current directory.
460 startp = memcpy (name - (p - path), path, p - path);
462 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
463 !g_file_test (startp, G_FILE_TEST_IS_DIR))
466 ret = g_strdup (startp);
469 g_free ((gchar *) path_copy);
474 while (*p++ != '\0');
478 g_free ((gchar *) path_copy);
484 /* The functions below are defined this way for compatibility reasons.
485 * See the note in gutils.h.
490 * @mask: a #gulong containing flags
491 * @nth_bit: the index of the bit to start the search from
493 * Find the position of the first bit set in @mask, searching
494 * from (but not including) @nth_bit upwards. Bits are numbered
495 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
496 * usually). To start searching from the 0th bit, set @nth_bit to -1.
498 * Returns: the index of the first bit set which is higher than @nth_bit, or -1
499 * if no higher bits are set
502 (g_bit_nth_lsf) (gulong mask,
505 return g_bit_nth_lsf_impl (mask, nth_bit);
510 * @mask: a #gulong containing flags
511 * @nth_bit: the index of the bit to start the search from
513 * Find the position of the first bit set in @mask, searching
514 * from (but not including) @nth_bit downwards. Bits are numbered
515 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
516 * usually). To start searching from the last bit, set @nth_bit to
517 * -1 or GLIB_SIZEOF_LONG * 8.
519 * Returns: the index of the first bit set which is lower than @nth_bit, or -1
520 * if no lower bits are set
523 (g_bit_nth_msf) (gulong mask,
526 return g_bit_nth_msf_impl (mask, nth_bit);
534 * Gets the number of bits used to hold @number,
535 * e.g. if @number is 4, 3 bits are needed.
537 * Returns: the number of bits used to hold @number
540 (g_bit_storage) (gulong number)
542 return g_bit_storage_impl (number);
545 G_LOCK_DEFINE_STATIC (g_utils_global);
554 static gchar *g_user_data_dir = NULL;
555 static gchar **g_system_data_dirs = NULL;
556 static gchar *g_user_cache_dir = NULL;
557 static gchar *g_user_config_dir = NULL;
558 static gchar **g_system_config_dirs = NULL;
560 static gchar **g_user_special_dirs = NULL;
562 /* fifteen minutes of fame for everybody */
563 #define G_USER_DIRS_EXPIRE 15 * 60
568 get_special_folder (int csidl)
570 wchar_t path[MAX_PATH+1];
572 LPITEMIDLIST pidl = NULL;
574 gchar *retval = NULL;
576 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
579 b = SHGetPathFromIDListW (pidl, path);
581 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
582 CoTaskMemFree (pidl);
588 get_windows_directory_root (void)
590 wchar_t wwindowsdir[MAX_PATH];
592 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
594 /* Usually X:\Windows, but in terminal server environments
595 * might be an UNC path, AFAIK.
597 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
600 if (windowsdir == NULL)
601 return g_strdup ("C:\\");
603 p = (char *) g_path_skip_root (windowsdir);
604 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
610 return g_strdup ("C:\\");
615 /* HOLDS: g_utils_global_lock */
616 static UserDatabaseEntry *
617 g_get_user_database_entry (void)
619 static UserDatabaseEntry *entry;
621 if (g_once_init_enter (&entry))
623 static UserDatabaseEntry e;
627 struct passwd *pw = NULL;
628 gpointer buffer = NULL;
632 # if defined (HAVE_GETPWUID_R)
634 # ifdef _SC_GETPW_R_SIZE_MAX
635 /* This reurns the maximum length */
636 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
640 # else /* _SC_GETPW_R_SIZE_MAX */
642 # endif /* _SC_GETPW_R_SIZE_MAX */
644 logname = (gchar *) g_getenv ("LOGNAME");
649 /* we allocate 6 extra bytes to work around a bug in
650 * Mac OS < 10.3. See #156446
652 buffer = g_malloc (bufsize + 6);
656 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
657 if (!pw || (pw->pw_uid != getuid ())) {
658 /* LOGNAME is lying, fall back to looking up the uid */
659 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
662 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
664 error = error < 0 ? errno : error;
668 /* we bail out prematurely if the user id can't be found
669 * (should be pretty rare case actually), or if the buffer
670 * should be sufficiently big and lookups are still not
673 if (error == 0 || error == ENOENT)
675 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
679 if (bufsize > 32 * 1024)
681 g_warning ("getpwuid_r(): failed due to: %s.",
690 # endif /* HAVE_GETPWUID_R */
694 pw = getpwuid (getuid ());
698 e.user_name = g_strdup (pw->pw_name);
701 if (pw->pw_gecos && *pw->pw_gecos != '\0')
703 gchar **gecos_fields;
706 /* split the gecos field and substitute '&' */
707 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
708 name_parts = g_strsplit (gecos_fields[0], "&", 0);
709 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
710 e.real_name = g_strjoinv (pw->pw_name, name_parts);
711 g_strfreev (gecos_fields);
712 g_strfreev (name_parts);
717 e.home_dir = g_strdup (pw->pw_dir);
722 #endif /* G_OS_UNIX */
727 wchar_t buffer[UNLEN+1];
729 if (GetUserNameW (buffer, (LPDWORD) &len))
731 e.user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
732 e.real_name = g_strdup (e.user_name);
735 #endif /* G_OS_WIN32 */
738 e.user_name = g_strdup ("somebody");
740 e.real_name = g_strdup ("Unknown");
742 g_once_init_leave (&entry, &e);
751 * Gets the user name of the current user. The encoding of the returned
752 * string is system-defined. On UNIX, it might be the preferred file name
753 * encoding, or something else, and there is no guarantee that it is even
754 * consistent on a machine. On Windows, it is always UTF-8.
756 * Returns: (type filename): the user name of the current user.
759 g_get_user_name (void)
761 UserDatabaseEntry *entry;
763 entry = g_get_user_database_entry ();
765 return entry->user_name;
771 * Gets the real name of the user. This usually comes from the user's
772 * entry in the `passwd` file. The encoding of the returned string is
773 * system-defined. (On Windows, it is, however, always UTF-8.) If the
774 * real user name cannot be determined, the string "Unknown" is
777 * Returns: (type filename): the user's real name.
780 g_get_real_name (void)
782 UserDatabaseEntry *entry;
784 entry = g_get_user_database_entry ();
786 return entry->real_name;
792 * Gets the current user's home directory.
794 * As with most UNIX tools, this function will return the value of the
795 * `HOME` environment variable if it is set to an existing absolute path
796 * name, falling back to the `passwd` file in the case that it is unset.
798 * If the path given in `HOME` is non-absolute, does not exist, or is
799 * not a directory, the result is undefined.
801 * Before version 2.36 this function would ignore the `HOME` environment
802 * variable, taking the value from the `passwd` database instead. This was
803 * changed to increase the compatibility of GLib with other programs (and
804 * the XDG basedir specification) and to increase testability of programs
805 * based on GLib (by making it easier to run them from test frameworks).
807 * If your program has a strong requirement for either the new or the
808 * old behaviour (and if you don't wish to increase your GLib
809 * dependency to ensure that the new behaviour is in effect) then you
810 * should either directly check the `HOME` environment variable yourself
811 * or unset it before calling any functions in GLib.
813 * Returns: (type filename): the current user's home directory
816 g_get_home_dir (void)
818 static gchar *home_dir;
820 if (g_once_init_enter (&home_dir))
824 /* We first check HOME and use it if it is set */
825 tmp = g_strdup (g_getenv ("HOME"));
828 /* Only believe HOME if it is an absolute path and exists.
830 * We only do this check on Windows for a couple of reasons.
831 * Historically, we only did it there because we used to ignore $HOME
832 * on UNIX. There are concerns about enabling it now on UNIX because
833 * of things like autofs. In short, if the user has a bogus value in
834 * $HOME then they get what they pay for...
838 if (!(g_path_is_absolute (tmp) &&
839 g_file_test (tmp, G_FILE_TEST_IS_DIR)))
846 /* In case HOME is Unix-style (it happens), convert it to
852 while ((p = strchr (tmp, '/')) != NULL)
858 /* USERPROFILE is probably the closest equivalent to $HOME? */
859 if (g_getenv ("USERPROFILE") != NULL)
860 tmp = g_strdup (g_getenv ("USERPROFILE"));
864 tmp = get_special_folder (CSIDL_PROFILE);
867 tmp = get_windows_directory_root ();
868 #endif /* G_OS_WIN32 */
872 /* If we didn't get it from any of those methods, we will have
873 * to read the user database entry.
875 UserDatabaseEntry *entry;
877 entry = g_get_user_database_entry ();
879 /* Strictly speaking, we should copy this, but we know that
880 * neither will ever be freed, so don't bother...
882 tmp = entry->home_dir;
885 g_once_init_leave (&home_dir, tmp);
894 * Gets the directory to use for temporary files.
896 * On UNIX, this is taken from the `TMPDIR` environment variable.
897 * If the variable is not set, `P_tmpdir` is
898 * used, as defined by the system C library. Failing that, a
899 * hard-coded default of "/tmp" is returned.
901 * On Windows, the `TEMP` environment variable is used, with the
902 * root directory of the Windows installation (eg: "C:\") used
905 * The encoding of the returned string is system-defined. On Windows,
906 * it is always UTF-8. The return value is never %NULL or the empty
909 * Returns: (type filename): the directory to use for temporary files.
914 static gchar *tmp_dir;
916 if (g_once_init_enter (&tmp_dir))
921 tmp = g_strdup (g_getenv ("TEMP"));
923 if (tmp == NULL || *tmp == '\0')
926 tmp = get_windows_directory_root ();
928 #else /* G_OS_WIN32 */
929 tmp = g_strdup (g_getenv ("TMPDIR"));
932 if (tmp == NULL || *tmp == '\0')
936 tmp = g_strdup (P_tmpdir);
938 if (k > 1 && G_IS_DIR_SEPARATOR (tmp[k - 1]))
941 #endif /* P_tmpdir */
943 if (tmp == NULL || *tmp == '\0')
946 tmp = g_strdup ("/tmp");
948 #endif /* !G_OS_WIN32 */
950 g_once_init_leave (&tmp_dir, tmp);
959 * Return a name for the machine.
961 * The returned name is not necessarily a fully-qualified domain name,
962 * or even present in DNS or some other name service at all. It need
963 * not even be unique on your local network or site, but usually it
964 * is. Callers should not rely on the return value having any specific
965 * properties like uniqueness for security purposes. Even if the name
966 * of the machine is changed while an application is running, the
967 * return value from this function does not change. The returned
968 * string is owned by GLib and should not be modified or freed. If no
969 * name can be determined, a default fixed string "localhost" is
972 * Returns: the host name of the machine.
977 g_get_host_name (void)
979 static gchar *hostname;
981 if (g_once_init_enter (&hostname))
987 failed = (gethostname (tmp, sizeof (tmp)) == -1);
989 DWORD size = sizeof (tmp);
990 failed = (!GetComputerName (tmp, &size));
993 g_once_init_leave (&hostname, g_strdup (failed ? "localhost" : tmp));
999 G_LOCK_DEFINE_STATIC (g_prgname);
1000 static gchar *g_prgname = NULL;
1005 * Gets the name of the program. This name should not be localized,
1006 * in contrast to g_get_application_name().
1008 * If you are using #GApplication the program name is set in
1009 * g_application_run(). In case of GDK or GTK+ it is set in
1010 * gdk_init(), which is called by gtk_init() and the
1011 * #GtkApplication::startup handler. The program name is found by
1012 * taking the last component of @argv[0].
1014 * Returns: the name of the program. The returned string belongs
1015 * to GLib and must not be modified or freed.
1018 g_get_prgname (void)
1024 if (g_prgname == NULL)
1026 static gboolean beenhere = FALSE;
1030 gchar *utf8_buf = NULL;
1031 wchar_t buf[MAX_PATH+1];
1034 if (GetModuleFileNameW (GetModuleHandle (NULL),
1035 buf, G_N_ELEMENTS (buf)) > 0)
1036 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1040 g_prgname = g_path_get_basename (utf8_buf);
1047 G_UNLOCK (g_prgname);
1054 * @prgname: the name of the program.
1056 * Sets the name of the program. This name should not be localized,
1057 * in contrast to g_set_application_name().
1059 * If you are using #GApplication the program name is set in
1060 * g_application_run(). In case of GDK or GTK+ it is set in
1061 * gdk_init(), which is called by gtk_init() and the
1062 * #GtkApplication::startup handler. The program name is found by
1063 * taking the last component of @argv[0].
1065 * Note that for thread-safety reasons this function can only be called once.
1068 g_set_prgname (const gchar *prgname)
1072 g_prgname = g_strdup (prgname);
1073 G_UNLOCK (g_prgname);
1076 G_LOCK_DEFINE_STATIC (g_application_name);
1077 static gchar *g_application_name = NULL;
1080 * g_get_application_name:
1082 * Gets a human-readable name for the application, as set by
1083 * g_set_application_name(). This name should be localized if
1084 * possible, and is intended for display to the user. Contrast with
1085 * g_get_prgname(), which gets a non-localized name. If
1086 * g_set_application_name() has not been called, returns the result of
1087 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1090 * Returns: human-readable application name. may return %NULL
1095 g_get_application_name (void)
1099 G_LOCK (g_application_name);
1100 retval = g_application_name;
1101 G_UNLOCK (g_application_name);
1104 return g_get_prgname ();
1110 * g_set_application_name:
1111 * @application_name: localized name of the application
1113 * Sets a human-readable name for the application. This name should be
1114 * localized if possible, and is intended for display to the user.
1115 * Contrast with g_set_prgname(), which sets a non-localized name.
1116 * g_set_prgname() will be called automatically by gtk_init(),
1117 * but g_set_application_name() will not.
1119 * Note that for thread safety reasons, this function can only
1122 * The application name will be used in contexts such as error messages,
1123 * or when displaying an application's name in the task list.
1128 g_set_application_name (const gchar *application_name)
1130 gboolean already_set = FALSE;
1132 G_LOCK (g_application_name);
1133 if (g_application_name)
1136 g_application_name = g_strdup (application_name);
1137 G_UNLOCK (g_application_name);
1140 g_warning ("g_set_application_name() called multiple times");
1144 * g_get_user_data_dir:
1146 * Returns a base directory in which to access application data such
1147 * as icons that is customized for a particular user.
1149 * On UNIX platforms this is determined using the mechanisms described
1151 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1152 * In this case the directory retrieved will be `XDG_DATA_HOME`.
1154 * On Windows this is the folder to use for local (as opposed to
1155 * roaming) application data. See documentation for
1156 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1157 * what g_get_user_config_dir() returns.
1159 * Returns: (type filename): a string owned by GLib that must not be modified
1164 g_get_user_data_dir (void)
1168 G_LOCK (g_utils_global);
1170 if (!g_user_data_dir)
1173 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1175 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1177 if (data_dir && data_dir[0])
1178 data_dir = g_strdup (data_dir);
1180 if (!data_dir || !data_dir[0])
1182 const gchar *home_dir = g_get_home_dir ();
1185 data_dir = g_build_filename (home_dir, ".local", "share", NULL);
1187 data_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".local", "share", NULL);
1190 g_user_data_dir = data_dir;
1193 data_dir = g_user_data_dir;
1195 G_UNLOCK (g_utils_global);
1201 g_init_user_config_dir (void)
1205 if (!g_user_config_dir)
1208 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1210 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1212 if (config_dir && config_dir[0])
1213 config_dir = g_strdup (config_dir);
1215 if (!config_dir || !config_dir[0])
1217 const gchar *home_dir = g_get_home_dir ();
1220 config_dir = g_build_filename (home_dir, ".config", NULL);
1222 config_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".config", NULL);
1225 g_user_config_dir = config_dir;
1230 * g_get_user_config_dir:
1232 * Returns a base directory in which to store user-specific application
1233 * configuration information such as user preferences and settings.
1235 * On UNIX platforms this is determined using the mechanisms described
1237 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1238 * In this case the directory retrieved will be `XDG_CONFIG_HOME`.
1240 * On Windows this is the folder to use for local (as opposed to
1241 * roaming) application data. See documentation for
1242 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1243 * what g_get_user_data_dir() returns.
1245 * Returns: (type filename): a string owned by GLib that must not be modified
1250 g_get_user_config_dir (void)
1252 G_LOCK (g_utils_global);
1254 g_init_user_config_dir ();
1256 G_UNLOCK (g_utils_global);
1258 return g_user_config_dir;
1262 * g_get_user_cache_dir:
1264 * Returns a base directory in which to store non-essential, cached
1265 * data specific to particular user.
1267 * On UNIX platforms this is determined using the mechanisms described
1269 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1270 * In this case the directory retrieved will be XDG_CACHE_HOME.
1272 * On Windows is the directory that serves as a common repository for
1273 * temporary Internet files. A typical path is
1274 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
1275 * See documentation for CSIDL_INTERNET_CACHE.
1277 * Returns: (type filename): a string owned by GLib that must not be modified
1282 g_get_user_cache_dir (void)
1286 G_LOCK (g_utils_global);
1288 if (!g_user_cache_dir)
1291 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1293 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1295 if (cache_dir && cache_dir[0])
1296 cache_dir = g_strdup (cache_dir);
1298 if (!cache_dir || !cache_dir[0])
1300 const gchar *home_dir = g_get_home_dir ();
1303 cache_dir = g_build_filename (home_dir, ".cache", NULL);
1305 cache_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".cache", NULL);
1307 g_user_cache_dir = cache_dir;
1310 cache_dir = g_user_cache_dir;
1312 G_UNLOCK (g_utils_global);
1318 * g_get_user_runtime_dir:
1320 * Returns a directory that is unique to the current user on the local
1323 * On UNIX platforms this is determined using the mechanisms described
1325 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1326 * This is the directory
1327 * specified in the `XDG_RUNTIME_DIR` environment variable.
1328 * In the case that this variable is not set, we return the value of
1329 * g_get_user_cache_dir(), after verifying that it exists.
1331 * On Windows this is the folder to use for local (as opposed to
1332 * roaming) application data. See documentation for
1333 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1334 * what g_get_user_config_dir() returns.
1336 * Returns: (type filename): a string owned by GLib that must not be
1337 * modified or freed.
1342 g_get_user_runtime_dir (void)
1345 static const gchar *runtime_dir;
1347 if (g_once_init_enter (&runtime_dir))
1351 dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
1355 /* No need to strdup this one since it is valid forever. */
1356 dir = g_get_user_cache_dir ();
1358 /* The user should be able to rely on the directory existing
1359 * when the function returns. Probably it already does, but
1360 * let's make sure. Just do mkdir() directly since it will be
1361 * no more expensive than a stat() in the case that the
1362 * directory already exists and is a lot easier.
1364 * $XDG_CACHE_HOME is probably ~/.cache/ so as long as $HOME
1365 * exists this will work. If the user changed $XDG_CACHE_HOME
1366 * then they can make sure that it exists...
1368 (void) mkdir (dir, 0700);
1371 g_assert (dir != NULL);
1373 g_once_init_leave (&runtime_dir, dir);
1378 return g_get_user_cache_dir ();
1385 find_folder (OSType type)
1387 gchar *filename = NULL;
1390 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
1392 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
1396 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
1400 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
1404 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
1406 CFStringGetCString (path, filename,
1407 CFStringGetLength (path) * 3 + 1,
1408 kCFStringEncodingUTF8);
1422 load_user_special_dirs (void)
1424 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
1425 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
1426 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
1427 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
1428 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
1429 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
1430 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
1431 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
1434 #elif defined(G_OS_WIN32)
1437 load_user_special_dirs (void)
1439 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1443 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
1445 static const GUID FOLDERID_Downloads =
1446 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1447 static const GUID FOLDERID_Public =
1448 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1452 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
1453 "SHGetKnownFolderPath");
1455 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1456 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
1458 if (p_SHGetKnownFolderPath == NULL)
1460 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1465 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1468 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1469 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
1470 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1471 CoTaskMemFree (wcp);
1474 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1477 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
1478 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
1480 if (p_SHGetKnownFolderPath == NULL)
1483 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1488 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
1491 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1492 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
1493 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1494 CoTaskMemFree (wcp);
1497 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1500 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
1501 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
1504 #else /* default is unix */
1506 /* adapted from xdg-user-dir-lookup.c
1508 * Copyright (C) 2007 Red Hat Inc.
1510 * Permission is hereby granted, free of charge, to any person
1511 * obtaining a copy of this software and associated documentation files
1512 * (the "Software"), to deal in the Software without restriction,
1513 * including without limitation the rights to use, copy, modify, merge,
1514 * publish, distribute, sublicense, and/or sell copies of the Software,
1515 * and to permit persons to whom the Software is furnished to do so,
1516 * subject to the following conditions:
1518 * The above copyright notice and this permission notice shall be
1519 * included in all copies or substantial portions of the Software.
1521 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1522 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1523 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1524 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1525 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1526 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1527 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1531 load_user_special_dirs (void)
1538 g_init_user_config_dir ();
1539 config_file = g_build_filename (g_user_config_dir,
1543 if (!g_file_get_contents (config_file, &data, NULL, NULL))
1545 g_free (config_file);
1549 lines = g_strsplit (data, "\n", -1);
1550 n_lines = g_strv_length (lines);
1553 for (i = 0; i < n_lines; i++)
1555 gchar *buffer = lines[i];
1558 gboolean is_relative = FALSE;
1559 GUserDirectory directory;
1561 /* Remove newline at end */
1562 len = strlen (buffer);
1563 if (len > 0 && buffer[len - 1] == '\n')
1564 buffer[len - 1] = 0;
1567 while (*p == ' ' || *p == '\t')
1570 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
1572 directory = G_USER_DIRECTORY_DESKTOP;
1573 p += strlen ("XDG_DESKTOP_DIR");
1575 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
1577 directory = G_USER_DIRECTORY_DOCUMENTS;
1578 p += strlen ("XDG_DOCUMENTS_DIR");
1580 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
1582 directory = G_USER_DIRECTORY_DOWNLOAD;
1583 p += strlen ("XDG_DOWNLOAD_DIR");
1585 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
1587 directory = G_USER_DIRECTORY_MUSIC;
1588 p += strlen ("XDG_MUSIC_DIR");
1590 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
1592 directory = G_USER_DIRECTORY_PICTURES;
1593 p += strlen ("XDG_PICTURES_DIR");
1595 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
1597 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
1598 p += strlen ("XDG_PUBLICSHARE_DIR");
1600 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
1602 directory = G_USER_DIRECTORY_TEMPLATES;
1603 p += strlen ("XDG_TEMPLATES_DIR");
1605 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
1607 directory = G_USER_DIRECTORY_VIDEOS;
1608 p += strlen ("XDG_VIDEOS_DIR");
1613 while (*p == ' ' || *p == '\t')
1620 while (*p == ' ' || *p == '\t')
1627 if (strncmp (p, "$HOME", 5) == 0)
1635 d = strrchr (p, '"');
1642 /* remove trailing slashes */
1644 if (d[len - 1] == '/')
1649 g_user_special_dirs[directory] = g_build_filename (g_get_home_dir (), d, NULL);
1652 g_user_special_dirs[directory] = g_strdup (d);
1656 g_free (config_file);
1659 #endif /* platform-specific load_user_special_dirs implementations */
1663 * g_reload_user_special_dirs_cache:
1665 * Resets the cache used for g_get_user_special_dir(), so
1666 * that the latest on-disk version is used. Call this only
1667 * if you just changed the data on disk yourself.
1669 * Due to threadsafety issues this may cause leaking of strings
1670 * that were previously returned from g_get_user_special_dir()
1671 * that can't be freed. We ensure to only leak the data for
1672 * the directories that actually changed value though.
1677 g_reload_user_special_dirs_cache (void)
1681 G_LOCK (g_utils_global);
1683 if (g_user_special_dirs != NULL)
1685 /* save a copy of the pointer, to check if some memory can be preserved */
1686 char **old_g_user_special_dirs = g_user_special_dirs;
1689 /* recreate and reload our cache */
1690 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1691 load_user_special_dirs ();
1693 /* only leak changed directories */
1694 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
1696 old_val = old_g_user_special_dirs[i];
1697 if (g_user_special_dirs[i] == NULL)
1699 g_user_special_dirs[i] = old_val;
1701 else if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
1704 g_free (g_user_special_dirs[i]);
1705 g_user_special_dirs[i] = old_val;
1711 /* free the old array */
1712 g_free (old_g_user_special_dirs);
1715 G_UNLOCK (g_utils_global);
1719 * g_get_user_special_dir:
1720 * @directory: the logical id of special directory
1722 * Returns the full path of a special directory using its logical id.
1724 * On UNIX this is done using the XDG special user directories.
1725 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
1726 * falls back to `$HOME/Desktop` when XDG special user directories have
1729 * Depending on the platform, the user might be able to change the path
1730 * of the special directory without requiring the session to restart; GLib
1731 * will not reflect any change once the special directories are loaded.
1733 * Returns: (type filename): the path to the specified special directory, or
1734 * %NULL if the logical id was not found. The returned string is owned by
1735 * GLib and should not be modified or freed.
1740 g_get_user_special_dir (GUserDirectory directory)
1742 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
1743 directory < G_USER_N_DIRECTORIES, NULL);
1745 G_LOCK (g_utils_global);
1747 if (G_UNLIKELY (g_user_special_dirs == NULL))
1749 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1751 load_user_special_dirs ();
1753 /* Special-case desktop for historical compatibility */
1754 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
1755 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = g_build_filename (g_get_home_dir (), "Desktop", NULL);
1758 G_UNLOCK (g_utils_global);
1760 return g_user_special_dirs[directory];
1765 #undef g_get_system_data_dirs
1768 get_module_for_address (gconstpointer address)
1770 /* Holds the g_utils_global lock */
1772 static gboolean beenhere = FALSE;
1773 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
1774 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
1775 HMODULE hmodule = NULL;
1782 p_GetModuleHandleExA =
1783 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1784 "GetModuleHandleExA");
1788 if (p_GetModuleHandleExA == NULL ||
1789 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
1790 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
1793 MEMORY_BASIC_INFORMATION mbi;
1794 VirtualQuery (address, &mbi, sizeof (mbi));
1795 hmodule = (HMODULE) mbi.AllocationBase;
1802 get_module_share_dir (gconstpointer address)
1808 hmodule = get_module_for_address (address);
1809 if (hmodule == NULL)
1812 filename = g_win32_get_package_installation_directory_of_module (hmodule);
1813 retval = g_build_filename (filename, "share", NULL);
1819 const gchar * const *
1820 g_win32_get_system_data_dirs_for_module (void (*address_of_function)(void))
1824 static GHashTable *per_module_data_dirs = NULL;
1830 if (address_of_function)
1832 G_LOCK (g_utils_global);
1833 hmodule = get_module_for_address (address_of_function);
1834 if (hmodule != NULL)
1836 if (per_module_data_dirs == NULL)
1837 per_module_data_dirs = g_hash_table_new (NULL, NULL);
1840 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
1844 G_UNLOCK (g_utils_global);
1845 return (const gchar * const *) retval;
1851 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
1853 /* Documents and Settings\All Users\Application Data */
1854 p = get_special_folder (CSIDL_COMMON_APPDATA);
1856 g_array_append_val (data_dirs, p);
1858 /* Documents and Settings\All Users\Documents */
1859 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1861 g_array_append_val (data_dirs, p);
1863 /* Using the above subfolders of Documents and Settings perhaps
1864 * makes sense from a Windows perspective.
1866 * But looking at the actual use cases of this function in GTK+
1867 * and GNOME software, what we really want is the "share"
1868 * subdirectory of the installation directory for the package
1869 * our caller is a part of.
1871 * The address_of_function parameter, if non-NULL, points to a
1872 * function in the calling module. Use that to determine that
1873 * module's installation folder, and use its "share" subfolder.
1875 * Additionally, also use the "share" subfolder of the installation
1876 * locations of GLib and the .exe file being run.
1878 * To guard against none of the above being what is really wanted,
1879 * callers of this function should have Win32-specific code to look
1880 * up their installation folder themselves, and handle a subfolder
1881 * "share" of it in the same way as the folders returned from this
1885 p = get_module_share_dir (address_of_function);
1887 g_array_append_val (data_dirs, p);
1889 if (glib_dll != NULL)
1891 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
1892 p = g_build_filename (glib_root, "share", NULL);
1894 g_array_append_val (data_dirs, p);
1898 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
1899 p = g_build_filename (exe_root, "share", NULL);
1901 g_array_append_val (data_dirs, p);
1904 retval = (gchar **) g_array_free (data_dirs, FALSE);
1906 if (address_of_function)
1908 if (hmodule != NULL)
1909 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
1910 G_UNLOCK (g_utils_global);
1913 return (const gchar * const *) retval;
1919 * g_get_system_data_dirs:
1921 * Returns an ordered list of base directories in which to access
1922 * system-wide application data.
1924 * On UNIX platforms this is determined using the mechanisms described
1926 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec)
1927 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
1929 * On Windows the first elements in the list are the Application Data
1930 * and Documents folders for All Users. (These can be determined only
1931 * on Windows 2000 or later and are not present in the list on other
1932 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
1933 * CSIDL_COMMON_DOCUMENTS.
1935 * Then follows the "share" subfolder in the installation folder for
1936 * the package containing the DLL that calls this function, if it can
1939 * Finally the list contains the "share" subfolder in the installation
1940 * folder for GLib, and in the installation folder for the package the
1941 * application's .exe file belongs to.
1943 * The installation folders above are determined by looking up the
1944 * folder where the module (DLL or EXE) in question is located. If the
1945 * folder's name is "bin", its parent is used, otherwise the folder
1948 * Note that on Windows the returned list can vary depending on where
1949 * this function is called.
1951 * Returns: (array zero-terminated=1) (element-type filename) (transfer none):
1952 * a %NULL-terminated array of strings owned by GLib that must not be
1953 * modified or freed.
1957 const gchar * const *
1958 g_get_system_data_dirs (void)
1960 gchar **data_dir_vector;
1962 G_LOCK (g_utils_global);
1964 if (!g_system_data_dirs)
1967 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
1969 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
1971 if (!data_dirs || !data_dirs[0])
1972 data_dirs = "/usr/local/share/:/usr/share/";
1974 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1977 g_system_data_dirs = data_dir_vector;
1980 data_dir_vector = g_system_data_dirs;
1982 G_UNLOCK (g_utils_global);
1984 return (const gchar * const *) data_dir_vector;
1988 * g_get_system_config_dirs:
1990 * Returns an ordered list of base directories in which to access
1991 * system-wide configuration information.
1993 * On UNIX platforms this is determined using the mechanisms described
1995 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1996 * In this case the list of directories retrieved will be `XDG_CONFIG_DIRS`.
1998 * On Windows is the directory that contains application data for all users.
1999 * A typical path is C:\Documents and Settings\All Users\Application Data.
2000 * This folder is used for application data that is not user specific.
2001 * For example, an application can store a spell-check dictionary, a database
2002 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2003 * This information will not roam and is available to anyone using the computer.
2005 * Returns: (array zero-terminated=1) (element-type filename) (transfer none):
2006 * a %NULL-terminated array of strings owned by GLib that must not be
2007 * modified or freed.
2011 const gchar * const *
2012 g_get_system_config_dirs (void)
2014 gchar *conf_dirs, **conf_dir_vector;
2016 G_LOCK (g_utils_global);
2018 if (!g_system_config_dirs)
2021 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2024 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2029 /* Return empty list */
2030 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2033 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2035 if (!conf_dirs || !conf_dirs[0])
2036 conf_dirs = "/etc/xdg";
2038 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2041 g_system_config_dirs = conf_dir_vector;
2044 conf_dir_vector = g_system_config_dirs;
2045 G_UNLOCK (g_utils_global);
2047 return (const gchar * const *) conf_dir_vector;
2051 * g_nullify_pointer:
2052 * @nullify_location: (not nullable): the memory address of the pointer.
2054 * Set the pointer at the specified location to %NULL.
2057 g_nullify_pointer (gpointer *nullify_location)
2059 g_return_if_fail (nullify_location != NULL);
2061 *nullify_location = NULL;
2064 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2065 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2066 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2067 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2068 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2069 #define EXABYTE_FACTOR (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2071 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2072 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2073 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2074 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2075 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2076 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2080 * @size: a size in bytes
2082 * Formats a size (for example the size of a file) into a human readable
2083 * string. Sizes are rounded to the nearest size prefix (kB, MB, GB)
2084 * and are displayed rounded to the nearest tenth. E.g. the file size
2085 * 3292528 bytes will be converted into the string "3.2 MB".
2087 * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2089 * This string should be freed with g_free() when not needed any longer.
2091 * See g_format_size_full() for more options about how the size might be
2094 * Returns: a newly-allocated formatted string containing a human readable
2100 g_format_size (guint64 size)
2102 return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2107 * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2108 * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2109 * of the returned string. For example, "45.6 kB (45,612 bytes)".
2110 * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2111 * suffixes. IEC units should only be used for reporting things with
2112 * a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2113 * Network and storage sizes should be reported in the normal SI units.
2115 * Flags to modify the format of the string returned by g_format_size_full().
2118 #pragma GCC diagnostic push
2119 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
2122 * g_format_size_full:
2123 * @size: a size in bytes
2124 * @flags: #GFormatSizeFlags to modify the output
2128 * This function is similar to g_format_size() but allows for flags
2129 * that modify the output. See #GFormatSizeFlags.
2131 * Returns: a newly-allocated formatted string containing a human
2132 * readable file size
2137 g_format_size_full (guint64 size,
2138 GFormatSizeFlags flags)
2142 string = g_string_new (NULL);
2144 if (flags & G_FORMAT_SIZE_IEC_UNITS)
2146 if (size < KIBIBYTE_FACTOR)
2148 g_string_printf (string,
2149 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2151 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2154 else if (size < MEBIBYTE_FACTOR)
2155 g_string_printf (string, _("%.1f KiB"), (gdouble) size / (gdouble) KIBIBYTE_FACTOR);
2156 else if (size < GIBIBYTE_FACTOR)
2157 g_string_printf (string, _("%.1f MiB"), (gdouble) size / (gdouble) MEBIBYTE_FACTOR);
2159 else if (size < TEBIBYTE_FACTOR)
2160 g_string_printf (string, _("%.1f GiB"), (gdouble) size / (gdouble) GIBIBYTE_FACTOR);
2162 else if (size < PEBIBYTE_FACTOR)
2163 g_string_printf (string, _("%.1f TiB"), (gdouble) size / (gdouble) TEBIBYTE_FACTOR);
2165 else if (size < EXBIBYTE_FACTOR)
2166 g_string_printf (string, _("%.1f PiB"), (gdouble) size / (gdouble) PEBIBYTE_FACTOR);
2169 g_string_printf (string, _("%.1f EiB"), (gdouble) size / (gdouble) EXBIBYTE_FACTOR);
2173 if (size < KILOBYTE_FACTOR)
2175 g_string_printf (string,
2176 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2178 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2181 else if (size < MEGABYTE_FACTOR)
2182 g_string_printf (string, _("%.1f kB"), (gdouble) size / (gdouble) KILOBYTE_FACTOR);
2184 else if (size < GIGABYTE_FACTOR)
2185 g_string_printf (string, _("%.1f MB"), (gdouble) size / (gdouble) MEGABYTE_FACTOR);
2187 else if (size < TERABYTE_FACTOR)
2188 g_string_printf (string, _("%.1f GB"), (gdouble) size / (gdouble) GIGABYTE_FACTOR);
2189 else if (size < PETABYTE_FACTOR)
2190 g_string_printf (string, _("%.1f TB"), (gdouble) size / (gdouble) TERABYTE_FACTOR);
2192 else if (size < EXABYTE_FACTOR)
2193 g_string_printf (string, _("%.1f PB"), (gdouble) size / (gdouble) PETABYTE_FACTOR);
2196 g_string_printf (string, _("%.1f EB"), (gdouble) size / (gdouble) EXABYTE_FACTOR);
2199 if (flags & G_FORMAT_SIZE_LONG_FORMAT)
2201 /* First problem: we need to use the number of bytes to decide on
2202 * the plural form that is used for display, but the number of
2203 * bytes potentially exceeds the size of a guint (which is what
2204 * ngettext() takes).
2206 * From a pragmatic standpoint, it seems that all known languages
2207 * base plural forms on one or both of the following:
2209 * - the lowest digits of the number
2211 * - if the number if greater than some small value
2213 * Here's how we fake it: Draw an arbitrary line at one thousand.
2214 * If the number is below that, then fine. If it is above it,
2215 * then we take the modulus of the number by one thousand (in
2216 * order to keep the lowest digits) and add one thousand to that
2217 * (in order to ensure that 1001 is not treated the same as 1).
2219 guint plural_form = size < 1000 ? size : size % 1000 + 1000;
2221 /* Second problem: we need to translate the string "%u byte" and
2222 * "%u bytes" for pluralisation, but the correct number format to
2223 * use for a gsize is different depending on which architecture
2226 * Solution: format the number separately and use "%s bytes" on
2229 const gchar *translated_format;
2230 gchar *formatted_number;
2232 /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2233 translated_format = g_dngettext(GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
2234 /* XXX: Windows doesn't support the "'" format modifier, so we
2235 * must not use it there. Instead, just display the number
2236 * without separation. Bug #655336 is open until a solution is
2240 formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2242 formatted_number = g_strdup_printf ("%"G_GUINT64_FORMAT, size);
2245 g_string_append (string, " (");
2246 g_string_append_printf (string, translated_format, formatted_number);
2247 g_free (formatted_number);
2248 g_string_append (string, ")");
2251 return g_string_free (string, FALSE);
2254 #pragma GCC diagnostic pop
2257 * g_format_size_for_display:
2258 * @size: a size in bytes
2260 * Formats a size (for example the size of a file) into a human
2261 * readable string. Sizes are rounded to the nearest size prefix
2262 * (KB, MB, GB) and are displayed rounded to the nearest tenth.
2263 * E.g. the file size 3292528 bytes will be converted into the
2266 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2268 * This string should be freed with g_free() when not needed any longer.
2270 * Returns: a newly-allocated formatted string containing a human
2271 * readable file size
2275 * Deprecated:2.30: This function is broken due to its use of SI
2276 * suffixes to denote IEC units. Use g_format_size() instead.
2279 g_format_size_for_display (goffset size)
2281 if (size < (goffset) KIBIBYTE_FACTOR)
2282 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
2285 gdouble displayed_size;
2287 if (size < (goffset) MEBIBYTE_FACTOR)
2289 displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
2290 /* Translators: this is from the deprecated function g_format_size_for_display() which uses 'KB' to
2291 * mean 1024 bytes. I am aware that 'KB' is not correct, but it has been preserved for reasons of
2292 * compatibility. Users will not see this string unless a program is using this deprecated function.
2293 * Please translate as literally as possible.
2295 return g_strdup_printf (_("%.1f KB"), displayed_size);
2297 else if (size < (goffset) GIBIBYTE_FACTOR)
2299 displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
2300 return g_strdup_printf (_("%.1f MB"), displayed_size);
2302 else if (size < (goffset) TEBIBYTE_FACTOR)
2304 displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
2305 return g_strdup_printf (_("%.1f GB"), displayed_size);
2307 else if (size < (goffset) PEBIBYTE_FACTOR)
2309 displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
2310 return g_strdup_printf (_("%.1f TB"), displayed_size);
2312 else if (size < (goffset) EXBIBYTE_FACTOR)
2314 displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
2315 return g_strdup_printf (_("%.1f PB"), displayed_size);
2319 displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
2320 return g_strdup_printf (_("%.1f EB"), displayed_size);
2325 #if defined (G_OS_WIN32) && !defined (_WIN64)
2327 /* Binary compatibility versions. Not for newly compiled code. */
2329 _GLIB_EXTERN const gchar *g_get_user_name_utf8 (void);
2330 _GLIB_EXTERN const gchar *g_get_real_name_utf8 (void);
2331 _GLIB_EXTERN const gchar *g_get_home_dir_utf8 (void);
2332 _GLIB_EXTERN const gchar *g_get_tmp_dir_utf8 (void);
2333 _GLIB_EXTERN gchar *g_find_program_in_path_utf8 (const gchar *program);
2336 g_find_program_in_path_utf8 (const gchar *program)
2338 return g_find_program_in_path (program);
2341 const gchar *g_get_user_name_utf8 (void) { return g_get_user_name (); }
2342 const gchar *g_get_real_name_utf8 (void) { return g_get_real_name (); }
2343 const gchar *g_get_home_dir_utf8 (void) { return g_get_home_dir (); }
2344 const gchar *g_get_tmp_dir_utf8 (void) { return g_get_tmp_dir (); }
2350 * Returns %TRUE if the current process was executed as setuid (or an
2351 * equivalent __libc_enable_secure is available). See:
2352 * http://osdir.com/ml/linux.lfs.hardened/2007-04/msg00032.html
2355 g_check_setuid (void)
2357 /* TODO: get __libc_enable_secure exported from glibc.
2358 * See http://www.openwall.com/lists/owl-dev/2012/08/14/1
2360 #if 0 && defined(HAVE_LIBC_ENABLE_SECURE)
2362 /* See glibc/include/unistd.h */
2363 extern int __libc_enable_secure;
2364 return __libc_enable_secure;
2366 #elif defined(HAVE_ISSETUGID) && !defined(__BIONIC__)
2367 /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
2369 /* Android had it in older versions but the new 64 bit ABI does not
2370 * have it anymore, and some versions of the 32 bit ABI neither.
2371 * https://code.google.com/p/android-developer-preview/issues/detail?id=168
2373 return issetugid ();
2374 #elif defined(G_OS_UNIX)
2375 uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
2376 gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
2378 static gsize check_setuid_initialised;
2379 static gboolean is_setuid;
2381 if (g_once_init_enter (&check_setuid_initialised))
2383 #ifdef HAVE_GETRESUID
2384 /* These aren't in the header files, so we prototype them here.
2386 int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
2387 int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);
2389 if (getresuid (&ruid, &euid, &suid) != 0 ||
2390 getresgid (&rgid, &egid, &sgid) != 0)
2391 #endif /* HAVE_GETRESUID */
2393 suid = ruid = getuid ();
2394 sgid = rgid = getgid ();
2399 is_setuid = (ruid != euid || ruid != suid ||
2400 rgid != egid || rgid != sgid);
2402 g_once_init_leave (&check_setuid_initialised, 1);
2414 * A wrapper for the POSIX abort() function.
2416 * On Windows it is a function that makes extra effort (including a call
2417 * to abort()) to ensure that a debugger-catchable exception is thrown
2418 * before the program terminates.
2420 * See your C library manual for more details about abort().
2427 /* One call to break the debugger */
2429 /* One call in case CRT does get saner about abort() behaviour */
2431 /* And one call to bind them all and terminate the program for sure */