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