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, see <http://www.gnu.org/licenses/>.
19 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
20 * file for a list of people on the GLib Team. See the ChangeLog
21 * files for a list of changes. These files are distributed with
22 * GLib at ftp://ftp.gtk.org/pub/gtk/.
26 * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
38 #include <ctype.h> /* For tolower() */
40 #include <sys/types.h>
46 #include <sys/types.h>
47 #ifdef HAVE_SYS_PARAM_H
48 #include <sys/param.h>
50 #ifdef HAVE_CRT_EXTERNS_H
51 #include <crt_externs.h> /* for _NSGetEnviron */
54 #include "glib-init.h"
55 #include "glib-private.h"
57 #include "gfileutils.h"
61 #include "gtestutils.h"
63 #include "gstrfuncs.h"
67 #ifdef G_PLATFORM_WIN32
75 * @title: Miscellaneous Utility Functions
76 * @short_description: a selection of portable utility functions
78 * These are portable utility functions.
81 #ifdef G_PLATFORM_WIN32
83 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
84 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
85 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
87 # include <lmcons.h> /* For UNLEN */
88 #endif /* G_PLATFORM_WIN32 */
93 /* older SDK (e.g. msvc 5.0) does not have these*/
94 # ifndef CSIDL_MYMUSIC
95 # define CSIDL_MYMUSIC 13
97 # ifndef CSIDL_MYVIDEO
98 # define CSIDL_MYVIDEO 14
100 # ifndef CSIDL_INTERNET_CACHE
101 # define CSIDL_INTERNET_CACHE 32
103 # ifndef CSIDL_COMMON_APPDATA
104 # define CSIDL_COMMON_APPDATA 35
106 # ifndef CSIDL_MYPICTURES
107 # define CSIDL_MYPICTURES 0x27
109 # ifndef CSIDL_COMMON_DOCUMENTS
110 # define CSIDL_COMMON_DOCUMENTS 46
112 # ifndef CSIDL_PROFILE
113 # define CSIDL_PROFILE 40
115 # include <process.h>
119 #include <CoreServices/CoreServices.h>
123 #include <langinfo.h>
126 #ifdef G_PLATFORM_WIN32
129 _glib_get_dll_directory (void)
133 wchar_t wc_fn
[MAX_PATH
];
136 if (glib_dll
== NULL
)
140 /* This code is different from that in
141 * g_win32_get_package_installation_directory_of_module() in that
142 * here we return the actual folder where the GLib DLL is. We don't
143 * do the check for it being in a "bin" or "lib" subfolder and then
144 * returning the parent of that.
146 * In a statically built GLib, glib_dll will be NULL and we will
147 * thus look up the application's .exe file's location.
149 if (!GetModuleFileNameW (glib_dll
, wc_fn
, MAX_PATH
))
152 retval
= g_utf16_to_utf8 (wc_fn
, -1, NULL
, NULL
, NULL
);
154 p
= strrchr (retval
, G_DIR_SEPARATOR
);
169 * @dest: the destination address to copy the bytes to.
170 * @src: the source address to copy the bytes from.
171 * @len: the number of bytes to copy.
173 * Copies a block of memory @len bytes long, from @src to @dest.
174 * The source and destination areas may overlap.
176 * Deprecated:2.40: Just use memmove().
185 * @func: (scope async): the function to call on normal program termination.
187 * Specifies a function to be called at normal program termination.
189 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
190 * macro that maps to a call to the atexit() function in the C
191 * library. This means that in case the code that calls g_atexit(),
192 * i.e. atexit(), is in a DLL, the function will be called when the
193 * DLL is detached from the program. This typically makes more sense
194 * than that the function is called when the GLib DLL is detached,
195 * which happened earlier when g_atexit() was a function in the GLib
198 * The behaviour of atexit() in the context of dynamically loaded
199 * modules is not formally specified and varies wildly.
201 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
202 * loaded module which is unloaded before the program terminates might
203 * well cause a crash at program exit.
205 * Some POSIX systems implement atexit() like Windows, and have each
206 * dynamically loaded module maintain an own atexit chain that is
207 * called when the module is unloaded.
209 * On other POSIX systems, before a dynamically loaded module is
210 * unloaded, the registered atexit functions (if any) residing in that
211 * module are called, regardless where the code that registered them
212 * resided. This is presumably the most robust approach.
214 * As can be seen from the above, for portability it's best to avoid
215 * calling g_atexit() (or atexit()) except in the main executable of a
218 * Deprecated:2.32: It is best to avoid g_atexit().
221 g_atexit (GVoidFunc func
)
225 result
= atexit ((void (*)(void)) func
);
228 g_error ("Could not register atexit() function: %s",
233 /* Based on execvp() from GNU Libc.
234 * Some of this code is cut-and-pasted into gspawn.c
238 my_strchrnul (const gchar
*str
,
241 gchar
*p
= (gchar
*)str
;
242 while (*p
&& (*p
!= c
))
250 static gchar
*inner_find_program_in_path (const gchar
*program
);
253 g_find_program_in_path (const gchar
*program
)
255 const gchar
*last_dot
= strrchr (program
, '.');
257 if (last_dot
== NULL
||
258 strchr (last_dot
, '\\') != NULL
||
259 strchr (last_dot
, '/') != NULL
)
261 const gint program_length
= strlen (program
);
262 gchar
*pathext
= g_build_path (";",
263 ".exe;.cmd;.bat;.com",
264 g_getenv ("PATHEXT"),
267 gchar
*decorated_program
;
273 gchar
*q
= my_strchrnul (p
, ';');
275 decorated_program
= g_malloc (program_length
+ (q
-p
) + 1);
276 memcpy (decorated_program
, program
, program_length
);
277 memcpy (decorated_program
+program_length
, p
, q
-p
);
278 decorated_program
[program_length
+ (q
-p
)] = '\0';
280 retval
= inner_find_program_in_path (decorated_program
);
281 g_free (decorated_program
);
289 } while (*p
++ != '\0');
294 return inner_find_program_in_path (program
);
300 * g_find_program_in_path:
301 * @program: a program name in the GLib file name encoding
303 * Locates the first executable named @program in the user's path, in the
304 * same way that execvp() would locate it. Returns an allocated string
305 * with the absolute path name, or %NULL if the program is not found in
306 * the path. If @program is already an absolute path, returns a copy of
307 * @program if @program exists and is executable, and %NULL otherwise.
309 * On Windows, if @program does not have a file type suffix, tries
310 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
311 * the `PATHEXT` environment variable.
313 * On Windows, it looks for the file in the same way as CreateProcess()
314 * would. This means first in the directory where the executing
315 * program was loaded from, then in the current directory, then in the
316 * Windows 32-bit system directory, then in the Windows directory, and
317 * finally in the directories in the `PATH` environment variable. If
318 * the program is found, the return value contains the full name
319 * including the type suffix.
321 * Returns: a newly-allocated string with the absolute path, or %NULL
325 inner_find_program_in_path (const gchar
*program
)
328 g_find_program_in_path (const gchar
*program
)
331 const gchar
*path
, *p
;
332 gchar
*name
, *freeme
;
334 const gchar
*path_copy
;
335 gchar
*filename
= NULL
, *appdir
= NULL
;
336 gchar
*sysdir
= NULL
, *windir
= NULL
;
338 wchar_t wfilename
[MAXPATHLEN
], wsysdir
[MAXPATHLEN
],
344 g_return_val_if_fail (program
!= NULL
, NULL
);
346 /* If it is an absolute path, or a relative path including subdirectories,
347 * don't look in PATH.
349 if (g_path_is_absolute (program
)
350 || strchr (program
, G_DIR_SEPARATOR
) != NULL
352 || strchr (program
, '/') != NULL
356 if (g_file_test (program
, G_FILE_TEST_IS_EXECUTABLE
) &&
357 !g_file_test (program
, G_FILE_TEST_IS_DIR
))
358 return g_strdup (program
);
363 path
= g_getenv ("PATH");
364 #if defined(G_OS_UNIX)
367 /* There is no 'PATH' in the environment. The default
368 * search path in GNU libc is the current directory followed by
369 * the path 'confstr' returns for '_CS_PATH'.
372 /* In GLib we put . last, for security, and don't use the
373 * unportable confstr(); UNIX98 does not actually specify
374 * what to search if PATH is unset. POSIX may, dunno.
377 path
= "/bin:/usr/bin:.";
380 n
= GetModuleFileNameW (NULL
, wfilename
, MAXPATHLEN
);
381 if (n
> 0 && n
< MAXPATHLEN
)
382 filename
= g_utf16_to_utf8 (wfilename
, -1, NULL
, NULL
, NULL
);
384 n
= GetSystemDirectoryW (wsysdir
, MAXPATHLEN
);
385 if (n
> 0 && n
< MAXPATHLEN
)
386 sysdir
= g_utf16_to_utf8 (wsysdir
, -1, NULL
, NULL
, NULL
);
388 n
= GetWindowsDirectoryW (wwindir
, MAXPATHLEN
);
389 if (n
> 0 && n
< MAXPATHLEN
)
390 windir
= g_utf16_to_utf8 (wwindir
, -1, NULL
, NULL
, NULL
);
394 appdir
= g_path_get_dirname (filename
);
398 path
= g_strdup (path
);
402 const gchar
*tem
= path
;
403 path
= g_strconcat (windir
, ";", path
, NULL
);
404 g_free ((gchar
*) tem
);
410 const gchar
*tem
= path
;
411 path
= g_strconcat (sysdir
, ";", path
, NULL
);
412 g_free ((gchar
*) tem
);
417 const gchar
*tem
= path
;
418 path
= g_strconcat (".;", path
, NULL
);
419 g_free ((gchar
*) tem
);
424 const gchar
*tem
= path
;
425 path
= g_strconcat (appdir
, ";", path
, NULL
);
426 g_free ((gchar
*) tem
);
433 len
= strlen (program
) + 1;
434 pathlen
= strlen (path
);
435 freeme
= name
= g_malloc (pathlen
+ len
+ 1);
437 /* Copy the file name at the top, including '\0' */
438 memcpy (name
+ pathlen
+ 1, program
, len
);
439 name
= name
+ pathlen
;
440 /* And add the slash before the filename */
441 *name
= G_DIR_SEPARATOR
;
449 p
= my_strchrnul (path
, G_SEARCHPATH_SEPARATOR
);
452 /* Two adjacent colons, or a colon at the beginning or the end
453 * of 'PATH' means to search the current directory.
457 startp
= memcpy (name
- (p
- path
), path
, p
- path
);
459 if (g_file_test (startp
, G_FILE_TEST_IS_EXECUTABLE
) &&
460 !g_file_test (startp
, G_FILE_TEST_IS_DIR
))
463 ret
= g_strdup (startp
);
466 g_free ((gchar
*) path_copy
);
471 while (*p
++ != '\0');
475 g_free ((gchar
*) path_copy
);
481 /* The functions below are defined this way for compatibility reasons.
482 * See the note in gutils.h.
487 * @mask: a #gulong containing flags
488 * @nth_bit: the index of the bit to start the search from
490 * Find the position of the first bit set in @mask, searching
491 * from (but not including) @nth_bit upwards. Bits are numbered
492 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
493 * usually). To start searching from the 0th bit, set @nth_bit to -1.
495 * Returns: the index of the first bit set which is higher than @nth_bit, or -1
496 * if no higher bits are set
499 (g_bit_nth_lsf
) (gulong mask
,
502 return g_bit_nth_lsf_impl (mask
, nth_bit
);
507 * @mask: a #gulong containing flags
508 * @nth_bit: the index of the bit to start the search from
510 * Find the position of the first bit set in @mask, searching
511 * from (but not including) @nth_bit downwards. Bits are numbered
512 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
513 * usually). To start searching from the last bit, set @nth_bit to
514 * -1 or GLIB_SIZEOF_LONG * 8.
516 * Returns: the index of the first bit set which is lower than @nth_bit, or -1
517 * if no lower bits are set
520 (g_bit_nth_msf
) (gulong mask
,
523 return g_bit_nth_msf_impl (mask
, nth_bit
);
531 * Gets the number of bits used to hold @number,
532 * e.g. if @number is 4, 3 bits are needed.
534 * Returns: the number of bits used to hold @number
537 (g_bit_storage
) (gulong number
)
539 return g_bit_storage_impl (number
);
542 G_LOCK_DEFINE_STATIC (g_utils_global
);
551 static gchar
*g_user_data_dir
= NULL
;
552 static gchar
**g_system_data_dirs
= NULL
;
553 static gchar
*g_user_cache_dir
= NULL
;
554 static gchar
*g_user_config_dir
= NULL
;
555 static gchar
**g_system_config_dirs
= NULL
;
557 static gchar
**g_user_special_dirs
= NULL
;
559 /* fifteen minutes of fame for everybody */
560 #define G_USER_DIRS_EXPIRE 15 * 60
565 get_special_folder (int csidl
)
567 wchar_t path
[MAX_PATH
+1];
569 LPITEMIDLIST pidl
= NULL
;
571 gchar
*retval
= NULL
;
573 hr
= SHGetSpecialFolderLocation (NULL
, csidl
, &pidl
);
576 b
= SHGetPathFromIDListW (pidl
, path
);
578 retval
= g_utf16_to_utf8 (path
, -1, NULL
, NULL
, NULL
);
579 CoTaskMemFree (pidl
);
585 get_windows_directory_root (void)
587 wchar_t wwindowsdir
[MAX_PATH
];
589 if (GetWindowsDirectoryW (wwindowsdir
, G_N_ELEMENTS (wwindowsdir
)))
591 /* Usually X:\Windows, but in terminal server environments
592 * might be an UNC path, AFAIK.
594 char *windowsdir
= g_utf16_to_utf8 (wwindowsdir
, -1, NULL
, NULL
, NULL
);
597 if (windowsdir
== NULL
)
598 return g_strdup ("C:\\");
600 p
= (char *) g_path_skip_root (windowsdir
);
601 if (G_IS_DIR_SEPARATOR (p
[-1]) && p
[-2] != ':')
607 return g_strdup ("C:\\");
612 /* HOLDS: g_utils_global_lock */
613 static UserDatabaseEntry
*
614 g_get_user_database_entry (void)
616 static UserDatabaseEntry
*entry
;
618 if (g_once_init_enter (&entry
))
620 static UserDatabaseEntry e
;
624 struct passwd
*pw
= NULL
;
625 gpointer buffer
= NULL
;
629 # if defined (HAVE_GETPWUID_R)
631 # ifdef _SC_GETPW_R_SIZE_MAX
632 /* This reurns the maximum length */
633 glong bufsize
= sysconf (_SC_GETPW_R_SIZE_MAX
);
637 # else /* _SC_GETPW_R_SIZE_MAX */
639 # endif /* _SC_GETPW_R_SIZE_MAX */
641 logname
= (gchar
*) g_getenv ("LOGNAME");
646 /* we allocate 6 extra bytes to work around a bug in
647 * Mac OS < 10.3. See #156446
649 buffer
= g_malloc (bufsize
+ 6);
653 error
= getpwnam_r (logname
, &pwd
, buffer
, bufsize
, &pw
);
654 if (!pw
|| (pw
->pw_uid
!= getuid ())) {
655 /* LOGNAME is lying, fall back to looking up the uid */
656 error
= getpwuid_r (getuid (), &pwd
, buffer
, bufsize
, &pw
);
659 error
= getpwuid_r (getuid (), &pwd
, buffer
, bufsize
, &pw
);
661 error
= error
< 0 ? errno
: error
;
665 /* we bail out prematurely if the user id can't be found
666 * (should be pretty rare case actually), or if the buffer
667 * should be sufficiently big and lookups are still not
670 if (error
== 0 || error
== ENOENT
)
672 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
676 if (bufsize
> 32 * 1024)
678 g_warning ("getpwuid_r(): failed due to: %s.",
687 # endif /* HAVE_GETPWUID_R */
691 pw
= getpwuid (getuid ());
695 e
.user_name
= g_strdup (pw
->pw_name
);
698 if (pw
->pw_gecos
&& *pw
->pw_gecos
!= '\0')
700 gchar
**gecos_fields
;
703 /* split the gecos field and substitute '&' */
704 gecos_fields
= g_strsplit (pw
->pw_gecos
, ",", 0);
705 name_parts
= g_strsplit (gecos_fields
[0], "&", 0);
706 pw
->pw_name
[0] = g_ascii_toupper (pw
->pw_name
[0]);
707 e
.real_name
= g_strjoinv (pw
->pw_name
, name_parts
);
708 g_strfreev (gecos_fields
);
709 g_strfreev (name_parts
);
714 e
.home_dir
= g_strdup (pw
->pw_dir
);
719 #endif /* G_OS_UNIX */
724 wchar_t buffer
[UNLEN
+1];
726 if (GetUserNameW (buffer
, (LPDWORD
) &len
))
728 e
.user_name
= g_utf16_to_utf8 (buffer
, -1, NULL
, NULL
, NULL
);
729 e
.real_name
= g_strdup (e
.user_name
);
732 #endif /* G_OS_WIN32 */
735 e
.user_name
= g_strdup ("somebody");
737 e
.real_name
= g_strdup ("Unknown");
739 g_once_init_leave (&entry
, &e
);
748 * Gets the user name of the current user. The encoding of the returned
749 * string is system-defined. On UNIX, it might be the preferred file name
750 * encoding, or something else, and there is no guarantee that it is even
751 * consistent on a machine. On Windows, it is always UTF-8.
753 * Returns: the user name of the current user.
756 g_get_user_name (void)
758 UserDatabaseEntry
*entry
;
760 entry
= g_get_user_database_entry ();
762 return entry
->user_name
;
768 * Gets the real name of the user. This usually comes from the user's
769 * entry in the `passwd` file. The encoding of the returned string is
770 * system-defined. (On Windows, it is, however, always UTF-8.) If the
771 * real user name cannot be determined, the string "Unknown" is
774 * Returns: the user's real name.
777 g_get_real_name (void)
779 UserDatabaseEntry
*entry
;
781 entry
= g_get_user_database_entry ();
783 return entry
->real_name
;
789 * Gets the current user's home directory.
791 * As with most UNIX tools, this function will return the value of the
792 * `HOME` environment variable if it is set to an existing absolute path
793 * name, falling back to the `passwd` file in the case that it is unset.
795 * If the path given in `HOME` is non-absolute, does not exist, or is
796 * not a directory, the result is undefined.
798 * Before version 2.36 this function would ignore the `HOME` environment
799 * variable, taking the value from the `passwd` database instead. This was
800 * changed to increase the compatibility of GLib with other programs (and
801 * the XDG basedir specification) and to increase testability of programs
802 * based on GLib (by making it easier to run them from test frameworks).
804 * If your program has a strong requirement for either the new or the
805 * old behaviour (and if you don't wish to increase your GLib
806 * dependency to ensure that the new behaviour is in effect) then you
807 * should either directly check the `HOME` environment variable yourself
808 * or unset it before calling any functions in GLib.
810 * Returns: the current user's home directory
813 g_get_home_dir (void)
815 static gchar
*home_dir
;
817 if (g_once_init_enter (&home_dir
))
821 /* We first check HOME and use it if it is set */
822 tmp
= g_strdup (g_getenv ("HOME"));
825 /* Only believe HOME if it is an absolute path and exists.
827 * We only do this check on Windows for a couple of reasons.
828 * Historically, we only did it there because we used to ignore $HOME
829 * on UNIX. There are concerns about enabling it now on UNIX because
830 * of things like autofs. In short, if the user has a bogus value in
831 * $HOME then they get what they pay for...
835 if (!(g_path_is_absolute (tmp
) &&
836 g_file_test (tmp
, G_FILE_TEST_IS_DIR
)))
843 /* In case HOME is Unix-style (it happens), convert it to
849 while ((p
= strchr (tmp
, '/')) != NULL
)
855 /* USERPROFILE is probably the closest equivalent to $HOME? */
856 if (g_getenv ("USERPROFILE") != NULL
)
857 tmp
= g_strdup (g_getenv ("USERPROFILE"));
861 tmp
= get_special_folder (CSIDL_PROFILE
);
864 tmp
= get_windows_directory_root ();
865 #endif /* G_OS_WIN32 */
869 /* If we didn't get it from any of those methods, we will have
870 * to read the user database entry.
872 UserDatabaseEntry
*entry
;
874 entry
= g_get_user_database_entry ();
876 /* Strictly speaking, we should copy this, but we know that
877 * neither will ever be freed, so don't bother...
879 tmp
= entry
->home_dir
;
882 g_once_init_leave (&home_dir
, tmp
);
891 * Gets the directory to use for temporary files.
893 * On UNIX, this is taken from the `TMPDIR` environment variable.
894 * If the variable is not set, `P_tmpdir` is
895 * used, as defined by the system C library. Failing that, a
896 * hard-coded default of "/tmp" is returned.
898 * On Windows, the `TEMP` environment variable is used, with the
899 * root directory of the Windows installation (eg: "C:\") used
902 * The encoding of the returned string is system-defined. On Windows,
903 * it is always UTF-8. The return value is never %NULL or the empty
906 * Returns: the directory to use for temporary files.
911 static gchar
*tmp_dir
;
913 if (g_once_init_enter (&tmp_dir
))
918 tmp
= g_strdup (g_getenv ("TEMP"));
920 if (tmp
== NULL
|| *tmp
== '\0')
923 tmp
= get_windows_directory_root ();
925 #else /* G_OS_WIN32 */
926 tmp
= g_strdup (g_getenv ("TMPDIR"));
929 if (tmp
== NULL
|| *tmp
== '\0')
933 tmp
= g_strdup (P_tmpdir
);
935 if (k
> 1 && G_IS_DIR_SEPARATOR (tmp
[k
- 1]))
938 #endif /* P_tmpdir */
940 if (tmp
== NULL
|| *tmp
== '\0')
943 tmp
= g_strdup ("/tmp");
945 #endif /* !G_OS_WIN32 */
947 g_once_init_leave (&tmp_dir
, tmp
);
956 * Return a name for the machine.
958 * The returned name is not necessarily a fully-qualified domain name,
959 * or even present in DNS or some other name service at all. It need
960 * not even be unique on your local network or site, but usually it
961 * is. Callers should not rely on the return value having any specific
962 * properties like uniqueness for security purposes. Even if the name
963 * of the machine is changed while an application is running, the
964 * return value from this function does not change. The returned
965 * string is owned by GLib and should not be modified or freed. If no
966 * name can be determined, a default fixed string "localhost" is
969 * Returns: the host name of the machine.
974 g_get_host_name (void)
976 static gchar
*hostname
;
978 if (g_once_init_enter (&hostname
))
984 failed
= (gethostname (tmp
, sizeof (tmp
)) == -1);
986 DWORD size
= sizeof (tmp
);
987 failed
= (!GetComputerName (tmp
, &size
));
990 g_once_init_leave (&hostname
, g_strdup (failed
? "localhost" : tmp
));
996 G_LOCK_DEFINE_STATIC (g_prgname
);
997 static gchar
*g_prgname
= NULL
;
1002 * Gets the name of the program. This name should not be localized,
1003 * in contrast to g_get_application_name().
1005 * If you are using GDK or GTK+ the program name is set in gdk_init(),
1006 * which is called by gtk_init(). The program name is found by taking
1007 * the last component of @argv[0].
1009 * Returns: the name of the program. The returned string belongs
1010 * to GLib and must not be modified or freed.
1013 g_get_prgname (void)
1019 if (g_prgname
== NULL
)
1021 static gboolean beenhere
= FALSE
;
1025 gchar
*utf8_buf
= NULL
;
1026 wchar_t buf
[MAX_PATH
+1];
1029 if (GetModuleFileNameW (GetModuleHandle (NULL
),
1030 buf
, G_N_ELEMENTS (buf
)) > 0)
1031 utf8_buf
= g_utf16_to_utf8 (buf
, -1, NULL
, NULL
, NULL
);
1035 g_prgname
= g_path_get_basename (utf8_buf
);
1042 G_UNLOCK (g_prgname
);
1049 * @prgname: the name of the program.
1051 * Sets the name of the program. This name should not be localized,
1052 * in contrast to g_set_application_name().
1054 * Note that for thread-safety reasons this function can only be called once.
1057 g_set_prgname (const gchar
*prgname
)
1061 g_prgname
= g_strdup (prgname
);
1062 G_UNLOCK (g_prgname
);
1065 G_LOCK_DEFINE_STATIC (g_application_name
);
1066 static gchar
*g_application_name
= NULL
;
1069 * g_get_application_name:
1071 * Gets a human-readable name for the application, as set by
1072 * g_set_application_name(). This name should be localized if
1073 * possible, and is intended for display to the user. Contrast with
1074 * g_get_prgname(), which gets a non-localized name. If
1075 * g_set_application_name() has not been called, returns the result of
1076 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1079 * Returns: human-readable application name. may return %NULL
1084 g_get_application_name (void)
1088 G_LOCK (g_application_name
);
1089 retval
= g_application_name
;
1090 G_UNLOCK (g_application_name
);
1093 return g_get_prgname ();
1099 * g_set_application_name:
1100 * @application_name: localized name of the application
1102 * Sets a human-readable name for the application. This name should be
1103 * localized if possible, and is intended for display to the user.
1104 * Contrast with g_set_prgname(), which sets a non-localized name.
1105 * g_set_prgname() will be called automatically by gtk_init(),
1106 * but g_set_application_name() will not.
1108 * Note that for thread safety reasons, this function can only
1111 * The application name will be used in contexts such as error messages,
1112 * or when displaying an application's name in the task list.
1117 g_set_application_name (const gchar
*application_name
)
1119 gboolean already_set
= FALSE
;
1121 G_LOCK (g_application_name
);
1122 if (g_application_name
)
1125 g_application_name
= g_strdup (application_name
);
1126 G_UNLOCK (g_application_name
);
1129 g_warning ("g_set_application_name() called multiple times");
1133 * g_get_user_data_dir:
1135 * Returns a base directory in which to access application data such
1136 * as icons that is customized for a particular user.
1138 * On UNIX platforms this is determined using the mechanisms described
1140 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1141 * In this case the directory retrieved will be `XDG_DATA_HOME`.
1143 * On Windows this is the folder to use for local (as opposed to
1144 * roaming) application data. See documentation for
1145 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1146 * what g_get_user_config_dir() returns.
1148 * Returns: a string owned by GLib that must not be modified
1153 g_get_user_data_dir (void)
1157 G_LOCK (g_utils_global
);
1159 if (!g_user_data_dir
)
1162 data_dir
= get_special_folder (CSIDL_LOCAL_APPDATA
);
1164 data_dir
= (gchar
*) g_getenv ("XDG_DATA_HOME");
1166 if (data_dir
&& data_dir
[0])
1167 data_dir
= g_strdup (data_dir
);
1169 if (!data_dir
|| !data_dir
[0])
1171 const gchar
*home_dir
= g_get_home_dir ();
1174 data_dir
= g_build_filename (home_dir
, ".local", "share", NULL
);
1176 data_dir
= g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".local", "share", NULL
);
1179 g_user_data_dir
= data_dir
;
1182 data_dir
= g_user_data_dir
;
1184 G_UNLOCK (g_utils_global
);
1190 g_init_user_config_dir (void)
1194 if (!g_user_config_dir
)
1197 config_dir
= get_special_folder (CSIDL_LOCAL_APPDATA
);
1199 config_dir
= (gchar
*) g_getenv ("XDG_CONFIG_HOME");
1201 if (config_dir
&& config_dir
[0])
1202 config_dir
= g_strdup (config_dir
);
1204 if (!config_dir
|| !config_dir
[0])
1206 const gchar
*home_dir
= g_get_home_dir ();
1209 config_dir
= g_build_filename (home_dir
, ".config", NULL
);
1211 config_dir
= g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".config", NULL
);
1214 g_user_config_dir
= config_dir
;
1219 * g_get_user_config_dir:
1221 * Returns a base directory in which to store user-specific application
1222 * configuration information such as user preferences and settings.
1224 * On UNIX platforms this is determined using the mechanisms described
1226 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1227 * In this case the directory retrieved will be `XDG_CONFIG_HOME`.
1229 * On Windows this is the folder to use for local (as opposed to
1230 * roaming) application data. See documentation for
1231 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1232 * what g_get_user_data_dir() returns.
1234 * Returns: a string owned by GLib that must not be modified
1239 g_get_user_config_dir (void)
1241 G_LOCK (g_utils_global
);
1243 g_init_user_config_dir ();
1245 G_UNLOCK (g_utils_global
);
1247 return g_user_config_dir
;
1251 * g_get_user_cache_dir:
1253 * Returns a base directory in which to store non-essential, cached
1254 * data specific to particular user.
1256 * On UNIX platforms this is determined using the mechanisms described
1258 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1259 * In this case the directory retrieved will be XDG_CACHE_HOME.
1261 * On Windows is the directory that serves as a common repository for
1262 * temporary Internet files. A typical path is
1263 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
1264 * See documentation for CSIDL_INTERNET_CACHE.
1266 * Returns: a string owned by GLib that must not be modified
1271 g_get_user_cache_dir (void)
1275 G_LOCK (g_utils_global
);
1277 if (!g_user_cache_dir
)
1280 cache_dir
= get_special_folder (CSIDL_INTERNET_CACHE
); /* XXX correct? */
1282 cache_dir
= (gchar
*) g_getenv ("XDG_CACHE_HOME");
1284 if (cache_dir
&& cache_dir
[0])
1285 cache_dir
= g_strdup (cache_dir
);
1287 if (!cache_dir
|| !cache_dir
[0])
1289 const gchar
*home_dir
= g_get_home_dir ();
1292 cache_dir
= g_build_filename (home_dir
, ".cache", NULL
);
1294 cache_dir
= g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".cache", NULL
);
1296 g_user_cache_dir
= cache_dir
;
1299 cache_dir
= g_user_cache_dir
;
1301 G_UNLOCK (g_utils_global
);
1307 * g_get_user_runtime_dir:
1309 * Returns a directory that is unique to the current user on the local
1312 * On UNIX platforms this is determined using the mechanisms described
1314 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1315 * This is the directory
1316 * specified in the `XDG_RUNTIME_DIR` environment variable.
1317 * In the case that this variable is not set, we return the value of
1318 * g_get_user_cache_dir(), after verifying that it exists.
1320 * On Windows this is the folder to use for local (as opposed to
1321 * roaming) application data. See documentation for
1322 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1323 * what g_get_user_config_dir() returns.
1325 * Returns: a string owned by GLib that must not be modified or freed.
1330 g_get_user_runtime_dir (void)
1333 static const gchar
*runtime_dir
;
1335 if (g_once_init_enter (&runtime_dir
))
1339 dir
= g_strdup (getenv ("XDG_RUNTIME_DIR"));
1343 /* No need to strdup this one since it is valid forever. */
1344 dir
= g_get_user_cache_dir ();
1346 /* The user should be able to rely on the directory existing
1347 * when the function returns. Probably it already does, but
1348 * let's make sure. Just do mkdir() directly since it will be
1349 * no more expensive than a stat() in the case that the
1350 * directory already exists and is a lot easier.
1352 * $XDG_CACHE_HOME is probably ~/.cache/ so as long as $HOME
1353 * exists this will work. If the user changed $XDG_CACHE_HOME
1354 * then they can make sure that it exists...
1356 (void) mkdir (dir
, 0700);
1359 g_assert (dir
!= NULL
);
1361 g_once_init_leave (&runtime_dir
, dir
);
1366 return g_get_user_cache_dir ();
1373 find_folder (OSType type
)
1375 gchar
*filename
= NULL
;
1378 if (FSFindFolder (kUserDomain
, type
, kDontCreateFolder
, &found
) == noErr
)
1380 CFURLRef url
= CFURLCreateFromFSRef (kCFAllocatorSystemDefault
, &found
);
1384 CFStringRef path
= CFURLCopyFileSystemPath (url
, kCFURLPOSIXPathStyle
);
1388 filename
= g_strdup (CFStringGetCStringPtr (path
, kCFStringEncodingUTF8
));
1392 filename
= g_new0 (gchar
, CFStringGetLength (path
) * 3 + 1);
1394 CFStringGetCString (path
, filename
,
1395 CFStringGetLength (path
) * 3 + 1,
1396 kCFStringEncodingUTF8
);
1410 load_user_special_dirs (void)
1412 g_user_special_dirs
[G_USER_DIRECTORY_DESKTOP
] = find_folder (kDesktopFolderType
);
1413 g_user_special_dirs
[G_USER_DIRECTORY_DOCUMENTS
] = find_folder (kDocumentsFolderType
);
1414 g_user_special_dirs
[G_USER_DIRECTORY_DOWNLOAD
] = find_folder (kDesktopFolderType
); /* XXX correct ? */
1415 g_user_special_dirs
[G_USER_DIRECTORY_MUSIC
] = find_folder (kMusicDocumentsFolderType
);
1416 g_user_special_dirs
[G_USER_DIRECTORY_PICTURES
] = find_folder (kPictureDocumentsFolderType
);
1417 g_user_special_dirs
[G_USER_DIRECTORY_PUBLIC_SHARE
] = NULL
;
1418 g_user_special_dirs
[G_USER_DIRECTORY_TEMPLATES
] = NULL
;
1419 g_user_special_dirs
[G_USER_DIRECTORY_VIDEOS
] = find_folder (kMovieDocumentsFolderType
);
1422 #elif defined(G_OS_WIN32)
1425 load_user_special_dirs (void)
1427 typedef HRESULT (WINAPI
*t_SHGetKnownFolderPath
) (const GUID
*rfid
,
1431 t_SHGetKnownFolderPath p_SHGetKnownFolderPath
;
1433 static const GUID FOLDERID_Downloads
=
1434 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1435 static const GUID FOLDERID_Public
=
1436 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1440 p_SHGetKnownFolderPath
= (t_SHGetKnownFolderPath
) GetProcAddress (GetModuleHandle ("shell32.dll"),
1441 "SHGetKnownFolderPath");
1443 g_user_special_dirs
[G_USER_DIRECTORY_DESKTOP
] = get_special_folder (CSIDL_DESKTOPDIRECTORY
);
1444 g_user_special_dirs
[G_USER_DIRECTORY_DOCUMENTS
] = get_special_folder (CSIDL_PERSONAL
);
1446 if (p_SHGetKnownFolderPath
== NULL
)
1448 g_user_special_dirs
[G_USER_DIRECTORY_DOWNLOAD
] = get_special_folder (CSIDL_DESKTOPDIRECTORY
);
1453 (*p_SHGetKnownFolderPath
) (&FOLDERID_Downloads
, 0, NULL
, &wcp
);
1456 g_user_special_dirs
[G_USER_DIRECTORY_DOWNLOAD
] = g_utf16_to_utf8 (wcp
, -1, NULL
, NULL
, NULL
);
1457 if (g_user_special_dirs
[G_USER_DIRECTORY_DOWNLOAD
] == NULL
)
1458 g_user_special_dirs
[G_USER_DIRECTORY_DOWNLOAD
] = get_special_folder (CSIDL_DESKTOPDIRECTORY
);
1459 CoTaskMemFree (wcp
);
1462 g_user_special_dirs
[G_USER_DIRECTORY_DOWNLOAD
] = get_special_folder (CSIDL_DESKTOPDIRECTORY
);
1465 g_user_special_dirs
[G_USER_DIRECTORY_MUSIC
] = get_special_folder (CSIDL_MYMUSIC
);
1466 g_user_special_dirs
[G_USER_DIRECTORY_PICTURES
] = get_special_folder (CSIDL_MYPICTURES
);
1468 if (p_SHGetKnownFolderPath
== NULL
)
1471 g_user_special_dirs
[G_USER_DIRECTORY_PUBLIC_SHARE
] = get_special_folder (CSIDL_COMMON_DOCUMENTS
);
1476 (*p_SHGetKnownFolderPath
) (&FOLDERID_Public
, 0, NULL
, &wcp
);
1479 g_user_special_dirs
[G_USER_DIRECTORY_PUBLIC_SHARE
] = g_utf16_to_utf8 (wcp
, -1, NULL
, NULL
, NULL
);
1480 if (g_user_special_dirs
[G_USER_DIRECTORY_PUBLIC_SHARE
] == NULL
)
1481 g_user_special_dirs
[G_USER_DIRECTORY_PUBLIC_SHARE
] = get_special_folder (CSIDL_COMMON_DOCUMENTS
);
1482 CoTaskMemFree (wcp
);
1485 g_user_special_dirs
[G_USER_DIRECTORY_PUBLIC_SHARE
] = get_special_folder (CSIDL_COMMON_DOCUMENTS
);
1488 g_user_special_dirs
[G_USER_DIRECTORY_TEMPLATES
] = get_special_folder (CSIDL_TEMPLATES
);
1489 g_user_special_dirs
[G_USER_DIRECTORY_VIDEOS
] = get_special_folder (CSIDL_MYVIDEO
);
1492 #else /* default is unix */
1494 /* adapted from xdg-user-dir-lookup.c
1496 * Copyright (C) 2007 Red Hat Inc.
1498 * Permission is hereby granted, free of charge, to any person
1499 * obtaining a copy of this software and associated documentation files
1500 * (the "Software"), to deal in the Software without restriction,
1501 * including without limitation the rights to use, copy, modify, merge,
1502 * publish, distribute, sublicense, and/or sell copies of the Software,
1503 * and to permit persons to whom the Software is furnished to do so,
1504 * subject to the following conditions:
1506 * The above copyright notice and this permission notice shall be
1507 * included in all copies or substantial portions of the Software.
1509 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1510 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1511 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1512 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1513 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1514 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1515 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1519 load_user_special_dirs (void)
1526 g_init_user_config_dir ();
1527 config_file
= g_build_filename (g_user_config_dir
,
1531 if (!g_file_get_contents (config_file
, &data
, NULL
, NULL
))
1533 g_free (config_file
);
1537 lines
= g_strsplit (data
, "\n", -1);
1538 n_lines
= g_strv_length (lines
);
1541 for (i
= 0; i
< n_lines
; i
++)
1543 gchar
*buffer
= lines
[i
];
1546 gboolean is_relative
= FALSE
;
1547 GUserDirectory directory
;
1549 /* Remove newline at end */
1550 len
= strlen (buffer
);
1551 if (len
> 0 && buffer
[len
- 1] == '\n')
1552 buffer
[len
- 1] = 0;
1555 while (*p
== ' ' || *p
== '\t')
1558 if (strncmp (p
, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
1560 directory
= G_USER_DIRECTORY_DESKTOP
;
1561 p
+= strlen ("XDG_DESKTOP_DIR");
1563 else if (strncmp (p
, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
1565 directory
= G_USER_DIRECTORY_DOCUMENTS
;
1566 p
+= strlen ("XDG_DOCUMENTS_DIR");
1568 else if (strncmp (p
, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
1570 directory
= G_USER_DIRECTORY_DOWNLOAD
;
1571 p
+= strlen ("XDG_DOWNLOAD_DIR");
1573 else if (strncmp (p
, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
1575 directory
= G_USER_DIRECTORY_MUSIC
;
1576 p
+= strlen ("XDG_MUSIC_DIR");
1578 else if (strncmp (p
, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
1580 directory
= G_USER_DIRECTORY_PICTURES
;
1581 p
+= strlen ("XDG_PICTURES_DIR");
1583 else if (strncmp (p
, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
1585 directory
= G_USER_DIRECTORY_PUBLIC_SHARE
;
1586 p
+= strlen ("XDG_PUBLICSHARE_DIR");
1588 else if (strncmp (p
, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
1590 directory
= G_USER_DIRECTORY_TEMPLATES
;
1591 p
+= strlen ("XDG_TEMPLATES_DIR");
1593 else if (strncmp (p
, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
1595 directory
= G_USER_DIRECTORY_VIDEOS
;
1596 p
+= strlen ("XDG_VIDEOS_DIR");
1601 while (*p
== ' ' || *p
== '\t')
1608 while (*p
== ' ' || *p
== '\t')
1615 if (strncmp (p
, "$HOME", 5) == 0)
1623 d
= strrchr (p
, '"');
1630 /* remove trailing slashes */
1632 if (d
[len
- 1] == '/')
1637 g_user_special_dirs
[directory
] = g_build_filename (g_get_home_dir (), d
, NULL
);
1640 g_user_special_dirs
[directory
] = g_strdup (d
);
1644 g_free (config_file
);
1647 #endif /* platform-specific load_user_special_dirs implementations */
1651 * g_reload_user_special_dirs_cache:
1653 * Resets the cache used for g_get_user_special_dir(), so
1654 * that the latest on-disk version is used. Call this only
1655 * if you just changed the data on disk yourself.
1657 * Due to threadsafety issues this may cause leaking of strings
1658 * that were previously returned from g_get_user_special_dir()
1659 * that can't be freed. We ensure to only leak the data for
1660 * the directories that actually changed value though.
1665 g_reload_user_special_dirs_cache (void)
1669 G_LOCK (g_utils_global
);
1671 if (g_user_special_dirs
!= NULL
)
1673 /* save a copy of the pointer, to check if some memory can be preserved */
1674 char **old_g_user_special_dirs
= g_user_special_dirs
;
1677 /* recreate and reload our cache */
1678 g_user_special_dirs
= g_new0 (gchar
*, G_USER_N_DIRECTORIES
);
1679 load_user_special_dirs ();
1681 /* only leak changed directories */
1682 for (i
= 0; i
< G_USER_N_DIRECTORIES
; i
++)
1684 old_val
= old_g_user_special_dirs
[i
];
1685 if (g_user_special_dirs
[i
] == NULL
)
1687 g_user_special_dirs
[i
] = old_val
;
1689 else if (g_strcmp0 (old_val
, g_user_special_dirs
[i
]) == 0)
1692 g_free (g_user_special_dirs
[i
]);
1693 g_user_special_dirs
[i
] = old_val
;
1699 /* free the old array */
1700 g_free (old_g_user_special_dirs
);
1703 G_UNLOCK (g_utils_global
);
1707 * g_get_user_special_dir:
1708 * @directory: the logical id of special directory
1710 * Returns the full path of a special directory using its logical id.
1712 * On UNIX this is done using the XDG special user directories.
1713 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
1714 * falls back to `$HOME/Desktop` when XDG special user directories have
1717 * Depending on the platform, the user might be able to change the path
1718 * of the special directory without requiring the session to restart; GLib
1719 * will not reflect any change once the special directories are loaded.
1721 * Returns: the path to the specified special directory, or %NULL
1722 * if the logical id was not found. The returned string is owned by
1723 * GLib and should not be modified or freed.
1728 g_get_user_special_dir (GUserDirectory directory
)
1730 g_return_val_if_fail (directory
>= G_USER_DIRECTORY_DESKTOP
&&
1731 directory
< G_USER_N_DIRECTORIES
, NULL
);
1733 G_LOCK (g_utils_global
);
1735 if (G_UNLIKELY (g_user_special_dirs
== NULL
))
1737 g_user_special_dirs
= g_new0 (gchar
*, G_USER_N_DIRECTORIES
);
1739 load_user_special_dirs ();
1741 /* Special-case desktop for historical compatibility */
1742 if (g_user_special_dirs
[G_USER_DIRECTORY_DESKTOP
] == NULL
)
1743 g_user_special_dirs
[G_USER_DIRECTORY_DESKTOP
] = g_build_filename (g_get_home_dir (), "Desktop", NULL
);
1746 G_UNLOCK (g_utils_global
);
1748 return g_user_special_dirs
[directory
];
1753 #undef g_get_system_data_dirs
1756 get_module_for_address (gconstpointer address
)
1758 /* Holds the g_utils_global lock */
1760 static gboolean beenhere
= FALSE
;
1761 typedef BOOL (WINAPI
*t_GetModuleHandleExA
) (DWORD
, LPCTSTR
, HMODULE
*);
1762 static t_GetModuleHandleExA p_GetModuleHandleExA
= NULL
;
1763 HMODULE hmodule
= NULL
;
1770 p_GetModuleHandleExA
=
1771 (t_GetModuleHandleExA
) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1772 "GetModuleHandleExA");
1776 if (p_GetModuleHandleExA
== NULL
||
1777 !(*p_GetModuleHandleExA
) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
|
1778 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
,
1781 MEMORY_BASIC_INFORMATION mbi
;
1782 VirtualQuery (address
, &mbi
, sizeof (mbi
));
1783 hmodule
= (HMODULE
) mbi
.AllocationBase
;
1790 get_module_share_dir (gconstpointer address
)
1796 hmodule
= get_module_for_address (address
);
1797 if (hmodule
== NULL
)
1800 filename
= g_win32_get_package_installation_directory_of_module (hmodule
);
1801 retval
= g_build_filename (filename
, "share", NULL
);
1807 const gchar
* const *
1808 g_win32_get_system_data_dirs_for_module (void (*address_of_function
)(void))
1812 static GHashTable
*per_module_data_dirs
= NULL
;
1818 if (address_of_function
)
1820 G_LOCK (g_utils_global
);
1821 hmodule
= get_module_for_address (address_of_function
);
1822 if (hmodule
!= NULL
)
1824 if (per_module_data_dirs
== NULL
)
1825 per_module_data_dirs
= g_hash_table_new (NULL
, NULL
);
1828 retval
= g_hash_table_lookup (per_module_data_dirs
, hmodule
);
1832 G_UNLOCK (g_utils_global
);
1833 return (const gchar
* const *) retval
;
1839 data_dirs
= g_array_new (TRUE
, TRUE
, sizeof (char *));
1841 /* Documents and Settings\All Users\Application Data */
1842 p
= get_special_folder (CSIDL_COMMON_APPDATA
);
1844 g_array_append_val (data_dirs
, p
);
1846 /* Documents and Settings\All Users\Documents */
1847 p
= get_special_folder (CSIDL_COMMON_DOCUMENTS
);
1849 g_array_append_val (data_dirs
, p
);
1851 /* Using the above subfolders of Documents and Settings perhaps
1852 * makes sense from a Windows perspective.
1854 * But looking at the actual use cases of this function in GTK+
1855 * and GNOME software, what we really want is the "share"
1856 * subdirectory of the installation directory for the package
1857 * our caller is a part of.
1859 * The address_of_function parameter, if non-NULL, points to a
1860 * function in the calling module. Use that to determine that
1861 * module's installation folder, and use its "share" subfolder.
1863 * Additionally, also use the "share" subfolder of the installation
1864 * locations of GLib and the .exe file being run.
1866 * To guard against none of the above being what is really wanted,
1867 * callers of this function should have Win32-specific code to look
1868 * up their installation folder themselves, and handle a subfolder
1869 * "share" of it in the same way as the folders returned from this
1873 p
= get_module_share_dir (address_of_function
);
1875 g_array_append_val (data_dirs
, p
);
1877 if (glib_dll
!= NULL
)
1879 gchar
*glib_root
= g_win32_get_package_installation_directory_of_module (glib_dll
);
1880 p
= g_build_filename (glib_root
, "share", NULL
);
1882 g_array_append_val (data_dirs
, p
);
1886 exe_root
= g_win32_get_package_installation_directory_of_module (NULL
);
1887 p
= g_build_filename (exe_root
, "share", NULL
);
1889 g_array_append_val (data_dirs
, p
);
1892 retval
= (gchar
**) g_array_free (data_dirs
, FALSE
);
1894 if (address_of_function
)
1896 if (hmodule
!= NULL
)
1897 g_hash_table_insert (per_module_data_dirs
, hmodule
, retval
);
1898 G_UNLOCK (g_utils_global
);
1901 return (const gchar
* const *) retval
;
1907 * g_get_system_data_dirs:
1909 * Returns an ordered list of base directories in which to access
1910 * system-wide application data.
1912 * On UNIX platforms this is determined using the mechanisms described
1914 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec)
1915 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
1917 * On Windows the first elements in the list are the Application Data
1918 * and Documents folders for All Users. (These can be determined only
1919 * on Windows 2000 or later and are not present in the list on other
1920 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
1921 * CSIDL_COMMON_DOCUMENTS.
1923 * Then follows the "share" subfolder in the installation folder for
1924 * the package containing the DLL that calls this function, if it can
1927 * Finally the list contains the "share" subfolder in the installation
1928 * folder for GLib, and in the installation folder for the package the
1929 * application's .exe file belongs to.
1931 * The installation folders above are determined by looking up the
1932 * folder where the module (DLL or EXE) in question is located. If the
1933 * folder's name is "bin", its parent is used, otherwise the folder
1936 * Note that on Windows the returned list can vary depending on where
1937 * this function is called.
1939 * Returns: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
1940 * not be modified or freed.
1943 const gchar
* const *
1944 g_get_system_data_dirs (void)
1946 gchar
**data_dir_vector
;
1948 G_LOCK (g_utils_global
);
1950 if (!g_system_data_dirs
)
1953 data_dir_vector
= (gchar
**) g_win32_get_system_data_dirs_for_module (NULL
);
1955 gchar
*data_dirs
= (gchar
*) g_getenv ("XDG_DATA_DIRS");
1957 if (!data_dirs
|| !data_dirs
[0])
1958 data_dirs
= "/usr/local/share/:/usr/share/";
1960 data_dir_vector
= g_strsplit (data_dirs
, G_SEARCHPATH_SEPARATOR_S
, 0);
1963 g_system_data_dirs
= data_dir_vector
;
1966 data_dir_vector
= g_system_data_dirs
;
1968 G_UNLOCK (g_utils_global
);
1970 return (const gchar
* const *) data_dir_vector
;
1974 * g_get_system_config_dirs:
1976 * Returns an ordered list of base directories in which to access
1977 * system-wide configuration information.
1979 * On UNIX platforms this is determined using the mechanisms described
1981 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1982 * In this case the list of directories retrieved will be `XDG_CONFIG_DIRS`.
1984 * On Windows is the directory that contains application data for all users.
1985 * A typical path is C:\Documents and Settings\All Users\Application Data.
1986 * This folder is used for application data that is not user specific.
1987 * For example, an application can store a spell-check dictionary, a database
1988 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
1989 * This information will not roam and is available to anyone using the computer.
1991 * Returns: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
1992 * not be modified or freed.
1995 const gchar
* const *
1996 g_get_system_config_dirs (void)
1998 gchar
*conf_dirs
, **conf_dir_vector
;
2000 G_LOCK (g_utils_global
);
2002 if (!g_system_config_dirs
)
2005 conf_dirs
= get_special_folder (CSIDL_COMMON_APPDATA
);
2008 conf_dir_vector
= g_strsplit (conf_dirs
, G_SEARCHPATH_SEPARATOR_S
, 0);
2013 /* Return empty list */
2014 conf_dir_vector
= g_strsplit ("", G_SEARCHPATH_SEPARATOR_S
, 0);
2017 conf_dirs
= (gchar
*) g_getenv ("XDG_CONFIG_DIRS");
2019 if (!conf_dirs
|| !conf_dirs
[0])
2020 conf_dirs
= "/etc/xdg";
2022 conf_dir_vector
= g_strsplit (conf_dirs
, G_SEARCHPATH_SEPARATOR_S
, 0);
2025 g_system_config_dirs
= conf_dir_vector
;
2028 conf_dir_vector
= g_system_config_dirs
;
2029 G_UNLOCK (g_utils_global
);
2031 return (const gchar
* const *) conf_dir_vector
;
2035 * g_nullify_pointer:
2036 * @nullify_location: (not nullable): the memory address of the pointer.
2038 * Set the pointer at the specified location to %NULL.
2041 g_nullify_pointer (gpointer
*nullify_location
)
2043 g_return_if_fail (nullify_location
!= NULL
);
2045 *nullify_location
= NULL
;
2048 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2049 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2050 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2051 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2052 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2053 #define EXABYTE_FACTOR (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2055 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2056 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2057 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2058 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2059 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2060 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2064 * @size: a size in bytes
2066 * Formats a size (for example the size of a file) into a human readable
2067 * string. Sizes are rounded to the nearest size prefix (kB, MB, GB)
2068 * and are displayed rounded to the nearest tenth. E.g. the file size
2069 * 3292528 bytes will be converted into the string "3.2 MB".
2071 * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2073 * This string should be freed with g_free() when not needed any longer.
2075 * See g_format_size_full() for more options about how the size might be
2078 * Returns: a newly-allocated formatted string containing a human readable
2084 g_format_size (guint64 size
)
2086 return g_format_size_full (size
, G_FORMAT_SIZE_DEFAULT
);
2091 * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2092 * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2093 * of the returned string. For example, "45.6 kB (45,612 bytes)".
2094 * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2095 * suffixes. IEC units should only be used for reporting things with
2096 * a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2097 * Network and storage sizes should be reported in the normal SI units.
2099 * Flags to modify the format of the string returned by g_format_size_full().
2102 #pragma GCC diagnostic push
2103 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
2106 * g_format_size_full:
2107 * @size: a size in bytes
2108 * @flags: #GFormatSizeFlags to modify the output
2112 * This function is similar to g_format_size() but allows for flags
2113 * that modify the output. See #GFormatSizeFlags.
2115 * Returns: a newly-allocated formatted string containing a human
2116 * readable file size
2121 g_format_size_full (guint64 size
,
2122 GFormatSizeFlags flags
)
2126 string
= g_string_new (NULL
);
2128 if (flags
& G_FORMAT_SIZE_IEC_UNITS
)
2130 if (size
< KIBIBYTE_FACTOR
)
2132 g_string_printf (string
,
2133 g_dngettext(GETTEXT_PACKAGE
, "%u byte", "%u bytes", (guint
) size
),
2135 flags
&= ~G_FORMAT_SIZE_LONG_FORMAT
;
2138 else if (size
< MEBIBYTE_FACTOR
)
2139 g_string_printf (string
, _("%.1f KiB"), (gdouble
) size
/ (gdouble
) KIBIBYTE_FACTOR
);
2140 else if (size
< GIBIBYTE_FACTOR
)
2141 g_string_printf (string
, _("%.1f MiB"), (gdouble
) size
/ (gdouble
) MEBIBYTE_FACTOR
);
2143 else if (size
< TEBIBYTE_FACTOR
)
2144 g_string_printf (string
, _("%.1f GiB"), (gdouble
) size
/ (gdouble
) GIBIBYTE_FACTOR
);
2146 else if (size
< PEBIBYTE_FACTOR
)
2147 g_string_printf (string
, _("%.1f TiB"), (gdouble
) size
/ (gdouble
) TEBIBYTE_FACTOR
);
2149 else if (size
< EXBIBYTE_FACTOR
)
2150 g_string_printf (string
, _("%.1f PiB"), (gdouble
) size
/ (gdouble
) PEBIBYTE_FACTOR
);
2153 g_string_printf (string
, _("%.1f EiB"), (gdouble
) size
/ (gdouble
) EXBIBYTE_FACTOR
);
2157 if (size
< KILOBYTE_FACTOR
)
2159 g_string_printf (string
,
2160 g_dngettext(GETTEXT_PACKAGE
, "%u byte", "%u bytes", (guint
) size
),
2162 flags
&= ~G_FORMAT_SIZE_LONG_FORMAT
;
2165 else if (size
< MEGABYTE_FACTOR
)
2166 g_string_printf (string
, _("%.1f kB"), (gdouble
) size
/ (gdouble
) KILOBYTE_FACTOR
);
2168 else if (size
< GIGABYTE_FACTOR
)
2169 g_string_printf (string
, _("%.1f MB"), (gdouble
) size
/ (gdouble
) MEGABYTE_FACTOR
);
2171 else if (size
< TERABYTE_FACTOR
)
2172 g_string_printf (string
, _("%.1f GB"), (gdouble
) size
/ (gdouble
) GIGABYTE_FACTOR
);
2173 else if (size
< PETABYTE_FACTOR
)
2174 g_string_printf (string
, _("%.1f TB"), (gdouble
) size
/ (gdouble
) TERABYTE_FACTOR
);
2176 else if (size
< EXABYTE_FACTOR
)
2177 g_string_printf (string
, _("%.1f PB"), (gdouble
) size
/ (gdouble
) PETABYTE_FACTOR
);
2180 g_string_printf (string
, _("%.1f EB"), (gdouble
) size
/ (gdouble
) EXABYTE_FACTOR
);
2183 if (flags
& G_FORMAT_SIZE_LONG_FORMAT
)
2185 /* First problem: we need to use the number of bytes to decide on
2186 * the plural form that is used for display, but the number of
2187 * bytes potentially exceeds the size of a guint (which is what
2188 * ngettext() takes).
2190 * From a pragmatic standpoint, it seems that all known languages
2191 * base plural forms on one or both of the following:
2193 * - the lowest digits of the number
2195 * - if the number if greater than some small value
2197 * Here's how we fake it: Draw an arbitrary line at one thousand.
2198 * If the number is below that, then fine. If it is above it,
2199 * then we take the modulus of the number by one thousand (in
2200 * order to keep the lowest digits) and add one thousand to that
2201 * (in order to ensure that 1001 is not treated the same as 1).
2203 guint plural_form
= size
< 1000 ? size
: size
% 1000 + 1000;
2205 /* Second problem: we need to translate the string "%u byte" and
2206 * "%u bytes" for pluralisation, but the correct number format to
2207 * use for a gsize is different depending on which architecture
2210 * Solution: format the number separately and use "%s bytes" on
2213 const gchar
*translated_format
;
2214 gchar
*formatted_number
;
2216 /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2217 translated_format
= g_dngettext(GETTEXT_PACKAGE
, "%s byte", "%s bytes", plural_form
);
2218 /* XXX: Windows doesn't support the "'" format modifier, so we
2219 * must not use it there. Instead, just display the number
2220 * without separation. Bug #655336 is open until a solution is
2224 formatted_number
= g_strdup_printf ("%'"G_GUINT64_FORMAT
, size
);
2226 formatted_number
= g_strdup_printf ("%"G_GUINT64_FORMAT
, size
);
2229 g_string_append (string
, " (");
2230 g_string_append_printf (string
, translated_format
, formatted_number
);
2231 g_free (formatted_number
);
2232 g_string_append (string
, ")");
2235 return g_string_free (string
, FALSE
);
2238 #pragma GCC diagnostic pop
2241 * g_format_size_for_display:
2242 * @size: a size in bytes
2244 * Formats a size (for example the size of a file) into a human
2245 * readable string. Sizes are rounded to the nearest size prefix
2246 * (KB, MB, GB) and are displayed rounded to the nearest tenth.
2247 * E.g. the file size 3292528 bytes will be converted into the
2250 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2252 * This string should be freed with g_free() when not needed any longer.
2254 * Returns: a newly-allocated formatted string containing a human
2255 * readable file size
2259 * Deprecated:2.30: This function is broken due to its use of SI
2260 * suffixes to denote IEC units. Use g_format_size() instead.
2263 g_format_size_for_display (goffset size
)
2265 if (size
< (goffset
) KIBIBYTE_FACTOR
)
2266 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE
, "%u byte", "%u bytes",(guint
) size
), (guint
) size
);
2269 gdouble displayed_size
;
2271 if (size
< (goffset
) MEBIBYTE_FACTOR
)
2273 displayed_size
= (gdouble
) size
/ (gdouble
) KIBIBYTE_FACTOR
;
2274 /* Translators: this is from the deprecated function g_format_size_for_display() which uses 'KB' to
2275 * mean 1024 bytes. I am aware that 'KB' is not correct, but it has been preserved for reasons of
2276 * compatibility. Users will not see this string unless a program is using this deprecated function.
2277 * Please translate as literally as possible.
2279 return g_strdup_printf (_("%.1f KB"), displayed_size
);
2281 else if (size
< (goffset
) GIBIBYTE_FACTOR
)
2283 displayed_size
= (gdouble
) size
/ (gdouble
) MEBIBYTE_FACTOR
;
2284 return g_strdup_printf (_("%.1f MB"), displayed_size
);
2286 else if (size
< (goffset
) TEBIBYTE_FACTOR
)
2288 displayed_size
= (gdouble
) size
/ (gdouble
) GIBIBYTE_FACTOR
;
2289 return g_strdup_printf (_("%.1f GB"), displayed_size
);
2291 else if (size
< (goffset
) PEBIBYTE_FACTOR
)
2293 displayed_size
= (gdouble
) size
/ (gdouble
) TEBIBYTE_FACTOR
;
2294 return g_strdup_printf (_("%.1f TB"), displayed_size
);
2296 else if (size
< (goffset
) EXBIBYTE_FACTOR
)
2298 displayed_size
= (gdouble
) size
/ (gdouble
) PEBIBYTE_FACTOR
;
2299 return g_strdup_printf (_("%.1f PB"), displayed_size
);
2303 displayed_size
= (gdouble
) size
/ (gdouble
) EXBIBYTE_FACTOR
;
2304 return g_strdup_printf (_("%.1f EB"), displayed_size
);
2309 #if defined (G_OS_WIN32) && !defined (_WIN64)
2311 /* Binary compatibility versions. Not for newly compiled code. */
2313 _GLIB_EXTERN
const gchar
*g_get_user_name_utf8 (void);
2314 _GLIB_EXTERN
const gchar
*g_get_real_name_utf8 (void);
2315 _GLIB_EXTERN
const gchar
*g_get_home_dir_utf8 (void);
2316 _GLIB_EXTERN
const gchar
*g_get_tmp_dir_utf8 (void);
2317 _GLIB_EXTERN gchar
*g_find_program_in_path_utf8 (const gchar
*program
);
2320 g_find_program_in_path_utf8 (const gchar
*program
)
2322 return g_find_program_in_path (program
);
2325 const gchar
*g_get_user_name_utf8 (void) { return g_get_user_name (); }
2326 const gchar
*g_get_real_name_utf8 (void) { return g_get_real_name (); }
2327 const gchar
*g_get_home_dir_utf8 (void) { return g_get_home_dir (); }
2328 const gchar
*g_get_tmp_dir_utf8 (void) { return g_get_tmp_dir (); }
2334 * Returns %TRUE if the current process was executed as setuid (or an
2335 * equivalent __libc_enable_secure is available). See:
2336 * http://osdir.com/ml/linux.lfs.hardened/2007-04/msg00032.html
2339 g_check_setuid (void)
2341 /* TODO: get __libc_enable_secure exported from glibc.
2342 * See http://www.openwall.com/lists/owl-dev/2012/08/14/1
2344 #if 0 && defined(HAVE_LIBC_ENABLE_SECURE)
2346 /* See glibc/include/unistd.h */
2347 extern int __libc_enable_secure
;
2348 return __libc_enable_secure
;
2350 #elif defined(HAVE_ISSETUGID) && !defined(__BIONIC__)
2351 /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
2353 /* Android had it in older versions but the new 64 bit ABI does not
2354 * have it anymore, and some versions of the 32 bit ABI neither.
2355 * https://code.google.com/p/android-developer-preview/issues/detail?id=168
2357 return issetugid ();
2358 #elif defined(G_OS_UNIX)
2359 uid_t ruid
, euid
, suid
; /* Real, effective and saved user ID's */
2360 gid_t rgid
, egid
, sgid
; /* Real, effective and saved group ID's */
2362 static gsize check_setuid_initialised
;
2363 static gboolean is_setuid
;
2365 if (g_once_init_enter (&check_setuid_initialised
))
2367 #ifdef HAVE_GETRESUID
2368 /* These aren't in the header files, so we prototype them here.
2370 int getresuid(uid_t
*ruid
, uid_t
*euid
, uid_t
*suid
);
2371 int getresgid(gid_t
*rgid
, gid_t
*egid
, gid_t
*sgid
);
2373 if (getresuid (&ruid
, &euid
, &suid
) != 0 ||
2374 getresgid (&rgid
, &egid
, &sgid
) != 0)
2375 #endif /* HAVE_GETRESUID */
2377 suid
= ruid
= getuid ();
2378 sgid
= rgid
= getgid ();
2383 is_setuid
= (ruid
!= euid
|| ruid
!= suid
||
2384 rgid
!= egid
|| rgid
!= sgid
);
2386 g_once_init_leave (&check_setuid_initialised
, 1);
2398 * A wrapper for the POSIX abort() function.
2400 * On Windows it is a function that makes extra effort (including a call
2401 * to abort()) to ensure that a debugger-catchable exception is thrown
2402 * before the program terminates.
2404 * See your C library manual for more details about abort().
2411 /* One call to break the debugger */
2413 /* One call in case CRT does get saner about abort() behaviour */
2415 /* And one call to bind them all and terminate the program for sure */