gutils.c 83.4 KB
Newer Older
Owen Taylor's avatar
Owen Taylor committed
1
/* GLIB - Library of useful routines for C programming
2
 * Copyright (C) 1995-1998  Peter Mattis, Spencer Kimball and Josh MacDonald
Owen Taylor's avatar
Owen Taylor committed
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
Owen Taylor's avatar
Owen Taylor committed
6 7 8 9 10 11
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
12
 * Lesser General Public License for more details.
Owen Taylor's avatar
Owen Taylor committed
13
 *
14
 * You should have received a copy of the GNU Lesser General Public
Owen Taylor's avatar
Owen Taylor committed
15 16 17 18
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */
19

20
/*
21
 * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22 23 24 25 26
 * file for a list of people on the GLib Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
 * GLib at ftp://ftp.gtk.org/pub/gtk/. 
 */

27 28 29 30
/* 
 * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
 */

31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
/**
 * SECTION:version
 * @Title: Version Information
 * @Short_description: Variables and functions to check the GLib version
 *
 * GLib provides version information, primarily useful in configure
 * checks for builds that have a configure script. Applications will
 * not typically use the features described here.
 */

/**
 * GLIB_MAJOR_VERSION:
 *
 * The major version number of the GLib library.
 *
 * Like #glib_major_version, but from the headers used at
 * application compile time, rather than from the library
 * linked against at application run time.
 */

/**
 * GLIB_MINOR_VERSION:
 *
 * The minor version number of the GLib library.
 *
 * Like #gtk_minor_version, but from the headers used at
 * application compile time, rather than from the library
 * linked against at application run time.
 */

/**
 * GLIB_MICRO_VERSION:
 *
 * The micro version number of the GLib library.
 *
 * Like #gtk_micro_version, but from the headers used at
 * application compile time, rather than from the library
 * linked against at application run time.
 */

71
#include "config.h"
72

73
#ifdef HAVE_UNISTD_H
74
#include <unistd.h>
75
#endif
Owen Taylor's avatar
Owen Taylor committed
76 77
#include <stdarg.h>
#include <stdlib.h>
78
#include <stdio.h>
79
#include <locale.h>
Owen Taylor's avatar
Owen Taylor committed
80
#include <string.h>
81
#include <ctype.h>		/* For tolower() */
Manish Singh's avatar
Manish Singh committed
82
#include <errno.h>
83 84
#include <sys/types.h>
#include <sys/stat.h>
85
#ifdef HAVE_PWD_H
86
#include <pwd.h>
87
#endif
88
#include <sys/types.h>
89
#ifdef HAVE_SYS_PARAM_H
90
#include <sys/param.h>
91
#endif
92
#ifdef HAVE_CRT_EXTERNS_H 
93
#include <crt_externs.h> /* for _NSGetEnviron */
94
#endif
95

96
/* implement gutils's inline functions
97
 */
98 99
#define	G_IMPLEMENT_INLINES 1
#define	__G_UTILS_C__
100 101
#include "gutils.h"

102
#include "glib-init.h"
103
#include "genviron.h"
104 105 106
#include "gfileutils.h"
#include "ghash.h"
#include "gslist.h"
107
#include "gprintfint.h"
108
#include "gthread.h"
109
#include "gthreadprivate.h"
110 111 112
#include "gtestutils.h"
#include "gunicode.h"
#include "gstrfuncs.h"
113
#include "garray.h"
114
#include "glibintl.h"
Owen Taylor's avatar
Owen Taylor committed
115

116 117 118 119 120 121
#ifdef G_PLATFORM_WIN32
#include "garray.h"
#include "gconvert.h"
#include "gwin32.h"
#endif

122 123 124 125 126 127 128 129 130

/**
 * SECTION:misc_utils
 * @title: Miscellaneous Utility Functions
 * @short_description: a selection of portable utility functions
 *
 * These are portable utility functions.
 */

131
#ifdef	MAXPATHLEN
132
#define	G_PATH_LENGTH	MAXPATHLEN
133
#elif	defined (PATH_MAX)
134 135 136 137 138 139
#define	G_PATH_LENGTH	PATH_MAX
#elif   defined (_PC_PATH_MAX)
#define	G_PATH_LENGTH	sysconf(_PC_PATH_MAX)
#else	
#define G_PATH_LENGTH   2048
#endif
140

141
#ifdef G_PLATFORM_WIN32
142
#  include <windows.h>
143 144 145 146
#  ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
#    define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
#    define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
#  endif
147
#  include <lmcons.h>		/* For UNLEN */
148 149 150
#endif /* G_PLATFORM_WIN32 */

#ifdef G_OS_WIN32
151
#  include <direct.h>
152
#  include <shlobj.h>
153
   /* older SDK (e.g. msvc 5.0) does not have these*/
154 155 156 157 158 159
#  ifndef CSIDL_MYMUSIC
#    define CSIDL_MYMUSIC 13
#  endif
#  ifndef CSIDL_MYVIDEO
#    define CSIDL_MYVIDEO 14
#  endif
160 161 162 163 164 165
#  ifndef CSIDL_INTERNET_CACHE
#    define CSIDL_INTERNET_CACHE 32
#  endif
#  ifndef CSIDL_COMMON_APPDATA
#    define CSIDL_COMMON_APPDATA 35
#  endif
166 167 168
#  ifndef CSIDL_MYPICTURES
#    define CSIDL_MYPICTURES 0x27
#  endif
169 170 171 172 173 174
#  ifndef CSIDL_COMMON_DOCUMENTS
#    define CSIDL_COMMON_DOCUMENTS 46
#  endif
#  ifndef CSIDL_PROFILE
#    define CSIDL_PROFILE 40
#  endif
175
#  include <process.h>
176
#endif
177

178 179 180 181
#ifdef HAVE_CARBON
#include <CoreServices/CoreServices.h>
#endif

182 183 184 185
#ifdef HAVE_CODESET
#include <langinfo.h>
#endif

Owen Taylor's avatar
Owen Taylor committed
186 187 188
const guint glib_major_version = GLIB_MAJOR_VERSION;
const guint glib_minor_version = GLIB_MINOR_VERSION;
const guint glib_micro_version = GLIB_MICRO_VERSION;
189 190
const guint glib_interface_age = GLIB_INTERFACE_AGE;
const guint glib_binary_age = GLIB_BINARY_AGE;
Owen Taylor's avatar
Owen Taylor committed
191

