Include a printf implementation supporting C99 snprintf and SUS
[platform/upstream/glib.git] / glib / gutils.c
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 #ifdef HAVE_CONFIG_H
32 #include <config.h>
33 #endif
34
35 #ifdef HAVE_UNISTD_H
36 #include <unistd.h>
37 #endif
38 #include <stdarg.h>
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <string.h>
42 #include <errno.h>
43 #ifdef HAVE_PWD_H
44 #include <pwd.h>
45 #endif
46 #include <sys/types.h>
47 #ifdef HAVE_SYS_PARAM_H
48 #include <sys/param.h>
49 #endif
50
51 /* implement gutils's inline functions
52  */
53 #define G_IMPLEMENT_INLINES 1
54 #define __G_UTILS_C__
55 #include "glib.h"
56 #include "gprintfint.h"
57
58 #ifdef  MAXPATHLEN
59 #define G_PATH_LENGTH   MAXPATHLEN
60 #elif   defined (PATH_MAX)
61 #define G_PATH_LENGTH   PATH_MAX
62 #elif   defined (_PC_PATH_MAX)
63 #define G_PATH_LENGTH   sysconf(_PC_PATH_MAX)
64 #else   
65 #define G_PATH_LENGTH   2048
66 #endif
67
68 #ifdef G_PLATFORM_WIN32
69 #  define STRICT                /* Strict typing, please */
70 #  include <windows.h>
71 #  undef STRICT
72 #  include <lmcons.h>           /* For UNLEN */
73 #  include <ctype.h>
74 #endif /* G_PLATFORM_WIN32 */
75
76 #ifdef G_OS_WIN32
77 #  include <direct.h>
78 #endif
79
80 #ifdef HAVE_CODESET
81 #include <langinfo.h>
82 #endif
83
84 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
85 #include <libintl.h>
86 #endif
87
88 const guint glib_major_version = GLIB_MAJOR_VERSION;
89 const guint glib_minor_version = GLIB_MINOR_VERSION;
90 const guint glib_micro_version = GLIB_MICRO_VERSION;
91 const guint glib_interface_age = GLIB_INTERFACE_AGE;
92 const guint glib_binary_age = GLIB_BINARY_AGE;
93
94 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
95 void 
96 g_memmove (gpointer dest, gconstpointer src, gulong len)
97 {
98   gchar* destptr = dest;
99   const gchar* srcptr = src;
100   if (src + len < dest || dest + len < src)
101     {
102       bcopy (src, dest, len);
103       return;
104     }
105   else if (dest <= src)
106     {
107       while (len--)
108         *(destptr++) = *(srcptr++);
109     }
110   else
111     {
112       destptr += len;
113       srcptr += len;
114       while (len--)
115         *(--destptr) = *(--srcptr);
116     }
117 }
118 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
119
120 void
121 g_atexit (GVoidFunc func)
122 {
123   gint result;
124   const gchar *error = NULL;
125
126   /* keep this in sync with glib.h */
127
128 #ifdef  G_NATIVE_ATEXIT
129   result = ATEXIT (func);
130   if (result)
131     error = g_strerror (errno);
132 #elif defined (HAVE_ATEXIT)
133 #  ifdef NeXT /* @#%@! NeXTStep */
134   result = !atexit ((void (*)(void)) func);
135   if (result)
136     error = g_strerror (errno);
137 #  else
138   result = atexit ((void (*)(void)) func);
139   if (result)
140     error = g_strerror (errno);
141 #  endif /* NeXT */
142 #elif defined (HAVE_ON_EXIT)
143   result = on_exit ((void (*)(int, void *)) func, NULL);
144   if (result)
145     error = g_strerror (errno);
146 #else
147   result = 0;
148   error = "no implementation";
149 #endif /* G_NATIVE_ATEXIT */
150
151   if (error)
152     g_error ("Could not register atexit() function: %s", error);
153 }
154
155 /* Based on execvp() from GNU Libc.
156  * Some of this code is cut-and-pasted into gspawn.c
157  */
158
159 static gchar*
160 my_strchrnul (const gchar *str, gchar c)
161 {
162   gchar *p = (gchar*)str;
163   while (*p && (*p != c))
164     ++p;
165
166   return p;
167 }
168
169 #ifdef G_OS_WIN32
170
171 gchar *inner_find_program_in_path (const gchar *program);
172
173 gchar*
174 g_find_program_in_path (const gchar *program)
175 {
176   const gchar *last_dot = strrchr (program, '.');
177
178   if (last_dot == NULL || strchr (last_dot, '\\') != NULL)
179     {
180       const gint program_length = strlen (program);
181       const gchar *pathext = getenv ("PATHEXT");
182       const gchar *p;
183       gchar *decorated_program;
184       gchar *retval;
185
186       if (pathext == NULL)
187         pathext = ".com;.exe;.bat";
188
189       p = pathext;
190       do
191         {
192           pathext = p;
193           p = my_strchrnul (pathext, ';');
194
195           decorated_program = g_malloc (program_length + (p-pathext) + 1);
196           memcpy (decorated_program, program, program_length);
197           memcpy (decorated_program+program_length, pathext, p-pathext);
198           decorated_program [program_length + (p-pathext)] = '\0';
199           
200           retval = inner_find_program_in_path (decorated_program);
201           g_free (decorated_program);
202
203           if (retval != NULL)
204             return retval;
205         } while (*p++ != '\0');
206       return NULL;
207     }
208   else
209     return inner_find_program_in_path (program);
210 }
211
212 #define g_find_program_in_path inner_find_program_in_path
213 #endif
214
215 /**
216  * g_find_program_in_path:
217  * @program: a program name
218  * 
219  * Locates the first executable named @program in the user's path, in the
220  * same way that execvp() would locate it. Returns an allocated string
221  * with the absolute path name, or NULL if the program is not found in
222  * the path. If @program is already an absolute path, returns a copy of
223  * @program if @program exists and is executable, and NULL otherwise.
224  * 
225  * On Windows, if @program does not have a file type suffix, tries to
226  * append the suffixes in the PATHEXT environment variable (if that
227  * doesn't exists, the suffixes .com, .exe, and .bat) in turn, and
228  * then look for the resulting file name in the same way as
229  * CreateProcess() would. This means first in the directory where the
230  * program was loaded from, then in the current directory, then in the
231  * Windows 32-bit system directory, then in the Windows directory, and
232  * finally in the directories in the PATH environment variable. If
233  * the program is found, the return value contains the full name
234  * including the type suffix.
235  *
236  * Return value: absolute path, or NULL
237  **/
238 gchar*
239 g_find_program_in_path (const gchar *program)
240 {
241   const gchar *path, *p;
242   gchar *name, *freeme;
243 #ifdef G_OS_WIN32
244   gchar *path_tmp;
245 #endif
246   size_t len;
247   size_t pathlen;
248
249   g_return_val_if_fail (program != NULL, NULL);
250
251   /* If it is an absolute path, or a relative path including subdirectories,
252    * don't look in PATH.
253    */
254   if (g_path_is_absolute (program)
255       || strchr (program, G_DIR_SEPARATOR) != NULL)
256     {
257       if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE))
258         return g_strdup (program);
259       else
260         return NULL;
261     }
262   
263   path = g_getenv ("PATH");
264 #ifdef G_OS_UNIX
265   if (path == NULL)
266     {
267       /* There is no `PATH' in the environment.  The default
268        * search path in GNU libc is the current directory followed by
269        * the path `confstr' returns for `_CS_PATH'.
270        */
271       
272       /* In GLib we put . last, for security, and don't use the
273        * unportable confstr(); UNIX98 does not actually specify
274        * what to search if PATH is unset. POSIX may, dunno.
275        */
276       
277       path = "/bin:/usr/bin:.";
278     }
279 #else
280   {
281     gchar *tmp;
282     gchar moddir[MAXPATHLEN], sysdir[MAXPATHLEN], windir[MAXPATHLEN];
283
284     GetModuleFileName (NULL, moddir, sizeof (moddir));
285     tmp = g_path_get_dirname (moddir);
286     GetSystemDirectory (sysdir, sizeof (sysdir));
287     GetWindowsDirectory (windir, sizeof (windir));
288     path_tmp = g_strconcat (tmp, ";.;", sysdir, ";", windir,
289                             (path != NULL ? ";" : NULL),
290                             (path != NULL ? path : NULL),
291                             NULL);
292     g_free (tmp);
293     path = path_tmp;
294   }
295 #endif
296   
297   len = strlen (program) + 1;
298   pathlen = strlen (path);
299   freeme = name = g_malloc (pathlen + len + 1);
300   
301   /* Copy the file name at the top, including '\0'  */
302   memcpy (name + pathlen + 1, program, len);
303   name = name + pathlen;
304   /* And add the slash before the filename  */
305   *name = G_DIR_SEPARATOR;
306   
307   p = path;
308   do
309     {
310       char *startp;
311
312       path = p;
313       p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
314
315       if (p == path)
316         /* Two adjacent colons, or a colon at the beginning or the end
317          * of `PATH' means to search the current directory.
318          */
319         startp = name + 1;
320       else
321         startp = memcpy (name - (p - path), path, p - path);
322
323       if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE))
324         {
325           gchar *ret;
326           ret = g_strdup (startp);
327           g_free (freeme);
328 #ifdef G_OS_WIN32
329           g_free (path_tmp);
330 #endif
331           return ret;
332         }
333     }
334   while (*p++ != '\0');
335   
336   g_free (freeme);
337 #ifdef G_OS_WIN32
338   g_free (path_tmp);
339 #endif
340
341   return NULL;
342 }
343
344 guint        
345 g_parse_debug_string  (const gchar     *string, 
346                        const GDebugKey *keys, 
347                        guint            nkeys)
348 {
349   guint i;
350   guint result = 0;
351   
352   g_return_val_if_fail (string != NULL, 0);
353   
354   if (!g_ascii_strcasecmp (string, "all"))
355     {
356       for (i=0; i<nkeys; i++)
357         result |= keys[i].value;
358     }
359   else
360     {
361       const gchar *p = string;
362       const gchar *q;
363       gboolean done = FALSE;
364       
365       while (*p && !done)
366         {
367           q = strchr (p, ':');
368           if (!q)
369             {
370               q = p + strlen(p);
371               done = TRUE;
372             }
373           
374           for (i=0; i<nkeys; i++)
375             if (g_ascii_strncasecmp(keys[i].key, p, q - p) == 0 &&
376                 keys[i].key[q - p] == '\0')
377               result |= keys[i].value;
378           
379           p = q + 1;
380         }
381     }
382   
383   return result;
384 }
385
386 G_CONST_RETURN gchar*
387 g_basename (const gchar    *file_name)
388 {
389   register gchar *base;
390   
391   g_return_val_if_fail (file_name != NULL, NULL);
392   
393   base = strrchr (file_name, G_DIR_SEPARATOR);
394   if (base)
395     return base + 1;
396
397 #ifdef G_OS_WIN32
398   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
399     return (gchar*) file_name + 2;
400 #endif /* G_OS_WIN32 */
401   
402   return (gchar*) file_name;
403 }
404
405 gchar*
406 g_path_get_basename (const gchar   *file_name)
407 {
408   register gssize base;             
409   register gssize last_nonslash;    
410   gsize len;    
411   gchar *retval;
412  
413   g_return_val_if_fail (file_name != NULL, NULL);
414
415   if (file_name[0] == '\0')
416     /* empty string */
417     return g_strdup (".");
418   
419   last_nonslash = strlen (file_name) - 1;
420
421   while (last_nonslash >= 0 && file_name [last_nonslash] == G_DIR_SEPARATOR)
422     last_nonslash--;
423
424   if (last_nonslash == -1)
425     /* string only containing slashes */
426     return g_strdup (G_DIR_SEPARATOR_S);
427
428 #ifdef G_OS_WIN32
429   if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
430     /* string only containing slashes and a drive */
431     return g_strdup (G_DIR_SEPARATOR_S);
432 #endif /* G_OS_WIN32 */
433
434   base = last_nonslash;
435
436   while (base >=0 && file_name [base] != G_DIR_SEPARATOR)
437     base--;
438
439 #ifdef G_OS_WIN32
440   if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
441     base = 1;
442 #endif /* G_OS_WIN32 */
443
444   len = last_nonslash - base;
445   retval = g_malloc (len + 1);
446   memcpy (retval, file_name + base + 1, len);
447   retval [len] = '\0';
448   return retval;
449 }
450
451 gboolean
452 g_path_is_absolute (const gchar *file_name)
453 {
454   g_return_val_if_fail (file_name != NULL, FALSE);
455   
456   if (file_name[0] == G_DIR_SEPARATOR
457 #ifdef G_OS_WIN32
458       || file_name[0] == '/'
459 #endif
460                                      )
461     return TRUE;
462
463 #ifdef G_OS_WIN32
464   /* Recognize drive letter on native Windows */
465   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && (file_name[2] == G_DIR_SEPARATOR || file_name[2] == '/'))
466     return TRUE;
467 #endif /* G_OS_WIN32 */
468
469   return FALSE;
470 }
471
472 G_CONST_RETURN gchar*
473 g_path_skip_root (const gchar *file_name)
474 {
475   g_return_val_if_fail (file_name != NULL, NULL);
476   
477 #ifdef G_PLATFORM_WIN32
478   /* Skip \\server\share (Win32) or //server/share (Cygwin) */
479   if (file_name[0] == G_DIR_SEPARATOR &&
480       file_name[1] == G_DIR_SEPARATOR &&
481       file_name[2])
482     {
483       gchar *p;
484
485       if ((p = strchr (file_name + 2, G_DIR_SEPARATOR)) > file_name + 2 &&
486           p[1])
487         {
488           file_name = p + 1;
489
490           while (file_name[0] && file_name[0] != G_DIR_SEPARATOR)
491             file_name++;
492
493           /* Possibly skip a backslash after the share name */
494           if (file_name[0] == G_DIR_SEPARATOR)
495             file_name++;
496
497           return (gchar *)file_name;
498         }
499     }
500 #endif
501   
502   /* Skip initial slashes */
503   if (file_name[0] == G_DIR_SEPARATOR)
504     {
505       while (file_name[0] == G_DIR_SEPARATOR)
506         file_name++;
507       return (gchar *)file_name;
508     }
509
510 #ifdef G_OS_WIN32
511   /* Skip X:\ */
512   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
513     return (gchar *)file_name + 3;
514 #endif
515
516   return NULL;
517 }
518
519 gchar*
520 g_path_get_dirname (const gchar    *file_name)
521 {
522   register gchar *base;
523   register gsize len;    
524   
525   g_return_val_if_fail (file_name != NULL, NULL);
526   
527   base = strrchr (file_name, G_DIR_SEPARATOR);
528   if (!base)
529     return g_strdup (".");
530   while (base > file_name && *base == G_DIR_SEPARATOR)
531     base--;
532   len = (guint) 1 + base - file_name;
533   
534   base = g_new (gchar, len + 1);
535   g_memmove (base, file_name, len);
536   base[len] = 0;
537   
538   return base;
539 }
540
541 gchar*
542 g_get_current_dir (void)
543 {
544   gchar *buffer = NULL;
545   gchar *dir = NULL;
546   static gulong max_len = 0;
547
548   if (max_len == 0) 
549     max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
550   
551   /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
552    * and, if that wasn't bad enough, hangs in doing so.
553    */
554 #if     (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
555   buffer = g_new (gchar, max_len + 1);
556   *buffer = 0;
557   dir = getwd (buffer);
558 #else   /* !sun || !HAVE_GETCWD */
559   while (max_len < G_MAXULONG / 2)
560     {
561       buffer = g_new (gchar, max_len + 1);
562       *buffer = 0;
563       dir = getcwd (buffer, max_len);
564
565       if (dir || errno != ERANGE)
566         break;
567
568       g_free (buffer);
569       max_len *= 2;
570     }
571 #endif  /* !sun || !HAVE_GETCWD */
572   
573   if (!dir || !*buffer)
574     {
575       /* hm, should we g_error() out here?
576        * this can happen if e.g. "./" has mode \0000
577        */
578       buffer[0] = G_DIR_SEPARATOR;
579       buffer[1] = 0;
580     }
581
582   dir = g_strdup (buffer);
583   g_free (buffer);
584   
585   return dir;
586 }
587
588 G_CONST_RETURN gchar*
589 g_getenv (const gchar *variable)
590 {
591 #ifndef G_OS_WIN32
592   g_return_val_if_fail (variable != NULL, NULL);
593
594   return getenv (variable);
595 #else
596   G_LOCK_DEFINE_STATIC (getenv);
597   struct env_struct
598   {
599     gchar *key;
600     gchar *value;
601   } *env;
602   static GArray *environs = NULL;
603   gchar *system_env;
604   guint length, i;
605   gchar dummy[2];
606
607   g_return_val_if_fail (variable != NULL, NULL);
608   
609   G_LOCK (getenv);
610
611   if (!environs)
612     environs = g_array_new (FALSE, FALSE, sizeof (struct env_struct));
613
614   /* First we try to find the envinronment variable inside the already
615    * found ones.
616    */
617
618   for (i = 0; i < environs->len; i++)
619     {
620       env = &g_array_index (environs, struct env_struct, i);
621       if (strcmp (env->key, variable) == 0)
622         {
623           g_assert (env->value);
624           G_UNLOCK (getenv);
625           return env->value;
626         }
627     }
628
629   /* If not found, we ask the system */
630
631   system_env = getenv (variable);
632   if (!system_env)
633     {
634       G_UNLOCK (getenv);
635       return NULL;
636     }
637
638   /* On Windows NT, it is relatively typical that environment variables
639    * contain references to other environment variables. Handle that by
640    * calling ExpandEnvironmentStrings.
641    */
642
643   g_array_set_size (environs, environs->len + 1);
644
645   env = &g_array_index (environs, struct env_struct, environs->len - 1);
646
647   /* First check how much space we need */
648   length = ExpandEnvironmentStrings (system_env, dummy, 2);
649
650   /* Then allocate that much, and actualy do the expansion and insert
651    * the new found pair into our buffer 
652    */
653
654   env->value = g_malloc (length);
655   env->key = g_strdup (variable);
656
657   ExpandEnvironmentStrings (system_env, env->value, length);
658
659   G_UNLOCK (getenv);
660   return env->value;
661 #endif
662 }
663
664
665 G_LOCK_DEFINE_STATIC (g_utils_global);
666
667 static  gchar   *g_tmp_dir = NULL;
668 static  gchar   *g_user_name = NULL;
669 static  gchar   *g_real_name = NULL;
670 static  gchar   *g_home_dir = NULL;
671
672 /* HOLDS: g_utils_global_lock */
673 static void
674 g_get_any_init (void)
675 {
676   if (!g_tmp_dir)
677     {
678       g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
679       if (!g_tmp_dir)
680         g_tmp_dir = g_strdup (g_getenv ("TMP"));
681       if (!g_tmp_dir)
682         g_tmp_dir = g_strdup (g_getenv ("TEMP"));
683       
684 #ifdef P_tmpdir
685       if (!g_tmp_dir)
686         {
687           gsize k;    
688           g_tmp_dir = g_strdup (P_tmpdir);
689           k = strlen (g_tmp_dir);
690           if (k > 1 && g_tmp_dir[k - 1] == G_DIR_SEPARATOR)
691             g_tmp_dir[k - 1] = '\0';
692         }
693 #endif
694       
695       if (!g_tmp_dir)
696         {
697 #ifndef G_OS_WIN32
698           g_tmp_dir = g_strdup ("/tmp");
699 #else /* G_OS_WIN32 */
700           g_tmp_dir = g_strdup ("C:\\");
701 #endif /* G_OS_WIN32 */
702         }
703       
704 #ifdef G_OS_WIN32
705       /* We check $HOME first for Win32, though it is a last resort for Unix
706        * where we prefer the results of getpwuid().
707        */
708       g_home_dir = g_strdup (g_getenv ("HOME"));
709       
710       /* In case HOME is Unix-style (it happens), convert it to
711        * Windows style.
712        */
713       if (g_home_dir)
714         {
715           gchar *p;
716           while ((p = strchr (g_home_dir, '/')) != NULL)
717             *p = '\\';
718         }
719
720       if (!g_home_dir)
721         {
722           /* USERPROFILE is probably the closest equivalent to $HOME? */
723           if (getenv ("USERPROFILE") != NULL)
724             g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
725         }
726
727       if (!g_home_dir)
728         {
729           /* At least at some time, HOMEDRIVE and HOMEPATH were used
730            * to point to the home directory, I think. But on Windows
731            * 2000 HOMEDRIVE seems to be equal to SYSTEMDRIVE, and
732            * HOMEPATH is its root "\"?
733            */
734           if (getenv ("HOMEDRIVE") != NULL && getenv ("HOMEPATH") != NULL)
735             {
736               gchar *homedrive, *homepath;
737               
738               homedrive = g_strdup (g_getenv ("HOMEDRIVE"));
739               homepath = g_strdup (g_getenv ("HOMEPATH"));
740               
741               g_home_dir = g_strconcat (homedrive, homepath, NULL);
742               g_free (homedrive);
743               g_free (homepath);
744             }
745         }
746 #endif /* G_OS_WIN32 */
747       
748 #ifdef HAVE_PWD_H
749       {
750         struct passwd *pw = NULL;
751         gpointer buffer = NULL;
752         gint error;
753         
754 #  if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
755         struct passwd pwd;
756 #    ifdef _SC_GETPW_R_SIZE_MAX  
757         /* This reurns the maximum length */
758         glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
759         
760         if (bufsize < 0)
761           bufsize = 64;
762 #    else /* _SC_GETPW_R_SIZE_MAX */
763         glong bufsize = 64;
764 #    endif /* _SC_GETPW_R_SIZE_MAX */
765         
766         do
767           {
768             g_free (buffer);
769             buffer = g_malloc (bufsize);
770             errno = 0;
771             
772 #    ifdef HAVE_POSIX_GETPWUID_R
773             error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
774             error = error < 0 ? errno : error;
775 #    else /* HAVE_NONPOSIX_GETPWUID_R */
776 #      ifdef _AIX
777             error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
778             pw = error == 0 ? &pwd : NULL;
779 #      else /* !_AIX */
780             pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
781             error = pw ? 0 : errno;
782 #      endif /* !_AIX */            
783 #    endif /* HAVE_NONPOSIX_GETPWUID_R */
784             
785             if (!pw)
786               {
787                 /* we bail out prematurely if the user id can't be found
788                  * (should be pretty rare case actually), or if the buffer
789                  * should be sufficiently big and lookups are still not
790                  * successfull.
791                  */
792                 if (error == 0 || error == ENOENT)
793                   {
794                     g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
795                                (gulong) getuid ());
796                     break;
797                   }
798                 if (bufsize > 32 * 1024)
799                   {
800                     g_warning ("getpwuid_r(): failed due to: %s.",
801                                g_strerror (error));
802                     break;
803                   }
804                 
805                 bufsize *= 2;
806               }
807           }
808         while (!pw);
809 #  endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
810         
811         if (!pw)
812           {
813             setpwent ();
814             pw = getpwuid (getuid ());
815             endpwent ();
816           }
817         if (pw)
818           {
819             g_user_name = g_strdup (pw->pw_name);
820             g_real_name = g_strdup (pw->pw_gecos);
821             if (!g_home_dir)
822               g_home_dir = g_strdup (pw->pw_dir);
823           }
824         g_free (buffer);
825       }
826       
827 #else /* !HAVE_PWD_H */
828       
829 #  ifdef G_OS_WIN32
830       {
831         guint len = UNLEN+1;
832         gchar buffer[UNLEN+1];
833         
834         if (GetUserName ((LPTSTR) buffer, (LPDWORD) &len))
835           {
836             g_user_name = g_strdup (buffer);
837             g_real_name = g_strdup (buffer);
838           }
839       }
840 #  endif /* G_OS_WIN32 */
841
842 #endif /* !HAVE_PWD_H */
843
844       if (!g_home_dir)
845         g_home_dir = g_strdup (g_getenv ("HOME"));
846       
847 #ifdef __EMX__
848       /* change '\\' in %HOME% to '/' */
849       g_strdelimit (g_home_dir, "\\",'/');
850 #endif
851       if (!g_user_name)
852         g_user_name = g_strdup ("somebody");
853       if (!g_real_name)
854         g_real_name = g_strdup ("Unknown");
855       else
856         {
857           gchar *p;
858
859           for (p = g_real_name; *p; p++)
860             if (*p == ',')
861               {
862                 *p = 0;
863                 p = g_strdup (g_real_name);
864                 g_free (g_real_name);
865                 g_real_name = p;
866                 break;
867               }
868         }
869     }
870 }
871
872 G_CONST_RETURN gchar*
873 g_get_user_name (void)
874 {
875   G_LOCK (g_utils_global);
876   if (!g_tmp_dir)
877     g_get_any_init ();
878   G_UNLOCK (g_utils_global);
879   
880   return g_user_name;
881 }
882
883 G_CONST_RETURN gchar*
884 g_get_real_name (void)
885 {
886   G_LOCK (g_utils_global);
887   if (!g_tmp_dir)
888     g_get_any_init ();
889   G_UNLOCK (g_utils_global);
890  
891   return g_real_name;
892 }
893
894 /* Return the home directory of the user. If there is a HOME
895  * environment variable, its value is returned, otherwise use some
896  * system-dependent way of finding it out. If no home directory can be
897  * deduced, return NULL.
898  */
899
900 G_CONST_RETURN gchar*
901 g_get_home_dir (void)
902 {
903   G_LOCK (g_utils_global);
904   if (!g_tmp_dir)
905     g_get_any_init ();
906   G_UNLOCK (g_utils_global);
907   
908   return g_home_dir;
909 }
910
911 /* Return a directory to be used to store temporary files. This is the
912  * value of the TMPDIR, TMP or TEMP environment variables (they are
913  * checked in that order). If none of those exist, use P_tmpdir from
914  * stdio.h.  If that isn't defined, return "/tmp" on POSIXly systems,
915  * and C:\ on Windows.
916  */
917
918 G_CONST_RETURN gchar*
919 g_get_tmp_dir (void)
920 {
921   G_LOCK (g_utils_global);
922   if (!g_tmp_dir)
923     g_get_any_init ();
924   G_UNLOCK (g_utils_global);
925   
926   return g_tmp_dir;
927 }
928
929 G_LOCK_DEFINE (g_prgname);
930 static gchar *g_prgname = NULL;
931
932 gchar*
933 g_get_prgname (void)
934 {
935   gchar* retval;
936
937   G_LOCK (g_prgname);
938   retval = g_prgname;
939   G_UNLOCK (g_prgname);
940
941   return retval;
942 }
943
944 void
945 g_set_prgname (const gchar *prgname)
946 {
947   G_LOCK (g_prgname);
948   g_free (g_prgname);
949   g_prgname = g_strdup (prgname);
950   G_UNLOCK (g_prgname);
951 }
952
953 G_LOCK_DEFINE (g_application_name);
954 static gchar *g_application_name = NULL;
955
956 /**
957  * g_get_application_name:
958  * 
959  * Gets a human-readable name for the application, as set by
960  * g_set_application_name(). This name should be localized if
961  * possible, and is intended for display to the user.  Contrast with
962  * g_get_prgname(), which gets a non-localized name. If
963  * g_set_application_name() has not been called, returns the result of
964  * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
965  * been called).
966  * 
967  * Return value: human-readable application name. may return %NULL
968  **/
969 G_CONST_RETURN gchar*
970 g_get_application_name (void)
971 {
972   gchar* retval;
973
974   G_LOCK (g_application_name);
975   retval = g_application_name;
976   G_UNLOCK (g_application_name);
977
978   if (retval == NULL)
979     return g_get_prgname ();
980   
981   return retval;
982 }
983
984 /**
985  * g_set_application_name:
986  * @application_name: localized name of the application
987  *
988  * Sets a human-readable name for the application. This name should be
989  * localized if possible, and is intended for display to the user.
990  * Contrast with g_set_prgname(), which sets a non-localized name.
991  * g_set_prgname() will be called automatically by gtk_init(),
992  * but g_set_application_name() will not.
993  *
994  * Note that for thread safety reasons, this function can only
995  * be called once.
996  *
997  * The application name will be used in contexts such as error messages,
998  * or when displaying an application's name in the task list.
999  * 
1000  **/
1001 void
1002 g_set_application_name (const gchar *application_name)
1003 {
1004   gboolean already_set = FALSE;
1005         
1006   G_LOCK (g_application_name);
1007   if (g_application_name)
1008     already_set = TRUE;
1009   else
1010     g_application_name = g_strdup (application_name);
1011   G_UNLOCK (g_application_name);
1012
1013   if (already_set)
1014     g_warning ("g_set_application() name called multiple times");
1015 }
1016
1017 guint
1018 g_direct_hash (gconstpointer v)
1019 {
1020   return GPOINTER_TO_UINT (v);
1021 }
1022
1023 gboolean
1024 g_direct_equal (gconstpointer v1,
1025                 gconstpointer v2)
1026 {
1027   return v1 == v2;
1028 }
1029
1030 gboolean
1031 g_int_equal (gconstpointer v1,
1032              gconstpointer v2)
1033 {
1034   return *((const gint*) v1) == *((const gint*) v2);
1035 }
1036
1037 guint
1038 g_int_hash (gconstpointer v)
1039 {
1040   return *(const gint*) v;
1041 }
1042
1043 /**
1044  * g_nullify_pointer:
1045  * @nullify_location: the memory address of the pointer.
1046  * 
1047  * Set the pointer at the specified location to %NULL.
1048  **/
1049 void
1050 g_nullify_pointer (gpointer *nullify_location)
1051 {
1052   g_return_if_fail (nullify_location != NULL);
1053
1054   *nullify_location = NULL;
1055 }
1056
1057 /**
1058  * g_get_codeset:
1059  * 
1060  * Get the codeset for the current locale.
1061  * 
1062  * Return value: a newly allocated string containing the name
1063  * of the codeset. This string must be freed with g_free().
1064  **/
1065 gchar *
1066 g_get_codeset (void)
1067 {
1068 #ifdef HAVE_CODESET  
1069   char *result = nl_langinfo (CODESET);
1070   return g_strdup (result);
1071 #else
1072 #ifdef G_PLATFORM_WIN32
1073   return g_strdup_printf ("CP%d", GetACP ());
1074 #else
1075   /* FIXME: Do something more intelligent based on setlocale (LC_CTYPE, NULL)
1076    */
1077   return g_strdup ("ISO-8859-1");
1078 #endif
1079 #endif
1080 }
1081
1082 #ifdef ENABLE_NLS
1083
1084 #include <libintl.h>
1085
1086 #ifdef G_PLATFORM_WIN32
1087
1088 G_WIN32_DLLMAIN_FOR_DLL_NAME (static, dll_name)
1089
1090 static const gchar *
1091 _glib_get_locale_dir (void)
1092 {
1093   static const gchar *cache = NULL;
1094   if (cache == NULL)
1095     cache = g_win32_get_package_installation_subdirectory
1096       (GETTEXT_PACKAGE, dll_name, "lib\\locale");
1097
1098   return cache;
1099 }
1100
1101 #undef GLIB_LOCALE_DIR
1102 #define GLIB_LOCALE_DIR _glib_get_locale_dir ()
1103
1104 #endif /* G_PLATFORM_WIN32 */
1105
1106 G_CONST_RETURN gchar *
1107 _glib_gettext (const gchar *str)
1108 {
1109   static gboolean _glib_gettext_initialized = FALSE;
1110
1111   if (!_glib_gettext_initialized)
1112     {
1113       bindtextdomain(GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
1114 #    ifdef HAVE_BIND_TEXTDOMAIN_CODESET
1115       bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
1116 #    endif
1117       _glib_gettext_initialized = TRUE;
1118     }
1119   
1120   return dgettext (GETTEXT_PACKAGE, str);
1121 }
1122
1123 #endif /* ENABLE_NLS */