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);
177 * @dest: the destination address to copy the bytes to.
178 * @src: the source address to copy the bytes from.
179 * @len: the number of bytes to copy.
181 * Copies a block of memory @len bytes long, from @src to @dest.
182 * The source and destination areas may overlap.
184 * Deprecated:2.40: Just use memmove().
193 * @func: (scope async): the function to call on normal program termination.
195 * Specifies a function to be called at normal program termination.
197 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
198 * macro that maps to a call to the atexit() function in the C
199 * library. This means that in case the code that calls g_atexit(),
200 * i.e. atexit(), is in a DLL, the function will be called when the
201 * DLL is detached from the program. This typically makes more sense
202 * than that the function is called when the GLib DLL is detached,
203 * which happened earlier when g_atexit() was a function in the GLib
206 * The behaviour of atexit() in the context of dynamically loaded
207 * modules is not formally specified and varies wildly.
209 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
210 * loaded module which is unloaded before the program terminates might
211 * well cause a crash at program exit.
213 * Some POSIX systems implement atexit() like Windows, and have each
214 * dynamically loaded module maintain an own atexit chain that is
215 * called when the module is unloaded.
217 * On other POSIX systems, before a dynamically loaded module is
218 * unloaded, the registered atexit functions (if any) residing in that
219 * module are called, regardless where the code that registered them
220 * resided. This is presumably the most robust approach.
222 * As can be seen from the above, for portability it's best to avoid
223 * calling g_atexit() (or atexit()) except in the main executable of a
226 * Deprecated:2.32: It is best to avoid g_atexit().
229 g_atexit (GVoidFunc func)
233 result = atexit ((void (*)(void)) func);
236 g_error ("Could not register atexit() function: %s",
241 /* Based on execvp() from GNU Libc.
242 * Some of this code is cut-and-pasted into gspawn.c
246 my_strchrnul (const gchar *str,
249 gchar *p = (gchar*)str;
250 while (*p && (*p != c))
258 static gchar *inner_find_program_in_path (const gchar *program);
261 g_find_program_in_path (const gchar *program)
263 const gchar *last_dot = strrchr (program, '.');
265 if (last_dot == NULL ||
266 strchr (last_dot, '\\') != NULL ||
267 strchr (last_dot, '/') != NULL)
269 const gint program_length = strlen (program);
270 gchar *pathext = g_build_path (";",
271 ".exe;.cmd;.bat;.com",
272 g_getenv ("PATHEXT"),
275 gchar *decorated_program;
281 gchar *q = my_strchrnul (p, ';');
283 decorated_program = g_malloc (program_length + (q-p) + 1);
284 memcpy (decorated_program, program, program_length);
285 memcpy (decorated_program+program_length, p, q-p);
286 decorated_program [program_length + (q-p)] = '\0';
288 retval = inner_find_program_in_path (decorated_program);
289 g_free (decorated_program);
297 } while (*p++ != '\0');
302 return inner_find_program_in_path (program);
308 * g_find_program_in_path:
309 * @program: a program name in the GLib file name encoding
311 * Locates the first executable named @program in the user's path, in the
312 * same way that execvp() would locate it. Returns an allocated string
313 * with the absolute path name, or %NULL if the program is not found in
314 * the path. If @program is already an absolute path, returns a copy of
315 * @program if @program exists and is executable, and %NULL otherwise.
317 * On Windows, if @program does not have a file type suffix, tries
318 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
319 * the <envar>PATHEXT</envar> environment variable.
321 * On Windows, it looks for the file in the same way as CreateProcess()
322 * would. This means first in the directory where the executing
323 * program was loaded from, then in the current directory, then in the
324 * Windows 32-bit system directory, then in the Windows directory, and
325 * finally in the directories in the <envar>PATH</envar> environment
326 * variable. If the program is found, the return value contains the
327 * full name including the type suffix.
329 * Return value: a newly-allocated string with the absolute path, or %NULL
333 inner_find_program_in_path (const gchar *program)
336 g_find_program_in_path (const gchar *program)
339 const gchar *path, *p;
340 gchar *name, *freeme;
342 const gchar *path_copy;
343 gchar *filename = NULL, *appdir = NULL;
344 gchar *sysdir = NULL, *windir = NULL;
346 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
352 g_return_val_if_fail (program != NULL, NULL);
354 /* If it is an absolute path, or a relative path including subdirectories,
355 * don't look in PATH.
357 if (g_path_is_absolute (program)
358 || strchr (program, G_DIR_SEPARATOR) != NULL
360 || strchr (program, '/') != NULL
364 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
365 !g_file_test (program, G_FILE_TEST_IS_DIR))
366 return g_strdup (program);
371 path = g_getenv ("PATH");
372 #if defined(G_OS_UNIX)
375 /* There is no 'PATH' in the environment. The default
376 * search path in GNU libc is the current directory followed by
377 * the path 'confstr' returns for '_CS_PATH'.
380 /* In GLib we put . last, for security, and don't use the
381 * unportable confstr(); UNIX98 does not actually specify
382 * what to search if PATH is unset. POSIX may, dunno.
385 path = "/bin:/usr/bin:.";
388 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
389 if (n > 0 && n < MAXPATHLEN)
390 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
392 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
393 if (n > 0 && n < MAXPATHLEN)
394 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
396 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
397 if (n > 0 && n < MAXPATHLEN)
398 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
402 appdir = g_path_get_dirname (filename);
406 path = g_strdup (path);
410 const gchar *tem = path;
411 path = g_strconcat (windir, ";", path, NULL);
412 g_free ((gchar *) tem);
418 const gchar *tem = path;
419 path = g_strconcat (sysdir, ";", path, NULL);
420 g_free ((gchar *) tem);
425 const gchar *tem = path;
426 path = g_strconcat (".;", path, NULL);
427 g_free ((gchar *) tem);
432 const gchar *tem = path;
433 path = g_strconcat (appdir, ";", path, NULL);
434 g_free ((gchar *) tem);
441 len = strlen (program) + 1;
442 pathlen = strlen (path);
443 freeme = name = g_malloc (pathlen + len + 1);
445 /* Copy the file name at the top, including '\0' */
446 memcpy (name + pathlen + 1, program, len);
447 name = name + pathlen;
448 /* And add the slash before the filename */
449 *name = G_DIR_SEPARATOR;
457 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
460 /* Two adjacent colons, or a colon at the beginning or the end
461 * of 'PATH' means to search the current directory.
465 startp = memcpy (name - (p - path), path, p - path);
467 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
468 !g_file_test (startp, G_FILE_TEST_IS_DIR))
471 ret = g_strdup (startp);
474 g_free ((gchar *) path_copy);
479 while (*p++ != '\0');
483 g_free ((gchar *) path_copy);
491 * @mask: a #gulong containing flags
492 * @nth_bit: the index of the bit to start the search from
494 * Find the position of the first bit set in @mask, searching
495 * from (but not including) @nth_bit upwards. Bits are numbered
496 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
497 * usually). To start searching from the 0th bit, set @nth_bit to -1.
499 * Returns: the index of the first bit set which is higher than @nth_bit
504 * @mask: a #gulong containing flags
505 * @nth_bit: the index of the bit to start the search from
507 * Find the position of the first bit set in @mask, searching
508 * from (but not including) @nth_bit downwards. Bits are numbered
509 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
510 * usually). To start searching from the last bit, set @nth_bit to
511 * -1 or GLIB_SIZEOF_LONG * 8.
513 * Returns: the index of the first bit set which is lower than @nth_bit
520 * Gets the number of bits used to hold @number,
521 * e.g. if @number is 4, 3 bits are needed.
523 * Returns: the number of bits used to hold @number
526 G_LOCK_DEFINE_STATIC (g_utils_global);
535 static gchar *g_user_data_dir = NULL;
536 static gchar **g_system_data_dirs = NULL;
537 static gchar *g_user_cache_dir = NULL;
538 static gchar *g_user_config_dir = NULL;
539 static gchar **g_system_config_dirs = NULL;
541 static gchar **g_user_special_dirs = NULL;
543 /* fifteen minutes of fame for everybody */
544 #define G_USER_DIRS_EXPIRE 15 * 60
549 get_special_folder (int csidl)
551 wchar_t path[MAX_PATH+1];
553 LPITEMIDLIST pidl = NULL;
555 gchar *retval = NULL;
557 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
560 b = SHGetPathFromIDListW (pidl, path);
562 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
563 CoTaskMemFree (pidl);
569 get_windows_directory_root (void)
571 wchar_t wwindowsdir[MAX_PATH];
573 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
575 /* Usually X:\Windows, but in terminal server environments
576 * might be an UNC path, AFAIK.
578 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
581 if (windowsdir == NULL)
582 return g_strdup ("C:\\");
584 p = (char *) g_path_skip_root (windowsdir);
585 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
591 return g_strdup ("C:\\");
596 /* HOLDS: g_utils_global_lock */
597 static UserDatabaseEntry *
598 g_get_user_database_entry (void)
600 static UserDatabaseEntry *entry;
602 if (g_once_init_enter (&entry))
604 static UserDatabaseEntry e;
608 struct passwd *pw = NULL;
609 gpointer buffer = NULL;
613 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
615 # ifdef _SC_GETPW_R_SIZE_MAX
616 /* This reurns the maximum length */
617 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
621 # else /* _SC_GETPW_R_SIZE_MAX */
623 # endif /* _SC_GETPW_R_SIZE_MAX */
625 logname = (gchar *) g_getenv ("LOGNAME");
630 /* we allocate 6 extra bytes to work around a bug in
631 * Mac OS < 10.3. See #156446
633 buffer = g_malloc (bufsize + 6);
636 # ifdef HAVE_POSIX_GETPWUID_R
638 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
639 if (!pw || (pw->pw_uid != getuid ())) {
640 /* LOGNAME is lying, fall back to looking up the uid */
641 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
644 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
646 error = error < 0 ? errno : error;
647 # else /* HAVE_NONPOSIX_GETPWUID_R */
649 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
650 pw = error == 0 ? &pwd : NULL;
653 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
654 if (!pw || (pw->pw_uid != getuid ())) {
655 /* LOGNAME is lying, fall back to looking up the uid */
656 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
659 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
661 error = pw ? 0 : errno;
663 # endif /* HAVE_NONPOSIX_GETPWUID_R */
667 /* we bail out prematurely if the user id can't be found
668 * (should be pretty rare case actually), or if the buffer
669 * should be sufficiently big and lookups are still not
672 if (error == 0 || error == ENOENT)
674 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
678 if (bufsize > 32 * 1024)
680 g_warning ("getpwuid_r(): failed due to: %s.",
689 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
693 pw = getpwuid (getuid ());
697 e.user_name = g_strdup (pw->pw_name);
700 if (pw->pw_gecos && *pw->pw_gecos != '\0')
702 gchar **gecos_fields;
705 /* split the gecos field and substitute '&' */
706 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
707 name_parts = g_strsplit (gecos_fields[0], "&", 0);
708 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
709 e.real_name = g_strjoinv (pw->pw_name, name_parts);
710 g_strfreev (gecos_fields);
711 g_strfreev (name_parts);
716 e.home_dir = g_strdup (pw->pw_dir);
721 #else /* !HAVE_PWD_H */
726 wchar_t buffer[UNLEN+1];
728 if (GetUserNameW (buffer, (LPDWORD) &len))
730 e.user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
731 e.real_name = g_strdup (e.user_name);
734 #endif /* G_OS_WIN32 */
736 #endif /* !HAVE_PWD_H */
739 e.user_name = g_strdup ("somebody");
741 e.real_name = g_strdup ("Unknown");
743 g_once_init_leave (&entry, &e);
752 * Gets the user name of the current user. The encoding of the returned
753 * string is system-defined. On UNIX, it might be the preferred file name
754 * encoding, or something else, and there is no guarantee that it is even
755 * consistent on a machine. On Windows, it is always UTF-8.
757 * Returns: the user name of the current user.
760 g_get_user_name (void)
762 UserDatabaseEntry *entry;
764 entry = g_get_user_database_entry ();
766 return entry->user_name;
772 * Gets the real name of the user. This usually comes from the user's entry
773 * in the <filename>passwd</filename> file. The encoding of the returned
774 * string is system-defined. (On Windows, it is, however, always UTF-8.)
775 * If the real user name cannot be determined, the string "Unknown" is
778 * Returns: the user's real name.
781 g_get_real_name (void)
783 UserDatabaseEntry *entry;
785 entry = g_get_user_database_entry ();
787 return entry->real_name;
793 * Gets the current user's home directory.
795 * As with most UNIX tools, this function will return the value of the
796 * <envar>HOME</envar> environment variable if it is set to an existing
797 * absolute path name, falling back to the <filename>passwd</filename>
798 * file in the case that it is unset.
800 * If the path given in <envar>HOME</envar> is non-absolute, does not
801 * exist, or is not a directory, the result is undefined.
804 * Before version 2.36 this function would ignore the
805 * <envar>HOME</envar> environment variable, taking the value from the
806 * <filename>passwd</filename> database instead. This was changed to
807 * increase the compatibility of GLib with other programs (and the XDG
808 * basedir specification) and to increase testability of programs
809 * based on GLib (by making it easier to run them from test
812 * If your program has a strong requirement for either the new or the
813 * old behaviour (and if you don't wish to increase your GLib
814 * dependency to ensure that the new behaviour is in effect) then you
815 * should either directly check the <envar>HOME</envar> environment
816 * variable yourself or unset it before calling any functions in GLib.
819 * Returns: the current user's home directory
822 g_get_home_dir (void)
824 static gchar *home_dir;
826 if (g_once_init_enter (&home_dir))
830 /* We first check HOME and use it if it is set */
831 tmp = g_strdup (g_getenv ("HOME"));
834 /* Only believe HOME if it is an absolute path and exists.
836 * We only do this check on Windows for a couple of reasons.
837 * Historically, we only did it there because we used to ignore $HOME
838 * on UNIX. There are concerns about enabling it now on UNIX because
839 * of things like autofs. In short, if the user has a bogus value in
840 * $HOME then they get what they pay for...
844 if (!(g_path_is_absolute (tmp) &&
845 g_file_test (tmp, G_FILE_TEST_IS_DIR)))
852 /* In case HOME is Unix-style (it happens), convert it to
858 while ((p = strchr (tmp, '/')) != NULL)
864 /* USERPROFILE is probably the closest equivalent to $HOME? */
865 if (g_getenv ("USERPROFILE") != NULL)
866 tmp = g_strdup (g_getenv ("USERPROFILE"));
870 tmp = get_special_folder (CSIDL_PROFILE);
873 tmp = get_windows_directory_root ();
874 #endif /* G_OS_WIN32 */
878 /* If we didn't get it from any of those methods, we will have
879 * to read the user database entry.
881 UserDatabaseEntry *entry;
883 entry = g_get_user_database_entry ();
885 /* Strictly speaking, we should copy this, but we know that
886 * neither will ever be freed, so don't bother...
888 tmp = entry->home_dir;
891 g_once_init_leave (&home_dir, tmp);
900 * Gets the directory to use for temporary files.
902 * On UNIX, this is taken from the <envar>TMPDIR</envar> environment
903 * variable. If the variable is not set, <literal>P_tmpdir</literal> is
904 * used, as defined by the system C library. Failing that, a hard-coded
905 * default of "/tmp" is returned.
907 * On Windows, the <envar>TEMP</envar> environment variable is used,
908 * with the root directory of the Windows installation (eg: "C:\") used
911 * The encoding of the returned string is system-defined. On Windows, it
912 * is always UTF-8. The return value is never %NULL or the empty string.
914 * Returns: the directory to use for temporary files.
919 static gchar *tmp_dir;
921 if (g_once_init_enter (&tmp_dir))
926 tmp = g_strdup (g_getenv ("TEMP"));
928 if (tmp == NULL || *tmp == '\0')
931 tmp = get_windows_directory_root ();
933 #else /* G_OS_WIN32 */
934 tmp = g_strdup (g_getenv ("TMPDIR"));
937 if (tmp == NULL || *tmp == '\0')
941 tmp = g_strdup (P_tmpdir);
943 if (k > 1 && G_IS_DIR_SEPARATOR (tmp[k - 1]))
946 #endif /* P_tmpdir */
948 if (tmp == NULL || *tmp == '\0')
951 tmp = g_strdup ("/tmp");
953 #endif /* !G_OS_WIN32 */
955 g_once_init_leave (&tmp_dir, tmp);
964 * Return a name for the machine.
966 * The returned name is not necessarily a fully-qualified domain name,
967 * or even present in DNS or some other name service at all. It need
968 * not even be unique on your local network or site, but usually it
969 * is. Callers should not rely on the return value having any specific
970 * properties like uniqueness for security purposes. Even if the name
971 * of the machine is changed while an application is running, the
972 * return value from this function does not change. The returned
973 * string is owned by GLib and should not be modified or freed. If no
974 * name can be determined, a default fixed string "localhost" is
977 * Returns: the host name of the machine.
982 g_get_host_name (void)
984 static gchar *hostname;
986 if (g_once_init_enter (&hostname))
992 failed = (gethostname (tmp, sizeof (tmp)) == -1);
994 DWORD size = sizeof (tmp);
995 failed = (!GetComputerName (tmp, &size));
998 g_once_init_leave (&hostname, g_strdup (failed ? "localhost" : tmp));
1004 G_LOCK_DEFINE_STATIC (g_prgname);
1005 static gchar *g_prgname = NULL;
1010 * Gets the name of the program. This name should <emphasis>not</emphasis>
1011 * be localized, contrast with g_get_application_name().
1012 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1013 * which is called by gtk_init(). The program name is found by taking
1014 * the last component of <literal>argv[0]</literal>.)
1016 * Returns: the name of the program. The returned string belongs
1017 * to GLib and must not be modified or freed.
1020 g_get_prgname (void)
1026 if (g_prgname == NULL)
1028 static gboolean beenhere = FALSE;
1032 gchar *utf8_buf = NULL;
1033 wchar_t buf[MAX_PATH+1];
1036 if (GetModuleFileNameW (GetModuleHandle (NULL),
1037 buf, G_N_ELEMENTS (buf)) > 0)
1038 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1042 g_prgname = g_path_get_basename (utf8_buf);
1049 G_UNLOCK (g_prgname);
1056 * @prgname: the name of the program.
1058 * Sets the name of the program. This name should <emphasis>not</emphasis>
1059 * be localized, contrast with g_set_application_name(). Note that for
1060 * thread-safety reasons this function can only be called once.
1063 g_set_prgname (const gchar *prgname)
1067 g_prgname = g_strdup (prgname);
1068 G_UNLOCK (g_prgname);
1071 G_LOCK_DEFINE_STATIC (g_application_name);
1072 static gchar *g_application_name = NULL;
1075 * g_get_application_name:
1077 * Gets a human-readable name for the application, as set by
1078 * g_set_application_name(). This name should be localized if
1079 * possible, and is intended for display to the user. Contrast with
1080 * g_get_prgname(), which gets a non-localized name. If
1081 * g_set_application_name() has not been called, returns the result of
1082 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1085 * Return value: human-readable application name. may return %NULL
1090 g_get_application_name (void)
1094 G_LOCK (g_application_name);
1095 retval = g_application_name;
1096 G_UNLOCK (g_application_name);
1099 return g_get_prgname ();
1105 * g_set_application_name:
1106 * @application_name: localized name of the application
1108 * Sets a human-readable name for the application. This name should be
1109 * localized if possible, and is intended for display to the user.
1110 * Contrast with g_set_prgname(), which sets a non-localized name.
1111 * g_set_prgname() will be called automatically by gtk_init(),
1112 * but g_set_application_name() will not.
1114 * Note that for thread safety reasons, this function can only
1117 * The application name will be used in contexts such as error messages,
1118 * or when displaying an application's name in the task list.
1123 g_set_application_name (const gchar *application_name)
1125 gboolean already_set = FALSE;
1127 G_LOCK (g_application_name);
1128 if (g_application_name)
1131 g_application_name = g_strdup (application_name);
1132 G_UNLOCK (g_application_name);
1135 g_warning ("g_set_application_name() called multiple times");
1139 * g_get_user_data_dir:
1141 * Returns a base directory in which to access application data such
1142 * as icons that is customized for a particular user.
1144 * On UNIX platforms this is determined using the mechanisms described in
1145 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1146 * XDG Base Directory Specification</ulink>.
1147 * In this case the directory retrieved will be XDG_DATA_HOME.
1149 * On Windows this is the folder to use for local (as opposed to
1150 * roaming) application data. See documentation for
1151 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1152 * what g_get_user_config_dir() returns.
1154 * Return value: a string owned by GLib that must not be modified
1159 g_get_user_data_dir (void)
1163 G_LOCK (g_utils_global);
1165 if (!g_user_data_dir)
1168 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1170 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1172 if (data_dir && data_dir[0])
1173 data_dir = g_strdup (data_dir);
1175 if (!data_dir || !data_dir[0])
1177 const gchar *home_dir = g_get_home_dir ();
1180 data_dir = g_build_filename (home_dir, ".local", "share", NULL);
1182 data_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".local", "share", NULL);
1185 g_user_data_dir = data_dir;
1188 data_dir = g_user_data_dir;
1190 G_UNLOCK (g_utils_global);
1196 g_init_user_config_dir (void)
1200 if (!g_user_config_dir)
1203 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1205 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1207 if (config_dir && config_dir[0])
1208 config_dir = g_strdup (config_dir);
1210 if (!config_dir || !config_dir[0])
1212 const gchar *home_dir = g_get_home_dir ();
1215 config_dir = g_build_filename (home_dir, ".config", NULL);
1217 config_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".config", NULL);
1220 g_user_config_dir = config_dir;
1225 * g_get_user_config_dir:
1227 * Returns a base directory in which to store user-specific application
1228 * configuration information such as user preferences and settings.
1230 * On UNIX platforms this is determined using the mechanisms described in
1231 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1232 * XDG Base Directory Specification</ulink>.
1233 * In this case the directory retrieved will be XDG_CONFIG_HOME.
1235 * On Windows this is the folder to use for local (as opposed to
1236 * roaming) application data. See documentation for
1237 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1238 * what g_get_user_data_dir() returns.
1240 * Return value: a string owned by GLib that must not be modified
1245 g_get_user_config_dir (void)
1247 G_LOCK (g_utils_global);
1249 g_init_user_config_dir ();
1251 G_UNLOCK (g_utils_global);
1253 return g_user_config_dir;
1257 * g_get_user_cache_dir:
1259 * Returns a base directory in which to store non-essential, cached
1260 * data specific to particular user.
1262 * On UNIX platforms this is determined using the mechanisms described in
1263 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1264 * XDG Base Directory Specification</ulink>.
1265 * In this case the directory retrieved will be XDG_CACHE_HOME.
1267 * On Windows is the directory that serves as a common repository for
1268 * temporary Internet files. A typical path is
1269 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
1270 * See documentation for CSIDL_INTERNET_CACHE.
1272 * Return value: a string owned by GLib that must not be modified
1277 g_get_user_cache_dir (void)
1281 G_LOCK (g_utils_global);
1283 if (!g_user_cache_dir)
1286 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1288 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1290 if (cache_dir && cache_dir[0])
1291 cache_dir = g_strdup (cache_dir);
1293 if (!cache_dir || !cache_dir[0])
1295 const gchar *home_dir = g_get_home_dir ();
1298 cache_dir = g_build_filename (home_dir, ".cache", NULL);
1300 cache_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".cache", NULL);
1302 g_user_cache_dir = cache_dir;
1305 cache_dir = g_user_cache_dir;
1307 G_UNLOCK (g_utils_global);
1313 * g_get_user_runtime_dir:
1315 * Returns a directory that is unique to the current user on the local
1318 * On UNIX platforms this is determined using the mechanisms described in
1319 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1320 * XDG Base Directory Specification</ulink>. This is the directory
1321 * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
1322 * In the case that this variable is not set, GLib will issue a warning
1323 * message to stderr and return the value of g_get_user_cache_dir().
1325 * On Windows this is the folder to use for local (as opposed to
1326 * roaming) application data. See documentation for
1327 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1328 * what g_get_user_config_dir() returns.
1330 * Returns: a string owned by GLib that must not be modified or freed.
1335 g_get_user_runtime_dir (void)
1338 static const gchar *runtime_dir;
1339 static gsize initialised;
1341 if (g_once_init_enter (&initialised))
1343 runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
1345 g_once_init_leave (&initialised, 1);
1351 /* Both fallback for UNIX and the default
1352 * in Windows: use the user cache directory.
1356 return g_get_user_cache_dir ();
1362 find_folder (OSType type)
1364 gchar *filename = NULL;
1367 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
1369 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
1373 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
1377 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
1381 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
1383 CFStringGetCString (path, filename,
1384 CFStringGetLength (path) * 3 + 1,
1385 kCFStringEncodingUTF8);
1399 load_user_special_dirs (void)
1401 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
1402 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
1403 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
1404 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
1405 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
1406 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
1407 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
1408 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
1411 #endif /* HAVE_CARBON */
1413 #if defined(G_OS_WIN32)
1415 load_user_special_dirs (void)
1417 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1421 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
1423 static const GUID FOLDERID_Downloads =
1424 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1425 static const GUID FOLDERID_Public =
1426 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1430 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
1431 "SHGetKnownFolderPath");
1433 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1434 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
1436 if (p_SHGetKnownFolderPath == NULL)
1438 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1443 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1446 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1447 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
1448 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1449 CoTaskMemFree (wcp);
1452 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1455 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
1456 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
1458 if (p_SHGetKnownFolderPath == NULL)
1461 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1466 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
1469 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1470 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
1471 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1472 CoTaskMemFree (wcp);
1475 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1478 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
1479 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
1481 #endif /* G_OS_WIN32 */
1484 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
1486 /* adapted from xdg-user-dir-lookup.c
1488 * Copyright (C) 2007 Red Hat Inc.
1490 * Permission is hereby granted, free of charge, to any person
1491 * obtaining a copy of this software and associated documentation files
1492 * (the "Software"), to deal in the Software without restriction,
1493 * including without limitation the rights to use, copy, modify, merge,
1494 * publish, distribute, sublicense, and/or sell copies of the Software,
1495 * and to permit persons to whom the Software is furnished to do so,
1496 * subject to the following conditions:
1498 * The above copyright notice and this permission notice shall be
1499 * included in all copies or substantial portions of the Software.
1501 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1502 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1503 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1504 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1505 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1506 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1507 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1511 load_user_special_dirs (void)
1518 g_init_user_config_dir ();
1519 config_file = g_build_filename (g_user_config_dir,
1523 if (!g_file_get_contents (config_file, &data, NULL, NULL))
1525 g_free (config_file);
1529 lines = g_strsplit (data, "\n", -1);
1530 n_lines = g_strv_length (lines);
1533 for (i = 0; i < n_lines; i++)
1535 gchar *buffer = lines[i];
1538 gboolean is_relative = FALSE;
1539 GUserDirectory directory;
1541 /* Remove newline at end */
1542 len = strlen (buffer);
1543 if (len > 0 && buffer[len - 1] == '\n')
1544 buffer[len - 1] = 0;
1547 while (*p == ' ' || *p == '\t')
1550 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
1552 directory = G_USER_DIRECTORY_DESKTOP;
1553 p += strlen ("XDG_DESKTOP_DIR");
1555 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
1557 directory = G_USER_DIRECTORY_DOCUMENTS;
1558 p += strlen ("XDG_DOCUMENTS_DIR");
1560 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
1562 directory = G_USER_DIRECTORY_DOWNLOAD;
1563 p += strlen ("XDG_DOWNLOAD_DIR");
1565 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
1567 directory = G_USER_DIRECTORY_MUSIC;
1568 p += strlen ("XDG_MUSIC_DIR");
1570 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
1572 directory = G_USER_DIRECTORY_PICTURES;
1573 p += strlen ("XDG_PICTURES_DIR");
1575 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
1577 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
1578 p += strlen ("XDG_PUBLICSHARE_DIR");
1580 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
1582 directory = G_USER_DIRECTORY_TEMPLATES;
1583 p += strlen ("XDG_TEMPLATES_DIR");
1585 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
1587 directory = G_USER_DIRECTORY_VIDEOS;
1588 p += strlen ("XDG_VIDEOS_DIR");
1593 while (*p == ' ' || *p == '\t')
1600 while (*p == ' ' || *p == '\t')
1607 if (strncmp (p, "$HOME", 5) == 0)
1615 d = strrchr (p, '"');
1622 /* remove trailing slashes */
1624 if (d[len - 1] == '/')
1629 g_user_special_dirs[directory] = g_build_filename (g_get_home_dir (), d, NULL);
1632 g_user_special_dirs[directory] = g_strdup (d);
1636 g_free (config_file);
1639 #endif /* G_OS_UNIX && !HAVE_CARBON */
1643 * g_reload_user_special_dirs_cache:
1645 * Resets the cache used for g_get_user_special_dir(), so
1646 * that the latest on-disk version is used. Call this only
1647 * if you just changed the data on disk yourself.
1649 * Due to threadsafety issues this may cause leaking of strings
1650 * that were previously returned from g_get_user_special_dir()
1651 * that can't be freed. We ensure to only leak the data for
1652 * the directories that actually changed value though.
1657 g_reload_user_special_dirs_cache (void)
1661 G_LOCK (g_utils_global);
1663 if (g_user_special_dirs != NULL)
1665 /* save a copy of the pointer, to check if some memory can be preserved */
1666 char **old_g_user_special_dirs = g_user_special_dirs;
1669 /* recreate and reload our cache */
1670 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1671 load_user_special_dirs ();
1673 /* only leak changed directories */
1674 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
1676 old_val = old_g_user_special_dirs[i];
1677 if (g_user_special_dirs[i] == NULL)
1679 g_user_special_dirs[i] = old_val;
1681 else if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
1684 g_free (g_user_special_dirs[i]);
1685 g_user_special_dirs[i] = old_val;
1691 /* free the old array */
1692 g_free (old_g_user_special_dirs);
1695 G_UNLOCK (g_utils_global);
1699 * g_get_user_special_dir:
1700 * @directory: the logical id of special directory
1702 * Returns the full path of a special directory using its logical id.
1704 * On Unix this is done using the XDG special user directories.
1705 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
1706 * falls back to <filename>$HOME/Desktop</filename> when XDG special
1707 * user directories have not been set up.
1709 * Depending on the platform, the user might be able to change the path
1710 * of the special directory without requiring the session to restart; GLib
1711 * will not reflect any change once the special directories are loaded.
1713 * Return value: the path to the specified special directory, or %NULL
1714 * if the logical id was not found. The returned string is owned by
1715 * GLib and should not be modified or freed.
1720 g_get_user_special_dir (GUserDirectory directory)
1722 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
1723 directory < G_USER_N_DIRECTORIES, NULL);
1725 G_LOCK (g_utils_global);
1727 if (G_UNLIKELY (g_user_special_dirs == NULL))
1729 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1731 load_user_special_dirs ();
1733 /* Special-case desktop for historical compatibility */
1734 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
1735 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = g_build_filename (g_get_home_dir (), "Desktop", NULL);
1738 G_UNLOCK (g_utils_global);
1740 return g_user_special_dirs[directory];
1745 #undef g_get_system_data_dirs
1748 get_module_for_address (gconstpointer address)
1750 /* Holds the g_utils_global lock */
1752 static gboolean beenhere = FALSE;
1753 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
1754 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
1755 HMODULE hmodule = NULL;
1762 p_GetModuleHandleExA =
1763 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1764 "GetModuleHandleExA");
1768 if (p_GetModuleHandleExA == NULL ||
1769 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
1770 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
1773 MEMORY_BASIC_INFORMATION mbi;
1774 VirtualQuery (address, &mbi, sizeof (mbi));
1775 hmodule = (HMODULE) mbi.AllocationBase;
1782 get_module_share_dir (gconstpointer address)
1788 hmodule = get_module_for_address (address);
1789 if (hmodule == NULL)
1792 filename = g_win32_get_package_installation_directory_of_module (hmodule);
1793 retval = g_build_filename (filename, "share", NULL);
1799 const gchar * const *
1800 g_win32_get_system_data_dirs_for_module (void (*address_of_function)(void))
1804 static GHashTable *per_module_data_dirs = NULL;
1809 if (address_of_function)
1811 G_LOCK (g_utils_global);
1812 hmodule = get_module_for_address (address_of_function);
1813 if (hmodule != NULL)
1815 if (per_module_data_dirs == NULL)
1816 per_module_data_dirs = g_hash_table_new (NULL, NULL);
1819 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
1823 G_UNLOCK (g_utils_global);
1824 return (const gchar * const *) retval;
1830 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
1832 /* Documents and Settings\All Users\Application Data */
1833 p = get_special_folder (CSIDL_COMMON_APPDATA);
1835 g_array_append_val (data_dirs, p);
1837 /* Documents and Settings\All Users\Documents */
1838 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1840 g_array_append_val (data_dirs, p);
1842 /* Using the above subfolders of Documents and Settings perhaps
1843 * makes sense from a Windows perspective.
1845 * But looking at the actual use cases of this function in GTK+
1846 * and GNOME software, what we really want is the "share"
1847 * subdirectory of the installation directory for the package
1848 * our caller is a part of.
1850 * The address_of_function parameter, if non-NULL, points to a
1851 * function in the calling module. Use that to determine that
1852 * module's installation folder, and use its "share" subfolder.
1854 * Additionally, also use the "share" subfolder of the installation
1855 * locations of GLib and the .exe file being run.
1857 * To guard against none of the above being what is really wanted,
1858 * callers of this function should have Win32-specific code to look
1859 * up their installation folder themselves, and handle a subfolder
1860 * "share" of it in the same way as the folders returned from this
1864 p = get_module_share_dir (address_of_function);
1866 g_array_append_val (data_dirs, p);
1868 if (glib_dll != NULL)
1870 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
1871 p = g_build_filename (glib_root, "share", NULL);
1873 g_array_append_val (data_dirs, p);
1877 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
1878 p = g_build_filename (exe_root, "share", NULL);
1880 g_array_append_val (data_dirs, p);
1883 retval = (gchar **) g_array_free (data_dirs, FALSE);
1885 if (address_of_function)
1887 if (hmodule != NULL)
1888 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
1889 G_UNLOCK (g_utils_global);
1892 return (const gchar * const *) retval;
1898 * g_get_system_data_dirs:
1900 * Returns an ordered list of base directories in which to access
1901 * system-wide application data.
1903 * On UNIX platforms this is determined using the mechanisms described in
1904 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1905 * XDG Base Directory Specification</ulink>
1906 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
1908 * On Windows the first elements in the list are the Application Data
1909 * and Documents folders for All Users. (These can be determined only
1910 * on Windows 2000 or later and are not present in the list on other
1911 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
1912 * CSIDL_COMMON_DOCUMENTS.
1914 * Then follows the "share" subfolder in the installation folder for
1915 * the package containing the DLL that calls this function, if it can
1918 * Finally the list contains the "share" subfolder in the installation
1919 * folder for GLib, and in the installation folder for the package the
1920 * application's .exe file belongs to.
1922 * The installation folders above are determined by looking up the
1923 * folder where the module (DLL or EXE) in question is located. If the
1924 * folder's name is "bin", its parent is used, otherwise the folder
1927 * Note that on Windows the returned list can vary depending on where
1928 * this function is called.
1930 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
1931 * not be modified or freed.
1934 const gchar * const *
1935 g_get_system_data_dirs (void)
1937 gchar **data_dir_vector;
1939 G_LOCK (g_utils_global);
1941 if (!g_system_data_dirs)
1944 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
1946 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
1948 if (!data_dirs || !data_dirs[0])
1949 data_dirs = "/usr/local/share/:/usr/share/";
1951 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1954 g_system_data_dirs = data_dir_vector;
1957 data_dir_vector = g_system_data_dirs;
1959 G_UNLOCK (g_utils_global);
1961 return (const gchar * const *) data_dir_vector;
1965 * g_get_system_config_dirs:
1967 * Returns an ordered list of base directories in which to access
1968 * system-wide configuration information.
1970 * On UNIX platforms this is determined using the mechanisms described in
1971 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1972 * XDG Base Directory Specification</ulink>.
1973 * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
1975 * On Windows is the directory that contains application data for all users.
1976 * A typical path is C:\Documents and Settings\All Users\Application Data.
1977 * This folder is used for application data that is not user specific.
1978 * For example, an application can store a spell-check dictionary, a database
1979 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
1980 * This information will not roam and is available to anyone using the computer.
1982 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
1983 * not be modified or freed.
1986 const gchar * const *
1987 g_get_system_config_dirs (void)
1989 gchar *conf_dirs, **conf_dir_vector;
1991 G_LOCK (g_utils_global);
1993 if (!g_system_config_dirs)
1996 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
1999 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2004 /* Return empty list */
2005 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2008 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2010 if (!conf_dirs || !conf_dirs[0])
2011 conf_dirs = "/etc/xdg";
2013 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2016 g_system_config_dirs = conf_dir_vector;
2019 conf_dir_vector = g_system_config_dirs;
2020 G_UNLOCK (g_utils_global);
2022 return (const gchar * const *) conf_dir_vector;
2026 * g_nullify_pointer:
2027 * @nullify_location: the memory address of the pointer.
2029 * Set the pointer at the specified location to %NULL.
2032 g_nullify_pointer (gpointer *nullify_location)
2034 g_return_if_fail (nullify_location != NULL);
2036 *nullify_location = NULL;
2039 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2040 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2041 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2042 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2043 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2044 #define EXABYTE_FACTOR (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2046 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2047 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2048 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2049 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2050 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2051 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2055 * @size: a size in bytes
2057 * Formats a size (for example the size of a file) into a human readable
2058 * string. Sizes are rounded to the nearest size prefix (kB, MB, GB)
2059 * and are displayed rounded to the nearest tenth. E.g. the file size
2060 * 3292528 bytes will be converted into the string "3.2 MB".
2062 * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2064 * This string should be freed with g_free() when not needed any longer.
2066 * See g_format_size_full() for more options about how the size might be
2069 * Returns: a newly-allocated formatted string containing a human readable
2075 g_format_size (guint64 size)
2077 return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2082 * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2083 * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2084 * of the returned string. For example, "45.6 kB (45,612 bytes)".
2085 * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2086 * suffixes. IEC units should only be used for reporting things with
2087 * a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2088 * Network and storage sizes should be reported in the normal SI units.
2090 * Flags to modify the format of the string returned by g_format_size_full().
2093 #pragma GCC diagnostic push
2094 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
2097 * g_format_size_full:
2098 * @size: a size in bytes
2099 * @flags: #GFormatSizeFlags to modify the output
2103 * This function is similar to g_format_size() but allows for flags
2104 * that modify the output. See #GFormatSizeFlags.
2106 * Returns: a newly-allocated formatted string containing a human
2107 * readable file size
2112 g_format_size_full (guint64 size,
2113 GFormatSizeFlags flags)
2117 string = g_string_new (NULL);
2119 if (flags & G_FORMAT_SIZE_IEC_UNITS)
2121 if (size < KIBIBYTE_FACTOR)
2123 g_string_printf (string,
2124 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2126 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2129 else if (size < MEBIBYTE_FACTOR)
2130 g_string_printf (string, _("%.1f KiB"), (gdouble) size / (gdouble) KIBIBYTE_FACTOR);
2131 else if (size < GIBIBYTE_FACTOR)
2132 g_string_printf (string, _("%.1f MiB"), (gdouble) size / (gdouble) MEBIBYTE_FACTOR);
2134 else if (size < TEBIBYTE_FACTOR)
2135 g_string_printf (string, _("%.1f GiB"), (gdouble) size / (gdouble) GIBIBYTE_FACTOR);
2137 else if (size < PEBIBYTE_FACTOR)
2138 g_string_printf (string, _("%.1f TiB"), (gdouble) size / (gdouble) TEBIBYTE_FACTOR);
2140 else if (size < EXBIBYTE_FACTOR)
2141 g_string_printf (string, _("%.1f PiB"), (gdouble) size / (gdouble) PEBIBYTE_FACTOR);
2144 g_string_printf (string, _("%.1f EiB"), (gdouble) size / (gdouble) EXBIBYTE_FACTOR);
2148 if (size < KILOBYTE_FACTOR)
2150 g_string_printf (string,
2151 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2153 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2156 else if (size < MEGABYTE_FACTOR)
2157 g_string_printf (string, _("%.1f kB"), (gdouble) size / (gdouble) KILOBYTE_FACTOR);
2159 else if (size < GIGABYTE_FACTOR)
2160 g_string_printf (string, _("%.1f MB"), (gdouble) size / (gdouble) MEGABYTE_FACTOR);
2162 else if (size < TERABYTE_FACTOR)
2163 g_string_printf (string, _("%.1f GB"), (gdouble) size / (gdouble) GIGABYTE_FACTOR);
2164 else if (size < PETABYTE_FACTOR)
2165 g_string_printf (string, _("%.1f TB"), (gdouble) size / (gdouble) TERABYTE_FACTOR);
2167 else if (size < EXABYTE_FACTOR)
2168 g_string_printf (string, _("%.1f PB"), (gdouble) size / (gdouble) PETABYTE_FACTOR);
2171 g_string_printf (string, _("%.1f EB"), (gdouble) size / (gdouble) EXABYTE_FACTOR);
2174 if (flags & G_FORMAT_SIZE_LONG_FORMAT)
2176 /* First problem: we need to use the number of bytes to decide on
2177 * the plural form that is used for display, but the number of
2178 * bytes potentially exceeds the size of a guint (which is what
2179 * ngettext() takes).
2181 * From a pragmatic standpoint, it seems that all known languages
2182 * base plural forms on one or both of the following:
2184 * - the lowest digits of the number
2186 * - if the number if greater than some small value
2188 * Here's how we fake it: Draw an arbitrary line at one thousand.
2189 * If the number is below that, then fine. If it is above it,
2190 * then we take the modulus of the number by one thousand (in
2191 * order to keep the lowest digits) and add one thousand to that
2192 * (in order to ensure that 1001 is not treated the same as 1).
2194 guint plural_form = size < 1000 ? size : size % 1000 + 1000;
2196 /* Second problem: we need to translate the string "%u byte" and
2197 * "%u bytes" for pluralisation, but the correct number format to
2198 * use for a gsize is different depending on which architecture
2201 * Solution: format the number separately and use "%s bytes" on
2204 const gchar *translated_format;
2205 gchar *formatted_number;
2207 /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2208 translated_format = g_dngettext(GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
2209 /* XXX: Windows doesn't support the "'" format modifier, so we
2210 * must not use it there. Instead, just display the number
2211 * without separation. Bug #655336 is open until a solution is
2215 formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2217 formatted_number = g_strdup_printf ("%"G_GUINT64_FORMAT, size);
2220 g_string_append (string, " (");
2221 g_string_append_printf (string, translated_format, formatted_number);
2222 g_free (formatted_number);
2223 g_string_append (string, ")");
2226 return g_string_free (string, FALSE);
2229 #pragma GCC diagnostic pop
2232 * g_format_size_for_display:
2233 * @size: a size in bytes
2235 * Formats a size (for example the size of a file) into a human
2236 * readable string. Sizes are rounded to the nearest size prefix
2237 * (KB, MB, GB) and are displayed rounded to the nearest tenth.
2238 * E.g. the file size 3292528 bytes will be converted into the
2241 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2243 * This string should be freed with g_free() when not needed any longer.
2245 * Returns: a newly-allocated formatted string containing a human
2246 * readable file size
2250 * Deprecated:2.30: This function is broken due to its use of SI
2251 * suffixes to denote IEC units. Use g_format_size() instead.
2254 g_format_size_for_display (goffset size)
2256 if (size < (goffset) KIBIBYTE_FACTOR)
2257 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
2260 gdouble displayed_size;
2262 if (size < (goffset) MEBIBYTE_FACTOR)
2264 displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
2265 /* Translators: this is from the deprecated function g_format_size_for_display() which uses 'KB' to
2266 * mean 1024 bytes. I am aware that 'KB' is not correct, but it has been preserved for reasons of
2267 * compatibility. Users will not see this string unless a program is using this deprecated function.
2268 * Please translate as literally as possible.
2270 return g_strdup_printf (_("%.1f KB"), displayed_size);
2272 else if (size < (goffset) GIBIBYTE_FACTOR)
2274 displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
2275 return g_strdup_printf (_("%.1f MB"), displayed_size);
2277 else if (size < (goffset) TEBIBYTE_FACTOR)
2279 displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
2280 return g_strdup_printf (_("%.1f GB"), displayed_size);
2282 else if (size < (goffset) PEBIBYTE_FACTOR)
2284 displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
2285 return g_strdup_printf (_("%.1f TB"), displayed_size);
2287 else if (size < (goffset) EXBIBYTE_FACTOR)
2289 displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
2290 return g_strdup_printf (_("%.1f PB"), displayed_size);
2294 displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
2295 return g_strdup_printf (_("%.1f EB"), displayed_size);
2300 #if defined (G_OS_WIN32) && !defined (_WIN64)
2302 /* Binary compatibility versions. Not for newly compiled code. */
2304 _GLIB_EXTERN const gchar *g_get_user_name_utf8 (void);
2305 _GLIB_EXTERN const gchar *g_get_real_name_utf8 (void);
2306 _GLIB_EXTERN const gchar *g_get_home_dir_utf8 (void);
2307 _GLIB_EXTERN const gchar *g_get_tmp_dir_utf8 (void);
2308 _GLIB_EXTERN gchar *g_find_program_in_path_utf8 (const gchar *program);
2311 g_find_program_in_path_utf8 (const gchar *program)
2313 return g_find_program_in_path (program);
2316 const gchar *g_get_user_name_utf8 (void) { return g_get_user_name (); }
2317 const gchar *g_get_real_name_utf8 (void) { return g_get_real_name (); }
2318 const gchar *g_get_home_dir_utf8 (void) { return g_get_home_dir (); }
2319 const gchar *g_get_tmp_dir_utf8 (void) { return g_get_tmp_dir (); }
2325 * Returns %TRUE if the current process was executed as setuid (or an
2326 * equivalent __libc_enable_secure is available). See:
2327 * http://osdir.com/ml/linux.lfs.hardened/2007-04/msg00032.html
2330 g_check_setuid (void)
2332 /* TODO: get __libc_enable_secure exported from glibc.
2333 * See http://www.openwall.com/lists/owl-dev/2012/08/14/1
2335 #if 0 && defined(HAVE_LIBC_ENABLE_SECURE)
2337 /* See glibc/include/unistd.h */
2338 extern int __libc_enable_secure;
2339 return __libc_enable_secure;
2341 #elif defined(HAVE_ISSETUGID)
2342 /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
2343 return issetugid ();
2344 #elif defined(G_OS_UNIX)
2345 uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
2346 gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
2348 static gsize check_setuid_initialised;
2349 static gboolean is_setuid;
2351 if (g_once_init_enter (&check_setuid_initialised))
2353 #ifdef HAVE_GETRESUID
2354 /* These aren't in the header files, so we prototype them here.
2356 int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
2357 int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);
2359 if (getresuid (&ruid, &euid, &suid) != 0 ||
2360 getresgid (&rgid, &egid, &sgid) != 0)
2361 #endif /* HAVE_GETRESUID */
2363 suid = ruid = getuid ();
2364 sgid = rgid = getgid ();
2369 is_setuid = (ruid != euid || ruid != suid ||
2370 rgid != egid || rgid != sgid);
2372 g_once_init_leave (&check_setuid_initialised, 1);