192 193
#ifdef G_PLATFORM_WIN32

Tor Lillqvist's avatar
Tor Lillqvist committed
194
gchar *
195
_glib_get_dll_directory (void)
Tor Lillqvist's avatar
Tor Lillqvist committed
196
{
197 198 199 200
  gchar *retval;
  gchar *p;
  wchar_t wc_fn[MAX_PATH];

201
#ifdef DLL_EXPORT
Tor Lillqvist's avatar
Tor Lillqvist committed
202 203
  if (glib_dll == NULL)
    return NULL;
204
#endif
205 206 207 208 209 210 211 212 213

  /* This code is different from that in
   * g_win32_get_package_installation_directory_of_module() in that
   * here we return the actual folder where the GLib DLL is. We don't
   * do the check for it being in a "bin" or "lib" subfolder and then
   * returning the parent of that.
   *
   * In a statically built GLib, glib_dll will be NULL and we will
   * thus look up the application's .exe file's location.
214
   */
215 216 217 218 219 220 221 222 223 224 225 226 227 228
  if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
    return NULL;

  retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);

  p = strrchr (retval, G_DIR_SEPARATOR);
  if (p == NULL)
    {
      /* Wtf? */
      return NULL;
    }
  *p = '\0';

  return retval;
Tor Lillqvist's avatar
Tor Lillqvist committed
229 230
}

231 232
#endif

233 234 235
/**
 * glib_check_version:
 * @required_major: the required major version.
236 237
 * @required_minor: the required minor version.
 * @required_micro: the required micro version.
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
 *
 * Checks that the GLib library in use is compatible with the
 * given version. Generally you would pass in the constants
 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
 * as the three arguments to this function; that produces
 * a check that the library in use is compatible with
 * the version of GLib the application or module was compiled
 * against.
 *
 * Compatibility is defined by two things: first the version
 * of the running library is newer than the version
 * @required_major.required_minor.@required_micro. Second
 * the running library must be binary compatible with the
 * version @required_major.required_minor.@required_micro
 * (same major version.)
 *
 * Return value: %NULL if the GLib library is compatible with the
 *   given version, or a string describing the version mismatch.
 *   The returned string is owned by GLib and must not be modified
 *   or freed.
 *
 * Since: 2.6
 **/
const gchar *
glib_check_version (guint required_major,
                    guint required_minor,
                    guint required_micro)
{
  gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
  gint required_effective_micro = 100 * required_minor + required_micro;

  if (required_major > GLIB_MAJOR_VERSION)
    return "GLib version too old (major mismatch)";
  if (required_major < GLIB_MAJOR_VERSION)
    return "GLib version too new (major mismatch)";
  if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
    return "GLib version too new (micro mismatch)";
  if (required_effective_micro > glib_effective_micro)
    return "GLib version too old (micro mismatch)";
  return NULL;
}

280
#if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
281 282 283 284 285 286 287 288 289 290 291 292 293 294
/**
 * g_memmove: 
 * @dest: the destination address to copy the bytes to.
 * @src: the source address to copy the bytes from.
 * @len: the number of bytes to copy.
 *
 * Copies a block of memory @len bytes long, from @src to @dest.
 * The source and destination areas may overlap.
 *
 * In order to use this function, you must include 
 * <filename>string.h</filename> yourself, because this macro will 
 * typically simply resolve to memmove() and GLib does not include 
 * <filename>string.h</filename> for you.
 */
295
void 
296 297 298
g_memmove (gpointer      dest, 
	   gconstpointer src, 
	   gulong        len)
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
{
  gchar* destptr = dest;
  const gchar* srcptr = src;
  if (src + len < dest || dest + len < src)
    {
      bcopy (src, dest, len);
      return;
    }
  else if (dest <= src)
    {
      while (len--)
	*(destptr++) = *(srcptr++);
    }
  else
    {
      destptr += len;
      srcptr += len;
      while (len--)
	*(--destptr) = *(--srcptr);
    }
}
#endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */

322 323 324 325
#ifdef G_OS_WIN32
#undef g_atexit
#endif

326 327
/**
 * g_atexit:
328
 * @func: (scope async): the function to call on normal program termination.
329 330
 * 
 * Specifies a function to be called at normal program termination.
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
 *
 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
 * macro that maps to a call to the atexit() function in the C
 * library. This means that in case the code that calls g_atexit(),
 * i.e. atexit(), is in a DLL, the function will be called when the
 * DLL is detached from the program. This typically makes more sense
 * than that the function is called when the GLib DLL is detached,
 * which happened earlier when g_atexit() was a function in the GLib
 * DLL.
 *
 * The behaviour of atexit() in the context of dynamically loaded
 * modules is not formally specified and varies wildly.
 *
 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
 * loaded module which is unloaded before the program terminates might
 * well cause a crash at program exit.
 *
 * Some POSIX systems implement atexit() like Windows, and have each
 * dynamically loaded module maintain an own atexit chain that is
 * called when the module is unloaded.
 *
 * On other POSIX systems, before a dynamically loaded module is
 * unloaded, the registered atexit functions (if any) residing in that
 * module are called, regardless where the code that registered them
 * resided. This is presumably the most robust approach.
 *
 * As can be seen from the above, for portability it's best to avoid
 * calling g_atexit() (or atexit()) except in the main executable of a
 * program.
360
 */
361 362 363 364
void
g_atexit (GVoidFunc func)
{
  gint result;
Havoc Pennington's avatar
Havoc Pennington committed
365
  const gchar *error = NULL;
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395

  /* keep this in sync with glib.h */

#ifdef	G_NATIVE_ATEXIT
  result = ATEXIT (func);
  if (result)
    error = g_strerror (errno);
#elif defined (HAVE_ATEXIT)
#  ifdef NeXT /* @#%@! NeXTStep */
  result = !atexit ((void (*)(void)) func);
  if (result)
    error = g_strerror (errno);
#  else
  result = atexit ((void (*)(void)) func);
  if (result)
    error = g_strerror (errno);
#  endif /* NeXT */
#elif defined (HAVE_ON_EXIT)
  result = on_exit ((void (*)(int, void *)) func, NULL);
  if (result)
    error = g_strerror (errno);
#else
  result = 0;
  error = "no implementation";
#endif /* G_NATIVE_ATEXIT */

  if (error)
    g_error ("Could not register atexit() function: %s", error);
}

