Merge branch '1175-source-names' into 'master'
[glib.git] / glib / gutils.c
blob2b750aba90cca3133542160310a3b0c785fbbca2
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
53 #ifdef HAVE_SYS_AUXV_H
54 #include <sys/auxv.h>
55 #endif
57 #include "glib-init.h"
58 #include "glib-private.h"
59 #include "genviron.h"
60 #include "gfileutils.h"
61 #include "ggettext.h"
62 #include "ghash.h"
63 #include "gthread.h"
64 #include "gtestutils.h"
65 #include "gunicode.h"
66 #include "gstrfuncs.h"
67 #include "garray.h"
68 #include "glibintl.h"
69 #include "gstdio.h"
71 #ifdef G_PLATFORM_WIN32
72 #include "gconvert.h"
73 #include "gwin32.h"
74 #endif
77 /**
78 * SECTION:misc_utils
79 * @title: Miscellaneous Utility Functions
80 * @short_description: a selection of portable utility functions
82 * These are portable utility functions.
85 #ifdef G_PLATFORM_WIN32
86 # include <windows.h>
87 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
88 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
89 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
90 # endif
91 # include <lmcons.h> /* For UNLEN */
92 #endif /* G_PLATFORM_WIN32 */
94 #ifdef G_OS_WIN32
95 # include <direct.h>
96 # include <shlobj.h>
97 /* older SDK (e.g. msvc 5.0) does not have these*/
98 # ifndef CSIDL_MYMUSIC
99 # define CSIDL_MYMUSIC 13
100 # endif
101 # ifndef CSIDL_MYVIDEO
102 # define CSIDL_MYVIDEO 14
103 # endif
104 # ifndef CSIDL_INTERNET_CACHE
105 # define CSIDL_INTERNET_CACHE 32
106 # endif
107 # ifndef CSIDL_COMMON_APPDATA
108 # define CSIDL_COMMON_APPDATA 35
109 # endif
110 # ifndef CSIDL_MYPICTURES
111 # define CSIDL_MYPICTURES 0x27
112 # endif
113 # ifndef CSIDL_COMMON_DOCUMENTS
114 # define CSIDL_COMMON_DOCUMENTS 46
115 # endif
116 # ifndef CSIDL_PROFILE
117 # define CSIDL_PROFILE 40
118 # endif
119 # include <process.h>
120 #endif
122 #ifdef HAVE_CARBON
123 #include <CoreServices/CoreServices.h>
124 #endif
126 #ifdef HAVE_CODESET
127 #include <langinfo.h>
128 #endif
130 #ifdef G_PLATFORM_WIN32
132 gchar *
133 _glib_get_dll_directory (void)
135 gchar *retval;
136 gchar *p;
137 wchar_t wc_fn[MAX_PATH];
139 #ifdef DLL_EXPORT
140 if (glib_dll == NULL)
141 return NULL;
142 #endif
144 /* This code is different from that in
145 * g_win32_get_package_installation_directory_of_module() in that
146 * here we return the actual folder where the GLib DLL is. We don't
147 * do the check for it being in a "bin" or "lib" subfolder and then
148 * returning the parent of that.
150 * In a statically built GLib, glib_dll will be NULL and we will
151 * thus look up the application's .exe file's location.
153 if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
154 return NULL;
156 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
158 p = strrchr (retval, G_DIR_SEPARATOR);
159 if (p == NULL)
161 /* Wtf? */
162 return NULL;
164 *p = '\0';
166 return retval;
169 #endif
172 * g_memmove:
173 * @dest: the destination address to copy the bytes to.
174 * @src: the source address to copy the bytes from.
175 * @len: the number of bytes to copy.
177 * Copies a block of memory @len bytes long, from @src to @dest.
178 * The source and destination areas may overlap.
180 * Deprecated:2.40: Just use memmove().
183 #ifdef G_OS_WIN32
184 #undef g_atexit
185 #endif
188 * g_atexit:
189 * @func: (scope async): the function to call on normal program termination.
191 * Specifies a function to be called at normal program termination.
193 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
194 * macro that maps to a call to the atexit() function in the C
195 * library. This means that in case the code that calls g_atexit(),
196 * i.e. atexit(), is in a DLL, the function will be called when the
197 * DLL is detached from the program. This typically makes more sense
198 * than that the function is called when the GLib DLL is detached,
199 * which happened earlier when g_atexit() was a function in the GLib
200 * DLL.
202 * The behaviour of atexit() in the context of dynamically loaded
203 * modules is not formally specified and varies wildly.
205 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
206 * loaded module which is unloaded before the program terminates might
207 * well cause a crash at program exit.
209 * Some POSIX systems implement atexit() like Windows, and have each
210 * dynamically loaded module maintain an own atexit chain that is
211 * called when the module is unloaded.
213 * On other POSIX systems, before a dynamically loaded module is
214 * unloaded, the registered atexit functions (if any) residing in that
215 * module are called, regardless where the code that registered them
216 * resided. This is presumably the most robust approach.
218 * As can be seen from the above, for portability it's best to avoid
219 * calling g_atexit() (or atexit()) except in the main executable of a
220 * program.
222 * Deprecated:2.32: It is best to avoid g_atexit().
224 void
225 g_atexit (GVoidFunc func)
227 gint result;
228 int errsv;
230 result = atexit ((void (*)(void)) func);
231 errsv = errno;
232 if (result)
234 g_error ("Could not register atexit() function: %s",
235 g_strerror (errsv));
239 /* Based on execvp() from GNU Libc.
240 * Some of this code is cut-and-pasted into gspawn.c
243 static gchar*
244 my_strchrnul (const gchar *str,
245 gchar c)
247 gchar *p = (gchar*)str;
248 while (*p && (*p != c))
249 ++p;
251 return p;
254 #ifdef G_OS_WIN32
256 static gchar *inner_find_program_in_path (const gchar *program);
258 gchar*
259 g_find_program_in_path (const gchar *program)
261 const gchar *last_dot = strrchr (program, '.');
263 if (last_dot == NULL ||
264 strchr (last_dot, '\\') != NULL ||
265 strchr (last_dot, '/') != NULL)
267 const gint program_length = strlen (program);
268 gchar *pathext = g_build_path (";",
269 ".exe;.cmd;.bat;.com",
270 g_getenv ("PATHEXT"),
271 NULL);
272 gchar *p;
273 gchar *decorated_program;
274 gchar *retval;
276 p = pathext;
279 gchar *q = my_strchrnul (p, ';');
281 decorated_program = g_malloc (program_length + (q-p) + 1);
282 memcpy (decorated_program, program, program_length);
283 memcpy (decorated_program+program_length, p, q-p);
284 decorated_program [program_length + (q-p)] = '\0';
286 retval = inner_find_program_in_path (decorated_program);
287 g_free (decorated_program);
289 if (retval != NULL)
291 g_free (pathext);
292 return retval;
294 p = q;
295 } while (*p++ != '\0');
296 g_free (pathext);
297 return NULL;
299 else
300 return inner_find_program_in_path (program);
303 #endif
306 * g_find_program_in_path:
307 * @program: (type filename): a program name in the GLib file name encoding
309 * Locates the first executable named @program in the user's path, in the
310 * same way that execvp() would locate it. Returns an allocated string
311 * with the absolute path name, or %NULL if the program is not found in
312 * the path. If @program is already an absolute path, returns a copy of
313 * @program if @program exists and is executable, and %NULL otherwise.
315 * On Windows, if @program does not have a file type suffix, tries
316 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
317 * the `PATHEXT` environment variable.
319 * On Windows, it looks for the file in the same way as CreateProcess()
320 * would. This means first in the directory where the executing
321 * program was loaded from, then in the current directory, then in the
322 * Windows 32-bit system directory, then in the Windows directory, and
323 * finally in the directories in the `PATH` environment variable. If
324 * the program is found, the return value contains the full name
325 * including the type suffix.
327 * Returns: (type filename): a newly-allocated string with the absolute path,
328 * or %NULL
330 #ifdef G_OS_WIN32
331 static gchar *
332 inner_find_program_in_path (const gchar *program)
333 #else
334 gchar*
335 g_find_program_in_path (const gchar *program)
336 #endif
338 const gchar *path, *p;
339 gchar *name, *freeme;
340 #ifdef G_OS_WIN32
341 const gchar *path_copy;
342 gchar *filename = NULL, *appdir = NULL;
343 gchar *sysdir = NULL, *windir = NULL;
344 int n;
345 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
346 wwindir[MAXPATHLEN];
347 #endif
348 gsize len;
349 gsize pathlen;
351 g_return_val_if_fail (program != NULL, NULL);
353 /* If it is an absolute path, or a relative path including subdirectories,
354 * don't look in PATH.
356 if (g_path_is_absolute (program)
357 || strchr (program, G_DIR_SEPARATOR) != NULL
358 #ifdef G_OS_WIN32
359 || strchr (program, '/') != NULL
360 #endif
363 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
364 !g_file_test (program, G_FILE_TEST_IS_DIR))
365 return g_strdup (program);
366 else
367 return NULL;
370 path = g_getenv ("PATH");
371 #if defined(G_OS_UNIX)
372 if (path == NULL)
374 /* There is no 'PATH' in the environment. The default
375 * search path in GNU libc is the current directory followed by
376 * the path 'confstr' returns for '_CS_PATH'.
379 /* In GLib we put . last, for security, and don't use the
380 * unportable confstr(); UNIX98 does not actually specify
381 * what to search if PATH is unset. POSIX may, dunno.
384 path = "/bin:/usr/bin:.";
386 #else
387 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
388 if (n > 0 && n < MAXPATHLEN)
389 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
391 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
392 if (n > 0 && n < MAXPATHLEN)
393 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
395 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
396 if (n > 0 && n < MAXPATHLEN)
397 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
399 if (filename)
401 appdir = g_path_get_dirname (filename);
402 g_free (filename);
405 path = g_strdup (path);
407 if (windir)
409 const gchar *tem = path;
410 path = g_strconcat (windir, ";", path, NULL);
411 g_free ((gchar *) tem);
412 g_free (windir);
415 if (sysdir)
417 const gchar *tem = path;
418 path = g_strconcat (sysdir, ";", path, NULL);
419 g_free ((gchar *) tem);
420 g_free (sysdir);
424 const gchar *tem = path;
425 path = g_strconcat (".;", path, NULL);
426 g_free ((gchar *) tem);
429 if (appdir)
431 const gchar *tem = path;
432 path = g_strconcat (appdir, ";", path, NULL);
433 g_free ((gchar *) tem);
434 g_free (appdir);
437 path_copy = path;
438 #endif
440 len = strlen (program) + 1;
441 pathlen = strlen (path);
442 freeme = name = g_malloc (pathlen + len + 1);
444 /* Copy the file name at the top, including '\0' */
445 memcpy (name + pathlen + 1, program, len);
446 name = name + pathlen;
447 /* And add the slash before the filename */
448 *name = G_DIR_SEPARATOR;
450 p = path;
453 char *startp;
455 path = p;
456 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
458 if (p == path)
459 /* Two adjacent colons, or a colon at the beginning or the end
460 * of 'PATH' means to search the current directory.
462 startp = name + 1;
463 else
464 startp = memcpy (name - (p - path), path, p - path);
466 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
467 !g_file_test (startp, G_FILE_TEST_IS_DIR))
469 gchar *ret;
470 ret = g_strdup (startp);
471 g_free (freeme);
472 #ifdef G_OS_WIN32
473 g_free ((gchar *) path_copy);
474 #endif
475 return ret;
478 while (*p++ != '\0');
480 g_free (freeme);
481 #ifdef G_OS_WIN32
482 g_free ((gchar *) path_copy);
483 #endif
485 return NULL;
488 /* The functions below are defined this way for compatibility reasons.
489 * See the note in gutils.h.
493 * g_bit_nth_lsf:
494 * @mask: a #gulong containing flags
495 * @nth_bit: the index of the bit to start the search from
497 * Find the position of the first bit set in @mask, searching
498 * from (but not including) @nth_bit upwards. Bits are numbered
499 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
500 * usually). To start searching from the 0th bit, set @nth_bit to -1.
502 * Returns: the index of the first bit set which is higher than @nth_bit, or -1
503 * if no higher bits are set
505 gint
506 (g_bit_nth_lsf) (gulong mask,
507 gint nth_bit)
509 return g_bit_nth_lsf_impl (mask, nth_bit);
513 * g_bit_nth_msf:
514 * @mask: a #gulong containing flags
515 * @nth_bit: the index of the bit to start the search from
517 * Find the position of the first bit set in @mask, searching
518 * from (but not including) @nth_bit downwards. Bits are numbered
519 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
520 * usually). To start searching from the last bit, set @nth_bit to
521 * -1 or GLIB_SIZEOF_LONG * 8.
523 * Returns: the index of the first bit set which is lower than @nth_bit, or -1
524 * if no lower bits are set
526 gint
527 (g_bit_nth_msf) (gulong mask,
528 gint nth_bit)
530 return g_bit_nth_msf_impl (mask, nth_bit);
535 * g_bit_storage:
536 * @number: a #guint
538 * Gets the number of bits used to hold @number,
539 * e.g. if @number is 4, 3 bits are needed.
541 * Returns: the number of bits used to hold @number
543 guint
544 (g_bit_storage) (gulong number)
546 return g_bit_storage_impl (number);
549 G_LOCK_DEFINE_STATIC (g_utils_global);
551 typedef struct
553 gchar *user_name;
554 gchar *real_name;
555 gchar *home_dir;
556 } UserDatabaseEntry;
558 static gchar *g_user_data_dir = NULL;
559 static gchar **g_system_data_dirs = NULL;
560 static gchar *g_user_cache_dir = NULL;
561 static gchar *g_user_config_dir = NULL;
562 static gchar **g_system_config_dirs = NULL;
564 static gchar **g_user_special_dirs = NULL;
566 /* fifteen minutes of fame for everybody */
567 #define G_USER_DIRS_EXPIRE 15 * 60
569 #ifdef G_OS_WIN32
571 static gchar *
572 get_special_folder (int csidl)
574 wchar_t path[MAX_PATH+1];
575 HRESULT hr;
576 LPITEMIDLIST pidl = NULL;
577 BOOL b;
578 gchar *retval = NULL;
580 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
581 if (hr == S_OK)
583 b = SHGetPathFromIDListW (pidl, path);
584 if (b)
585 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
586 CoTaskMemFree (pidl);
588 return retval;
591 static char *
592 get_windows_directory_root (void)
594 wchar_t wwindowsdir[MAX_PATH];
596 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
598 /* Usually X:\Windows, but in terminal server environments
599 * might be an UNC path, AFAIK.
601 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
602 char *p;
604 if (windowsdir == NULL)
605 return g_strdup ("C:\\");
607 p = (char *) g_path_skip_root (windowsdir);
608 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
609 p--;
610 *p = '\0';
611 return windowsdir;
613 else
614 return g_strdup ("C:\\");
617 #endif
619 /* HOLDS: g_utils_global_lock */
620 static UserDatabaseEntry *
621 g_get_user_database_entry (void)
623 static UserDatabaseEntry *entry;
625 if (g_once_init_enter (&entry))
627 static UserDatabaseEntry e;
629 #ifdef G_OS_UNIX
631 struct passwd *pw = NULL;
632 gpointer buffer = NULL;
633 gint error;
634 gchar *logname;
636 # if defined (HAVE_GETPWUID_R)
637 struct passwd pwd;
638 # ifdef _SC_GETPW_R_SIZE_MAX
639 /* This reurns the maximum length */
640 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
642 if (bufsize < 0)
643 bufsize = 64;
644 # else /* _SC_GETPW_R_SIZE_MAX */
645 glong bufsize = 64;
646 # endif /* _SC_GETPW_R_SIZE_MAX */
648 logname = (gchar *) g_getenv ("LOGNAME");
652 g_free (buffer);
653 /* we allocate 6 extra bytes to work around a bug in
654 * Mac OS < 10.3. See #156446
656 buffer = g_malloc (bufsize + 6);
657 errno = 0;
659 if (logname) {
660 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
661 if (!pw || (pw->pw_uid != getuid ())) {
662 /* LOGNAME is lying, fall back to looking up the uid */
663 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
665 } else {
666 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
668 error = error < 0 ? errno : error;
670 if (!pw)
672 /* we bail out prematurely if the user id can't be found
673 * (should be pretty rare case actually), or if the buffer
674 * should be sufficiently big and lookups are still not
675 * successful.
677 if (error == 0 || error == ENOENT)
679 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
680 (gulong) getuid ());
681 break;
683 if (bufsize > 32 * 1024)
685 g_warning ("getpwuid_r(): failed due to: %s.",
686 g_strerror (error));
687 break;
690 bufsize *= 2;
693 while (!pw);
694 # endif /* HAVE_GETPWUID_R */
696 if (!pw)
698 pw = getpwuid (getuid ());
700 if (pw)
702 e.user_name = g_strdup (pw->pw_name);
704 #ifndef __BIONIC__
705 if (pw->pw_gecos && *pw->pw_gecos != '\0')
707 gchar **gecos_fields;
708 gchar **name_parts;
710 /* split the gecos field and substitute '&' */
711 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
712 name_parts = g_strsplit (gecos_fields[0], "&", 0);
713 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
714 e.real_name = g_strjoinv (pw->pw_name, name_parts);
715 g_strfreev (gecos_fields);
716 g_strfreev (name_parts);
718 #endif
720 if (!e.home_dir)
721 e.home_dir = g_strdup (pw->pw_dir);
723 g_free (buffer);
726 #endif /* G_OS_UNIX */
728 #ifdef G_OS_WIN32
730 guint len = UNLEN+1;
731 wchar_t buffer[UNLEN+1];
733 if (GetUserNameW (buffer, (LPDWORD) &len))
735 e.user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
736 e.real_name = g_strdup (e.user_name);
739 #endif /* G_OS_WIN32 */
741 if (!e.user_name)
742 e.user_name = g_strdup ("somebody");
743 if (!e.real_name)
744 e.real_name = g_strdup ("Unknown");
746 g_once_init_leave (&entry, &e);
749 return entry;
753 * g_get_user_name:
755 * Gets the user name of the current user. The encoding of the returned
756 * string is system-defined. On UNIX, it might be the preferred file name
757 * encoding, or something else, and there is no guarantee that it is even
758 * consistent on a machine. On Windows, it is always UTF-8.
760 * Returns: (type filename): the user name of the current user.
762 const gchar *
763 g_get_user_name (void)
765 UserDatabaseEntry *entry;
767 entry = g_get_user_database_entry ();
769 return entry->user_name;
773 * g_get_real_name:
775 * Gets the real name of the user. This usually comes from the user's
776 * entry in the `passwd` file. The encoding of the returned string is
777 * system-defined. (On Windows, it is, however, always UTF-8.) If the
778 * real user name cannot be determined, the string "Unknown" is
779 * returned.
781 * Returns: (type filename): the user's real name.
783 const gchar *
784 g_get_real_name (void)
786 UserDatabaseEntry *entry;
788 entry = g_get_user_database_entry ();
790 return entry->real_name;
794 * g_get_home_dir:
796 * Gets the current user's home directory.
798 * As with most UNIX tools, this function will return the value of the
799 * `HOME` environment variable if it is set to an existing absolute path
800 * name, falling back to the `passwd` file in the case that it is unset.
802 * If the path given in `HOME` is non-absolute, does not exist, or is
803 * not a directory, the result is undefined.
805 * Before version 2.36 this function would ignore the `HOME` environment
806 * variable, taking the value from the `passwd` database instead. This was
807 * changed to increase the compatibility of GLib with other programs (and
808 * the XDG basedir specification) and to increase testability of programs
809 * based on GLib (by making it easier to run them from test frameworks).
811 * If your program has a strong requirement for either the new or the
812 * old behaviour (and if you don't wish to increase your GLib
813 * dependency to ensure that the new behaviour is in effect) then you
814 * should either directly check the `HOME` environment variable yourself
815 * or unset it before calling any functions in GLib.
817 * Returns: (type filename): the current user's home directory
819 const gchar *
820 g_get_home_dir (void)
822 static gchar *home_dir;
824 if (g_once_init_enter (&home_dir))
826 gchar *tmp;
828 /* We first check HOME and use it if it is set */
829 tmp = g_strdup (g_getenv ("HOME"));
831 #ifdef G_OS_WIN32
832 /* Only believe HOME if it is an absolute path and exists.
834 * We only do this check on Windows for a couple of reasons.
835 * Historically, we only did it there because we used to ignore $HOME
836 * on UNIX. There are concerns about enabling it now on UNIX because
837 * of things like autofs. In short, if the user has a bogus value in
838 * $HOME then they get what they pay for...
840 if (tmp)
842 if (!(g_path_is_absolute (tmp) &&
843 g_file_test (tmp, G_FILE_TEST_IS_DIR)))
845 g_free (tmp);
846 tmp = NULL;
850 /* In case HOME is Unix-style (it happens), convert it to
851 * Windows style.
853 if (tmp)
855 gchar *p;
856 while ((p = strchr (tmp, '/')) != NULL)
857 *p = '\\';
860 if (!tmp)
862 /* USERPROFILE is probably the closest equivalent to $HOME? */
863 if (g_getenv ("USERPROFILE") != NULL)
864 tmp = g_strdup (g_getenv ("USERPROFILE"));
867 if (!tmp)
868 tmp = get_special_folder (CSIDL_PROFILE);
870 if (!tmp)
871 tmp = get_windows_directory_root ();
872 #endif /* G_OS_WIN32 */
874 if (!tmp)
876 /* If we didn't get it from any of those methods, we will have
877 * to read the user database entry.
879 UserDatabaseEntry *entry;
881 entry = g_get_user_database_entry ();
883 /* Strictly speaking, we should copy this, but we know that
884 * neither will ever be freed, so don't bother...
886 tmp = entry->home_dir;
889 /* If we have been denied access to /etc/passwd (for example, by an
890 * overly-zealous LSM), make up a junk value. The return value at this
891 * point is explicitly documented as ‘undefined’. Memory management is as
892 * immediately above: strictly this should be copied, but we know not
893 * copying it is OK. */
894 if (tmp == NULL)
896 g_warning ("Could not find home directory: $HOME is not set, and "
897 "user database could not be read.");
898 tmp = "/";
901 g_once_init_leave (&home_dir, tmp);
904 return home_dir;
908 * g_get_tmp_dir:
910 * Gets the directory to use for temporary files.
912 * On UNIX, this is taken from the `TMPDIR` environment variable.
913 * If the variable is not set, `P_tmpdir` is
914 * used, as defined by the system C library. Failing that, a
915 * hard-coded default of "/tmp" is returned.
917 * On Windows, the `TEMP` environment variable is used, with the
918 * root directory of the Windows installation (eg: "C:\") used
919 * as a default.
921 * The encoding of the returned string is system-defined. On Windows,
922 * it is always UTF-8. The return value is never %NULL or the empty
923 * string.
925 * Returns: (type filename): the directory to use for temporary files.
927 const gchar *
928 g_get_tmp_dir (void)
930 static gchar *tmp_dir;
932 if (g_once_init_enter (&tmp_dir))
934 gchar *tmp;
936 #ifdef G_OS_WIN32
937 tmp = g_strdup (g_getenv ("TEMP"));
939 if (tmp == NULL || *tmp == '\0')
941 g_free (tmp);
942 tmp = get_windows_directory_root ();
944 #else /* G_OS_WIN32 */
945 tmp = g_strdup (g_getenv ("TMPDIR"));
947 #ifdef P_tmpdir
948 if (tmp == NULL || *tmp == '\0')
950 gsize k;
951 g_free (tmp);
952 tmp = g_strdup (P_tmpdir);
953 k = strlen (tmp);
954 if (k > 1 && G_IS_DIR_SEPARATOR (tmp[k - 1]))
955 tmp[k - 1] = '\0';
957 #endif /* P_tmpdir */
959 if (tmp == NULL || *tmp == '\0')
961 g_free (tmp);
962 tmp = g_strdup ("/tmp");
964 #endif /* !G_OS_WIN32 */
966 g_once_init_leave (&tmp_dir, tmp);
969 return tmp_dir;
973 * g_get_host_name:
975 * Return a name for the machine.
977 * The returned name is not necessarily a fully-qualified domain name,
978 * or even present in DNS or some other name service at all. It need
979 * not even be unique on your local network or site, but usually it
980 * is. Callers should not rely on the return value having any specific
981 * properties like uniqueness for security purposes. Even if the name
982 * of the machine is changed while an application is running, the
983 * return value from this function does not change. The returned
984 * string is owned by GLib and should not be modified or freed. If no
985 * name can be determined, a default fixed string "localhost" is
986 * returned.
988 * The encoding of the returned string is UTF-8.
990 * Returns: the host name of the machine.
992 * Since: 2.8
994 const gchar *
995 g_get_host_name (void)
997 static gchar *hostname;
999 if (g_once_init_enter (&hostname))
1001 gboolean failed;
1002 gchar *utmp;
1004 #ifndef G_OS_WIN32
1005 gchar *tmp = g_malloc (sizeof (gchar) * 100);
1006 failed = (gethostname (tmp, sizeof (gchar) * 100) == -1);
1007 if (failed)
1008 g_clear_pointer (&tmp, g_free);
1009 utmp = tmp;
1010 #else
1011 wchar_t tmp[MAX_COMPUTERNAME_LENGTH + 1];
1012 DWORD size = sizeof (tmp) / sizeof (tmp[0]);
1013 failed = (!GetComputerNameW (tmp, &size));
1014 if (!failed)
1015 utmp = g_utf16_to_utf8 (tmp, size, NULL, NULL, NULL);
1016 if (utmp == NULL)
1017 failed = TRUE;
1018 #endif
1020 g_once_init_leave (&hostname, failed ? g_strdup ("localhost") : utmp);
1023 return hostname;
1026 G_LOCK_DEFINE_STATIC (g_prgname);
1027 static gchar *g_prgname = NULL;
1030 * g_get_prgname:
1032 * Gets the name of the program. This name should not be localized,
1033 * in contrast to g_get_application_name().
1035 * If you are using #GApplication the program name is set in
1036 * g_application_run(). In case of GDK or GTK+ it is set in
1037 * gdk_init(), which is called by gtk_init() and the
1038 * #GtkApplication::startup handler. The program name is found by
1039 * taking the last component of @argv[0].
1041 * Returns: the name of the program. The returned string belongs
1042 * to GLib and must not be modified or freed.
1044 const gchar*
1045 g_get_prgname (void)
1047 gchar* retval;
1049 G_LOCK (g_prgname);
1050 #ifdef G_OS_WIN32
1051 if (g_prgname == NULL)
1053 static gboolean beenhere = FALSE;
1055 if (!beenhere)
1057 gchar *utf8_buf = NULL;
1058 wchar_t buf[MAX_PATH+1];
1060 beenhere = TRUE;
1061 if (GetModuleFileNameW (GetModuleHandle (NULL),
1062 buf, G_N_ELEMENTS (buf)) > 0)
1063 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1065 if (utf8_buf)
1067 g_prgname = g_path_get_basename (utf8_buf);
1068 g_free (utf8_buf);
1072 #endif
1073 retval = g_prgname;
1074 G_UNLOCK (g_prgname);
1076 return retval;
1080 * g_set_prgname:
1081 * @prgname: the name of the program.
1083 * Sets the name of the program. This name should not be localized,
1084 * in contrast to g_set_application_name().
1086 * If you are using #GApplication the program name is set in
1087 * g_application_run(). In case of GDK or GTK+ it is set in
1088 * gdk_init(), which is called by gtk_init() and the
1089 * #GtkApplication::startup handler. The program name is found by
1090 * taking the last component of @argv[0].
1092 * Note that for thread-safety reasons this function can only be called once.
1094 void
1095 g_set_prgname (const gchar *prgname)
1097 G_LOCK (g_prgname);
1098 g_free (g_prgname);
1099 g_prgname = g_strdup (prgname);
1100 G_UNLOCK (g_prgname);
1103 G_LOCK_DEFINE_STATIC (g_application_name);
1104 static gchar *g_application_name = NULL;
1107 * g_get_application_name:
1109 * Gets a human-readable name for the application, as set by
1110 * g_set_application_name(). This name should be localized if
1111 * possible, and is intended for display to the user. Contrast with
1112 * g_get_prgname(), which gets a non-localized name. If
1113 * g_set_application_name() has not been called, returns the result of
1114 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1115 * been called).
1117 * Returns: human-readable application name. may return %NULL
1119 * Since: 2.2
1121 const gchar *
1122 g_get_application_name (void)
1124 gchar* retval;
1126 G_LOCK (g_application_name);
1127 retval = g_application_name;
1128 G_UNLOCK (g_application_name);
1130 if (retval == NULL)
1131 return g_get_prgname ();
1133 return retval;
1137 * g_set_application_name:
1138 * @application_name: localized name of the application
1140 * Sets a human-readable name for the application. This name should be
1141 * localized if possible, and is intended for display to the user.
1142 * Contrast with g_set_prgname(), which sets a non-localized name.
1143 * g_set_prgname() will be called automatically by gtk_init(),
1144 * but g_set_application_name() will not.
1146 * Note that for thread safety reasons, this function can only
1147 * be called once.
1149 * The application name will be used in contexts such as error messages,
1150 * or when displaying an application's name in the task list.
1152 * Since: 2.2
1154 void
1155 g_set_application_name (const gchar *application_name)
1157 gboolean already_set = FALSE;
1159 G_LOCK (g_application_name);
1160 if (g_application_name)
1161 already_set = TRUE;
1162 else
1163 g_application_name = g_strdup (application_name);
1164 G_UNLOCK (g_application_name);
1166 if (already_set)
1167 g_warning ("g_set_application_name() called multiple times");
1171 * g_get_user_data_dir:
1173 * Returns a base directory in which to access application data such
1174 * as icons that is customized for a particular user.
1176 * On UNIX platforms this is determined using the mechanisms described
1177 * in the
1178 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1179 * In this case the directory retrieved will be `XDG_DATA_HOME`.
1181 * On Windows it follows XDG Base Directory Specification if `XDG_DATA_HOME`
1182 * is defined. If `XDG_DATA_HOME` is undefined, the folder to use for local (as
1183 * opposed to roaming) application data is used instead. See the
1184 * [documentation for `CSIDL_LOCAL_APPDATA`](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx#csidl_local_appdata).
1185 * Note that in this case on Windows it will be the same
1186 * as what g_get_user_config_dir() returns.
1188 * Returns: (type filename): a string owned by GLib that must not be modified
1189 * or freed.
1190 * Since: 2.6
1192 const gchar *
1193 g_get_user_data_dir (void)
1195 gchar *data_dir = NULL;
1197 G_LOCK (g_utils_global);
1199 if (!g_user_data_dir)
1201 const gchar *data_dir_env = g_getenv ("XDG_DATA_HOME");
1203 if (data_dir_env && data_dir_env[0])
1204 data_dir = g_strdup (data_dir_env);
1205 #ifdef G_OS_WIN32
1206 else
1207 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1208 #endif
1209 if (!data_dir || !data_dir[0])
1211 const gchar *home_dir = g_get_home_dir ();
1213 if (home_dir)
1214 data_dir = g_build_filename (home_dir, ".local", "share", NULL);
1215 else
1216 data_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".local", "share", NULL);
1219 g_user_data_dir = data_dir;
1221 else
1222 data_dir = g_user_data_dir;
1224 G_UNLOCK (g_utils_global);
1226 return data_dir;
1229 static void
1230 g_init_user_config_dir (void)
1232 gchar *config_dir = NULL;
1234 if (!g_user_config_dir)
1236 const gchar *config_dir_env = g_getenv ("XDG_CONFIG_HOME");
1238 if (config_dir_env && config_dir_env[0])
1239 config_dir = g_strdup (config_dir_env);
1240 #ifdef G_OS_WIN32
1241 else
1242 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1243 #endif
1244 if (!config_dir || !config_dir[0])
1246 const gchar *home_dir = g_get_home_dir ();
1248 if (home_dir)
1249 config_dir = g_build_filename (home_dir, ".config", NULL);
1250 else
1251 config_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".config", NULL);
1254 g_user_config_dir = config_dir;
1259 * g_get_user_config_dir:
1261 * Returns a base directory in which to store user-specific application
1262 * configuration information such as user preferences and settings.
1264 * On UNIX platforms this is determined using the mechanisms described
1265 * in the
1266 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1267 * In this case the directory retrieved will be `XDG_CONFIG_HOME`.
1269 * On Windows it follows XDG Base Directory Specification if `XDG_CONFIG_HOME` is defined.
1270 * If `XDG_CONFIG_HOME` is undefined, the folder to use for local (as opposed
1271 * to roaming) application data is used instead. See the
1272 * [documentation for `CSIDL_LOCAL_APPDATA`](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx#csidl_local_appdata).
1273 * Note that in this case on Windows it will be the same
1274 * as what g_get_user_data_dir() returns.
1276 * Returns: (type filename): a string owned by GLib that must not be modified
1277 * or freed.
1278 * Since: 2.6
1280 const gchar *
1281 g_get_user_config_dir (void)
1283 G_LOCK (g_utils_global);
1285 g_init_user_config_dir ();
1287 G_UNLOCK (g_utils_global);
1289 return g_user_config_dir;
1293 * g_get_user_cache_dir:
1295 * Returns a base directory in which to store non-essential, cached
1296 * data specific to particular user.
1298 * On UNIX platforms this is determined using the mechanisms described
1299 * in the
1300 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1301 * In this case the directory retrieved will be `XDG_CACHE_HOME`.
1303 * On Windows it follows XDG Base Directory Specification if `XDG_CACHE_HOME` is defined.
1304 * If `XDG_CACHE_HOME` is undefined, the directory that serves as a common
1305 * repository for temporary Internet files is used instead. A typical path is
1306 * `C:\Documents and Settings\username\Local Settings\Temporary Internet Files`.
1307 * See the [documentation for `CSIDL_INTERNET_CACHE`](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx#csidl_internet_cache).
1309 * Returns: (type filename): a string owned by GLib that must not be modified
1310 * or freed.
1311 * Since: 2.6
1313 const gchar *
1314 g_get_user_cache_dir (void)
1316 gchar *cache_dir = NULL;
1318 G_LOCK (g_utils_global);
1320 if (!g_user_cache_dir)
1322 const gchar *cache_dir_env = g_getenv ("XDG_CACHE_HOME");
1324 if (cache_dir_env && cache_dir_env[0])
1325 cache_dir = g_strdup (cache_dir_env);
1326 #ifdef G_OS_WIN32
1327 else
1328 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE);
1329 #endif
1330 if (!cache_dir || !cache_dir[0])
1332 const gchar *home_dir = g_get_home_dir ();
1334 if (home_dir)
1335 cache_dir = g_build_filename (home_dir, ".cache", NULL);
1336 else
1337 cache_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".cache", NULL);
1339 g_user_cache_dir = cache_dir;
1341 else
1342 cache_dir = g_user_cache_dir;
1344 G_UNLOCK (g_utils_global);
1346 return cache_dir;
1350 * g_get_user_runtime_dir:
1352 * Returns a directory that is unique to the current user on the local
1353 * system.
1355 * This is determined using the mechanisms described
1356 * in the
1357 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1358 * This is the directory
1359 * specified in the `XDG_RUNTIME_DIR` environment variable.
1360 * In the case that this variable is not set, we return the value of
1361 * g_get_user_cache_dir(), after verifying that it exists.
1363 * Returns: (type filename): a string owned by GLib that must not be
1364 * modified or freed.
1366 * Since: 2.28
1368 const gchar *
1369 g_get_user_runtime_dir (void)
1371 static const gchar *runtime_dir;
1373 if (g_once_init_enter (&runtime_dir))
1375 const gchar *dir;
1377 dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
1379 if (dir == NULL)
1381 /* No need to strdup this one since it is valid forever. */
1382 dir = g_get_user_cache_dir ();
1384 /* The user should be able to rely on the directory existing
1385 * when the function returns. Probably it already does, but
1386 * let's make sure. Just do mkdir() directly since it will be
1387 * no more expensive than a stat() in the case that the
1388 * directory already exists and is a lot easier.
1390 * $XDG_CACHE_HOME is probably ~/.cache/ so as long as $HOME
1391 * exists this will work. If the user changed $XDG_CACHE_HOME
1392 * then they can make sure that it exists...
1394 (void) g_mkdir (dir, 0700);
1397 g_assert (dir != NULL);
1399 g_once_init_leave (&runtime_dir, dir);
1402 return runtime_dir;
1405 #ifdef HAVE_CARBON
1407 static gchar *
1408 find_folder (OSType type)
1410 gchar *filename = NULL;
1411 FSRef found;
1413 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
1415 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
1417 if (url)
1419 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
1421 if (path)
1423 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
1425 if (! filename)
1427 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
1429 CFStringGetCString (path, filename,
1430 CFStringGetLength (path) * 3 + 1,
1431 kCFStringEncodingUTF8);
1434 CFRelease (path);
1437 CFRelease (url);
1441 return filename;
1444 static void
1445 load_user_special_dirs (void)
1447 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
1448 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
1449 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
1450 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
1451 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
1452 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
1453 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
1454 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
1457 #elif defined(G_OS_WIN32)
1459 static void
1460 load_user_special_dirs (void)
1462 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1463 DWORD dwFlags,
1464 HANDLE hToken,
1465 PWSTR *ppszPath);
1466 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
1468 static const GUID FOLDERID_Downloads =
1469 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1470 static const GUID FOLDERID_Public =
1471 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1473 wchar_t *wcp;
1475 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
1476 "SHGetKnownFolderPath");
1478 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1479 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
1481 if (p_SHGetKnownFolderPath == NULL)
1483 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1485 else
1487 wcp = NULL;
1488 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1489 if (wcp)
1491 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1492 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
1493 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1494 CoTaskMemFree (wcp);
1496 else
1497 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1500 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
1501 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
1503 if (p_SHGetKnownFolderPath == NULL)
1505 /* XXX */
1506 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1508 else
1510 wcp = NULL;
1511 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
1512 if (wcp)
1514 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1515 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
1516 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1517 CoTaskMemFree (wcp);
1519 else
1520 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1523 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
1524 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
1527 #else /* default is unix */
1529 /* adapted from xdg-user-dir-lookup.c
1531 * Copyright (C) 2007 Red Hat Inc.
1533 * Permission is hereby granted, free of charge, to any person
1534 * obtaining a copy of this software and associated documentation files
1535 * (the "Software"), to deal in the Software without restriction,
1536 * including without limitation the rights to use, copy, modify, merge,
1537 * publish, distribute, sublicense, and/or sell copies of the Software,
1538 * and to permit persons to whom the Software is furnished to do so,
1539 * subject to the following conditions:
1541 * The above copyright notice and this permission notice shall be
1542 * included in all copies or substantial portions of the Software.
1544 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1545 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1546 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1547 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1548 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1549 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1550 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1551 * SOFTWARE.
1553 static void
1554 load_user_special_dirs (void)
1556 gchar *config_file;
1557 gchar *data;
1558 gchar **lines;
1559 gint n_lines, i;
1561 g_init_user_config_dir ();
1562 config_file = g_build_filename (g_user_config_dir,
1563 "user-dirs.dirs",
1564 NULL);
1566 if (!g_file_get_contents (config_file, &data, NULL, NULL))
1568 g_free (config_file);
1569 return;
1572 lines = g_strsplit (data, "\n", -1);
1573 n_lines = g_strv_length (lines);
1574 g_free (data);
1576 for (i = 0; i < n_lines; i++)
1578 gchar *buffer = lines[i];
1579 gchar *d, *p;
1580 gint len;
1581 gboolean is_relative = FALSE;
1582 GUserDirectory directory;
1584 /* Remove newline at end */
1585 len = strlen (buffer);
1586 if (len > 0 && buffer[len - 1] == '\n')
1587 buffer[len - 1] = 0;
1589 p = buffer;
1590 while (*p == ' ' || *p == '\t')
1591 p++;
1593 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
1595 directory = G_USER_DIRECTORY_DESKTOP;
1596 p += strlen ("XDG_DESKTOP_DIR");
1598 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
1600 directory = G_USER_DIRECTORY_DOCUMENTS;
1601 p += strlen ("XDG_DOCUMENTS_DIR");
1603 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
1605 directory = G_USER_DIRECTORY_DOWNLOAD;
1606 p += strlen ("XDG_DOWNLOAD_DIR");
1608 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
1610 directory = G_USER_DIRECTORY_MUSIC;
1611 p += strlen ("XDG_MUSIC_DIR");
1613 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
1615 directory = G_USER_DIRECTORY_PICTURES;
1616 p += strlen ("XDG_PICTURES_DIR");
1618 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
1620 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
1621 p += strlen ("XDG_PUBLICSHARE_DIR");
1623 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
1625 directory = G_USER_DIRECTORY_TEMPLATES;
1626 p += strlen ("XDG_TEMPLATES_DIR");
1628 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
1630 directory = G_USER_DIRECTORY_VIDEOS;
1631 p += strlen ("XDG_VIDEOS_DIR");
1633 else
1634 continue;
1636 while (*p == ' ' || *p == '\t')
1637 p++;
1639 if (*p != '=')
1640 continue;
1641 p++;
1643 while (*p == ' ' || *p == '\t')
1644 p++;
1646 if (*p != '"')
1647 continue;
1648 p++;
1650 if (strncmp (p, "$HOME", 5) == 0)
1652 p += 5;
1653 is_relative = TRUE;
1655 else if (*p != '/')
1656 continue;
1658 d = strrchr (p, '"');
1659 if (!d)
1660 continue;
1661 *d = 0;
1663 d = p;
1665 /* remove trailing slashes */
1666 len = strlen (d);
1667 if (d[len - 1] == '/')
1668 d[len - 1] = 0;
1670 if (is_relative)
1672 g_user_special_dirs[directory] = g_build_filename (g_get_home_dir (), d, NULL);
1674 else
1675 g_user_special_dirs[directory] = g_strdup (d);
1678 g_strfreev (lines);
1679 g_free (config_file);
1682 #endif /* platform-specific load_user_special_dirs implementations */
1686 * g_reload_user_special_dirs_cache:
1688 * Resets the cache used for g_get_user_special_dir(), so
1689 * that the latest on-disk version is used. Call this only
1690 * if you just changed the data on disk yourself.
1692 * Due to threadsafety issues this may cause leaking of strings
1693 * that were previously returned from g_get_user_special_dir()
1694 * that can't be freed. We ensure to only leak the data for
1695 * the directories that actually changed value though.
1697 * Since: 2.22
1699 void
1700 g_reload_user_special_dirs_cache (void)
1702 int i;
1704 G_LOCK (g_utils_global);
1706 if (g_user_special_dirs != NULL)
1708 /* save a copy of the pointer, to check if some memory can be preserved */
1709 char **old_g_user_special_dirs = g_user_special_dirs;
1710 char *old_val;
1712 /* recreate and reload our cache */
1713 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1714 load_user_special_dirs ();
1716 /* only leak changed directories */
1717 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
1719 old_val = old_g_user_special_dirs[i];
1720 if (g_user_special_dirs[i] == NULL)
1722 g_user_special_dirs[i] = old_val;
1724 else if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
1726 /* don't leak */
1727 g_free (g_user_special_dirs[i]);
1728 g_user_special_dirs[i] = old_val;
1730 else
1731 g_free (old_val);
1734 /* free the old array */
1735 g_free (old_g_user_special_dirs);
1738 G_UNLOCK (g_utils_global);
1742 * g_get_user_special_dir:
1743 * @directory: the logical id of special directory
1745 * Returns the full path of a special directory using its logical id.
1747 * On UNIX this is done using the XDG special user directories.
1748 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
1749 * falls back to `$HOME/Desktop` when XDG special user directories have
1750 * not been set up.
1752 * Depending on the platform, the user might be able to change the path
1753 * of the special directory without requiring the session to restart; GLib
1754 * will not reflect any change once the special directories are loaded.
1756 * Returns: (type filename): the path to the specified special directory, or
1757 * %NULL if the logical id was not found. The returned string is owned by
1758 * GLib and should not be modified or freed.
1760 * Since: 2.14
1762 const gchar *
1763 g_get_user_special_dir (GUserDirectory directory)
1765 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
1766 directory < G_USER_N_DIRECTORIES, NULL);
1768 G_LOCK (g_utils_global);
1770 if (G_UNLIKELY (g_user_special_dirs == NULL))
1772 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1774 load_user_special_dirs ();
1776 /* Special-case desktop for historical compatibility */
1777 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
1778 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = g_build_filename (g_get_home_dir (), "Desktop", NULL);
1781 G_UNLOCK (g_utils_global);
1783 return g_user_special_dirs[directory];
1786 #ifdef G_OS_WIN32
1788 #undef g_get_system_data_dirs
1790 static HMODULE
1791 get_module_for_address (gconstpointer address)
1793 /* Holds the g_utils_global lock */
1795 static gboolean beenhere = FALSE;
1796 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
1797 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
1798 HMODULE hmodule = NULL;
1800 if (!address)
1801 return NULL;
1803 if (!beenhere)
1805 p_GetModuleHandleExA =
1806 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1807 "GetModuleHandleExA");
1808 beenhere = TRUE;
1811 if (p_GetModuleHandleExA == NULL ||
1812 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
1813 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
1814 address, &hmodule))
1816 MEMORY_BASIC_INFORMATION mbi;
1817 VirtualQuery (address, &mbi, sizeof (mbi));
1818 hmodule = (HMODULE) mbi.AllocationBase;
1821 return hmodule;
1824 static gchar *
1825 get_module_share_dir (gconstpointer address)
1827 HMODULE hmodule;
1828 gchar *filename;
1829 gchar *retval;
1831 hmodule = get_module_for_address (address);
1832 if (hmodule == NULL)
1833 return NULL;
1835 filename = g_win32_get_package_installation_directory_of_module (hmodule);
1836 retval = g_build_filename (filename, "share", NULL);
1837 g_free (filename);
1839 return retval;
1842 static const gchar * const *
1843 g_win32_get_system_data_dirs_for_module_real (void (*address_of_function)(void))
1845 GArray *data_dirs;
1846 HMODULE hmodule;
1847 static GHashTable *per_module_data_dirs = NULL;
1848 gchar **retval;
1849 gchar *p;
1850 gchar *exe_root;
1852 hmodule = NULL;
1853 if (address_of_function)
1855 G_LOCK (g_utils_global);
1856 hmodule = get_module_for_address (address_of_function);
1857 if (hmodule != NULL)
1859 if (per_module_data_dirs == NULL)
1860 per_module_data_dirs = g_hash_table_new (NULL, NULL);
1861 else
1863 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
1865 if (retval != NULL)
1867 G_UNLOCK (g_utils_global);
1868 return (const gchar * const *) retval;
1874 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
1876 /* Documents and Settings\All Users\Application Data */
1877 p = get_special_folder (CSIDL_COMMON_APPDATA);
1878 if (p)
1879 g_array_append_val (data_dirs, p);
1881 /* Documents and Settings\All Users\Documents */
1882 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1883 if (p)
1884 g_array_append_val (data_dirs, p);
1886 /* Using the above subfolders of Documents and Settings perhaps
1887 * makes sense from a Windows perspective.
1889 * But looking at the actual use cases of this function in GTK+
1890 * and GNOME software, what we really want is the "share"
1891 * subdirectory of the installation directory for the package
1892 * our caller is a part of.
1894 * The address_of_function parameter, if non-NULL, points to a
1895 * function in the calling module. Use that to determine that
1896 * module's installation folder, and use its "share" subfolder.
1898 * Additionally, also use the "share" subfolder of the installation
1899 * locations of GLib and the .exe file being run.
1901 * To guard against none of the above being what is really wanted,
1902 * callers of this function should have Win32-specific code to look
1903 * up their installation folder themselves, and handle a subfolder
1904 * "share" of it in the same way as the folders returned from this
1905 * function.
1908 p = get_module_share_dir (address_of_function);
1909 if (p)
1910 g_array_append_val (data_dirs, p);
1912 if (glib_dll != NULL)
1914 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
1915 p = g_build_filename (glib_root, "share", NULL);
1916 if (p)
1917 g_array_append_val (data_dirs, p);
1918 g_free (glib_root);
1921 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
1922 p = g_build_filename (exe_root, "share", NULL);
1923 if (p)
1924 g_array_append_val (data_dirs, p);
1925 g_free (exe_root);
1927 retval = (gchar **) g_array_free (data_dirs, FALSE);
1929 if (address_of_function)
1931 if (hmodule != NULL)
1932 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
1933 G_UNLOCK (g_utils_global);
1936 return (const gchar * const *) retval;
1939 const gchar * const *
1940 g_win32_get_system_data_dirs_for_module (void (*address_of_function)(void))
1942 gboolean should_call_g_get_system_data_dirs;
1944 should_call_g_get_system_data_dirs = TRUE;
1945 /* These checks are the same as the ones that g_get_system_data_dirs() does.
1946 * Please keep them in sync.
1948 G_LOCK (g_utils_global);
1950 if (!g_system_data_dirs)
1952 const gchar *data_dirs = g_getenv ("XDG_DATA_DIRS");
1954 if (!data_dirs || !data_dirs[0])
1955 should_call_g_get_system_data_dirs = FALSE;
1958 G_UNLOCK (g_utils_global);
1960 /* There is a subtle difference between g_win32_get_system_data_dirs_for_module (NULL),
1961 * which is what GLib code can normally call,
1962 * and g_win32_get_system_data_dirs_for_module (&_g_win32_get_system_data_dirs),
1963 * which is what the inline function used by non-GLib code calls.
1964 * The former gets prefix relative to currently-running executable,
1965 * the latter - relative to the module that calls _g_win32_get_system_data_dirs()
1966 * (disguised as g_get_system_data_dirs()), which could be an executable or
1967 * a DLL that is located somewhere else.
1968 * This is why that inline function in gutils.h exists, and why we can't just
1969 * call g_get_system_data_dirs() from there - because we need to get the address
1970 * local to the non-GLib caller-module.
1974 * g_get_system_data_dirs() will fall back to calling
1975 * g_win32_get_system_data_dirs_for_module_real(NULL) if XDG_DATA_DIRS is NULL
1976 * or an empty string. The checks above ensure that we do not call it in such
1977 * cases and use the address_of_function that we've been given by the inline function.
1978 * The reason we're calling g_get_system_data_dirs /at all/ is to give
1979 * XDG_DATA_DIRS precedence (if it is set).
1981 if (should_call_g_get_system_data_dirs)
1982 return g_get_system_data_dirs ();
1984 return g_win32_get_system_data_dirs_for_module_real (address_of_function);
1987 #endif
1990 * g_get_system_data_dirs:
1992 * Returns an ordered list of base directories in which to access
1993 * system-wide application data.
1995 * On UNIX platforms this is determined using the mechanisms described
1996 * in the
1997 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec)
1998 * In this case the list of directories retrieved will be `XDG_DATA_DIRS`.
2000 * On Windows it follows XDG Base Directory Specification if `XDG_DATA_DIRS` is defined.
2001 * If `XDG_DATA_DIRS` is undefined,
2002 * the first elements in the list are the Application Data
2003 * and Documents folders for All Users. (These can be determined only
2004 * on Windows 2000 or later and are not present in the list on other
2005 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2006 * CSIDL_COMMON_DOCUMENTS.
2008 * Then follows the "share" subfolder in the installation folder for
2009 * the package containing the DLL that calls this function, if it can
2010 * be determined.
2012 * Finally the list contains the "share" subfolder in the installation
2013 * folder for GLib, and in the installation folder for the package the
2014 * application's .exe file belongs to.
2016 * The installation folders above are determined by looking up the
2017 * folder where the module (DLL or EXE) in question is located. If the
2018 * folder's name is "bin", its parent is used, otherwise the folder
2019 * itself.
2021 * Note that on Windows the returned list can vary depending on where
2022 * this function is called.
2024 * Returns: (array zero-terminated=1) (element-type filename) (transfer none):
2025 * a %NULL-terminated array of strings owned by GLib that must not be
2026 * modified or freed.
2028 * Since: 2.6
2030 const gchar * const *
2031 g_get_system_data_dirs (void)
2033 gchar **data_dir_vector;
2035 /* These checks are the same as the ones that g_win32_get_system_data_dirs_for_module()
2036 * does. Please keep them in sync.
2038 G_LOCK (g_utils_global);
2040 if (!g_system_data_dirs)
2042 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2044 #ifndef G_OS_WIN32
2045 if (!data_dirs || !data_dirs[0])
2046 data_dirs = "/usr/local/share/:/usr/share/";
2048 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2049 #else
2050 if (!data_dirs || !data_dirs[0])
2051 data_dir_vector = g_strdupv ((gchar **) g_win32_get_system_data_dirs_for_module_real (NULL));
2052 else
2053 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2054 #endif
2056 g_system_data_dirs = data_dir_vector;
2058 else
2059 data_dir_vector = g_system_data_dirs;
2061 G_UNLOCK (g_utils_global);
2063 return (const gchar * const *) data_dir_vector;
2067 * g_get_system_config_dirs:
2069 * Returns an ordered list of base directories in which to access
2070 * system-wide configuration information.
2072 * On UNIX platforms this is determined using the mechanisms described
2073 * in the
2074 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2075 * In this case the list of directories retrieved will be `XDG_CONFIG_DIRS`.
2077 * On Windows it follows XDG Base Directory Specification if `XDG_CONFIG_DIRS` is defined.
2078 * If `XDG_CONFIG_DIRS` is undefined, the directory that contains application
2079 * data for all users is used instead. A typical path is
2080 * `C:\Documents and Settings\All Users\Application Data`.
2081 * This folder is used for application data
2082 * that is not user specific. For example, an application can store
2083 * a spell-check dictionary, a database of clip art, or a log file in the
2084 * CSIDL_COMMON_APPDATA folder. This information will not roam and is available
2085 * to anyone using the computer.
2087 * Returns: (array zero-terminated=1) (element-type filename) (transfer none):
2088 * a %NULL-terminated array of strings owned by GLib that must not be
2089 * modified or freed.
2091 * Since: 2.6
2093 const gchar * const *
2094 g_get_system_config_dirs (void)
2096 gchar **conf_dir_vector;
2098 G_LOCK (g_utils_global);
2100 if (!g_system_config_dirs)
2102 const gchar *conf_dirs = g_getenv ("XDG_CONFIG_DIRS");
2103 #ifdef G_OS_WIN32
2104 if (conf_dirs)
2106 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2108 else
2110 gchar *special_conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2112 if (special_conf_dirs)
2113 conf_dir_vector = g_strsplit (special_conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2114 else
2115 /* Return empty list */
2116 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2118 g_free (special_conf_dirs);
2120 #else
2121 if (!conf_dirs || !conf_dirs[0])
2122 conf_dirs = "/etc/xdg";
2124 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2125 #endif
2127 g_system_config_dirs = conf_dir_vector;
2129 else
2130 conf_dir_vector = g_system_config_dirs;
2131 G_UNLOCK (g_utils_global);
2133 return (const gchar * const *) conf_dir_vector;
2137 * g_nullify_pointer:
2138 * @nullify_location: (not nullable): the memory address of the pointer.
2140 * Set the pointer at the specified location to %NULL.
2142 void
2143 g_nullify_pointer (gpointer *nullify_location)
2145 g_return_if_fail (nullify_location != NULL);
2147 *nullify_location = NULL;
2150 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2151 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2152 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2153 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2154 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2155 #define EXABYTE_FACTOR (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2157 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2158 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2159 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2160 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2161 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2162 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2165 * g_format_size:
2166 * @size: a size in bytes
2168 * Formats a size (for example the size of a file) into a human readable
2169 * string. Sizes are rounded to the nearest size prefix (kB, MB, GB)
2170 * and are displayed rounded to the nearest tenth. E.g. the file size
2171 * 3292528 bytes will be converted into the string "3.2 MB".
2173 * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2175 * This string should be freed with g_free() when not needed any longer.
2177 * See g_format_size_full() for more options about how the size might be
2178 * formatted.
2180 * Returns: a newly-allocated formatted string containing a human readable
2181 * file size
2183 * Since: 2.30
2185 gchar *
2186 g_format_size (guint64 size)
2188 return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2192 * GFormatSizeFlags:
2193 * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2194 * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2195 * of the returned string. For example, "45.6 kB (45,612 bytes)".
2196 * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2197 * suffixes. IEC units should only be used for reporting things with
2198 * a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2199 * Network and storage sizes should be reported in the normal SI units.
2200 * @G_FORMAT_SIZE_BITS: set the size as a quantity in bits, rather than
2201 * bytes, and return units in bits. For example, ‘Mb’ rather than ‘MB’.
2203 * Flags to modify the format of the string returned by g_format_size_full().
2206 #pragma GCC diagnostic push
2207 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
2210 * g_format_size_full:
2211 * @size: a size in bytes
2212 * @flags: #GFormatSizeFlags to modify the output
2214 * Formats a size.
2216 * This function is similar to g_format_size() but allows for flags
2217 * that modify the output. See #GFormatSizeFlags.
2219 * Returns: a newly-allocated formatted string containing a human
2220 * readable file size
2222 * Since: 2.30
2224 gchar *
2225 g_format_size_full (guint64 size,
2226 GFormatSizeFlags flags)
2228 struct Format
2230 guint64 factor;
2231 char string[9];
2234 typedef enum
2236 FORMAT_BYTES,
2237 FORMAT_BYTES_IEC,
2238 FORMAT_BITS,
2239 FORMAT_BITS_IEC
2240 } FormatIndex;
2242 const struct Format formats[4][6] = {
2244 { KILOBYTE_FACTOR, N_("%.1f kB") },
2245 { MEGABYTE_FACTOR, N_("%.1f MB") },
2246 { GIGABYTE_FACTOR, N_("%.1f GB") },
2247 { TERABYTE_FACTOR, N_("%.1f TB") },
2248 { PETABYTE_FACTOR, N_("%.1f PB") },
2249 { EXABYTE_FACTOR, N_("%.1f EB") }
2252 { KIBIBYTE_FACTOR, N_("%.1f KiB") },
2253 { MEBIBYTE_FACTOR, N_("%.1f MiB") },
2254 { GIBIBYTE_FACTOR, N_("%.1f GiB") },
2255 { TEBIBYTE_FACTOR, N_("%.1f TiB") },
2256 { PEBIBYTE_FACTOR, N_("%.1f PiB") },
2257 { EXBIBYTE_FACTOR, N_("%.1f EiB") }
2260 { KILOBYTE_FACTOR, N_("%.1f kb") },
2261 { MEGABYTE_FACTOR, N_("%.1f Mb") },
2262 { GIGABYTE_FACTOR, N_("%.1f Gb") },
2263 { TERABYTE_FACTOR, N_("%.1f Tb") },
2264 { PETABYTE_FACTOR, N_("%.1f Pb") },
2265 { EXABYTE_FACTOR, N_("%.1f Eb") }
2268 { KIBIBYTE_FACTOR, N_("%.1f Kib") },
2269 { MEBIBYTE_FACTOR, N_("%.1f Mib") },
2270 { GIBIBYTE_FACTOR, N_("%.1f Gib") },
2271 { TEBIBYTE_FACTOR, N_("%.1f Tib") },
2272 { PEBIBYTE_FACTOR, N_("%.1f Pib") },
2273 { EXBIBYTE_FACTOR, N_("%.1f Eib") }
2277 GString *string;
2278 FormatIndex index;
2280 string = g_string_new (NULL);
2282 switch (flags & ~G_FORMAT_SIZE_LONG_FORMAT)
2284 case G_FORMAT_SIZE_DEFAULT:
2285 index = FORMAT_BYTES;
2286 break;
2287 case (G_FORMAT_SIZE_DEFAULT | G_FORMAT_SIZE_IEC_UNITS):
2288 index = FORMAT_BYTES_IEC;
2289 break;
2290 case G_FORMAT_SIZE_BITS:
2291 index = FORMAT_BITS;
2292 break;
2293 case (G_FORMAT_SIZE_BITS | G_FORMAT_SIZE_IEC_UNITS):
2294 index = FORMAT_BITS_IEC;
2295 break;
2296 default:
2297 g_assert_not_reached ();
2301 if (size < formats[index][0].factor)
2303 const char * format;
2305 if (index == FORMAT_BYTES || index == FORMAT_BYTES_IEC)
2307 format = g_dngettext (GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size);
2309 else
2311 format = g_dngettext (GETTEXT_PACKAGE, "%u bit", "%u bits", (guint) size);
2314 g_string_printf (string, format, (guint) size);
2316 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2318 else
2320 const gsize n = G_N_ELEMENTS (formats[index]);
2321 gsize i;
2324 * Point the last format (the highest unit) by default
2325 * and then then scan all formats, starting with the 2nd one
2326 * because the 1st is already managed by with the plural form
2328 const struct Format * f = &formats[index][n - 1];
2330 for (i = 1; i < n; i++)
2332 if (size < formats[index][i].factor)
2334 f = &formats[index][i - 1];
2335 break;
2339 g_string_printf (string, _(f->string), (gdouble) size / (gdouble) f->factor);
2342 if (flags & G_FORMAT_SIZE_LONG_FORMAT)
2344 /* First problem: we need to use the number of bytes to decide on
2345 * the plural form that is used for display, but the number of
2346 * bytes potentially exceeds the size of a guint (which is what
2347 * ngettext() takes).
2349 * From a pragmatic standpoint, it seems that all known languages
2350 * base plural forms on one or both of the following:
2352 * - the lowest digits of the number
2354 * - if the number if greater than some small value
2356 * Here's how we fake it: Draw an arbitrary line at one thousand.
2357 * If the number is below that, then fine. If it is above it,
2358 * then we take the modulus of the number by one thousand (in
2359 * order to keep the lowest digits) and add one thousand to that
2360 * (in order to ensure that 1001 is not treated the same as 1).
2362 guint plural_form = size < 1000 ? size : size % 1000 + 1000;
2364 /* Second problem: we need to translate the string "%u byte/bit" and
2365 * "%u bytes/bits" for pluralisation, but the correct number format to
2366 * use for a gsize is different depending on which architecture
2367 * we're on.
2369 * Solution: format the number separately and use "%s bytes/bits" on
2370 * all platforms.
2372 const gchar *translated_format;
2373 gchar *formatted_number;
2375 if (index == FORMAT_BYTES || index == FORMAT_BYTES_IEC)
2377 /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2378 translated_format = g_dngettext (GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
2380 else
2382 /* Translators: the %s in "%s bits" will always be replaced by a number. */
2383 translated_format = g_dngettext (GETTEXT_PACKAGE, "%s bit", "%s bits", plural_form);
2385 /* XXX: Windows doesn't support the "'" format modifier, so we
2386 * must not use it there. Instead, just display the number
2387 * without separation. Bug #655336 is open until a solution is
2388 * found.
2390 #ifndef G_OS_WIN32
2391 formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2392 #else
2393 formatted_number = g_strdup_printf ("%"G_GUINT64_FORMAT, size);
2394 #endif
2396 g_string_append (string, " (");
2397 g_string_append_printf (string, translated_format, formatted_number);
2398 g_free (formatted_number);
2399 g_string_append (string, ")");
2402 return g_string_free (string, FALSE);
2405 #pragma GCC diagnostic pop
2408 * g_format_size_for_display:
2409 * @size: a size in bytes
2411 * Formats a size (for example the size of a file) into a human
2412 * readable string. Sizes are rounded to the nearest size prefix
2413 * (KB, MB, GB) and are displayed rounded to the nearest tenth.
2414 * E.g. the file size 3292528 bytes will be converted into the
2415 * string "3.1 MB".
2417 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2419 * This string should be freed with g_free() when not needed any longer.
2421 * Returns: a newly-allocated formatted string containing a human
2422 * readable file size
2424 * Since: 2.16
2426 * Deprecated:2.30: This function is broken due to its use of SI
2427 * suffixes to denote IEC units. Use g_format_size() instead.
2429 gchar *
2430 g_format_size_for_display (goffset size)
2432 if (size < (goffset) KIBIBYTE_FACTOR)
2433 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
2434 else
2436 gdouble displayed_size;
2438 if (size < (goffset) MEBIBYTE_FACTOR)
2440 displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
2441 /* Translators: this is from the deprecated function g_format_size_for_display() which uses 'KB' to
2442 * mean 1024 bytes. I am aware that 'KB' is not correct, but it has been preserved for reasons of
2443 * compatibility. Users will not see this string unless a program is using this deprecated function.
2444 * Please translate as literally as possible.
2446 return g_strdup_printf (_("%.1f KB"), displayed_size);
2448 else if (size < (goffset) GIBIBYTE_FACTOR)
2450 displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
2451 return g_strdup_printf (_("%.1f MB"), displayed_size);
2453 else if (size < (goffset) TEBIBYTE_FACTOR)
2455 displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
2456 return g_strdup_printf (_("%.1f GB"), displayed_size);
2458 else if (size < (goffset) PEBIBYTE_FACTOR)
2460 displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
2461 return g_strdup_printf (_("%.1f TB"), displayed_size);
2463 else if (size < (goffset) EXBIBYTE_FACTOR)
2465 displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
2466 return g_strdup_printf (_("%.1f PB"), displayed_size);
2468 else
2470 displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
2471 return g_strdup_printf (_("%.1f EB"), displayed_size);
2476 #if defined (G_OS_WIN32) && !defined (_WIN64)
2478 /* Binary compatibility versions. Not for newly compiled code. */
2480 _GLIB_EXTERN const gchar *g_get_user_name_utf8 (void);
2481 _GLIB_EXTERN const gchar *g_get_real_name_utf8 (void);
2482 _GLIB_EXTERN const gchar *g_get_home_dir_utf8 (void);
2483 _GLIB_EXTERN const gchar *g_get_tmp_dir_utf8 (void);
2484 _GLIB_EXTERN gchar *g_find_program_in_path_utf8 (const gchar *program);
2486 gchar *
2487 g_find_program_in_path_utf8 (const gchar *program)
2489 return g_find_program_in_path (program);
2492 const gchar *g_get_user_name_utf8 (void) { return g_get_user_name (); }
2493 const gchar *g_get_real_name_utf8 (void) { return g_get_real_name (); }
2494 const gchar *g_get_home_dir_utf8 (void) { return g_get_home_dir (); }
2495 const gchar *g_get_tmp_dir_utf8 (void) { return g_get_tmp_dir (); }
2497 #endif
2499 /* Private API:
2501 * Returns %TRUE if the current process was executed as setuid
2503 gboolean
2504 g_check_setuid (void)
2506 #if defined(HAVE_SYS_AUXV_H)
2507 unsigned long value;
2508 int errsv;
2510 errno = 0;
2511 value = getauxval (AT_SECURE);
2512 errsv = errno;
2513 if (errsv)
2514 g_error ("getauxval () failed: %s", g_strerror (errsv));
2515 return value;
2516 #elif defined(HAVE_ISSETUGID) && !defined(__BIONIC__)
2517 /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
2519 /* Android had it in older versions but the new 64 bit ABI does not
2520 * have it anymore, and some versions of the 32 bit ABI neither.
2521 * https://code.google.com/p/android-developer-preview/issues/detail?id=168
2523 return issetugid ();
2524 #elif defined(G_OS_UNIX)
2525 uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
2526 gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
2528 static gsize check_setuid_initialised;
2529 static gboolean is_setuid;
2531 if (g_once_init_enter (&check_setuid_initialised))
2533 #ifdef HAVE_GETRESUID
2534 /* These aren't in the header files, so we prototype them here.
2536 int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
2537 int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);
2539 if (getresuid (&ruid, &euid, &suid) != 0 ||
2540 getresgid (&rgid, &egid, &sgid) != 0)
2541 #endif /* HAVE_GETRESUID */
2543 suid = ruid = getuid ();
2544 sgid = rgid = getgid ();
2545 euid = geteuid ();
2546 egid = getegid ();
2549 is_setuid = (ruid != euid || ruid != suid ||
2550 rgid != egid || rgid != sgid);
2552 g_once_init_leave (&check_setuid_initialised, 1);
2554 return is_setuid;
2555 #else
2556 return FALSE;
2557 #endif
2560 #ifdef G_OS_WIN32
2562 * g_abort:
2564 * A wrapper for the POSIX abort() function.
2566 * On Windows it is a function that makes extra effort (including a call
2567 * to abort()) to ensure that a debugger-catchable exception is thrown
2568 * before the program terminates.
2570 * See your C library manual for more details about abort().
2572 * Since: 2.50
2574 void
2575 g_abort (void)
2577 /* One call to break the debugger */
2578 DebugBreak ();
2579 /* One call in case CRT does get saner about abort() behaviour */
2580 abort ();
2581 /* And one call to bind them all and terminate the program for sure */
2582 ExitProcess (127);
2584 #endif