Move the g_locale_get_codeset() up in the header file to correspond to to
[platform/upstream/glib.git] / 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 Library 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  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library 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-1999.  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_INLINE_FUNC extern
54 #define G_CAN_INLINE 1
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_OS_WIN32
68 #  define STRICT                        /* Strict typing, please */
69 #  include <windows.h>
70 #  include <ctype.h>
71 #  include <direct.h>
72 #  include <io.h>
73 #endif /* G_OS_WIN32 */
74
75 #ifdef HAVE_CODESET
76 #include <langinfo.h>
77 #endif
78
79 const guint glib_major_version = GLIB_MAJOR_VERSION;
80 const guint glib_minor_version = GLIB_MINOR_VERSION;
81 const guint glib_micro_version = GLIB_MICRO_VERSION;
82 const guint glib_interface_age = GLIB_INTERFACE_AGE;
83 const guint glib_binary_age = GLIB_BINARY_AGE;
84
85 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
86 void 
87 g_memmove (gpointer dest, gconstpointer src, gulong len)
88 {
89   gchar* destptr = dest;
90   const gchar* srcptr = src;
91   if (src + len < dest || dest + len < src)
92     {
93       bcopy (src, dest, len);
94       return;
95     }
96   else if (dest <= src)
97     {
98       while (len--)
99         *(destptr++) = *(srcptr++);
100     }
101   else
102     {
103       destptr += len;
104       srcptr += len;
105       while (len--)
106         *(--destptr) = *(--srcptr);
107     }
108 }
109 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
110
111 void
112 g_atexit (GVoidFunc func)
113 {
114   gint result;
115   gchar *error = NULL;
116
117   /* keep this in sync with glib.h */
118
119 #ifdef  G_NATIVE_ATEXIT
120   result = ATEXIT (func);
121   if (result)
122     error = g_strerror (errno);
123 #elif defined (HAVE_ATEXIT)
124 #  ifdef NeXT /* @#%@! NeXTStep */
125   result = !atexit ((void (*)(void)) func);
126   if (result)
127     error = g_strerror (errno);
128 #  else
129   result = atexit ((void (*)(void)) func);
130   if (result)
131     error = g_strerror (errno);
132 #  endif /* NeXT */
133 #elif defined (HAVE_ON_EXIT)
134   result = on_exit ((void (*)(int, void *)) func, NULL);
135   if (result)
136     error = g_strerror (errno);
137 #else
138   result = 0;
139   error = "no implementation";
140 #endif /* G_NATIVE_ATEXIT */
141
142   if (error)
143     g_error ("Could not register atexit() function: %s", error);
144 }
145
146 gint
147 g_snprintf (gchar       *str,
148             gulong       n,
149             gchar const *fmt,
150             ...)
151 {
152 #ifdef  HAVE_VSNPRINTF
153   va_list args;
154   gint retval;
155   
156   g_return_val_if_fail (str != NULL, 0);
157   g_return_val_if_fail (n > 0, 0);
158   g_return_val_if_fail (fmt != NULL, 0);
159
160   va_start (args, fmt);
161   retval = vsnprintf (str, n, fmt, args);
162   va_end (args);
163
164   if (retval < 0)
165     {
166       str[n-1] = '\0';
167       retval = strlen (str);
168     }
169
170   return retval;
171 #else   /* !HAVE_VSNPRINTF */
172   gchar *printed;
173   va_list args;
174   
175   g_return_val_if_fail (str != NULL, 0);
176   g_return_val_if_fail (n > 0, 0);
177   g_return_val_if_fail (fmt != NULL, 0);
178
179   va_start (args, fmt);
180   printed = g_strdup_vprintf (fmt, args);
181   va_end (args);
182   
183   strncpy (str, printed, n);
184   str[n-1] = '\0';
185
186   g_free (printed);
187   
188   return strlen (str);
189 #endif  /* !HAVE_VSNPRINTF */
190 }
191
192 gint
193 g_vsnprintf (gchar       *str,
194              gulong       n,
195              gchar const *fmt,
196              va_list      args)
197 {
198 #ifdef  HAVE_VSNPRINTF
199   gint retval;
200   
201   g_return_val_if_fail (str != NULL, 0);
202   g_return_val_if_fail (n > 0, 0);
203   g_return_val_if_fail (fmt != NULL, 0);
204
205   retval = vsnprintf (str, n, fmt, args);
206   
207   if (retval < 0)
208     {
209       str[n-1] = '\0';
210       retval = strlen (str);
211     }
212
213   return retval;
214 #else   /* !HAVE_VSNPRINTF */
215   gchar *printed;
216   
217   g_return_val_if_fail (str != NULL, 0);
218   g_return_val_if_fail (n > 0, 0);
219   g_return_val_if_fail (fmt != NULL, 0);
220
221   printed = g_strdup_vprintf (fmt, args);
222   strncpy (str, printed, n);
223   str[n-1] = '\0';
224
225   g_free (printed);
226   
227   return strlen (str);
228 #endif /* !HAVE_VSNPRINTF */
229 }
230
231 guint        
232 g_parse_debug_string  (const gchar *string, 
233                        GDebugKey   *keys, 
234                        guint        nkeys)
235 {
236   guint i;
237   guint result = 0;
238   
239   g_return_val_if_fail (string != NULL, 0);
240   
241   if (!g_strcasecmp (string, "all"))
242     {
243       for (i=0; i<nkeys; i++)
244         result |= keys[i].value;
245     }
246   else
247     {
248       gchar *str = g_strdup (string);
249       gchar *p = str;
250       gchar *q;
251       gboolean done = FALSE;
252       
253       while (*p && !done)
254         {
255           q = strchr (p, ':');
256           if (!q)
257             {
258               q = p + strlen(p);
259               done = TRUE;
260             }
261           
262           *q = 0;
263           
264           for (i=0; i<nkeys; i++)
265             if (!g_strcasecmp(keys[i].key, p))
266               result |= keys[i].value;
267           
268           p = q+1;
269         }
270       
271       g_free (str);
272     }
273   
274   return result;
275 }
276
277 gchar*
278 g_basename (const gchar    *file_name)
279 {
280   register gchar *base;
281   
282   g_return_val_if_fail (file_name != NULL, NULL);
283   
284   base = strrchr (file_name, G_DIR_SEPARATOR);
285   if (base)
286     return base + 1;
287
288 #ifdef G_OS_WIN32
289   if (isalpha (file_name[0]) && file_name[1] == ':')
290     return (gchar*) file_name + 2;
291 #endif /* G_OS_WIN32 */
292   
293   return (gchar*) file_name;
294 }
295
296 gboolean
297 g_path_is_absolute (const gchar *file_name)
298 {
299   g_return_val_if_fail (file_name != NULL, FALSE);
300   
301   if (file_name[0] == G_DIR_SEPARATOR)
302     return TRUE;
303
304 #ifdef G_OS_WIN32
305   if (isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
306     return TRUE;
307 #endif
308
309   return FALSE;
310 }
311
312 gchar*
313 g_path_skip_root (gchar *file_name)
314 {
315   g_return_val_if_fail (file_name != NULL, NULL);
316   
317   if (file_name[0] == G_DIR_SEPARATOR)
318     return file_name + 1;
319
320 #ifdef G_OS_WIN32
321   if (isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
322     return file_name + 3;
323 #endif
324
325   return NULL;
326 }
327
328 gchar*
329 g_dirname (const gchar     *file_name)
330 {
331   register gchar *base;
332   register guint len;
333   
334   g_return_val_if_fail (file_name != NULL, NULL);
335   
336   base = strrchr (file_name, G_DIR_SEPARATOR);
337   if (!base)
338     return g_strdup (".");
339   while (base > file_name && *base == G_DIR_SEPARATOR)
340     base--;
341   len = (guint) 1 + base - file_name;
342   
343   base = g_new (gchar, len + 1);
344   g_memmove (base, file_name, len);
345   base[len] = 0;
346   
347   return base;
348 }
349
350 gchar*
351 g_get_current_dir (void)
352 {
353   gchar *buffer = NULL;
354   gchar *dir = NULL;
355   static gulong max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
356   
357   /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
358    * and, if that wasn't bad enough, hangs in doing so.
359    */
360 #if     defined (sun) && !defined (__SVR4)
361   buffer = g_new (gchar, max_len + 1);
362   *buffer = 0;
363   dir = getwd (buffer);
364 #else   /* !sun */
365   while (max_len < G_MAXULONG / 2)
366     {
367       buffer = g_new (gchar, max_len + 1);
368       *buffer = 0;
369       dir = getcwd (buffer, max_len);
370
371       if (dir || errno != ERANGE)
372         break;
373
374       g_free (buffer);
375       max_len *= 2;
376     }
377 #endif  /* !sun */
378   
379   if (!dir || !*buffer)
380     {
381       /* hm, should we g_error() out here?
382        * this can happen if e.g. "./" has mode \0000
383        */
384       buffer[0] = G_DIR_SEPARATOR;
385       buffer[1] = 0;
386     }
387
388   dir = g_strdup (buffer);
389   g_free (buffer);
390   
391   return dir;
392 }
393
394 gchar*
395 g_getenv (const gchar *variable)
396 {
397 #ifndef G_OS_WIN32
398   g_return_val_if_fail (variable != NULL, NULL);
399
400   return getenv (variable);
401 #else
402   G_LOCK_DEFINE_STATIC (getenv);
403   struct env_struct
404   {
405     gchar *key;
406     gchar *value;
407   } *env;
408   static GArray *environs = NULL;
409   gchar *system_env;
410   guint length, i;
411   gchar dummy[2];
412
413   g_return_val_if_fail (variable != NULL, NULL);
414   
415   G_LOCK (getenv);
416
417   if (!environs)
418     environs = g_array_new (FALSE, FALSE, sizeof (struct env_struct));
419
420   /* First we try to find the envinronment variable inside the already
421    * found ones.
422    */
423
424   for (i = 0; i < environs->len; i++)
425     {
426       env = &g_array_index (environs, struct env_struct, i);
427       if (strcmp (env->key, variable) == 0)
428         {
429           g_assert (env->value);
430           G_UNLOCK (getenv);
431           return env->value;
432         }
433     }
434
435   /* If not found, we ask the system */
436
437   system_env = getenv (variable);
438   if (!system_env)
439     {
440       G_UNLOCK (getenv);
441       return NULL;
442     }
443
444   /* On Windows NT, it is relatively typical that environment variables
445    * contain references to other environment variables. Handle that by
446    * calling ExpandEnvironmentStrings.
447    */
448
449   g_array_set_size (environs, environs->len + 1);
450
451   env = &g_array_index (environs, struct env_struct, environs->len - 1);
452
453   /* First check how much space we need */
454   length = ExpandEnvironmentStrings (system_env, dummy, 2);
455
456   /* Then allocate that much, and actualy do the expansion and insert
457    * the new found pair into our buffer 
458    */
459
460   env->value = g_malloc (length);
461   env->key = g_strdup (variable);
462
463   ExpandEnvironmentStrings (system_env, env->value, length);
464
465   G_UNLOCK (getenv);
466   return env->value;
467 #endif
468 }
469
470
471 G_LOCK_DEFINE_STATIC (g_utils_global);
472
473 static  gchar   *g_tmp_dir = NULL;
474 static  gchar   *g_user_name = NULL;
475 static  gchar   *g_real_name = NULL;
476 static  gchar   *g_home_dir = NULL;
477
478 /* HOLDS: g_utils_global_lock */
479 static void
480 g_get_any_init (void)
481 {
482   if (!g_tmp_dir)
483     {
484       g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
485       if (!g_tmp_dir)
486         g_tmp_dir = g_strdup (g_getenv ("TMP"));
487       if (!g_tmp_dir)
488         g_tmp_dir = g_strdup (g_getenv ("TEMP"));
489       
490 #ifdef P_tmpdir
491       if (!g_tmp_dir)
492         {
493           int k;
494           g_tmp_dir = g_strdup (P_tmpdir);
495           k = strlen (g_tmp_dir);
496           if (g_tmp_dir[k-1] == G_DIR_SEPARATOR)
497             g_tmp_dir[k-1] = '\0';
498         }
499 #endif
500       
501       if (!g_tmp_dir)
502         {
503 #ifndef G_OS_WIN32
504           g_tmp_dir = g_strdup ("/tmp");
505 #else /* G_OS_WIN32 */
506           g_tmp_dir = g_strdup ("C:\\");
507 #endif /* G_OS_WIN32 */
508         }
509       
510       if (!g_home_dir)
511         g_home_dir = g_strdup (g_getenv ("HOME"));
512       
513 #ifdef G_OS_WIN32
514       if (!g_home_dir)
515         {
516           /* The official way to specify a home directory on NT is
517            * the HOMEDRIVE and HOMEPATH environment variables.
518            *
519            * This is inside #ifdef G_OS_WIN32 because with the cygwin dll,
520            * HOME should be a POSIX style pathname.
521            */
522           
523           if (getenv ("HOMEDRIVE") != NULL && getenv ("HOMEPATH") != NULL)
524             {
525               gchar *homedrive, *homepath;
526               
527               homedrive = g_strdup (g_getenv ("HOMEDRIVE"));
528               homepath = g_strdup (g_getenv ("HOMEPATH"));
529               
530               g_home_dir = g_strconcat (homedrive, homepath, NULL);
531               g_free (homedrive);
532               g_free (homepath);
533             }
534         }
535 #endif /* G_OS_WIN32 */
536       
537 #ifdef HAVE_PWD_H
538       {
539         struct passwd *pw = NULL;
540         gpointer buffer = NULL;
541         
542 #  ifdef HAVE_GETPWUID_R
543         struct passwd pwd;
544 #    ifdef _SC_GETPW_R_SIZE_MAX  
545         /* This reurns the maximum length */
546         guint bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
547 #    else /* _SC_GETPW_R_SIZE_MAX */
548         guint bufsize = 64;
549 #    endif /* _SC_GETPW_R_SIZE_MAX */
550         gint error;
551         
552         do
553           {
554             g_free (buffer);
555             buffer = g_malloc (bufsize);
556             errno = 0;
557             
558 #    ifdef HAVE_GETPWUID_R_POSIX
559             error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
560             error = error < 0 ? errno : error;
561 #    else /* !HAVE_GETPWUID_R_POSIX */
562 #      ifdef _AIX
563             error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
564             pw = error == 0 ? &pwd : NULL;
565 #      else /* !_AIX */
566             pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
567             error = pw ? 0 : errno;
568 #      endif /* !_AIX */            
569 #    endif /* !HAVE_GETPWUID_R_POSIX */
570             
571             if (!pw)
572               {
573                 /* we bail out prematurely if the user id can't be found
574                  * (should be pretty rare case actually), or if the buffer
575                  * should be sufficiently big and lookups are still not
576                  * successfull.
577                  */
578                 if (error == 0 || error == ENOENT)
579                   {
580                     g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
581                                (gulong) getuid ());
582                     break;
583                   }
584                 if (bufsize > 32 * 1024)
585                   {
586                     g_warning ("getpwuid_r(): failed due to: %s.",
587                                g_strerror (error));
588                     break;
589                   }
590                 
591                 bufsize *= 2;
592               }
593           }
594         while (!pw);
595 #  endif /* !HAVE_GETPWUID_R */
596         
597         if (!pw)
598           {
599             setpwent ();
600             pw = getpwuid (getuid ());
601             endpwent ();
602           }
603         if (pw)
604           {
605             g_user_name = g_strdup (pw->pw_name);
606             g_real_name = g_strdup (pw->pw_gecos);
607             if (!g_home_dir)
608               g_home_dir = g_strdup (pw->pw_dir);
609           }
610         g_free (buffer);
611       }
612       
613 #else /* !HAVE_PWD_H */
614       
615 #  ifdef G_OS_WIN32
616       {
617         guint len = 17;
618         gchar buffer[17];
619         
620         if (GetUserName (buffer, &len))
621           {
622             g_user_name = g_strdup (buffer);
623             g_real_name = g_strdup (buffer);
624           }
625       }
626 #  endif /* G_OS_WIN32 */
627       
628 #endif /* !HAVE_PWD_H */
629       
630 #ifdef __EMX__
631       /* change '\\' in %HOME% to '/' */
632       g_strdelimit (g_home_dir, "\\",'/');
633 #endif
634       if (!g_user_name)
635         g_user_name = g_strdup ("somebody");
636       if (!g_real_name)
637         g_real_name = g_strdup ("Unknown");
638       else
639         {
640           gchar *p;
641
642           for (p = g_real_name; *p; p++)
643             if (*p == ',')
644               {
645                 *p = 0;
646                 p = g_strdup (g_real_name);
647                 g_free (g_real_name);
648                 g_real_name = p;
649                 break;
650               }
651         }
652     }
653 }
654
655 gchar*
656 g_get_user_name (void)
657 {
658   G_LOCK (g_utils_global);
659   if (!g_tmp_dir)
660     g_get_any_init ();
661   G_UNLOCK (g_utils_global);
662   
663   return g_user_name;
664 }
665
666 gchar*
667 g_get_real_name (void)
668 {
669   G_LOCK (g_utils_global);
670   if (!g_tmp_dir)
671     g_get_any_init ();
672   G_UNLOCK (g_utils_global);
673  
674   return g_real_name;
675 }
676
677 /* Return the home directory of the user. If there is a HOME
678  * environment variable, its value is returned, otherwise use some
679  * system-dependent way of finding it out. If no home directory can be
680  * deduced, return NULL.
681  */
682
683 gchar*
684 g_get_home_dir (void)
685 {
686   G_LOCK (g_utils_global);
687   if (!g_tmp_dir)
688     g_get_any_init ();
689   G_UNLOCK (g_utils_global);
690   
691   return g_home_dir;
692 }
693
694 /* Return a directory to be used to store temporary files. This is the
695  * value of the TMPDIR, TMP or TEMP environment variables (they are
696  * checked in that order). If none of those exist, use P_tmpdir from
697  * stdio.h.  If that isn't defined, return "/tmp" on POSIXly systems,
698  * and C:\ on Windows.
699  */
700
701 gchar*
702 g_get_tmp_dir (void)
703 {
704   G_LOCK (g_utils_global);
705   if (!g_tmp_dir)
706     g_get_any_init ();
707   G_UNLOCK (g_utils_global);
708   
709   return g_tmp_dir;
710 }
711
712 static gchar *g_prgname = NULL;
713
714 gchar*
715 g_get_prgname (void)
716 {
717   gchar* retval;
718
719   G_LOCK (g_utils_global);
720   retval = g_prgname;
721   G_UNLOCK (g_utils_global);
722
723   return retval;
724 }
725
726 void
727 g_set_prgname (const gchar *prgname)
728 {
729   gchar *c;
730     
731   G_LOCK (g_utils_global);
732   c = g_prgname;
733   g_prgname = g_strdup (prgname);
734   g_free (c);
735   G_UNLOCK (g_utils_global);
736 }
737
738 guint
739 g_direct_hash (gconstpointer v)
740 {
741   return GPOINTER_TO_UINT (v);
742 }
743
744 gint
745 g_direct_equal (gconstpointer v1,
746                 gconstpointer v2)
747 {
748   return v1 == v2;
749 }
750
751 gint
752 g_int_equal (gconstpointer v1,
753              gconstpointer v2)
754 {
755   return *((const gint*) v1) == *((const gint*) v2);
756 }
757
758 guint
759 g_int_hash (gconstpointer v)
760 {
761   return *(const gint*) v;
762 }
763
764 /**
765  * g_get_codeset:
766  * 
767  * Get the codeset for the current locale.
768  * 
769  * Return value: a newly allocated string containing the name
770  * of the codeset. This string must be freed with g_free().
771  **/
772 gchar *
773 g_get_codeset (void)
774 {
775 #ifdef HAVE_CODESET  
776   char *result = nl_langinfo (CODESET);
777   return g_strdup (result);
778 #else
779   /* FIXME: Do something more intelligent based on setlocale (LC_CTYPE, NULL)
780    */
781   return g_strdup ("ISO-8859-1");
782 #endif
783 }