Havoc Pennington's avatar
Havoc Pennington committed
396 397 398 399 400
/* Based on execvp() from GNU Libc.
 * Some of this code is cut-and-pasted into gspawn.c
 */

static gchar*
401 402
my_strchrnul (const gchar *str, 
	      gchar        c)
Havoc Pennington's avatar
Havoc Pennington committed
403 404 405 406 407 408 409 410
{
  gchar *p = (gchar*)str;
  while (*p && (*p != c))
    ++p;

  return p;
}

411 412
#ifdef G_OS_WIN32

413
static gchar *inner_find_program_in_path (const gchar *program);
414 415 416 417 418 419

gchar*
g_find_program_in_path (const gchar *program)
{
  const gchar *last_dot = strrchr (program, '.');

420 421 422
  if (last_dot == NULL ||
      strchr (last_dot, '\\') != NULL ||
      strchr (last_dot, '/') != NULL)
423 424
    {
      const gint program_length = strlen (program);
425 426 427 428 429
      gchar *pathext = g_build_path (";",
				     ".exe;.cmd;.bat;.com",
				     g_getenv ("PATHEXT"),
				     NULL);
      gchar *p;
430 431 432 433 434 435
      gchar *decorated_program;
      gchar *retval;

      p = pathext;
      do
	{
436
	  gchar *q = my_strchrnul (p, ';');
437

438
	  decorated_program = g_malloc (program_length + (q-p) + 1);
439
	  memcpy (decorated_program, program, program_length);
440 441
	  memcpy (decorated_program+program_length, p, q-p);
	  decorated_program [program_length + (q-p)] = '\0';
442 443 444 445 446
	  
	  retval = inner_find_program_in_path (decorated_program);
	  g_free (decorated_program);

	  if (retval != NULL)
447 448 449 450 451
	    {
	      g_free (pathext);
	      return retval;
	    }
	  p = q;
452
	} while (*p++ != '\0');
453
      g_free (pathext);
454 455 456 457 458 459 460 461
      return NULL;
    }
  else
    return inner_find_program_in_path (program);
}

#endif

Havoc Pennington's avatar
Havoc Pennington committed
462 463
/**
 * g_find_program_in_path:
464
 * @program: a program name in the GLib file name encoding
Havoc Pennington's avatar
Havoc Pennington committed
465
 * 
Havoc Pennington's avatar
Havoc Pennington committed
466
 * Locates the first executable named @program in the user's path, in the
Havoc Pennington's avatar
Havoc Pennington committed
467
 * same way that execvp() would locate it. Returns an allocated string
468
 * with the absolute path name, or %NULL if the program is not found in
Havoc Pennington's avatar
Havoc Pennington committed
469
 * the path. If @program is already an absolute path, returns a copy of
470 471
 * @program if @program exists and is executable, and %NULL otherwise.
 *  
472 473
 * On Windows, if @program does not have a file type suffix, tries
 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
474 475 476
 * the <envar>PATHEXT</envar> environment variable. 
 * 
 * On Windows, it looks for the file in the same way as CreateProcess() 
477
 * would. This means first in the directory where the executing
478 479
 * program was loaded from, then in the current directory, then in the
 * Windows 32-bit system directory, then in the Windows directory, and
480 481 482
 * finally in the directories in the <envar>PATH</envar> environment 
 * variable. If the program is found, the return value contains the 
 * full name including the type suffix.
483
 *
484
 * Return value: absolute path, or %NULL
Havoc Pennington's avatar
Havoc Pennington committed
485
 **/
486
#ifdef G_OS_WIN32
487 488 489
static gchar *
inner_find_program_in_path (const gchar *program)
#else
Havoc Pennington's avatar
Havoc Pennington committed
490
gchar*
Havoc Pennington's avatar
Havoc Pennington committed
491
g_find_program_in_path (const gchar *program)
492
#endif
Havoc Pennington's avatar
Havoc Pennington committed
493
{
Havoc Pennington's avatar
Havoc Pennington committed
494 495
  const gchar *path, *p;
  gchar *name, *freeme;
496
#ifdef G_OS_WIN32
497 498 499
  const gchar *path_copy;
  gchar *filename = NULL, *appdir = NULL;
  gchar *sysdir = NULL, *windir = NULL;
500 501 502
  int n;
  wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
    wwindir[MAXPATHLEN];
503
#endif
504 505
  gsize len;
  gsize pathlen;
Havoc Pennington's avatar
Havoc Pennington committed
506

Havoc Pennington's avatar
Havoc Pennington committed
507
  g_return_val_if_fail (program != NULL, NULL);
Havoc Pennington's avatar
Havoc Pennington committed
508

509 510 511 512
  /* If it is an absolute path, or a relative path including subdirectories,
   * don't look in PATH.
   */
  if (g_path_is_absolute (program)
513 514 515 516 517
      || strchr (program, G_DIR_SEPARATOR) != NULL
#ifdef G_OS_WIN32
      || strchr (program, '/') != NULL
#endif
      )
Havoc Pennington's avatar
Havoc Pennington committed
518
    {
519 520
      if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
	  !g_file_test (program, G_FILE_TEST_IS_DIR))
Havoc Pennington's avatar
Havoc Pennington committed
521
        return g_strdup (program);
Havoc Pennington's avatar
Havoc Pennington committed
522 523 524 525 526
      else
        return NULL;
    }
  
  path = g_getenv ("PATH");
527
#if defined(G_OS_UNIX) || defined(G_OS_BEOS)
Havoc Pennington's avatar
Havoc Pennington committed
528 529 530
  if (path == NULL)
    {
      /* There is no `PATH' in the environment.  The default
Havoc Pennington's avatar
Havoc Pennington committed
531
       * search path in GNU libc is the current directory followed by
Havoc Pennington's avatar
Havoc Pennington committed
532 533 534 535 536 537 538 539 540 541
       * the path `confstr' returns for `_CS_PATH'.
       */
      
      /* In GLib we put . last, for security, and don't use the
       * unportable confstr(); UNIX98 does not actually specify
       * what to search if PATH is unset. POSIX may, dunno.
       */
      
      path = "/bin:/usr/bin:.";
    }
