Use G_BEGIN_DECLS and G_END_DECLS.
[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 Glib'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 #ifdef  HAVE_VSNPRINTF
345   va_list args;
346   gint retval;
347   
348   g_return_val_if_fail (str != NULL, 0);
349   g_return_val_if_fail (n > 0, 0);
350   g_return_val_if_fail (fmt != NULL, 0);
351
352   va_start (args, fmt);
353   retval = vsnprintf (str, n, fmt, args);
354   va_end (args);
355
356   if (retval < 0)
357     {
358       str[n-1] = '\0';
359       retval = strlen (str);
360     }
361
362   return retval;
363 #else   /* !HAVE_VSNPRINTF */
364   gchar *printed;
365   va_list args;
366   
367   g_return_val_if_fail (str != NULL, 0);
368   g_return_val_if_fail (n > 0, 0);
369   g_return_val_if_fail (fmt != NULL, 0);
370
371   va_start (args, fmt);
372   printed = g_strdup_vprintf (fmt, args);
373   va_end (args);
374   
375   strncpy (str, printed, n);
376   str[n-1] = '\0';
377
378   g_free (printed);
379   
380   return strlen (str);
381 #endif  /* !HAVE_VSNPRINTF */
382 }
383
384 gint
385 g_vsnprintf (gchar       *str,
386              gulong       n,
387              gchar const *fmt,
388              va_list      args)
389 {
390 #ifdef  HAVE_VSNPRINTF
391   gint retval;
392   
393   g_return_val_if_fail (str != NULL, 0);
394   g_return_val_if_fail (n > 0, 0);
395   g_return_val_if_fail (fmt != NULL, 0);
396
397   retval = vsnprintf (str, n, fmt, args);
398   
399   if (retval < 0)
400     {
401       str[n-1] = '\0';
402       retval = strlen (str);
403     }
404
405   return retval;
406 #else   /* !HAVE_VSNPRINTF */
407   gchar *printed;
408   
409   g_return_val_if_fail (str != NULL, 0);
410   g_return_val_if_fail (n > 0, 0);
411   g_return_val_if_fail (fmt != NULL, 0);
412
413   printed = g_strdup_vprintf (fmt, args);
414   strncpy (str, printed, n);
415   str[n-1] = '\0';
416
417   g_free (printed);
418   
419   return strlen (str);
420 #endif /* !HAVE_VSNPRINTF */
421 }
422
423 guint        
424 g_parse_debug_string  (const gchar *string, 
425                        GDebugKey   *keys, 
426                        guint        nkeys)
427 {
428   guint i;
429   guint result = 0;
430   
431   g_return_val_if_fail (string != NULL, 0);
432   
433   if (!g_strcasecmp (string, "all"))
434     {
435       for (i=0; i<nkeys; i++)
436         result |= keys[i].value;
437     }
438   else
439     {
440       gchar *str = g_strdup (string);
441       gchar *p = str;
442       gchar *q;
443       gboolean done = FALSE;
444       
445       while (*p && !done)
446         {
447           q = strchr (p, ':');
448           if (!q)
449             {
450               q = p + strlen(p);
451               done = TRUE;
452             }
453           
454           *q = 0;
455           
456           for (i=0; i<nkeys; i++)
457             if (!g_strcasecmp(keys[i].key, p))
458               result |= keys[i].value;
459           
460           p = q+1;
461         }
462       
463       g_free (str);
464     }
465   
466   return result;
467 }
468
469 G_CONST_RETURN gchar*
470 g_basename (const gchar    *file_name)
471 {
472   register gchar *base;
473 #if defined(G_ENABLE_DEBUG) && !defined(G_OS_WIN32)
474   static gboolean first_call = TRUE;
475
476   if (first_call)
477     {
478       g_message ("g_basename is deprecated. Use g_path_get_basename instead. "
479                  "Beware that the string returned by g_path_get_basename() has "
480                  " to be g_free()ed.");
481       first_call = FALSE;
482     }
483 #endif /* G_ENABLE_DEBUG */
484   
485   g_return_val_if_fail (file_name != NULL, NULL);
486   
487   base = strrchr (file_name, G_DIR_SEPARATOR);
488   if (base)
489     return base + 1;
490
491 #ifdef G_OS_WIN32
492   if (isalpha (file_name[0]) && file_name[1] == ':')
493     return (gchar*) file_name + 2;
494 #endif /* G_OS_WIN32 */
495   
496   return (gchar*) file_name;
497 }
498
499 gchar*
500 g_path_get_basename (const gchar   *file_name)
501 {
502   register gint base;
503   register gint last_nonslash;
504   guint len;
505   gchar *retval;
506  
507   g_return_val_if_fail (file_name != NULL, NULL);
508   
509   if (file_name[0] == '\0')
510     /* empty string */
511     return g_strdup (".");
512
513   last_nonslash = strlen (file_name) - 1;
514
515   while (last_nonslash >= 0 && file_name [last_nonslash] == G_DIR_SEPARATOR)
516     last_nonslash--;
517
518   if (last_nonslash == -1)
519     /* string only containing slashes */
520     return g_strdup (G_DIR_SEPARATOR_S);
521
522 #ifdef G_OS_WIN32
523   if (last_nonslash == 1 && isalpha (file_name[0]) && file_name[1] == ':')
524     /* string only containing slashes and a drive */
525     return g_strdup (G_DIR_SEPARATOR_S);
526 #endif /* G_OS_WIN32 */
527
528   base = last_nonslash;
529
530   while (base >=0 && file_name [base] != G_DIR_SEPARATOR)
531     base--;
532
533 #ifdef G_OS_WIN32
534   if (base == -1 && isalpha (file_name[0]) && file_name[1] == ':')
535     base = 1;
536 #endif /* G_OS_WIN32 */
537
538   len = last_nonslash - base;
539   retval = g_malloc (len + 1);
540   memcpy (retval, file_name + base + 1, len);
541   retval [len] = '\0';
542   return retval;
543 }
544
545 gboolean
546 g_path_is_absolute (const gchar *file_name)
547 {
548   g_return_val_if_fail (file_name != NULL, FALSE);
549   
550   if (file_name[0] == G_DIR_SEPARATOR)
551     return TRUE;
552
553 #ifdef G_OS_WIN32
554   /* Recognize drive letter on native Windows */
555   if (isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
556     return TRUE;
557 #endif /* G_OS_WIN32 */
558
559   return FALSE;
560 }
561
562 G_CONST_RETURN gchar*
563 g_path_skip_root (const gchar *file_name)
564 {
565   g_return_val_if_fail (file_name != NULL, NULL);
566   
567 #ifdef G_PLATFORM_WIN32
568   /* Skip \\server\share (Win32) or //server/share (Cygwin) */
569   if (file_name[0] == G_DIR_SEPARATOR &&
570       file_name[1] == G_DIR_SEPARATOR &&
571       file_name[2])
572     {
573       gchar *p;
574
575       if ((p = strchr (file_name + 2, G_DIR_SEPARATOR)) > file_name + 2 &&
576           p[1])
577         {
578           file_name = p + 1;
579
580           while (file_name[0] && file_name[0] != G_DIR_SEPARATOR)
581             file_name++;
582
583           /* Possibly skip a backslash after the share name */
584           if (file_name[0] == G_DIR_SEPARATOR)
585             file_name++;
586
587           return (gchar *)file_name;
588         }
589     }
590 #endif
591   
592   /* Skip initial slashes */
593   if (file_name[0] == G_DIR_SEPARATOR)
594     {
595       while (file_name[0] == G_DIR_SEPARATOR)
596         file_name++;
597       return (gchar *)file_name;
598     }
599
600 #ifdef G_OS_WIN32
601   /* Skip X:\ */
602   if (isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
603     return (gchar *)file_name + 3;
604 #endif
605
606   return NULL;
607 }
608
609 gchar*
610 g_path_get_dirname (const gchar    *file_name)
611 {
612   register gchar *base;
613   register guint len;
614   
615   g_return_val_if_fail (file_name != NULL, NULL);
616   
617   base = strrchr (file_name, G_DIR_SEPARATOR);
618   if (!base)
619     return g_strdup (".");
620   while (base > file_name && *base == G_DIR_SEPARATOR)
621     base--;
622   len = (guint) 1 + base - file_name;
623   
624   base = g_new (gchar, len + 1);
625   g_memmove (base, file_name, len);
626   base[len] = 0;
627   
628   return base;
629 }
630
631 gchar*
632 g_dirname (const gchar     *file_name)
633 {
634 #if defined(G_ENABLE_DEBUG) && !defined(G_OS_WIN32)
635   static gboolean first_call = TRUE;
636
637   if (first_call)
638     {
639       g_message ("g_dirname() is deprecated. Use g_path_get_dirname() instead.");
640       first_call = FALSE;
641     }
642 #endif /* G_ENABLE_DEBUG */
643
644   return g_path_get_dirname (file_name);
645 }
646
647 gchar*
648 g_get_current_dir (void)
649 {
650   gchar *buffer = NULL;
651   gchar *dir = NULL;
652   static gulong max_len = 0;
653
654   if (max_len == 0) 
655     max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
656   
657   /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
658    * and, if that wasn't bad enough, hangs in doing so.
659    */
660 #if     (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
661   buffer = g_new (gchar, max_len + 1);
662   *buffer = 0;
663   dir = getwd (buffer);
664 #else   /* !sun || !HAVE_GETCWD */
665   while (max_len < G_MAXULONG / 2)
666     {
667       buffer = g_new (gchar, max_len + 1);
668       *buffer = 0;
669       dir = getcwd (buffer, max_len);
670
671       if (dir || errno != ERANGE)
672         break;
673
674       g_free (buffer);
675       max_len *= 2;
676     }
677 #endif  /* !sun || !HAVE_GETCWD */
678   
679   if (!dir || !*buffer)
680     {
681       /* hm, should we g_error() out here?
682        * this can happen if e.g. "./" has mode \0000
683        */
684       buffer[0] = G_DIR_SEPARATOR;
685       buffer[1] = 0;
686     }
687
688   dir = g_strdup (buffer);
689   g_free (buffer);
690   
691   return dir;
692 }
693
694 G_CONST_RETURN gchar*
695 g_getenv (const gchar *variable)
696 {
697 #ifndef G_OS_WIN32
698   g_return_val_if_fail (variable != NULL, NULL);
699
700   return getenv (variable);
701 #else
702   G_LOCK_DEFINE_STATIC (getenv);
703   struct env_struct
704   {
705     gchar *key;
706     gchar *value;
707   } *env;
708   static GArray *environs = NULL;
709   gchar *system_env;
710   guint length, i;
711   gchar dummy[2];
712
713   g_return_val_if_fail (variable != NULL, NULL);
714   
715   G_LOCK (getenv);
716
717   if (!environs)
718     environs = g_array_new (FALSE, FALSE, sizeof (struct env_struct));
719
720   /* First we try to find the envinronment variable inside the already
721    * found ones.
722    */
723
724   for (i = 0; i < environs->len; i++)
725     {
726       env = &g_array_index (environs, struct env_struct, i);
727       if (strcmp (env->key, variable) == 0)
728         {
729           g_assert (env->value);
730           G_UNLOCK (getenv);
731           return env->value;
732         }
733     }
734
735   /* If not found, we ask the system */
736
737   system_env = getenv (variable);
738   if (!system_env)
739     {
740       G_UNLOCK (getenv);
741       return NULL;
742     }
743
744   /* On Windows NT, it is relatively typical that environment variables
745    * contain references to other environment variables. Handle that by
746    * calling ExpandEnvironmentStrings.
747    */
748
749   g_array_set_size (environs, environs->len + 1);
750
751   env = &g_array_index (environs, struct env_struct, environs->len - 1);
752
753   /* First check how much space we need */
754   length = ExpandEnvironmentStrings (system_env, dummy, 2);
755
756   /* Then allocate that much, and actualy do the expansion and insert
757    * the new found pair into our buffer 
758    */
759
760   env->value = g_malloc (length);
761   env->key = g_strdup (variable);
762
763   ExpandEnvironmentStrings (system_env, env->value, length);
764
765   G_UNLOCK (getenv);
766   return env->value;
767 #endif
768 }
769
770
771 G_LOCK_DEFINE_STATIC (g_utils_global);
772
773 static  gchar   *g_tmp_dir = NULL;
774 static  gchar   *g_user_name = NULL;
775 static  gchar   *g_real_name = NULL;
776 static  gchar   *g_home_dir = NULL;
777
778 /* HOLDS: g_utils_global_lock */
779 static void
780 g_get_any_init (void)
781 {
782   if (!g_tmp_dir)
783     {
784       g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
785       if (!g_tmp_dir)
786         g_tmp_dir = g_strdup (g_getenv ("TMP"));
787       if (!g_tmp_dir)
788         g_tmp_dir = g_strdup (g_getenv ("TEMP"));
789       
790 #ifdef P_tmpdir
791       if (!g_tmp_dir)
792         {
793           int k;
794           g_tmp_dir = g_strdup (P_tmpdir);
795           k = strlen (g_tmp_dir);
796           if (g_tmp_dir[k-1] == G_DIR_SEPARATOR)
797             g_tmp_dir[k-1] = '\0';
798         }
799 #endif
800       
801       if (!g_tmp_dir)
802         {
803 #ifndef G_OS_WIN32
804           g_tmp_dir = g_strdup ("/tmp");
805 #else /* G_OS_WIN32 */
806           g_tmp_dir = g_strdup ("C:\\");
807 #endif /* G_OS_WIN32 */
808         }
809       
810       if (!g_home_dir)
811         g_home_dir = g_strdup (g_getenv ("HOME"));
812       
813 #ifdef G_OS_WIN32
814       /* In case HOME is Unix-style (it happens), convert it to
815        * Windows style.
816        */
817       if (g_home_dir)
818         {
819           gchar *p;
820           while ((p = strchr (g_home_dir, '/')) != NULL)
821             *p = '\\';
822         }
823
824       if (!g_home_dir)
825         {
826           /* USERPROFILE is probably the closest equivalent to $HOME? */
827           if (getenv ("USERPROFILE") != NULL)
828             g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
829         }
830
831       if (!g_home_dir)
832         {
833           /* At least at some time, HOMEDRIVE and HOMEPATH were used
834            * to point to the home directory, I think. But on Windows
835            * 2000 HOMEDRIVE seems to be equal to SYSTEMDRIVE, and
836            * HOMEPATH is its root "\"?
837            */
838           if (getenv ("HOMEDRIVE") != NULL && getenv ("HOMEPATH") != NULL)
839             {
840               gchar *homedrive, *homepath;
841               
842               homedrive = g_strdup (g_getenv ("HOMEDRIVE"));
843               homepath = g_strdup (g_getenv ("HOMEPATH"));
844               
845               g_home_dir = g_strconcat (homedrive, homepath, NULL);
846               g_free (homedrive);
847               g_free (homepath);
848             }
849         }
850 #endif /* G_OS_WIN32 */
851       
852 #ifdef HAVE_PWD_H
853       {
854         struct passwd *pw = NULL;
855         gpointer buffer = NULL;
856         
857 #  if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
858         struct passwd pwd;
859 #    ifdef _SC_GETPW_R_SIZE_MAX  
860         /* This reurns the maximum length */
861         guint bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
862 #    else /* _SC_GETPW_R_SIZE_MAX */
863         guint bufsize = 64;
864 #    endif /* _SC_GETPW_R_SIZE_MAX */
865         gint error;
866         
867         do
868           {
869             g_free (buffer);
870             buffer = g_malloc (bufsize);
871             errno = 0;
872             
873 #    ifdef HAVE_POSIX_GETPWUID_R
874             error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
875             error = error < 0 ? errno : error;
876 #    else /* HAVE_NONPOSIX_GETPWUID_R */
877 #      ifdef _AIX
878             error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
879             pw = error == 0 ? &pwd : NULL;
880 #      else /* !_AIX */
881             pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
882             error = pw ? 0 : errno;
883 #      endif /* !_AIX */            
884 #    endif /* HAVE_NONPOSIX_GETPWUID_R */
885             
886             if (!pw)
887               {
888                 /* we bail out prematurely if the user id can't be found
889                  * (should be pretty rare case actually), or if the buffer
890                  * should be sufficiently big and lookups are still not
891                  * successfull.
892                  */
893                 if (error == 0 || error == ENOENT)
894                   {
895                     g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
896                                (gulong) getuid ());
897                     break;
898                   }
899                 if (bufsize > 32 * 1024)
900                   {
901                     g_warning ("getpwuid_r(): failed due to: %s.",
902                                g_strerror (error));
903                     break;
904                   }
905                 
906                 bufsize *= 2;
907               }
908           }
909         while (!pw);
910 #  endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
911         
912         if (!pw)
913           {
914             setpwent ();
915             pw = getpwuid (getuid ());
916             endpwent ();
917           }
918         if (pw)
919           {
920             g_user_name = g_strdup (pw->pw_name);
921             g_real_name = g_strdup (pw->pw_gecos);
922             if (!g_home_dir)
923               g_home_dir = g_strdup (pw->pw_dir);
924           }
925         g_free (buffer);
926       }
927       
928 #else /* !HAVE_PWD_H */
929       
930 #  ifdef G_OS_WIN32
931       {
932         guint len = 17;
933         gchar buffer[17];
934         
935         if (GetUserName ((LPTSTR) buffer, (LPDWORD) &len))
936           {
937             g_user_name = g_strdup (buffer);
938             g_real_name = g_strdup (buffer);
939           }
940       }
941 #  endif /* G_OS_WIN32 */
942       
943 #endif /* !HAVE_PWD_H */
944       
945 #ifdef __EMX__
946       /* change '\\' in %HOME% to '/' */
947       g_strdelimit (g_home_dir, "\\",'/');
948 #endif
949       if (!g_user_name)
950         g_user_name = g_strdup ("somebody");
951       if (!g_real_name)
952         g_real_name = g_strdup ("Unknown");
953       else
954         {
955           gchar *p;
956
957           for (p = g_real_name; *p; p++)
958             if (*p == ',')
959               {
960                 *p = 0;
961                 p = g_strdup (g_real_name);
962                 g_free (g_real_name);
963                 g_real_name = p;
964                 break;
965               }
966         }
967     }
968 }
969
970 G_CONST_RETURN gchar*
971 g_get_user_name (void)
972 {
973   G_LOCK (g_utils_global);
974   if (!g_tmp_dir)
975     g_get_any_init ();
976   G_UNLOCK (g_utils_global);
977   
978   return g_user_name;
979 }
980
981 G_CONST_RETURN gchar*
982 g_get_real_name (void)
983 {
984   G_LOCK (g_utils_global);
985   if (!g_tmp_dir)
986     g_get_any_init ();
987   G_UNLOCK (g_utils_global);
988  
989   return g_real_name;
990 }
991
992 /* Return the home directory of the user. If there is a HOME
993  * environment variable, its value is returned, otherwise use some
994  * system-dependent way of finding it out. If no home directory can be
995  * deduced, return NULL.
996  */
997
998 G_CONST_RETURN gchar*
999 g_get_home_dir (void)
1000 {
1001   G_LOCK (g_utils_global);
1002   if (!g_tmp_dir)
1003     g_get_any_init ();
1004   G_UNLOCK (g_utils_global);
1005   
1006   return g_home_dir;
1007 }
1008
1009 /* Return a directory to be used to store temporary files. This is the
1010  * value of the TMPDIR, TMP or TEMP environment variables (they are
1011  * checked in that order). If none of those exist, use P_tmpdir from
1012  * stdio.h.  If that isn't defined, return "/tmp" on POSIXly systems,
1013  * and C:\ on Windows.
1014  */
1015
1016 G_CONST_RETURN gchar*
1017 g_get_tmp_dir (void)
1018 {
1019   G_LOCK (g_utils_global);
1020   if (!g_tmp_dir)
1021     g_get_any_init ();
1022   G_UNLOCK (g_utils_global);
1023   
1024   return g_tmp_dir;
1025 }
1026
1027 static gchar *g_prgname = NULL;
1028
1029 gchar*
1030 g_get_prgname (void)
1031 {
1032   gchar* retval;
1033
1034   G_LOCK (g_utils_global);
1035   retval = g_prgname;
1036   G_UNLOCK (g_utils_global);
1037
1038   return retval;
1039 }
1040
1041 void
1042 g_set_prgname (const gchar *prgname)
1043 {
1044   gchar *c;
1045     
1046   G_LOCK (g_utils_global);
1047   c = g_prgname;
1048   g_prgname = g_strdup (prgname);
1049   g_free (c);
1050   G_UNLOCK (g_utils_global);
1051 }
1052
1053 guint
1054 g_direct_hash (gconstpointer v)
1055 {
1056   return GPOINTER_TO_UINT (v);
1057 }
1058
1059 gboolean
1060 g_direct_equal (gconstpointer v1,
1061                 gconstpointer v2)
1062 {
1063   return v1 == v2;
1064 }
1065
1066 gboolean
1067 g_int_equal (gconstpointer v1,
1068              gconstpointer v2)
1069 {
1070   return *((const gint*) v1) == *((const gint*) v2);
1071 }
1072
1073 guint
1074 g_int_hash (gconstpointer v)
1075 {
1076   return *(const gint*) v;
1077 }
1078
1079 /**
1080  * g_get_codeset:
1081  * 
1082  * Get the codeset for the current locale.
1083  * 
1084  * Return value: a newly allocated string containing the name
1085  * of the codeset. This string must be freed with g_free().
1086  **/
1087 gchar *
1088 g_get_codeset (void)
1089 {
1090 #ifdef HAVE_CODESET  
1091   char *result = nl_langinfo (CODESET);
1092   return g_strdup (result);
1093 #else
1094 #ifdef G_PLATFORM_WIN32
1095   return g_strdup_printf ("CP%d", GetACP ());
1096 #else
1097   /* FIXME: Do something more intelligent based on setlocale (LC_CTYPE, NULL)
1098    */
1099   return g_strdup ("ISO-8859-1");
1100 #endif
1101 #endif
1102 }
1103
1104 #ifdef ENABLE_NLS
1105
1106 #include <libintl.h>
1107
1108
1109 #ifndef GLIB_LOCALE_DIR
1110 #ifdef G_PLATFORM_WIN32
1111
1112 #define GLIB_LOCALE_DIR                                         \
1113   g_win32_get_package_installation_subdirectory                 \
1114   (GETTEXT_PACKAGE, g_strdup_printf ("glib-%d.%d.dll",          \
1115                                      GLIB_MAJOR_VERSION,        \
1116                                      GLIB_MINOR_VERSION),       \
1117    "locale")
1118
1119 #endif /* G_PLATFORM_WIN32 */
1120 #endif /* !GLIB_LOCALE_DIR */
1121
1122 G_CONST_RETURN gchar *
1123 _glib_gettext (const gchar *str)
1124 {
1125   gboolean _glib_gettext_initialized = FALSE;
1126
1127   if (!_glib_gettext_initialized)
1128     {
1129       bindtextdomain(GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
1130       _glib_gettext_initialized = TRUE;
1131     }
1132   
1133   return dgettext (GETTEXT_PACKAGE, str);
1134 }
1135
1136 #endif /* ENABLE_NLS */
1137
1138