meson: Use glib-mkenums directly instead of via build_mkenum.py
[glib.git] / glib / gutils.c
blob70b08b6e114f76cc0b8a5e9e0c35ada80d0e9d08
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.1 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 #GApplication the program name is set in
1007 * g_application_run(). In case of GDK or GTK+ it is set in
1008 * gdk_init(), which is called by gtk_init() and the
1009 * #GtkApplication::startup handler. The program name is found by
1010 * taking the last component of @argv[0].
1012 * Returns: the name of the program. The returned string belongs
1013 * to GLib and must not be modified or freed.
1015 const gchar*
1016 g_get_prgname (void)
1018 gchar* retval;
1020 G_LOCK (g_prgname);
1021 #ifdef G_OS_WIN32
1022 if (g_prgname == NULL)
1024 static gboolean beenhere = FALSE;
1026 if (!beenhere)
1028 gchar *utf8_buf = NULL;
1029 wchar_t buf[MAX_PATH+1];
1031 beenhere = TRUE;
1032 if (GetModuleFileNameW (GetModuleHandle (NULL),
1033 buf, G_N_ELEMENTS (buf)) > 0)
1034 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1036 if (utf8_buf)
1038 g_prgname = g_path_get_basename (utf8_buf);
1039 g_free (utf8_buf);
1043 #endif
1044 retval = g_prgname;
1045 G_UNLOCK (g_prgname);
1047 return retval;
1051 * g_set_prgname:
1052 * @prgname: the name of the program.
1054 * Sets the name of the program. This name should not be localized,
1055 * in contrast to g_set_application_name().
1057 * If you are using #GApplication the program name is set in
1058 * g_application_run(). In case of GDK or GTK+ it is set in
1059 * gdk_init(), which is called by gtk_init() and the
1060 * #GtkApplication::startup handler. The program name is found by
1061 * taking the last component of @argv[0].
1063 * Note that for thread-safety reasons this function can only be called once.
1065 void
1066 g_set_prgname (const gchar *prgname)
1068 G_LOCK (g_prgname);
1069 g_free (g_prgname);
1070 g_prgname = g_strdup (prgname);
1071 G_UNLOCK (g_prgname);
1074 G_LOCK_DEFINE_STATIC (g_application_name);
1075 static gchar *g_application_name = NULL;
1078 * g_get_application_name:
1080 * Gets a human-readable name for the application, as set by
1081 * g_set_application_name(). This name should be localized if
1082 * possible, and is intended for display to the user. Contrast with
1083 * g_get_prgname(), which gets a non-localized name. If
1084 * g_set_application_name() has not been called, returns the result of
1085 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1086 * been called).
1088 * Returns: human-readable application name. may return %NULL
1090 * Since: 2.2
1092 const gchar *
1093 g_get_application_name (void)
1095 gchar* retval;
1097 G_LOCK (g_application_name);
1098 retval = g_application_name;
1099 G_UNLOCK (g_application_name);
1101 if (retval == NULL)
1102 return g_get_prgname ();
1104 return retval;
1108 * g_set_application_name:
1109 * @application_name: localized name of the application
1111 * Sets a human-readable name for the application. This name should be
1112 * localized if possible, and is intended for display to the user.
1113 * Contrast with g_set_prgname(), which sets a non-localized name.
1114 * g_set_prgname() will be called automatically by gtk_init(),
1115 * but g_set_application_name() will not.
1117 * Note that for thread safety reasons, this function can only
1118 * be called once.
1120 * The application name will be used in contexts such as error messages,
1121 * or when displaying an application's name in the task list.
1123 * Since: 2.2
1125 void
1126 g_set_application_name (const gchar *application_name)
1128 gboolean already_set = FALSE;
1130 G_LOCK (g_application_name);
1131 if (g_application_name)
1132 already_set = TRUE;
1133 else
1134 g_application_name = g_strdup (application_name);
1135 G_UNLOCK (g_application_name);
1137 if (already_set)
1138 g_warning ("g_set_application_name() called multiple times");
1142 * g_get_user_data_dir:
1144 * Returns a base directory in which to access application data such
1145 * as icons that is customized for a particular user.
1147 * On UNIX platforms this is determined using the mechanisms described
1148 * in the
1149 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1150 * In this case the directory retrieved will be `XDG_DATA_HOME`.
1152 * On Windows this is the folder to use for local (as opposed to
1153 * roaming) application data. See documentation for
1154 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1155 * what g_get_user_config_dir() returns.
1157 * Returns: (type filename): a string owned by GLib that must not be modified
1158 * or freed.
1159 * Since: 2.6
1161 const gchar *
1162 g_get_user_data_dir (void)
1164 gchar *data_dir;
1166 G_LOCK (g_utils_global);
1168 if (!g_user_data_dir)
1170 #ifdef G_OS_WIN32
1171 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1172 #else
1173 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1175 if (data_dir && data_dir[0])
1176 data_dir = g_strdup (data_dir);
1177 #endif
1178 if (!data_dir || !data_dir[0])
1180 const gchar *home_dir = g_get_home_dir ();
1182 if (home_dir)
1183 data_dir = g_build_filename (home_dir, ".local", "share", NULL);
1184 else
1185 data_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".local", "share", NULL);
1188 g_user_data_dir = data_dir;
1190 else
1191 data_dir = g_user_data_dir;
1193 G_UNLOCK (g_utils_global);
1195 return data_dir;
1198 static void
1199 g_init_user_config_dir (void)
1201 gchar *config_dir;
1203 if (!g_user_config_dir)
1205 #ifdef G_OS_WIN32
1206 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1207 #else
1208 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1210 if (config_dir && config_dir[0])
1211 config_dir = g_strdup (config_dir);
1212 #endif
1213 if (!config_dir || !config_dir[0])
1215 const gchar *home_dir = g_get_home_dir ();
1217 if (home_dir)
1218 config_dir = g_build_filename (home_dir, ".config", NULL);
1219 else
1220 config_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".config", NULL);
1223 g_user_config_dir = config_dir;
1228 * g_get_user_config_dir:
1230 * Returns a base directory in which to store user-specific application
1231 * configuration information such as user preferences and settings.
1233 * On UNIX platforms this is determined using the mechanisms described
1234 * in the
1235 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1236 * In this case the directory retrieved will be `XDG_CONFIG_HOME`.
1238 * On Windows this is the folder to use for local (as opposed to
1239 * roaming) application data. See documentation for
1240 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1241 * what g_get_user_data_dir() returns.
1243 * Returns: (type filename): a string owned by GLib that must not be modified
1244 * or freed.
1245 * Since: 2.6
1247 const gchar *
1248 g_get_user_config_dir (void)
1250 G_LOCK (g_utils_global);
1252 g_init_user_config_dir ();
1254 G_UNLOCK (g_utils_global);
1256 return g_user_config_dir;
1260 * g_get_user_cache_dir:
1262 * Returns a base directory in which to store non-essential, cached
1263 * data specific to particular user.
1265 * On UNIX platforms this is determined using the mechanisms described
1266 * in the
1267 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1268 * In this case the directory retrieved will be XDG_CACHE_HOME.
1270 * On Windows is the directory that serves as a common repository for
1271 * temporary Internet files. A typical path is
1272 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
1273 * See documentation for CSIDL_INTERNET_CACHE.
1275 * Returns: (type filename): a string owned by GLib that must not be modified
1276 * or freed.
1277 * Since: 2.6
1279 const gchar *
1280 g_get_user_cache_dir (void)
1282 gchar *cache_dir;
1284 G_LOCK (g_utils_global);
1286 if (!g_user_cache_dir)
1288 #ifdef G_OS_WIN32
1289 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1290 #else
1291 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1293 if (cache_dir && cache_dir[0])
1294 cache_dir = g_strdup (cache_dir);
1295 #endif
1296 if (!cache_dir || !cache_dir[0])
1298 const gchar *home_dir = g_get_home_dir ();
1300 if (home_dir)
1301 cache_dir = g_build_filename (home_dir, ".cache", NULL);
1302 else
1303 cache_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".cache", NULL);
1305 g_user_cache_dir = cache_dir;
1307 else
1308 cache_dir = g_user_cache_dir;
1310 G_UNLOCK (g_utils_global);
1312 return cache_dir;
1316 * g_get_user_runtime_dir:
1318 * Returns a directory that is unique to the current user on the local
1319 * system.
1321 * On UNIX platforms this is determined using the mechanisms described
1322 * in the
1323 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1324 * This is the directory
1325 * specified in the `XDG_RUNTIME_DIR` environment variable.
1326 * In the case that this variable is not set, we return the value of
1327 * g_get_user_cache_dir(), after verifying that it exists.
1329 * On Windows this is the folder to use for local (as opposed to
1330 * roaming) application data. See documentation for
1331 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1332 * what g_get_user_config_dir() returns.
1334 * Returns: (type filename): a string owned by GLib that must not be
1335 * modified or freed.
1337 * Since: 2.28
1339 const gchar *
1340 g_get_user_runtime_dir (void)
1342 #ifndef G_OS_WIN32
1343 static const gchar *runtime_dir;
1345 if (g_once_init_enter (&runtime_dir))
1347 const gchar *dir;
1349 dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
1351 if (dir == NULL)
1353 /* No need to strdup this one since it is valid forever. */
1354 dir = g_get_user_cache_dir ();
1356 /* The user should be able to rely on the directory existing
1357 * when the function returns. Probably it already does, but
1358 * let's make sure. Just do mkdir() directly since it will be
1359 * no more expensive than a stat() in the case that the
1360 * directory already exists and is a lot easier.
1362 * $XDG_CACHE_HOME is probably ~/.cache/ so as long as $HOME
1363 * exists this will work. If the user changed $XDG_CACHE_HOME
1364 * then they can make sure that it exists...
1366 (void) mkdir (dir, 0700);
1369 g_assert (dir != NULL);
1371 g_once_init_leave (&runtime_dir, dir);
1374 return runtime_dir;
1375 #else /* Windows */
1376 return g_get_user_cache_dir ();
1377 #endif
1380 #ifdef HAVE_CARBON
1382 static gchar *
1383 find_folder (OSType type)
1385 gchar *filename = NULL;
1386 FSRef found;
1388 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
1390 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
1392 if (url)
1394 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
1396 if (path)
1398 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
1400 if (! filename)
1402 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
1404 CFStringGetCString (path, filename,
1405 CFStringGetLength (path) * 3 + 1,
1406 kCFStringEncodingUTF8);
1409 CFRelease (path);
1412 CFRelease (url);
1416 return filename;
1419 static void
1420 load_user_special_dirs (void)
1422 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
1423 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
1424 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
1425 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
1426 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
1427 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
1428 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
1429 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
1432 #elif defined(G_OS_WIN32)
1434 static void
1435 load_user_special_dirs (void)
1437 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1438 DWORD dwFlags,
1439 HANDLE hToken,
1440 PWSTR *ppszPath);
1441 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
1443 static const GUID FOLDERID_Downloads =
1444 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1445 static const GUID FOLDERID_Public =
1446 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1448 wchar_t *wcp;
1450 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
1451 "SHGetKnownFolderPath");
1453 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1454 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
1456 if (p_SHGetKnownFolderPath == NULL)
1458 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1460 else
1462 wcp = NULL;
1463 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1464 if (wcp)
1466 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1467 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
1468 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1469 CoTaskMemFree (wcp);
1471 else
1472 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1475 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
1476 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
1478 if (p_SHGetKnownFolderPath == NULL)
1480 /* XXX */
1481 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1483 else
1485 wcp = NULL;
1486 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
1487 if (wcp)
1489 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1490 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
1491 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1492 CoTaskMemFree (wcp);
1494 else
1495 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1498 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
1499 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
1502 #else /* default is unix */
1504 /* adapted from xdg-user-dir-lookup.c
1506 * Copyright (C) 2007 Red Hat Inc.
1508 * Permission is hereby granted, free of charge, to any person
1509 * obtaining a copy of this software and associated documentation files
1510 * (the "Software"), to deal in the Software without restriction,
1511 * including without limitation the rights to use, copy, modify, merge,
1512 * publish, distribute, sublicense, and/or sell copies of the Software,
1513 * and to permit persons to whom the Software is furnished to do so,
1514 * subject to the following conditions:
1516 * The above copyright notice and this permission notice shall be
1517 * included in all copies or substantial portions of the Software.
1519 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1520 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1521 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1522 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1523 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1524 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1525 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1526 * SOFTWARE.
1528 static void
1529 load_user_special_dirs (void)
1531 gchar *config_file;
1532 gchar *data;
1533 gchar **lines;
1534 gint n_lines, i;
1536 g_init_user_config_dir ();
1537 config_file = g_build_filename (g_user_config_dir,
1538 "user-dirs.dirs",
1539 NULL);
1541 if (!g_file_get_contents (config_file, &data, NULL, NULL))
1543 g_free (config_file);
1544 return;
1547 lines = g_strsplit (data, "\n", -1);
1548 n_lines = g_strv_length (lines);
1549 g_free (data);
1551 for (i = 0; i < n_lines; i++)
1553 gchar *buffer = lines[i];
1554 gchar *d, *p;
1555 gint len;
1556 gboolean is_relative = FALSE;
1557 GUserDirectory directory;
1559 /* Remove newline at end */
1560 len = strlen (buffer);
1561 if (len > 0 && buffer[len - 1] == '\n')
1562 buffer[len - 1] = 0;
1564 p = buffer;
1565 while (*p == ' ' || *p == '\t')
1566 p++;
1568 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
1570 directory = G_USER_DIRECTORY_DESKTOP;
1571 p += strlen ("XDG_DESKTOP_DIR");
1573 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
1575 directory = G_USER_DIRECTORY_DOCUMENTS;
1576 p += strlen ("XDG_DOCUMENTS_DIR");
1578 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
1580 directory = G_USER_DIRECTORY_DOWNLOAD;
1581 p += strlen ("XDG_DOWNLOAD_DIR");
1583 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
1585 directory = G_USER_DIRECTORY_MUSIC;
1586 p += strlen ("XDG_MUSIC_DIR");
1588 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
1590 directory = G_USER_DIRECTORY_PICTURES;
1591 p += strlen ("XDG_PICTURES_DIR");
1593 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
1595 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
1596 p += strlen ("XDG_PUBLICSHARE_DIR");
1598 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
1600 directory = G_USER_DIRECTORY_TEMPLATES;
1601 p += strlen ("XDG_TEMPLATES_DIR");
1603 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
1605 directory = G_USER_DIRECTORY_VIDEOS;
1606 p += strlen ("XDG_VIDEOS_DIR");
1608 else
1609 continue;
1611 while (*p == ' ' || *p == '\t')
1612 p++;
1614 if (*p != '=')
1615 continue;
1616 p++;
1618 while (*p == ' ' || *p == '\t')
1619 p++;
1621 if (*p != '"')
1622 continue;
1623 p++;
1625 if (strncmp (p, "$HOME", 5) == 0)
1627 p += 5;
1628 is_relative = TRUE;
1630 else if (*p != '/')
1631 continue;
1633 d = strrchr (p, '"');
1634 if (!d)
1635 continue;
1636 *d = 0;
1638 d = p;
1640 /* remove trailing slashes */
1641 len = strlen (d);
1642 if (d[len - 1] == '/')
1643 d[len - 1] = 0;
1645 if (is_relative)
1647 g_user_special_dirs[directory] = g_build_filename (g_get_home_dir (), d, NULL);
1649 else
1650 g_user_special_dirs[directory] = g_strdup (d);
1653 g_strfreev (lines);
1654 g_free (config_file);
1657 #endif /* platform-specific load_user_special_dirs implementations */
1661 * g_reload_user_special_dirs_cache:
1663 * Resets the cache used for g_get_user_special_dir(), so
1664 * that the latest on-disk version is used. Call this only
1665 * if you just changed the data on disk yourself.
1667 * Due to threadsafety issues this may cause leaking of strings
1668 * that were previously returned from g_get_user_special_dir()
1669 * that can't be freed. We ensure to only leak the data for
1670 * the directories that actually changed value though.
1672 * Since: 2.22
1674 void
1675 g_reload_user_special_dirs_cache (void)
1677 int i;
1679 G_LOCK (g_utils_global);
1681 if (g_user_special_dirs != NULL)
1683 /* save a copy of the pointer, to check if some memory can be preserved */
1684 char **old_g_user_special_dirs = g_user_special_dirs;
1685 char *old_val;
1687 /* recreate and reload our cache */
1688 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1689 load_user_special_dirs ();
1691 /* only leak changed directories */
1692 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
1694 old_val = old_g_user_special_dirs[i];
1695 if (g_user_special_dirs[i] == NULL)
1697 g_user_special_dirs[i] = old_val;
1699 else if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
1701 /* don't leak */
1702 g_free (g_user_special_dirs[i]);
1703 g_user_special_dirs[i] = old_val;
1705 else
1706 g_free (old_val);
1709 /* free the old array */
1710 g_free (old_g_user_special_dirs);
1713 G_UNLOCK (g_utils_global);
1717 * g_get_user_special_dir:
1718 * @directory: the logical id of special directory
1720 * Returns the full path of a special directory using its logical id.
1722 * On UNIX this is done using the XDG special user directories.
1723 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
1724 * falls back to `$HOME/Desktop` when XDG special user directories have
1725 * not been set up.
1727 * Depending on the platform, the user might be able to change the path
1728 * of the special directory without requiring the session to restart; GLib
1729 * will not reflect any change once the special directories are loaded.
1731 * Returns: (type filename): the path to the specified special directory, or
1732 * %NULL if the logical id was not found. The returned string is owned by
1733 * GLib and should not be modified or freed.
1735 * Since: 2.14
1737 const gchar *
1738 g_get_user_special_dir (GUserDirectory directory)
1740 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
1741 directory < G_USER_N_DIRECTORIES, NULL);
1743 G_LOCK (g_utils_global);
1745 if (G_UNLIKELY (g_user_special_dirs == NULL))
1747 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1749 load_user_special_dirs ();
1751 /* Special-case desktop for historical compatibility */
1752 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
1753 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = g_build_filename (g_get_home_dir (), "Desktop", NULL);
1756 G_UNLOCK (g_utils_global);
1758 return g_user_special_dirs[directory];
1761 #ifdef G_OS_WIN32
1763 #undef g_get_system_data_dirs
1765 static HMODULE
1766 get_module_for_address (gconstpointer address)
1768 /* Holds the g_utils_global lock */
1770 static gboolean beenhere = FALSE;
1771 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
1772 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
1773 HMODULE hmodule = NULL;
1775 if (!address)
1776 return NULL;
1778 if (!beenhere)
1780 p_GetModuleHandleExA =
1781 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1782 "GetModuleHandleExA");
1783 beenhere = TRUE;
1786 if (p_GetModuleHandleExA == NULL ||
1787 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
1788 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
1789 address, &hmodule))
1791 MEMORY_BASIC_INFORMATION mbi;
1792 VirtualQuery (address, &mbi, sizeof (mbi));
1793 hmodule = (HMODULE) mbi.AllocationBase;
1796 return hmodule;
1799 static gchar *
1800 get_module_share_dir (gconstpointer address)
1802 HMODULE hmodule;
1803 gchar *filename;
1804 gchar *retval;
1806 hmodule = get_module_for_address (address);
1807 if (hmodule == NULL)
1808 return NULL;
1810 filename = g_win32_get_package_installation_directory_of_module (hmodule);
1811 retval = g_build_filename (filename, "share", NULL);
1812 g_free (filename);
1814 return retval;
1817 const gchar * const *
1818 g_win32_get_system_data_dirs_for_module (void (*address_of_function)(void))
1820 GArray *data_dirs;
1821 HMODULE hmodule;
1822 static GHashTable *per_module_data_dirs = NULL;
1823 gchar **retval;
1824 gchar *p;
1825 gchar *exe_root;
1827 hmodule = NULL;
1828 if (address_of_function)
1830 G_LOCK (g_utils_global);
1831 hmodule = get_module_for_address (address_of_function);
1832 if (hmodule != NULL)
1834 if (per_module_data_dirs == NULL)
1835 per_module_data_dirs = g_hash_table_new (NULL, NULL);
1836 else
1838 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
1840 if (retval != NULL)
1842 G_UNLOCK (g_utils_global);
1843 return (const gchar * const *) retval;
1849 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
1851 /* Documents and Settings\All Users\Application Data */
1852 p = get_special_folder (CSIDL_COMMON_APPDATA);
1853 if (p)
1854 g_array_append_val (data_dirs, p);
1856 /* Documents and Settings\All Users\Documents */
1857 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1858 if (p)
1859 g_array_append_val (data_dirs, p);
1861 /* Using the above subfolders of Documents and Settings perhaps
1862 * makes sense from a Windows perspective.
1864 * But looking at the actual use cases of this function in GTK+
1865 * and GNOME software, what we really want is the "share"
1866 * subdirectory of the installation directory for the package
1867 * our caller is a part of.
1869 * The address_of_function parameter, if non-NULL, points to a
1870 * function in the calling module. Use that to determine that
1871 * module's installation folder, and use its "share" subfolder.
1873 * Additionally, also use the "share" subfolder of the installation
1874 * locations of GLib and the .exe file being run.
1876 * To guard against none of the above being what is really wanted,
1877 * callers of this function should have Win32-specific code to look
1878 * up their installation folder themselves, and handle a subfolder
1879 * "share" of it in the same way as the folders returned from this
1880 * function.
1883 p = get_module_share_dir (address_of_function);
1884 if (p)
1885 g_array_append_val (data_dirs, p);
1887 if (glib_dll != NULL)
1889 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
1890 p = g_build_filename (glib_root, "share", NULL);
1891 if (p)
1892 g_array_append_val (data_dirs, p);
1893 g_free (glib_root);
1896 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
1897 p = g_build_filename (exe_root, "share", NULL);
1898 if (p)
1899 g_array_append_val (data_dirs, p);
1900 g_free (exe_root);
1902 retval = (gchar **) g_array_free (data_dirs, FALSE);
1904 if (address_of_function)
1906 if (hmodule != NULL)
1907 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
1908 G_UNLOCK (g_utils_global);
1911 return (const gchar * const *) retval;
1914 #endif
1917 * g_get_system_data_dirs:
1919 * Returns an ordered list of base directories in which to access
1920 * system-wide application data.
1922 * On UNIX platforms this is determined using the mechanisms described
1923 * in the
1924 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec)
1925 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
1927 * On Windows the first elements in the list are the Application Data
1928 * and Documents folders for All Users. (These can be determined only
1929 * on Windows 2000 or later and are not present in the list on other
1930 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
1931 * CSIDL_COMMON_DOCUMENTS.
1933 * Then follows the "share" subfolder in the installation folder for
1934 * the package containing the DLL that calls this function, if it can
1935 * be determined.
1937 * Finally the list contains the "share" subfolder in the installation
1938 * folder for GLib, and in the installation folder for the package the
1939 * application's .exe file belongs to.
1941 * The installation folders above are determined by looking up the
1942 * folder where the module (DLL or EXE) in question is located. If the
1943 * folder's name is "bin", its parent is used, otherwise the folder
1944 * itself.
1946 * Note that on Windows the returned list can vary depending on where
1947 * this function is called.
1949 * Returns: (array zero-terminated=1) (element-type filename) (transfer none):
1950 * a %NULL-terminated array of strings owned by GLib that must not be
1951 * modified or freed.
1953 * Since: 2.6
1955 const gchar * const *
1956 g_get_system_data_dirs (void)
1958 gchar **data_dir_vector;
1960 G_LOCK (g_utils_global);
1962 if (!g_system_data_dirs)
1964 #ifdef G_OS_WIN32
1965 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
1966 #else
1967 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
1969 if (!data_dirs || !data_dirs[0])
1970 data_dirs = "/usr/local/share/:/usr/share/";
1972 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1973 #endif
1975 g_system_data_dirs = data_dir_vector;
1977 else
1978 data_dir_vector = g_system_data_dirs;
1980 G_UNLOCK (g_utils_global);
1982 return (const gchar * const *) data_dir_vector;
1986 * g_get_system_config_dirs:
1988 * Returns an ordered list of base directories in which to access
1989 * system-wide configuration information.
1991 * On UNIX platforms this is determined using the mechanisms described
1992 * in the
1993 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1994 * In this case the list of directories retrieved will be `XDG_CONFIG_DIRS`.
1996 * On Windows is the directory that contains application data for all users.
1997 * A typical path is C:\Documents and Settings\All Users\Application Data.
1998 * This folder is used for application data that is not user specific.
1999 * For example, an application can store a spell-check dictionary, a database
2000 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2001 * This information will not roam and is available to anyone using the computer.
2003 * Returns: (array zero-terminated=1) (element-type filename) (transfer none):
2004 * a %NULL-terminated array of strings owned by GLib that must not be
2005 * modified or freed.
2007 * Since: 2.6
2009 const gchar * const *
2010 g_get_system_config_dirs (void)
2012 gchar *conf_dirs, **conf_dir_vector;
2014 G_LOCK (g_utils_global);
2016 if (!g_system_config_dirs)
2018 #ifdef G_OS_WIN32
2019 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2020 if (conf_dirs)
2022 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2023 g_free (conf_dirs);
2025 else
2027 /* Return empty list */
2028 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2030 #else
2031 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2033 if (!conf_dirs || !conf_dirs[0])
2034 conf_dirs = "/etc/xdg";
2036 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2037 #endif
2039 g_system_config_dirs = conf_dir_vector;
2041 else
2042 conf_dir_vector = g_system_config_dirs;
2043 G_UNLOCK (g_utils_global);
2045 return (const gchar * const *) conf_dir_vector;
2049 * g_nullify_pointer:
2050 * @nullify_location: (not nullable): the memory address of the pointer.
2052 * Set the pointer at the specified location to %NULL.
2054 void
2055 g_nullify_pointer (gpointer *nullify_location)
2057 g_return_if_fail (nullify_location != NULL);
2059 *nullify_location = NULL;
2062 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2063 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2064 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2065 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2066 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2067 #define EXABYTE_FACTOR (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2069 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2070 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2071 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2072 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2073 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2074 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2077 * g_format_size:
2078 * @size: a size in bytes
2080 * Formats a size (for example the size of a file) into a human readable
2081 * string. Sizes are rounded to the nearest size prefix (kB, MB, GB)
2082 * and are displayed rounded to the nearest tenth. E.g. the file size
2083 * 3292528 bytes will be converted into the string "3.2 MB".
2085 * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2087 * This string should be freed with g_free() when not needed any longer.
2089 * See g_format_size_full() for more options about how the size might be
2090 * formatted.
2092 * Returns: a newly-allocated formatted string containing a human readable
2093 * file size
2095 * Since: 2.30
2097 gchar *
2098 g_format_size (guint64 size)
2100 return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2104 * GFormatSizeFlags:
2105 * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2106 * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2107 * of the returned string. For example, "45.6 kB (45,612 bytes)".
2108 * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2109 * suffixes. IEC units should only be used for reporting things with
2110 * a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2111 * Network and storage sizes should be reported in the normal SI units.
2113 * Flags to modify the format of the string returned by g_format_size_full().
2116 #pragma GCC diagnostic push
2117 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
2120 * g_format_size_full:
2121 * @size: a size in bytes
2122 * @flags: #GFormatSizeFlags to modify the output
2124 * Formats a size.
2126 * This function is similar to g_format_size() but allows for flags
2127 * that modify the output. See #GFormatSizeFlags.
2129 * Returns: a newly-allocated formatted string containing a human
2130 * readable file size
2132 * Since: 2.30
2134 gchar *
2135 g_format_size_full (guint64 size,
2136 GFormatSizeFlags flags)
2138 GString *string;
2140 string = g_string_new (NULL);
2142 if (flags & G_FORMAT_SIZE_IEC_UNITS)
2144 if (size < KIBIBYTE_FACTOR)
2146 g_string_printf (string,
2147 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2148 (guint) size);
2149 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2152 else if (size < MEBIBYTE_FACTOR)
2153 g_string_printf (string, _("%.1f KiB"), (gdouble) size / (gdouble) KIBIBYTE_FACTOR);
2154 else if (size < GIBIBYTE_FACTOR)
2155 g_string_printf (string, _("%.1f MiB"), (gdouble) size / (gdouble) MEBIBYTE_FACTOR);
2157 else if (size < TEBIBYTE_FACTOR)
2158 g_string_printf (string, _("%.1f GiB"), (gdouble) size / (gdouble) GIBIBYTE_FACTOR);
2160 else if (size < PEBIBYTE_FACTOR)
2161 g_string_printf (string, _("%.1f TiB"), (gdouble) size / (gdouble) TEBIBYTE_FACTOR);
2163 else if (size < EXBIBYTE_FACTOR)
2164 g_string_printf (string, _("%.1f PiB"), (gdouble) size / (gdouble) PEBIBYTE_FACTOR);
2166 else
2167 g_string_printf (string, _("%.1f EiB"), (gdouble) size / (gdouble) EXBIBYTE_FACTOR);
2169 else
2171 if (size < KILOBYTE_FACTOR)
2173 g_string_printf (string,
2174 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2175 (guint) size);
2176 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2179 else if (size < MEGABYTE_FACTOR)
2180 g_string_printf (string, _("%.1f kB"), (gdouble) size / (gdouble) KILOBYTE_FACTOR);
2182 else if (size < GIGABYTE_FACTOR)
2183 g_string_printf (string, _("%.1f MB"), (gdouble) size / (gdouble) MEGABYTE_FACTOR);
2185 else if (size < TERABYTE_FACTOR)
2186 g_string_printf (string, _("%.1f GB"), (gdouble) size / (gdouble) GIGABYTE_FACTOR);
2187 else if (size < PETABYTE_FACTOR)
2188 g_string_printf (string, _("%.1f TB"), (gdouble) size / (gdouble) TERABYTE_FACTOR);
2190 else if (size < EXABYTE_FACTOR)
2191 g_string_printf (string, _("%.1f PB"), (gdouble) size / (gdouble) PETABYTE_FACTOR);
2193 else
2194 g_string_printf (string, _("%.1f EB"), (gdouble) size / (gdouble) EXABYTE_FACTOR);
2197 if (flags & G_FORMAT_SIZE_LONG_FORMAT)
2199 /* First problem: we need to use the number of bytes to decide on
2200 * the plural form that is used for display, but the number of
2201 * bytes potentially exceeds the size of a guint (which is what
2202 * ngettext() takes).
2204 * From a pragmatic standpoint, it seems that all known languages
2205 * base plural forms on one or both of the following:
2207 * - the lowest digits of the number
2209 * - if the number if greater than some small value
2211 * Here's how we fake it: Draw an arbitrary line at one thousand.
2212 * If the number is below that, then fine. If it is above it,
2213 * then we take the modulus of the number by one thousand (in
2214 * order to keep the lowest digits) and add one thousand to that
2215 * (in order to ensure that 1001 is not treated the same as 1).
2217 guint plural_form = size < 1000 ? size : size % 1000 + 1000;
2219 /* Second problem: we need to translate the string "%u byte" and
2220 * "%u bytes" for pluralisation, but the correct number format to
2221 * use for a gsize is different depending on which architecture
2222 * we're on.
2224 * Solution: format the number separately and use "%s bytes" on
2225 * all platforms.
2227 const gchar *translated_format;
2228 gchar *formatted_number;
2230 /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2231 translated_format = g_dngettext(GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
2232 /* XXX: Windows doesn't support the "'" format modifier, so we
2233 * must not use it there. Instead, just display the number
2234 * without separation. Bug #655336 is open until a solution is
2235 * found.
2237 #ifndef G_OS_WIN32
2238 formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2239 #else
2240 formatted_number = g_strdup_printf ("%"G_GUINT64_FORMAT, size);
2241 #endif
2243 g_string_append (string, " (");
2244 g_string_append_printf (string, translated_format, formatted_number);
2245 g_free (formatted_number);
2246 g_string_append (string, ")");
2249 return g_string_free (string, FALSE);
2252 #pragma GCC diagnostic pop
2255 * g_format_size_for_display:
2256 * @size: a size in bytes
2258 * Formats a size (for example the size of a file) into a human
2259 * readable string. Sizes are rounded to the nearest size prefix
2260 * (KB, MB, GB) and are displayed rounded to the nearest tenth.
2261 * E.g. the file size 3292528 bytes will be converted into the
2262 * string "3.1 MB".
2264 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2266 * This string should be freed with g_free() when not needed any longer.
2268 * Returns: a newly-allocated formatted string containing a human
2269 * readable file size
2271 * Since: 2.16
2273 * Deprecated:2.30: This function is broken due to its use of SI
2274 * suffixes to denote IEC units. Use g_format_size() instead.
2276 gchar *
2277 g_format_size_for_display (goffset size)
2279 if (size < (goffset) KIBIBYTE_FACTOR)
2280 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
2281 else
2283 gdouble displayed_size;
2285 if (size < (goffset) MEBIBYTE_FACTOR)
2287 displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
2288 /* Translators: this is from the deprecated function g_format_size_for_display() which uses 'KB' to
2289 * mean 1024 bytes. I am aware that 'KB' is not correct, but it has been preserved for reasons of
2290 * compatibility. Users will not see this string unless a program is using this deprecated function.
2291 * Please translate as literally as possible.
2293 return g_strdup_printf (_("%.1f KB"), displayed_size);
2295 else if (size < (goffset) GIBIBYTE_FACTOR)
2297 displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
2298 return g_strdup_printf (_("%.1f MB"), displayed_size);
2300 else if (size < (goffset) TEBIBYTE_FACTOR)
2302 displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
2303 return g_strdup_printf (_("%.1f GB"), displayed_size);
2305 else if (size < (goffset) PEBIBYTE_FACTOR)
2307 displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
2308 return g_strdup_printf (_("%.1f TB"), displayed_size);
2310 else if (size < (goffset) EXBIBYTE_FACTOR)
2312 displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
2313 return g_strdup_printf (_("%.1f PB"), displayed_size);
2315 else
2317 displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
2318 return g_strdup_printf (_("%.1f EB"), displayed_size);
2323 #if defined (G_OS_WIN32) && !defined (_WIN64)
2325 /* Binary compatibility versions. Not for newly compiled code. */
2327 _GLIB_EXTERN const gchar *g_get_user_name_utf8 (void);
2328 _GLIB_EXTERN const gchar *g_get_real_name_utf8 (void);
2329 _GLIB_EXTERN const gchar *g_get_home_dir_utf8 (void);
2330 _GLIB_EXTERN const gchar *g_get_tmp_dir_utf8 (void);
2331 _GLIB_EXTERN gchar *g_find_program_in_path_utf8 (const gchar *program);
2333 gchar *
2334 g_find_program_in_path_utf8 (const gchar *program)
2336 return g_find_program_in_path (program);
2339 const gchar *g_get_user_name_utf8 (void) { return g_get_user_name (); }
2340 const gchar *g_get_real_name_utf8 (void) { return g_get_real_name (); }
2341 const gchar *g_get_home_dir_utf8 (void) { return g_get_home_dir (); }
2342 const gchar *g_get_tmp_dir_utf8 (void) { return g_get_tmp_dir (); }
2344 #endif
2346 /* Private API:
2348 * Returns %TRUE if the current process was executed as setuid (or an
2349 * equivalent __libc_enable_secure is available). See:
2350 * http://osdir.com/ml/linux.lfs.hardened/2007-04/msg00032.html
2352 gboolean
2353 g_check_setuid (void)
2355 /* TODO: get __libc_enable_secure exported from glibc.
2356 * See http://www.openwall.com/lists/owl-dev/2012/08/14/1
2358 #if 0 && defined(HAVE_LIBC_ENABLE_SECURE)
2360 /* See glibc/include/unistd.h */
2361 extern int __libc_enable_secure;
2362 return __libc_enable_secure;
2364 #elif defined(HAVE_ISSETUGID) && !defined(__BIONIC__)
2365 /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
2367 /* Android had it in older versions but the new 64 bit ABI does not
2368 * have it anymore, and some versions of the 32 bit ABI neither.
2369 * https://code.google.com/p/android-developer-preview/issues/detail?id=168
2371 return issetugid ();
2372 #elif defined(G_OS_UNIX)
2373 uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
2374 gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
2376 static gsize check_setuid_initialised;
2377 static gboolean is_setuid;
2379 if (g_once_init_enter (&check_setuid_initialised))
2381 #ifdef HAVE_GETRESUID
2382 /* These aren't in the header files, so we prototype them here.
2384 int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
2385 int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);
2387 if (getresuid (&ruid, &euid, &suid) != 0 ||
2388 getresgid (&rgid, &egid, &sgid) != 0)
2389 #endif /* HAVE_GETRESUID */
2391 suid = ruid = getuid ();
2392 sgid = rgid = getgid ();
2393 euid = geteuid ();
2394 egid = getegid ();
2397 is_setuid = (ruid != euid || ruid != suid ||
2398 rgid != egid || rgid != sgid);
2400 g_once_init_leave (&check_setuid_initialised, 1);
2402 return is_setuid;
2403 #else
2404 return FALSE;
2405 #endif
2408 #ifdef G_OS_WIN32
2410 * g_abort:
2412 * A wrapper for the POSIX abort() function.
2414 * On Windows it is a function that makes extra effort (including a call
2415 * to abort()) to ensure that a debugger-catchable exception is thrown
2416 * before the program terminates.
2418 * See your C library manual for more details about abort().
2420 * Since: 2.50
2422 void
2423 g_abort (void)
2425 /* One call to break the debugger */
2426 DebugBreak ();
2427 /* One call in case CRT does get saner about abort() behaviour */
2428 abort ();
2429 /* And one call to bind them all and terminate the program for sure */
2430 ExitProcess (127);
2432 #endif