542
#else
543 544 545 546 547 548 549 550 551 552 553
  n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
  if (n > 0 && n < MAXPATHLEN)
    filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
  
  n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
  if (n > 0 && n < MAXPATHLEN)
    sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
  
  n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
  if (n > 0 && n < MAXPATHLEN)
    windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
  
  if (filename)
    {
      appdir = g_path_get_dirname (filename);
      g_free (filename);
    }
  
  path = g_strdup (path);

  if (windir)
    {
      const gchar *tem = path;
      path = g_strconcat (windir, ";", path, NULL);
      g_free ((gchar *) tem);
      g_free (windir);
    }
  
  if (sysdir)
    {
      const gchar *tem = path;
      path = g_strconcat (sysdir, ";", path, NULL);
      g_free ((gchar *) tem);
      g_free (sysdir);
    }
  
579
  {
580 581 582
    const gchar *tem = path;
    path = g_strconcat (".;", path, NULL);
    g_free ((gchar *) tem);
583
  }
584 585 586 587 588 589 590 591 592 593
  
  if (appdir)
    {
      const gchar *tem = path;
      path = g_strconcat (appdir, ";", path, NULL);
      g_free ((gchar *) tem);
      g_free (appdir);
    }

  path_copy = path;
594
#endif
Havoc Pennington's avatar
Havoc Pennington committed
595
  
Havoc Pennington's avatar
Havoc Pennington committed
596
  len = strlen (program) + 1;
Havoc Pennington's avatar
Havoc Pennington committed
597 598 599 600
  pathlen = strlen (path);
  freeme = name = g_malloc (pathlen + len + 1);
  
  /* Copy the file name at the top, including '\0'  */
Havoc Pennington's avatar
Havoc Pennington committed
601
  memcpy (name + pathlen + 1, program, len);
Havoc Pennington's avatar
Havoc Pennington committed
602 603
  name = name + pathlen;
  /* And add the slash before the filename  */
604
  *name = G_DIR_SEPARATOR;
Havoc Pennington's avatar
Havoc Pennington committed
605 606 607 608 609 610 611
  
  p = path;
  do
    {
      char *startp;

      path = p;
612
      p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
Havoc Pennington's avatar
Havoc Pennington committed
613 614 615 616 617 618 619 620 621

      if (p == path)
        /* Two adjacent colons, or a colon at the beginning or the end
         * of `PATH' means to search the current directory.
         */
        startp = name + 1;
      else
        startp = memcpy (name - (p - path), path, p - path);

622 623
      if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
	  !g_file_test (startp, G_FILE_TEST_IS_DIR))
Havoc Pennington's avatar
Havoc Pennington committed
624 625 626 627
        {
          gchar *ret;
          ret = g_strdup (startp);
          g_free (freeme);
628
#ifdef G_OS_WIN32
629
	  g_free ((gchar *) path_copy);
630
#endif
Havoc Pennington's avatar
Havoc Pennington committed
631 632 633 634 635 636
          return ret;
        }
    }
  while (*p++ != '\0');
  
  g_free (freeme);
637
#ifdef G_OS_WIN32
638
  g_free ((gchar *) path_copy);
639
#endif
Havoc Pennington's avatar
Havoc Pennington committed
640 641 642 643

  return NULL;
}

644 645 646 647 648 649 650 651 652
/**
 * g_basename:
 * @file_name: the name of the file.
 * 
 * Gets the name of the file without any leading directory components.  
 * It returns a pointer into the given file name string.
 * 
 * Return value: the name of the file without any leading directory components.
 *
653
 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
654 655
 * g_path_get_basename() allocates new memory for the returned string, unlike
 * this function which returns a pointer into the argument.
656
 **/
657
const gchar *
658 659 660 661 662 663
g_basename (const gchar	   *file_name)
{
  register gchar *base;
  
  g_return_val_if_fail (file_name != NULL, NULL);
  
664
  base = strrchr (file_name, G_DIR_SEPARATOR);
665 666 667 668 669 670 671 672 673

#ifdef G_OS_WIN32
  {
    gchar *q = strrchr (file_name, '/');
    if (base == NULL || (q != NULL && q > base))
	base = q;
  }
#endif

674 675
  if (base)
    return base + 1;
676

677
#ifdef G_OS_WIN32
678
  if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
679
    return (gchar*) file_name + 2;
680
#endif /* G_OS_WIN32 */
681 682 683 684
  
  return (gchar*) file_name;
}

685 686 687 688 689 690 691 692 693 694 695 696 697
/**
 * g_path_get_basename:
 * @file_name: the name of the file.
 *
 * Gets the last component of the filename. If @file_name ends with a 
 * directory separator it gets the component before the last slash. If 
 * @file_name consists only of directory separators (and on Windows, 
 * possibly a drive letter), a single separator is returned. If
 * @file_name is empty, it gets ".".
 *
 * Return value: a newly allocated string containing the last component of 
 *   the filename.
 */
698 699 700
gchar*
g_path_get_basename (const gchar   *file_name)
{
701 702 703
  register gssize base;             
  register gssize last_nonslash;    
  gsize len;    
704 705 706
  gchar *retval;
 
  g_return_val_if_fail (file_name != NULL, NULL);
707

708 709 710
  if (file_name[0] == '\0')
    /* empty string */
    return g_strdup (".");
711
  
712 713
  last_nonslash = strlen (file_name) - 1;

714
  while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
715 716 717 718 719 720 721
    last_nonslash--;

  if (last_nonslash == -1)
    /* string only containing slashes */
    return g_strdup (G_DIR_SEPARATOR_S);

#ifdef G_OS_WIN32
722
  if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
723 724 725 726 727 728
    /* string only containing slashes and a drive */
    return g_strdup (G_DIR_SEPARATOR_S);
#endif /* G_OS_WIN32 */

  base = last_nonslash;

729
  while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
730 731 732
    base--;

#ifdef G_OS_WIN32
733
  if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
734 735 736 737 738 739 740 741 742 743
    base = 1;
#endif /* G_OS_WIN32 */

  len = last_nonslash - base;
  retval = g_malloc (len + 1);
  memcpy (retval, file_name + base + 1, len);
  retval [len] = '\0';
  return retval;
}

