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"
42 #include <ctype.h> /* For tolower() */
44 #include <sys/types.h>
49 #include <sys/types.h>
50 #ifdef HAVE_SYS_PARAM_H
51 #include <sys/param.h>
53 #ifdef HAVE_CRT_EXTERNS_H
54 #include <crt_externs.h> /* for _NSGetEnviron */
57 /* implement gutils's inline functions
59 #define G_IMPLEMENT_INLINES 1
63 #include "glib-init.h"
64 #include "glib-private.h"
66 #include "gfileutils.h"
70 #include "gtestutils.h"
72 #include "gstrfuncs.h"
76 #ifdef G_PLATFORM_WIN32
84 * @title: Miscellaneous Utility Functions
85 * @short_description: a selection of portable utility functions
87 * These are portable utility functions.
90 #ifdef G_PLATFORM_WIN32
92 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
93 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
94 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
96 # include <lmcons.h> /* For UNLEN */
97 #endif /* G_PLATFORM_WIN32 */
102 /* older SDK (e.g. msvc 5.0) does not have these*/
103 # ifndef CSIDL_MYMUSIC
104 # define CSIDL_MYMUSIC 13
106 # ifndef CSIDL_MYVIDEO
107 # define CSIDL_MYVIDEO 14
109 # ifndef CSIDL_INTERNET_CACHE
110 # define CSIDL_INTERNET_CACHE 32
112 # ifndef CSIDL_COMMON_APPDATA
113 # define CSIDL_COMMON_APPDATA 35
115 # ifndef CSIDL_MYPICTURES
116 # define CSIDL_MYPICTURES 0x27
118 # ifndef CSIDL_COMMON_DOCUMENTS
119 # define CSIDL_COMMON_DOCUMENTS 46
121 # ifndef CSIDL_PROFILE
122 # define CSIDL_PROFILE 40
124 # include <process.h>
128 #include <CoreServices/CoreServices.h>
132 #include <langinfo.h>
135 #ifdef G_PLATFORM_WIN32
138 _glib_get_dll_directory (void)
142 wchar_t wc_fn[MAX_PATH];
145 if (glib_dll == NULL)
149 /* This code is different from that in
150 * g_win32_get_package_installation_directory_of_module() in that
151 * here we return the actual folder where the GLib DLL is. We don't
152 * do the check for it being in a "bin" or "lib" subfolder and then
153 * returning the parent of that.
155 * In a statically built GLib, glib_dll will be NULL and we will
156 * thus look up the application's .exe file's location.
158 if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
161 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
163 p = strrchr (retval, G_DIR_SEPARATOR);
178 * @dest: the destination address to copy the bytes to.
179 * @src: the source address to copy the bytes from.
180 * @len: the number of bytes to copy.
182 * Copies a block of memory @len bytes long, from @src to @dest.
183 * The source and destination areas may overlap.
185 * Deprecated:2.40: Just use memmove().
194 * @func: (scope async): the function to call on normal program termination.
196 * Specifies a function to be called at normal program termination.
198 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
199 * macro that maps to a call to the atexit() function in the C
200 * library. This means that in case the code that calls g_atexit(),
201 * i.e. atexit(), is in a DLL, the function will be called when the
202 * DLL is detached from the program. This typically makes more sense
203 * than that the function is called when the GLib DLL is detached,
204 * which happened earlier when g_atexit() was a function in the GLib
207 * The behaviour of atexit() in the context of dynamically loaded
208 * modules is not formally specified and varies wildly.
210 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
211 * loaded module which is unloaded before the program terminates might
212 * well cause a crash at program exit.
214 * Some POSIX systems implement atexit() like Windows, and have each
215 * dynamically loaded module maintain an own atexit chain that is
216 * called when the module is unloaded.
218 * On other POSIX systems, before a dynamically loaded module is
219 * unloaded, the registered atexit functions (if any) residing in that
220 * module are called, regardless where the code that registered them
221 * resided. This is presumably the most robust approach.
223 * As can be seen from the above, for portability it's best to avoid
224 * calling g_atexit() (or atexit()) except in the main executable of a
227 * Deprecated:2.32: It is best to avoid g_atexit().
230 g_atexit (GVoidFunc func)
234 result = atexit ((void (*)(void)) func);
237 g_error ("Could not register atexit() function: %s",
242 /* Based on execvp() from GNU Libc.
243 * Some of this code is cut-and-pasted into gspawn.c
247 my_strchrnul (const gchar *str,
250 gchar *p = (gchar*)str;
251 while (*p && (*p != c))
259 static gchar *inner_find_program_in_path (const gchar *program);
262 g_find_program_in_path (const gchar *program)
264 const gchar *last_dot = strrchr (program, '.');
266 if (last_dot == NULL ||
267 strchr (last_dot, '\\') != NULL ||
268 strchr (last_dot, '/') != NULL)
270 const gint program_length = strlen (program);
271 gchar *pathext = g_build_path (";",
272 ".exe;.cmd;.bat;.com",
273 g_getenv ("PATHEXT"),
276 gchar *decorated_program;
282 gchar *q = my_strchrnul (p, ';');
284 decorated_program = g_malloc (program_length + (q-p) + 1);
285 memcpy (decorated_program, program, program_length);
286 memcpy (decorated_program+program_length, p, q-p);
287 decorated_program [program_length + (q-p)] = '\0';
289 retval = inner_find_program_in_path (decorated_program);
290 g_free (decorated_program);
298 } while (*p++ != '\0');
303 return inner_find_program_in_path (program);
309 * g_find_program_in_path:
310 * @program: a program name in the GLib file name encoding
312 * Locates the first executable named @program in the user's path, in the
313 * same way that execvp() would locate it. Returns an allocated string
314 * with the absolute path name, or %NULL if the program is not found in
315 * the path. If @program is already an absolute path, returns a copy of
316 * @program if @program exists and is executable, and %NULL otherwise.
318 * On Windows, if @program does not have a file type suffix, tries
319 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
320 * the <envar>PATHEXT</envar> environment variable.
322 * On Windows, it looks for the file in the same way as CreateProcess()
323 * would. This means first in the directory where the executing
324 * program was loaded from, then in the current directory, then in the
325 * Windows 32-bit system directory, then in the Windows directory, and
326 * finally in the directories in the <envar>PATH</envar> environment
327 * variable. If the program is found, the return value contains the
328 * full name including the type suffix.
330 * Return value: a newly-allocated string with the absolute path, or %NULL
334 inner_find_program_in_path (const gchar *program)
337 g_find_program_in_path (const gchar *program)
340 const gchar *path, *p;
341 gchar *name, *freeme;
343 const gchar *path_copy;
344 gchar *filename = NULL, *appdir = NULL;
345 gchar *sysdir = NULL, *windir = NULL;
347 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
353 g_return_val_if_fail (program != NULL, NULL);
355 /* If it is an absolute path, or a relative path including subdirectories,
356 * don't look in PATH.
358 if (g_path_is_absolute (program)
359 || strchr (program, G_DIR_SEPARATOR) != NULL
361 || strchr (program, '/') != NULL
365 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
366 !g_file_test (program, G_FILE_TEST_IS_DIR))
367 return g_strdup (program);
372 path = g_getenv ("PATH");
373 #if defined(G_OS_UNIX)
376 /* There is no 'PATH' in the environment. The default
377 * search path in GNU libc is the current directory followed by
378 * the path 'confstr' returns for '_CS_PATH'.
381 /* In GLib we put . last, for security, and don't use the
382 * unportable confstr(); UNIX98 does not actually specify
383 * what to search if PATH is unset. POSIX may, dunno.
386 path = "/bin:/usr/bin:.";
389 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
390 if (n > 0 && n < MAXPATHLEN)
391 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
393 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
394 if (n > 0 && n < MAXPATHLEN)
395 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
397 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
398 if (n > 0 && n < MAXPATHLEN)
399 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
403 appdir = g_path_get_dirname (filename);
407 path = g_strdup (path);
411 const gchar *tem = path;
412 path = g_strconcat (windir, ";", path, NULL);
413 g_free ((gchar *) tem);
419 const gchar *tem = path;
420 path = g_strconcat (sysdir, ";", path, NULL);
421 g_free ((gchar *) tem);
426 const gchar *tem = path;
427 path = g_strconcat (".;", path, NULL);
428 g_free ((gchar *) tem);
433 const gchar *tem = path;
434 path = g_strconcat (appdir, ";", path, NULL);
435 g_free ((gchar *) tem);
442 len = strlen (program) + 1;
443 pathlen = strlen (path);
444 freeme = name = g_malloc (pathlen + len + 1);
446 /* Copy the file name at the top, including '\0' */
447 memcpy (name + pathlen + 1, program, len);
448 name = name + pathlen;
449 /* And add the slash before the filename */
450 *name = G_DIR_SEPARATOR;
458 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
461 /* Two adjacent colons, or a colon at the beginning or the end
462 * of 'PATH' means to search the current directory.
466 startp = memcpy (name - (p - path), path, p - path);
468 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
469 !g_file_test (startp, G_FILE_TEST_IS_DIR))
472 ret = g_strdup (startp);
475 g_free ((gchar *) path_copy);
480 while (*p++ != '\0');
484 g_free ((gchar *) path_copy);
492 * @mask: a #gulong containing flags
493 * @nth_bit: the index of the bit to start the search from
495 * Find the position of the first bit set in @mask, searching
496 * from (but not including) @nth_bit upwards. Bits are numbered
497 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
498 * usually). To start searching from the 0th bit, set @nth_bit to -1.
500 * Returns: the index of the first bit set which is higher than @nth_bit
505 * @mask: a #gulong containing flags
506 * @nth_bit: the index of the bit to start the search from
508 * Find the position of the first bit set in @mask, searching
509 * from (but not including) @nth_bit downwards. Bits are numbered
510 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
511 * usually). To start searching from the last bit, set @nth_bit to
512 * -1 or GLIB_SIZEOF_LONG * 8.
514 * Returns: the index of the first bit set which is lower than @nth_bit
521 * Gets the number of bits used to hold @number,
522 * e.g. if @number is 4, 3 bits are needed.
524 * Returns: the number of bits used to hold @number
527 G_LOCK_DEFINE_STATIC (g_utils_global);
536 static gchar *g_user_data_dir = NULL;
537 static gchar **g_system_data_dirs = NULL;
538 static gchar *g_user_cache_dir = NULL;
539 static gchar *g_user_config_dir = NULL;
540 static gchar **g_system_config_dirs = NULL;
542 static gchar **g_user_special_dirs = NULL;
544 /* fifteen minutes of fame for everybody */
545 #define G_USER_DIRS_EXPIRE 15 * 60
550 get_special_folder (int csidl)
552 wchar_t path[MAX_PATH+1];
554 LPITEMIDLIST pidl = NULL;
556 gchar *retval = NULL;
558 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
561 b = SHGetPathFromIDListW (pidl, path);
563 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
564 CoTaskMemFree (pidl);
570 get_windows_directory_root (void)
572 wchar_t wwindowsdir[MAX_PATH];
574 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
576 /* Usually X:\Windows, but in terminal server environments
577 * might be an UNC path, AFAIK.
579 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
582 if (windowsdir == NULL)
583 return g_strdup ("C:\\");
585 p = (char *) g_path_skip_root (windowsdir);
586 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
592 return g_strdup ("C:\\");
597 /* HOLDS: g_utils_global_lock */
598 static UserDatabaseEntry *
599 g_get_user_database_entry (void)
601 static UserDatabaseEntry *entry;
603 if (g_once_init_enter (&entry))
605 static UserDatabaseEntry e;
609 struct passwd *pw = NULL;
610 gpointer buffer = NULL;
614 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
616 # ifdef _SC_GETPW_R_SIZE_MAX
617 /* This reurns the maximum length */
618 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
622 # else /* _SC_GETPW_R_SIZE_MAX */
624 # endif /* _SC_GETPW_R_SIZE_MAX */
626 logname = (gchar *) g_getenv ("LOGNAME");
631 /* we allocate 6 extra bytes to work around a bug in
632 * Mac OS < 10.3. See #156446
634 buffer = g_malloc (bufsize + 6);
637 # ifdef HAVE_POSIX_GETPWUID_R
639 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
640 if (!pw || (pw->pw_uid != getuid ())) {
641 /* LOGNAME is lying, fall back to looking up the uid */
642 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
645 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
647 error = error < 0 ? errno : error;
648 # else /* HAVE_NONPOSIX_GETPWUID_R */
650 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
651 pw = error == 0 ? &pwd : NULL;
654 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
655 if (!pw || (pw->pw_uid != getuid ())) {
656 /* LOGNAME is lying, fall back to looking up the uid */
657 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
660 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
662 error = pw ? 0 : errno;
664 # endif /* HAVE_NONPOSIX_GETPWUID_R */
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_POSIX_GETPWUID_R || HAVE_NONPOSIX_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: 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 entry
772 * in the <filename>passwd</filename> file. The encoding of the returned
773 * string is system-defined. (On Windows, it is, however, always UTF-8.)
774 * If the real user name cannot be determined, the string "Unknown" is
777 * Returns: 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 * <envar>HOME</envar> environment variable if it is set to an existing
796 * absolute path name, falling back to the <filename>passwd</filename>
797 * file in the case that it is unset.
799 * If the path given in <envar>HOME</envar> is non-absolute, does not
800 * exist, or is not a directory, the result is undefined.
803 * Before version 2.36 this function would ignore the
804 * <envar>HOME</envar> environment variable, taking the value from the
805 * <filename>passwd</filename> database instead. This was changed to
806 * increase the compatibility of GLib with other programs (and the XDG
807 * basedir specification) and to increase testability of programs
808 * based on GLib (by making it easier to run them from test
811 * If your program has a strong requirement for either the new or the
812 * old behaviour (and if you don't wish to increase your GLib
813 * dependency to ensure that the new behaviour is in effect) then you
814 * should either directly check the <envar>HOME</envar> environment
815 * variable yourself or unset it before calling any functions in GLib.
818 * Returns: the current user's home directory
821 g_get_home_dir (void)
823 static gchar *home_dir;
825 if (g_once_init_enter (&home_dir))
829 /* We first check HOME and use it if it is set */
830 tmp = g_strdup (g_getenv ("HOME"));
833 /* Only believe HOME if it is an absolute path and exists.
835 * We only do this check on Windows for a couple of reasons.
836 * Historically, we only did it there because we used to ignore $HOME
837 * on UNIX. There are concerns about enabling it now on UNIX because
838 * of things like autofs. In short, if the user has a bogus value in
839 * $HOME then they get what they pay for...
843 if (!(g_path_is_absolute (tmp) &&
844 g_file_test (tmp, G_FILE_TEST_IS_DIR)))
851 /* In case HOME is Unix-style (it happens), convert it to
857 while ((p = strchr (tmp, '/')) != NULL)
863 /* USERPROFILE is probably the closest equivalent to $HOME? */
864 if (g_getenv ("USERPROFILE") != NULL)
865 tmp = g_strdup (g_getenv ("USERPROFILE"));
869 tmp = get_special_folder (CSIDL_PROFILE);
872 tmp = get_windows_directory_root ();
873 #endif /* G_OS_WIN32 */
877 /* If we didn't get it from any of those methods, we will have
878 * to read the user database entry.
880 UserDatabaseEntry *entry;
882 entry = g_get_user_database_entry ();
884 /* Strictly speaking, we should copy this, but we know that
885 * neither will ever be freed, so don't bother...
887 tmp = entry->home_dir;
890 g_once_init_leave (&home_dir, tmp);
899 * Gets the directory to use for temporary files.
901 * On UNIX, this is taken from the <envar>TMPDIR</envar> environment
902 * variable. If the variable is not set, <literal>P_tmpdir</literal> is
903 * used, as defined by the system C library. Failing that, a hard-coded
904 * default of "/tmp" is returned.
906 * On Windows, the <envar>TEMP</envar> environment variable is used,
907 * with the root directory of the Windows installation (eg: "C:\") used
910 * The encoding of the returned string is system-defined. On Windows, it
911 * is always UTF-8. The return value is never %NULL or the empty string.
913 * Returns: the directory to use for temporary files.
918 static gchar *tmp_dir;
920 if (g_once_init_enter (&tmp_dir))
925 tmp = g_strdup (g_getenv ("TEMP"));
927 if (tmp == NULL || *tmp == '\0')
930 tmp = get_windows_directory_root ();
932 #else /* G_OS_WIN32 */
933 tmp = g_strdup (g_getenv ("TMPDIR"));
936 if (tmp == NULL || *tmp == '\0')
940 tmp = g_strdup (P_tmpdir);
942 if (k > 1 && G_IS_DIR_SEPARATOR (tmp[k - 1]))
945 #endif /* P_tmpdir */
947 if (tmp == NULL || *tmp == '\0')
950 tmp = g_strdup ("/tmp");
952 #endif /* !G_OS_WIN32 */
954 g_once_init_leave (&tmp_dir, tmp);
963 * Return a name for the machine.
965 * The returned name is not necessarily a fully-qualified domain name,
966 * or even present in DNS or some other name service at all. It need
967 * not even be unique on your local network or site, but usually it
968 * is. Callers should not rely on the return value having any specific
969 * properties like uniqueness for security purposes. Even if the name
970 * of the machine is changed while an application is running, the
971 * return value from this function does not change. The returned
972 * string is owned by GLib and should not be modified or freed. If no
973 * name can be determined, a default fixed string "localhost" is
976 * Returns: the host name of the machine.
981 g_get_host_name (void)
983 static gchar *hostname;
985 if (g_once_init_enter (&hostname))
991 failed = (gethostname (tmp, sizeof (tmp)) == -1);
993 DWORD size = sizeof (tmp);
994 failed = (!GetComputerName (tmp, &size));
997 g_once_init_leave (&hostname, g_strdup (failed ? "localhost" : tmp));
1003 G_LOCK_DEFINE_STATIC (g_prgname);
1004 static gchar *g_prgname = NULL;
1009 * Gets the name of the program. This name should <emphasis>not</emphasis>
1010 * be localized, contrast with g_get_application_name().
1011 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1012 * which is called by gtk_init(). The program name is found by taking
1013 * the last component of <literal>argv[0]</literal>.)
1015 * Returns: the name of the program. The returned string belongs
1016 * to GLib and must not be modified or freed.
1019 g_get_prgname (void)
1025 if (g_prgname == NULL)
1027 static gboolean beenhere = FALSE;
1031 gchar *utf8_buf = NULL;
1032 wchar_t buf[MAX_PATH+1];
1035 if (GetModuleFileNameW (GetModuleHandle (NULL),
1036 buf, G_N_ELEMENTS (buf)) > 0)
1037 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1041 g_prgname = g_path_get_basename (utf8_buf);
1048 G_UNLOCK (g_prgname);
1055 * @prgname: the name of the program.
1057 * Sets the name of the program. This name should <emphasis>not</emphasis>
1058 * be localized, contrast with g_set_application_name(). Note that for
1059 * thread-safety reasons this function can only be called once.
1062 g_set_prgname (const gchar *prgname)
1066 g_prgname = g_strdup (prgname);
1067 G_UNLOCK (g_prgname);
1070 G_LOCK_DEFINE_STATIC (g_application_name);
1071 static gchar *g_application_name = NULL;
1074 * g_get_application_name:
1076 * Gets a human-readable name for the application, as set by
1077 * g_set_application_name(). This name should be localized if
1078 * possible, and is intended for display to the user. Contrast with
1079 * g_get_prgname(), which gets a non-localized name. If
1080 * g_set_application_name() has not been called, returns the result of
1081 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1084 * Return value: human-readable application name. may return %NULL
1089 g_get_application_name (void)
1093 G_LOCK (g_application_name);
1094 retval = g_application_name;
1095 G_UNLOCK (g_application_name);
1098 return g_get_prgname ();
1104 * g_set_application_name:
1105 * @application_name: localized name of the application
1107 * Sets a human-readable name for the application. This name should be
1108 * localized if possible, and is intended for display to the user.
1109 * Contrast with g_set_prgname(), which sets a non-localized name.
1110 * g_set_prgname() will be called automatically by gtk_init(),
1111 * but g_set_application_name() will not.
1113 * Note that for thread safety reasons, this function can only
1116 * The application name will be used in contexts such as error messages,
1117 * or when displaying an application's name in the task list.
1122 g_set_application_name (const gchar *application_name)
1124 gboolean already_set = FALSE;
1126 G_LOCK (g_application_name);
1127 if (g_application_name)
1130 g_application_name = g_strdup (application_name);
1131 G_UNLOCK (g_application_name);
1134 g_warning ("g_set_application_name() called multiple times");
1138 * g_get_user_data_dir:
1140 * Returns a base directory in which to access application data such
1141 * as icons that is customized for a particular user.
1143 * On UNIX platforms this is determined using the mechanisms described in
1144 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1145 * XDG Base Directory Specification</ulink>.
1146 * In this case the directory retrieved will be XDG_DATA_HOME.
1148 * On Windows this is the folder to use for local (as opposed to
1149 * roaming) application data. See documentation for
1150 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1151 * what g_get_user_config_dir() returns.
1153 * Return value: a string owned by GLib that must not be modified
1158 g_get_user_data_dir (void)
1162 G_LOCK (g_utils_global);
1164 if (!g_user_data_dir)
1167 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1169 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1171 if (data_dir && data_dir[0])
1172 data_dir = g_strdup (data_dir);
1174 if (!data_dir || !data_dir[0])
1176 const gchar *home_dir = g_get_home_dir ();
1179 data_dir = g_build_filename (home_dir, ".local", "share", NULL);
1181 data_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".local", "share", NULL);
1184 g_user_data_dir = data_dir;
1187 data_dir = g_user_data_dir;
1189 G_UNLOCK (g_utils_global);
1195 g_init_user_config_dir (void)
1199 if (!g_user_config_dir)
1202 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1204 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1206 if (config_dir && config_dir[0])
1207 config_dir = g_strdup (config_dir);
1209 if (!config_dir || !config_dir[0])
1211 const gchar *home_dir = g_get_home_dir ();
1214 config_dir = g_build_filename (home_dir, ".config", NULL);
1216 config_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".config", NULL);
1219 g_user_config_dir = config_dir;
1224 * g_get_user_config_dir:
1226 * Returns a base directory in which to store user-specific application
1227 * configuration information such as user preferences and settings.
1229 * On UNIX platforms this is determined using the mechanisms described in
1230 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1231 * XDG Base Directory Specification</ulink>.
1232 * In this case the directory retrieved will be XDG_CONFIG_HOME.
1234 * On Windows this is the folder to use for local (as opposed to
1235 * roaming) application data. See documentation for
1236 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1237 * what g_get_user_data_dir() returns.
1239 * Return value: a string owned by GLib that must not be modified
1244 g_get_user_config_dir (void)
1246 G_LOCK (g_utils_global);
1248 g_init_user_config_dir ();
1250 G_UNLOCK (g_utils_global);
1252 return g_user_config_dir;
1256 * g_get_user_cache_dir:
1258 * Returns a base directory in which to store non-essential, cached
1259 * data specific to particular user.
1261 * On UNIX platforms this is determined using the mechanisms described in
1262 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1263 * XDG Base Directory Specification</ulink>.
1264 * In this case the directory retrieved will be XDG_CACHE_HOME.
1266 * On Windows is the directory that serves as a common repository for
1267 * temporary Internet files. A typical path is
1268 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
1269 * See documentation for CSIDL_INTERNET_CACHE.
1271 * Return value: a string owned by GLib that must not be modified
1276 g_get_user_cache_dir (void)
1280 G_LOCK (g_utils_global);
1282 if (!g_user_cache_dir)
1285 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1287 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1289 if (cache_dir && cache_dir[0])
1290 cache_dir = g_strdup (cache_dir);
1292 if (!cache_dir || !cache_dir[0])
1294 const gchar *home_dir = g_get_home_dir ();
1297 cache_dir = g_build_filename (home_dir, ".cache", NULL);
1299 cache_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".cache", NULL);
1301 g_user_cache_dir = cache_dir;
1304 cache_dir = g_user_cache_dir;
1306 G_UNLOCK (g_utils_global);
1312 * g_get_user_runtime_dir:
1314 * Returns a directory that is unique to the current user on the local
1317 * On UNIX platforms this is determined using the mechanisms described in
1318 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1319 * XDG Base Directory Specification</ulink>. This is the directory
1320 * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
1321 * In the case that this variable is not set, GLib will issue a warning
1322 * message to stderr and return the value of g_get_user_cache_dir().
1324 * On Windows this is the folder to use for local (as opposed to
1325 * roaming) application data. See documentation for
1326 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1327 * what g_get_user_config_dir() returns.
1329 * Returns: a string owned by GLib that must not be modified or freed.
1334 g_get_user_runtime_dir (void)
1337 static const gchar *runtime_dir;
1338 static gsize initialised;
1340 if (g_once_init_enter (&initialised))
1342 runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
1344 g_once_init_leave (&initialised, 1);
1350 /* Both fallback for UNIX and the default
1351 * in Windows: use the user cache directory.
1355 return g_get_user_cache_dir ();
1361 find_folder (OSType type)
1363 gchar *filename = NULL;
1366 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
1368 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
1372 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
1376 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
1380 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
1382 CFStringGetCString (path, filename,
1383 CFStringGetLength (path) * 3 + 1,
1384 kCFStringEncodingUTF8);
1398 load_user_special_dirs (void)
1400 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
1401 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
1402 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
1403 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
1404 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
1405 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
1406 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
1407 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
1410 #endif /* HAVE_CARBON */
1412 #if defined(G_OS_WIN32)
1414 load_user_special_dirs (void)
1416 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1420 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
1422 static const GUID FOLDERID_Downloads =
1423 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1424 static const GUID FOLDERID_Public =
1425 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1429 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
1430 "SHGetKnownFolderPath");
1432 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1433 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
1435 if (p_SHGetKnownFolderPath == NULL)
1437 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1442 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1445 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1446 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
1447 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1448 CoTaskMemFree (wcp);
1451 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1454 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
1455 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
1457 if (p_SHGetKnownFolderPath == NULL)
1460 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1465 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
1468 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1469 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
1470 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1471 CoTaskMemFree (wcp);
1474 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1477 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
1478 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
1480 #endif /* G_OS_WIN32 */
1483 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
1485 /* adapted from xdg-user-dir-lookup.c
1487 * Copyright (C) 2007 Red Hat Inc.
1489 * Permission is hereby granted, free of charge, to any person
1490 * obtaining a copy of this software and associated documentation files
1491 * (the "Software"), to deal in the Software without restriction,
1492 * including without limitation the rights to use, copy, modify, merge,
1493 * publish, distribute, sublicense, and/or sell copies of the Software,
1494 * and to permit persons to whom the Software is furnished to do so,
1495 * subject to the following conditions:
1497 * The above copyright notice and this permission notice shall be
1498 * included in all copies or substantial portions of the Software.
1500 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1501 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1502 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1503 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1504 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1505 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1506 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1510 load_user_special_dirs (void)
1517 g_init_user_config_dir ();
1518 config_file = g_build_filename (g_user_config_dir,
1522 if (!g_file_get_contents (config_file, &data, NULL, NULL))
1524 g_free (config_file);
1528 lines = g_strsplit (data, "\n", -1);
1529 n_lines = g_strv_length (lines);
1532 for (i = 0; i < n_lines; i++)
1534 gchar *buffer = lines[i];
1537 gboolean is_relative = FALSE;
1538 GUserDirectory directory;
1540 /* Remove newline at end */
1541 len = strlen (buffer);
1542 if (len > 0 && buffer[len - 1] == '\n')
1543 buffer[len - 1] = 0;
1546 while (*p == ' ' || *p == '\t')
1549 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
1551 directory = G_USER_DIRECTORY_DESKTOP;
1552 p += strlen ("XDG_DESKTOP_DIR");
1554 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
1556 directory = G_USER_DIRECTORY_DOCUMENTS;
1557 p += strlen ("XDG_DOCUMENTS_DIR");
1559 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
1561 directory = G_USER_DIRECTORY_DOWNLOAD;
1562 p += strlen ("XDG_DOWNLOAD_DIR");
1564 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
1566 directory = G_USER_DIRECTORY_MUSIC;
1567 p += strlen ("XDG_MUSIC_DIR");
1569 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
1571 directory = G_USER_DIRECTORY_PICTURES;
1572 p += strlen ("XDG_PICTURES_DIR");
1574 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
1576 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
1577 p += strlen ("XDG_PUBLICSHARE_DIR");
1579 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
1581 directory = G_USER_DIRECTORY_TEMPLATES;
1582 p += strlen ("XDG_TEMPLATES_DIR");
1584 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
1586 directory = G_USER_DIRECTORY_VIDEOS;
1587 p += strlen ("XDG_VIDEOS_DIR");
1592 while (*p == ' ' || *p == '\t')
1599 while (*p == ' ' || *p == '\t')
1606 if (strncmp (p, "$HOME", 5) == 0)
1614 d = strrchr (p, '"');
1621 /* remove trailing slashes */
1623 if (d[len - 1] == '/')
1628 g_user_special_dirs[directory] = g_build_filename (g_get_home_dir (), d, NULL);
1631 g_user_special_dirs[directory] = g_strdup (d);
1635 g_free (config_file);
1638 #endif /* G_OS_UNIX && !HAVE_CARBON */
1642 * g_reload_user_special_dirs_cache:
1644 * Resets the cache used for g_get_user_special_dir(), so
1645 * that the latest on-disk version is used. Call this only
1646 * if you just changed the data on disk yourself.
1648 * Due to threadsafety issues this may cause leaking of strings
1649 * that were previously returned from g_get_user_special_dir()
1650 * that can't be freed. We ensure to only leak the data for
1651 * the directories that actually changed value though.
1656 g_reload_user_special_dirs_cache (void)
1660 G_LOCK (g_utils_global);
1662 if (g_user_special_dirs != NULL)
1664 /* save a copy of the pointer, to check if some memory can be preserved */
1665 char **old_g_user_special_dirs = g_user_special_dirs;
1668 /* recreate and reload our cache */
1669 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1670 load_user_special_dirs ();
1672 /* only leak changed directories */
1673 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
1675 old_val = old_g_user_special_dirs[i];
1676 if (g_user_special_dirs[i] == NULL)
1678 g_user_special_dirs[i] = old_val;
1680 else if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
1683 g_free (g_user_special_dirs[i]);
1684 g_user_special_dirs[i] = old_val;
1690 /* free the old array */
1691 g_free (old_g_user_special_dirs);
1694 G_UNLOCK (g_utils_global);
1698 * g_get_user_special_dir:
1699 * @directory: the logical id of special directory
1701 * Returns the full path of a special directory using its logical id.
1703 * On Unix this is done using the XDG special user directories.
1704 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
1705 * falls back to <filename>$HOME/Desktop</filename> when XDG special
1706 * user directories have not been set up.
1708 * Depending on the platform, the user might be able to change the path
1709 * of the special directory without requiring the session to restart; GLib
1710 * will not reflect any change once the special directories are loaded.
1712 * Return value: the path to the specified special directory, or %NULL
1713 * if the logical id was not found. The returned string is owned by
1714 * GLib and should not be modified or freed.
1719 g_get_user_special_dir (GUserDirectory directory)
1721 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
1722 directory < G_USER_N_DIRECTORIES, NULL);
1724 G_LOCK (g_utils_global);
1726 if (G_UNLIKELY (g_user_special_dirs == NULL))
1728 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1730 load_user_special_dirs ();
1732 /* Special-case desktop for historical compatibility */
1733 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
1734 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = g_build_filename (g_get_home_dir (), "Desktop", NULL);
1737 G_UNLOCK (g_utils_global);
1739 return g_user_special_dirs[directory];
1744 #undef g_get_system_data_dirs
1747 get_module_for_address (gconstpointer address)
1749 /* Holds the g_utils_global lock */
1751 static gboolean beenhere = FALSE;
1752 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
1753 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
1754 HMODULE hmodule = NULL;
1761 p_GetModuleHandleExA =
1762 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1763 "GetModuleHandleExA");
1767 if (p_GetModuleHandleExA == NULL ||
1768 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
1769 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
1772 MEMORY_BASIC_INFORMATION mbi;
1773 VirtualQuery (address, &mbi, sizeof (mbi));
1774 hmodule = (HMODULE) mbi.AllocationBase;
1781 get_module_share_dir (gconstpointer address)
1787 hmodule = get_module_for_address (address);
1788 if (hmodule == NULL)
1791 filename = g_win32_get_package_installation_directory_of_module (hmodule);
1792 retval = g_build_filename (filename, "share", NULL);
1798 const gchar * const *
1799 g_win32_get_system_data_dirs_for_module (void (*address_of_function)(void))
1803 static GHashTable *per_module_data_dirs = NULL;
1808 if (address_of_function)
1810 G_LOCK (g_utils_global);
1811 hmodule = get_module_for_address (address_of_function);
1812 if (hmodule != NULL)
1814 if (per_module_data_dirs == NULL)
1815 per_module_data_dirs = g_hash_table_new (NULL, NULL);
1818 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
1822 G_UNLOCK (g_utils_global);
1823 return (const gchar * const *) retval;
1829 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
1831 /* Documents and Settings\All Users\Application Data */
1832 p = get_special_folder (CSIDL_COMMON_APPDATA);
1834 g_array_append_val (data_dirs, p);
1836 /* Documents and Settings\All Users\Documents */
1837 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1839 g_array_append_val (data_dirs, p);
1841 /* Using the above subfolders of Documents and Settings perhaps
1842 * makes sense from a Windows perspective.
1844 * But looking at the actual use cases of this function in GTK+
1845 * and GNOME software, what we really want is the "share"
1846 * subdirectory of the installation directory for the package
1847 * our caller is a part of.
1849 * The address_of_function parameter, if non-NULL, points to a
1850 * function in the calling module. Use that to determine that
1851 * module's installation folder, and use its "share" subfolder.
1853 * Additionally, also use the "share" subfolder of the installation
1854 * locations of GLib and the .exe file being run.
1856 * To guard against none of the above being what is really wanted,
1857 * callers of this function should have Win32-specific code to look
1858 * up their installation folder themselves, and handle a subfolder
1859 * "share" of it in the same way as the folders returned from this
1863 p = get_module_share_dir (address_of_function);
1865 g_array_append_val (data_dirs, p);
1867 if (glib_dll != NULL)
1869 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
1870 p = g_build_filename (glib_root, "share", NULL);
1872 g_array_append_val (data_dirs, p);
1876 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
1877 p = g_build_filename (exe_root, "share", NULL);
1879 g_array_append_val (data_dirs, p);
1882 retval = (gchar **) g_array_free (data_dirs, FALSE);
1884 if (address_of_function)
1886 if (hmodule != NULL)
1887 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
1888 G_UNLOCK (g_utils_global);
1891 return (const gchar * const *) retval;
1897 * g_get_system_data_dirs:
1899 * Returns an ordered list of base directories in which to access
1900 * system-wide application data.
1902 * On UNIX platforms this is determined using the mechanisms described in
1903 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1904 * XDG Base Directory Specification</ulink>
1905 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
1907 * On Windows the first elements in the list are the Application Data
1908 * and Documents folders for All Users. (These can be determined only
1909 * on Windows 2000 or later and are not present in the list on other
1910 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
1911 * CSIDL_COMMON_DOCUMENTS.
1913 * Then follows the "share" subfolder in the installation folder for
1914 * the package containing the DLL that calls this function, if it can
1917 * Finally the list contains the "share" subfolder in the installation
1918 * folder for GLib, and in the installation folder for the package the
1919 * application's .exe file belongs to.
1921 * The installation folders above are determined by looking up the
1922 * folder where the module (DLL or EXE) in question is located. If the
1923 * folder's name is "bin", its parent is used, otherwise the folder
1926 * Note that on Windows the returned list can vary depending on where
1927 * this function is called.
1929 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
1930 * not be modified or freed.
1933 const gchar * const *
1934 g_get_system_data_dirs (void)
1936 gchar **data_dir_vector;
1938 G_LOCK (g_utils_global);
1940 if (!g_system_data_dirs)
1943 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
1945 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
1947 if (!data_dirs || !data_dirs[0])
1948 data_dirs = "/usr/local/share/:/usr/share/";
1950 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1953 g_system_data_dirs = data_dir_vector;
1956 data_dir_vector = g_system_data_dirs;
1958 G_UNLOCK (g_utils_global);
1960 return (const gchar * const *) data_dir_vector;
1964 * g_get_system_config_dirs:
1966 * Returns an ordered list of base directories in which to access
1967 * system-wide configuration information.
1969 * On UNIX platforms this is determined using the mechanisms described in
1970 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1971 * XDG Base Directory Specification</ulink>.
1972 * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
1974 * On Windows is the directory that contains application data for all users.
1975 * A typical path is C:\Documents and Settings\All Users\Application Data.
1976 * This folder is used for application data that is not user specific.
1977 * For example, an application can store a spell-check dictionary, a database
1978 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
1979 * This information will not roam and is available to anyone using the computer.
1981 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
1982 * not be modified or freed.
1985 const gchar * const *
1986 g_get_system_config_dirs (void)
1988 gchar *conf_dirs, **conf_dir_vector;
1990 G_LOCK (g_utils_global);
1992 if (!g_system_config_dirs)
1995 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
1998 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2003 /* Return empty list */
2004 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2007 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2009 if (!conf_dirs || !conf_dirs[0])
2010 conf_dirs = "/etc/xdg";
2012 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2015 g_system_config_dirs = conf_dir_vector;
2018 conf_dir_vector = g_system_config_dirs;
2019 G_UNLOCK (g_utils_global);
2021 return (const gchar * const *) conf_dir_vector;
2025 * g_nullify_pointer:
2026 * @nullify_location: the memory address of the pointer.
2028 * Set the pointer at the specified location to %NULL.
2031 g_nullify_pointer (gpointer *nullify_location)
2033 g_return_if_fail (nullify_location != NULL);
2035 *nullify_location = NULL;
2038 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2039 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2040 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2041 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2042 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2043 #define EXABYTE_FACTOR (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2045 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2046 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2047 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2048 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2049 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2050 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2054 * @size: a size in bytes
2056 * Formats a size (for example the size of a file) into a human readable
2057 * string. Sizes are rounded to the nearest size prefix (kB, MB, GB)
2058 * and are displayed rounded to the nearest tenth. E.g. the file size
2059 * 3292528 bytes will be converted into the string "3.2 MB".
2061 * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2063 * This string should be freed with g_free() when not needed any longer.
2065 * See g_format_size_full() for more options about how the size might be
2068 * Returns: a newly-allocated formatted string containing a human readable
2074 g_format_size (guint64 size)
2076 return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2081 * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2082 * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2083 * of the returned string. For example, "45.6 kB (45,612 bytes)".
2084 * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2085 * suffixes. IEC units should only be used for reporting things with
2086 * a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2087 * Network and storage sizes should be reported in the normal SI units.
2089 * Flags to modify the format of the string returned by g_format_size_full().
2092 #pragma GCC diagnostic push
2093 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
2096 * g_format_size_full:
2097 * @size: a size in bytes
2098 * @flags: #GFormatSizeFlags to modify the output
2102 * This function is similar to g_format_size() but allows for flags
2103 * that modify the output. See #GFormatSizeFlags.
2105 * Returns: a newly-allocated formatted string containing a human
2106 * readable file size
2111 g_format_size_full (guint64 size,
2112 GFormatSizeFlags flags)
2116 string = g_string_new (NULL);
2118 if (flags & G_FORMAT_SIZE_IEC_UNITS)
2120 if (size < KIBIBYTE_FACTOR)
2122 g_string_printf (string,
2123 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2125 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2128 else if (size < MEBIBYTE_FACTOR)
2129 g_string_printf (string, _("%.1f KiB"), (gdouble) size / (gdouble) KIBIBYTE_FACTOR);
2130 else if (size < GIBIBYTE_FACTOR)
2131 g_string_printf (string, _("%.1f MiB"), (gdouble) size / (gdouble) MEBIBYTE_FACTOR);
2133 else if (size < TEBIBYTE_FACTOR)
2134 g_string_printf (string, _("%.1f GiB"), (gdouble) size / (gdouble) GIBIBYTE_FACTOR);
2136 else if (size < PEBIBYTE_FACTOR)
2137 g_string_printf (string, _("%.1f TiB"), (gdouble) size / (gdouble) TEBIBYTE_FACTOR);
2139 else if (size < EXBIBYTE_FACTOR)
2140 g_string_printf (string, _("%.1f PiB"), (gdouble) size / (gdouble) PEBIBYTE_FACTOR);
2143 g_string_printf (string, _("%.1f EiB"), (gdouble) size / (gdouble) EXBIBYTE_FACTOR);
2147 if (size < KILOBYTE_FACTOR)
2149 g_string_printf (string,
2150 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2152 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2155 else if (size < MEGABYTE_FACTOR)
2156 g_string_printf (string, _("%.1f kB"), (gdouble) size / (gdouble) KILOBYTE_FACTOR);
2158 else if (size < GIGABYTE_FACTOR)
2159 g_string_printf (string, _("%.1f MB"), (gdouble) size / (gdouble) MEGABYTE_FACTOR);
2161 else if (size < TERABYTE_FACTOR)
2162 g_string_printf (string, _("%.1f GB"), (gdouble) size / (gdouble) GIGABYTE_FACTOR);
2163 else if (size < PETABYTE_FACTOR)
2164 g_string_printf (string, _("%.1f TB"), (gdouble) size / (gdouble) TERABYTE_FACTOR);
2166 else if (size < EXABYTE_FACTOR)
2167 g_string_printf (string, _("%.1f PB"), (gdouble) size / (gdouble) PETABYTE_FACTOR);
2170 g_string_printf (string, _("%.1f EB"), (gdouble) size / (gdouble) EXABYTE_FACTOR);
2173 if (flags & G_FORMAT_SIZE_LONG_FORMAT)
2175 /* First problem: we need to use the number of bytes to decide on
2176 * the plural form that is used for display, but the number of
2177 * bytes potentially exceeds the size of a guint (which is what
2178 * ngettext() takes).
2180 * From a pragmatic standpoint, it seems that all known languages
2181 * base plural forms on one or both of the following:
2183 * - the lowest digits of the number
2185 * - if the number if greater than some small value
2187 * Here's how we fake it: Draw an arbitrary line at one thousand.
2188 * If the number is below that, then fine. If it is above it,
2189 * then we take the modulus of the number by one thousand (in
2190 * order to keep the lowest digits) and add one thousand to that
2191 * (in order to ensure that 1001 is not treated the same as 1).
2193 guint plural_form = size < 1000 ? size : size % 1000 + 1000;
2195 /* Second problem: we need to translate the string "%u byte" and
2196 * "%u bytes" for pluralisation, but the correct number format to
2197 * use for a gsize is different depending on which architecture
2200 * Solution: format the number separately and use "%s bytes" on
2203 const gchar *translated_format;
2204 gchar *formatted_number;
2206 /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2207 translated_format = g_dngettext(GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
2208 /* XXX: Windows doesn't support the "'" format modifier, so we
2209 * must not use it there. Instead, just display the number
2210 * without separation. Bug #655336 is open until a solution is
2214 formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2216 formatted_number = g_strdup_printf ("%"G_GUINT64_FORMAT, size);
2219 g_string_append (string, " (");
2220 g_string_append_printf (string, translated_format, formatted_number);
2221 g_free (formatted_number);
2222 g_string_append (string, ")");
2225 return g_string_free (string, FALSE);
2228 #pragma GCC diagnostic pop
2231 * g_format_size_for_display:
2232 * @size: a size in bytes
2234 * Formats a size (for example the size of a file) into a human
2235 * readable string. Sizes are rounded to the nearest size prefix
2236 * (KB, MB, GB) and are displayed rounded to the nearest tenth.
2237 * E.g. the file size 3292528 bytes will be converted into the
2240 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2242 * This string should be freed with g_free() when not needed any longer.
2244 * Returns: a newly-allocated formatted string containing a human
2245 * readable file size
2249 * Deprecated:2.30: This function is broken due to its use of SI
2250 * suffixes to denote IEC units. Use g_format_size() instead.
2253 g_format_size_for_display (goffset size)
2255 if (size < (goffset) KIBIBYTE_FACTOR)
2256 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
2259 gdouble displayed_size;
2261 if (size < (goffset) MEBIBYTE_FACTOR)
2263 displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
2264 /* Translators: this is from the deprecated function g_format_size_for_display() which uses 'KB' to
2265 * mean 1024 bytes. I am aware that 'KB' is not correct, but it has been preserved for reasons of
2266 * compatibility. Users will not see this string unless a program is using this deprecated function.
2267 * Please translate as literally as possible.
2269 return g_strdup_printf (_("%.1f KB"), displayed_size);
2271 else if (size < (goffset) GIBIBYTE_FACTOR)
2273 displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
2274 return g_strdup_printf (_("%.1f MB"), displayed_size);
2276 else if (size < (goffset) TEBIBYTE_FACTOR)
2278 displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
2279 return g_strdup_printf (_("%.1f GB"), displayed_size);
2281 else if (size < (goffset) PEBIBYTE_FACTOR)
2283 displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
2284 return g_strdup_printf (_("%.1f TB"), displayed_size);
2286 else if (size < (goffset) EXBIBYTE_FACTOR)
2288 displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
2289 return g_strdup_printf (_("%.1f PB"), displayed_size);
2293 displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
2294 return g_strdup_printf (_("%.1f EB"), displayed_size);
2299 #if defined (G_OS_WIN32) && !defined (_WIN64)
2301 /* Binary compatibility versions. Not for newly compiled code. */
2303 _GLIB_EXTERN const gchar *g_get_user_name_utf8 (void);
2304 _GLIB_EXTERN const gchar *g_get_real_name_utf8 (void);
2305 _GLIB_EXTERN const gchar *g_get_home_dir_utf8 (void);
2306 _GLIB_EXTERN const gchar *g_get_tmp_dir_utf8 (void);
2307 _GLIB_EXTERN gchar *g_find_program_in_path_utf8 (const gchar *program);
2310 g_find_program_in_path_utf8 (const gchar *program)
2312 return g_find_program_in_path (program);
2315 const gchar *g_get_user_name_utf8 (void) { return g_get_user_name (); }
2316 const gchar *g_get_real_name_utf8 (void) { return g_get_real_name (); }
2317 const gchar *g_get_home_dir_utf8 (void) { return g_get_home_dir (); }
2318 const gchar *g_get_tmp_dir_utf8 (void) { return g_get_tmp_dir (); }
2324 * Returns %TRUE if the current process was executed as setuid (or an
2325 * equivalent __libc_enable_secure is available). See:
2326 * http://osdir.com/ml/linux.lfs.hardened/2007-04/msg00032.html
2329 g_check_setuid (void)
2331 /* TODO: get __libc_enable_secure exported from glibc.
2332 * See http://www.openwall.com/lists/owl-dev/2012/08/14/1
2334 #if 0 && defined(HAVE_LIBC_ENABLE_SECURE)
2336 /* See glibc/include/unistd.h */
2337 extern int __libc_enable_secure;
2338 return __libc_enable_secure;
2340 #elif defined(HAVE_ISSETUGID)
2341 /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
2342 return issetugid ();
2343 #elif defined(G_OS_UNIX)
2344 uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
2345 gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
2347 static gsize check_setuid_initialised;
2348 static gboolean is_setuid;
2350 if (g_once_init_enter (&check_setuid_initialised))
2352 #ifdef HAVE_GETRESUID
2353 /* These aren't in the header files, so we prototype them here.
2355 int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
2356 int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);
2358 if (getresuid (&ruid, &euid, &suid) != 0 ||
2359 getresgid (&rgid, &egid, &sgid) != 0)
2360 #endif /* HAVE_GETRESUID */
2362 suid = ruid = getuid ();
2363 sgid = rgid = getgid ();
2368 is_setuid = (ruid != euid || ruid != suid ||
2369 rgid != egid || rgid != sgid);
2371 g_once_init_leave (&check_setuid_initialised, 1);