utils: Compile g_abort() only on Windows
[glib.git] / glib / gutils.c
blob7fc3c6f62b4d78f8042397598674de4924de38b8
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/.
25 /*
26 * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
29 #include "config.h"
31 #include "gutils.h"
33 #include <stdarg.h>
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <locale.h>
37 #include <string.h>
38 #include <ctype.h> /* For tolower() */
39 #include <errno.h>
40 #include <sys/types.h>
41 #include <sys/stat.h>
42 #ifdef G_OS_UNIX
43 #include <pwd.h>
44 #include <unistd.h>
45 #endif
46 #include <sys/types.h>
47 #ifdef HAVE_SYS_PARAM_H
48 #include <sys/param.h>
49 #endif
50 #ifdef HAVE_CRT_EXTERNS_H
51 #include <crt_externs.h> /* for _NSGetEnviron */
52 #endif
54 #include "glib-init.h"
55 #include "glib-private.h"
56 #include "genviron.h"
57 #include "gfileutils.h"
58 #include "ggettext.h"
59 #include "ghash.h"
60 #include "gthread.h"
61 #include "gtestutils.h"
62 #include "gunicode.h"
63 #include "gstrfuncs.h"
64 #include "garray.h"
65 #include "glibintl.h"
67 #ifdef G_PLATFORM_WIN32
68 #include "gconvert.h"
69 #include "gwin32.h"
70 #endif
73 /**
74 * SECTION:misc_utils
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
82 # include <windows.h>
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
86 # endif
87 # include <lmcons.h> /* For UNLEN */
88 #endif /* G_PLATFORM_WIN32 */
90 #ifdef G_OS_WIN32
91 # include <direct.h>
92 # include <shlobj.h>
93 /* older SDK (e.g. msvc 5.0) does not have these*/
94 # ifndef CSIDL_MYMUSIC
95 # define CSIDL_MYMUSIC 13
96 # endif
97 # ifndef CSIDL_MYVIDEO
98 # define CSIDL_MYVIDEO 14
99 # endif
100 # ifndef CSIDL_INTERNET_CACHE
101 # define CSIDL_INTERNET_CACHE 32
102 # endif
103 # ifndef CSIDL_COMMON_APPDATA
104 # define CSIDL_COMMON_APPDATA 35
105 # endif
106 # ifndef CSIDL_MYPICTURES
107 # define CSIDL_MYPICTURES 0x27
108 # endif
109 # ifndef CSIDL_COMMON_DOCUMENTS
110 # define CSIDL_COMMON_DOCUMENTS 46
111 # endif
112 # ifndef CSIDL_PROFILE
113 # define CSIDL_PROFILE 40
114 # endif
115 # include <process.h>
116 #endif
118 #ifdef HAVE_CARBON
119 #include <CoreServices/CoreServices.h>
120 #endif
122 #ifdef HAVE_CODESET
123 #include <langinfo.h>
124 #endif
126 #ifdef G_PLATFORM_WIN32
128 gchar *
129 _glib_get_dll_directory (void)
131 gchar *retval;
132 gchar *p;
133 wchar_t wc_fn[MAX_PATH];
135 #ifdef DLL_EXPORT
136 if (glib_dll == NULL)
137 return NULL;
138 #endif
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))
150 return NULL;
152 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
154 p = strrchr (retval, G_DIR_SEPARATOR);
155 if (p == NULL)
157 /* Wtf? */
158 return NULL;
160 *p = '\0';
162 return retval;
165 #endif
168 * g_memmove:
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().
179 #ifdef G_OS_WIN32
180 #undef g_atexit
181 #endif
184 * g_atexit:
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
196 * DLL.
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
216 * program.
218 * Deprecated:2.32: It is best to avoid g_atexit().
220 void
221 g_atexit (GVoidFunc func)
223 gint result;
225 result = atexit ((void (*)(void)) func);
226 if (result)
228 g_error ("Could not register atexit() function: %s",
229 g_strerror (errno));
233 /* Based on execvp() from GNU Libc.
234 * Some of this code is cut-and-pasted into gspawn.c
237 static gchar*
238 my_strchrnul (const gchar *str,
239 gchar c)
241 gchar *p = (gchar*)str;
242 while (*p && (*p != c))
243 ++p;
245 return p;
248 #ifdef G_OS_WIN32
250 static gchar *inner_find_program_in_path (const gchar *program);
252 gchar*
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"),
265 NULL);
266 gchar *p;
267 gchar *decorated_program;
268 gchar *retval;
270 p = pathext;
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);
283 if (retval != NULL)
285 g_free (pathext);
286 return retval;
288 p = q;
289 } while (*p++ != '\0');
290 g_free (pathext);
291 return NULL;
293 else
294 return inner_find_program_in_path (program);
297 #endif
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
323 #ifdef G_OS_WIN32
324 static gchar *
325 inner_find_program_in_path (const gchar *program)
326 #else
327 gchar*
328 g_find_program_in_path (const gchar *program)
329 #endif
331 const gchar *path, *p;
332 gchar *name, *freeme;
333 #ifdef G_OS_WIN32
334 const gchar *path_copy;
335 gchar *filename = NULL, *appdir = NULL;
336 gchar *sysdir = NULL, *windir = NULL;
337 int n;
338 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
339 wwindir[MAXPATHLEN];
340 #endif
341 gsize len;
342 gsize pathlen;
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
351 #ifdef G_OS_WIN32
352 || strchr (program, '/') != NULL
353 #endif
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);
359 else
360 return NULL;
363 path = g_getenv ("PATH");
364 #if defined(G_OS_UNIX)
365 if (path == NULL)
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:.";
379 #else
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);
392 if (filename)
394 appdir = g_path_get_dirname (filename);
395 g_free (filename);
398 path = g_strdup (path);
400 if (windir)
402 const gchar *tem = path;
403 path = g_strconcat (windir, ";", path, NULL);
404 g_free ((gchar *) tem);
405 g_free (windir);
408 if (sysdir)
410 const gchar *tem = path;
411 path = g_strconcat (sysdir, ";", path, NULL);
412 g_free ((gchar *) tem);
413 g_free (sysdir);
417 const gchar *tem = path;
418 path = g_strconcat (".;", path, NULL);
419 g_free ((gchar *) tem);
422 if (appdir)
424 const gchar *tem = path;
425 path = g_strconcat (appdir, ";", path, NULL);
426 g_free ((gchar *) tem);
427 g_free (appdir);
430 path_copy = path;
431 #endif
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;
443 p = path;
446 char *startp;
448 path = p;
449 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
451 if (p == path)
452 /* Two adjacent colons, or a colon at the beginning or the end
453 * of 'PATH' means to search the current directory.
455 startp = name + 1;
456 else
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))
462 gchar *ret;
463 ret = g_strdup (startp);
464 g_free (freeme);
465 #ifdef G_OS_WIN32
466 g_free ((gchar *) path_copy);
467 #endif
468 return ret;
471 while (*p++ != '\0');
473 g_free (freeme);
474 #ifdef G_OS_WIN32
475 g_free ((gchar *) path_copy);
476 #endif
478 return NULL;
481 /* The functions below are defined this way for compatibility reasons.
482 * See the note in gutils.h.
486 * g_bit_nth_lsf:
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
498 gint
499 (g_bit_nth_lsf) (gulong mask,
500 gint nth_bit)
502 return g_bit_nth_lsf_impl (mask, nth_bit);
506 * g_bit_nth_msf:
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
519 gint
520 (g_bit_nth_msf) (gulong mask,
521 gint nth_bit)
523 return g_bit_nth_msf_impl (mask, nth_bit);
528 * g_bit_storage:
529 * @number: a #guint
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
536 guint
537 (g_bit_storage) (gulong number)
539 return g_bit_storage_impl (number);
542 G_LOCK_DEFINE_STATIC (g_utils_global);
544 typedef struct
546 gchar *user_name;
547 gchar *real_name;
548 gchar *home_dir;
549 } UserDatabaseEntry;
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
562 #ifdef G_OS_WIN32
564 static gchar *
565 get_special_folder (int csidl)
567 wchar_t path[MAX_PATH+1];
568 HRESULT hr;
569 LPITEMIDLIST pidl = NULL;
570 BOOL b;
571 gchar *retval = NULL;
573 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
574 if (hr == S_OK)
576 b = SHGetPathFromIDListW (pidl, path);
577 if (b)
578 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
579 CoTaskMemFree (pidl);
581 return retval;
584 static char *
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);
595 char *p;
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] != ':')
602 p--;
603 *p = '\0';
604 return windowsdir;
606 else
607 return g_strdup ("C:\\");
610 #endif
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;
622 #ifdef G_OS_UNIX
624 struct passwd *pw = NULL;
625 gpointer buffer = NULL;
626 gint error;
627 gchar *logname;
629 # if defined (HAVE_GETPWUID_R)
630 struct passwd pwd;
631 # ifdef _SC_GETPW_R_SIZE_MAX
632 /* This reurns the maximum length */
633 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
635 if (bufsize < 0)
636 bufsize = 64;
637 # else /* _SC_GETPW_R_SIZE_MAX */
638 glong bufsize = 64;
639 # endif /* _SC_GETPW_R_SIZE_MAX */
641 logname = (gchar *) g_getenv ("LOGNAME");
645 g_free (buffer);
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);
650 errno = 0;
652 if (logname) {
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);
658 } else {
659 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
661 error = error < 0 ? errno : error;
663 if (!pw)
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
668 * successful.
670 if (error == 0 || error == ENOENT)
672 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
673 (gulong) getuid ());
674 break;
676 if (bufsize > 32 * 1024)
678 g_warning ("getpwuid_r(): failed due to: %s.",
679 g_strerror (error));
680 break;
683 bufsize *= 2;
686 while (!pw);
687 # endif /* HAVE_GETPWUID_R */
689 if (!pw)
691 pw = getpwuid (getuid ());
693 if (pw)
695 e.user_name = g_strdup (pw->pw_name);
697 #ifndef __BIONIC__
698 if (pw->pw_gecos && *pw->pw_gecos != '\0')
700 gchar **gecos_fields;
701 gchar **name_parts;
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);
711 #endif
713 if (!e.home_dir)
714 e.home_dir = g_strdup (pw->pw_dir);
716 g_free (buffer);
719 #endif /* G_OS_UNIX */
721 #ifdef G_OS_WIN32
723 guint len = UNLEN+1;
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 */
734 if (!e.user_name)
735 e.user_name = g_strdup ("somebody");
736 if (!e.real_name)
737 e.real_name = g_strdup ("Unknown");
739 g_once_init_leave (&entry, &e);
742 return entry;
746 * g_get_user_name:
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.
755 const gchar *
756 g_get_user_name (void)
758 UserDatabaseEntry *entry;
760 entry = g_get_user_database_entry ();
762 return entry->user_name;
766 * g_get_real_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
772 * returned.
774 * Returns: the user's real name.
776 const gchar *
777 g_get_real_name (void)
779 UserDatabaseEntry *entry;
781 entry = g_get_user_database_entry ();
783 return entry->real_name;
787 * g_get_home_dir:
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
812 const gchar *
813 g_get_home_dir (void)
815 static gchar *home_dir;
817 if (g_once_init_enter (&home_dir))
819 gchar *tmp;
821 /* We first check HOME and use it if it is set */
822 tmp = g_strdup (g_getenv ("HOME"));
824 #ifdef G_OS_WIN32
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...
833 if (tmp)
835 if (!(g_path_is_absolute (tmp) &&
836 g_file_test (tmp, G_FILE_TEST_IS_DIR)))
838 g_free (tmp);
839 tmp = NULL;
843 /* In case HOME is Unix-style (it happens), convert it to
844 * Windows style.
846 if (tmp)
848 gchar *p;
849 while ((p = strchr (tmp, '/')) != NULL)
850 *p = '\\';
853 if (!tmp)
855 /* USERPROFILE is probably the closest equivalent to $HOME? */
856 if (g_getenv ("USERPROFILE") != NULL)
857 tmp = g_strdup (g_getenv ("USERPROFILE"));
860 if (!tmp)
861 tmp = get_special_folder (CSIDL_PROFILE);
863 if (!tmp)
864 tmp = get_windows_directory_root ();
865 #endif /* G_OS_WIN32 */
867 if (!tmp)
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);
885 return home_dir;
889 * g_get_tmp_dir:
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
900 * as a default.
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
904 * string.
906 * Returns: the directory to use for temporary files.
908 const gchar *
909 g_get_tmp_dir (void)
911 static gchar *tmp_dir;
913 if (g_once_init_enter (&tmp_dir))
915 gchar *tmp;
917 #ifdef G_OS_WIN32
918 tmp = g_strdup (g_getenv ("TEMP"));
920 if (tmp == NULL || *tmp == '\0')
922 g_free (tmp);
923 tmp = get_windows_directory_root ();
925 #else /* G_OS_WIN32 */
926 tmp = g_strdup (g_getenv ("TMPDIR"));
928 #ifdef P_tmpdir
929 if (tmp == NULL || *tmp == '\0')
931 gsize k;
932 g_free (tmp);
933 tmp = g_strdup (P_tmpdir);
934 k = strlen (tmp);
935 if (k > 1 && G_IS_DIR_SEPARATOR (tmp[k - 1]))
936 tmp[k - 1] = '\0';
938 #endif /* P_tmpdir */
940 if (tmp == NULL || *tmp == '\0')
942 g_free (tmp);
943 tmp = g_strdup ("/tmp");
945 #endif /* !G_OS_WIN32 */
947 g_once_init_leave (&tmp_dir, tmp);
950 return tmp_dir;
954 * g_get_host_name:
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
967 * returned.
969 * Returns: the host name of the machine.
971 * Since: 2.8
973 const gchar *
974 g_get_host_name (void)
976 static gchar *hostname;
978 if (g_once_init_enter (&hostname))
980 gboolean failed;
981 gchar tmp[100];
983 #ifndef G_OS_WIN32
984 failed = (gethostname (tmp, sizeof (tmp)) == -1);
985 #else
986 DWORD size = sizeof (tmp);
987 failed = (!GetComputerName (tmp, &size));
988 #endif
990 g_once_init_leave (&hostname, g_strdup (failed ? "localhost" : tmp));
993 return hostname;
996 G_LOCK_DEFINE_STATIC (g_prgname);
997 static gchar *g_prgname = NULL;
1000 * g_get_prgname:
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.
1012 const gchar*
1013 g_get_prgname (void)
1015 gchar* retval;
1017 G_LOCK (g_prgname);
1018 #ifdef G_OS_WIN32
1019 if (g_prgname == NULL)
1021 static gboolean beenhere = FALSE;
1023 if (!beenhere)
1025 gchar *utf8_buf = NULL;
1026 wchar_t buf[MAX_PATH+1];
1028 beenhere = TRUE;
1029 if (GetModuleFileNameW (GetModuleHandle (NULL),
1030 buf, G_N_ELEMENTS (buf)) > 0)
1031 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1033 if (utf8_buf)
1035 g_prgname = g_path_get_basename (utf8_buf);
1036 g_free (utf8_buf);
1040 #endif
1041 retval = g_prgname;
1042 G_UNLOCK (g_prgname);
1044 return retval;
1048 * g_set_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.
1056 void
1057 g_set_prgname (const gchar *prgname)
1059 G_LOCK (g_prgname);
1060 g_free (g_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
1077 * been called).
1079 * Returns: human-readable application name. may return %NULL
1081 * Since: 2.2
1083 const gchar *
1084 g_get_application_name (void)
1086 gchar* retval;
1088 G_LOCK (g_application_name);
1089 retval = g_application_name;
1090 G_UNLOCK (g_application_name);
1092 if (retval == NULL)
1093 return g_get_prgname ();
1095 return retval;
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
1109 * be called once.
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.
1114 * Since: 2.2
1116 void
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)
1123 already_set = TRUE;
1124 else
1125 g_application_name = g_strdup (application_name);
1126 G_UNLOCK (g_application_name);
1128 if (already_set)
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
1139 * in the
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
1149 * or freed.
1150 * Since: 2.6
1152 const gchar *
1153 g_get_user_data_dir (void)
1155 gchar *data_dir;
1157 G_LOCK (g_utils_global);
1159 if (!g_user_data_dir)
1161 #ifdef G_OS_WIN32
1162 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1163 #else
1164 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1166 if (data_dir && data_dir[0])
1167 data_dir = g_strdup (data_dir);
1168 #endif
1169 if (!data_dir || !data_dir[0])
1171 const gchar *home_dir = g_get_home_dir ();
1173 if (home_dir)
1174 data_dir = g_build_filename (home_dir, ".local", "share", NULL);
1175 else
1176 data_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".local", "share", NULL);
1179 g_user_data_dir = data_dir;
1181 else
1182 data_dir = g_user_data_dir;
1184 G_UNLOCK (g_utils_global);
1186 return data_dir;
1189 static void
1190 g_init_user_config_dir (void)
1192 gchar *config_dir;
1194 if (!g_user_config_dir)
1196 #ifdef G_OS_WIN32
1197 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1198 #else
1199 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1201 if (config_dir && config_dir[0])
1202 config_dir = g_strdup (config_dir);
1203 #endif
1204 if (!config_dir || !config_dir[0])
1206 const gchar *home_dir = g_get_home_dir ();
1208 if (home_dir)
1209 config_dir = g_build_filename (home_dir, ".config", NULL);
1210 else
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
1225 * in the
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
1235 * or freed.
1236 * Since: 2.6
1238 const gchar *
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
1257 * in the
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
1267 * or freed.
1268 * Since: 2.6
1270 const gchar *
1271 g_get_user_cache_dir (void)
1273 gchar *cache_dir;
1275 G_LOCK (g_utils_global);
1277 if (!g_user_cache_dir)
1279 #ifdef G_OS_WIN32
1280 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1281 #else
1282 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1284 if (cache_dir && cache_dir[0])
1285 cache_dir = g_strdup (cache_dir);
1286 #endif
1287 if (!cache_dir || !cache_dir[0])
1289 const gchar *home_dir = g_get_home_dir ();
1291 if (home_dir)
1292 cache_dir = g_build_filename (home_dir, ".cache", NULL);
1293 else
1294 cache_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".cache", NULL);
1296 g_user_cache_dir = cache_dir;
1298 else
1299 cache_dir = g_user_cache_dir;
1301 G_UNLOCK (g_utils_global);
1303 return cache_dir;
1307 * g_get_user_runtime_dir:
1309 * Returns a directory that is unique to the current user on the local
1310 * system.
1312 * On UNIX platforms this is determined using the mechanisms described
1313 * in the
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.
1327 * Since: 2.28
1329 const gchar *
1330 g_get_user_runtime_dir (void)
1332 #ifndef G_OS_WIN32
1333 static const gchar *runtime_dir;
1335 if (g_once_init_enter (&runtime_dir))
1337 const gchar *dir;
1339 dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
1341 if (dir == NULL)
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);
1364 return runtime_dir;
1365 #else /* Windows */
1366 return g_get_user_cache_dir ();
1367 #endif
1370 #ifdef HAVE_CARBON
1372 static gchar *
1373 find_folder (OSType type)
1375 gchar *filename = NULL;
1376 FSRef found;
1378 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
1380 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
1382 if (url)
1384 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
1386 if (path)
1388 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
1390 if (! filename)
1392 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
1394 CFStringGetCString (path, filename,
1395 CFStringGetLength (path) * 3 + 1,
1396 kCFStringEncodingUTF8);
1399 CFRelease (path);
1402 CFRelease (url);
1406 return filename;
1409 static void
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)
1424 static void
1425 load_user_special_dirs (void)
1427 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1428 DWORD dwFlags,
1429 HANDLE hToken,
1430 PWSTR *ppszPath);
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 } };
1438 wchar_t *wcp;
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);
1450 else
1452 wcp = NULL;
1453 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1454 if (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);
1461 else
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)
1470 /* XXX */
1471 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1473 else
1475 wcp = NULL;
1476 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
1477 if (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);
1484 else
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
1516 * SOFTWARE.
1518 static void
1519 load_user_special_dirs (void)
1521 gchar *config_file;
1522 gchar *data;
1523 gchar **lines;
1524 gint n_lines, i;
1526 g_init_user_config_dir ();
1527 config_file = g_build_filename (g_user_config_dir,
1528 "user-dirs.dirs",
1529 NULL);
1531 if (!g_file_get_contents (config_file, &data, NULL, NULL))
1533 g_free (config_file);
1534 return;
1537 lines = g_strsplit (data, "\n", -1);
1538 n_lines = g_strv_length (lines);
1539 g_free (data);
1541 for (i = 0; i < n_lines; i++)
1543 gchar *buffer = lines[i];
1544 gchar *d, *p;
1545 gint len;
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;
1554 p = buffer;
1555 while (*p == ' ' || *p == '\t')
1556 p++;
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");
1598 else
1599 continue;
1601 while (*p == ' ' || *p == '\t')
1602 p++;
1604 if (*p != '=')
1605 continue;
1606 p++;
1608 while (*p == ' ' || *p == '\t')
1609 p++;
1611 if (*p != '"')
1612 continue;
1613 p++;
1615 if (strncmp (p, "$HOME", 5) == 0)
1617 p += 5;
1618 is_relative = TRUE;
1620 else if (*p != '/')
1621 continue;
1623 d = strrchr (p, '"');
1624 if (!d)
1625 continue;
1626 *d = 0;
1628 d = p;
1630 /* remove trailing slashes */
1631 len = strlen (d);
1632 if (d[len - 1] == '/')
1633 d[len - 1] = 0;
1635 if (is_relative)
1637 g_user_special_dirs[directory] = g_build_filename (g_get_home_dir (), d, NULL);
1639 else
1640 g_user_special_dirs[directory] = g_strdup (d);
1643 g_strfreev (lines);
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.
1662 * Since: 2.22
1664 void
1665 g_reload_user_special_dirs_cache (void)
1667 int i;
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;
1675 char *old_val;
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)
1691 /* don't leak */
1692 g_free (g_user_special_dirs[i]);
1693 g_user_special_dirs[i] = old_val;
1695 else
1696 g_free (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
1715 * not been set up.
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.
1725 * Since: 2.14
1727 const gchar *
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];
1751 #ifdef G_OS_WIN32
1753 #undef g_get_system_data_dirs
1755 static HMODULE
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;
1765 if (!address)
1766 return NULL;
1768 if (!beenhere)
1770 p_GetModuleHandleExA =
1771 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1772 "GetModuleHandleExA");
1773 beenhere = TRUE;
1776 if (p_GetModuleHandleExA == NULL ||
1777 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
1778 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
1779 address, &hmodule))
1781 MEMORY_BASIC_INFORMATION mbi;
1782 VirtualQuery (address, &mbi, sizeof (mbi));
1783 hmodule = (HMODULE) mbi.AllocationBase;
1786 return hmodule;
1789 static gchar *
1790 get_module_share_dir (gconstpointer address)
1792 HMODULE hmodule;
1793 gchar *filename;
1794 gchar *retval;
1796 hmodule = get_module_for_address (address);
1797 if (hmodule == NULL)
1798 return NULL;
1800 filename = g_win32_get_package_installation_directory_of_module (hmodule);
1801 retval = g_build_filename (filename, "share", NULL);
1802 g_free (filename);
1804 return retval;
1807 const gchar * const *
1808 g_win32_get_system_data_dirs_for_module (void (*address_of_function)(void))
1810 GArray *data_dirs;
1811 HMODULE hmodule;
1812 static GHashTable *per_module_data_dirs = NULL;
1813 gchar **retval;
1814 gchar *p;
1815 gchar *exe_root;
1817 hmodule = 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);
1826 else
1828 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
1830 if (retval != NULL)
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);
1843 if (p)
1844 g_array_append_val (data_dirs, p);
1846 /* Documents and Settings\All Users\Documents */
1847 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1848 if (p)
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
1870 * function.
1873 p = get_module_share_dir (address_of_function);
1874 if (p)
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);
1881 if (p)
1882 g_array_append_val (data_dirs, p);
1883 g_free (glib_root);
1886 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
1887 p = g_build_filename (exe_root, "share", NULL);
1888 if (p)
1889 g_array_append_val (data_dirs, p);
1890 g_free (exe_root);
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;
1904 #endif
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
1913 * in the
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
1925 * be determined.
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
1934 * itself.
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.
1941 * Since: 2.6
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)
1952 #ifdef G_OS_WIN32
1953 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
1954 #else
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);
1961 #endif
1963 g_system_data_dirs = data_dir_vector;
1965 else
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
1980 * in the
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.
1993 * Since: 2.6
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)
2004 #ifdef G_OS_WIN32
2005 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2006 if (conf_dirs)
2008 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2009 g_free (conf_dirs);
2011 else
2013 /* Return empty list */
2014 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2016 #else
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);
2023 #endif
2025 g_system_config_dirs = conf_dir_vector;
2027 else
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.
2040 void
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)
2063 * g_format_size:
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
2076 * formatted.
2078 * Returns: a newly-allocated formatted string containing a human readable
2079 * file size
2081 * Since: 2.30
2083 gchar *
2084 g_format_size (guint64 size)
2086 return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2090 * GFormatSizeFlags:
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
2110 * Formats a size.
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
2118 * Since: 2.30
2120 gchar *
2121 g_format_size_full (guint64 size,
2122 GFormatSizeFlags flags)
2124 GString *string;
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),
2134 (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);
2152 else
2153 g_string_printf (string, _("%.1f EiB"), (gdouble) size / (gdouble) EXBIBYTE_FACTOR);
2155 else
2157 if (size < KILOBYTE_FACTOR)
2159 g_string_printf (string,
2160 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2161 (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);
2179 else
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
2208 * we're on.
2210 * Solution: format the number separately and use "%s bytes" on
2211 * all platforms.
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
2221 * found.
2223 #ifndef G_OS_WIN32
2224 formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2225 #else
2226 formatted_number = g_strdup_printf ("%"G_GUINT64_FORMAT, size);
2227 #endif
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
2248 * string "3.1 MB".
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
2257 * Since: 2.16
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.
2262 gchar *
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);
2267 else
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);
2301 else
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);
2319 gchar *
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 (); }
2330 #endif
2332 /* Private API:
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
2338 gboolean
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 ();
2379 euid = geteuid ();
2380 egid = getegid ();
2383 is_setuid = (ruid != euid || ruid != suid ||
2384 rgid != egid || rgid != sgid);
2386 g_once_init_leave (&check_setuid_initialised, 1);
2388 return is_setuid;
2389 #else
2390 return FALSE;
2391 #endif
2394 #ifdef G_OS_WIN32
2396 * g_abort:
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().
2406 * Since: 2.50
2408 void
2409 g_abort (void)
2411 /* One call to break the debugger */
2412 DebugBreak ();
2413 /* One call in case CRT does get saner about abort() behaviour */
2414 abort ();
2415 /* And one call to bind them all and terminate the program for sure */
2416 ExitProcess (127);
2418 #endif