744 745 746 747
/**
 * g_path_is_absolute:
 * @file_name: a file name.
 *
748 749
 * Returns %TRUE if the given @file_name is an absolute file name.
 * Note that this is a somewhat vague concept on Windows.
750
 *
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
 * On POSIX systems, an absolute file name is well-defined. It always
 * starts from the single root directory. For example "/usr/local".
 *
 * On Windows, the concepts of current drive and drive-specific
 * current directory introduce vagueness. This function interprets as
 * an absolute file name one that either begins with a directory
 * separator such as "\Users\tml" or begins with the root on a drive,
 * for example "C:\Windows". The first case also includes UNC paths
 * such as "\\myserver\docs\foo". In all cases, either slashes or
 * backslashes are accepted.
 *
 * Note that a file name relative to the current drive root does not
 * truly specify a file uniquely over time and across processes, as
 * the current drive is a per-process value and can be changed.
 *
 * File names relative the current directory on some specific drive,
 * such as "D:foo/bar", are not interpreted as absolute by this
 * function, but they obviously are not relative to the normal current
 * directory as returned by getcwd() or g_get_current_dir()
 * either. Such paths should be avoided, or need to be handled using
 * Windows-specific code.
 *
 * Returns: %TRUE if @file_name is absolute. 
774
 */
775 776 777 778 779
gboolean
g_path_is_absolute (const gchar *file_name)
{
  g_return_val_if_fail (file_name != NULL, FALSE);
  
780
  if (G_IS_DIR_SEPARATOR (file_name[0]))
781 782
    return TRUE;

783
#ifdef G_OS_WIN32
784
  /* Recognize drive letter on native Windows */
785 786
  if (g_ascii_isalpha (file_name[0]) && 
      file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
787
    return TRUE;
788
#endif /* G_OS_WIN32 */
789 790 791 792

  return FALSE;
}

793 794 795 796 797 798 799 800 801 802
/**
 * g_path_skip_root:
 * @file_name: a file name.
 *
 * Returns a pointer into @file_name after the root component, i.e. after
 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
 * path it returns %NULL.
 *
 * Returns: a pointer into @file_name after the root component.
 */
803
const gchar *
Havoc Pennington's avatar
Havoc Pennington committed
804
g_path_skip_root (const gchar *file_name)
805 806 807
{
  g_return_val_if_fail (file_name != NULL, NULL);
  
808
#ifdef G_PLATFORM_WIN32
809 810 811
  /* Skip \\server\share or //server/share */
  if (G_IS_DIR_SEPARATOR (file_name[0]) &&
      G_IS_DIR_SEPARATOR (file_name[1]) &&
812 813
      file_name[2] &&
      !G_IS_DIR_SEPARATOR (file_name[2]))
814
    {
815
      gchar *p;
816

817 818 819 820 821 822 823 824 825 826
      p = strchr (file_name + 2, G_DIR_SEPARATOR);
#ifdef G_OS_WIN32
      {
	gchar *q = strchr (file_name + 2, '/');
	if (p == NULL || (q != NULL && q < p))
	  p = q;
      }
#endif
      if (p &&
	  p > file_name + 2 &&
827 828 829 830
	  p[1])
	{
	  file_name = p + 1;

831
	  while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
832 833 834
	    file_name++;

	  /* Possibly skip a backslash after the share name */
835
	  if (G_IS_DIR_SEPARATOR (file_name[0]))
836 837
	    file_name++;

Havoc Pennington's avatar
Havoc Pennington committed
838
	  return (gchar *)file_name;
839 840
	}
    }
841 842 843
#endif
  
  /* Skip initial slashes */
844
  if (G_IS_DIR_SEPARATOR (file_name[0]))
845
    {
846
      while (G_IS_DIR_SEPARATOR (file_name[0]))
847
	file_name++;
Havoc Pennington's avatar
Havoc Pennington committed
848
      return (gchar *)file_name;
849
    }
850

851
#ifdef G_OS_WIN32
852
  /* Skip X:\ */
853
  if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
Havoc Pennington's avatar
Havoc Pennington committed
854
    return (gchar *)file_name + 3;
855 856 857 858 859
#endif

  return NULL;
}

860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
/**
 * g_bit_nth_lsf:
 * @mask: a #gulong containing flags
 * @nth_bit: the index of the bit to start the search from
 *
 * Find the position of the first bit set in @mask, searching
 * from (but not including) @nth_bit upwards. Bits are numbered
 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
 * usually). To start searching from the 0th bit, set @nth_bit to -1.
 *
 * Returns: the index of the first bit set which is higher than @nth_bit
 */

/**
 * g_bit_nth_msf:
 * @mask: a #gulong containing flags
 * @nth_bit: the index of the bit to start the search from
 *
 * Find the position of the first bit set in @mask, searching
 * from (but not including) @nth_bit downwards. Bits are numbered
 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
 * usually). To start searching from the last bit, set @nth_bit to
 * -1 or GLIB_SIZEOF_LONG * 8.
 *
 * Returns: the index of the first bit set which is lower than @nth_bit
 */

/**
 * g_bit_storage:
 * @number: a #guint
 *
 * Gets the number of bits used to hold @number,
 * e.g. if @number is 4, 3 bits are needed.
 *
 * Returns: the number of bits used to hold @number
 */

/**
 * g_dirname:
 * @file_name: the name of the file
 *
 * Gets the directory components of a file name.
 * If the file name has no directory components "." is returned.
 * The returned string should be freed when no longer needed.
 *
 * Returns: the directory components of the file
 *
 * Deprecated: use g_path_get_dirname() instead
 */

910 911 912 913 914 915 916 917 918 919
/**
 * g_path_get_dirname:
 * @file_name: the name of the file.
 *
 * Gets the directory components of a file name.  If the file name has no
 * directory components "." is returned.  The returned string should be
 * freed when no longer needed.
 * 
 * Returns: the directory components of the file.
 */
920
gchar*
921
g_path_get_dirname (const gchar	   *file_name)
922 923
{
  register gchar *base;
924
  register gsize len;    
925 926 927
  
  g_return_val_if_fail (file_name != NULL, NULL);
  
928
  base = strrchr (file_name, G_DIR_SEPARATOR);
929 930 931 932 933 934 935
#ifdef G_OS_WIN32
  {
    gchar *q = strrchr (file_name, '/');
    if (base == NULL || (q != NULL && q > base))
	base = q;
  }
#endif
936
  if (!base)
937 938 939 940 941 942 943 944 945 946 947 948 949 950
    {
#ifdef G_OS_WIN32
      if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
	{
	  gchar drive_colon_dot[4];

	  drive_colon_dot[0] = file_name[0];
	  drive_colon_dot[1] = ':';
	  drive_colon_dot[2] = '.';
	  drive_colon_dot[3] = '\0';

	  return g_strdup (drive_colon_dot);
	}
#endif
951
    return g_strdup (".");
952 953
    }

954
  while (base > file_name && G_IS_DIR_SEPARATOR (*base))
955
    base--;
956 957

#ifdef G_OS_WIN32
958 959 960 961 962 963 964 965 966 967 968 969
  /* base points to the char before the last slash.
   *
   * In case file_name is the root of a drive (X:\) or a child of the
   * root of a drive (X:\foo), include the slash.
   *
   * In case file_name is the root share of an UNC path
   * (\\server\share), add a slash, returning \\server\share\ .
   *
   * In case file_name is a direct child of a share in an UNC path
   * (\\server\share\foo), include the slash after the share name,
   * returning \\server\share\ .
   */
970
  if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
    base++;
  else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
	   G_IS_DIR_SEPARATOR (file_name[1]) &&
	   file_name[2] &&
	   !G_IS_DIR_SEPARATOR (file_name[2]) &&
	   base >= file_name + 2)
    {
      const gchar *p = file_name + 2;
      while (*p && !G_IS_DIR_SEPARATOR (*p))
	p++;
      if (p == base + 1)
	{
	  len = (guint) strlen (file_name) + 1;
	  base = g_new (gchar, len + 1);
	  strcpy (base, file_name);
	  base[len-1] = G_DIR_SEPARATOR;
	  base[len] = 0;
	  return base;
	}
      if (G_IS_DIR_SEPARATOR (*p))
	{
	  p++;
	  while (*p && !G_IS_DIR_SEPARATOR (*p))
	    p++;
	  if (p == base + 1)
	    base++;
	}
    }
999 1000
#endif

1001
  len = (guint) 1 + base - file_name;
Tim Janik's avatar
Tim Janik committed
1002
  
1003 1004 1005
  base = g_new (gchar, len + 1);
  g_memmove (base, file_name, len);
  base[len] = 0;
Tim Janik's avatar
Tim Janik committed
1006
  
1007 1008 1009
  return base;
}

