Add configure test for garbage collector friendliness for GLib. If
[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   gchar *v;
383   guint k;
384   static gchar *p = NULL;
385   static gint l;
386   gchar dummy[2];
387
388   g_return_val_if_fail (variable != NULL, NULL);
389   
390   v = getenv (variable);
391   if (!v)
392     return NULL;
393   
394   /* On Windows NT, it is relatively typical that environment variables
395    * contain references to other environment variables. Handle that by
396    * calling ExpandEnvironmentStrings.
397    */
398
399   /* First check how much space we need */
400   k = ExpandEnvironmentStrings (v, dummy, 2);
401   /* Then allocate that much, and actualy do the expansion */
402   if (p == NULL)
403     {
404       p = g_malloc (k);
405       l = k;
406     }
407   else if (k > l)
408     {
409       p = g_realloc (p, k);
410       l = k;
411     }
412   ExpandEnvironmentStrings (v, p, k);
413   return p;
414 #endif
415 }
416
417
418 G_LOCK_DEFINE_STATIC (g_utils_global);
419
420 static  gchar   *g_tmp_dir = NULL;
421 static  gchar   *g_user_name = NULL;
422 static  gchar   *g_real_name = NULL;
423 static  gchar   *g_home_dir = NULL;
424
425 /* HOLDS: g_utils_global_lock */
426 static void
427 g_get_any_init (void)
428 {
429   if (!g_tmp_dir)
430     {
431       g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
432       if (!g_tmp_dir)
433         g_tmp_dir = g_strdup (g_getenv ("TMP"));
434       if (!g_tmp_dir)
435         g_tmp_dir = g_strdup (g_getenv ("TEMP"));
436       
437 #ifdef P_tmpdir
438       if (!g_tmp_dir)
439         {
440           int k;
441           g_tmp_dir = g_strdup (P_tmpdir);
442           k = strlen (g_tmp_dir);
443           if (g_tmp_dir[k-1] == G_DIR_SEPARATOR)
444             g_tmp_dir[k-1] = '\0';
445         }
446 #endif
447       
448       if (!g_tmp_dir)
449         {
450 #ifndef G_OS_WIN32
451           g_tmp_dir = g_strdup ("/tmp");
452 #else /* G_OS_WIN32 */
453           g_tmp_dir = g_strdup ("C:\\");
454 #endif /* G_OS_WIN32 */
455         }
456       
457       if (!g_home_dir)
458         g_home_dir = g_strdup (g_getenv ("HOME"));
459       
460 #ifdef G_OS_WIN32
461       if (!g_home_dir)
462         {
463           /* The official way to specify a home directory on NT is
464            * the HOMEDRIVE and HOMEPATH environment variables.
465            *
466            * This is inside #ifdef G_OS_WIN32 because with the cygwin dll,
467            * HOME should be a POSIX style pathname.
468            */
469           
470           if (getenv ("HOMEDRIVE") != NULL && getenv ("HOMEPATH") != NULL)
471             {
472               gchar *homedrive, *homepath;
473               
474               homedrive = g_strdup (g_getenv ("HOMEDRIVE"));
475               homepath = g_strdup (g_getenv ("HOMEPATH"));
476               
477               g_home_dir = g_strconcat (homedrive, homepath, NULL);
478               g_free (homedrive);
479               g_free (homepath);
480             }
481         }
482 #endif /* G_OS_WIN32 */
483       
484 #ifdef HAVE_PWD_H
485       {
486         struct passwd *pw = NULL;
487         gpointer buffer = NULL;
488         
489 #  ifdef HAVE_GETPWUID_R
490         struct passwd pwd;
491 #    ifdef _SC_GETPW_R_SIZE_MAX  
492         /* This reurns the maximum length */
493         guint bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
494 #    else /* _SC_GETPW_R_SIZE_MAX */
495         guint bufsize = 64;
496 #    endif /* _SC_GETPW_R_SIZE_MAX */
497         gint error;
498         
499         do
500           {
501             g_free (buffer);
502             buffer = g_malloc (bufsize);
503             errno = 0;
504             
505 #    ifdef HAVE_GETPWUID_R_POSIX
506             error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
507             error = error < 0 ? errno : error;
508 #    else /* !HAVE_GETPWUID_R_POSIX */
509 #      ifdef _AIX
510             error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
511             pw = error == 0 ? &pwd : NULL;
512 #      else /* !_AIX */
513             pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
514             error = pw ? 0 : errno;
515 #      endif /* !_AIX */            
516 #    endif /* !HAVE_GETPWUID_R_POSIX */
517             
518             if (!pw)
519               {
520                 /* we bail out prematurely if the user id can't be found
521                  * (should be pretty rare case actually), or if the buffer
522                  * should be sufficiently big and lookups are still not
523                  * successfull.
524                  */
525                 if (error == 0 || error == ENOENT)
526                   {
527                     g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
528                                (gulong) getuid ());
529                     break;
530                   }
531                 if (bufsize > 32 * 1024)
532                   {
533                     g_warning ("getpwuid_r(): failed due to: %s.",
534                                g_strerror (error));
535                     break;
536                   }
537                 
538                 bufsize *= 2;
539               }
540           }
541         while (!pw);
542 #  endif /* !HAVE_GETPWUID_R */
543         
544         if (!pw)
545           {
546             setpwent ();
547             pw = getpwuid (getuid ());
548             endpwent ();
549           }
550         if (pw)
551           {
552             g_user_name = g_strdup (pw->pw_name);
553             g_real_name = g_strdup (pw->pw_gecos);
554             if (!g_home_dir)
555               g_home_dir = g_strdup (pw->pw_dir);
556           }
557         g_free (buffer);
558       }
559       
560 #else /* !HAVE_PWD_H */
561       
562 #  ifdef G_OS_WIN32
563       {
564         guint len = 17;
565         gchar buffer[17];
566         
567         if (GetUserName (buffer, &len))
568           {
569             g_user_name = g_strdup (buffer);
570             g_real_name = g_strdup (buffer);
571           }
572       }
573 #  endif /* G_OS_WIN32 */
574       
575 #endif /* !HAVE_PWD_H */
576       
577 #ifdef __EMX__
578       /* change '\\' in %HOME% to '/' */
579       g_strdelimit (g_home_dir, "\\",'/');
580 #endif
581       if (!g_user_name)
582         g_user_name = g_strdup ("somebody");
583       if (!g_real_name)
584         g_real_name = g_strdup ("Unknown");
585       else
586         {
587           gchar *p;
588
589           for (p = g_real_name; *p; p++)
590             if (*p == ',')
591               {
592                 *p = 0;
593                 p = g_strdup (g_real_name);
594                 g_free (g_real_name);
595                 g_real_name = p;
596                 break;
597               }
598         }
599     }
600 }
601
602 gchar*
603 g_get_user_name (void)
604 {
605   G_LOCK (g_utils_global);
606   if (!g_tmp_dir)
607     g_get_any_init ();
608   G_UNLOCK (g_utils_global);
609   
610   return g_user_name;
611 }
612
613 gchar*
614 g_get_real_name (void)
615 {
616   G_LOCK (g_utils_global);
617   if (!g_tmp_dir)
618     g_get_any_init ();
619   G_UNLOCK (g_utils_global);
620  
621   return g_real_name;
622 }
623
624 /* Return the home directory of the user. If there is a HOME
625  * environment variable, its value is returned, otherwise use some
626  * system-dependent way of finding it out. If no home directory can be
627  * deduced, return NULL.
628  */
629
630 gchar*
631 g_get_home_dir (void)
632 {
633   G_LOCK (g_utils_global);
634   if (!g_tmp_dir)
635     g_get_any_init ();
636   G_UNLOCK (g_utils_global);
637   
638   return g_home_dir;
639 }
640
641 /* Return a directory to be used to store temporary files. This is the
642  * value of the TMPDIR, TMP or TEMP environment variables (they are
643  * checked in that order). If none of those exist, use P_tmpdir from
644  * stdio.h.  If that isn't defined, return "/tmp" on POSIXly systems,
645  * and C:\ on Windows.
646  */
647
648 gchar*
649 g_get_tmp_dir (void)
650 {
651   G_LOCK (g_utils_global);
652   if (!g_tmp_dir)
653     g_get_any_init ();
654   G_UNLOCK (g_utils_global);
655   
656   return g_tmp_dir;
657 }
658
659 static gchar *g_prgname = NULL;
660
661 gchar*
662 g_get_prgname (void)
663 {
664   gchar* retval;
665
666   G_LOCK (g_utils_global);
667   retval = g_prgname;
668   G_UNLOCK (g_utils_global);
669
670   return retval;
671 }
672
673 void
674 g_set_prgname (const gchar *prgname)
675 {
676   gchar *c;
677     
678   G_LOCK (g_utils_global);
679   c = g_prgname;
680   g_prgname = g_strdup (prgname);
681   g_free (c);
682   G_UNLOCK (g_utils_global);
683 }
684
685 guint
686 g_direct_hash (gconstpointer v)
687 {
688   return GPOINTER_TO_UINT (v);
689 }
690
691 gint
692 g_direct_equal (gconstpointer v1,
693                 gconstpointer v2)
694 {
695   return v1 == v2;
696 }
697
698 gint
699 g_int_equal (gconstpointer v1,
700              gconstpointer v2)
701 {
702   return *((const gint*) v1) == *((const gint*) v2);
703 }
704
705 guint
706 g_int_hash (gconstpointer v)
707 {
708   return *(const gint*) v;
709 }