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, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
21 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
22 * file for a list of people on the GLib Team. See the ChangeLog
23 * files for a list of changes. These files are distributed with
24 * GLib at ftp://ftp.gtk.org/pub/gtk/.
28 * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
32 #include "glibconfig.h"
39 #include <ctype.h> /* For tolower() */
41 #include <sys/types.h>
47 #include <sys/types.h>
48 #ifdef HAVE_SYS_PARAM_H
49 #include <sys/param.h>
51 #ifdef HAVE_CRT_EXTERNS_H
52 #include <crt_externs.h> /* for _NSGetEnviron */
55 /* implement gutils's inline functions
57 #define G_IMPLEMENT_INLINES 1
61 #include "glib-init.h"
62 #include "glib-private.h"
64 #include "gfileutils.h"
68 #include "gtestutils.h"
70 #include "gstrfuncs.h"
74 #ifdef G_PLATFORM_WIN32
82 * @title: Miscellaneous Utility Functions
83 * @short_description: a selection of portable utility functions
85 * These are portable utility functions.
88 #ifdef G_PLATFORM_WIN32
90 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
91 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
92 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
94 # include <lmcons.h> /* For UNLEN */
95 #endif /* G_PLATFORM_WIN32 */
100 /* older SDK (e.g. msvc 5.0) does not have these*/
101 # ifndef CSIDL_MYMUSIC
102 # define CSIDL_MYMUSIC 13
104 # ifndef CSIDL_MYVIDEO
105 # define CSIDL_MYVIDEO 14
107 # ifndef CSIDL_INTERNET_CACHE
108 # define CSIDL_INTERNET_CACHE 32
110 # ifndef CSIDL_COMMON_APPDATA
111 # define CSIDL_COMMON_APPDATA 35
113 # ifndef CSIDL_MYPICTURES
114 # define CSIDL_MYPICTURES 0x27
116 # ifndef CSIDL_COMMON_DOCUMENTS
117 # define CSIDL_COMMON_DOCUMENTS 46
119 # ifndef CSIDL_PROFILE
120 # define CSIDL_PROFILE 40
122 # include <process.h>
126 #include <CoreServices/CoreServices.h>
130 #include <langinfo.h>
133 #ifdef G_PLATFORM_WIN32
136 _glib_get_dll_directory (void)
140 wchar_t wc_fn[MAX_PATH];
143 if (glib_dll == NULL)
147 /* This code is different from that in
148 * g_win32_get_package_installation_directory_of_module() in that
149 * here we return the actual folder where the GLib DLL is. We don't
150 * do the check for it being in a "bin" or "lib" subfolder and then
151 * returning the parent of that.
153 * In a statically built GLib, glib_dll will be NULL and we will
154 * thus look up the application's .exe file's location.
156 if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
159 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
161 p = strrchr (retval, G_DIR_SEPARATOR);
176 * @dest: the destination address to copy the bytes to.
177 * @src: the source address to copy the bytes from.
178 * @len: the number of bytes to copy.
180 * Copies a block of memory @len bytes long, from @src to @dest.
181 * The source and destination areas may overlap.
183 * Deprecated:2.40: Just use memmove().
192 * @func: (scope async): the function to call on normal program termination.
194 * Specifies a function to be called at normal program termination.
196 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
197 * macro that maps to a call to the atexit() function in the C
198 * library. This means that in case the code that calls g_atexit(),
199 * i.e. atexit(), is in a DLL, the function will be called when the
200 * DLL is detached from the program. This typically makes more sense
201 * than that the function is called when the GLib DLL is detached,
202 * which happened earlier when g_atexit() was a function in the GLib
205 * The behaviour of atexit() in the context of dynamically loaded
206 * modules is not formally specified and varies wildly.
208 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
209 * loaded module which is unloaded before the program terminates might
210 * well cause a crash at program exit.
212 * Some POSIX systems implement atexit() like Windows, and have each
213 * dynamically loaded module maintain an own atexit chain that is
214 * called when the module is unloaded.
216 * On other POSIX systems, before a dynamically loaded module is
217 * unloaded, the registered atexit functions (if any) residing in that
218 * module are called, regardless where the code that registered them
219 * resided. This is presumably the most robust approach.
221 * As can be seen from the above, for portability it's best to avoid
222 * calling g_atexit() (or atexit()) except in the main executable of a
225 * Deprecated:2.32: It is best to avoid g_atexit().
228 g_atexit (GVoidFunc func)
232 result = atexit ((void (*)(void)) func);
235 g_error ("Could not register atexit() function: %s",
240 /* Based on execvp() from GNU Libc.
241 * Some of this code is cut-and-pasted into gspawn.c
245 my_strchrnul (const gchar *str,
248 gchar *p = (gchar*)str;
249 while (*p && (*p != c))
257 static gchar *inner_find_program_in_path (const gchar *program);
260 g_find_program_in_path (const gchar *program)
262 const gchar *last_dot = strrchr (program, '.');
264 if (last_dot == NULL ||
265 strchr (last_dot, '\\') != NULL ||
266 strchr (last_dot, '/') != NULL)
268 const gint program_length = strlen (program);
269 gchar *pathext = g_build_path (";",
270 ".exe;.cmd;.bat;.com",
271 g_getenv ("PATHEXT"),
274 gchar *decorated_program;
280 gchar *q = my_strchrnul (p, ';');
282 decorated_program = g_malloc (program_length + (q-p) + 1);
283 memcpy (decorated_program, program, program_length);
284 memcpy (decorated_program+program_length, p, q-p);
285 decorated_program [program_length + (q-p)] = '\0';
287 retval = inner_find_program_in_path (decorated_program);
288 g_free (decorated_program);
296 } while (*p++ != '\0');
301 return inner_find_program_in_path (program);
307 * g_find_program_in_path:
308 * @program: a program name in the GLib file name encoding
310 * Locates the first executable named @program in the user's path, in the
311 * same way that execvp() would locate it. Returns an allocated string
312 * with the absolute path name, or %NULL if the program is not found in
313 * the path. If @program is already an absolute path, returns a copy of
314 * @program if @program exists and is executable, and %NULL otherwise.
316 * On Windows, if @program does not have a file type suffix, tries
317 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
318 * the <envar>PATHEXT</envar> environment variable.
320 * On Windows, it looks for the file in the same way as CreateProcess()
321 * would. This means first in the directory where the executing
322 * program was loaded from, then in the current directory, then in the
323 * Windows 32-bit system directory, then in the Windows directory, and
324 * finally in the directories in the <envar>PATH</envar> environment
325 * variable. If the program is found, the return value contains the
326 * full name including the type suffix.
328 * Return value: a newly-allocated string with the absolute path, or %NULL
332 inner_find_program_in_path (const gchar *program)
335 g_find_program_in_path (const gchar *program)
338 const gchar *path, *p;
339 gchar *name, *freeme;
341 const gchar *path_copy;
342 gchar *filename = NULL, *appdir = NULL;
343 gchar *sysdir = NULL, *windir = NULL;
345 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
351 g_return_val_if_fail (program != NULL, NULL);
353 /* If it is an absolute path, or a relative path including subdirectories,
354 * don't look in PATH.
356 if (g_path_is_absolute (program)
357 || strchr (program, G_DIR_SEPARATOR) != NULL
359 || strchr (program, '/') != NULL
363 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
364 !g_file_test (program, G_FILE_TEST_IS_DIR))
365 return g_strdup (program);
370 path = g_getenv ("PATH");
371 #if defined(G_OS_UNIX)
374 /* There is no 'PATH' in the environment. The default
375 * search path in GNU libc is the current directory followed by
376 * the path 'confstr' returns for '_CS_PATH'.
379 /* In GLib we put . last, for security, and don't use the
380 * unportable confstr(); UNIX98 does not actually specify
381 * what to search if PATH is unset. POSIX may, dunno.
384 path = "/bin:/usr/bin:.";
387 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
388 if (n > 0 && n < MAXPATHLEN)
389 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
391 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
392 if (n > 0 && n < MAXPATHLEN)
393 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
395 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
396 if (n > 0 && n < MAXPATHLEN)
397 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
401 appdir = g_path_get_dirname (filename);
405 path = g_strdup (path);
409 const gchar *tem = path;
410 path = g_strconcat (windir, ";", path, NULL);
411 g_free ((gchar *) tem);
417 const gchar *tem = path;
418 path = g_strconcat (sysdir, ";", path, NULL);
419 g_free ((gchar *) tem);
424 const gchar *tem = path;
425 path = g_strconcat (".;", path, NULL);
426 g_free ((gchar *) tem);
431 const gchar *tem = path;
432 path = g_strconcat (appdir, ";", path, NULL);
433 g_free ((gchar *) tem);
440 len = strlen (program) + 1;
441 pathlen = strlen (path);
442 freeme = name = g_malloc (pathlen + len + 1);
444 /* Copy the file name at the top, including '\0' */
445 memcpy (name + pathlen + 1, program, len);
446 name = name + pathlen;
447 /* And add the slash before the filename */
448 *name = G_DIR_SEPARATOR;
456 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
459 /* Two adjacent colons, or a colon at the beginning or the end
460 * of 'PATH' means to search the current directory.
464 startp = memcpy (name - (p - path), path, p - path);
466 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
467 !g_file_test (startp, G_FILE_TEST_IS_DIR))
470 ret = g_strdup (startp);
473 g_free ((gchar *) path_copy);
478 while (*p++ != '\0');
482 g_free ((gchar *) path_copy);
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
503 * @mask: a #gulong containing flags
504 * @nth_bit: the index of the bit to start the search from
506 * Find the position of the first bit set in @mask, searching
507 * from (but not including) @nth_bit downwards. Bits are numbered
508 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
509 * usually). To start searching from the last bit, set @nth_bit to
510 * -1 or GLIB_SIZEOF_LONG * 8.
512 * Returns: the index of the first bit set which is lower than @nth_bit
519 * Gets the number of bits used to hold @number,
520 * e.g. if @number is 4, 3 bits are needed.
522 * Returns: the number of bits used to hold @number
525 G_LOCK_DEFINE_STATIC (g_utils_global);
534 static gchar *g_user_data_dir = NULL;
535 static gchar **g_system_data_dirs = NULL;
536 static gchar *g_user_cache_dir = NULL;
537 static gchar *g_user_config_dir = NULL;
538 static gchar **g_system_config_dirs = NULL;
540 static gchar **g_user_special_dirs = NULL;
542 /* fifteen minutes of fame for everybody */
543 #define G_USER_DIRS_EXPIRE 15 * 60
548 get_special_folder (int csidl)
550 wchar_t path[MAX_PATH+1];
552 LPITEMIDLIST pidl = NULL;
554 gchar *retval = NULL;
556 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
559 b = SHGetPathFromIDListW (pidl, path);
561 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
562 CoTaskMemFree (pidl);
568 get_windows_directory_root (void)
570 wchar_t wwindowsdir[MAX_PATH];
572 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
574 /* Usually X:\Windows, but in terminal server environments
575 * might be an UNC path, AFAIK.
577 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
580 if (windowsdir == NULL)
581 return g_strdup ("C:\\");
583 p = (char *) g_path_skip_root (windowsdir);
584 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
590 return g_strdup ("C:\\");
595 /* HOLDS: g_utils_global_lock */
596 static UserDatabaseEntry *
597 g_get_user_database_entry (void)
599 static UserDatabaseEntry *entry;
601 if (g_once_init_enter (&entry))
603 static UserDatabaseEntry e;
607 struct passwd *pw = NULL;
608 gpointer buffer = NULL;
612 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
614 # ifdef _SC_GETPW_R_SIZE_MAX
615 /* This reurns the maximum length */
616 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
620 # else /* _SC_GETPW_R_SIZE_MAX */
622 # endif /* _SC_GETPW_R_SIZE_MAX */
624 logname = (gchar *) g_getenv ("LOGNAME");
629 /* we allocate 6 extra bytes to work around a bug in
630 * Mac OS < 10.3. See #156446
632 buffer = g_malloc (bufsize + 6);
635 # ifdef HAVE_POSIX_GETPWUID_R
637 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
638 if (!pw || (pw->pw_uid != getuid ())) {
639 /* LOGNAME is lying, fall back to looking up the uid */
640 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
643 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
645 error = error < 0 ? errno : error;
646 # else /* HAVE_NONPOSIX_GETPWUID_R */
648 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
649 pw = error == 0 ? &pwd : NULL;
652 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
653 if (!pw || (pw->pw_uid != getuid ())) {
654 /* LOGNAME is lying, fall back to looking up the uid */
655 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
658 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
660 error = pw ? 0 : errno;
662 # endif /* HAVE_NONPOSIX_GETPWUID_R */
666 /* we bail out prematurely if the user id can't be found
667 * (should be pretty rare case actually), or if the buffer
668 * should be sufficiently big and lookups are still not
671 if (error == 0 || error == ENOENT)
673 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
677 if (bufsize > 32 * 1024)
679 g_warning ("getpwuid_r(): failed due to: %s.",
688 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
692 pw = getpwuid (getuid ());
696 e.user_name = g_strdup (pw->pw_name);
699 if (pw->pw_gecos && *pw->pw_gecos != '\0')
701 gchar **gecos_fields;
704 /* split the gecos field and substitute '&' */
705 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
706 name_parts = g_strsplit (gecos_fields[0], "&", 0);
707 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
708 e.real_name = g_strjoinv (pw->pw_name, name_parts);
709 g_strfreev (gecos_fields);
710 g_strfreev (name_parts);
715 e.home_dir = g_strdup (pw->pw_dir);
720 #endif /* G_OS_UNIX */
725 wchar_t buffer[UNLEN+1];
727 if (GetUserNameW (buffer, (LPDWORD) &len))
729 e.user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
730 e.real_name = g_strdup (e.user_name);
733 #endif /* G_OS_WIN32 */
736 e.user_name = g_strdup ("somebody");
738 e.real_name = g_strdup ("Unknown");
740 g_once_init_leave (&entry, &e);
749 * Gets the user name of the current user. The encoding of the returned
750 * string is system-defined. On UNIX, it might be the preferred file name
751 * encoding, or something else, and there is no guarantee that it is even
752 * consistent on a machine. On Windows, it is always UTF-8.
754 * Returns: the user name of the current user.
757 g_get_user_name (void)
759 UserDatabaseEntry *entry;
761 entry = g_get_user_database_entry ();
763 return entry->user_name;
769 * Gets the real name of the user. This usually comes from the user's entry
770 * in the <filename>passwd</filename> file. The encoding of the returned
771 * string is system-defined. (On Windows, it is, however, always UTF-8.)
772 * If the real user name cannot be determined, the string "Unknown" is
775 * Returns: the user's real name.
778 g_get_real_name (void)
780 UserDatabaseEntry *entry;
782 entry = g_get_user_database_entry ();
784 return entry->real_name;
790 * Gets the current user's home directory.
792 * As with most UNIX tools, this function will return the value of the
793 * <envar>HOME</envar> environment variable if it is set to an existing
794 * absolute path name, falling back to the <filename>passwd</filename>
795 * file in the case that it is unset.
797 * If the path given in <envar>HOME</envar> is non-absolute, does not
798 * exist, or is not a directory, the result is undefined.
801 * Before version 2.36 this function would ignore the
802 * <envar>HOME</envar> environment variable, taking the value from the
803 * <filename>passwd</filename> database instead. This was changed to
804 * increase the compatibility of GLib with other programs (and the XDG
805 * basedir specification) and to increase testability of programs
806 * based on GLib (by making it easier to run them from test
809 * If your program has a strong requirement for either the new or the
810 * old behaviour (and if you don't wish to increase your GLib
811 * dependency to ensure that the new behaviour is in effect) then you
812 * should either directly check the <envar>HOME</envar> environment
813 * variable yourself or unset it before calling any functions in GLib.
816 * Returns: the current user's home directory
819 g_get_home_dir (void)
821 static gchar *home_dir;
823 if (g_once_init_enter (&home_dir))
827 /* We first check HOME and use it if it is set */
828 tmp = g_strdup (g_getenv ("HOME"));
831 /* Only believe HOME if it is an absolute path and exists.
833 * We only do this check on Windows for a couple of reasons.
834 * Historically, we only did it there because we used to ignore $HOME
835 * on UNIX. There are concerns about enabling it now on UNIX because
836 * of things like autofs. In short, if the user has a bogus value in
837 * $HOME then they get what they pay for...
841 if (!(g_path_is_absolute (tmp) &&
842 g_file_test (tmp, G_FILE_TEST_IS_DIR)))
849 /* In case HOME is Unix-style (it happens), convert it to
855 while ((p = strchr (tmp, '/')) != NULL)
861 /* USERPROFILE is probably the closest equivalent to $HOME? */
862 if (g_getenv ("USERPROFILE") != NULL)
863 tmp = g_strdup (g_getenv ("USERPROFILE"));
867 tmp = get_special_folder (CSIDL_PROFILE);
870 tmp = get_windows_directory_root ();
871 #endif /* G_OS_WIN32 */
875 /* If we didn't get it from any of those methods, we will have
876 * to read the user database entry.
878 UserDatabaseEntry *entry;
880 entry = g_get_user_database_entry ();
882 /* Strictly speaking, we should copy this, but we know that
883 * neither will ever be freed, so don't bother...
885 tmp = entry->home_dir;
888 g_once_init_leave (&home_dir, tmp);
897 * Gets the directory to use for temporary files.
899 * On UNIX, this is taken from the <envar>TMPDIR</envar> environment
900 * variable. If the variable is not set, <literal>P_tmpdir</literal> is
901 * used, as defined by the system C library. Failing that, a hard-coded
902 * default of "/tmp" is returned.
904 * On Windows, the <envar>TEMP</envar> environment variable is used,
905 * with the root directory of the Windows installation (eg: "C:\") used
908 * The encoding of the returned string is system-defined. On Windows, it
909 * is always UTF-8. The return value is never %NULL or the empty string.
911 * Returns: the directory to use for temporary files.
916 static gchar *tmp_dir;
918 if (g_once_init_enter (&tmp_dir))
923 tmp = g_strdup (g_getenv ("TEMP"));
925 if (tmp == NULL || *tmp == '\0')
928 tmp = get_windows_directory_root ();
930 #else /* G_OS_WIN32 */
931 tmp = g_strdup (g_getenv ("TMPDIR"));
934 if (tmp == NULL || *tmp == '\0')
938 tmp = g_strdup (P_tmpdir);
940 if (k > 1 && G_IS_DIR_SEPARATOR (tmp[k - 1]))
943 #endif /* P_tmpdir */
945 if (tmp == NULL || *tmp == '\0')
948 tmp = g_strdup ("/tmp");
950 #endif /* !G_OS_WIN32 */
952 g_once_init_leave (&tmp_dir, tmp);
961 * Return a name for the machine.
963 * The returned name is not necessarily a fully-qualified domain name,
964 * or even present in DNS or some other name service at all. It need
965 * not even be unique on your local network or site, but usually it
966 * is. Callers should not rely on the return value having any specific
967 * properties like uniqueness for security purposes. Even if the name
968 * of the machine is changed while an application is running, the
969 * return value from this function does not change. The returned
970 * string is owned by GLib and should not be modified or freed. If no
971 * name can be determined, a default fixed string "localhost" is
974 * Returns: the host name of the machine.
979 g_get_host_name (void)
981 static gchar *hostname;
983 if (g_once_init_enter (&hostname))
989 failed = (gethostname (tmp, sizeof (tmp)) == -1);
991 DWORD size = sizeof (tmp);
992 failed = (!GetComputerName (tmp, &size));
995 g_once_init_leave (&hostname, g_strdup (failed ? "localhost" : tmp));
1001 G_LOCK_DEFINE_STATIC (g_prgname);
1002 static gchar *g_prgname = NULL;
1007 * Gets the name of the program. This name should <emphasis>not</emphasis>
1008 * be localized, contrast with g_get_application_name().
1009 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1010 * which is called by gtk_init(). The program name is found by taking
1011 * the last component of <literal>argv[0]</literal>.)
1013 * Returns: the name of the program. The returned string belongs
1014 * to GLib and must not be modified or freed.
1017 g_get_prgname (void)
1023 if (g_prgname == NULL)
1025 static gboolean beenhere = FALSE;
1029 gchar *utf8_buf = NULL;
1030 wchar_t buf[MAX_PATH+1];
1033 if (GetModuleFileNameW (GetModuleHandle (NULL),
1034 buf, G_N_ELEMENTS (buf)) > 0)
1035 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1039 g_prgname = g_path_get_basename (utf8_buf);
1046 G_UNLOCK (g_prgname);
1053 * @prgname: the name of the program.
1055 * Sets the name of the program. This name should <emphasis>not</emphasis>
1056 * be localized, contrast with g_set_application_name(). Note that for
1057 * thread-safety reasons this function can only be called once.
1060 g_set_prgname (const gchar *prgname)
1064 g_prgname = g_strdup (prgname);
1065 G_UNLOCK (g_prgname);
1068 G_LOCK_DEFINE_STATIC (g_application_name);
1069 static gchar *g_application_name = NULL;
1072 * g_get_application_name:
1074 * Gets a human-readable name for the application, as set by
1075 * g_set_application_name(). This name should be localized if
1076 * possible, and is intended for display to the user. Contrast with
1077 * g_get_prgname(), which gets a non-localized name. If
1078 * g_set_application_name() has not been called, returns the result of
1079 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1082 * Return value: human-readable application name. may return %NULL
1087 g_get_application_name (void)
1091 G_LOCK (g_application_name);
1092 retval = g_application_name;
1093 G_UNLOCK (g_application_name);
1096 return g_get_prgname ();
1102 * g_set_application_name:
1103 * @application_name: localized name of the application
1105 * Sets a human-readable name for the application. This name should be
1106 * localized if possible, and is intended for display to the user.
1107 * Contrast with g_set_prgname(), which sets a non-localized name.
1108 * g_set_prgname() will be called automatically by gtk_init(),
1109 * but g_set_application_name() will not.
1111 * Note that for thread safety reasons, this function can only
1114 * The application name will be used in contexts such as error messages,
1115 * or when displaying an application's name in the task list.
1120 g_set_application_name (const gchar *application_name)
1122 gboolean already_set = FALSE;
1124 G_LOCK (g_application_name);
1125 if (g_application_name)
1128 g_application_name = g_strdup (application_name);
1129 G_UNLOCK (g_application_name);
1132 g_warning ("g_set_application_name() called multiple times");
1136 * g_get_user_data_dir:
1138 * Returns a base directory in which to access application data such
1139 * as icons that is customized for a particular user.
1141 * On UNIX platforms this is determined using the mechanisms described in
1142 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1143 * XDG Base Directory Specification</ulink>.
1144 * In this case the directory retrieved will be XDG_DATA_HOME.
1146 * On Windows this is the folder to use for local (as opposed to
1147 * roaming) application data. See documentation for
1148 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1149 * what g_get_user_config_dir() returns.
1151 * Return value: a string owned by GLib that must not be modified
1156 g_get_user_data_dir (void)
1160 G_LOCK (g_utils_global);
1162 if (!g_user_data_dir)
1165 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1167 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1169 if (data_dir && data_dir[0])
1170 data_dir = g_strdup (data_dir);
1172 if (!data_dir || !data_dir[0])
1174 const gchar *home_dir = g_get_home_dir ();
1177 data_dir = g_build_filename (home_dir, ".local", "share", NULL);
1179 data_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".local", "share", NULL);
1182 g_user_data_dir = data_dir;
1185 data_dir = g_user_data_dir;
1187 G_UNLOCK (g_utils_global);
1193 g_init_user_config_dir (void)
1197 if (!g_user_config_dir)
1200 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1202 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1204 if (config_dir && config_dir[0])
1205 config_dir = g_strdup (config_dir);
1207 if (!config_dir || !config_dir[0])
1209 const gchar *home_dir = g_get_home_dir ();
1212 config_dir = g_build_filename (home_dir, ".config", NULL);
1214 config_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".config", NULL);
1217 g_user_config_dir = config_dir;
1222 * g_get_user_config_dir:
1224 * Returns a base directory in which to store user-specific application
1225 * configuration information such as user preferences and settings.
1227 * On UNIX platforms this is determined using the mechanisms described in
1228 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1229 * XDG Base Directory Specification</ulink>.
1230 * In this case the directory retrieved will be XDG_CONFIG_HOME.
1232 * On Windows this is the folder to use for local (as opposed to
1233 * roaming) application data. See documentation for
1234 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1235 * what g_get_user_data_dir() returns.
1237 * Return value: a string owned by GLib that must not be modified
1242 g_get_user_config_dir (void)
1244 G_LOCK (g_utils_global);
1246 g_init_user_config_dir ();
1248 G_UNLOCK (g_utils_global);
1250 return g_user_config_dir;
1254 * g_get_user_cache_dir:
1256 * Returns a base directory in which to store non-essential, cached
1257 * data specific to particular user.
1259 * On UNIX platforms this is determined using the mechanisms described in
1260 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1261 * XDG Base Directory Specification</ulink>.
1262 * In this case the directory retrieved will be XDG_CACHE_HOME.
1264 * On Windows is the directory that serves as a common repository for
1265 * temporary Internet files. A typical path is
1266 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
1267 * See documentation for CSIDL_INTERNET_CACHE.
1269 * Return value: a string owned by GLib that must not be modified
1274 g_get_user_cache_dir (void)
1278 G_LOCK (g_utils_global);
1280 if (!g_user_cache_dir)
1283 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1285 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1287 if (cache_dir && cache_dir[0])
1288 cache_dir = g_strdup (cache_dir);
1290 if (!cache_dir || !cache_dir[0])
1292 const gchar *home_dir = g_get_home_dir ();
1295 cache_dir = g_build_filename (home_dir, ".cache", NULL);
1297 cache_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".cache", NULL);
1299 g_user_cache_dir = cache_dir;
1302 cache_dir = g_user_cache_dir;
1304 G_UNLOCK (g_utils_global);
1310 * g_get_user_runtime_dir:
1312 * Returns a directory that is unique to the current user on the local
1315 * On UNIX platforms this is determined using the mechanisms described in
1316 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1317 * XDG Base Directory Specification</ulink>. This is the directory
1318 * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
1319 * In the case that this variable is not set, GLib will issue a warning
1320 * message to stderr and return the value of g_get_user_cache_dir().
1322 * On Windows this is the folder to use for local (as opposed to
1323 * roaming) application data. See documentation for
1324 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1325 * what g_get_user_config_dir() returns.
1327 * Returns: a string owned by GLib that must not be modified or freed.
1332 g_get_user_runtime_dir (void)
1335 static const gchar *runtime_dir;
1336 static gsize initialised;
1338 if (g_once_init_enter (&initialised))
1340 runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
1342 g_once_init_leave (&initialised, 1);
1348 /* Both fallback for UNIX and the default
1349 * in Windows: use the user cache directory.
1353 return g_get_user_cache_dir ();
1359 find_folder (OSType type)
1361 gchar *filename = NULL;
1364 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
1366 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
1370 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
1374 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
1378 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
1380 CFStringGetCString (path, filename,
1381 CFStringGetLength (path) * 3 + 1,
1382 kCFStringEncodingUTF8);
1396 load_user_special_dirs (void)
1398 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
1399 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
1400 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
1401 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
1402 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
1403 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
1404 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
1405 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
1408 #endif /* HAVE_CARBON */
1410 #if defined(G_OS_WIN32)
1412 load_user_special_dirs (void)
1414 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1418 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
1420 static const GUID FOLDERID_Downloads =
1421 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1422 static const GUID FOLDERID_Public =
1423 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1427 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
1428 "SHGetKnownFolderPath");
1430 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1431 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
1433 if (p_SHGetKnownFolderPath == NULL)
1435 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1440 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1443 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1444 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
1445 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1446 CoTaskMemFree (wcp);
1449 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1452 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
1453 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
1455 if (p_SHGetKnownFolderPath == NULL)
1458 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1463 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
1466 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1467 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
1468 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1469 CoTaskMemFree (wcp);
1472 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1475 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
1476 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
1478 #endif /* G_OS_WIN32 */
1481 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
1483 /* adapted from xdg-user-dir-lookup.c
1485 * Copyright (C) 2007 Red Hat Inc.
1487 * Permission is hereby granted, free of charge, to any person
1488 * obtaining a copy of this software and associated documentation files
1489 * (the "Software"), to deal in the Software without restriction,
1490 * including without limitation the rights to use, copy, modify, merge,
1491 * publish, distribute, sublicense, and/or sell copies of the Software,
1492 * and to permit persons to whom the Software is furnished to do so,
1493 * subject to the following conditions:
1495 * The above copyright notice and this permission notice shall be
1496 * included in all copies or substantial portions of the Software.
1498 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1499 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1500 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1501 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1502 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1503 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1504 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1508 load_user_special_dirs (void)
1515 g_init_user_config_dir ();
1516 config_file = g_build_filename (g_user_config_dir,
1520 if (!g_file_get_contents (config_file, &data, NULL, NULL))
1522 g_free (config_file);
1526 lines = g_strsplit (data, "\n", -1);
1527 n_lines = g_strv_length (lines);
1530 for (i = 0; i < n_lines; i++)
1532 gchar *buffer = lines[i];
1535 gboolean is_relative = FALSE;
1536 GUserDirectory directory;
1538 /* Remove newline at end */
1539 len = strlen (buffer);
1540 if (len > 0 && buffer[len - 1] == '\n')
1541 buffer[len - 1] = 0;
1544 while (*p == ' ' || *p == '\t')
1547 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
1549 directory = G_USER_DIRECTORY_DESKTOP;
1550 p += strlen ("XDG_DESKTOP_DIR");
1552 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
1554 directory = G_USER_DIRECTORY_DOCUMENTS;
1555 p += strlen ("XDG_DOCUMENTS_DIR");
1557 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
1559 directory = G_USER_DIRECTORY_DOWNLOAD;
1560 p += strlen ("XDG_DOWNLOAD_DIR");
1562 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
1564 directory = G_USER_DIRECTORY_MUSIC;
1565 p += strlen ("XDG_MUSIC_DIR");
1567 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
1569 directory = G_USER_DIRECTORY_PICTURES;
1570 p += strlen ("XDG_PICTURES_DIR");
1572 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
1574 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
1575 p += strlen ("XDG_PUBLICSHARE_DIR");
1577 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
1579 directory = G_USER_DIRECTORY_TEMPLATES;
1580 p += strlen ("XDG_TEMPLATES_DIR");
1582 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
1584 directory = G_USER_DIRECTORY_VIDEOS;
1585 p += strlen ("XDG_VIDEOS_DIR");
1590 while (*p == ' ' || *p == '\t')
1597 while (*p == ' ' || *p == '\t')
1604 if (strncmp (p, "$HOME", 5) == 0)
1612 d = strrchr (p, '"');
1619 /* remove trailing slashes */
1621 if (d[len - 1] == '/')
1626 g_user_special_dirs[directory] = g_build_filename (g_get_home_dir (), d, NULL);
1629 g_user_special_dirs[directory] = g_strdup (d);
1633 g_free (config_file);
1636 #endif /* G_OS_UNIX && !HAVE_CARBON */
1640 * g_reload_user_special_dirs_cache:
1642 * Resets the cache used for g_get_user_special_dir(), so
1643 * that the latest on-disk version is used. Call this only
1644 * if you just changed the data on disk yourself.
1646 * Due to threadsafety issues this may cause leaking of strings
1647 * that were previously returned from g_get_user_special_dir()
1648 * that can't be freed. We ensure to only leak the data for
1649 * the directories that actually changed value though.
1654 g_reload_user_special_dirs_cache (void)
1658 G_LOCK (g_utils_global);
1660 if (g_user_special_dirs != NULL)
1662 /* save a copy of the pointer, to check if some memory can be preserved */
1663 char **old_g_user_special_dirs = g_user_special_dirs;
1666 /* recreate and reload our cache */
1667 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1668 load_user_special_dirs ();
1670 /* only leak changed directories */
1671 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
1673 old_val = old_g_user_special_dirs[i];
1674 if (g_user_special_dirs[i] == NULL)
1676 g_user_special_dirs[i] = old_val;
1678 else if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
1681 g_free (g_user_special_dirs[i]);
1682 g_user_special_dirs[i] = old_val;
1688 /* free the old array */
1689 g_free (old_g_user_special_dirs);
1692 G_UNLOCK (g_utils_global);
1696 * g_get_user_special_dir:
1697 * @directory: the logical id of special directory
1699 * Returns the full path of a special directory using its logical id.
1701 * On Unix this is done using the XDG special user directories.
1702 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
1703 * falls back to <filename>$HOME/Desktop</filename> when XDG special
1704 * user directories have not been set up.
1706 * Depending on the platform, the user might be able to change the path
1707 * of the special directory without requiring the session to restart; GLib
1708 * will not reflect any change once the special directories are loaded.
1710 * Return value: the path to the specified special directory, or %NULL
1711 * if the logical id was not found. The returned string is owned by
1712 * GLib and should not be modified or freed.
1717 g_get_user_special_dir (GUserDirectory directory)
1719 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
1720 directory < G_USER_N_DIRECTORIES, NULL);
1722 G_LOCK (g_utils_global);
1724 if (G_UNLIKELY (g_user_special_dirs == NULL))
1726 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1728 load_user_special_dirs ();
1730 /* Special-case desktop for historical compatibility */
1731 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
1732 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = g_build_filename (g_get_home_dir (), "Desktop", NULL);
1735 G_UNLOCK (g_utils_global);
1737 return g_user_special_dirs[directory];
1742 #undef g_get_system_data_dirs
1745 get_module_for_address (gconstpointer address)
1747 /* Holds the g_utils_global lock */
1749 static gboolean beenhere = FALSE;
1750 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
1751 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
1752 HMODULE hmodule = NULL;
1759 p_GetModuleHandleExA =
1760 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1761 "GetModuleHandleExA");
1765 if (p_GetModuleHandleExA == NULL ||
1766 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
1767 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
1770 MEMORY_BASIC_INFORMATION mbi;
1771 VirtualQuery (address, &mbi, sizeof (mbi));
1772 hmodule = (HMODULE) mbi.AllocationBase;
1779 get_module_share_dir (gconstpointer address)
1785 hmodule = get_module_for_address (address);
1786 if (hmodule == NULL)
1789 filename = g_win32_get_package_installation_directory_of_module (hmodule);
1790 retval = g_build_filename (filename, "share", NULL);
1796 const gchar * const *
1797 g_win32_get_system_data_dirs_for_module (void (*address_of_function)(void))
1801 static GHashTable *per_module_data_dirs = NULL;
1806 if (address_of_function)
1808 G_LOCK (g_utils_global);
1809 hmodule = get_module_for_address (address_of_function);
1810 if (hmodule != NULL)
1812 if (per_module_data_dirs == NULL)
1813 per_module_data_dirs = g_hash_table_new (NULL, NULL);
1816 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
1820 G_UNLOCK (g_utils_global);
1821 return (const gchar * const *) retval;
1827 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
1829 /* Documents and Settings\All Users\Application Data */
1830 p = get_special_folder (CSIDL_COMMON_APPDATA);
1832 g_array_append_val (data_dirs, p);
1834 /* Documents and Settings\All Users\Documents */
1835 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1837 g_array_append_val (data_dirs, p);
1839 /* Using the above subfolders of Documents and Settings perhaps
1840 * makes sense from a Windows perspective.
1842 * But looking at the actual use cases of this function in GTK+
1843 * and GNOME software, what we really want is the "share"
1844 * subdirectory of the installation directory for the package
1845 * our caller is a part of.
1847 * The address_of_function parameter, if non-NULL, points to a
1848 * function in the calling module. Use that to determine that
1849 * module's installation folder, and use its "share" subfolder.
1851 * Additionally, also use the "share" subfolder of the installation
1852 * locations of GLib and the .exe file being run.
1854 * To guard against none of the above being what is really wanted,
1855 * callers of this function should have Win32-specific code to look
1856 * up their installation folder themselves, and handle a subfolder
1857 * "share" of it in the same way as the folders returned from this
1861 p = get_module_share_dir (address_of_function);
1863 g_array_append_val (data_dirs, p);
1865 if (glib_dll != NULL)
1867 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
1868 p = g_build_filename (glib_root, "share", NULL);
1870 g_array_append_val (data_dirs, p);
1874 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
1875 p = g_build_filename (exe_root, "share", NULL);
1877 g_array_append_val (data_dirs, p);
1880 retval = (gchar **) g_array_free (data_dirs, FALSE);
1882 if (address_of_function)
1884 if (hmodule != NULL)
1885 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
1886 G_UNLOCK (g_utils_global);
1889 return (const gchar * const *) retval;
1895 * g_get_system_data_dirs:
1897 * Returns an ordered list of base directories in which to access
1898 * system-wide application data.
1900 * On UNIX platforms this is determined using the mechanisms described in
1901 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1902 * XDG Base Directory Specification</ulink>
1903 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
1905 * On Windows the first elements in the list are the Application Data
1906 * and Documents folders for All Users. (These can be determined only
1907 * on Windows 2000 or later and are not present in the list on other
1908 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
1909 * CSIDL_COMMON_DOCUMENTS.
1911 * Then follows the "share" subfolder in the installation folder for
1912 * the package containing the DLL that calls this function, if it can
1915 * Finally the list contains the "share" subfolder in the installation
1916 * folder for GLib, and in the installation folder for the package the
1917 * application's .exe file belongs to.
1919 * The installation folders above are determined by looking up the
1920 * folder where the module (DLL or EXE) in question is located. If the
1921 * folder's name is "bin", its parent is used, otherwise the folder
1924 * Note that on Windows the returned list can vary depending on where
1925 * this function is called.
1927 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
1928 * not be modified or freed.
1931 const gchar * const *
1932 g_get_system_data_dirs (void)
1934 gchar **data_dir_vector;
1936 G_LOCK (g_utils_global);
1938 if (!g_system_data_dirs)
1941 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
1943 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
1945 if (!data_dirs || !data_dirs[0])
1946 data_dirs = "/usr/local/share/:/usr/share/";
1948 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1951 g_system_data_dirs = data_dir_vector;
1954 data_dir_vector = g_system_data_dirs;
1956 G_UNLOCK (g_utils_global);
1958 return (const gchar * const *) data_dir_vector;
1962 * g_get_system_config_dirs:
1964 * Returns an ordered list of base directories in which to access
1965 * system-wide configuration information.
1967 * On UNIX platforms this is determined using the mechanisms described in
1968 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1969 * XDG Base Directory Specification</ulink>.
1970 * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
1972 * On Windows is the directory that contains application data for all users.
1973 * A typical path is C:\Documents and Settings\All Users\Application Data.
1974 * This folder is used for application data that is not user specific.
1975 * For example, an application can store a spell-check dictionary, a database
1976 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
1977 * This information will not roam and is available to anyone using the computer.
1979 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
1980 * not be modified or freed.
1983 const gchar * const *
1984 g_get_system_config_dirs (void)
1986 gchar *conf_dirs, **conf_dir_vector;
1988 G_LOCK (g_utils_global);
1990 if (!g_system_config_dirs)
1993 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
1996 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2001 /* Return empty list */
2002 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2005 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2007 if (!conf_dirs || !conf_dirs[0])
2008 conf_dirs = "/etc/xdg";
2010 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2013 g_system_config_dirs = conf_dir_vector;
2016 conf_dir_vector = g_system_config_dirs;
2017 G_UNLOCK (g_utils_global);
2019 return (const gchar * const *) conf_dir_vector;
2023 * g_nullify_pointer:
2024 * @nullify_location: the memory address of the pointer.
2026 * Set the pointer at the specified location to %NULL.
2029 g_nullify_pointer (gpointer *nullify_location)
2031 g_return_if_fail (nullify_location != NULL);
2033 *nullify_location = NULL;
2036 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2037 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2038 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2039 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2040 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2041 #define EXABYTE_FACTOR (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2043 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2044 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2045 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2046 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2047 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2048 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2052 * @size: a size in bytes
2054 * Formats a size (for example the size of a file) into a human readable
2055 * string. Sizes are rounded to the nearest size prefix (kB, MB, GB)
2056 * and are displayed rounded to the nearest tenth. E.g. the file size
2057 * 3292528 bytes will be converted into the string "3.2 MB".
2059 * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2061 * This string should be freed with g_free() when not needed any longer.
2063 * See g_format_size_full() for more options about how the size might be
2066 * Returns: a newly-allocated formatted string containing a human readable
2072 g_format_size (guint64 size)
2074 return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2079 * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2080 * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2081 * of the returned string. For example, "45.6 kB (45,612 bytes)".
2082 * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2083 * suffixes. IEC units should only be used for reporting things with
2084 * a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2085 * Network and storage sizes should be reported in the normal SI units.
2087 * Flags to modify the format of the string returned by g_format_size_full().
2090 #pragma GCC diagnostic push
2091 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
2094 * g_format_size_full:
2095 * @size: a size in bytes
2096 * @flags: #GFormatSizeFlags to modify the output
2100 * This function is similar to g_format_size() but allows for flags
2101 * that modify the output. See #GFormatSizeFlags.
2103 * Returns: a newly-allocated formatted string containing a human
2104 * readable file size
2109 g_format_size_full (guint64 size,
2110 GFormatSizeFlags flags)
2114 string = g_string_new (NULL);
2116 if (flags & G_FORMAT_SIZE_IEC_UNITS)
2118 if (size < KIBIBYTE_FACTOR)
2120 g_string_printf (string,
2121 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2123 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2126 else if (size < MEBIBYTE_FACTOR)
2127 g_string_printf (string, _("%.1f KiB"), (gdouble) size / (gdouble) KIBIBYTE_FACTOR);
2128 else if (size < GIBIBYTE_FACTOR)
2129 g_string_printf (string, _("%.1f MiB"), (gdouble) size / (gdouble) MEBIBYTE_FACTOR);
2131 else if (size < TEBIBYTE_FACTOR)
2132 g_string_printf (string, _("%.1f GiB"), (gdouble) size / (gdouble) GIBIBYTE_FACTOR);
2134 else if (size < PEBIBYTE_FACTOR)
2135 g_string_printf (string, _("%.1f TiB"), (gdouble) size / (gdouble) TEBIBYTE_FACTOR);
2137 else if (size < EXBIBYTE_FACTOR)
2138 g_string_printf (string, _("%.1f PiB"), (gdouble) size / (gdouble) PEBIBYTE_FACTOR);
2141 g_string_printf (string, _("%.1f EiB"), (gdouble) size / (gdouble) EXBIBYTE_FACTOR);
2145 if (size < KILOBYTE_FACTOR)
2147 g_string_printf (string,
2148 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2150 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2153 else if (size < MEGABYTE_FACTOR)
2154 g_string_printf (string, _("%.1f kB"), (gdouble) size / (gdouble) KILOBYTE_FACTOR);
2156 else if (size < GIGABYTE_FACTOR)
2157 g_string_printf (string, _("%.1f MB"), (gdouble) size / (gdouble) MEGABYTE_FACTOR);
2159 else if (size < TERABYTE_FACTOR)
2160 g_string_printf (string, _("%.1f GB"), (gdouble) size / (gdouble) GIGABYTE_FACTOR);
2161 else if (size < PETABYTE_FACTOR)
2162 g_string_printf (string, _("%.1f TB"), (gdouble) size / (gdouble) TERABYTE_FACTOR);
2164 else if (size < EXABYTE_FACTOR)
2165 g_string_printf (string, _("%.1f PB"), (gdouble) size / (gdouble) PETABYTE_FACTOR);
2168 g_string_printf (string, _("%.1f EB"), (gdouble) size / (gdouble) EXABYTE_FACTOR);
2171 if (flags & G_FORMAT_SIZE_LONG_FORMAT)
2173 /* First problem: we need to use the number of bytes to decide on
2174 * the plural form that is used for display, but the number of
2175 * bytes potentially exceeds the size of a guint (which is what
2176 * ngettext() takes).
2178 * From a pragmatic standpoint, it seems that all known languages
2179 * base plural forms on one or both of the following:
2181 * - the lowest digits of the number
2183 * - if the number if greater than some small value
2185 * Here's how we fake it: Draw an arbitrary line at one thousand.
2186 * If the number is below that, then fine. If it is above it,
2187 * then we take the modulus of the number by one thousand (in
2188 * order to keep the lowest digits) and add one thousand to that
2189 * (in order to ensure that 1001 is not treated the same as 1).
2191 guint plural_form = size < 1000 ? size : size % 1000 + 1000;
2193 /* Second problem: we need to translate the string "%u byte" and
2194 * "%u bytes" for pluralisation, but the correct number format to
2195 * use for a gsize is different depending on which architecture
2198 * Solution: format the number separately and use "%s bytes" on
2201 const gchar *translated_format;
2202 gchar *formatted_number;
2204 /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2205 translated_format = g_dngettext(GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
2206 /* XXX: Windows doesn't support the "'" format modifier, so we
2207 * must not use it there. Instead, just display the number
2208 * without separation. Bug #655336 is open until a solution is
2212 formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2214 formatted_number = g_strdup_printf ("%"G_GUINT64_FORMAT, size);
2217 g_string_append (string, " (");
2218 g_string_append_printf (string, translated_format, formatted_number);
2219 g_free (formatted_number);
2220 g_string_append (string, ")");
2223 return g_string_free (string, FALSE);
2226 #pragma GCC diagnostic pop
2229 * g_format_size_for_display:
2230 * @size: a size in bytes
2232 * Formats a size (for example the size of a file) into a human
2233 * readable string. Sizes are rounded to the nearest size prefix
2234 * (KB, MB, GB) and are displayed rounded to the nearest tenth.
2235 * E.g. the file size 3292528 bytes will be converted into the
2238 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2240 * This string should be freed with g_free() when not needed any longer.
2242 * Returns: a newly-allocated formatted string containing a human
2243 * readable file size
2247 * Deprecated:2.30: This function is broken due to its use of SI
2248 * suffixes to denote IEC units. Use g_format_size() instead.
2251 g_format_size_for_display (goffset size)
2253 if (size < (goffset) KIBIBYTE_FACTOR)
2254 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
2257 gdouble displayed_size;
2259 if (size < (goffset) MEBIBYTE_FACTOR)
2261 displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
2262 /* Translators: this is from the deprecated function g_format_size_for_display() which uses 'KB' to
2263 * mean 1024 bytes. I am aware that 'KB' is not correct, but it has been preserved for reasons of
2264 * compatibility. Users will not see this string unless a program is using this deprecated function.
2265 * Please translate as literally as possible.
2267 return g_strdup_printf (_("%.1f KB"), displayed_size);
2269 else if (size < (goffset) GIBIBYTE_FACTOR)
2271 displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
2272 return g_strdup_printf (_("%.1f MB"), displayed_size);
2274 else if (size < (goffset) TEBIBYTE_FACTOR)
2276 displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
2277 return g_strdup_printf (_("%.1f GB"), displayed_size);
2279 else if (size < (goffset) PEBIBYTE_FACTOR)
2281 displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
2282 return g_strdup_printf (_("%.1f TB"), displayed_size);
2284 else if (size < (goffset) EXBIBYTE_FACTOR)
2286 displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
2287 return g_strdup_printf (_("%.1f PB"), displayed_size);
2291 displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
2292 return g_strdup_printf (_("%.1f EB"), displayed_size);
2297 #if defined (G_OS_WIN32) && !defined (_WIN64)
2299 /* Binary compatibility versions. Not for newly compiled code. */
2301 _GLIB_EXTERN const gchar *g_get_user_name_utf8 (void);
2302 _GLIB_EXTERN const gchar *g_get_real_name_utf8 (void);
2303 _GLIB_EXTERN const gchar *g_get_home_dir_utf8 (void);
2304 _GLIB_EXTERN const gchar *g_get_tmp_dir_utf8 (void);
2305 _GLIB_EXTERN gchar *g_find_program_in_path_utf8 (const gchar *program);
2308 g_find_program_in_path_utf8 (const gchar *program)
2310 return g_find_program_in_path (program);
2313 const gchar *g_get_user_name_utf8 (void) { return g_get_user_name (); }
2314 const gchar *g_get_real_name_utf8 (void) { return g_get_real_name (); }
2315 const gchar *g_get_home_dir_utf8 (void) { return g_get_home_dir (); }
2316 const gchar *g_get_tmp_dir_utf8 (void) { return g_get_tmp_dir (); }
2322 * Returns %TRUE if the current process was executed as setuid (or an
2323 * equivalent __libc_enable_secure is available). See:
2324 * http://osdir.com/ml/linux.lfs.hardened/2007-04/msg00032.html
2327 g_check_setuid (void)
2329 /* TODO: get __libc_enable_secure exported from glibc.
2330 * See http://www.openwall.com/lists/owl-dev/2012/08/14/1
2332 #if 0 && defined(HAVE_LIBC_ENABLE_SECURE)
2334 /* See glibc/include/unistd.h */
2335 extern int __libc_enable_secure;
2336 return __libc_enable_secure;
2338 #elif defined(HAVE_ISSETUGID)
2339 /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
2340 return issetugid ();
2341 #elif defined(G_OS_UNIX)
2342 uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
2343 gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
2345 static gsize check_setuid_initialised;
2346 static gboolean is_setuid;
2348 if (g_once_init_enter (&check_setuid_initialised))
2350 #ifdef HAVE_GETRESUID
2351 /* These aren't in the header files, so we prototype them here.
2353 int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
2354 int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);
2356 if (getresuid (&ruid, &euid, &suid) != 0 ||
2357 getresgid (&rgid, &egid, &sgid) != 0)
2358 #endif /* HAVE_GETRESUID */
2360 suid = ruid = getuid ();
2361 sgid = rgid = getgid ();
2366 is_setuid = (ruid != euid || ruid != suid ||
2367 rgid != egid || rgid != sgid);
2369 g_once_init_leave (&check_setuid_initialised, 1);