1010 1011 1012 1013 1014 1015 1016 1017 1018
/**
 * g_get_current_dir:
 *
 * Gets the current directory.
 * The returned string should be freed when no longer needed. The encoding 
 * of the returned string is system defined. On Windows, it is always UTF-8.
 * 
 * Returns: the current directory.
 */
1019
gchar*
1020
g_get_current_dir (void)
1021
{
1022 1023
#ifdef G_OS_WIN32

1024
  gchar *dir = NULL;
1025 1026
  wchar_t dummy[2], *wdir;
  int len;
1027

1028 1029
  len = GetCurrentDirectoryW (2, dummy);
  wdir = g_new (wchar_t, len);
1030

1031 1032 1033 1034
  if (GetCurrentDirectoryW (len, wdir) == len - 1)
    dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
  
  g_free (wdir);
1035

1036 1037 1038
  if (dir == NULL)
    dir = g_strdup ("\\");

1039
  return dir;
1040

1041
#else
1042 1043 1044 1045 1046 1047 1048 1049

  gchar *buffer = NULL;
  gchar *dir = NULL;
  static gulong max_len = 0;

  if (max_len == 0) 
    max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
  
1050 1051 1052
  /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
   * and, if that wasn't bad enough, hangs in doing so.
   */
1053
#if	(defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
1054 1055
  buffer = g_new (gchar, max_len + 1);
  *buffer = 0;
1056
  dir = getwd (buffer);
1057
#else	/* !sun || !HAVE_GETCWD */
1058
  while (max_len < G_MAXULONG / 2)
1059
    {
1060
      g_free (buffer);
1061 1062 1063 1064 1065 1066 1067 1068 1069
      buffer = g_new (gchar, max_len + 1);
      *buffer = 0;
      dir = getcwd (buffer, max_len);

      if (dir || errno != ERANGE)
	break;

      max_len *= 2;
    }
1070
#endif	/* !sun || !HAVE_GETCWD */
1071
  
1072
  if (!dir || !*buffer)
1073
    {
1074 1075
      /* hm, should we g_error() out here?
       * this can happen if e.g. "./" has mode \0000
1076
       */
1077
      buffer[0] = G_DIR_SEPARATOR;
1078
      buffer[1] = 0;
1079
    }
1080 1081 1082

  dir = g_strdup (buffer);
  g_free (buffer);
1083
  
1084
  return dir;
1085
#endif /* !Win32 */
1086 1087
}

1088
G_LOCK_DEFINE_STATIC (g_utils_global);
1089

1090 1091 1092 1093
static	gchar	*g_tmp_dir = NULL;
static	gchar	*g_user_name = NULL;
static	gchar	*g_real_name = NULL;
static	gchar	*g_home_dir = NULL;
1094
static	gchar	*g_host_name = NULL;
1095

1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
#ifdef G_OS_WIN32
/* System codepage versions of the above, kept at file level so that they,
 * too, are produced only once.
 */
static	gchar	*g_tmp_dir_cp = NULL;
static	gchar	*g_user_name_cp = NULL;
static	gchar	*g_real_name_cp = NULL;
static	gchar	*g_home_dir_cp = NULL;
#endif

1106 1107 1108 1109 1110 1111
static  gchar   *g_user_data_dir = NULL;
static  gchar  **g_system_data_dirs = NULL;
static  gchar   *g_user_cache_dir = NULL;
static  gchar   *g_user_config_dir = NULL;
static  gchar  **g_system_config_dirs = NULL;

1112 1113 1114 1115 1116
static  gchar  **g_user_special_dirs = NULL;

/* fifteen minutes of fame for everybody */
#define G_USER_DIRS_EXPIRE      15 * 60

1117 1118 1119 1120 1121
#ifdef G_OS_WIN32

static gchar *
get_special_folder (int csidl)
{
1122
  wchar_t path[MAX_PATH+1];
1123 1124 1125 1126 1127 1128 1129 1130
  HRESULT hr;
  LPITEMIDLIST pidl = NULL;
  BOOL b;
  gchar *retval = NULL;

  hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
  if (hr == S_OK)
    {
1131
      b = SHGetPathFromIDListW (pidl, path);
1132
      if (b)
1133
	retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1134 1135
      CoTaskMemFree (pidl);
    }
1136
  return retval;
1137 1138
}

