1 /* GLIB - Library of useful routines for C programming
   2  * Copyright (C) 1995-1998  Peter Mattis, Spencer Kimball and Josh MacDonald
   3  *
   4  * This library is free software; you can redistribute it and/or
   5  * modify it under the terms of the GNU Lesser General Public
   6  * License as published by the Free Software Foundation; either
   7  * version 2 of the License, or (at your option) any later version.
   8  *
   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.
  13  *
  14  * You should have received a copy of the GNU Lesser General Public
  15  * License along with this library; if not, write to the
  16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  17  * Boston, MA 02111-1307, USA.
  18  */
  19 
  20 /*
  21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
  22  * file for a list of people on the GLib Team.  See the ChangeLog
  23  * files for a list of changes.  These files are distributed with
  24  * GLib at ftp://ftp.gtk.org/pub/gtk/.
  25  */
  26 
  27 /*
  28  * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
  29  */
  30 
  31 #include "config.h"
  32 
  33 #ifdef HAVE_UNISTD_H
  34 #include <unistd.h>
  35 #endif
  36 #include <stdarg.h>
  37 #include <stdlib.h>
  38 #include <stdio.h>
  39 #include <locale.h>
  40 #include <string.h>
  41 #include <ctype.h>      /* For tolower() */
  42 #include <errno.h>
  43 #include <sys/types.h>
  44 #include <sys/stat.h>
  45 #ifdef HAVE_PWD_H
  46 #include <pwd.h>
  47 #endif
  48 #include <sys/types.h>
  49 #ifdef HAVE_SYS_PARAM_H
  50 #include <sys/param.h>
  51 #endif
  52 #ifdef HAVE_CRT_EXTERNS_H
  53 #include <crt_externs.h> /* for _NSGetEnviron */
  54 #endif
  55 
  56 /* implement gutils's inline functions
  57  */
  58 #define G_IMPLEMENT_INLINES 1
  59 #define __G_UTILS_C__
  60 #include "gutils.h"
  61 
  62 #include "gfileutils.h"
  63 #include "ghash.h"
  64 #include "gslist.h"
  65 #include "gprintfint.h"
  66 #include "gthread.h"
  67 #include "gthreadprivate.h"
  68 #include "gtestutils.h"
  69 #include "gunicode.h"
  70 #include "gstrfuncs.h"
  71 #include "garray.h"
  72 #include "glibintl.h"
  73 
  74 #ifdef G_PLATFORM_WIN32
  75 #include "garray.h"
  76 #include "gconvert.h"
  77 #include "gwin32.h"
  78 #endif
  79 
  80 #ifdef  MAXPATHLEN
  81 #define G_PATH_LENGTH   MAXPATHLEN
  82 #elif   defined (PATH_MAX)
  83 #define G_PATH_LENGTH   PATH_MAX
  84 #elif   defined (_PC_PATH_MAX)
  85 #define G_PATH_LENGTH   sysconf(_PC_PATH_MAX)
  86 #else
  87 #define G_PATH_LENGTH   2048
  88 #endif
  89 
  90 #ifdef G_PLATFORM_WIN32
  91 #  define STRICT        /* Strict typing, please */
  92 #  include <windows.h>
  93 #  undef STRICT
  94 #  ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
  95 #    define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
  96 #    define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
  97 #  endif
  98 #  include <lmcons.h>       /* For UNLEN */
  99 #endif /* G_PLATFORM_WIN32 */
 100 
 101 #ifdef G_OS_WIN32
 102 #  include <direct.h>
 103 #  include <shlobj.h>
 104    /* older SDK (e.g. msvc 5.0) does not have these*/
 105 #  ifndef CSIDL_MYMUSIC
 106 #    define CSIDL_MYMUSIC 13
 107 #  endif
 108 #  ifndef CSIDL_MYVIDEO
 109 #    define CSIDL_MYVIDEO 14
 110 #  endif
 111 #  ifndef CSIDL_INTERNET_CACHE
 112 #    define CSIDL_INTERNET_CACHE 32
 113 #  endif
 114 #  ifndef CSIDL_COMMON_APPDATA
 115 #    define CSIDL_COMMON_APPDATA 35
 116 #  endif
 117 #  ifndef CSIDL_MYPICTURES
 118 #    define CSIDL_MYPICTURES 0x27
 119 #  endif
 120 #  ifndef CSIDL_COMMON_DOCUMENTS
 121 #    define CSIDL_COMMON_DOCUMENTS 46
 122 #  endif
 123 #  ifndef CSIDL_PROFILE
 124 #    define CSIDL_PROFILE 40
 125 #  endif
 126 #  include <process.h>
 127 #endif
 128 
 129 #ifdef HAVE_CARBON
 130 #include <CoreServices/CoreServices.h>
 131 #endif
 132 
 133 #ifdef HAVE_CODESET
 134 #include <langinfo.h>
 135 #endif
 136 
 137 const guint glib_major_version = GLIB_MAJOR_VERSION;
 138 const guint glib_minor_version = GLIB_MINOR_VERSION;
 139 const guint glib_micro_version = GLIB_MICRO_VERSION;
 140 const guint glib_interface_age = GLIB_INTERFACE_AGE;
 141 const guint glib_binary_age = GLIB_BINARY_AGE;
 142 
 143 #ifdef G_PLATFORM_WIN32
 144 
 145 static HMODULE glib_dll = NULL;
 146 
 147 #ifdef DLL_EXPORT
 148 
 149 BOOL WINAPI
 150 DllMain (HINSTANCE hinstDLL,
 151      DWORD     fdwReason,
 152      LPVOID    lpvReserved)
 153 {
 154   if (fdwReason == DLL_PROCESS_ATTACH)
 155       glib_dll = hinstDLL;
 156 
 157   return TRUE;
 158 }
 159 
 160 #endif
 161 
 162 gchar *
 163 _glib_get_dll_directory (void)
 164 {
 165   gchar *retval;
 166   gchar *p;
 167   wchar_t wc_fn[MAX_PATH];
 168 
 169 #ifdef DLL_EXPORT
 170   if (glib_dll == NULL)
 171     return NULL;
 172 #endif
 173 
 174   /* This code is different from that in
 175    * g_win32_get_package_installation_directory_of_module() in that
 176    * here we return the actual folder where the GLib DLL is. We don't
 177    * do the check for it being in a "bin" or "lib" subfolder and then
 178    * returning the parent of that.
 179    *
 180    * In a statically built GLib, glib_dll will be NULL and we will
 181    * thus look up the application's .exe file's location.
 182    */
 183   if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
 184     return NULL;
 185 
 186   retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
 187 
 188   p = strrchr (retval, G_DIR_SEPARATOR);
 189   if (p == NULL)
 190     {
 191       /* Wtf? */
 192       return NULL;
 193     }
 194   *p = '\0';
 195 
 196   return retval;
 197 }
 198 
 199 #endif
 200 
 201 /**
 202  * glib_check_version:
 203  * @required_major: the required major version.
 204  * @required_minor: the required minor version.
 205  * @required_micro: the required micro version.
 206  *
 207  * Checks that the GLib library in use is compatible with the
 208  * given version. Generally you would pass in the constants
 209  * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
 210  * as the three arguments to this function; that produces
 211  * a check that the library in use is compatible with
 212  * the version of GLib the application or module was compiled
 213  * against.
 214  *
 215  * Compatibility is defined by two things: first the version
 216  * of the running library is newer than the version
 217  * @required_major.required_minor.@required_micro. Second
 218  * the running library must be binary compatible with the
 219  * version @required_major.required_minor.@required_micro
 220  * (same major version.)
 221  *
 222  * Return value: %NULL if the GLib library is compatible with the
 223  *   given version, or a string describing the version mismatch.
 224  *   The returned string is owned by GLib and must not be modified
 225  *   or freed.
 226  *
 227  * Since: 2.6
 228  **/
 229 const gchar *
 230 glib_check_version (guint required_major,
 231                     guint required_minor,
 232                     guint required_micro)
 233 {
 234   gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
 235   gint required_effective_micro = 100 * required_minor + required_micro;
 236 
 237   if (required_major > GLIB_MAJOR_VERSION)
 238     return "GLib version too old (major mismatch)";
 239   if (required_major < GLIB_MAJOR_VERSION)
 240     return "GLib version too new (major mismatch)";
 241   if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
 242     return "GLib version too new (micro mismatch)";
 243   if (required_effective_micro > glib_effective_micro)
 244     return "GLib version too old (micro mismatch)";
 245   return NULL;
 246 }
 247 
 248 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
 249 /**
 250  * g_memmove:
 251  * @dest: the destination address to copy the bytes to.
 252  * @src: the source address to copy the bytes from.
 253  * @len: the number of bytes to copy.
 254  *
 255  * Copies a block of memory @len bytes long, from @src to @dest.
 256  * The source and destination areas may overlap.
 257  *
 258  * In order to use this function, you must include
 259  * <filename>string.h</filename> yourself, because this macro will
 260  * typically simply resolve to memmove() and GLib does not include
 261  * <filename>string.h</filename> for you.
 262  */
 263 void
 264 g_memmove (gpointer      dest,
 265        gconstpointer src,
 266        gulong        len)
 267 {
 268   gchar* destptr = dest;
 269   const gchar* srcptr = src;
 270   if (src + len < dest || dest + len < src)
 271     {
 272       bcopy (src, dest, len);
 273       return;
 274     }
 275   else if (dest <= src)
 276     {
 277       while (len--)
 278     *(destptr++) = *(srcptr++);
 279     }
 280   else
 281     {
 282       destptr += len;
 283       srcptr += len;
 284       while (len--)
 285     *(--destptr) = *(--srcptr);
 286     }
 287 }
 288 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
 289 
 290 #ifdef G_OS_WIN32
 291 #undef g_atexit
 292 #endif
 293 
 294 /**
 295  * g_atexit:
 296  * @func: the function to call on normal program termination.
 297  *
 298  * Specifies a function to be called at normal program termination.
 299  *
 300  * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
 301  * macro that maps to a call to the atexit() function in the C
 302  * library. This means that in case the code that calls g_atexit(),
 303  * i.e. atexit(), is in a DLL, the function will be called when the
 304  * DLL is detached from the program. This typically makes more sense
 305  * than that the function is called when the GLib DLL is detached,
 306  * which happened earlier when g_atexit() was a function in the GLib
 307  * DLL.
 308  *
 309  * The behaviour of atexit() in the context of dynamically loaded
 310  * modules is not formally specified and varies wildly.
 311  *
 312  * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
 313  * loaded module which is unloaded before the program terminates might
 314  * well cause a crash at program exit.
 315  *
 316  * Some POSIX systems implement atexit() like Windows, and have each
 317  * dynamically loaded module maintain an own atexit chain that is
 318  * called when the module is unloaded.
 319  *
 320  * On other POSIX systems, before a dynamically loaded module is
 321  * unloaded, the registered atexit functions (if any) residing in that
 322  * module are called, regardless where the code that registered them
 323  * resided. This is presumably the most robust approach.
 324  *
 325  * As can be seen from the above, for portability it's best to avoid
 326  * calling g_atexit() (or atexit()) except in the main executable of a
 327  * program.
 328  */
 329 void
 330 g_atexit (GVoidFunc func)
 331 {
 332   gint result;
 333   const gchar *error = NULL;
 334 
 335   /* keep this in sync with glib.h */
 336 
 337 #ifdef  G_NATIVE_ATEXIT
 338   result = ATEXIT (func);
 339   if (result)
 340     error = g_strerror (errno);
 341 #elif defined (HAVE_ATEXIT)
 342 #  ifdef NeXT /* @#%@! NeXTStep */
 343   result = !atexit ((void (*)(void)) func);
 344   if (result)
 345     error = g_strerror (errno);
 346 #  else
 347   result = atexit ((void (*)(void)) func);
 348   if (result)
 349     error = g_strerror (errno);
 350 #  endif /* NeXT */
 351 #elif defined (HAVE_ON_EXIT)
 352   result = on_exit ((void (*)(int, void *)) func, NULL);
 353   if (result)
 354     error = g_strerror (errno);
 355 #else
 356   result = 0;
 357   error = "no implementation";
 358 #endif /* G_NATIVE_ATEXIT */
 359 
 360   if (error)
 361     g_error ("Could not register atexit() function: %s", error);
 362 }
 363 
 364 /* Based on execvp() from GNU Libc.
 365  * Some of this code is cut-and-pasted into gspawn.c
 366  */
 367 
 368 static gchar*
 369 my_strchrnul (const gchar *str,
 370           gchar        c)
 371 {
 372   gchar *p = (gchar*)str;
 373   while (*p && (*p != c))
 374     ++p;
 375 
 376   return p;
 377 }
 378 
 379 #ifdef G_OS_WIN32
 380 
 381 static gchar *inner_find_program_in_path (const gchar *program);
 382 
 383 gchar*
 384 g_find_program_in_path (const gchar *program)
 385 {
 386   const gchar *last_dot = strrchr (program, '.');
 387 
 388   if (last_dot == NULL ||
 389       strchr (last_dot, '\\') != NULL ||
 390       strchr (last_dot, '/') != NULL)
 391     {
 392       const gint program_length = strlen (program);
 393       gchar *pathext = g_build_path (";",
 394                      ".exe;.cmd;.bat;.com",
 395                      g_getenv ("PATHEXT"),
 396                      NULL);
 397       gchar *p;
 398       gchar *decorated_program;
 399       gchar *retval;
 400 
 401       p = pathext;
 402       do
 403     {
 404       gchar *q = my_strchrnul (p, ';');
 405 
 406       decorated_program = g_malloc (program_length + (q-p) + 1);
 407       memcpy (decorated_program, program, program_length);
 408       memcpy (decorated_program+program_length, p, q-p);
 409       decorated_program [program_length + (q-p)] = '\0';
 410 
 411       retval = inner_find_program_in_path (decorated_program);
 412       g_free (decorated_program);
 413 
 414       if (retval != NULL)
 415         {
 416           g_free (pathext);
 417           return retval;
 418         }
 419       p = q;
 420     } while (*p++ != '\0');
 421       g_free (pathext);
 422       return NULL;
 423     }
 424   else
 425     return inner_find_program_in_path (program);
 426 }
 427 
 428 #endif
 429 
 430 /**
 431  * g_find_program_in_path:
 432  * @program: a program name in the GLib file name encoding
 433  *
 434  * Locates the first executable named @program in the user's path, in the
 435  * same way that execvp() would locate it. Returns an allocated string
 436  * with the absolute path name, or %NULL if the program is not found in
 437  * the path. If @program is already an absolute path, returns a copy of
 438  * @program if @program exists and is executable, and %NULL otherwise.
 439  *
 440  * On Windows, if @program does not have a file type suffix, tries
 441  * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
 442  * the <envar>PATHEXT</envar> environment variable.
 443  *
 444  * On Windows, it looks for the file in the same way as CreateProcess()
 445  * would. This means first in the directory where the executing
 446  * program was loaded from, then in the current directory, then in the
 447  * Windows 32-bit system directory, then in the Windows directory, and
 448  * finally in the directories in the <envar>PATH</envar> environment
 449  * variable. If the program is found, the return value contains the
 450  * full name including the type suffix.
 451  *
 452  * Return value: absolute path, or %NULL
 453  **/
 454 #ifdef G_OS_WIN32
 455 static gchar *
 456 inner_find_program_in_path (const gchar *program)
 457 #else
 458 gchar*
 459 g_find_program_in_path (const gchar *program)
 460 #endif
 461 {
 462   const gchar *path, *p;
 463   gchar *name, *freeme;
 464 #ifdef G_OS_WIN32
 465   const gchar *path_copy;
 466   gchar *filename = NULL, *appdir = NULL;
 467   gchar *sysdir = NULL, *windir = NULL;
 468   int n;
 469   wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
 470     wwindir[MAXPATHLEN];
 471 #endif
 472   gsize len;
 473   gsize pathlen;
 474 
 475   g_return_val_if_fail (program != NULL, NULL);
 476 
 477   /* If it is an absolute path, or a relative path including subdirectories,
 478    * don't look in PATH.
 479    */
 480   if (g_path_is_absolute (program)
 481       || strchr (program, G_DIR_SEPARATOR) != NULL
 482 #ifdef G_OS_WIN32
 483       || strchr (program, '/') != NULL
 484 #endif
 485       )
 486     {
 487       if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
 488       !g_file_test (program, G_FILE_TEST_IS_DIR))
 489         return g_strdup (program);
 490       else
 491         return NULL;
 492     }
 493 
 494   path = g_getenv ("PATH");
 495 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
 496   if (path == NULL)
 497     {
 498       /* There is no `PATH' in the environment.  The default
 499        * search path in GNU libc is the current directory followed by
 500        * the path `confstr' returns for `_CS_PATH'.
 501        */
 502 
 503       /* In GLib we put . last, for security, and don't use the
 504        * unportable confstr(); UNIX98 does not actually specify
 505        * what to search if PATH is unset. POSIX may, dunno.
 506        */
 507 
 508       path = "/bin:/usr/bin:.";
 509     }
 510 #else
 511   n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
 512   if (n > 0 && n < MAXPATHLEN)
 513     filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
 514 
 515   n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
 516   if (n > 0 && n < MAXPATHLEN)
 517     sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
 518 
 519   n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
 520   if (n > 0 && n < MAXPATHLEN)
 521     windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
 522 
 523   if (filename)
 524     {
 525       appdir = g_path_get_dirname (filename);
 526       g_free (filename);
 527     }
 528 
 529   path = g_strdup (path);
 530 
 531   if (windir)
 532     {
 533       const gchar *tem = path;
 534       path = g_strconcat (windir, ";", path, NULL);
 535       g_free ((gchar *) tem);
 536       g_free (windir);
 537     }
 538 
 539   if (sysdir)
 540     {
 541       const gchar *tem = path;
 542       path = g_strconcat (sysdir, ";", path, NULL);
 543       g_free ((gchar *) tem);
 544       g_free (sysdir);
 545     }
 546 
 547   {
 548     const gchar *tem = path;
 549     path = g_strconcat (".;", path, NULL);
 550     g_free ((gchar *) tem);
 551   }
 552 
 553   if (appdir)
 554     {
 555       const gchar *tem = path;
 556       path = g_strconcat (appdir, ";", path, NULL);
 557       g_free ((gchar *) tem);
 558       g_free (appdir);
 559     }
 560 
 561   path_copy = path;
 562 #endif
 563 
 564   len = strlen (program) + 1;
 565   pathlen = strlen (path);
 566   freeme = name = g_malloc (pathlen + len + 1);
 567 #ifdef GSTREAMER_LITE
 568   if (freeme == NULL)
 569       return NULL;
 570 #endif // GSTREAMER_LITE
 571 
 572   /* Copy the file name at the top, including '\0'  */
 573   memcpy (name + pathlen + 1, program, len);
 574   name = name + pathlen;
 575   /* And add the slash before the filename  */
 576   *name = G_DIR_SEPARATOR;
 577 
 578   p = path;
 579   do
 580     {
 581       char *startp;
 582 
 583       path = p;
 584       p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
 585 
 586       if (p == path)
 587         /* Two adjacent colons, or a colon at the beginning or the end
 588          * of `PATH' means to search the current directory.
 589          */
 590         startp = name + 1;
 591       else
 592         startp = memcpy (name - (p - path), path, p - path);
 593 
 594       if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
 595       !g_file_test (startp, G_FILE_TEST_IS_DIR))
 596         {
 597           gchar *ret;
 598           ret = g_strdup (startp);
 599           g_free (freeme);
 600 #ifdef G_OS_WIN32
 601       g_free ((gchar *) path_copy);
 602 #endif
 603           return ret;
 604         }
 605     }
 606   while (*p++ != '\0');
 607 
 608   g_free (freeme);
 609 #ifdef G_OS_WIN32
 610   g_free ((gchar *) path_copy);
 611 #endif
 612 
 613   return NULL;
 614 }
 615 
 616 static gboolean
 617 debug_key_matches (const gchar *key,
 618            const gchar *token,
 619            guint        length)
 620 {
 621   for (; length; length--, key++, token++)
 622     {
 623       char k = (*key   == '_') ? '-' : tolower (*key  );
 624       char t = (*token == '_') ? '-' : tolower (*token);
 625 
 626       if (k != t)
 627         return FALSE;
 628     }
 629 
 630   return *key == '\0';
 631 }
 632 
 633 /**
 634  * g_parse_debug_string:
 635  * @string: a list of debug options separated by colons, spaces, or
 636  * commas, or %NULL.
 637  * @keys: pointer to an array of #GDebugKey which associate
 638  *     strings with bit flags.
 639  * @nkeys: the number of #GDebugKey<!-- -->s in the array.
 640  *
 641  * Parses a string containing debugging options
 642  * into a %guint containing bit flags. This is used
 643  * within GDK and GTK+ to parse the debug options passed on the
 644  * command line or through environment variables.
 645  *
 646  * If @string is equal to "all", all flags are set.  If @string
 647  * is equal to "help", all the available keys in @keys are printed
 648  * out to standard error.
 649  *
 650  * Returns: the combined set of bit flags.
 651  */
 652 guint
 653 g_parse_debug_string  (const gchar     *string,
 654                const GDebugKey *keys,
 655                guint            nkeys)
 656 {
 657   guint i;
 658   guint result = 0;
 659 
 660   if (string == NULL)
 661     return 0;
 662 
 663   /* this function is used by gmem.c/gslice.c initialization code,
 664    * so introducing malloc dependencies here would require adaptions
 665    * of those code portions.
 666    */
 667 
 668   if (!g_ascii_strcasecmp (string, "all"))
 669     {
 670       for (i=0; i<nkeys; i++)
 671     result |= keys[i].value;
 672     }
 673   else if (!g_ascii_strcasecmp (string, "help"))
 674     {
 675       /* using stdio directly for the reason stated above */
 676       fprintf (stderr, "Supported debug values: ");
 677       for (i=0; i<nkeys; i++)
 678     fprintf (stderr, " %s", keys[i].key);
 679       fprintf (stderr, "\n");
 680     }
 681   else
 682     {
 683       const gchar *p = string;
 684       const gchar *q;
 685 
 686       while (*p)
 687     {
 688       q = strpbrk (p, ":;, \t");
 689       if (!q)
 690         q = p + strlen(p);
 691 
 692       for (i = 0; i < nkeys; i++)
 693         if (debug_key_matches (keys[i].key, p, q - p))
 694           result |= keys[i].value;
 695 
 696       p = q;
 697       if (*p)
 698         p++;
 699     }
 700     }
 701 
 702   return result;
 703 }
 704 
 705 /**
 706  * g_basename:
 707  * @file_name: the name of the file.
 708  *
 709  * Gets the name of the file without any leading directory components.
 710  * It returns a pointer into the given file name string.
 711  *
 712  * Return value: the name of the file without any leading directory components.
 713  *
 714  * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
 715  * g_path_get_basename() allocates new memory for the returned string, unlike
 716  * this function which returns a pointer into the argument.
 717  **/
 718 G_CONST_RETURN gchar*
 719 g_basename (const gchar    *file_name)
 720 {
 721   register gchar *base;
 722 
 723   g_return_val_if_fail (file_name != NULL, NULL);
 724 
 725   base = strrchr (file_name, G_DIR_SEPARATOR);
 726 
 727 #ifdef G_OS_WIN32
 728   {
 729     gchar *q = strrchr (file_name, '/');
 730     if (base == NULL || (q != NULL && q > base))
 731     base = q;
 732   }
 733 #endif
 734 
 735   if (base)
 736     return base + 1;
 737 
 738 #ifdef G_OS_WIN32
 739   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
 740     return (gchar*) file_name + 2;
 741 #endif /* G_OS_WIN32 */
 742 
 743   return (gchar*) file_name;
 744 }
 745 
 746 /**
 747  * g_path_get_basename:
 748  * @file_name: the name of the file.
 749  *
 750  * Gets the last component of the filename. If @file_name ends with a
 751  * directory separator it gets the component before the last slash. If
 752  * @file_name consists only of directory separators (and on Windows,
 753  * possibly a drive letter), a single separator is returned. If
 754  * @file_name is empty, it gets ".".
 755  *
 756  * Return value: a newly allocated string containing the last component of
 757  *   the filename.
 758  */
 759 gchar*
 760 g_path_get_basename (const gchar   *file_name)
 761 {
 762   register gssize base;
 763   register gssize last_nonslash;
 764   gsize len;
 765   gchar *retval;
 766 
 767   g_return_val_if_fail (file_name != NULL, NULL);
 768 
 769   if (file_name[0] == '\0')
 770     /* empty string */
 771     return g_strdup (".");
 772 
 773   last_nonslash = strlen (file_name) - 1;
 774 
 775   while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
 776     last_nonslash--;
 777 
 778   if (last_nonslash == -1)
 779     /* string only containing slashes */
 780     return g_strdup (G_DIR_SEPARATOR_S);
 781 
 782 #ifdef G_OS_WIN32
 783   if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
 784     /* string only containing slashes and a drive */
 785     return g_strdup (G_DIR_SEPARATOR_S);
 786 #endif /* G_OS_WIN32 */
 787 
 788   base = last_nonslash;
 789 
 790   while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
 791     base--;
 792 
 793 #ifdef G_OS_WIN32
 794   if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
 795     base = 1;
 796 #endif /* G_OS_WIN32 */
 797 
 798   len = last_nonslash - base;
 799   retval = g_malloc (len + 1);
 800 #ifdef GSTREAMER_LITE
 801   if (retval == NULL)
 802       return NULL;
 803 #endif // GSTREAMER_LITE
 804   memcpy (retval, file_name + base + 1, len);
 805   retval [len] = '\0';
 806   return retval;
 807 }
 808 
 809 /**
 810  * g_path_is_absolute:
 811  * @file_name: a file name.
 812  *
 813  * Returns %TRUE if the given @file_name is an absolute file name.
 814  * Note that this is a somewhat vague concept on Windows.
 815  *
 816  * On POSIX systems, an absolute file name is well-defined. It always
 817  * starts from the single root directory. For example "/usr/local".
 818  *
 819  * On Windows, the concepts of current drive and drive-specific
 820  * current directory introduce vagueness. This function interprets as
 821  * an absolute file name one that either begins with a directory
 822  * separator such as "\Users\tml" or begins with the root on a drive,
 823  * for example "C:\Windows". The first case also includes UNC paths
 824  * such as "\\myserver\docs\foo". In all cases, either slashes or
 825  * backslashes are accepted.
 826  *
 827  * Note that a file name relative to the current drive root does not
 828  * truly specify a file uniquely over time and across processes, as
 829  * the current drive is a per-process value and can be changed.
 830  *
 831  * File names relative the current directory on some specific drive,
 832  * such as "D:foo/bar", are not interpreted as absolute by this
 833  * function, but they obviously are not relative to the normal current
 834  * directory as returned by getcwd() or g_get_current_dir()
 835  * either. Such paths should be avoided, or need to be handled using
 836  * Windows-specific code.
 837  *
 838  * Returns: %TRUE if @file_name is absolute.
 839  */
 840 gboolean
 841 g_path_is_absolute (const gchar *file_name)
 842 {
 843   g_return_val_if_fail (file_name != NULL, FALSE);
 844 
 845   if (G_IS_DIR_SEPARATOR (file_name[0]))
 846     return TRUE;
 847 
 848 #ifdef G_OS_WIN32
 849   /* Recognize drive letter on native Windows */
 850   if (g_ascii_isalpha (file_name[0]) &&
 851       file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
 852     return TRUE;
 853 #endif /* G_OS_WIN32 */
 854 
 855   return FALSE;
 856 }
 857 
 858 /**
 859  * g_path_skip_root:
 860  * @file_name: a file name.
 861  *
 862  * Returns a pointer into @file_name after the root component, i.e. after
 863  * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
 864  * path it returns %NULL.
 865  *
 866  * Returns: a pointer into @file_name after the root component.
 867  */
 868 G_CONST_RETURN gchar*
 869 g_path_skip_root (const gchar *file_name)
 870 {
 871   g_return_val_if_fail (file_name != NULL, NULL);
 872 
 873 #ifdef G_PLATFORM_WIN32
 874   /* Skip \\server\share or //server/share */
 875   if (G_IS_DIR_SEPARATOR (file_name[0]) &&
 876       G_IS_DIR_SEPARATOR (file_name[1]) &&
 877       file_name[2] &&
 878       !G_IS_DIR_SEPARATOR (file_name[2]))
 879     {
 880       gchar *p;
 881 
 882       p = strchr (file_name + 2, G_DIR_SEPARATOR);
 883 #ifdef G_OS_WIN32
 884       {
 885     gchar *q = strchr (file_name + 2, '/');
 886     if (p == NULL || (q != NULL && q < p))
 887       p = q;
 888       }
 889 #endif
 890       if (p &&
 891       p > file_name + 2 &&
 892       p[1])
 893     {
 894       file_name = p + 1;
 895 
 896       while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
 897         file_name++;
 898 
 899       /* Possibly skip a backslash after the share name */
 900       if (G_IS_DIR_SEPARATOR (file_name[0]))
 901         file_name++;
 902 
 903       return (gchar *)file_name;
 904     }
 905     }
 906 #endif
 907 
 908   /* Skip initial slashes */
 909   if (G_IS_DIR_SEPARATOR (file_name[0]))
 910     {
 911       while (G_IS_DIR_SEPARATOR (file_name[0]))
 912     file_name++;
 913       return (gchar *)file_name;
 914     }
 915 
 916 #ifdef G_OS_WIN32
 917   /* Skip X:\ */
 918   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
 919     return (gchar *)file_name + 3;
 920 #endif
 921 
 922   return NULL;
 923 }
 924 
 925 /**
 926  * g_path_get_dirname:
 927  * @file_name: the name of the file.
 928  *
 929  * Gets the directory components of a file name.  If the file name has no
 930  * directory components "." is returned.  The returned string should be
 931  * freed when no longer needed.
 932  *
 933  * Returns: the directory components of the file.
 934  */
 935 gchar*
 936 g_path_get_dirname (const gchar    *file_name)
 937 {
 938   register gchar *base;
 939   register gsize len;
 940 
 941   g_return_val_if_fail (file_name != NULL, NULL);
 942 
 943   base = strrchr (file_name, G_DIR_SEPARATOR);
 944 #ifdef G_OS_WIN32
 945   {
 946     gchar *q = strrchr (file_name, '/');
 947     if (base == NULL || (q != NULL && q > base))
 948     base = q;
 949   }
 950 #endif
 951   if (!base)
 952     {
 953 #ifdef G_OS_WIN32
 954       if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
 955     {
 956       gchar drive_colon_dot[4];
 957 
 958       drive_colon_dot[0] = file_name[0];
 959       drive_colon_dot[1] = ':';
 960       drive_colon_dot[2] = '.';
 961       drive_colon_dot[3] = '\0';
 962 
 963       return g_strdup (drive_colon_dot);
 964     }
 965 #endif
 966     return g_strdup (".");
 967     }
 968 
 969   while (base > file_name && G_IS_DIR_SEPARATOR (*base))
 970     base--;
 971 
 972 #ifdef G_OS_WIN32
 973   /* base points to the char before the last slash.
 974    *
 975    * In case file_name is the root of a drive (X:\) or a child of the
 976    * root of a drive (X:\foo), include the slash.
 977    *
 978    * In case file_name is the root share of an UNC path
 979    * (\\server\share), add a slash, returning \\server\share\ .
 980    *
 981    * In case file_name is a direct child of a share in an UNC path
 982    * (\\server\share\foo), include the slash after the share name,
 983    * returning \\server\share\ .
 984    */
 985   if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
 986     base++;
 987   else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
 988        G_IS_DIR_SEPARATOR (file_name[1]) &&
 989        file_name[2] &&
 990        !G_IS_DIR_SEPARATOR (file_name[2]) &&
 991        base >= file_name + 2)
 992     {
 993       const gchar *p = file_name + 2;
 994       while (*p && !G_IS_DIR_SEPARATOR (*p))
 995     p++;
 996       if (p == base + 1)
 997     {
 998       len = (guint) strlen (file_name) + 1;
 999       base = g_new (gchar, len + 1);
1000       strcpy (base, file_name);
1001       base[len-1] = G_DIR_SEPARATOR;
1002       base[len] = 0;
1003       return base;
1004     }
1005       if (G_IS_DIR_SEPARATOR (*p))
1006     {
1007       p++;
1008       while (*p && !G_IS_DIR_SEPARATOR (*p))
1009         p++;
1010       if (p == base + 1)
1011         base++;
1012     }
1013     }
1014 #endif
1015 
1016   len = (guint) 1 + base - file_name;
1017 
1018   base = g_new (gchar, len + 1);
1019   g_memmove (base, file_name, len);
1020   base[len] = 0;
1021 
1022   return base;
1023 }
1024 
1025 /**
1026  * g_get_current_dir:
1027  *
1028  * Gets the current directory.
1029  * The returned string should be freed when no longer needed. The encoding
1030  * of the returned string is system defined. On Windows, it is always UTF-8.
1031  *
1032  * Returns: the current directory.
1033  */
1034 gchar*
1035 g_get_current_dir (void)
1036 {
1037 #ifdef G_OS_WIN32
1038 
1039   gchar *dir = NULL;
1040   wchar_t dummy[2], *wdir;
1041   int len;
1042 
1043   len = GetCurrentDirectoryW (2, dummy);
1044   wdir = g_new (wchar_t, len);
1045 
1046   if (GetCurrentDirectoryW (len, wdir) == len - 1)
1047     dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
1048 
1049   g_free (wdir);
1050 
1051   if (dir == NULL)
1052     dir = g_strdup ("\\");
1053 
1054   return dir;
1055 
1056 #else
1057 
1058   gchar *buffer = NULL;
1059   gchar *dir = NULL;
1060   static gulong max_len = 0;
1061 
1062   if (max_len == 0)
1063     max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
1064 
1065   /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
1066    * and, if that wasn't bad enough, hangs in doing so.
1067    */
1068 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
1069   buffer = g_new (gchar, max_len + 1);
1070   *buffer = 0;
1071   dir = getwd (buffer);
1072 #else   /* !sun || !HAVE_GETCWD */
1073   while (max_len < G_MAXULONG / 2)
1074     {
1075       g_free (buffer);
1076       buffer = g_new (gchar, max_len + 1);
1077       *buffer = 0;
1078       dir = getcwd (buffer, max_len);
1079 
1080       if (dir || errno != ERANGE)
1081     break;
1082 
1083       max_len *= 2;
1084     }
1085 #endif  /* !sun || !HAVE_GETCWD */
1086 
1087   if (!dir || !*buffer)
1088     {
1089       /* hm, should we g_error() out here?
1090        * this can happen if e.g. "./" has mode \0000
1091        */
1092       buffer[0] = G_DIR_SEPARATOR;
1093       buffer[1] = 0;
1094     }
1095 
1096   dir = g_strdup (buffer);
1097   g_free (buffer);
1098 
1099   return dir;
1100 #endif /* !Win32 */
1101 }
1102 
1103 /**
1104  * g_getenv:
1105  * @variable: the environment variable to get, in the GLib file name encoding.
1106  *
1107  * Returns the value of an environment variable. The name and value
1108  * are in the GLib file name encoding. On UNIX, this means the actual
1109  * bytes which might or might not be in some consistent character set
1110  * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1111  * environment variable's value contains references to other
1112  * environment variables, they are expanded.
1113  *
1114  * Return value: the value of the environment variable, or %NULL if
1115  * the environment variable is not found. The returned string may be
1116  * overwritten by the next call to g_getenv(), g_setenv() or
1117  * g_unsetenv().
1118  **/
1119 G_CONST_RETURN gchar*
1120 g_getenv (const gchar *variable)
1121 {
1122 #ifndef G_OS_WIN32
1123 
1124   g_return_val_if_fail (variable != NULL, NULL);
1125 
1126   return getenv (variable);
1127 
1128 #else /* G_OS_WIN32 */
1129 
1130   GQuark quark;
1131   gchar *value;
1132   wchar_t dummy[2], *wname, *wvalue;
1133   int len;
1134 
1135   g_return_val_if_fail (variable != NULL, NULL);
1136   g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1137 
1138   /* On Windows NT, it is relatively typical that environment
1139    * variables contain references to other environment variables. If
1140    * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1141    * environment variables would be stored in the Registry as
1142    * REG_EXPAND_SZ type values, and would then get automatically
1143    * expanded before a program sees them. But there is broken software
1144    * that stores environment variables as REG_SZ values even if they
1145    * contain references to other environment variables.)
1146    */
1147 
1148   wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1149 
1150   len = GetEnvironmentVariableW (wname, dummy, 2);
1151 
1152   if (len == 0)
1153     {
1154       g_free (wname);
1155       return NULL;
1156     }
1157   else if (len == 1)
1158     len = 2;
1159 
1160   wvalue = g_new (wchar_t, len);
1161 
1162   if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1163     {
1164       g_free (wname);
1165       g_free (wvalue);
1166       return NULL;
1167     }
1168 
1169   if (wcschr (wvalue, L'%') != NULL)
1170     {
1171       wchar_t *tem = wvalue;
1172 
1173       len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1174 
1175       if (len > 0)
1176     {
1177       wvalue = g_new (wchar_t, len);
1178 
1179       if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1180         {
1181           g_free (wvalue);
1182           wvalue = tem;
1183         }
1184       else
1185         g_free (tem);
1186     }
1187     }
1188 
1189   value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1190 
1191   g_free (wname);
1192   g_free (wvalue);
1193 
1194   quark = g_quark_from_string (value);
1195   g_free (value);
1196 
1197   return g_quark_to_string (quark);
1198 
1199 #endif /* G_OS_WIN32 */
1200 }
1201 
1202 /* _g_getenv_nomalloc
1203  * this function does a getenv() without doing any kind of allocation
1204  * through glib. it's suitable for chars <= 127 only (both, for the
1205  * variable name and the contents) and for contents < 1024 chars in
1206  * length. also, it aliases "" to a NULL return value.
1207  **/
1208 const gchar*
1209 _g_getenv_nomalloc (const gchar *variable,
1210                     gchar        buffer[1024])
1211 {
1212   const gchar *retval = getenv (variable);
1213   if (retval && retval[0])
1214     {
1215       gint l = strlen (retval);
1216       if (l < 1024)
1217         {
1218           strncpy (buffer, retval, l);
1219           buffer[l] = 0;
1220           return buffer;
1221         }
1222     }
1223   return NULL;
1224 }
1225 
1226 /**
1227  * g_setenv:
1228  * @variable: the environment variable to set, must not contain '='.
1229  * @value: the value for to set the variable to.
1230  * @overwrite: whether to change the variable if it already exists.
1231  *
1232  * Sets an environment variable. Both the variable's name and value
1233  * should be in the GLib file name encoding. On UNIX, this means that
1234  * they can be any sequence of bytes. On Windows, they should be in
1235  * UTF-8.
1236  *
1237  * Note that on some systems, when variables are overwritten, the memory
1238  * used for the previous variables and its value isn't reclaimed.
1239  *
1240  * Returns: %FALSE if the environment variable couldn't be set.
1241  *
1242  * Since: 2.4
1243  */
1244 gboolean
1245 g_setenv (const gchar *variable,
1246       const gchar *value,
1247       gboolean     overwrite)
1248 {
1249 #ifndef G_OS_WIN32
1250 
1251   gint result;
1252 #ifndef HAVE_SETENV
1253   gchar *string;
1254 #endif
1255 
1256   g_return_val_if_fail (variable != NULL, FALSE);
1257   g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1258 
1259 #ifdef HAVE_SETENV
1260   result = setenv (variable, value, overwrite);
1261 #else
1262   if (!overwrite && getenv (variable) != NULL)
1263     return TRUE;
1264 
1265   /* This results in a leak when you overwrite existing
1266    * settings. It would be fairly easy to fix this by keeping
1267    * our own parallel array or hash table.
1268    */
1269   string = g_strconcat (variable, "=", value, NULL);
1270   result = putenv (string);
1271 #endif
1272   return result == 0;
1273 
1274 #else /* G_OS_WIN32 */
1275 
1276   gboolean retval;
1277   wchar_t *wname, *wvalue, *wassignment;
1278   gchar *tem;
1279 
1280   g_return_val_if_fail (variable != NULL, FALSE);
1281   g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1282   g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1283   g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1284 
1285   if (!overwrite && g_getenv (variable) != NULL)
1286     return TRUE;
1287 
1288   /* We want to (if possible) set both the environment variable copy
1289    * kept by the C runtime and the one kept by the system.
1290    *
1291    * We can't use only the C runtime's putenv or _wputenv() as that
1292    * won't work for arbitrary Unicode strings in a "non-Unicode" app
1293    * (with main() and not wmain()). In a "main()" app the C runtime
1294    * initializes the C runtime's environment table by converting the
1295    * real (wide char) environment variables to system codepage, thus
1296    * breaking those that aren't representable in the system codepage.
1297    *
1298    * As the C runtime's putenv() will also set the system copy, we do
1299    * the putenv() first, then call SetEnvironmentValueW ourselves.
1300    */
1301 
1302   wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1303   wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1304   tem = g_strconcat (variable, "=", value, NULL);
1305   wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1306 
1307   g_free (tem);
1308   _wputenv (wassignment);
1309   g_free (wassignment);
1310 
1311   retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1312 
1313   g_free (wname);
1314   g_free (wvalue);
1315 
1316   return retval;
1317 
1318 #endif /* G_OS_WIN32 */
1319 }
1320 
1321 #ifdef HAVE__NSGETENVIRON
1322 #define environ (*_NSGetEnviron())
1323 #elif !defined(G_OS_WIN32)
1324 
1325 /* According to the Single Unix Specification, environ is not in
1326  * any system header, although unistd.h often declares it.
1327  */
1328 extern char **environ;
1329 #endif
1330 
1331 /**
1332  * g_unsetenv:
1333  * @variable: the environment variable to remove, must not contain '='.
1334  *
1335  * Removes an environment variable from the environment.
1336  *
1337  * Note that on some systems, when variables are overwritten, the memory
1338  * used for the previous variables and its value isn't reclaimed.
1339  * Furthermore, this function can't be guaranteed to operate in a
1340  * threadsafe way.
1341  *
1342  * Since: 2.4
1343  **/
1344 void
1345 g_unsetenv (const gchar *variable)
1346 {
1347 #ifndef G_OS_WIN32
1348 
1349 #ifdef HAVE_UNSETENV
1350   g_return_if_fail (variable != NULL);
1351   g_return_if_fail (strchr (variable, '=') == NULL);
1352 
1353   unsetenv (variable);
1354 #else /* !HAVE_UNSETENV */
1355   int len;
1356   gchar **e, **f;
1357 
1358   g_return_if_fail (variable != NULL);
1359   g_return_if_fail (strchr (variable, '=') == NULL);
1360 
1361   len = strlen (variable);
1362 
1363   /* Mess directly with the environ array.
1364    * This seems to be the only portable way to do this.
1365    *
1366    * Note that we remove *all* environment entries for
1367    * the variable name, not just the first.
1368    */
1369   e = f = environ;
1370   while (*e != NULL)
1371     {
1372       if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1373     {
1374       *f = *e;
1375       f++;
1376     }
1377       e++;
1378     }
1379   *f = NULL;
1380 #endif /* !HAVE_UNSETENV */
1381 
1382 #else  /* G_OS_WIN32 */
1383 
1384   wchar_t *wname, *wassignment;
1385   gchar *tem;
1386 
1387   g_return_if_fail (variable != NULL);
1388   g_return_if_fail (strchr (variable, '=') == NULL);
1389   g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1390 
1391   wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1392   tem = g_strconcat (variable, "=", NULL);
1393   wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1394 
1395   g_free (tem);
1396   _wputenv (wassignment);
1397   g_free (wassignment);
1398 
1399   SetEnvironmentVariableW (wname, NULL);
1400 
1401   g_free (wname);
1402 
1403 #endif /* G_OS_WIN32 */
1404 }
1405 
1406 /**
1407  * g_listenv:
1408  *
1409  * Gets the names of all variables set in the environment.
1410  *
1411  * Returns: (array zero-terminated=1) (transfer full): a %NULL-terminated list of strings which must be freed
1412  * with g_strfreev().
1413  *
1414  * Programs that want to be portable to Windows should typically use
1415  * this function and g_getenv() instead of using the environ array
1416  * from the C library directly. On Windows, the strings in the environ
1417  * array are in system codepage encoding, while in most of the typical
1418  * use cases for environment variables in GLib-using programs you want
1419  * the UTF-8 encoding that this function and g_getenv() provide.
1420  *
1421  * Since: 2.8
1422  */
1423 gchar **
1424 g_listenv (void)
1425 {
1426 #ifndef G_OS_WIN32
1427   gchar **result, *eq;
1428   gint len, i, j;
1429 
1430   len = g_strv_length (environ);
1431   result = g_new0 (gchar *, len + 1);
1432 
1433   j = 0;
1434   for (i = 0; i < len; i++)
1435     {
1436       eq = strchr (environ[i], '=');
1437       if (eq)
1438     result[j++] = g_strndup (environ[i], eq - environ[i]);
1439     }
1440 
1441   result[j] = NULL;
1442 
1443   return result;
1444 #else
1445   gchar **result, *eq;
1446   gint len = 0, j;
1447   wchar_t *p, *q;
1448 
1449   p = (wchar_t *) GetEnvironmentStringsW ();
1450   if (p != NULL)
1451     {
1452       q = p;
1453       while (*q)
1454     {
1455       q += wcslen (q) + 1;
1456       len++;
1457     }
1458     }
1459   result = g_new0 (gchar *, len + 1);
1460 
1461   j = 0;
1462   q = p;
1463   while (*q)
1464     {
1465       result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1466       if (result[j] != NULL)
1467     {
1468       eq = strchr (result[j], '=');
1469       if (eq && eq > result[j])
1470         {
1471           *eq = '\0';
1472           j++;
1473         }
1474       else
1475         g_free (result[j]);
1476     }
1477       q += wcslen (q) + 1;
1478     }
1479   result[j] = NULL;
1480   FreeEnvironmentStringsW (p);
1481 
1482   return result;
1483 #endif
1484 }
1485 
1486 /**
1487  * g_get_environ:
1488  *
1489  * Gets the list of environment variables for the current process.  The
1490  * list is %NULL terminated and each item in the list is of the form
1491  * 'NAME=VALUE'.
1492  *
1493  * This is equivalent to direct access to the 'environ' global variable,
1494  * except portable.
1495  *
1496  * The return value is freshly allocated and it should be freed with
1497  * g_strfreev() when it is no longer needed.
1498  *
1499  * Returns: (array zero-terminated=1) (transfer full): the list of environment variables
1500  *
1501  * Since: 2.28
1502  */
1503 gchar **
1504 g_get_environ (void)
1505 {
1506 #ifndef G_OS_WIN32
1507   return g_strdupv (environ);
1508 #else
1509   gunichar2 *strings;
1510   gchar **result;
1511   gint i, n;
1512 
1513   strings = GetEnvironmentStringsW ();
1514   for (n = 0; strings[n]; n += wcslen (strings + n) + 1);
1515   result = g_new (char *, n + 1);
1516   for (i = 0; strings[i]; i += wcslen (strings + i) + 1)
1517     result[i] = g_utf16_to_utf8 (strings + i, -1, NULL, NULL, NULL);
1518   FreeEnvironmentStringsW (strings);
1519   result[i] = NULL;
1520 
1521   return result;
1522 #endif
1523 }
1524 
1525 G_LOCK_DEFINE_STATIC (g_utils_global);
1526 
1527 static  gchar   *g_tmp_dir = NULL;
1528 static  gchar   *g_user_name = NULL;
1529 static  gchar   *g_real_name = NULL;
1530 static  gchar   *g_home_dir = NULL;
1531 static  gchar   *g_host_name = NULL;
1532 
1533 #ifdef G_OS_WIN32
1534 /* System codepage versions of the above, kept at file level so that they,
1535  * too, are produced only once.
1536  */
1537 static  gchar   *g_tmp_dir_cp = NULL;
1538 static  gchar   *g_user_name_cp = NULL;
1539 static  gchar   *g_real_name_cp = NULL;
1540 static  gchar   *g_home_dir_cp = NULL;
1541 #endif
1542 
1543 static  gchar   *g_user_data_dir = NULL;
1544 static  gchar  **g_system_data_dirs = NULL;
1545 static  gchar   *g_user_cache_dir = NULL;
1546 static  gchar   *g_user_config_dir = NULL;
1547 static  gchar  **g_system_config_dirs = NULL;
1548 
1549 static  gchar  **g_user_special_dirs = NULL;
1550 
1551 /* fifteen minutes of fame for everybody */
1552 #define G_USER_DIRS_EXPIRE      15 * 60
1553 
1554 #ifdef G_OS_WIN32
1555 
1556 static gchar *
1557 get_special_folder (int csidl)
1558 {
1559   wchar_t path[MAX_PATH+1];
1560   HRESULT hr;
1561   LPITEMIDLIST pidl = NULL;
1562   BOOL b;
1563   gchar *retval = NULL;
1564 
1565   hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1566   if (hr == S_OK)
1567     {
1568       b = SHGetPathFromIDListW (pidl, path);
1569       if (b)
1570     retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1571       CoTaskMemFree (pidl);
1572     }
1573   return retval;
1574 }
1575 
1576 static char *
1577 get_windows_directory_root (void)
1578 {
1579   wchar_t wwindowsdir[MAX_PATH];
1580 
1581   if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1582     {
1583       /* Usually X:\Windows, but in terminal server environments
1584        * might be an UNC path, AFAIK.
1585        */
1586       char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1587       char *p;
1588 
1589       if (windowsdir == NULL)
1590     return g_strdup ("C:\\");
1591 
1592       p = (char *) g_path_skip_root (windowsdir);
1593 #ifdef GSTREAMER_LITE
1594       if (p == NULL)
1595         return g_strdup ("C:\\");
1596 #endif // GSTREAMER_LITE
1597       if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1598     p--;
1599       *p = '\0';
1600       return windowsdir;
1601     }
1602   else
1603     return g_strdup ("C:\\");
1604 }
1605 
1606 #endif
1607 
1608 /* HOLDS: g_utils_global_lock */
1609 static void
1610 g_get_any_init_do (void)
1611 {
1612   gchar hostname[100];
1613 
1614   g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1615   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1616     g_tmp_dir = g_strdup (g_getenv ("TMP"));
1617   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1618     g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1619 
1620 #ifdef G_OS_WIN32
1621   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1622     g_tmp_dir = get_windows_directory_root ();
1623 #else
1624 #ifdef P_tmpdir
1625   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1626     {
1627       gsize k;
1628       g_tmp_dir = g_strdup (P_tmpdir);
1629       k = strlen (g_tmp_dir);
1630       if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1631     g_tmp_dir[k - 1] = '\0';
1632     }
1633 #endif
1634 
1635   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1636     {
1637       g_tmp_dir = g_strdup ("/tmp");
1638     }
1639 #endif  /* !G_OS_WIN32 */
1640 
1641 #ifdef G_OS_WIN32
1642   /* We check $HOME first for Win32, though it is a last resort for Unix
1643    * where we prefer the results of getpwuid().
1644    */
1645   g_home_dir = g_strdup (g_getenv ("HOME"));
1646 
1647   /* Only believe HOME if it is an absolute path and exists */
1648   if (g_home_dir)
1649     {
1650       if (!(g_path_is_absolute (g_home_dir) &&
1651         g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1652     {
1653       g_free (g_home_dir);
1654       g_home_dir = NULL;
1655     }
1656     }
1657 
1658   /* In case HOME is Unix-style (it happens), convert it to
1659    * Windows style.
1660    */
1661   if (g_home_dir)
1662     {
1663       gchar *p;
1664       while ((p = strchr (g_home_dir, '/')) != NULL)
1665     *p = '\\';
1666     }
1667 
1668   if (!g_home_dir)
1669     {
1670       /* USERPROFILE is probably the closest equivalent to $HOME? */
1671       if (g_getenv ("USERPROFILE") != NULL)
1672     g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1673     }
1674 
1675   if (!g_home_dir)
1676     g_home_dir = get_special_folder (CSIDL_PROFILE);
1677 
1678   if (!g_home_dir)
1679     g_home_dir = get_windows_directory_root ();
1680 #endif /* G_OS_WIN32 */
1681 
1682 #ifdef HAVE_PWD_H
1683   {
1684     struct passwd *pw = NULL;
1685     gpointer buffer = NULL;
1686     gint error;
1687     gchar *logname;
1688 
1689 #  if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1690     struct passwd pwd;
1691 #    ifdef _SC_GETPW_R_SIZE_MAX
1692     /* This reurns the maximum length */
1693     glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1694 
1695     if (bufsize < 0)
1696       bufsize = 64;
1697 #    else /* _SC_GETPW_R_SIZE_MAX */
1698     glong bufsize = 64;
1699 #    endif /* _SC_GETPW_R_SIZE_MAX */
1700 
1701     logname = (gchar *) g_getenv ("LOGNAME");
1702 
1703     do
1704       {
1705     g_free (buffer);
1706     /* we allocate 6 extra bytes to work around a bug in
1707      * Mac OS < 10.3. See #156446
1708      */
1709     buffer = g_malloc (bufsize + 6);
1710     errno = 0;
1711 
1712 #    ifdef HAVE_POSIX_GETPWUID_R
1713     if (logname) {
1714       error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1715       if (!pw || (pw->pw_uid != getuid ())) {
1716         /* LOGNAME is lying, fall back to looking up the uid */
1717         error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1718       }
1719     } else {
1720       error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1721     }
1722     error = error < 0 ? errno : error;
1723 #    else /* HAVE_NONPOSIX_GETPWUID_R */
1724    /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1725 #      if defined(_AIX) || defined(__hpux)
1726     error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1727     pw = error == 0 ? &pwd : NULL;
1728 #      else /* !_AIX */
1729     if (logname) {
1730       pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1731       if (!pw || (pw->pw_uid != getuid ())) {
1732         /* LOGNAME is lying, fall back to looking up the uid */
1733         pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1734       }
1735     } else {
1736       pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1737     }
1738     error = pw ? 0 : errno;
1739 #      endif /* !_AIX */
1740 #    endif /* HAVE_NONPOSIX_GETPWUID_R */
1741 
1742     if (!pw)
1743       {
1744         /* we bail out prematurely if the user id can't be found
1745          * (should be pretty rare case actually), or if the buffer
1746          * should be sufficiently big and lookups are still not
1747          * successfull.
1748          */
1749         if (error == 0 || error == ENOENT)
1750           {
1751         g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1752                (gulong) getuid ());
1753         break;
1754           }
1755         if (bufsize > 32 * 1024)
1756           {
1757         g_warning ("getpwuid_r(): failed due to: %s.",
1758                g_strerror (error));
1759         break;
1760           }
1761 
1762         bufsize *= 2;
1763       }
1764       }
1765     while (!pw);
1766 #  endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1767 
1768     if (!pw)
1769       {
1770     setpwent ();
1771     pw = getpwuid (getuid ());
1772     endpwent ();
1773       }
1774     if (pw)
1775       {
1776     g_user_name = g_strdup (pw->pw_name);
1777 
1778     if (pw->pw_gecos && *pw->pw_gecos != '\0')
1779       {
1780         gchar **gecos_fields;
1781         gchar **name_parts;
1782 
1783         /* split the gecos field and substitute '&' */
1784         gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1785         name_parts = g_strsplit (gecos_fields[0], "&", 0);
1786         pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1787         g_real_name = g_strjoinv (pw->pw_name, name_parts);
1788         g_strfreev (gecos_fields);
1789         g_strfreev (name_parts);
1790       }
1791 
1792     if (!g_home_dir)
1793       g_home_dir = g_strdup (pw->pw_dir);
1794       }
1795     g_free (buffer);
1796   }
1797 
1798 #else /* !HAVE_PWD_H */
1799 
1800 #ifdef G_OS_WIN32
1801   {
1802     guint len = UNLEN+1;
1803     wchar_t buffer[UNLEN+1];
1804 
1805     if (GetUserNameW (buffer, (LPDWORD) &len))
1806       {
1807     g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1808     g_real_name = g_strdup (g_user_name);
1809       }
1810   }
1811 #endif /* G_OS_WIN32 */
1812 
1813 #endif /* !HAVE_PWD_H */
1814 
1815 #ifndef G_OS_WIN32
1816   if (!g_home_dir)
1817     g_home_dir = g_strdup (g_getenv ("HOME"));
1818 #endif
1819 
1820 #ifdef __EMX__
1821   /* change '\\' in %HOME% to '/' */
1822   g_strdelimit (g_home_dir, "\\",'/');
1823 #endif
1824   if (!g_user_name)
1825     g_user_name = g_strdup ("somebody");
1826   if (!g_real_name)
1827     g_real_name = g_strdup ("Unknown");
1828 
1829   {
1830 #ifndef G_OS_WIN32
1831     gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1832 #else
1833     DWORD size = sizeof (hostname);
1834     gboolean hostname_fail = (!GetComputerName (hostname, &size));
1835 #endif
1836     g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1837   }
1838 
1839 #ifdef G_OS_WIN32
1840   g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1841   g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1842   g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1843 
1844   if (!g_tmp_dir_cp)
1845     g_tmp_dir_cp = g_strdup ("\\");
1846   if (!g_user_name_cp)
1847     g_user_name_cp = g_strdup ("somebody");
1848   if (!g_real_name_cp)
1849     g_real_name_cp = g_strdup ("Unknown");
1850 
1851   /* home_dir might be NULL, unlike tmp_dir, user_name and
1852    * real_name.
1853    */
1854   if (g_home_dir)
1855     g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1856   else
1857     g_home_dir_cp = NULL;
1858 #endif /* G_OS_WIN32 */
1859 }
1860 
1861 static inline void
1862 g_get_any_init (void)
1863 {
1864   if (!g_tmp_dir)
1865     g_get_any_init_do ();
1866 }
1867 
1868 static inline void
1869 g_get_any_init_locked (void)
1870 {
1871   G_LOCK (g_utils_global);
1872   g_get_any_init ();
1873   G_UNLOCK (g_utils_global);
1874 }
1875 
1876 
1877 /**
1878  * g_get_user_name:
1879  *
1880  * Gets the user name of the current user. The encoding of the returned
1881  * string is system-defined. On UNIX, it might be the preferred file name
1882  * encoding, or something else, and there is no guarantee that it is even
1883  * consistent on a machine. On Windows, it is always UTF-8.
1884  *
1885  * Returns: the user name of the current user.
1886  */
1887 G_CONST_RETURN gchar*
1888 g_get_user_name (void)
1889 {
1890   g_get_any_init_locked ();
1891   return g_user_name;
1892 }
1893 
1894 /**
1895  * g_get_real_name:
1896  *
1897  * Gets the real name of the user. This usually comes from the user's entry
1898  * in the <filename>passwd</filename> file. The encoding of the returned
1899  * string is system-defined. (On Windows, it is, however, always UTF-8.)
1900  * If the real user name cannot be determined, the string "Unknown" is
1901  * returned.
1902  *
1903  * Returns: the user's real name.
1904  */
1905 G_CONST_RETURN gchar*
1906 g_get_real_name (void)
1907 {
1908   g_get_any_init_locked ();
1909   return g_real_name;
1910 }
1911 
1912 /**
1913  * g_get_home_dir:
1914  *
1915  * Gets the current user's home directory as defined in the
1916  * password database.
1917  *
1918  * Note that in contrast to traditional UNIX tools, this function
1919  * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1920  * environment variable.
1921  *
1922  * One of the reasons for this decision is that applications in many
1923  * cases need special handling to deal with the case where
1924  * <envar>HOME</envar> is
1925  * <simplelist>
1926  *   <member>Not owned by the user</member>
1927  *   <member>Not writeable</member>
1928  *   <member>Not even readable</member>
1929  * </simplelist>
1930  * Since applications are in general <emphasis>not</emphasis> written
1931  * to deal with these situations it was considered better to make
1932  * g_get_home_dir() not pay attention to <envar>HOME</envar> and to
1933  * return the real home directory for the user. If applications
1934  * want to pay attention to <envar>HOME</envar>, they can do:
1935  * |[
1936  *  const char *homedir = g_getenv ("HOME");
1937  *   if (!homedir)
1938  *      homedir = g_get_home_dir (<!-- -->);
1939  * ]|
1940  *
1941  * Returns: the current user's home directory
1942  */
1943 G_CONST_RETURN gchar*
1944 g_get_home_dir (void)
1945 {
1946   g_get_any_init_locked ();
1947   return g_home_dir;
1948 }
1949 
1950 /**
1951  * g_get_tmp_dir:
1952  *
1953  * Gets the directory to use for temporary files. This is found from
1954  * inspecting the environment variables <envar>TMPDIR</envar>,
1955  * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1956  * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1957  * The encoding of the returned string is system-defined. On Windows,
1958  * it is always UTF-8. The return value is never %NULL or the empty string.
1959  *
1960  * Returns: the directory to use for temporary files.
1961  */
1962 G_CONST_RETURN gchar*
1963 g_get_tmp_dir (void)
1964 {
1965   g_get_any_init_locked ();
1966   return g_tmp_dir;
1967 }
1968 
1969 /**
1970  * g_get_host_name:
1971  *
1972  * Return a name for the machine.
1973  *
1974  * The returned name is not necessarily a fully-qualified domain name,
1975  * or even present in DNS or some other name service at all. It need
1976  * not even be unique on your local network or site, but usually it
1977  * is. Callers should not rely on the return value having any specific
1978  * properties like uniqueness for security purposes. Even if the name
1979  * of the machine is changed while an application is running, the
1980  * return value from this function does not change. The returned
1981  * string is owned by GLib and should not be modified or freed. If no
1982  * name can be determined, a default fixed string "localhost" is
1983  * returned.
1984  *
1985  * Returns: the host name of the machine.
1986  *
1987  * Since: 2.8
1988  */
1989 const gchar *
1990 g_get_host_name (void)
1991 {
1992   g_get_any_init_locked ();
1993   return g_host_name;
1994 }
1995 
1996 G_LOCK_DEFINE_STATIC (g_prgname);
1997 static gchar *g_prgname = NULL;
1998 
1999 /**
2000  * g_get_prgname:
2001  *
2002  * Gets the name of the program. This name should <emphasis>not</emphasis>
2003  * be localized, contrast with g_get_application_name().
2004  * (If you are using GDK or GTK+ the program name is set in gdk_init(),
2005  * which is called by gtk_init(). The program name is found by taking
2006  * the last component of <literal>argv[0]</literal>.)
2007  *
2008  * Returns: the name of the program. The returned string belongs
2009  * to GLib and must not be modified or freed.
2010  */
2011 gchar*
2012 g_get_prgname (void)
2013 {
2014   gchar* retval;
2015 
2016   G_LOCK (g_prgname);
2017 #ifdef G_OS_WIN32
2018   if (g_prgname == NULL)
2019     {
2020       static gboolean beenhere = FALSE;
2021 
2022       if (!beenhere)
2023     {
2024       gchar *utf8_buf = NULL;
2025       wchar_t buf[MAX_PATH+1];
2026 
2027       beenhere = TRUE;
2028       if (GetModuleFileNameW (GetModuleHandle (NULL),
2029                   buf, G_N_ELEMENTS (buf)) > 0)
2030         utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
2031 
2032       if (utf8_buf)
2033         {
2034           g_prgname = g_path_get_basename (utf8_buf);
2035           g_free (utf8_buf);
2036         }
2037     }
2038     }
2039 #endif
2040   retval = g_prgname;
2041   G_UNLOCK (g_prgname);
2042 
2043   return retval;
2044 }
2045 
2046 /**
2047  * g_set_prgname:
2048  * @prgname: the name of the program.
2049  *
2050  * Sets the name of the program. This name should <emphasis>not</emphasis>
2051  * be localized, contrast with g_set_application_name(). Note that for
2052  * thread-safety reasons this function can only be called once.
2053  */
2054 void
2055 g_set_prgname (const gchar *prgname)
2056 {
2057   G_LOCK (g_prgname);
2058   g_free (g_prgname);
2059   g_prgname = g_strdup (prgname);
2060   G_UNLOCK (g_prgname);
2061 }
2062 
2063 G_LOCK_DEFINE_STATIC (g_application_name);
2064 static gchar *g_application_name = NULL;
2065 
2066 /**
2067  * g_get_application_name:
2068  *
2069  * Gets a human-readable name for the application, as set by
2070  * g_set_application_name(). This name should be localized if
2071  * possible, and is intended for display to the user.  Contrast with
2072  * g_get_prgname(), which gets a non-localized name. If
2073  * g_set_application_name() has not been called, returns the result of
2074  * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
2075  * been called).
2076  *
2077  * Return value: human-readable application name. may return %NULL
2078  *
2079  * Since: 2.2
2080  **/
2081 G_CONST_RETURN gchar*
2082 g_get_application_name (void)
2083 {
2084   gchar* retval;
2085 
2086   G_LOCK (g_application_name);
2087   retval = g_application_name;
2088   G_UNLOCK (g_application_name);
2089 
2090   if (retval == NULL)
2091     return g_get_prgname ();
2092 
2093   return retval;
2094 }
2095 
2096 /**
2097  * g_set_application_name:
2098  * @application_name: localized name of the application
2099  *
2100  * Sets a human-readable name for the application. This name should be
2101  * localized if possible, and is intended for display to the user.
2102  * Contrast with g_set_prgname(), which sets a non-localized name.
2103  * g_set_prgname() will be called automatically by gtk_init(),
2104  * but g_set_application_name() will not.
2105  *
2106  * Note that for thread safety reasons, this function can only
2107  * be called once.
2108  *
2109  * The application name will be used in contexts such as error messages,
2110  * or when displaying an application's name in the task list.
2111  *
2112  * Since: 2.2
2113  **/
2114 void
2115 g_set_application_name (const gchar *application_name)
2116 {
2117   gboolean already_set = FALSE;
2118 
2119   G_LOCK (g_application_name);
2120   if (g_application_name)
2121     already_set = TRUE;
2122   else
2123     g_application_name = g_strdup (application_name);
2124   G_UNLOCK (g_application_name);
2125 
2126   if (already_set)
2127     g_warning ("g_set_application_name() called multiple times");
2128 }
2129 
2130 /**
2131  * g_get_user_data_dir:
2132  *
2133  * Returns a base directory in which to access application data such
2134  * as icons that is customized for a particular user.
2135  *
2136  * On UNIX platforms this is determined using the mechanisms described in
2137  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2138  * XDG Base Directory Specification</ulink>.
2139  * In this case the directory retrieved will be XDG_DATA_HOME.
2140  *
2141  * On Windows this is the folder to use for local (as opposed to
2142  * roaming) application data. See documentation for
2143  * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2144  * what g_get_user_config_dir() returns.
2145  *
2146  * Return value: a string owned by GLib that must not be modified
2147  *               or freed.
2148  * Since: 2.6
2149  **/
2150 G_CONST_RETURN gchar*
2151 g_get_user_data_dir (void)
2152 {
2153   gchar *data_dir;
2154 
2155   G_LOCK (g_utils_global);
2156 
2157   if (!g_user_data_dir)
2158     {
2159 #ifdef G_OS_WIN32
2160       data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2161 #else
2162       data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2163 
2164       if (data_dir && data_dir[0])
2165         data_dir = g_strdup (data_dir);
2166 #endif
2167       if (!data_dir || !data_dir[0])
2168     {
2169       g_get_any_init ();
2170 
2171       if (g_home_dir)
2172         data_dir = g_build_filename (g_home_dir, ".local",
2173                      "share", NULL);
2174       else
2175         data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
2176                      "share", NULL);
2177     }
2178 
2179       g_user_data_dir = data_dir;
2180     }
2181   else
2182     data_dir = g_user_data_dir;
2183 
2184   G_UNLOCK (g_utils_global);
2185 
2186   return data_dir;
2187 }
2188 
2189 static void
2190 g_init_user_config_dir (void)
2191 {
2192   gchar *config_dir;
2193 
2194   if (!g_user_config_dir)
2195     {
2196 #ifdef G_OS_WIN32
2197       config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2198 #else
2199       config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2200 
2201       if (config_dir && config_dir[0])
2202     config_dir = g_strdup (config_dir);
2203 #endif
2204       if (!config_dir || !config_dir[0])
2205     {
2206       g_get_any_init ();
2207 
2208       if (g_home_dir)
2209         config_dir = g_build_filename (g_home_dir, ".config", NULL);
2210       else
2211         config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2212     }
2213 
2214       g_user_config_dir = config_dir;
2215     }
2216 }
2217 
2218 /**
2219  * g_get_user_config_dir:
2220  *
2221  * Returns a base directory in which to store user-specific application
2222  * configuration information such as user preferences and settings.
2223  *
2224  * On UNIX platforms this is determined using the mechanisms described in
2225  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2226  * XDG Base Directory Specification</ulink>.
2227  * In this case the directory retrieved will be XDG_CONFIG_HOME.
2228  *
2229  * On Windows this is the folder to use for local (as opposed to
2230  * roaming) application data. See documentation for
2231  * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2232  * what g_get_user_data_dir() returns.
2233  *
2234  * Return value: a string owned by GLib that must not be modified
2235  *               or freed.
2236  * Since: 2.6
2237  **/
2238 G_CONST_RETURN gchar*
2239 g_get_user_config_dir (void)
2240 {
2241   G_LOCK (g_utils_global);
2242 
2243   g_init_user_config_dir ();
2244 
2245   G_UNLOCK (g_utils_global);
2246 
2247   return g_user_config_dir;
2248 }
2249 
2250 /**
2251  * g_get_user_cache_dir:
2252  *
2253  * Returns a base directory in which to store non-essential, cached
2254  * data specific to particular user.
2255  *
2256  * On UNIX platforms this is determined using the mechanisms described in
2257  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2258  * XDG Base Directory Specification</ulink>.
2259  * In this case the directory retrieved will be XDG_CACHE_HOME.
2260  *
2261  * On Windows is the directory that serves as a common repository for
2262  * temporary Internet files. A typical path is
2263  * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
2264  * See documentation for CSIDL_INTERNET_CACHE.
2265  *
2266  * Return value: a string owned by GLib that must not be modified
2267  *               or freed.
2268  * Since: 2.6
2269  **/
2270 G_CONST_RETURN gchar*
2271 g_get_user_cache_dir (void)
2272 {
2273   gchar *cache_dir;
2274 
2275   G_LOCK (g_utils_global);
2276 
2277   if (!g_user_cache_dir)
2278     {
2279 #ifdef G_OS_WIN32
2280       cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2281 #else
2282       cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2283 
2284       if (cache_dir && cache_dir[0])
2285           cache_dir = g_strdup (cache_dir);
2286 #endif
2287       if (!cache_dir || !cache_dir[0])
2288     {
2289       g_get_any_init ();
2290 
2291       if (g_home_dir)
2292         cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2293       else
2294         cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2295     }
2296       g_user_cache_dir = cache_dir;
2297     }
2298   else
2299     cache_dir = g_user_cache_dir;
2300 
2301   G_UNLOCK (g_utils_global);
2302 
2303   return cache_dir;
2304 }
2305 
2306 /**
2307  * g_get_user_runtime_dir:
2308  *
2309  * Returns a directory that is unique to the current user on the local
2310  * system.
2311  *
2312  * On UNIX platforms this is determined using the mechanisms described in
2313  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2314  * XDG Base Directory Specification</ulink>.  This is the directory
2315  * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
2316  * In the case that this variable is not set, GLib will issue a warning
2317  * message to stderr and return the value of g_get_user_cache_dir().
2318  *
2319  * On Windows this is the folder to use for local (as opposed to
2320  * roaming) application data. See documentation for
2321  * CSIDL_LOCAL_APPDATA.  Note that on Windows it thus is the same as
2322  * what g_get_user_config_dir() returns.
2323  *
2324  * Returns: a string owned by GLib that must not be modified or freed.
2325  *
2326  * Since: 2.28
2327  **/
2328 const gchar *
2329 g_get_user_runtime_dir (void)
2330 {
2331 #ifndef G_OS_WIN32
2332   static const gchar *runtime_dir;
2333   static gsize initialised;
2334 
2335   if (g_once_init_enter (&initialised))
2336     {
2337       runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
2338 
2339       if (runtime_dir == NULL)
2340         g_warning ("XDG_RUNTIME_DIR variable not set.  "
2341                    "Falling back to XDG cache dir.");
2342 
2343       g_once_init_leave (&initialised, 1);
2344     }
2345 
2346   if (runtime_dir)
2347     return runtime_dir;
2348 
2349   /* Both fallback for UNIX and the default
2350    * in Windows: use the user cache directory.
2351    */
2352 #endif
2353 
2354   return g_get_user_cache_dir ();
2355 }
2356 
2357 #ifdef HAVE_CARBON
2358 
2359 static gchar *
2360 find_folder (OSType type)
2361 {
2362   gchar *filename = NULL;
2363   FSRef  found;
2364 
2365   if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2366     {
2367       CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2368 
2369       if (url)
2370     {
2371       CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2372 
2373       if (path)
2374         {
2375           filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2376 
2377           if (! filename)
2378         {
2379           filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2380 
2381           CFStringGetCString (path, filename,
2382                       CFStringGetLength (path) * 3 + 1,
2383                       kCFStringEncodingUTF8);
2384         }
2385 
2386           CFRelease (path);
2387         }
2388 
2389       CFRelease (url);
2390     }
2391     }
2392 
2393   return filename;
2394 }
2395 
2396 static void
2397 load_user_special_dirs (void)
2398 {
2399   g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2400   g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2401   g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2402   g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2403   g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2404   g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2405   g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2406   g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2407 }
2408 
2409 #endif /* HAVE_CARBON */
2410 
2411 #if defined(G_OS_WIN32)
2412 static void
2413 load_user_special_dirs (void)
2414 {
2415   typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
2416                             DWORD dwFlags,
2417                             HANDLE hToken,
2418                             PWSTR *ppszPath);
2419   t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
2420 
2421   static const GUID FOLDERID_Downloads =
2422     { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
2423   static const GUID FOLDERID_Public =
2424     { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
2425 
2426   wchar_t *wcp;
2427 
2428   p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
2429                                     "SHGetKnownFolderPath");
2430 
2431   g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2432   g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2433 
2434   if (p_SHGetKnownFolderPath == NULL)
2435     {
2436       g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2437     }
2438   else
2439     {
2440       wcp = NULL;
2441       (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
2442       if (wcp)
2443         {
2444           g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2445           if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
2446               g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2447           CoTaskMemFree (wcp);
2448         }
2449       else
2450           g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2451     }
2452 
2453   g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2454   g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2455 
2456   if (p_SHGetKnownFolderPath == NULL)
2457     {
2458       /* XXX */
2459       g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2460     }
2461   else
2462     {
2463       wcp = NULL;
2464       (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
2465       if (wcp)
2466         {
2467           g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2468           if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
2469               g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2470           CoTaskMemFree (wcp);
2471         }
2472       else
2473           g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2474     }
2475 
2476   g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2477   g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2478 }
2479 #endif /* G_OS_WIN32 */
2480 
2481 static void g_init_user_config_dir (void);
2482 
2483 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2484 
2485 /* adapted from xdg-user-dir-lookup.c
2486  *
2487  * Copyright (C) 2007 Red Hat Inc.
2488  *
2489  * Permission is hereby granted, free of charge, to any person
2490  * obtaining a copy of this software and associated documentation files
2491  * (the "Software"), to deal in the Software without restriction,
2492  * including without limitation the rights to use, copy, modify, merge,
2493  * publish, distribute, sublicense, and/or sell copies of the Software,
2494  * and to permit persons to whom the Software is furnished to do so,
2495  * subject to the following conditions:
2496  *
2497  * The above copyright notice and this permission notice shall be
2498  * included in all copies or substantial portions of the Software.
2499  *
2500  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2501  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2502  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2503  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2504  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2505  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2506  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2507  * SOFTWARE.
2508  */
2509 static void
2510 load_user_special_dirs (void)
2511 {
2512   gchar *config_file;
2513   gchar *data;
2514   gchar **lines;
2515   gint n_lines, i;
2516 
2517   g_init_user_config_dir ();
2518   config_file = g_build_filename (g_user_config_dir,
2519                                   "user-dirs.dirs",
2520                                   NULL);
2521 
2522   if (!g_file_get_contents (config_file, &data, NULL, NULL))
2523     {
2524       g_free (config_file);
2525       return;
2526     }
2527 
2528   lines = g_strsplit (data, "\n", -1);
2529   n_lines = g_strv_length (lines);
2530   g_free (data);
2531 
2532   for (i = 0; i < n_lines; i++)
2533     {
2534       gchar *buffer = lines[i];
2535       gchar *d, *p;
2536       gint len;
2537       gboolean is_relative = FALSE;
2538       GUserDirectory directory;
2539 
2540       /* Remove newline at end */
2541       len = strlen (buffer);
2542       if (len > 0 && buffer[len - 1] == '\n')
2543     buffer[len - 1] = 0;
2544 
2545       p = buffer;
2546       while (*p == ' ' || *p == '\t')
2547     p++;
2548 
2549       if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2550         {
2551           directory = G_USER_DIRECTORY_DESKTOP;
2552           p += strlen ("XDG_DESKTOP_DIR");
2553         }
2554       else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2555         {
2556           directory = G_USER_DIRECTORY_DOCUMENTS;
2557           p += strlen ("XDG_DOCUMENTS_DIR");
2558         }
2559       else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2560         {
2561           directory = G_USER_DIRECTORY_DOWNLOAD;
2562           p += strlen ("XDG_DOWNLOAD_DIR");
2563         }
2564       else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2565         {
2566           directory = G_USER_DIRECTORY_MUSIC;
2567           p += strlen ("XDG_MUSIC_DIR");
2568         }
2569       else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2570         {
2571           directory = G_USER_DIRECTORY_PICTURES;
2572           p += strlen ("XDG_PICTURES_DIR");
2573         }
2574       else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2575         {
2576           directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2577           p += strlen ("XDG_PUBLICSHARE_DIR");
2578         }
2579       else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2580         {
2581           directory = G_USER_DIRECTORY_TEMPLATES;
2582           p += strlen ("XDG_TEMPLATES_DIR");
2583         }
2584       else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2585         {
2586           directory = G_USER_DIRECTORY_VIDEOS;
2587           p += strlen ("XDG_VIDEOS_DIR");
2588         }
2589       else
2590     continue;
2591 
2592       while (*p == ' ' || *p == '\t')
2593     p++;
2594 
2595       if (*p != '=')
2596     continue;
2597       p++;
2598 
2599       while (*p == ' ' || *p == '\t')
2600     p++;
2601 
2602       if (*p != '"')
2603     continue;
2604       p++;
2605 
2606       if (strncmp (p, "$HOME", 5) == 0)
2607     {
2608       p += 5;
2609       is_relative = TRUE;
2610     }
2611       else if (*p != '/')
2612     continue;
2613 
2614       d = strrchr (p, '"');
2615       if (!d)
2616         continue;
2617       *d = 0;
2618 
2619       d = p;
2620 
2621       /* remove trailing slashes */
2622       len = strlen (d);
2623       if (d[len - 1] == '/')
2624         d[len - 1] = 0;
2625 
2626       if (is_relative)
2627         {
2628           g_get_any_init ();
2629           g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2630         }
2631       else
2632     g_user_special_dirs[directory] = g_strdup (d);
2633     }
2634 
2635   g_strfreev (lines);
2636   g_free (config_file);
2637 }
2638 
2639 #endif /* G_OS_UNIX && !HAVE_CARBON */
2640 
2641 
2642 /**
2643  * g_reload_user_special_dirs_cache:
2644  *
2645  * Resets the cache used for g_get_user_special_dir(), so
2646  * that the latest on-disk version is used. Call this only
2647  * if you just changed the data on disk yourself.
2648  *
2649  * Due to threadsafety issues this may cause leaking of strings
2650  * that were previously returned from g_get_user_special_dir()
2651  * that can't be freed. We ensure to only leak the data for
2652  * the directories that actually changed value though.
2653  *
2654  * Since: 2.22
2655  */
2656 void
2657 g_reload_user_special_dirs_cache (void)
2658 {
2659   int i;
2660 
2661   G_LOCK (g_utils_global);
2662 
2663   if (g_user_special_dirs != NULL)
2664     {
2665       /* save a copy of the pointer, to check if some memory can be preserved */
2666       char **old_g_user_special_dirs = g_user_special_dirs;
2667       char *old_val;
2668 
2669       /* recreate and reload our cache */
2670       g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2671       load_user_special_dirs ();
2672 
2673       /* only leak changed directories */
2674       for (i = 0; i < G_USER_N_DIRECTORIES; i++)
2675         {
2676       old_val = old_g_user_special_dirs[i];
2677       if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
2678             {
2679           /* don't leak */
2680           g_free (g_user_special_dirs[i]);
2681           g_user_special_dirs[i] = old_val;
2682             }
2683       else
2684             g_free (old_val);
2685         }
2686 
2687       /* free the old array */
2688       g_free (old_g_user_special_dirs);
2689     }
2690 
2691   G_UNLOCK (g_utils_global);
2692 }
2693 
2694 /**
2695  * g_get_user_special_dir:
2696  * @directory: the logical id of special directory
2697  *
2698  * Returns the full path of a special directory using its logical id.
2699  *
2700  * On Unix this is done using the XDG special user directories.
2701  * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
2702  * falls back to <filename>$HOME/Desktop</filename> when XDG special
2703  * user directories have not been set up.
2704  *
2705  * Depending on the platform, the user might be able to change the path
2706  * of the special directory without requiring the session to restart; GLib
2707  * will not reflect any change once the special directories are loaded.
2708  *
2709  * Return value: the path to the specified special directory, or %NULL
2710  *   if the logical id was not found. The returned string is owned by
2711  *   GLib and should not be modified or freed.
2712  *
2713  * Since: 2.14
2714  */
2715 G_CONST_RETURN gchar *
2716 g_get_user_special_dir (GUserDirectory directory)
2717 {
2718   g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2719                         directory < G_USER_N_DIRECTORIES, NULL);
2720 
2721   G_LOCK (g_utils_global);
2722 
2723   if (G_UNLIKELY (g_user_special_dirs == NULL))
2724     {
2725       g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2726 
2727       load_user_special_dirs ();
2728 
2729       /* Special-case desktop for historical compatibility */
2730       if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2731         {
2732           g_get_any_init ();
2733 
2734           g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2735             g_build_filename (g_home_dir, "Desktop", NULL);
2736         }
2737     }
2738 
2739   G_UNLOCK (g_utils_global);
2740 
2741   return g_user_special_dirs[directory];
2742 }
2743 
2744 #ifdef G_OS_WIN32
2745 
2746 #undef g_get_system_data_dirs
2747 
2748 static HMODULE
2749 get_module_for_address (gconstpointer address)
2750 {
2751   /* Holds the g_utils_global lock */
2752 
2753   static gboolean beenhere = FALSE;
2754   typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2755   static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2756   HMODULE hmodule = NULL;
2757 
2758   if (!address)
2759     return NULL;
2760 
2761   if (!beenhere)
2762     {
2763       p_GetModuleHandleExA =
2764     (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2765                            "GetModuleHandleExA");
2766       beenhere = TRUE;
2767     }
2768 
2769   if (p_GetModuleHandleExA == NULL ||
2770       !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2771                 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2772                 address, &hmodule))
2773     {
2774       MEMORY_BASIC_INFORMATION mbi;
2775       VirtualQuery (address, &mbi, sizeof (mbi));
2776       hmodule = (HMODULE) mbi.AllocationBase;
2777     }
2778 
2779   return hmodule;
2780 }
2781 
2782 static gchar *
2783 get_module_share_dir (gconstpointer address)
2784 {
2785   HMODULE hmodule;
2786   gchar *filename;
2787   gchar *retval;
2788 
2789   hmodule = get_module_for_address (address);
2790   if (hmodule == NULL)
2791     return NULL;
2792 
2793   filename = g_win32_get_package_installation_directory_of_module (hmodule);
2794   retval = g_build_filename (filename, "share", NULL);
2795   g_free (filename);
2796 
2797   return retval;
2798 }
2799 
2800 G_CONST_RETURN gchar * G_CONST_RETURN *
2801 g_win32_get_system_data_dirs_for_module (void (*address_of_function)())
2802 {
2803   GArray *data_dirs;
2804   HMODULE hmodule;
2805   static GHashTable *per_module_data_dirs = NULL;
2806   gchar **retval;
2807   gchar *p;
2808   gchar *exe_root;
2809 
2810   if (address_of_function)
2811     {
2812       G_LOCK (g_utils_global);
2813       hmodule = get_module_for_address (address_of_function);
2814       if (hmodule != NULL)
2815     {
2816       if (per_module_data_dirs == NULL)
2817         per_module_data_dirs = g_hash_table_new (NULL, NULL);
2818       else
2819         {
2820           retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2821 
2822           if (retval != NULL)
2823         {
2824           G_UNLOCK (g_utils_global);
2825           return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2826         }
2827         }
2828     }
2829     }
2830 
2831   data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2832 
2833   /* Documents and Settings\All Users\Application Data */
2834   p = get_special_folder (CSIDL_COMMON_APPDATA);
2835   if (p)
2836     g_array_append_val (data_dirs, p);
2837 
2838   /* Documents and Settings\All Users\Documents */
2839   p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2840   if (p)
2841     g_array_append_val (data_dirs, p);
2842 
2843   /* Using the above subfolders of Documents and Settings perhaps
2844    * makes sense from a Windows perspective.
2845    *
2846    * But looking at the actual use cases of this function in GTK+
2847    * and GNOME software, what we really want is the "share"
2848    * subdirectory of the installation directory for the package
2849    * our caller is a part of.
2850    *
2851    * The address_of_function parameter, if non-NULL, points to a
2852    * function in the calling module. Use that to determine that
2853    * module's installation folder, and use its "share" subfolder.
2854    *
2855    * Additionally, also use the "share" subfolder of the installation
2856    * locations of GLib and the .exe file being run.
2857    *
2858    * To guard against none of the above being what is really wanted,
2859    * callers of this function should have Win32-specific code to look
2860    * up their installation folder themselves, and handle a subfolder
2861    * "share" of it in the same way as the folders returned from this
2862    * function.
2863    */
2864 
2865   p = get_module_share_dir (address_of_function);
2866   if (p)
2867     g_array_append_val (data_dirs, p);
2868 
2869   if (glib_dll != NULL)
2870     {
2871       gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
2872       p = g_build_filename (glib_root, "share", NULL);
2873       if (p)
2874     g_array_append_val (data_dirs, p);
2875       g_free (glib_root);
2876     }
2877 
2878   exe_root = g_win32_get_package_installation_directory_of_module (NULL);
2879   p = g_build_filename (exe_root, "share", NULL);
2880   if (p)
2881     g_array_append_val (data_dirs, p);
2882   g_free (exe_root);
2883 
2884   retval = (gchar **) g_array_free (data_dirs, FALSE);
2885 
2886   if (address_of_function)
2887     {
2888       if (hmodule != NULL)
2889     g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2890       G_UNLOCK (g_utils_global);
2891     }
2892 
2893   return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2894 }
2895 
2896 #endif
2897 
2898 /**
2899  * g_get_system_data_dirs:
2900  *
2901  * Returns an ordered list of base directories in which to access
2902  * system-wide application data.
2903  *
2904  * On UNIX platforms this is determined using the mechanisms described in
2905  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2906  * XDG Base Directory Specification</ulink>
2907  * In this case the list of directories retrieved will be XDG_DATA_DIRS.
2908  *
2909  * On Windows the first elements in the list are the Application Data
2910  * and Documents folders for All Users. (These can be determined only
2911  * on Windows 2000 or later and are not present in the list on other
2912  * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2913  * CSIDL_COMMON_DOCUMENTS.
2914  *
2915  * Then follows the "share" subfolder in the installation folder for
2916  * the package containing the DLL that calls this function, if it can
2917  * be determined.
2918  *
2919  * Finally the list contains the "share" subfolder in the installation
2920  * folder for GLib, and in the installation folder for the package the
2921  * application's .exe file belongs to.
2922  *
2923  * The installation folders above are determined by looking up the
2924  * folder where the module (DLL or EXE) in question is located. If the
2925  * folder's name is "bin", its parent is used, otherwise the folder
2926  * itself.
2927  *
2928  * Note that on Windows the returned list can vary depending on where
2929  * this function is called.
2930  *
2931  * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
2932  *               not be modified or freed.
2933  * Since: 2.6
2934  **/
2935 G_CONST_RETURN gchar * G_CONST_RETURN *
2936 g_get_system_data_dirs (void)
2937 {
2938   gchar **data_dir_vector;
2939 
2940   G_LOCK (g_utils_global);
2941 
2942   if (!g_system_data_dirs)
2943     {
2944 #ifdef G_OS_WIN32
2945       data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2946 #else
2947       gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2948 
2949       if (!data_dirs || !data_dirs[0])
2950           data_dirs = "/usr/local/share/:/usr/share/";
2951 
2952       data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2953 #endif
2954 
2955       g_system_data_dirs = data_dir_vector;
2956     }
2957   else
2958     data_dir_vector = g_system_data_dirs;
2959 
2960   G_UNLOCK (g_utils_global);
2961 
2962   return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2963 }
2964 
2965 /**
2966  * g_get_system_config_dirs:
2967  *
2968  * Returns an ordered list of base directories in which to access
2969  * system-wide configuration information.
2970  *
2971  * On UNIX platforms this is determined using the mechanisms described in
2972  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2973  * XDG Base Directory Specification</ulink>.
2974  * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
2975  *
2976  * On Windows is the directory that contains application data for all users.
2977  * A typical path is C:\Documents and Settings\All Users\Application Data.
2978  * This folder is used for application data that is not user specific.
2979  * For example, an application can store a spell-check dictionary, a database
2980  * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2981  * This information will not roam and is available to anyone using the computer.
2982  *
2983  * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
2984  *               not be modified or freed.
2985  * Since: 2.6
2986  **/
2987 G_CONST_RETURN gchar * G_CONST_RETURN *
2988 g_get_system_config_dirs (void)
2989 {
2990   gchar *conf_dirs, **conf_dir_vector;
2991 
2992   G_LOCK (g_utils_global);
2993 
2994   if (!g_system_config_dirs)
2995     {
2996 #ifdef G_OS_WIN32
2997       conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2998       if (conf_dirs)
2999     {
3000       conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
3001       g_free (conf_dirs);
3002     }
3003       else
3004     {
3005       /* Return empty list */
3006       conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
3007     }
3008 #else
3009       conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
3010 
3011       if (!conf_dirs || !conf_dirs[0])
3012           conf_dirs = "/etc/xdg";
3013 
3014       conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
3015 #endif
3016 
3017       g_system_config_dirs = conf_dir_vector;
3018     }
3019   else
3020     conf_dir_vector = g_system_config_dirs;
3021   G_UNLOCK (g_utils_global);
3022 
3023   return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
3024 }
3025 
3026 #ifndef G_OS_WIN32
3027 
3028 static GHashTable *alias_table = NULL;
3029 
3030 /* read an alias file for the locales */
3031 static void
3032 read_aliases (gchar *file)
3033 {
3034   FILE *fp;
3035   char buf[256];
3036 
3037   if (!alias_table)
3038     alias_table = g_hash_table_new (g_str_hash, g_str_equal);
3039   fp = fopen (file,"r");
3040   if (!fp)
3041     return;
3042   while (fgets (buf, 256, fp))
3043     {
3044       char *p, *q;
3045 
3046       g_strstrip (buf);
3047 
3048       /* Line is a comment */
3049       if ((buf[0] == '#') || (buf[0] == '\0'))
3050     continue;
3051 
3052       /* Reads first column */
3053       for (p = buf, q = NULL; *p; p++) {
3054     if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
3055       *p = '\0';
3056       q = p+1;
3057       while ((*q == '\t') || (*q == ' ')) {
3058         q++;
3059       }
3060       break;
3061     }
3062       }
3063       /* The line only had one column */
3064       if (!q || *q == '\0')
3065     continue;
3066 
3067       /* Read second column */
3068       for (p = q; *p; p++) {
3069     if ((*p == '\t') || (*p == ' ')) {
3070       *p = '\0';
3071       break;
3072     }
3073       }
3074 
3075       /* Add to alias table if necessary */
3076       if (!g_hash_table_lookup (alias_table, buf)) {
3077     g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
3078       }
3079     }
3080   fclose (fp);
3081 }
3082 
3083 #endif
3084 
3085 static char *
3086 unalias_lang (char *lang)
3087 {
3088 #ifndef G_OS_WIN32
3089   char *p;
3090   int i;
3091 
3092   if (!alias_table)
3093     read_aliases ("/usr/share/locale/locale.alias");
3094 
3095   i = 0;
3096   while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
3097     {
3098       lang = p;
3099       if (i++ == 30)
3100         {
3101           static gboolean said_before = FALSE;
3102       if (!said_before)
3103             g_warning ("Too many alias levels for a locale, "
3104                "may indicate a loop");
3105       said_before = TRUE;
3106       return lang;
3107     }
3108     }
3109 #endif
3110   return lang;
3111 }
3112 
3113 /* Mask for components of locale spec. The ordering here is from
3114  * least significant to most significant
3115  */
3116 enum
3117 {
3118   COMPONENT_CODESET =   1 << 0,
3119   COMPONENT_TERRITORY = 1 << 1,
3120   COMPONENT_MODIFIER =  1 << 2
3121 };
3122 
3123 /* Break an X/Open style locale specification into components
3124  */
3125 static guint
3126 explode_locale (const gchar *locale,
3127         gchar      **language,
3128         gchar      **territory,
3129         gchar      **codeset,
3130         gchar      **modifier)
3131 {
3132   const gchar *uscore_pos;
3133   const gchar *at_pos;
3134   const gchar *dot_pos;
3135 
3136   guint mask = 0;
3137 
3138   uscore_pos = strchr (locale, '_');
3139   dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
3140   at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
3141 
3142   if (at_pos)
3143     {
3144       mask |= COMPONENT_MODIFIER;
3145       *modifier = g_strdup (at_pos);
3146     }
3147   else
3148     at_pos = locale + strlen (locale);
3149 
3150   if (dot_pos)
3151     {
3152       mask |= COMPONENT_CODESET;
3153       *codeset = g_strndup (dot_pos, at_pos - dot_pos);
3154     }
3155   else
3156     dot_pos = at_pos;
3157 
3158   if (uscore_pos)
3159     {
3160       mask |= COMPONENT_TERRITORY;
3161       *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
3162     }
3163   else
3164     uscore_pos = dot_pos;
3165 
3166   *language = g_strndup (locale, uscore_pos - locale);
3167 
3168   return mask;
3169 }
3170 
3171 /*
3172  * Compute all interesting variants for a given locale name -
3173  * by stripping off different components of the value.
3174  *
3175  * For simplicity, we assume that the locale is in
3176  * X/Open format: language[_territory][.codeset][@modifier]
3177  *
3178  * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
3179  *       as well. We could just copy the code from glibc wholesale
3180  *       but it is big, ugly, and complicated, so I'm reluctant
3181  *       to do so when this should handle 99% of the time...
3182  */
3183 static void
3184 append_locale_variants (GPtrArray *array,
3185                         const gchar *locale)
3186 {
3187   gchar *language = NULL;
3188   gchar *territory = NULL;
3189   gchar *codeset = NULL;
3190   gchar *modifier = NULL;
3191 
3192   guint mask;
3193   guint i, j;
3194 
3195   g_return_if_fail (locale != NULL);
3196 
3197   mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
3198 
3199   /* Iterate through all possible combinations, from least attractive
3200    * to most attractive.
3201    */
3202   for (j = 0; j <= mask; ++j)
3203     {
3204       i = mask - j;
3205 
3206       if ((i & ~mask) == 0)
3207         {
3208           gchar *val = g_strconcat (language,
3209                                     (i & COMPONENT_TERRITORY) ? territory : "",
3210                                     (i & COMPONENT_CODESET) ? codeset : "",
3211                                     (i & COMPONENT_MODIFIER) ? modifier : "",
3212                                     NULL);
3213           g_ptr_array_add (array, val);
3214         }
3215     }
3216 
3217   g_free (language);
3218   if (mask & COMPONENT_CODESET)
3219     g_free (codeset);
3220   if (mask & COMPONENT_TERRITORY)
3221     g_free (territory);
3222   if (mask & COMPONENT_MODIFIER)
3223     g_free (modifier);
3224 }
3225 
3226 /**
3227  * g_get_locale_variants:
3228  * @locale: a locale identifier
3229  *
3230  * Returns a list of derived variants of @locale, which can be used to
3231  * e.g. construct locale-dependent filenames or search paths. The returned
3232  * list is sorted from most desirable to least desirable.
3233  * This function handles territory, charset and extra locale modifiers.
3234  *
3235  * For example, if @locale is "fr_BE", then the returned list
3236  * is "fr_BE", "fr".
3237  *
3238  * If you need the list of variants for the <emphasis>current locale</emphasis>,
3239  * use g_get_language_names().
3240  *
3241  * Returns: (transfer full) (array zero-terminated=1) (element-type utf8): a newly
3242  *   allocated array of newly allocated strings with the locale variants. Free with
3243  *   g_strfreev().
3244  *
3245  * Since: 2.28
3246  */
3247 gchar **
3248 g_get_locale_variants (const gchar *locale)
3249 {
3250   GPtrArray *array;
3251 
3252   g_return_val_if_fail (locale != NULL, NULL);
3253 
3254   array = g_ptr_array_sized_new (8);
3255   append_locale_variants (array, locale);
3256   g_ptr_array_add (array, NULL);
3257 
3258   return (gchar **) g_ptr_array_free (array, FALSE);
3259 }
3260 
3261 /* The following is (partly) taken from the gettext package.
3262    Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc.  */
3263 
3264 static const gchar *
3265 guess_category_value (const gchar *category_name)
3266 {
3267   const gchar *retval;
3268 
3269   /* The highest priority value is the `LANGUAGE' environment
3270      variable.  This is a GNU extension.  */
3271   retval = g_getenv ("LANGUAGE");
3272   if ((retval != NULL) && (retval[0] != '\0'))
3273     return retval;
3274 
3275   /* `LANGUAGE' is not set.  So we have to proceed with the POSIX
3276      methods of looking to `LC_ALL', `LC_xxx', and `LANG'.  On some
3277      systems this can be done by the `setlocale' function itself.  */
3278 
3279   /* Setting of LC_ALL overwrites all other.  */
3280   retval = g_getenv ("LC_ALL");
3281   if ((retval != NULL) && (retval[0] != '\0'))
3282     return retval;
3283 
3284   /* Next comes the name of the desired category.  */
3285   retval = g_getenv (category_name);
3286   if ((retval != NULL) && (retval[0] != '\0'))
3287     return retval;
3288 
3289   /* Last possibility is the LANG environment variable.  */
3290   retval = g_getenv ("LANG");
3291   if ((retval != NULL) && (retval[0] != '\0'))
3292     return retval;
3293 
3294 #ifdef G_PLATFORM_WIN32
3295   /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
3296    * LANG, which we already did above. Oh well. The main point of
3297    * calling g_win32_getlocale() is to get the thread's locale as used
3298    * by Windows and the Microsoft C runtime (in the "English_United
3299    * States" format) translated into the Unixish format.
3300    */
3301   {
3302     char *locale = g_win32_getlocale ();
3303     retval = g_intern_string (locale);
3304     g_free (locale);
3305     return retval;
3306   }
3307 #endif
3308 
3309   return NULL;
3310 }
3311 
3312 typedef struct _GLanguageNamesCache GLanguageNamesCache;
3313 
3314 struct _GLanguageNamesCache {
3315   gchar *languages;
3316   gchar **language_names;
3317 };
3318 
3319 static void
3320 language_names_cache_free (gpointer data)
3321 {
3322   GLanguageNamesCache *cache = data;
3323   g_free (cache->languages);
3324   g_strfreev (cache->language_names);
3325   g_free (cache);
3326 }
3327 
3328 /**
3329  * g_get_language_names:
3330  *
3331  * Computes a list of applicable locale names, which can be used to
3332  * e.g. construct locale-dependent filenames or search paths. The returned
3333  * list is sorted from most desirable to least desirable and always contains
3334  * the default locale "C".
3335  *
3336  * For example, if LANGUAGE=de:en_US, then the returned list is
3337  * "de", "en_US", "en", "C".
3338  *
3339  * This function consults the environment variables <envar>LANGUAGE</envar>,
3340  * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
3341  * to find the list of locales specified by the user.
3342  *
3343  * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib
3344  *    that must not be modified or freed.
3345  *
3346  * Since: 2.6
3347  **/
3348 G_CONST_RETURN gchar * G_CONST_RETURN *
3349 g_get_language_names (void)
3350 {
3351   static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
3352   GLanguageNamesCache *cache = g_static_private_get (&cache_private);
3353   const gchar *value;
3354 
3355   if (!cache)
3356     {
3357       cache = g_new0 (GLanguageNamesCache, 1);
3358       g_static_private_set (&cache_private, cache, language_names_cache_free);
3359     }
3360 
3361   value = guess_category_value ("LC_MESSAGES");
3362   if (!value)
3363     value = "C";
3364 
3365   if (!(cache->languages && strcmp (cache->languages, value) == 0))
3366     {
3367       GPtrArray *array;
3368       gchar **alist, **a;
3369 
3370       g_free (cache->languages);
3371       g_strfreev (cache->language_names);
3372       cache->languages = g_strdup (value);
3373 
3374       array = g_ptr_array_sized_new (8);
3375 
3376       alist = g_strsplit (value, ":", 0);
3377       for (a = alist; *a; a++)
3378         append_locale_variants (array, unalias_lang (*a));
3379       g_strfreev (alist);
3380       g_ptr_array_add (array, g_strdup ("C"));
3381       g_ptr_array_add (array, NULL);
3382 
3383       cache->language_names = (gchar **) g_ptr_array_free (array, FALSE);
3384     }
3385 
3386   return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
3387 }
3388 
3389 /**
3390  * g_direct_hash:
3391  * @v: a #gpointer key
3392  *
3393  * Converts a gpointer to a hash value.
3394  * It can be passed to g_hash_table_new() as the @hash_func parameter,
3395  * when using pointers as keys in a #GHashTable.
3396  *
3397  * Returns: a hash value corresponding to the key.
3398  */
3399 guint
3400 g_direct_hash (gconstpointer v)
3401 {
3402   return GPOINTER_TO_UINT (v);
3403 }
3404 
3405 /**
3406  * g_direct_equal:
3407  * @v1: a key.
3408  * @v2: a key to compare with @v1.
3409  *
3410  * Compares two #gpointer arguments and returns %TRUE if they are equal.
3411  * It can be passed to g_hash_table_new() as the @key_equal_func
3412  * parameter, when using pointers as keys in a #GHashTable.
3413  *
3414  * Returns: %TRUE if the two keys match.
3415  */
3416 gboolean
3417 g_direct_equal (gconstpointer v1,
3418         gconstpointer v2)
3419 {
3420   return v1 == v2;
3421 }
3422 
3423 /**
3424  * g_int_equal:
3425  * @v1: a pointer to a #gint key.
3426  * @v2: a pointer to a #gint key to compare with @v1.
3427  *
3428  * Compares the two #gint values being pointed to and returns
3429  * %TRUE if they are equal.
3430  * It can be passed to g_hash_table_new() as the @key_equal_func
3431  * parameter, when using pointers to integers as keys in a #GHashTable.
3432  *
3433  * Returns: %TRUE if the two keys match.
3434  */
3435 gboolean
3436 g_int_equal (gconstpointer v1,
3437          gconstpointer v2)
3438 {
3439   return *((const gint*) v1) == *((const gint*) v2);
3440 }
3441 
3442 /**
3443  * g_int_hash:
3444  * @v: a pointer to a #gint key
3445  *
3446  * Converts a pointer to a #gint to a hash value.
3447  * It can be passed to g_hash_table_new() as the @hash_func parameter,
3448  * when using pointers to integers values as keys in a #GHashTable.
3449  *
3450  * Returns: a hash value corresponding to the key.
3451  */
3452 guint
3453 g_int_hash (gconstpointer v)
3454 {
3455   return *(const gint*) v;
3456 }
3457 
3458 /**
3459  * g_int64_equal:
3460  * @v1: a pointer to a #gint64 key.
3461  * @v2: a pointer to a #gint64 key to compare with @v1.
3462  *
3463  * Compares the two #gint64 values being pointed to and returns
3464  * %TRUE if they are equal.
3465  * It can be passed to g_hash_table_new() as the @key_equal_func
3466  * parameter, when using pointers to 64-bit integers as keys in a #GHashTable.
3467  *
3468  * Returns: %TRUE if the two keys match.
3469  *
3470  * Since: 2.22
3471  */
3472 gboolean
3473 g_int64_equal (gconstpointer v1,
3474                gconstpointer v2)
3475 {
3476   return *((const gint64*) v1) == *((const gint64*) v2);
3477 }
3478 
3479 /**
3480  * g_int64_hash:
3481  * @v: a pointer to a #gint64 key
3482  *
3483  * Converts a pointer to a #gint64 to a hash value.
3484  * It can be passed to g_hash_table_new() as the @hash_func parameter,
3485  * when using pointers to 64-bit integers values as keys in a #GHashTable.
3486  *
3487  * Returns: a hash value corresponding to the key.
3488  *
3489  * Since: 2.22
3490  */
3491 guint
3492 g_int64_hash (gconstpointer v)
3493 {
3494   return (guint) *(const gint64*) v;
3495 }
3496 
3497 /**
3498  * g_double_equal:
3499  * @v1: a pointer to a #gdouble key.
3500  * @v2: a pointer to a #gdouble key to compare with @v1.
3501  *
3502  * Compares the two #gdouble values being pointed to and returns
3503  * %TRUE if they are equal.
3504  * It can be passed to g_hash_table_new() as the @key_equal_func
3505  * parameter, when using pointers to doubles as keys in a #GHashTable.
3506  *
3507  * Returns: %TRUE if the two keys match.
3508  *
3509  * Since: 2.22
3510  */
3511 gboolean
3512 g_double_equal (gconstpointer v1,
3513                 gconstpointer v2)
3514 {
3515   return *((const gdouble*) v1) == *((const gdouble*) v2);
3516 }
3517 
3518 /**
3519  * g_double_hash:
3520  * @v: a pointer to a #gdouble key
3521  *
3522  * Converts a pointer to a #gdouble to a hash value.
3523  * It can be passed to g_hash_table_new() as the @hash_func parameter,
3524  * when using pointers to doubles as keys in a #GHashTable.
3525  *
3526  * Returns: a hash value corresponding to the key.
3527  *
3528  * Since: 2.22
3529  */
3530 guint
3531 g_double_hash (gconstpointer v)
3532 {
3533   return (guint) *(const gdouble*) v;
3534 }
3535 
3536 /**
3537  * g_nullify_pointer:
3538  * @nullify_location: the memory address of the pointer.
3539  *
3540  * Set the pointer at the specified location to %NULL.
3541  **/
3542 void
3543 g_nullify_pointer (gpointer *nullify_location)
3544 {
3545   g_return_if_fail (nullify_location != NULL);
3546 
3547   *nullify_location = NULL;
3548 }
3549 
3550 /**
3551  * g_get_codeset:
3552  *
3553  * Get the codeset for the current locale.
3554  *
3555  * Return value: a newly allocated string containing the name
3556  * of the codeset. This string must be freed with g_free().
3557  **/
3558 gchar *
3559 g_get_codeset (void)
3560 {
3561   const gchar *charset;
3562 
3563   g_get_charset (&charset);
3564 
3565   return g_strdup (charset);
3566 }
3567 
3568 /* This is called from g_thread_init(). It's used to
3569  * initialize some static data in a threadsafe way.
3570  */
3571 void
3572 _g_utils_thread_init (void)
3573 {
3574   g_get_language_names ();
3575 }
3576 
3577 #ifdef G_OS_WIN32
3578 
3579 /**
3580  * _glib_get_locale_dir:
3581  *
3582  * Return the path to the share\locale or lib\locale subfolder of the
3583  * GLib installation folder. The path is in the system codepage. We
3584  * have to use system codepage as bindtextdomain() doesn't have a
3585  * UTF-8 interface.
3586  */
3587 static gchar *
3588 _glib_get_locale_dir (void)
3589 {
3590   gchar *install_dir = NULL, *locale_dir;
3591   gchar *retval = NULL;
3592 
3593   if (glib_dll != NULL)
3594     install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
3595 
3596   if (install_dir)
3597     {
3598       /*
3599        * Append "/share/locale" or "/lib/locale" depending on whether
3600        * autoconfigury detected GNU gettext or not.
3601        */
3602       const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3603       while (*--p != '/')
3604     ;
3605       while (*--p != '/')
3606     ;
3607 
3608       locale_dir = g_build_filename (install_dir, p, NULL);
3609 
3610       retval = g_win32_locale_filename_from_utf8 (locale_dir);
3611 
3612       g_free (install_dir);
3613       g_free (locale_dir);
3614     }
3615 
3616   if (retval)
3617     return retval;
3618   else
3619     return g_strdup ("");
3620 }
3621 
3622 #undef GLIB_LOCALE_DIR
3623 
3624 #endif /* G_OS_WIN32 */
3625 
3626 static void
3627 ensure_gettext_initialized(void)
3628 {
3629   static gboolean _glib_gettext_initialized = FALSE;
3630 
3631   if (!_glib_gettext_initialized)
3632     {
3633 #ifdef G_OS_WIN32
3634       gchar *tmp = _glib_get_locale_dir ();
3635       bindtextdomain (GETTEXT_PACKAGE, tmp);
3636       g_free (tmp);
3637 #else
3638       bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3639 #endif
3640 #    ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3641       bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3642 #    endif
3643       _glib_gettext_initialized = TRUE;
3644     }
3645 }
3646 
3647 /**
3648  * glib_gettext:
3649  * @str: The string to be translated
3650  *
3651  * Returns the translated string from the glib translations.
3652  * This is an internal function and should only be used by
3653  * the internals of glib (such as libgio).
3654  *
3655  * Returns: the transation of @str to the current locale
3656  */
3657 G_CONST_RETURN gchar *
3658 glib_gettext (const gchar *str)
3659 {
3660   ensure_gettext_initialized();
3661 
3662   return g_dgettext (GETTEXT_PACKAGE, str);
3663 }
3664 
3665 /**
3666  * glib_pgettext:
3667  * @msgctxtid: a combined message context and message id, separated
3668  *   by a \004 character
3669  * @msgidoffset: the offset of the message id in @msgctxid
3670  *
3671  * This function is a variant of glib_gettext() which supports
3672  * a disambiguating message context. See g_dpgettext() for full
3673  * details.
3674  *
3675  * This is an internal function and should only be used by
3676  * the internals of glib (such as libgio).
3677  *
3678  * Returns: the transation of @str to the current locale
3679  */
3680 G_CONST_RETURN gchar *
3681 glib_pgettext(const gchar *msgctxtid,
3682               gsize        msgidoffset)
3683 {
3684   ensure_gettext_initialized();
3685 
3686   return g_dpgettext (GETTEXT_PACKAGE, msgctxtid, msgidoffset);
3687 }
3688 
3689 #if defined (G_OS_WIN32) && !defined (_WIN64)
3690 
3691 /* Binary compatibility versions. Not for newly compiled code. */
3692 
3693 #undef g_find_program_in_path
3694 
3695 gchar*
3696 g_find_program_in_path (const gchar *program)
3697 {
3698   gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3699   gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3700   gchar *retval;
3701 
3702   g_free (utf8_program);
3703   if (utf8_retval == NULL)
3704     return NULL;
3705   retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3706   g_free (utf8_retval);
3707 
3708   return retval;
3709 }
3710 
3711 #undef g_get_current_dir
3712 
3713 gchar*
3714 g_get_current_dir (void)
3715 {
3716   gchar *utf8_dir = g_get_current_dir_utf8 ();
3717   gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3718   g_free (utf8_dir);
3719   return dir;
3720 }
3721 
3722 #undef g_getenv
3723 
3724 G_CONST_RETURN gchar*
3725 g_getenv (const gchar *variable)
3726 {
3727   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3728   const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3729   gchar *value;
3730   GQuark quark;
3731 
3732   g_free (utf8_variable);
3733   if (!utf8_value)
3734     return NULL;
3735   value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3736   quark = g_quark_from_string (value);
3737   g_free (value);
3738 
3739   return g_quark_to_string (quark);
3740 }
3741 
3742 #undef g_setenv
3743 
3744 gboolean
3745 g_setenv (const gchar *variable,
3746       const gchar *value,
3747       gboolean     overwrite)
3748 {
3749   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3750   gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3751   gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3752 
3753   g_free (utf8_variable);
3754   g_free (utf8_value);
3755 
3756   return retval;
3757 }
3758 
3759 #undef g_unsetenv
3760 
3761 void
3762 g_unsetenv (const gchar *variable)
3763 {
3764   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3765 
3766   g_unsetenv_utf8 (utf8_variable);
3767 
3768   g_free (utf8_variable);
3769 }
3770 
3771 #undef g_get_user_name
3772 
3773 G_CONST_RETURN gchar*
3774 g_get_user_name (void)
3775 {
3776   g_get_any_init_locked ();
3777   return g_user_name_cp;
3778 }
3779 
3780 #undef g_get_real_name
3781 
3782 G_CONST_RETURN gchar*
3783 g_get_real_name (void)
3784 {
3785   g_get_any_init_locked ();
3786   return g_real_name_cp;
3787 }
3788 
3789 #undef g_get_home_dir
3790 
3791 G_CONST_RETURN gchar*
3792 g_get_home_dir (void)
3793 {
3794   g_get_any_init_locked ();
3795   return g_home_dir_cp;
3796 }
3797 
3798 #undef g_get_tmp_dir
3799 
3800 G_CONST_RETURN gchar*
3801 g_get_tmp_dir (void)
3802 {
3803   g_get_any_init_locked ();
3804   return g_tmp_dir_cp;
3805 }
3806 
3807 #endif