Partly revert "glib: Add filename type annotations"
[glib.git] / glib / gutils.c
blob9f7b7e3cf61453cfbd84949c09f75f1dd484df88
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: (type filename): 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: (type filename): a newly-allocated string with the absolute path,
322 * or %NULL
324 #ifdef G_OS_WIN32
325 static gchar *
326 inner_find_program_in_path (const gchar *program)
327 #else
328 gchar*
329 g_find_program_in_path (const gchar *program)
330 #endif
332 const gchar *path, *p;
333 gchar *name, *freeme;
334 #ifdef G_OS_WIN32
335 const gchar *path_copy;
336 gchar *filename = NULL, *appdir = NULL;
337 gchar *sysdir = NULL, *windir = NULL;
338 int n;
339 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
340 wwindir[MAXPATHLEN];
341 #endif
342 gsize len;
343 gsize pathlen;
345 g_return_val_if_fail (program != NULL, NULL);
347 /* If it is an absolute path, or a relative path including subdirectories,
348 * don't look in PATH.
350 if (g_path_is_absolute (program)
351 || strchr (program, G_DIR_SEPARATOR) != NULL
352 #ifdef G_OS_WIN32
353 || strchr (program, '/') != NULL
354 #endif
357 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
358 !g_file_test (program, G_FILE_TEST_IS_DIR))
359 return g_strdup (program);
360 else
361 return NULL;
364 path = g_getenv ("PATH");
365 #if defined(G_OS_UNIX)
366 if (path == NULL)
368 /* There is no 'PATH' in the environment. The default
369 * search path in GNU libc is the current directory followed by
370 * the path 'confstr' returns for '_CS_PATH'.
373 /* In GLib we put . last, for security, and don't use the
374 * unportable confstr(); UNIX98 does not actually specify
375 * what to search if PATH is unset. POSIX may, dunno.
378 path = "/bin:/usr/bin:.";
380 #else
381 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
382 if (n > 0 && n < MAXPATHLEN)
383 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
385 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
386 if (n > 0 && n < MAXPATHLEN)
387 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
389 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
390 if (n > 0 && n < MAXPATHLEN)
391 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
393 if (filename)
395 appdir = g_path_get_dirname (filename);
396 g_free (filename);
399 path = g_strdup (path);
401 if (windir)
403 const gchar *tem = path;
404 path = g_strconcat (windir, ";", path, NULL);
405 g_free ((gchar *) tem);
406 g_free (windir);
409 if (sysdir)
411 const gchar *tem = path;
412 path = g_strconcat (sysdir, ";", path, NULL);
413 g_free ((gchar *) tem);
414 g_free (sysdir);
418 const gchar *tem = path;
419 path = g_strconcat (".;", path, NULL);
420 g_free ((gchar *) tem);
423 if (appdir)
425 const gchar *tem = path;
426 path = g_strconcat (appdir, ";", path, NULL);
427 g_free ((gchar *) tem);
428 g_free (appdir);
431 path_copy = path;
432 #endif
434 len = strlen (program) + 1;
435 pathlen = strlen (path);
436 freeme = name = g_malloc (pathlen + len + 1);
438 /* Copy the file name at the top, including '\0' */
439 memcpy (name + pathlen + 1, program, len);
440 name = name + pathlen;
441 /* And add the slash before the filename */
442 *name = G_DIR_SEPARATOR;
444 p = path;
447 char *startp;
449 path = p;
450 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
452 if (p == path)
453 /* Two adjacent colons, or a colon at the beginning or the end
454 * of 'PATH' means to search the current directory.
456 startp = name + 1;
457 else
458 startp = memcpy (name - (p - path), path, p - path);
460 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
461 !g_file_test (startp, G_FILE_TEST_IS_DIR))
463 gchar *ret;
464 ret = g_strdup (startp);
465 g_free (freeme);
466 #ifdef G_OS_WIN32
467 g_free ((gchar *) path_copy);
468 #endif
469 return ret;
472 while (*p++ != '\0');
474 g_free (freeme);
475 #ifdef G_OS_WIN32
476 g_free ((gchar *) path_copy);
477 #endif
479 return NULL;
482 /* The functions below are defined this way for compatibility reasons.
483 * See the note in gutils.h.
487 * g_bit_nth_lsf:
488 * @mask: a #gulong containing flags
489 * @nth_bit: the index of the bit to start the search from
491 * Find the position of the first bit set in @mask, searching
492 * from (but not including) @nth_bit upwards. Bits are numbered
493 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
494 * usually). To start searching from the 0th bit, set @nth_bit to -1.
496 * Returns: the index of the first bit set which is higher than @nth_bit, or -1
497 * if no higher bits are set
499 gint
500 (g_bit_nth_lsf) (gulong mask,
501 gint nth_bit)
503 return g_bit_nth_lsf_impl (mask, nth_bit);
507 * g_bit_nth_msf:
508 * @mask: a #gulong containing flags
509 * @nth_bit: the index of the bit to start the search from
511 * Find the position of the first bit set in @mask, searching
512 * from (but not including) @nth_bit downwards. Bits are numbered
513 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
514 * usually). To start searching from the last bit, set @nth_bit to
515 * -1 or GLIB_SIZEOF_LONG * 8.
517 * Returns: the index of the first bit set which is lower than @nth_bit, or -1
518 * if no lower bits are set
520 gint
521 (g_bit_nth_msf) (gulong mask,
522 gint nth_bit)
524 return g_bit_nth_msf_impl (mask, nth_bit);
529 * g_bit_storage:
530 * @number: a #guint
532 * Gets the number of bits used to hold @number,
533 * e.g. if @number is 4, 3 bits are needed.
535 * Returns: the number of bits used to hold @number
537 guint
538 (g_bit_storage) (gulong number)
540 return g_bit_storage_impl (number);
543 G_LOCK_DEFINE_STATIC (g_utils_global);
545 typedef struct
547 gchar *user_name;
548 gchar *real_name;
549 gchar *home_dir;
550 } UserDatabaseEntry;
552 static gchar *g_user_data_dir = NULL;
553 static gchar **g_system_data_dirs = NULL;
554 static gchar *g_user_cache_dir = NULL;
555 static gchar *g_user_config_dir = NULL;
556 static gchar **g_system_config_dirs = NULL;
558 static gchar **g_user_special_dirs = NULL;
560 /* fifteen minutes of fame for everybody */
561 #define G_USER_DIRS_EXPIRE 15 * 60
563 #ifdef G_OS_WIN32
565 static gchar *
566 get_special_folder (int csidl)
568 wchar_t path[MAX_PATH+1];
569 HRESULT hr;
570 LPITEMIDLIST pidl = NULL;
571 BOOL b;
572 gchar *retval = NULL;
574 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
575 if (hr == S_OK)
577 b = SHGetPathFromIDListW (pidl, path);
578 if (b)
579 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
580 CoTaskMemFree (pidl);
582 return retval;
585 static char *
586 get_windows_directory_root (void)
588 wchar_t wwindowsdir[MAX_PATH];
590 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
592 /* Usually X:\Windows, but in terminal server environments
593 * might be an UNC path, AFAIK.
595 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
596 char *p;
598 if (windowsdir == NULL)
599 return g_strdup ("C:\\");
601 p = (char *) g_path_skip_root (windowsdir);
602 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
603 p--;
604 *p = '\0';
605 return windowsdir;
607 else
608 return g_strdup ("C:\\");
611 #endif
613 /* HOLDS: g_utils_global_lock */
614 static UserDatabaseEntry *
615 g_get_user_database_entry (void)
617 static UserDatabaseEntry *entry;
619 if (g_once_init_enter (&entry))
621 static UserDatabaseEntry e;
623 #ifdef G_OS_UNIX
625 struct passwd *pw = NULL;
626 gpointer buffer = NULL;
627 gint error;
628 gchar *logname;
630 # if defined (HAVE_GETPWUID_R)
631 struct passwd pwd;
632 # ifdef _SC_GETPW_R_SIZE_MAX
633 /* This reurns the maximum length */
634 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
636 if (bufsize < 0)
637 bufsize = 64;
638 # else /* _SC_GETPW_R_SIZE_MAX */
639 glong bufsize = 64;
640 # endif /* _SC_GETPW_R_SIZE_MAX */
642 logname = (gchar *) g_getenv ("LOGNAME");
646 g_free (buffer);
647 /* we allocate 6 extra bytes to work around a bug in
648 * Mac OS < 10.3. See #156446
650 buffer = g_malloc (bufsize + 6);
651 errno = 0;
653 if (logname) {
654 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
655 if (!pw || (pw->pw_uid != getuid ())) {
656 /* LOGNAME is lying, fall back to looking up the uid */
657 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
659 } else {
660 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
662 error = error < 0 ? errno : error;
664 if (!pw)
666 /* we bail out prematurely if the user id can't be found
667 * (should be pretty rare case actually), or if the buffer
668 * should be sufficiently big and lookups are still not
669 * successful.
671 if (error == 0 || error == ENOENT)
673 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
674 (gulong) getuid ());
675 break;
677 if (bufsize > 32 * 1024)
679 g_warning ("getpwuid_r(): failed due to: %s.",
680 g_strerror (error));
681 break;
684 bufsize *= 2;
687 while (!pw);
688 # endif /* HAVE_GETPWUID_R */
690 if (!pw)
692 pw = getpwuid (getuid ());
694 if (pw)
696 e.user_name = g_strdup (pw->pw_name);
698 #ifndef __BIONIC__
699 if (pw->pw_gecos && *pw->pw_gecos != '\0')
701 gchar **gecos_fields;
702 gchar **name_parts;
704 /* split the gecos field and substitute '&' */
705 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
706 name_parts = g_strsplit (gecos_fields[0], "&", 0);
707 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
708 e.real_name = g_strjoinv (pw->pw_name, name_parts);
709 g_strfreev (gecos_fields);
710 g_strfreev (name_parts);
712 #endif
714 if (!e.home_dir)
715 e.home_dir = g_strdup (pw->pw_dir);
717 g_free (buffer);
720 #endif /* G_OS_UNIX */
722 #ifdef G_OS_WIN32
724 guint len = UNLEN+1;
725 wchar_t buffer[UNLEN+1];
727 if (GetUserNameW (buffer, (LPDWORD) &len))
729 e.user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
730 e.real_name = g_strdup (e.user_name);
733 #endif /* G_OS_WIN32 */
735 if (!e.user_name)
736 e.user_name = g_strdup ("somebody");
737 if (!e.real_name)
738 e.real_name = g_strdup ("Unknown");
740 g_once_init_leave (&entry, &e);
743 return entry;
747 * g_get_user_name:
749 * Gets the user name of the current user. The encoding of the returned
750 * string is system-defined. On UNIX, it might be the preferred file name
751 * encoding, or something else, and there is no guarantee that it is even
752 * consistent on a machine. On Windows, it is always UTF-8.
754 * Returns: (type filename): the user name of the current user.
756 const gchar *
757 g_get_user_name (void)
759 UserDatabaseEntry *entry;
761 entry = g_get_user_database_entry ();
763 return entry->user_name;
767 * g_get_real_name:
769 * Gets the real name of the user. This usually comes from the user's
770 * entry in the `passwd` file. The encoding of the returned string is
771 * system-defined. (On Windows, it is, however, always UTF-8.) If the
772 * real user name cannot be determined, the string "Unknown" is
773 * returned.
775 * Returns: (type filename): the user's real name.
777 const gchar *
778 g_get_real_name (void)
780 UserDatabaseEntry *entry;
782 entry = g_get_user_database_entry ();
784 return entry->real_name;
788 * g_get_home_dir:
790 * Gets the current user's home directory.
792 * As with most UNIX tools, this function will return the value of the
793 * `HOME` environment variable if it is set to an existing absolute path
794 * name, falling back to the `passwd` file in the case that it is unset.
796 * If the path given in `HOME` is non-absolute, does not exist, or is
797 * not a directory, the result is undefined.
799 * Before version 2.36 this function would ignore the `HOME` environment
800 * variable, taking the value from the `passwd` database instead. This was
801 * changed to increase the compatibility of GLib with other programs (and
802 * the XDG basedir specification) and to increase testability of programs
803 * based on GLib (by making it easier to run them from test frameworks).
805 * If your program has a strong requirement for either the new or the
806 * old behaviour (and if you don't wish to increase your GLib
807 * dependency to ensure that the new behaviour is in effect) then you
808 * should either directly check the `HOME` environment variable yourself
809 * or unset it before calling any functions in GLib.
811 * Returns: (type filename): the current user's home directory
813 const gchar *
814 g_get_home_dir (void)
816 static gchar *home_dir;
818 if (g_once_init_enter (&home_dir))
820 gchar *tmp;
822 /* We first check HOME and use it if it is set */
823 tmp = g_strdup (g_getenv ("HOME"));
825 #ifdef G_OS_WIN32
826 /* Only believe HOME if it is an absolute path and exists.
828 * We only do this check on Windows for a couple of reasons.
829 * Historically, we only did it there because we used to ignore $HOME
830 * on UNIX. There are concerns about enabling it now on UNIX because
831 * of things like autofs. In short, if the user has a bogus value in
832 * $HOME then they get what they pay for...
834 if (tmp)
836 if (!(g_path_is_absolute (tmp) &&
837 g_file_test (tmp, G_FILE_TEST_IS_DIR)))
839 g_free (tmp);
840 tmp = NULL;
844 /* In case HOME is Unix-style (it happens), convert it to
845 * Windows style.
847 if (tmp)
849 gchar *p;
850 while ((p = strchr (tmp, '/')) != NULL)
851 *p = '\\';
854 if (!tmp)
856 /* USERPROFILE is probably the closest equivalent to $HOME? */
857 if (g_getenv ("USERPROFILE") != NULL)
858 tmp = g_strdup (g_getenv ("USERPROFILE"));
861 if (!tmp)
862 tmp = get_special_folder (CSIDL_PROFILE);
864 if (!tmp)
865 tmp = get_windows_directory_root ();
866 #endif /* G_OS_WIN32 */
868 if (!tmp)
870 /* If we didn't get it from any of those methods, we will have
871 * to read the user database entry.
873 UserDatabaseEntry *entry;
875 entry = g_get_user_database_entry ();
877 /* Strictly speaking, we should copy this, but we know that
878 * neither will ever be freed, so don't bother...
880 tmp = entry->home_dir;
883 g_once_init_leave (&home_dir, tmp);
886 return home_dir;
890 * g_get_tmp_dir:
892 * Gets the directory to use for temporary files.
894 * On UNIX, this is taken from the `TMPDIR` environment variable.
895 * If the variable is not set, `P_tmpdir` is
896 * used, as defined by the system C library. Failing that, a
897 * hard-coded default of "/tmp" is returned.
899 * On Windows, the `TEMP` environment variable is used, with the
900 * root directory of the Windows installation (eg: "C:\") used
901 * as a default.
903 * The encoding of the returned string is system-defined. On Windows,
904 * it is always UTF-8. The return value is never %NULL or the empty
905 * string.
907 * Returns: (type filename): the directory to use for temporary files.
909 const gchar *
910 g_get_tmp_dir (void)
912 static gchar *tmp_dir;
914 if (g_once_init_enter (&tmp_dir))
916 gchar *tmp;
918 #ifdef G_OS_WIN32
919 tmp = g_strdup (g_getenv ("TEMP"));
921 if (tmp == NULL || *tmp == '\0')
923 g_free (tmp);
924 tmp = get_windows_directory_root ();
926 #else /* G_OS_WIN32 */
927 tmp = g_strdup (g_getenv ("TMPDIR"));
929 #ifdef P_tmpdir
930 if (tmp == NULL || *tmp == '\0')
932 gsize k;
933 g_free (tmp);
934 tmp = g_strdup (P_tmpdir);
935 k = strlen (tmp);
936 if (k > 1 && G_IS_DIR_SEPARATOR (tmp[k - 1]))
937 tmp[k - 1] = '\0';
939 #endif /* P_tmpdir */
941 if (tmp == NULL || *tmp == '\0')
943 g_free (tmp);
944 tmp = g_strdup ("/tmp");
946 #endif /* !G_OS_WIN32 */
948 g_once_init_leave (&tmp_dir, tmp);
951 return tmp_dir;
955 * g_get_host_name:
957 * Return a name for the machine.
959 * The returned name is not necessarily a fully-qualified domain name,
960 * or even present in DNS or some other name service at all. It need
961 * not even be unique on your local network or site, but usually it
962 * is. Callers should not rely on the return value having any specific
963 * properties like uniqueness for security purposes. Even if the name
964 * of the machine is changed while an application is running, the
965 * return value from this function does not change. The returned
966 * string is owned by GLib and should not be modified or freed. If no
967 * name can be determined, a default fixed string "localhost" is
968 * returned.
970 * Returns: the host name of the machine.
972 * Since: 2.8
974 const gchar *
975 g_get_host_name (void)
977 static gchar *hostname;
979 if (g_once_init_enter (&hostname))
981 gboolean failed;
982 gchar tmp[100];
984 #ifndef G_OS_WIN32
985 failed = (gethostname (tmp, sizeof (tmp)) == -1);
986 #else
987 DWORD size = sizeof (tmp);
988 failed = (!GetComputerName (tmp, &size));
989 #endif
991 g_once_init_leave (&hostname, g_strdup (failed ? "localhost" : tmp));
994 return hostname;
997 G_LOCK_DEFINE_STATIC (g_prgname);
998 static gchar *g_prgname = NULL;
1001 * g_get_prgname:
1003 * Gets the name of the program. This name should not be localized,
1004 * in contrast to g_get_application_name().
1006 * If you are using GDK or GTK+ the program name is set in gdk_init(),
1007 * which is called by gtk_init(). The program name is found by taking
1008 * the last component of @argv[0].
1010 * Returns: the name of the program. The returned string belongs
1011 * to GLib and must not be modified or freed.
1013 const gchar*
1014 g_get_prgname (void)
1016 gchar* retval;
1018 G_LOCK (g_prgname);
1019 #ifdef G_OS_WIN32
1020 if (g_prgname == NULL)
1022 static gboolean beenhere = FALSE;
1024 if (!beenhere)
1026 gchar *utf8_buf = NULL;
1027 wchar_t buf[MAX_PATH+1];
1029 beenhere = TRUE;
1030 if (GetModuleFileNameW (GetModuleHandle (NULL),
1031 buf, G_N_ELEMENTS (buf)) > 0)
1032 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1034 if (utf8_buf)
1036 g_prgname = g_path_get_basename (utf8_buf);
1037 g_free (utf8_buf);
1041 #endif
1042 retval = g_prgname;
1043 G_UNLOCK (g_prgname);
1045 return retval;
1049 * g_set_prgname:
1050 * @prgname: the name of the program.
1052 * Sets the name of the program. This name should not be localized,
1053 * in contrast to g_set_application_name().
1055 * Note that for thread-safety reasons this function can only be called once.
1057 void
1058 g_set_prgname (const gchar *prgname)
1060 G_LOCK (g_prgname);
1061 g_free (g_prgname);
1062 g_prgname = g_strdup (prgname);
1063 G_UNLOCK (g_prgname);
1066 G_LOCK_DEFINE_STATIC (g_application_name);
1067 static gchar *g_application_name = NULL;
1070 * g_get_application_name:
1072 * Gets a human-readable name for the application, as set by
1073 * g_set_application_name(). This name should be localized if
1074 * possible, and is intended for display to the user. Contrast with
1075 * g_get_prgname(), which gets a non-localized name. If
1076 * g_set_application_name() has not been called, returns the result of
1077 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1078 * been called).
1080 * Returns: human-readable application name. may return %NULL
1082 * Since: 2.2
1084 const gchar *
1085 g_get_application_name (void)
1087 gchar* retval;
1089 G_LOCK (g_application_name);
1090 retval = g_application_name;
1091 G_UNLOCK (g_application_name);
1093 if (retval == NULL)
1094 return g_get_prgname ();
1096 return retval;
1100 * g_set_application_name:
1101 * @application_name: localized name of the application
1103 * Sets a human-readable name for the application. This name should be
1104 * localized if possible, and is intended for display to the user.
1105 * Contrast with g_set_prgname(), which sets a non-localized name.
1106 * g_set_prgname() will be called automatically by gtk_init(),
1107 * but g_set_application_name() will not.
1109 * Note that for thread safety reasons, this function can only
1110 * be called once.
1112 * The application name will be used in contexts such as error messages,
1113 * or when displaying an application's name in the task list.
1115 * Since: 2.2
1117 void
1118 g_set_application_name (const gchar *application_name)
1120 gboolean already_set = FALSE;
1122 G_LOCK (g_application_name);
1123 if (g_application_name)
1124 already_set = TRUE;
1125 else
1126 g_application_name = g_strdup (application_name);
1127 G_UNLOCK (g_application_name);
1129 if (already_set)
1130 g_warning ("g_set_application_name() called multiple times");
1134 * g_get_user_data_dir:
1136 * Returns a base directory in which to access application data such
1137 * as icons that is customized for a particular user.
1139 * On UNIX platforms this is determined using the mechanisms described
1140 * in the
1141 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1142 * In this case the directory retrieved will be `XDG_DATA_HOME`.
1144 * On Windows this is the folder to use for local (as opposed to
1145 * roaming) application data. See documentation for
1146 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1147 * what g_get_user_config_dir() returns.
1149 * Returns: (type filename): a string owned by GLib that must not be modified
1150 * or freed.
1151 * Since: 2.6
1153 const gchar *
1154 g_get_user_data_dir (void)
1156 gchar *data_dir;
1158 G_LOCK (g_utils_global);
1160 if (!g_user_data_dir)
1162 #ifdef G_OS_WIN32
1163 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1164 #else
1165 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1167 if (data_dir && data_dir[0])
1168 data_dir = g_strdup (data_dir);
1169 #endif
1170 if (!data_dir || !data_dir[0])
1172 const gchar *home_dir = g_get_home_dir ();
1174 if (home_dir)
1175 data_dir = g_build_filename (home_dir, ".local", "share", NULL);
1176 else
1177 data_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".local", "share", NULL);
1180 g_user_data_dir = data_dir;
1182 else
1183 data_dir = g_user_data_dir;
1185 G_UNLOCK (g_utils_global);
1187 return data_dir;
1190 static void
1191 g_init_user_config_dir (void)
1193 gchar *config_dir;
1195 if (!g_user_config_dir)
1197 #ifdef G_OS_WIN32
1198 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1199 #else
1200 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1202 if (config_dir && config_dir[0])
1203 config_dir = g_strdup (config_dir);
1204 #endif
1205 if (!config_dir || !config_dir[0])
1207 const gchar *home_dir = g_get_home_dir ();
1209 if (home_dir)
1210 config_dir = g_build_filename (home_dir, ".config", NULL);
1211 else
1212 config_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".config", NULL);
1215 g_user_config_dir = config_dir;
1220 * g_get_user_config_dir:
1222 * Returns a base directory in which to store user-specific application
1223 * configuration information such as user preferences and settings.
1225 * On UNIX platforms this is determined using the mechanisms described
1226 * in the
1227 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1228 * In this case the directory retrieved will be `XDG_CONFIG_HOME`.
1230 * On Windows this is the folder to use for local (as opposed to
1231 * roaming) application data. See documentation for
1232 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1233 * what g_get_user_data_dir() returns.
1235 * Returns: (type filename): a string owned by GLib that must not be modified
1236 * or freed.
1237 * Since: 2.6
1239 const gchar *
1240 g_get_user_config_dir (void)
1242 G_LOCK (g_utils_global);
1244 g_init_user_config_dir ();
1246 G_UNLOCK (g_utils_global);
1248 return g_user_config_dir;
1252 * g_get_user_cache_dir:
1254 * Returns a base directory in which to store non-essential, cached
1255 * data specific to particular user.
1257 * On UNIX platforms this is determined using the mechanisms described
1258 * in the
1259 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1260 * In this case the directory retrieved will be XDG_CACHE_HOME.
1262 * On Windows is the directory that serves as a common repository for
1263 * temporary Internet files. A typical path is
1264 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
1265 * See documentation for CSIDL_INTERNET_CACHE.
1267 * Returns: (type filename): a string owned by GLib that must not be modified
1268 * or freed.
1269 * Since: 2.6
1271 const gchar *
1272 g_get_user_cache_dir (void)
1274 gchar *cache_dir;
1276 G_LOCK (g_utils_global);
1278 if (!g_user_cache_dir)
1280 #ifdef G_OS_WIN32
1281 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1282 #else
1283 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1285 if (cache_dir && cache_dir[0])
1286 cache_dir = g_strdup (cache_dir);
1287 #endif
1288 if (!cache_dir || !cache_dir[0])
1290 const gchar *home_dir = g_get_home_dir ();
1292 if (home_dir)
1293 cache_dir = g_build_filename (home_dir, ".cache", NULL);
1294 else
1295 cache_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".cache", NULL);
1297 g_user_cache_dir = cache_dir;
1299 else
1300 cache_dir = g_user_cache_dir;
1302 G_UNLOCK (g_utils_global);
1304 return cache_dir;
1308 * g_get_user_runtime_dir:
1310 * Returns a directory that is unique to the current user on the local
1311 * system.
1313 * On UNIX platforms this is determined using the mechanisms described
1314 * in the
1315 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1316 * This is the directory
1317 * specified in the `XDG_RUNTIME_DIR` environment variable.
1318 * In the case that this variable is not set, we return the value of
1319 * g_get_user_cache_dir(), after verifying that it exists.
1321 * On Windows this is the folder to use for local (as opposed to
1322 * roaming) application data. See documentation for
1323 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1324 * what g_get_user_config_dir() returns.
1326 * Returns: (type filename): a string owned by GLib that must not be
1327 * modified or freed.
1329 * Since: 2.28
1331 const gchar *
1332 g_get_user_runtime_dir (void)
1334 #ifndef G_OS_WIN32
1335 static const gchar *runtime_dir;
1337 if (g_once_init_enter (&runtime_dir))
1339 const gchar *dir;
1341 dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
1343 if (dir == NULL)
1345 /* No need to strdup this one since it is valid forever. */
1346 dir = g_get_user_cache_dir ();
1348 /* The user should be able to rely on the directory existing
1349 * when the function returns. Probably it already does, but
1350 * let's make sure. Just do mkdir() directly since it will be
1351 * no more expensive than a stat() in the case that the
1352 * directory already exists and is a lot easier.
1354 * $XDG_CACHE_HOME is probably ~/.cache/ so as long as $HOME
1355 * exists this will work. If the user changed $XDG_CACHE_HOME
1356 * then they can make sure that it exists...
1358 (void) mkdir (dir, 0700);
1361 g_assert (dir != NULL);
1363 g_once_init_leave (&runtime_dir, dir);
1366 return runtime_dir;
1367 #else /* Windows */
1368 return g_get_user_cache_dir ();
1369 #endif
1372 #ifdef HAVE_CARBON
1374 static gchar *
1375 find_folder (OSType type)
1377 gchar *filename = NULL;
1378 FSRef found;
1380 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
1382 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
1384 if (url)
1386 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
1388 if (path)
1390 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
1392 if (! filename)
1394 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
1396 CFStringGetCString (path, filename,
1397 CFStringGetLength (path) * 3 + 1,
1398 kCFStringEncodingUTF8);
1401 CFRelease (path);
1404 CFRelease (url);
1408 return filename;
1411 static void
1412 load_user_special_dirs (void)
1414 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
1415 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
1416 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
1417 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
1418 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
1419 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
1420 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
1421 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
1424 #elif defined(G_OS_WIN32)
1426 static void
1427 load_user_special_dirs (void)
1429 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1430 DWORD dwFlags,
1431 HANDLE hToken,
1432 PWSTR *ppszPath);
1433 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
1435 static const GUID FOLDERID_Downloads =
1436 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1437 static const GUID FOLDERID_Public =
1438 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1440 wchar_t *wcp;
1442 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
1443 "SHGetKnownFolderPath");
1445 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1446 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
1448 if (p_SHGetKnownFolderPath == NULL)
1450 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1452 else
1454 wcp = NULL;
1455 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1456 if (wcp)
1458 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1459 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
1460 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1461 CoTaskMemFree (wcp);
1463 else
1464 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1467 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
1468 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
1470 if (p_SHGetKnownFolderPath == NULL)
1472 /* XXX */
1473 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1475 else
1477 wcp = NULL;
1478 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
1479 if (wcp)
1481 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1482 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
1483 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1484 CoTaskMemFree (wcp);
1486 else
1487 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1490 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
1491 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
1494 #else /* default is unix */
1496 /* adapted from xdg-user-dir-lookup.c
1498 * Copyright (C) 2007 Red Hat Inc.
1500 * Permission is hereby granted, free of charge, to any person
1501 * obtaining a copy of this software and associated documentation files
1502 * (the "Software"), to deal in the Software without restriction,
1503 * including without limitation the rights to use, copy, modify, merge,
1504 * publish, distribute, sublicense, and/or sell copies of the Software,
1505 * and to permit persons to whom the Software is furnished to do so,
1506 * subject to the following conditions:
1508 * The above copyright notice and this permission notice shall be
1509 * included in all copies or substantial portions of the Software.
1511 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1512 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1513 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1514 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1515 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1516 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1517 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1518 * SOFTWARE.
1520 static void
1521 load_user_special_dirs (void)
1523 gchar *config_file;
1524 gchar *data;
1525 gchar **lines;
1526 gint n_lines, i;
1528 g_init_user_config_dir ();
1529 config_file = g_build_filename (g_user_config_dir,
1530 "user-dirs.dirs",
1531 NULL);
1533 if (!g_file_get_contents (config_file, &data, NULL, NULL))
1535 g_free (config_file);
1536 return;
1539 lines = g_strsplit (data, "\n", -1);
1540 n_lines = g_strv_length (lines);
1541 g_free (data);
1543 for (i = 0; i < n_lines; i++)
1545 gchar *buffer = lines[i];
1546 gchar *d, *p;
1547 gint len;
1548 gboolean is_relative = FALSE;
1549 GUserDirectory directory;
1551 /* Remove newline at end */
1552 len = strlen (buffer);
1553 if (len > 0 && buffer[len - 1] == '\n')
1554 buffer[len - 1] = 0;
1556 p = buffer;
1557 while (*p == ' ' || *p == '\t')
1558 p++;
1560 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
1562 directory = G_USER_DIRECTORY_DESKTOP;
1563 p += strlen ("XDG_DESKTOP_DIR");
1565 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
1567 directory = G_USER_DIRECTORY_DOCUMENTS;
1568 p += strlen ("XDG_DOCUMENTS_DIR");
1570 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
1572 directory = G_USER_DIRECTORY_DOWNLOAD;
1573 p += strlen ("XDG_DOWNLOAD_DIR");
1575 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
1577 directory = G_USER_DIRECTORY_MUSIC;
1578 p += strlen ("XDG_MUSIC_DIR");
1580 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
1582 directory = G_USER_DIRECTORY_PICTURES;
1583 p += strlen ("XDG_PICTURES_DIR");
1585 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
1587 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
1588 p += strlen ("XDG_PUBLICSHARE_DIR");
1590 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
1592 directory = G_USER_DIRECTORY_TEMPLATES;
1593 p += strlen ("XDG_TEMPLATES_DIR");
1595 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
1597 directory = G_USER_DIRECTORY_VIDEOS;
1598 p += strlen ("XDG_VIDEOS_DIR");
1600 else
1601 continue;
1603 while (*p == ' ' || *p == '\t')
1604 p++;
1606 if (*p != '=')
1607 continue;
1608 p++;
1610 while (*p == ' ' || *p == '\t')
1611 p++;
1613 if (*p != '"')
1614 continue;
1615 p++;
1617 if (strncmp (p, "$HOME", 5) == 0)
1619 p += 5;
1620 is_relative = TRUE;
1622 else if (*p != '/')
1623 continue;
1625 d = strrchr (p, '"');
1626 if (!d)
1627 continue;
1628 *d = 0;
1630 d = p;
1632 /* remove trailing slashes */
1633 len = strlen (d);
1634 if (d[len - 1] == '/')
1635 d[len - 1] = 0;
1637 if (is_relative)
1639 g_user_special_dirs[directory] = g_build_filename (g_get_home_dir (), d, NULL);
1641 else
1642 g_user_special_dirs[directory] = g_strdup (d);
1645 g_strfreev (lines);
1646 g_free (config_file);
1649 #endif /* platform-specific load_user_special_dirs implementations */
1653 * g_reload_user_special_dirs_cache:
1655 * Resets the cache used for g_get_user_special_dir(), so
1656 * that the latest on-disk version is used. Call this only
1657 * if you just changed the data on disk yourself.
1659 * Due to threadsafety issues this may cause leaking of strings
1660 * that were previously returned from g_get_user_special_dir()
1661 * that can't be freed. We ensure to only leak the data for
1662 * the directories that actually changed value though.
1664 * Since: 2.22
1666 void
1667 g_reload_user_special_dirs_cache (void)
1669 int i;
1671 G_LOCK (g_utils_global);
1673 if (g_user_special_dirs != NULL)
1675 /* save a copy of the pointer, to check if some memory can be preserved */
1676 char **old_g_user_special_dirs = g_user_special_dirs;
1677 char *old_val;
1679 /* recreate and reload our cache */
1680 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1681 load_user_special_dirs ();
1683 /* only leak changed directories */
1684 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
1686 old_val = old_g_user_special_dirs[i];
1687 if (g_user_special_dirs[i] == NULL)
1689 g_user_special_dirs[i] = old_val;
1691 else if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
1693 /* don't leak */
1694 g_free (g_user_special_dirs[i]);
1695 g_user_special_dirs[i] = old_val;
1697 else
1698 g_free (old_val);
1701 /* free the old array */
1702 g_free (old_g_user_special_dirs);
1705 G_UNLOCK (g_utils_global);
1709 * g_get_user_special_dir:
1710 * @directory: the logical id of special directory
1712 * Returns the full path of a special directory using its logical id.
1714 * On UNIX this is done using the XDG special user directories.
1715 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
1716 * falls back to `$HOME/Desktop` when XDG special user directories have
1717 * not been set up.
1719 * Depending on the platform, the user might be able to change the path
1720 * of the special directory without requiring the session to restart; GLib
1721 * will not reflect any change once the special directories are loaded.
1723 * Returns: (type filename): the path to the specified special directory, or
1724 * %NULL if the logical id was not found. The returned string is owned by
1725 * GLib and should not be modified or freed.
1727 * Since: 2.14
1729 const gchar *
1730 g_get_user_special_dir (GUserDirectory directory)
1732 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
1733 directory < G_USER_N_DIRECTORIES, NULL);
1735 G_LOCK (g_utils_global);
1737 if (G_UNLIKELY (g_user_special_dirs == NULL))
1739 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1741 load_user_special_dirs ();
1743 /* Special-case desktop for historical compatibility */
1744 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
1745 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = g_build_filename (g_get_home_dir (), "Desktop", NULL);
1748 G_UNLOCK (g_utils_global);
1750 return g_user_special_dirs[directory];
1753 #ifdef G_OS_WIN32
1755 #undef g_get_system_data_dirs
1757 static HMODULE
1758 get_module_for_address (gconstpointer address)
1760 /* Holds the g_utils_global lock */
1762 static gboolean beenhere = FALSE;
1763 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
1764 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
1765 HMODULE hmodule = NULL;
1767 if (!address)
1768 return NULL;
1770 if (!beenhere)
1772 p_GetModuleHandleExA =
1773 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1774 "GetModuleHandleExA");
1775 beenhere = TRUE;
1778 if (p_GetModuleHandleExA == NULL ||
1779 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
1780 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
1781 address, &hmodule))
1783 MEMORY_BASIC_INFORMATION mbi;
1784 VirtualQuery (address, &mbi, sizeof (mbi));
1785 hmodule = (HMODULE) mbi.AllocationBase;
1788 return hmodule;
1791 static gchar *
1792 get_module_share_dir (gconstpointer address)
1794 HMODULE hmodule;
1795 gchar *filename;
1796 gchar *retval;
1798 hmodule = get_module_for_address (address);
1799 if (hmodule == NULL)
1800 return NULL;
1802 filename = g_win32_get_package_installation_directory_of_module (hmodule);
1803 retval = g_build_filename (filename, "share", NULL);
1804 g_free (filename);
1806 return retval;
1809 const gchar * const *
1810 g_win32_get_system_data_dirs_for_module (void (*address_of_function)(void))
1812 GArray *data_dirs;
1813 HMODULE hmodule;
1814 static GHashTable *per_module_data_dirs = NULL;
1815 gchar **retval;
1816 gchar *p;
1817 gchar *exe_root;
1819 hmodule = NULL;
1820 if (address_of_function)
1822 G_LOCK (g_utils_global);
1823 hmodule = get_module_for_address (address_of_function);
1824 if (hmodule != NULL)
1826 if (per_module_data_dirs == NULL)
1827 per_module_data_dirs = g_hash_table_new (NULL, NULL);
1828 else
1830 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
1832 if (retval != NULL)
1834 G_UNLOCK (g_utils_global);
1835 return (const gchar * const *) retval;
1841 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
1843 /* Documents and Settings\All Users\Application Data */
1844 p = get_special_folder (CSIDL_COMMON_APPDATA);
1845 if (p)
1846 g_array_append_val (data_dirs, p);
1848 /* Documents and Settings\All Users\Documents */
1849 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1850 if (p)
1851 g_array_append_val (data_dirs, p);
1853 /* Using the above subfolders of Documents and Settings perhaps
1854 * makes sense from a Windows perspective.
1856 * But looking at the actual use cases of this function in GTK+
1857 * and GNOME software, what we really want is the "share"
1858 * subdirectory of the installation directory for the package
1859 * our caller is a part of.
1861 * The address_of_function parameter, if non-NULL, points to a
1862 * function in the calling module. Use that to determine that
1863 * module's installation folder, and use its "share" subfolder.
1865 * Additionally, also use the "share" subfolder of the installation
1866 * locations of GLib and the .exe file being run.
1868 * To guard against none of the above being what is really wanted,
1869 * callers of this function should have Win32-specific code to look
1870 * up their installation folder themselves, and handle a subfolder
1871 * "share" of it in the same way as the folders returned from this
1872 * function.
1875 p = get_module_share_dir (address_of_function);
1876 if (p)
1877 g_array_append_val (data_dirs, p);
1879 if (glib_dll != NULL)
1881 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
1882 p = g_build_filename (glib_root, "share", NULL);
1883 if (p)
1884 g_array_append_val (data_dirs, p);
1885 g_free (glib_root);
1888 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
1889 p = g_build_filename (exe_root, "share", NULL);
1890 if (p)
1891 g_array_append_val (data_dirs, p);
1892 g_free (exe_root);
1894 retval = (gchar **) g_array_free (data_dirs, FALSE);
1896 if (address_of_function)
1898 if (hmodule != NULL)
1899 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
1900 G_UNLOCK (g_utils_global);
1903 return (const gchar * const *) retval;
1906 #endif
1909 * g_get_system_data_dirs:
1911 * Returns an ordered list of base directories in which to access
1912 * system-wide application data.
1914 * On UNIX platforms this is determined using the mechanisms described
1915 * in the
1916 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec)
1917 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
1919 * On Windows the first elements in the list are the Application Data
1920 * and Documents folders for All Users. (These can be determined only
1921 * on Windows 2000 or later and are not present in the list on other
1922 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
1923 * CSIDL_COMMON_DOCUMENTS.
1925 * Then follows the "share" subfolder in the installation folder for
1926 * the package containing the DLL that calls this function, if it can
1927 * be determined.
1929 * Finally the list contains the "share" subfolder in the installation
1930 * folder for GLib, and in the installation folder for the package the
1931 * application's .exe file belongs to.
1933 * The installation folders above are determined by looking up the
1934 * folder where the module (DLL or EXE) in question is located. If the
1935 * folder's name is "bin", its parent is used, otherwise the folder
1936 * itself.
1938 * Note that on Windows the returned list can vary depending on where
1939 * this function is called.
1941 * Returns: (array zero-terminated=1) (element-type filename) (transfer none):
1942 * a %NULL-terminated array of strings owned by GLib that must not be
1943 * modified or freed.
1945 * Since: 2.6
1947 const gchar * const *
1948 g_get_system_data_dirs (void)
1950 gchar **data_dir_vector;
1952 G_LOCK (g_utils_global);
1954 if (!g_system_data_dirs)
1956 #ifdef G_OS_WIN32
1957 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
1958 #else
1959 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
1961 if (!data_dirs || !data_dirs[0])
1962 data_dirs = "/usr/local/share/:/usr/share/";
1964 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1965 #endif
1967 g_system_data_dirs = data_dir_vector;
1969 else
1970 data_dir_vector = g_system_data_dirs;
1972 G_UNLOCK (g_utils_global);
1974 return (const gchar * const *) data_dir_vector;
1978 * g_get_system_config_dirs:
1980 * Returns an ordered list of base directories in which to access
1981 * system-wide configuration information.
1983 * On UNIX platforms this is determined using the mechanisms described
1984 * in the
1985 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1986 * In this case the list of directories retrieved will be `XDG_CONFIG_DIRS`.
1988 * On Windows is the directory that contains application data for all users.
1989 * A typical path is C:\Documents and Settings\All Users\Application Data.
1990 * This folder is used for application data that is not user specific.
1991 * For example, an application can store a spell-check dictionary, a database
1992 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
1993 * This information will not roam and is available to anyone using the computer.
1995 * Returns: (array zero-terminated=1) (element-type filename) (transfer none):
1996 * a %NULL-terminated array of strings owned by GLib that must not be
1997 * modified or freed.
1999 * Since: 2.6
2001 const gchar * const *
2002 g_get_system_config_dirs (void)
2004 gchar *conf_dirs, **conf_dir_vector;
2006 G_LOCK (g_utils_global);
2008 if (!g_system_config_dirs)
2010 #ifdef G_OS_WIN32
2011 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2012 if (conf_dirs)
2014 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2015 g_free (conf_dirs);
2017 else
2019 /* Return empty list */
2020 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2022 #else
2023 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2025 if (!conf_dirs || !conf_dirs[0])
2026 conf_dirs = "/etc/xdg";
2028 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2029 #endif
2031 g_system_config_dirs = conf_dir_vector;
2033 else
2034 conf_dir_vector = g_system_config_dirs;
2035 G_UNLOCK (g_utils_global);
2037 return (const gchar * const *) conf_dir_vector;
2041 * g_nullify_pointer:
2042 * @nullify_location: (not nullable): the memory address of the pointer.
2044 * Set the pointer at the specified location to %NULL.
2046 void
2047 g_nullify_pointer (gpointer *nullify_location)
2049 g_return_if_fail (nullify_location != NULL);
2051 *nullify_location = NULL;
2054 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2055 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2056 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2057 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2058 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2059 #define EXABYTE_FACTOR (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2061 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2062 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2063 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2064 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2065 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2066 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2069 * g_format_size:
2070 * @size: a size in bytes
2072 * Formats a size (for example the size of a file) into a human readable
2073 * string. Sizes are rounded to the nearest size prefix (kB, MB, GB)
2074 * and are displayed rounded to the nearest tenth. E.g. the file size
2075 * 3292528 bytes will be converted into the string "3.2 MB".
2077 * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2079 * This string should be freed with g_free() when not needed any longer.
2081 * See g_format_size_full() for more options about how the size might be
2082 * formatted.
2084 * Returns: a newly-allocated formatted string containing a human readable
2085 * file size
2087 * Since: 2.30
2089 gchar *
2090 g_format_size (guint64 size)
2092 return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2096 * GFormatSizeFlags:
2097 * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2098 * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2099 * of the returned string. For example, "45.6 kB (45,612 bytes)".
2100 * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2101 * suffixes. IEC units should only be used for reporting things with
2102 * a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2103 * Network and storage sizes should be reported in the normal SI units.
2105 * Flags to modify the format of the string returned by g_format_size_full().
2108 #pragma GCC diagnostic push
2109 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
2112 * g_format_size_full:
2113 * @size: a size in bytes
2114 * @flags: #GFormatSizeFlags to modify the output
2116 * Formats a size.
2118 * This function is similar to g_format_size() but allows for flags
2119 * that modify the output. See #GFormatSizeFlags.
2121 * Returns: a newly-allocated formatted string containing a human
2122 * readable file size
2124 * Since: 2.30
2126 gchar *
2127 g_format_size_full (guint64 size,
2128 GFormatSizeFlags flags)
2130 GString *string;
2132 string = g_string_new (NULL);
2134 if (flags & G_FORMAT_SIZE_IEC_UNITS)
2136 if (size < KIBIBYTE_FACTOR)
2138 g_string_printf (string,
2139 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2140 (guint) size);
2141 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2144 else if (size < MEBIBYTE_FACTOR)
2145 g_string_printf (string, _("%.1f KiB"), (gdouble) size / (gdouble) KIBIBYTE_FACTOR);
2146 else if (size < GIBIBYTE_FACTOR)
2147 g_string_printf (string, _("%.1f MiB"), (gdouble) size / (gdouble) MEBIBYTE_FACTOR);
2149 else if (size < TEBIBYTE_FACTOR)
2150 g_string_printf (string, _("%.1f GiB"), (gdouble) size / (gdouble) GIBIBYTE_FACTOR);
2152 else if (size < PEBIBYTE_FACTOR)
2153 g_string_printf (string, _("%.1f TiB"), (gdouble) size / (gdouble) TEBIBYTE_FACTOR);
2155 else if (size < EXBIBYTE_FACTOR)
2156 g_string_printf (string, _("%.1f PiB"), (gdouble) size / (gdouble) PEBIBYTE_FACTOR);
2158 else
2159 g_string_printf (string, _("%.1f EiB"), (gdouble) size / (gdouble) EXBIBYTE_FACTOR);
2161 else
2163 if (size < KILOBYTE_FACTOR)
2165 g_string_printf (string,
2166 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2167 (guint) size);
2168 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2171 else if (size < MEGABYTE_FACTOR)
2172 g_string_printf (string, _("%.1f kB"), (gdouble) size / (gdouble) KILOBYTE_FACTOR);
2174 else if (size < GIGABYTE_FACTOR)
2175 g_string_printf (string, _("%.1f MB"), (gdouble) size / (gdouble) MEGABYTE_FACTOR);
2177 else if (size < TERABYTE_FACTOR)
2178 g_string_printf (string, _("%.1f GB"), (gdouble) size / (gdouble) GIGABYTE_FACTOR);
2179 else if (size < PETABYTE_FACTOR)
2180 g_string_printf (string, _("%.1f TB"), (gdouble) size / (gdouble) TERABYTE_FACTOR);
2182 else if (size < EXABYTE_FACTOR)
2183 g_string_printf (string, _("%.1f PB"), (gdouble) size / (gdouble) PETABYTE_FACTOR);
2185 else
2186 g_string_printf (string, _("%.1f EB"), (gdouble) size / (gdouble) EXABYTE_FACTOR);
2189 if (flags & G_FORMAT_SIZE_LONG_FORMAT)
2191 /* First problem: we need to use the number of bytes to decide on
2192 * the plural form that is used for display, but the number of
2193 * bytes potentially exceeds the size of a guint (which is what
2194 * ngettext() takes).
2196 * From a pragmatic standpoint, it seems that all known languages
2197 * base plural forms on one or both of the following:
2199 * - the lowest digits of the number
2201 * - if the number if greater than some small value
2203 * Here's how we fake it: Draw an arbitrary line at one thousand.
2204 * If the number is below that, then fine. If it is above it,
2205 * then we take the modulus of the number by one thousand (in
2206 * order to keep the lowest digits) and add one thousand to that
2207 * (in order to ensure that 1001 is not treated the same as 1).
2209 guint plural_form = size < 1000 ? size : size % 1000 + 1000;
2211 /* Second problem: we need to translate the string "%u byte" and
2212 * "%u bytes" for pluralisation, but the correct number format to
2213 * use for a gsize is different depending on which architecture
2214 * we're on.
2216 * Solution: format the number separately and use "%s bytes" on
2217 * all platforms.
2219 const gchar *translated_format;
2220 gchar *formatted_number;
2222 /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2223 translated_format = g_dngettext(GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
2224 /* XXX: Windows doesn't support the "'" format modifier, so we
2225 * must not use it there. Instead, just display the number
2226 * without separation. Bug #655336 is open until a solution is
2227 * found.
2229 #ifndef G_OS_WIN32
2230 formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2231 #else
2232 formatted_number = g_strdup_printf ("%"G_GUINT64_FORMAT, size);
2233 #endif
2235 g_string_append (string, " (");
2236 g_string_append_printf (string, translated_format, formatted_number);
2237 g_free (formatted_number);
2238 g_string_append (string, ")");
2241 return g_string_free (string, FALSE);
2244 #pragma GCC diagnostic pop
2247 * g_format_size_for_display:
2248 * @size: a size in bytes
2250 * Formats a size (for example the size of a file) into a human
2251 * readable string. Sizes are rounded to the nearest size prefix
2252 * (KB, MB, GB) and are displayed rounded to the nearest tenth.
2253 * E.g. the file size 3292528 bytes will be converted into the
2254 * string "3.1 MB".
2256 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2258 * This string should be freed with g_free() when not needed any longer.
2260 * Returns: a newly-allocated formatted string containing a human
2261 * readable file size
2263 * Since: 2.16
2265 * Deprecated:2.30: This function is broken due to its use of SI
2266 * suffixes to denote IEC units. Use g_format_size() instead.
2268 gchar *
2269 g_format_size_for_display (goffset size)
2271 if (size < (goffset) KIBIBYTE_FACTOR)
2272 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
2273 else
2275 gdouble displayed_size;
2277 if (size < (goffset) MEBIBYTE_FACTOR)
2279 displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
2280 /* Translators: this is from the deprecated function g_format_size_for_display() which uses 'KB' to
2281 * mean 1024 bytes. I am aware that 'KB' is not correct, but it has been preserved for reasons of
2282 * compatibility. Users will not see this string unless a program is using this deprecated function.
2283 * Please translate as literally as possible.
2285 return g_strdup_printf (_("%.1f KB"), displayed_size);
2287 else if (size < (goffset) GIBIBYTE_FACTOR)
2289 displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
2290 return g_strdup_printf (_("%.1f MB"), displayed_size);
2292 else if (size < (goffset) TEBIBYTE_FACTOR)
2294 displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
2295 return g_strdup_printf (_("%.1f GB"), displayed_size);
2297 else if (size < (goffset) PEBIBYTE_FACTOR)
2299 displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
2300 return g_strdup_printf (_("%.1f TB"), displayed_size);
2302 else if (size < (goffset) EXBIBYTE_FACTOR)
2304 displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
2305 return g_strdup_printf (_("%.1f PB"), displayed_size);
2307 else
2309 displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
2310 return g_strdup_printf (_("%.1f EB"), displayed_size);
2315 #if defined (G_OS_WIN32) && !defined (_WIN64)
2317 /* Binary compatibility versions. Not for newly compiled code. */
2319 _GLIB_EXTERN const gchar *g_get_user_name_utf8 (void);
2320 _GLIB_EXTERN const gchar *g_get_real_name_utf8 (void);
2321 _GLIB_EXTERN const gchar *g_get_home_dir_utf8 (void);
2322 _GLIB_EXTERN const gchar *g_get_tmp_dir_utf8 (void);
2323 _GLIB_EXTERN gchar *g_find_program_in_path_utf8 (const gchar *program);
2325 gchar *
2326 g_find_program_in_path_utf8 (const gchar *program)
2328 return g_find_program_in_path (program);
2331 const gchar *g_get_user_name_utf8 (void) { return g_get_user_name (); }
2332 const gchar *g_get_real_name_utf8 (void) { return g_get_real_name (); }
2333 const gchar *g_get_home_dir_utf8 (void) { return g_get_home_dir (); }
2334 const gchar *g_get_tmp_dir_utf8 (void) { return g_get_tmp_dir (); }
2336 #endif
2338 /* Private API:
2340 * Returns %TRUE if the current process was executed as setuid (or an
2341 * equivalent __libc_enable_secure is available). See:
2342 * http://osdir.com/ml/linux.lfs.hardened/2007-04/msg00032.html
2344 gboolean
2345 g_check_setuid (void)
2347 /* TODO: get __libc_enable_secure exported from glibc.
2348 * See http://www.openwall.com/lists/owl-dev/2012/08/14/1
2350 #if 0 && defined(HAVE_LIBC_ENABLE_SECURE)
2352 /* See glibc/include/unistd.h */
2353 extern int __libc_enable_secure;
2354 return __libc_enable_secure;
2356 #elif defined(HAVE_ISSETUGID) && !defined(__BIONIC__)
2357 /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
2359 /* Android had it in older versions but the new 64 bit ABI does not
2360 * have it anymore, and some versions of the 32 bit ABI neither.
2361 * https://code.google.com/p/android-developer-preview/issues/detail?id=168
2363 return issetugid ();
2364 #elif defined(G_OS_UNIX)
2365 uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
2366 gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
2368 static gsize check_setuid_initialised;
2369 static gboolean is_setuid;
2371 if (g_once_init_enter (&check_setuid_initialised))
2373 #ifdef HAVE_GETRESUID
2374 /* These aren't in the header files, so we prototype them here.
2376 int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
2377 int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);
2379 if (getresuid (&ruid, &euid, &suid) != 0 ||
2380 getresgid (&rgid, &egid, &sgid) != 0)
2381 #endif /* HAVE_GETRESUID */
2383 suid = ruid = getuid ();
2384 sgid = rgid = getgid ();
2385 euid = geteuid ();
2386 egid = getegid ();
2389 is_setuid = (ruid != euid || ruid != suid ||
2390 rgid != egid || rgid != sgid);
2392 g_once_init_leave (&check_setuid_initialised, 1);
2394 return is_setuid;
2395 #else
2396 return FALSE;
2397 #endif
2400 #ifdef G_OS_WIN32
2402 * g_abort:
2404 * A wrapper for the POSIX abort() function.
2406 * On Windows it is a function that makes extra effort (including a call
2407 * to abort()) to ensure that a debugger-catchable exception is thrown
2408 * before the program terminates.
2410 * See your C library manual for more details about abort().
2412 * Since: 2.50
2414 void
2415 g_abort (void)
2417 /* One call to break the debugger */
2418 DebugBreak ();
2419 /* One call in case CRT does get saner about abort() behaviour */
2420 abort ();
2421 /* And one call to bind them all and terminate the program for sure */
2422 ExitProcess (127);
2424 #endif