1139 1140 1141
static char *
get_windows_directory_root (void)
{
1142
  wchar_t wwindowsdir[MAX_PATH];
1143

1144
  if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1145 1146 1147 1148
    {
      /* Usually X:\Windows, but in terminal server environments
       * might be an UNC path, AFAIK.
       */
1149 1150 1151 1152 1153 1154 1155
      char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
      char *p;

      if (windowsdir == NULL)
	return g_strdup ("C:\\");

      p = (char *) g_path_skip_root (windowsdir);
1156 1157 1158
      if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
	p--;
      *p = '\0';
1159
      return windowsdir;
1160 1161 1162 1163 1164
    }
  else
    return g_strdup ("C:\\");
}

1165 1166
#endif

1167
/* HOLDS: g_utils_global_lock */
1168
static void
1169
g_get_any_init_do (void)
1170
{
1171 1172 1173
  gchar hostname[100];

  g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1174
  if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1175
    g_tmp_dir = g_strdup (g_getenv ("TMP"));
1176
  if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1177
    g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1178

1179
#ifdef G_OS_WIN32
1180
  if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1181 1182
    g_tmp_dir = get_windows_directory_root ();
#else  
1183
#ifdef P_tmpdir
1184
  if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1185 1186 1187 1188 1189 1190 1191
    {
      gsize k;    
      g_tmp_dir = g_strdup (P_tmpdir);
      k = strlen (g_tmp_dir);
      if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
	g_tmp_dir[k - 1] = '\0';
    }
1192
#endif
1193
  
1194
  if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1195 1196 1197
    {
      g_tmp_dir = g_strdup ("/tmp");
    }
1198
#endif	/* !G_OS_WIN32 */
1199
  
1200
#ifdef G_OS_WIN32
1201 1202 1203 1204
  /* We check $HOME first for Win32, though it is a last resort for Unix
   * where we prefer the results of getpwuid().
   */
  g_home_dir = g_strdup (g_getenv ("HOME"));
1205

1206 1207 1208 1209 1210
  /* Only believe HOME if it is an absolute path and exists */
  if (g_home_dir)
    {
      if (!(g_path_is_absolute (g_home_dir) &&
	    g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1211
	{
1212 1213
	  g_free (g_home_dir);
	  g_home_dir = NULL;
1214
	}
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
    }
  
  /* In case HOME is Unix-style (it happens), convert it to
   * Windows style.
   */
  if (g_home_dir)
    {
      gchar *p;
      while ((p = strchr (g_home_dir, '/')) != NULL)
	*p = '\\';
    }
1226

1227 1228 1229 1230 1231 1232
  if (!g_home_dir)
    {
      /* USERPROFILE is probably the closest equivalent to $HOME? */
      if (g_getenv ("USERPROFILE") != NULL)
	g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
    }
1233

1234 1235 1236 1237 1238
  if (!g_home_dir)
    g_home_dir = get_special_folder (CSIDL_PROFILE);
  
  if (!g_home_dir)
    g_home_dir = get_windows_directory_root ();
1239
#endif /* G_OS_WIN32 */
1240
  
1241
#ifdef HAVE_PWD_H
1242 1243 1244 1245
  {
    struct passwd *pw = NULL;
    gpointer buffer = NULL;
    gint error;
1246 1247
    gchar *logname;

1248
#  if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1249
    struct passwd pwd;
1250
#    ifdef _SC_GETPW_R_SIZE_MAX  
1251 1252 1253 1254 1255
    /* This reurns the maximum length */
    glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
    
    if (bufsize < 0)
      bufsize = 64;
1256
#    else /* _SC_GETPW_R_SIZE_MAX */
1257
    glong bufsize = 64;
1258
#    endif /* _SC_GETPW_R_SIZE_MAX */
1259 1260 1261

    logname = (gchar *) g_getenv ("LOGNAME");
        
1262 1263 1264 1265 1266 1267 1268 1269
    do
      {
	g_free (buffer);
	/* we allocate 6 extra bytes to work around a bug in 
	 * Mac OS < 10.3. See #156446
	 */
	buffer = g_malloc (bufsize + 6);
	errno = 0;
1270
	
1271
#    ifdef HAVE_POSIX_GETPWUID_R
1272 1273 1274 1275 1276 1277 1278 1279 1280
	if (logname) {
	  error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
	  if (!pw || (pw->pw_uid != getuid ())) {
	    /* LOGNAME is lying, fall back to looking up the uid */
	    error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
	  }
	} else {
	  error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
	}
1281
	error = error < 0 ? errno : error;
1282
#    else /* HAVE_NONPOSIX_GETPWUID_R */
1283
   /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1284
#      if defined(_AIX) || defined(__hpux)
1285 1286
	error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
	pw = error == 0 ? &pwd : NULL;
1287
#      else /* !_AIX */
1288 1289 1290 1291 1292 1293 1294 1295 1296
	if (logname) {
	  pw = getpwnam_r (logname, &pwd, buffer, bufsize);
	  if (!pw || (pw->pw_uid != getuid ())) {
	    /* LOGNAME is lying, fall back to looking up the uid */
	    pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
	  }
	} else {
	  pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
	}
1297
	error = pw ? 0 : errno;
1298
#      endif /* !_AIX */            
1299
#    endif /* HAVE_NONPOSIX_GETPWUID_R */
1300
	
1301 1302
	if (!pw)
	  {
1303 1304 1305
	    /* we bail out prematurely if the user id can't be found
	     * (should be pretty rare case actually), or if the buffer
	     * should be sufficiently big and lookups are still not
Matthias Clasen's avatar
Matthias Clasen committed
1306
	     * successful.
1307 1308
	     */
	    if (error == 0 || error == ENOENT)
1309
	      {
1310 1311 1312
		g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
			   (gulong) getuid ());
		break;
1313
	      }
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
	    if (bufsize > 32 * 1024)
	      {
		g_warning ("getpwuid_r(): failed due to: %s.",
			   g_strerror (error));
		break;
	      }
	    
	    bufsize *= 2;
	  }
      }
    while (!pw);
#  endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
    
    if (!pw)
      {
	setpwent ();
	pw = getpwuid (getuid ());
	endpwent ();
      }
    if (pw)
      {
	g_user_name = g_strdup (pw->pw_name);
1336

1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
	if (pw->pw_gecos && *pw->pw_gecos != '\0') 
	  {
	    gchar **gecos_fields;
	    gchar **name_parts;

	    /* split the gecos field and substitute '&' */
	    gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
	    name_parts = g_strsplit (gecos_fields[0], "&", 0);
	    pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
	    g_real_name = g_strjoinv (pw->pw_name, name_parts);
	    g_strfreev (gecos_fields);
	    g_strfreev (name_parts);
1349
	  }
1350 1351 1352

	if (!g_home_dir)
	  g_home_dir = g_strdup (pw->pw_dir);
1353
      }
1354 1355 1356
    g_free (buffer);
  }
  
1357
#else /* !HAVE_PWD_H */
1358
  
1359
#ifdef G_OS_WIN32
1360 1361 1362
  {
    guint len = UNLEN+1;
    wchar_t buffer[UNLEN+1];
1363
    
1364 1365 1366 1367 1368 1369
    if (GetUserNameW (buffer, (LPDWORD) &len))
      {
	g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
	g_real_name = g_strdup (g_user_name);
      }
  }
1370
#endif /* G_OS_WIN32 */
1371

1372
#endif /* !HAVE_PWD_H */
1373

1374
#ifndef G_OS_WIN32
1375 1376
  if (!g_home_dir)
    g_home_dir = g_strdup (g_getenv ("HOME"));
1377 1378
#endif

Asbjørn Pettersen's avatar
Asbjørn Pettersen committed
1379
#ifdef __EMX__
1380 1381
  /* change '\\' in %HOME% to '/' */
  g_strdelimit (g_home_dir, "\\",'/');
Asbjørn Pettersen's avatar
Asbjørn Pettersen committed
1382
#endif
1383 1384 1385 1386
  if (!g_user_name)
    g_user_name = g_strdup ("somebody");
  if (!g_real_name)
    g_real_name = g_strdup ("Unknown");
1387

1388
  {
1389
#ifndef G_OS_WIN32
1390
    gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1391
#else
1392 1393
    DWORD size = sizeof (hostname);
    gboolean hostname_fail = (!GetComputerName (hostname, &size));
1394
#endif
1395 1396
    g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
  }
1397

1398
#ifdef G_OS_WIN32
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
  g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
  g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
  g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);

  if (!g_tmp_dir_cp)
    g_tmp_dir_cp = g_strdup ("\\");
  if (!g_user_name_cp)
    g_user_name_cp = g_strdup ("somebody");
  if (!g_real_name_cp)
    g_real_name_cp = g_strdup ("Unknown");

  /* home_dir might be NULL, unlike tmp_dir, user_name and
   * real_name.
   */
  if (g_home_dir)
    g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
  else
    g_home_dir_cp = NULL;
1417
#endif /* G_OS_WIN32 */
1418 1419
}

