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.
41 #include <ctype.h> /* For tolower() */
43 #include <sys/types.h>
48 #include <sys/types.h>
49 #ifdef HAVE_SYS_PARAM_H
50 #include <sys/param.h>
52 #ifdef HAVE_CRT_EXTERNS_H
53 #include <crt_externs.h> /* for _NSGetEnviron */
56 /* implement gutils's inline functions
58 #define G_IMPLEMENT_INLINES 1
62 #include "glib-init.h"
63 #include "glib-private.h"
65 #include "gfileutils.h"
69 #include "gtestutils.h"
71 #include "gstrfuncs.h"
75 #ifdef G_PLATFORM_WIN32
83 * @title: Miscellaneous Utility Functions
84 * @short_description: a selection of portable utility functions
86 * These are portable utility functions.
89 #ifdef G_PLATFORM_WIN32
91 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
92 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
93 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
95 # include <lmcons.h> /* For UNLEN */
96 #endif /* G_PLATFORM_WIN32 */
101 /* older SDK (e.g. msvc 5.0) does not have these*/
102 # ifndef CSIDL_MYMUSIC
103 # define CSIDL_MYMUSIC 13
105 # ifndef CSIDL_MYVIDEO
106 # define CSIDL_MYVIDEO 14
108 # ifndef CSIDL_INTERNET_CACHE
109 # define CSIDL_INTERNET_CACHE 32
111 # ifndef CSIDL_COMMON_APPDATA
112 # define CSIDL_COMMON_APPDATA 35
114 # ifndef CSIDL_MYPICTURES
115 # define CSIDL_MYPICTURES 0x27
117 # ifndef CSIDL_COMMON_DOCUMENTS
118 # define CSIDL_COMMON_DOCUMENTS 46
120 # ifndef CSIDL_PROFILE
121 # define CSIDL_PROFILE 40
123 # include <process.h>
127 #include <CoreServices/CoreServices.h>
131 #include <langinfo.h>
134 #ifdef G_PLATFORM_WIN32
137 _glib_get_dll_directory (void)
141 wchar_t wc_fn[MAX_PATH];
144 if (glib_dll == NULL)
148 /* This code is different from that in
149 * g_win32_get_package_installation_directory_of_module() in that
150 * here we return the actual folder where the GLib DLL is. We don't
151 * do the check for it being in a "bin" or "lib" subfolder and then
152 * returning the parent of that.
154 * In a statically built GLib, glib_dll will be NULL and we will
155 * thus look up the application's .exe file's location.
157 if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
160 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
162 p = strrchr (retval, G_DIR_SEPARATOR);
175 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
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 * In order to use this function, you must include
186 * <filename>string.h</filename> yourself, because this macro will
187 * typically simply resolve to memmove() and GLib does not include
188 * <filename>string.h</filename> for you.
191 g_memmove (gpointer dest,
195 gchar* destptr = dest;
196 const gchar* srcptr = src;
197 if (src + len < dest || dest + len < src)
199 bcopy (src, dest, len);
202 else if (dest <= src)
205 *(destptr++) = *(srcptr++);
212 *(--destptr) = *(--srcptr);
215 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
223 * @func: (scope async): the function to call on normal program termination.
225 * Specifies a function to be called at normal program termination.
227 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
228 * macro that maps to a call to the atexit() function in the C
229 * library. This means that in case the code that calls g_atexit(),
230 * i.e. atexit(), is in a DLL, the function will be called when the
231 * DLL is detached from the program. This typically makes more sense
232 * than that the function is called when the GLib DLL is detached,
233 * which happened earlier when g_atexit() was a function in the GLib
236 * The behaviour of atexit() in the context of dynamically loaded
237 * modules is not formally specified and varies wildly.
239 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
240 * loaded module which is unloaded before the program terminates might
241 * well cause a crash at program exit.
243 * Some POSIX systems implement atexit() like Windows, and have each
244 * dynamically loaded module maintain an own atexit chain that is
245 * called when the module is unloaded.
247 * On other POSIX systems, before a dynamically loaded module is
248 * unloaded, the registered atexit functions (if any) residing in that
249 * module are called, regardless where the code that registered them
250 * resided. This is presumably the most robust approach.
252 * As can be seen from the above, for portability it's best to avoid
253 * calling g_atexit() (or atexit()) except in the main executable of a
256 * Deprecated:2.32: It is best to avoid g_atexit().
259 g_atexit (GVoidFunc func)
262 const gchar *error = NULL;
264 /* keep this in sync with glib.h */
266 #ifdef G_NATIVE_ATEXIT
267 result = ATEXIT (func);
269 error = g_strerror (errno);
270 #elif defined (HAVE_ATEXIT)
271 # ifdef NeXT /* @#%@! NeXTStep */
272 result = !atexit ((void (*)(void)) func);
274 error = g_strerror (errno);
276 result = atexit ((void (*)(void)) func);
278 error = g_strerror (errno);
280 #elif defined (HAVE_ON_EXIT)
281 result = on_exit ((void (*)(int, void *)) func, NULL);
283 error = g_strerror (errno);
286 error = "no implementation";
287 #endif /* G_NATIVE_ATEXIT */
290 g_error ("Could not register atexit() function: %s", error);
293 /* Based on execvp() from GNU Libc.
294 * Some of this code is cut-and-pasted into gspawn.c
298 my_strchrnul (const gchar *str,
301 gchar *p = (gchar*)str;
302 while (*p && (*p != c))
310 static gchar *inner_find_program_in_path (const gchar *program);
313 g_find_program_in_path (const gchar *program)
315 const gchar *last_dot = strrchr (program, '.');
317 if (last_dot == NULL ||
318 strchr (last_dot, '\\') != NULL ||
319 strchr (last_dot, '/') != NULL)
321 const gint program_length = strlen (program);
322 gchar *pathext = g_build_path (";",
323 ".exe;.cmd;.bat;.com",
324 g_getenv ("PATHEXT"),
327 gchar *decorated_program;
333 gchar *q = my_strchrnul (p, ';');
335 decorated_program = g_malloc (program_length + (q-p) + 1);
336 memcpy (decorated_program, program, program_length);
337 memcpy (decorated_program+program_length, p, q-p);
338 decorated_program [program_length + (q-p)] = '\0';
340 retval = inner_find_program_in_path (decorated_program);
341 g_free (decorated_program);
349 } while (*p++ != '\0');
354 return inner_find_program_in_path (program);
360 * g_find_program_in_path:
361 * @program: a program name in the GLib file name encoding
363 * Locates the first executable named @program in the user's path, in the
364 * same way that execvp() would locate it. Returns an allocated string
365 * with the absolute path name, or %NULL if the program is not found in
366 * the path. If @program is already an absolute path, returns a copy of
367 * @program if @program exists and is executable, and %NULL otherwise.
369 * On Windows, if @program does not have a file type suffix, tries
370 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
371 * the <envar>PATHEXT</envar> environment variable.
373 * On Windows, it looks for the file in the same way as CreateProcess()
374 * would. This means first in the directory where the executing
375 * program was loaded from, then in the current directory, then in the
376 * Windows 32-bit system directory, then in the Windows directory, and
377 * finally in the directories in the <envar>PATH</envar> environment
378 * variable. If the program is found, the return value contains the
379 * full name including the type suffix.
381 * Return value: a newly-allocated string with the absolute path, or %NULL
385 inner_find_program_in_path (const gchar *program)
388 g_find_program_in_path (const gchar *program)
391 const gchar *path, *p;
392 gchar *name, *freeme;
394 const gchar *path_copy;
395 gchar *filename = NULL, *appdir = NULL;
396 gchar *sysdir = NULL, *windir = NULL;
398 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
404 g_return_val_if_fail (program != NULL, NULL);
406 /* If it is an absolute path, or a relative path including subdirectories,
407 * don't look in PATH.
409 if (g_path_is_absolute (program)
410 || strchr (program, G_DIR_SEPARATOR) != NULL
412 || strchr (program, '/') != NULL
416 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
417 !g_file_test (program, G_FILE_TEST_IS_DIR))
418 return g_strdup (program);
423 path = g_getenv ("PATH");
424 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
427 /* There is no `PATH' in the environment. The default
428 * search path in GNU libc is the current directory followed by
429 * the path `confstr' returns for `_CS_PATH'.
432 /* In GLib we put . last, for security, and don't use the
433 * unportable confstr(); UNIX98 does not actually specify
434 * what to search if PATH is unset. POSIX may, dunno.
437 path = "/bin:/usr/bin:.";
440 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
441 if (n > 0 && n < MAXPATHLEN)
442 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
444 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
445 if (n > 0 && n < MAXPATHLEN)
446 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
448 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
449 if (n > 0 && n < MAXPATHLEN)
450 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
454 appdir = g_path_get_dirname (filename);
458 path = g_strdup (path);
462 const gchar *tem = path;
463 path = g_strconcat (windir, ";", path, NULL);
464 g_free ((gchar *) tem);
470 const gchar *tem = path;
471 path = g_strconcat (sysdir, ";", path, NULL);
472 g_free ((gchar *) tem);
477 const gchar *tem = path;
478 path = g_strconcat (".;", path, NULL);
479 g_free ((gchar *) tem);
484 const gchar *tem = path;
485 path = g_strconcat (appdir, ";", path, NULL);
486 g_free ((gchar *) tem);
493 len = strlen (program) + 1;
494 pathlen = strlen (path);
495 freeme = name = g_malloc (pathlen + len + 1);
497 /* Copy the file name at the top, including '\0' */
498 memcpy (name + pathlen + 1, program, len);
499 name = name + pathlen;
500 /* And add the slash before the filename */
501 *name = G_DIR_SEPARATOR;
509 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
512 /* Two adjacent colons, or a colon at the beginning or the end
513 * of `PATH' means to search the current directory.
517 startp = memcpy (name - (p - path), path, p - path);
519 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
520 !g_file_test (startp, G_FILE_TEST_IS_DIR))
523 ret = g_strdup (startp);
526 g_free ((gchar *) path_copy);
531 while (*p++ != '\0');
535 g_free ((gchar *) path_copy);
543 * @mask: a #gulong containing flags
544 * @nth_bit: the index of the bit to start the search from
546 * Find the position of the first bit set in @mask, searching
547 * from (but not including) @nth_bit upwards. Bits are numbered
548 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
549 * usually). To start searching from the 0th bit, set @nth_bit to -1.
551 * Returns: the index of the first bit set which is higher than @nth_bit
556 * @mask: a #gulong containing flags
557 * @nth_bit: the index of the bit to start the search from
559 * Find the position of the first bit set in @mask, searching
560 * from (but not including) @nth_bit downwards. Bits are numbered
561 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
562 * usually). To start searching from the last bit, set @nth_bit to
563 * -1 or GLIB_SIZEOF_LONG * 8.
565 * Returns: the index of the first bit set which is lower than @nth_bit
572 * Gets the number of bits used to hold @number,
573 * e.g. if @number is 4, 3 bits are needed.
575 * Returns: the number of bits used to hold @number
578 G_LOCK_DEFINE_STATIC (g_utils_global);
580 static gchar *g_tmp_dir = NULL;
581 static gchar *g_user_name = NULL;
582 static gchar *g_real_name = NULL;
583 static gchar *g_home_dir = NULL;
584 static gchar *g_host_name = NULL;
586 static gchar *g_user_data_dir = NULL;
587 static gchar **g_system_data_dirs = NULL;
588 static gchar *g_user_cache_dir = NULL;
589 static gchar *g_user_config_dir = NULL;
590 static gchar **g_system_config_dirs = NULL;
592 static gchar **g_user_special_dirs = NULL;
594 /* fifteen minutes of fame for everybody */
595 #define G_USER_DIRS_EXPIRE 15 * 60
600 get_special_folder (int csidl)
602 wchar_t path[MAX_PATH+1];
604 LPITEMIDLIST pidl = NULL;
606 gchar *retval = NULL;
608 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
611 b = SHGetPathFromIDListW (pidl, path);
613 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
614 CoTaskMemFree (pidl);
620 get_windows_directory_root (void)
622 wchar_t wwindowsdir[MAX_PATH];
624 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
626 /* Usually X:\Windows, but in terminal server environments
627 * might be an UNC path, AFAIK.
629 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
632 if (windowsdir == NULL)
633 return g_strdup ("C:\\");
635 p = (char *) g_path_skip_root (windowsdir);
636 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
642 return g_strdup ("C:\\");
647 /* HOLDS: g_utils_global_lock */
649 g_get_any_init_do (void)
653 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
655 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
658 g_tmp_dir = g_strdup (g_getenv ("TMP"));
661 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
664 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
668 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
671 g_tmp_dir = get_windows_directory_root ();
676 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
680 g_tmp_dir = g_strdup (P_tmpdir);
681 k = strlen (g_tmp_dir);
682 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
683 g_tmp_dir[k - 1] = '\0';
687 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
690 g_tmp_dir = g_strdup ("/tmp");
692 #endif /* !G_OS_WIN32 */
694 /* We first check HOME and use it if it is set */
695 g_home_dir = g_strdup (g_getenv ("HOME"));
698 /* Only believe HOME if it is an absolute path and exists.
700 * We only do this check on Windows for a couple of reasons.
701 * Historically, we only did it there because we used to ignore $HOME
702 * on UNIX. There are concerns about enabling it now on UNIX because
703 * of things like autofs. In short, if the user has a bogus value in
704 * $HOME then they get what they pay for...
708 if (!(g_path_is_absolute (g_home_dir) &&
709 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
716 /* In case HOME is Unix-style (it happens), convert it to
722 while ((p = strchr (g_home_dir, '/')) != NULL)
728 /* USERPROFILE is probably the closest equivalent to $HOME? */
729 if (g_getenv ("USERPROFILE") != NULL)
730 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
734 g_home_dir = get_special_folder (CSIDL_PROFILE);
737 g_home_dir = get_windows_directory_root ();
738 #endif /* G_OS_WIN32 */
742 struct passwd *pw = NULL;
743 gpointer buffer = NULL;
747 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
749 # ifdef _SC_GETPW_R_SIZE_MAX
750 /* This reurns the maximum length */
751 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
755 # else /* _SC_GETPW_R_SIZE_MAX */
757 # endif /* _SC_GETPW_R_SIZE_MAX */
759 logname = (gchar *) g_getenv ("LOGNAME");
764 /* we allocate 6 extra bytes to work around a bug in
765 * Mac OS < 10.3. See #156446
767 buffer = g_malloc (bufsize + 6);
770 # ifdef HAVE_POSIX_GETPWUID_R
772 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
773 if (!pw || (pw->pw_uid != getuid ())) {
774 /* LOGNAME is lying, fall back to looking up the uid */
775 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
778 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
780 error = error < 0 ? errno : error;
781 # else /* HAVE_NONPOSIX_GETPWUID_R */
782 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
783 # if defined(_AIX) || defined(__hpux)
784 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
785 pw = error == 0 ? &pwd : NULL;
788 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
789 if (!pw || (pw->pw_uid != getuid ())) {
790 /* LOGNAME is lying, fall back to looking up the uid */
791 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
794 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
796 error = pw ? 0 : errno;
798 # endif /* HAVE_NONPOSIX_GETPWUID_R */
802 /* we bail out prematurely if the user id can't be found
803 * (should be pretty rare case actually), or if the buffer
804 * should be sufficiently big and lookups are still not
807 if (error == 0 || error == ENOENT)
809 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
813 if (bufsize > 32 * 1024)
815 g_warning ("getpwuid_r(): failed due to: %s.",
824 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
829 pw = getpwuid (getuid ());
834 g_user_name = g_strdup (pw->pw_name);
836 if (pw->pw_gecos && *pw->pw_gecos != '\0')
838 gchar **gecos_fields;
841 /* split the gecos field and substitute '&' */
842 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
843 name_parts = g_strsplit (gecos_fields[0], "&", 0);
844 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
845 g_real_name = g_strjoinv (pw->pw_name, name_parts);
846 g_strfreev (gecos_fields);
847 g_strfreev (name_parts);
851 g_home_dir = g_strdup (pw->pw_dir);
856 #else /* !HAVE_PWD_H */
861 wchar_t buffer[UNLEN+1];
863 if (GetUserNameW (buffer, (LPDWORD) &len))
865 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
866 g_real_name = g_strdup (g_user_name);
869 #endif /* G_OS_WIN32 */
871 #endif /* !HAVE_PWD_H */
874 /* change '\\' in %HOME% to '/' */
875 g_strdelimit (g_home_dir, "\\",'/');
878 g_user_name = g_strdup ("somebody");
880 g_real_name = g_strdup ("Unknown");
884 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
886 DWORD size = sizeof (hostname);
887 gboolean hostname_fail = (!GetComputerName (hostname, &size));
889 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
893 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
894 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
895 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
898 g_tmp_dir_cp = g_strdup ("\\");
900 g_user_name_cp = g_strdup ("somebody");
902 g_real_name_cp = g_strdup ("Unknown");
904 /* home_dir might be NULL, unlike tmp_dir, user_name and
908 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
910 g_home_dir_cp = NULL;
911 #endif /* G_OS_WIN32 */
915 g_get_any_init (void)
918 g_get_any_init_do ();
922 g_get_any_init_locked (void)
924 G_LOCK (g_utils_global);
926 G_UNLOCK (g_utils_global);
933 * Gets the user name of the current user. The encoding of the returned
934 * string is system-defined. On UNIX, it might be the preferred file name
935 * encoding, or something else, and there is no guarantee that it is even
936 * consistent on a machine. On Windows, it is always UTF-8.
938 * Returns: the user name of the current user.
941 g_get_user_name (void)
943 g_get_any_init_locked ();
950 * Gets the real name of the user. This usually comes from the user's entry
951 * in the <filename>passwd</filename> file. The encoding of the returned
952 * string is system-defined. (On Windows, it is, however, always UTF-8.)
953 * If the real user name cannot be determined, the string "Unknown" is
956 * Returns: the user's real name.
959 g_get_real_name (void)
961 g_get_any_init_locked ();
968 * Gets the current user's home directory.
970 * As with most UNIX tools, this function will return the value of the
971 * <envar>HOME</envar> environment variable if it is set to an existing
972 * absolute path name, falling back to the <filename>passwd</filename>
973 * file in the case that it is unset.
975 * If the path given in <envar>HOME</envar> is non-absolute, does not
976 * exist, or is not a directory, the result is undefined.
979 * Before version 2.36 this function would ignore the
980 * <envar>HOME</envar> environment variable, taking the value from the
981 * <filename>passwd</filename> database instead. This was changed to
982 * increase the compatibility of GLib with other programs (and the XDG
983 * basedir specification) and to increase testability of programs
984 * based on GLib (by making it easier to run them from test
987 * If your program has a strong requirement for either the new or the
988 * old behaviour (and if you don't wish to increase your GLib
989 * dependency to ensure that the new behaviour is in effect) then you
990 * should either directly check the <envar>HOME</envar> environment
991 * variable yourself or unset it before calling any functions in GLib.
994 * Returns: the current user's home directory
997 g_get_home_dir (void)
999 g_get_any_init_locked ();
1006 * Gets the directory to use for temporary files. This is found from
1007 * inspecting the environment variables <envar>TMPDIR</envar>,
1008 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1009 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1010 * The encoding of the returned string is system-defined. On Windows,
1011 * it is always UTF-8. The return value is never %NULL or the empty string.
1013 * Returns: the directory to use for temporary files.
1016 g_get_tmp_dir (void)
1018 g_get_any_init_locked ();
1025 * Return a name for the machine.
1027 * The returned name is not necessarily a fully-qualified domain name,
1028 * or even present in DNS or some other name service at all. It need
1029 * not even be unique on your local network or site, but usually it
1030 * is. Callers should not rely on the return value having any specific
1031 * properties like uniqueness for security purposes. Even if the name
1032 * of the machine is changed while an application is running, the
1033 * return value from this function does not change. The returned
1034 * string is owned by GLib and should not be modified or freed. If no
1035 * name can be determined, a default fixed string "localhost" is
1038 * Returns: the host name of the machine.
1043 g_get_host_name (void)
1045 g_get_any_init_locked ();
1049 G_LOCK_DEFINE_STATIC (g_prgname);
1050 static gchar *g_prgname = NULL;
1055 * Gets the name of the program. This name should <emphasis>not</emphasis>
1056 * be localized, contrast with g_get_application_name().
1057 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1058 * which is called by gtk_init(). The program name is found by taking
1059 * the last component of <literal>argv[0]</literal>.)
1061 * Returns: the name of the program. The returned string belongs
1062 * to GLib and must not be modified or freed.
1065 g_get_prgname (void)
1071 if (g_prgname == NULL)
1073 static gboolean beenhere = FALSE;
1077 gchar *utf8_buf = NULL;
1078 wchar_t buf[MAX_PATH+1];
1081 if (GetModuleFileNameW (GetModuleHandle (NULL),
1082 buf, G_N_ELEMENTS (buf)) > 0)
1083 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1087 g_prgname = g_path_get_basename (utf8_buf);
1094 G_UNLOCK (g_prgname);
1101 * @prgname: the name of the program.
1103 * Sets the name of the program. This name should <emphasis>not</emphasis>
1104 * be localized, contrast with g_set_application_name(). Note that for
1105 * thread-safety reasons this function can only be called once.
1108 g_set_prgname (const gchar *prgname)
1112 g_prgname = g_strdup (prgname);
1113 G_UNLOCK (g_prgname);
1116 G_LOCK_DEFINE_STATIC (g_application_name);
1117 static gchar *g_application_name = NULL;
1120 * g_get_application_name:
1122 * Gets a human-readable name for the application, as set by
1123 * g_set_application_name(). This name should be localized if
1124 * possible, and is intended for display to the user. Contrast with
1125 * g_get_prgname(), which gets a non-localized name. If
1126 * g_set_application_name() has not been called, returns the result of
1127 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1130 * Return value: human-readable application name. may return %NULL
1135 g_get_application_name (void)
1139 G_LOCK (g_application_name);
1140 retval = g_application_name;
1141 G_UNLOCK (g_application_name);
1144 return g_get_prgname ();
1150 * g_set_application_name:
1151 * @application_name: localized name of the application
1153 * Sets a human-readable name for the application. This name should be
1154 * localized if possible, and is intended for display to the user.
1155 * Contrast with g_set_prgname(), which sets a non-localized name.
1156 * g_set_prgname() will be called automatically by gtk_init(),
1157 * but g_set_application_name() will not.
1159 * Note that for thread safety reasons, this function can only
1162 * The application name will be used in contexts such as error messages,
1163 * or when displaying an application's name in the task list.
1168 g_set_application_name (const gchar *application_name)
1170 gboolean already_set = FALSE;
1172 G_LOCK (g_application_name);
1173 if (g_application_name)
1176 g_application_name = g_strdup (application_name);
1177 G_UNLOCK (g_application_name);
1180 g_warning ("g_set_application_name() called multiple times");
1184 * g_get_user_data_dir:
1186 * Returns a base directory in which to access application data such
1187 * as icons that is customized for a particular user.
1189 * On UNIX platforms this is determined using the mechanisms described in
1190 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1191 * XDG Base Directory Specification</ulink>.
1192 * In this case the directory retrieved will be XDG_DATA_HOME.
1194 * On Windows this is the folder to use for local (as opposed to
1195 * roaming) application data. See documentation for
1196 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1197 * what g_get_user_config_dir() returns.
1199 * Return value: a string owned by GLib that must not be modified
1204 g_get_user_data_dir (void)
1208 G_LOCK (g_utils_global);
1210 if (!g_user_data_dir)
1213 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1215 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1217 if (data_dir && data_dir[0])
1218 data_dir = g_strdup (data_dir);
1220 if (!data_dir || !data_dir[0])
1225 data_dir = g_build_filename (g_home_dir, ".local",
1228 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
1232 g_user_data_dir = data_dir;
1235 data_dir = g_user_data_dir;
1237 G_UNLOCK (g_utils_global);
1243 g_init_user_config_dir (void)
1247 if (!g_user_config_dir)
1250 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1252 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1254 if (config_dir && config_dir[0])
1255 config_dir = g_strdup (config_dir);
1257 if (!config_dir || !config_dir[0])
1262 config_dir = g_build_filename (g_home_dir, ".config", NULL);
1264 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
1267 g_user_config_dir = config_dir;
1272 * g_get_user_config_dir:
1274 * Returns a base directory in which to store user-specific application
1275 * configuration information such as user preferences and settings.
1277 * On UNIX platforms this is determined using the mechanisms described in
1278 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1279 * XDG Base Directory Specification</ulink>.
1280 * In this case the directory retrieved will be XDG_CONFIG_HOME.
1282 * On Windows this is the folder to use for local (as opposed to
1283 * roaming) application data. See documentation for
1284 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1285 * what g_get_user_data_dir() returns.
1287 * Return value: a string owned by GLib that must not be modified
1292 g_get_user_config_dir (void)
1294 G_LOCK (g_utils_global);
1296 g_init_user_config_dir ();
1298 G_UNLOCK (g_utils_global);
1300 return g_user_config_dir;
1304 * g_get_user_cache_dir:
1306 * Returns a base directory in which to store non-essential, cached
1307 * data specific to particular user.
1309 * On UNIX platforms this is determined using the mechanisms described in
1310 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1311 * XDG Base Directory Specification</ulink>.
1312 * In this case the directory retrieved will be XDG_CACHE_HOME.
1314 * On Windows is the directory that serves as a common repository for
1315 * temporary Internet files. A typical path is
1316 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
1317 * See documentation for CSIDL_INTERNET_CACHE.
1319 * Return value: a string owned by GLib that must not be modified
1324 g_get_user_cache_dir (void)
1328 G_LOCK (g_utils_global);
1330 if (!g_user_cache_dir)
1333 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1335 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1337 if (cache_dir && cache_dir[0])
1338 cache_dir = g_strdup (cache_dir);
1340 if (!cache_dir || !cache_dir[0])
1345 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
1347 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
1349 g_user_cache_dir = cache_dir;
1352 cache_dir = g_user_cache_dir;
1354 G_UNLOCK (g_utils_global);
1360 * g_get_user_runtime_dir:
1362 * Returns a directory that is unique to the current user on the local
1365 * On UNIX platforms this is determined using the mechanisms described in
1366 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1367 * XDG Base Directory Specification</ulink>. This is the directory
1368 * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
1369 * In the case that this variable is not set, GLib will issue a warning
1370 * message to stderr and return the value of g_get_user_cache_dir().
1372 * On Windows this is the folder to use for local (as opposed to
1373 * roaming) application data. See documentation for
1374 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1375 * what g_get_user_config_dir() returns.
1377 * Returns: a string owned by GLib that must not be modified or freed.
1382 g_get_user_runtime_dir (void)
1385 static const gchar *runtime_dir;
1386 static gsize initialised;
1388 if (g_once_init_enter (&initialised))
1390 runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
1392 g_once_init_leave (&initialised, 1);
1398 /* Both fallback for UNIX and the default
1399 * in Windows: use the user cache directory.
1403 return g_get_user_cache_dir ();
1409 find_folder (OSType type)
1411 gchar *filename = NULL;
1414 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
1416 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
1420 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
1424 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
1428 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
1430 CFStringGetCString (path, filename,
1431 CFStringGetLength (path) * 3 + 1,
1432 kCFStringEncodingUTF8);
1446 load_user_special_dirs (void)
1448 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
1449 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
1450 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
1451 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
1452 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
1453 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
1454 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
1455 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
1458 #endif /* HAVE_CARBON */
1460 #if defined(G_OS_WIN32)
1462 load_user_special_dirs (void)
1464 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1468 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
1470 static const GUID FOLDERID_Downloads =
1471 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1472 static const GUID FOLDERID_Public =
1473 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1477 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
1478 "SHGetKnownFolderPath");
1480 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1481 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
1483 if (p_SHGetKnownFolderPath == NULL)
1485 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1490 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1493 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1494 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
1495 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1496 CoTaskMemFree (wcp);
1499 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1502 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
1503 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
1505 if (p_SHGetKnownFolderPath == NULL)
1508 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1513 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
1516 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1517 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
1518 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1519 CoTaskMemFree (wcp);
1522 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1525 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
1526 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
1528 #endif /* G_OS_WIN32 */
1530 static void g_init_user_config_dir (void);
1532 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
1534 /* adapted from xdg-user-dir-lookup.c
1536 * Copyright (C) 2007 Red Hat Inc.
1538 * Permission is hereby granted, free of charge, to any person
1539 * obtaining a copy of this software and associated documentation files
1540 * (the "Software"), to deal in the Software without restriction,
1541 * including without limitation the rights to use, copy, modify, merge,
1542 * publish, distribute, sublicense, and/or sell copies of the Software,
1543 * and to permit persons to whom the Software is furnished to do so,
1544 * subject to the following conditions:
1546 * The above copyright notice and this permission notice shall be
1547 * included in all copies or substantial portions of the Software.
1549 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1550 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1551 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1552 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1553 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1554 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1555 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1559 load_user_special_dirs (void)
1566 g_init_user_config_dir ();
1567 config_file = g_build_filename (g_user_config_dir,
1571 if (!g_file_get_contents (config_file, &data, NULL, NULL))
1573 g_free (config_file);
1577 lines = g_strsplit (data, "\n", -1);
1578 n_lines = g_strv_length (lines);
1581 for (i = 0; i < n_lines; i++)
1583 gchar *buffer = lines[i];
1586 gboolean is_relative = FALSE;
1587 GUserDirectory directory;
1589 /* Remove newline at end */
1590 len = strlen (buffer);
1591 if (len > 0 && buffer[len - 1] == '\n')
1592 buffer[len - 1] = 0;
1595 while (*p == ' ' || *p == '\t')
1598 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
1600 directory = G_USER_DIRECTORY_DESKTOP;
1601 p += strlen ("XDG_DESKTOP_DIR");
1603 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
1605 directory = G_USER_DIRECTORY_DOCUMENTS;
1606 p += strlen ("XDG_DOCUMENTS_DIR");
1608 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
1610 directory = G_USER_DIRECTORY_DOWNLOAD;
1611 p += strlen ("XDG_DOWNLOAD_DIR");
1613 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
1615 directory = G_USER_DIRECTORY_MUSIC;
1616 p += strlen ("XDG_MUSIC_DIR");
1618 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
1620 directory = G_USER_DIRECTORY_PICTURES;
1621 p += strlen ("XDG_PICTURES_DIR");
1623 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
1625 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
1626 p += strlen ("XDG_PUBLICSHARE_DIR");
1628 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
1630 directory = G_USER_DIRECTORY_TEMPLATES;
1631 p += strlen ("XDG_TEMPLATES_DIR");
1633 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
1635 directory = G_USER_DIRECTORY_VIDEOS;
1636 p += strlen ("XDG_VIDEOS_DIR");
1641 while (*p == ' ' || *p == '\t')
1648 while (*p == ' ' || *p == '\t')
1655 if (strncmp (p, "$HOME", 5) == 0)
1663 d = strrchr (p, '"');
1670 /* remove trailing slashes */
1672 if (d[len - 1] == '/')
1678 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
1681 g_user_special_dirs[directory] = g_strdup (d);
1685 g_free (config_file);
1688 #endif /* G_OS_UNIX && !HAVE_CARBON */
1692 * g_reload_user_special_dirs_cache:
1694 * Resets the cache used for g_get_user_special_dir(), so
1695 * that the latest on-disk version is used. Call this only
1696 * if you just changed the data on disk yourself.
1698 * Due to threadsafety issues this may cause leaking of strings
1699 * that were previously returned from g_get_user_special_dir()
1700 * that can't be freed. We ensure to only leak the data for
1701 * the directories that actually changed value though.
1706 g_reload_user_special_dirs_cache (void)
1710 G_LOCK (g_utils_global);
1712 if (g_user_special_dirs != NULL)
1714 /* save a copy of the pointer, to check if some memory can be preserved */
1715 char **old_g_user_special_dirs = g_user_special_dirs;
1718 /* recreate and reload our cache */
1719 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1720 load_user_special_dirs ();
1722 /* only leak changed directories */
1723 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
1725 old_val = old_g_user_special_dirs[i];
1726 if (g_user_special_dirs[i] == NULL)
1728 g_user_special_dirs[i] = old_val;
1730 else if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
1733 g_free (g_user_special_dirs[i]);
1734 g_user_special_dirs[i] = old_val;
1740 /* free the old array */
1741 g_free (old_g_user_special_dirs);
1744 G_UNLOCK (g_utils_global);
1748 * g_get_user_special_dir:
1749 * @directory: the logical id of special directory
1751 * Returns the full path of a special directory using its logical id.
1753 * On Unix this is done using the XDG special user directories.
1754 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
1755 * falls back to <filename>$HOME/Desktop</filename> when XDG special
1756 * user directories have not been set up.
1758 * Depending on the platform, the user might be able to change the path
1759 * of the special directory without requiring the session to restart; GLib
1760 * will not reflect any change once the special directories are loaded.
1762 * Return value: the path to the specified special directory, or %NULL
1763 * if the logical id was not found. The returned string is owned by
1764 * GLib and should not be modified or freed.
1769 g_get_user_special_dir (GUserDirectory directory)
1771 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
1772 directory < G_USER_N_DIRECTORIES, NULL);
1774 G_LOCK (g_utils_global);
1776 if (G_UNLIKELY (g_user_special_dirs == NULL))
1778 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1780 load_user_special_dirs ();
1782 /* Special-case desktop for historical compatibility */
1783 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
1787 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
1788 g_build_filename (g_home_dir, "Desktop", NULL);
1792 G_UNLOCK (g_utils_global);
1794 return g_user_special_dirs[directory];
1799 #undef g_get_system_data_dirs
1802 get_module_for_address (gconstpointer address)
1804 /* Holds the g_utils_global lock */
1806 static gboolean beenhere = FALSE;
1807 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
1808 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
1809 HMODULE hmodule = NULL;
1816 p_GetModuleHandleExA =
1817 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1818 "GetModuleHandleExA");
1822 if (p_GetModuleHandleExA == NULL ||
1823 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
1824 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
1827 MEMORY_BASIC_INFORMATION mbi;
1828 VirtualQuery (address, &mbi, sizeof (mbi));
1829 hmodule = (HMODULE) mbi.AllocationBase;
1836 get_module_share_dir (gconstpointer address)
1842 hmodule = get_module_for_address (address);
1843 if (hmodule == NULL)
1846 filename = g_win32_get_package_installation_directory_of_module (hmodule);
1847 retval = g_build_filename (filename, "share", NULL);
1853 const gchar * const *
1854 g_win32_get_system_data_dirs_for_module (void (*address_of_function)(void))
1858 static GHashTable *per_module_data_dirs = NULL;
1863 if (address_of_function)
1865 G_LOCK (g_utils_global);
1866 hmodule = get_module_for_address (address_of_function);
1867 if (hmodule != NULL)
1869 if (per_module_data_dirs == NULL)
1870 per_module_data_dirs = g_hash_table_new (NULL, NULL);
1873 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
1877 G_UNLOCK (g_utils_global);
1878 return (const gchar * const *) retval;
1884 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
1886 /* Documents and Settings\All Users\Application Data */
1887 p = get_special_folder (CSIDL_COMMON_APPDATA);
1889 g_array_append_val (data_dirs, p);
1891 /* Documents and Settings\All Users\Documents */
1892 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1894 g_array_append_val (data_dirs, p);
1896 /* Using the above subfolders of Documents and Settings perhaps
1897 * makes sense from a Windows perspective.
1899 * But looking at the actual use cases of this function in GTK+
1900 * and GNOME software, what we really want is the "share"
1901 * subdirectory of the installation directory for the package
1902 * our caller is a part of.
1904 * The address_of_function parameter, if non-NULL, points to a
1905 * function in the calling module. Use that to determine that
1906 * module's installation folder, and use its "share" subfolder.
1908 * Additionally, also use the "share" subfolder of the installation
1909 * locations of GLib and the .exe file being run.
1911 * To guard against none of the above being what is really wanted,
1912 * callers of this function should have Win32-specific code to look
1913 * up their installation folder themselves, and handle a subfolder
1914 * "share" of it in the same way as the folders returned from this
1918 p = get_module_share_dir (address_of_function);
1920 g_array_append_val (data_dirs, p);
1922 if (glib_dll != NULL)
1924 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
1925 p = g_build_filename (glib_root, "share", NULL);
1927 g_array_append_val (data_dirs, p);
1931 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
1932 p = g_build_filename (exe_root, "share", NULL);
1934 g_array_append_val (data_dirs, p);
1937 retval = (gchar **) g_array_free (data_dirs, FALSE);
1939 if (address_of_function)
1941 if (hmodule != NULL)
1942 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
1943 G_UNLOCK (g_utils_global);
1946 return (const gchar * const *) retval;
1952 * g_get_system_data_dirs:
1954 * Returns an ordered list of base directories in which to access
1955 * system-wide application data.
1957 * On UNIX platforms this is determined using the mechanisms described in
1958 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1959 * XDG Base Directory Specification</ulink>
1960 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
1962 * On Windows the first elements in the list are the Application Data
1963 * and Documents folders for All Users. (These can be determined only
1964 * on Windows 2000 or later and are not present in the list on other
1965 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
1966 * CSIDL_COMMON_DOCUMENTS.
1968 * Then follows the "share" subfolder in the installation folder for
1969 * the package containing the DLL that calls this function, if it can
1972 * Finally the list contains the "share" subfolder in the installation
1973 * folder for GLib, and in the installation folder for the package the
1974 * application's .exe file belongs to.
1976 * The installation folders above are determined by looking up the
1977 * folder where the module (DLL or EXE) in question is located. If the
1978 * folder's name is "bin", its parent is used, otherwise the folder
1981 * Note that on Windows the returned list can vary depending on where
1982 * this function is called.
1984 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
1985 * not be modified or freed.
1988 const gchar * const *
1989 g_get_system_data_dirs (void)
1991 gchar **data_dir_vector;
1993 G_LOCK (g_utils_global);
1995 if (!g_system_data_dirs)
1998 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2000 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2002 if (!data_dirs || !data_dirs[0])
2003 data_dirs = "/usr/local/share/:/usr/share/";
2005 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2008 g_system_data_dirs = data_dir_vector;
2011 data_dir_vector = g_system_data_dirs;
2013 G_UNLOCK (g_utils_global);
2015 return (const gchar * const *) data_dir_vector;
2019 * g_get_system_config_dirs:
2021 * Returns an ordered list of base directories in which to access
2022 * system-wide configuration information.
2024 * On UNIX platforms this is determined using the mechanisms described in
2025 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2026 * XDG Base Directory Specification</ulink>.
2027 * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
2029 * On Windows is the directory that contains application data for all users.
2030 * A typical path is C:\Documents and Settings\All Users\Application Data.
2031 * This folder is used for application data that is not user specific.
2032 * For example, an application can store a spell-check dictionary, a database
2033 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2034 * This information will not roam and is available to anyone using the computer.
2036 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
2037 * not be modified or freed.
2040 const gchar * const *
2041 g_get_system_config_dirs (void)
2043 gchar *conf_dirs, **conf_dir_vector;
2045 G_LOCK (g_utils_global);
2047 if (!g_system_config_dirs)
2050 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2053 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2058 /* Return empty list */
2059 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2062 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2064 if (!conf_dirs || !conf_dirs[0])
2065 conf_dirs = "/etc/xdg";
2067 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2070 g_system_config_dirs = conf_dir_vector;
2073 conf_dir_vector = g_system_config_dirs;
2074 G_UNLOCK (g_utils_global);
2076 return (const gchar * const *) conf_dir_vector;
2080 * g_nullify_pointer:
2081 * @nullify_location: the memory address of the pointer.
2083 * Set the pointer at the specified location to %NULL.
2086 g_nullify_pointer (gpointer *nullify_location)
2088 g_return_if_fail (nullify_location != NULL);
2090 *nullify_location = NULL;
2093 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2094 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2095 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2096 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2097 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2098 #define EXABYTE_FACTOR (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2100 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2101 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2102 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2103 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2104 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2105 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2109 * @size: a size in bytes
2111 * Formats a size (for example the size of a file) into a human readable
2112 * string. Sizes are rounded to the nearest size prefix (kB, MB, GB)
2113 * and are displayed rounded to the nearest tenth. E.g. the file size
2114 * 3292528 bytes will be converted into the string "3.2 MB".
2116 * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2118 * This string should be freed with g_free() when not needed any longer.
2120 * See g_format_size_full() for more options about how the size might be
2123 * Returns: a newly-allocated formatted string containing a human readable
2129 g_format_size (guint64 size)
2131 return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2136 * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2137 * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2138 * of the returned string. For example, "45.6 kB (45,612 bytes)".
2139 * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2140 * suffixes. IEC units should only be used for reporting things with
2141 * a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2142 * Network and storage sizes should be reported in the normal SI units.
2144 * Flags to modify the format of the string returned by g_format_size_full().
2148 * g_format_size_full:
2149 * @size: a size in bytes
2150 * @flags: #GFormatSizeFlags to modify the output
2154 * This function is similar to g_format_size() but allows for flags
2155 * that modify the output. See #GFormatSizeFlags.
2157 * Returns: a newly-allocated formatted string containing a human
2158 * readable file size
2163 g_format_size_full (guint64 size,
2164 GFormatSizeFlags flags)
2168 string = g_string_new (NULL);
2170 if (flags & G_FORMAT_SIZE_IEC_UNITS)
2172 if (size < KIBIBYTE_FACTOR)
2174 g_string_printf (string,
2175 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2177 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2180 else if (size < MEBIBYTE_FACTOR)
2181 g_string_printf (string, _("%.1f KiB"), (gdouble) size / (gdouble) KIBIBYTE_FACTOR);
2182 else if (size < GIBIBYTE_FACTOR)
2183 g_string_printf (string, _("%.1f MiB"), (gdouble) size / (gdouble) MEBIBYTE_FACTOR);
2185 else if (size < TEBIBYTE_FACTOR)
2186 g_string_printf (string, _("%.1f GiB"), (gdouble) size / (gdouble) GIBIBYTE_FACTOR);
2188 else if (size < PEBIBYTE_FACTOR)
2189 g_string_printf (string, _("%.1f TiB"), (gdouble) size / (gdouble) TEBIBYTE_FACTOR);
2191 else if (size < EXBIBYTE_FACTOR)
2192 g_string_printf (string, _("%.1f PiB"), (gdouble) size / (gdouble) PEBIBYTE_FACTOR);
2195 g_string_printf (string, _("%.1f EiB"), (gdouble) size / (gdouble) EXBIBYTE_FACTOR);
2199 if (size < KILOBYTE_FACTOR)
2201 g_string_printf (string,
2202 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2204 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2207 else if (size < MEGABYTE_FACTOR)
2208 g_string_printf (string, _("%.1f kB"), (gdouble) size / (gdouble) KILOBYTE_FACTOR);
2210 else if (size < GIGABYTE_FACTOR)
2211 g_string_printf (string, _("%.1f MB"), (gdouble) size / (gdouble) MEGABYTE_FACTOR);
2213 else if (size < TERABYTE_FACTOR)
2214 g_string_printf (string, _("%.1f GB"), (gdouble) size / (gdouble) GIGABYTE_FACTOR);
2215 else if (size < PETABYTE_FACTOR)
2216 g_string_printf (string, _("%.1f TB"), (gdouble) size / (gdouble) TERABYTE_FACTOR);
2218 else if (size < EXABYTE_FACTOR)
2219 g_string_printf (string, _("%.1f PB"), (gdouble) size / (gdouble) PETABYTE_FACTOR);
2222 g_string_printf (string, _("%.1f EB"), (gdouble) size / (gdouble) EXABYTE_FACTOR);
2225 if (flags & G_FORMAT_SIZE_LONG_FORMAT)
2227 /* First problem: we need to use the number of bytes to decide on
2228 * the plural form that is used for display, but the number of
2229 * bytes potentially exceeds the size of a guint (which is what
2230 * ngettext() takes).
2232 * From a pragmatic standpoint, it seems that all known languages
2233 * base plural forms on one or both of the following:
2235 * - the lowest digits of the number
2237 * - if the number if greater than some small value
2239 * Here's how we fake it: Draw an arbitrary line at one thousand.
2240 * If the number is below that, then fine. If it is above it,
2241 * then we take the modulus of the number by one thousand (in
2242 * order to keep the lowest digits) and add one thousand to that
2243 * (in order to ensure that 1001 is not treated the same as 1).
2245 guint plural_form = size < 1000 ? size : size % 1000 + 1000;
2247 /* Second problem: we need to translate the string "%u byte" and
2248 * "%u bytes" for pluralisation, but the correct number format to
2249 * use for a gsize is different depending on which architecture
2252 * Solution: format the number separately and use "%s bytes" on
2255 const gchar *translated_format;
2256 gchar *formatted_number;
2258 /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2259 translated_format = g_dngettext(GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
2260 /* XXX: Windows doesn't support the "'" format modifier, so we
2261 * must not use it there. Instead, just display the number
2262 * without separation. Bug #655336 is open until a solution is
2266 formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2268 formatted_number = g_strdup_printf ("%"G_GUINT64_FORMAT, size);
2271 g_string_append (string, " (");
2272 g_string_append_printf (string, translated_format, formatted_number);
2273 g_free (formatted_number);
2274 g_string_append (string, ")");
2277 return g_string_free (string, FALSE);
2281 * g_format_size_for_display:
2282 * @size: a size in bytes
2284 * Formats a size (for example the size of a file) into a human
2285 * readable string. Sizes are rounded to the nearest size prefix
2286 * (KB, MB, GB) and are displayed rounded to the nearest tenth.
2287 * E.g. the file size 3292528 bytes will be converted into the
2290 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2292 * This string should be freed with g_free() when not needed any longer.
2294 * Returns: a newly-allocated formatted string containing a human
2295 * readable file size
2299 * Deprecated:2.30: This function is broken due to its use of SI
2300 * suffixes to denote IEC units. Use g_format_size() instead.
2303 g_format_size_for_display (goffset size)
2305 if (size < (goffset) KIBIBYTE_FACTOR)
2306 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
2309 gdouble displayed_size;
2311 if (size < (goffset) MEBIBYTE_FACTOR)
2313 displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
2314 /* Translators: this is from the deprecated function g_format_size_for_display() which uses 'KB' to
2315 * mean 1024 bytes. I am aware that 'KB' is not correct, but it has been preserved for reasons of
2316 * compatibility. Users will not see this string unless a program is using this deprecated function.
2317 * Please translate as literally as possible.
2319 return g_strdup_printf (_("%.1f KB"), displayed_size);
2321 else if (size < (goffset) GIBIBYTE_FACTOR)
2323 displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
2324 return g_strdup_printf (_("%.1f MB"), displayed_size);
2326 else if (size < (goffset) TEBIBYTE_FACTOR)
2328 displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
2329 return g_strdup_printf (_("%.1f GB"), displayed_size);
2331 else if (size < (goffset) PEBIBYTE_FACTOR)
2333 displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
2334 return g_strdup_printf (_("%.1f TB"), displayed_size);
2336 else if (size < (goffset) EXBIBYTE_FACTOR)
2338 displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
2339 return g_strdup_printf (_("%.1f PB"), displayed_size);
2343 displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
2344 return g_strdup_printf (_("%.1f EB"), displayed_size);
2349 #if defined (G_OS_WIN32) && !defined (_WIN64)
2351 /* Binary compatibility versions. Not for newly compiled code. */
2353 _GLIB_EXTERN const gchar *g_get_user_name_utf8 (void);
2354 _GLIB_EXTERN const gchar *g_get_real_name_utf8 (void);
2355 _GLIB_EXTERN const gchar *g_get_home_dir_utf8 (void);
2356 _GLIB_EXTERN const gchar *g_get_tmp_dir_utf8 (void);
2357 _GLIB_EXTERN gchar *g_find_program_in_path_utf8 (const gchar *program);
2360 g_find_program_in_path_utf8 (const gchar *program)
2362 return g_find_program_in_path (program);
2365 const gchar *g_get_user_name_utf8 (void) { return g_get_user_name (); }
2366 const gchar *g_get_real_name_utf8 (void) { return g_get_real_name (); }
2367 const gchar *g_get_home_dir_utf8 (void) { return g_get_home_dir (); }
2368 const gchar *g_get_tmp_dir_utf8 (void) { return g_get_tmp_dir (); }
2374 * Returns %TRUE if the current process was executed as setuid (or an
2375 * equivalent __libc_enable_secure is available). See:
2376 * http://osdir.com/ml/linux.lfs.hardened/2007-04/msg00032.html
2379 g_check_setuid (void)
2381 /* TODO: get __libc_enable_secure exported from glibc.
2382 * See http://www.openwall.com/lists/owl-dev/2012/08/14/1
2384 #if 0 && defined(HAVE_LIBC_ENABLE_SECURE)
2386 /* See glibc/include/unistd.h */
2387 extern int __libc_enable_secure;
2388 return __libc_enable_secure;
2390 #elif defined(HAVE_ISSETUGID)
2391 /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
2392 return issetugid ();
2393 #elif defined(G_OS_UNIX)
2394 uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
2395 gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
2397 static gsize check_setuid_initialised;
2398 static gboolean is_setuid;
2400 if (g_once_init_enter (&check_setuid_initialised))
2402 #ifdef HAVE_GETRESUID
2403 /* These aren't in the header files, so we prototype them here.
2405 int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
2406 int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);
2408 if (getresuid (&ruid, &euid, &suid) != 0 ||
2409 getresgid (&rgid, &egid, &sgid) != 0)
2410 #endif /* HAVE_GETRESUID */
2412 suid = ruid = getuid ();
2413 sgid = rgid = getgid ();
2418 is_setuid = (ruid != euid || ruid != suid ||
2419 rgid != egid || rgid != sgid);
2421 g_once_init_leave (&check_setuid_initialised, 1);