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