1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
static inline void
g_get_any_init (void)
{
  if (!g_tmp_dir)
    g_get_any_init_do ();
}

static inline void
g_get_any_init_locked (void)
{
  G_LOCK (g_utils_global);
  g_get_any_init ();
  G_UNLOCK (g_utils_global);
}


1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
/**
 * g_get_user_name:
 *
 * Gets the user name of the current user. The encoding of the returned
 * string is system-defined. On UNIX, it might be the preferred file name
 * encoding, or something else, and there is no guarantee that it is even
 * consistent on a machine. On Windows, it is always UTF-8.
 *
 * Returns: the user name of the current user.
 */
1446
const gchar *
1447 1448
g_get_user_name (void)
{
1449
  g_get_any_init_locked ();
1450 1451 1452
  return g_user_name;
}

1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
/**
 * g_get_real_name:
 *
 * Gets the real name of the user. This usually comes from the user's entry 
 * in the <filename>passwd</filename> file. The encoding of the returned 
 * string is system-defined. (On Windows, it is, however, always UTF-8.) 
 * If the real user name cannot be determined, the string "Unknown" is 
 * returned.
 *
 * Returns: the user's real name.
 */
1464
const gchar *
1465 1466
g_get_real_name (void)
{
1467
  g_get_any_init_locked ();
1468 1469 1470
  return g_real_name;
}

1471 1472 1473
/**
 * g_get_home_dir:
 *
Matthias Clasen's avatar
Matthias Clasen committed
1474 1475
 * Gets the current user's home directory as defined in the 
 * password database.
1476 1477 1478
 *
 * Note that in contrast to traditional UNIX tools, this function 
 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar> 
Matthias Clasen's avatar
Matthias Clasen committed
1479
 * environment variable. 
1480
 *
Matthias Clasen's avatar
Matthias Clasen committed
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
 * One of the reasons for this decision is that applications in many 
 * cases need special handling to deal with the case where 
 * <envar>HOME</envar> is
 * <simplelist>
 *   <member>Not owned by the user</member>
 *   <member>Not writeable</member>
 *   <member>Not even readable</member>
 * </simplelist>
 * Since applications are in general <emphasis>not</emphasis> written 
 * to deal with these situations it was considered better to make 
Matthias Clasen's avatar
Matthias Clasen committed
1491
 * g_get_home_dir() not pay attention to <envar>HOME</envar> and to 
Matthias Clasen's avatar
Matthias Clasen committed
1492 1493
 * return the real home directory for the user. If applications
 * want to pay attention to <envar>HOME</envar>, they can do:
Matthias Clasen's avatar
Matthias Clasen committed
1494
 * |[
Matthias Clasen's avatar
Matthias Clasen committed
1495 1496
 *  const char *homedir = g_getenv ("HOME");
 *   if (!homedir)
Matthias Clasen's avatar
Matthias Clasen committed
1497
 *      homedir = g_get_home_dir (<!-- -->);
Matthias Clasen's avatar
Matthias Clasen committed
1498
 * ]|
Matthias Clasen's avatar
Matthias Clasen committed
1499 1500
 *
 * Returns: the current user's home directory
1501
 */
1502
const gchar *
1503 1504
g_get_home_dir (void)
{
1505
  g_get_any_init_locked ();
1506 1507 1508
  return g_home_dir;
}

1509 1510 1511 1512 1513 1514 1515 1516
/**
 * g_get_tmp_dir:
 *
 * Gets the directory to use for temporary files. This is found from 
 * inspecting the environment variables <envar>TMPDIR</envar>, 
 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none 
 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows. 
 * The encoding of the returned string is system-defined. On Windows, 
1517
 * it is always UTF-8. The return value is never %NULL or the empty string.
1518 1519
 *
 * Returns: the directory to use for temporary files.