Copy all elements of the allocations[] array, including the last. (Pointed
[glib.git] / gutils.c
blob04771cc7992e05a71d2cef1aae51413eb2ea7654
1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1998 Peter Mattis, Spencer Kimball and Josh MacDonald
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.
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.
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.
20 /*
21 * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
28 #include "glibconfig.h"
30 #ifdef HAVE_UNISTD_H
31 #include <unistd.h>
32 #endif
33 #include <stdarg.h>
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <errno.h>
38 #ifdef HAVE_PWD_H
39 #include <pwd.h>
40 #endif
41 #include <sys/types.h>
42 #ifdef HAVE_SYS_PARAM_H
43 #include <sys/param.h>
44 #endif
46 #ifdef NATIVE_WIN32
47 # define STRICT /* Strict typing, please */
48 # include <windows.h>
49 # include <direct.h>
50 # include <errno.h>
51 # include <ctype.h>
52 # ifdef _MSC_VER
53 # include <io.h>
54 # endif /* _MSC_VER */
55 #endif /* NATIVE_WIN32 */
57 /* implement Glib's inline functions
59 #define G_INLINE_FUNC extern
60 #define G_CAN_INLINE 1
61 #include "glib.h"
63 #ifdef MAXPATHLEN
64 #define G_PATH_LENGTH (MAXPATHLEN + 1)
65 #elif defined (PATH_MAX)
66 #define G_PATH_LENGTH (PATH_MAX + 1)
67 #else /* !MAXPATHLEN */
68 #define G_PATH_LENGTH (2048 + 1)
69 #endif /* !MAXPATHLEN && !PATH_MAX */
71 const guint glib_major_version = GLIB_MAJOR_VERSION;
72 const guint glib_minor_version = GLIB_MINOR_VERSION;
73 const guint glib_micro_version = GLIB_MICRO_VERSION;
74 const guint glib_interface_age = GLIB_INTERFACE_AGE;
75 const guint glib_binary_age = GLIB_BINARY_AGE;
77 #if defined (NATIVE_WIN32) && defined (__LCC__)
78 int __stdcall
79 LibMain (void *hinstDll,
80 unsigned long dwReason,
81 void *reserved)
83 return 1;
85 #endif /* NATIVE_WIN32 && __LCC__ */
87 void
88 g_atexit (GVoidFunc func)
90 gint result;
91 gchar *error = NULL;
93 /* keep this in sync with glib.h */
95 #ifdef G_NATIVE_ATEXIT
96 result = ATEXIT (func);
97 if (result)
98 error = g_strerror (errno);
99 #elif defined (HAVE_ATEXIT)
100 # ifdef NeXT /* @#%@! NeXTStep */
101 result = !atexit ((void (*)(void)) func);
102 if (result)
103 error = g_strerror (errno);
104 # else
105 result = atexit ((void (*)(void)) func);
106 if (result)
107 error = g_strerror (errno);
108 # endif /* NeXT */
109 #elif defined (HAVE_ON_EXIT)
110 result = on_exit ((void (*)(int, void *)) func, NULL);
111 if (result)
112 error = g_strerror (errno);
113 #else
114 result = 0;
115 error = "no implementation";
116 #endif /* G_NATIVE_ATEXIT */
118 if (error)
119 g_error ("Could not register atexit() function: %s", error);
122 gint
123 g_snprintf (gchar *str,
124 gulong n,
125 gchar const *fmt,
126 ...)
128 #ifdef HAVE_VSNPRINTF
129 va_list args;
130 gint retval;
132 va_start (args, fmt);
133 retval = vsnprintf (str, n, fmt, args);
134 va_end (args);
136 return retval;
137 #else /* !HAVE_VSNPRINTF */
138 gchar *printed;
139 va_list args;
141 va_start (args, fmt);
142 printed = g_strdup_vprintf (fmt, args);
143 va_end (args);
145 strncpy (str, printed, n);
146 str[n-1] = '\0';
148 g_free (printed);
150 return strlen (str);
151 #endif /* !HAVE_VSNPRINTF */
154 gint
155 g_vsnprintf (gchar *str,
156 gulong n,
157 gchar const *fmt,
158 va_list args)
160 #ifdef HAVE_VSNPRINTF
161 gint retval;
163 retval = vsnprintf (str, n, fmt, args);
165 return retval;
166 #else /* !HAVE_VSNPRINTF */
167 gchar *printed;
169 printed = g_strdup_vprintf (fmt, args);
170 strncpy (str, printed, n);
171 str[n-1] = '\0';
173 g_free (printed);
175 return strlen (str);
176 #endif /* !HAVE_VSNPRINTF */
179 guint
180 g_parse_debug_string (const gchar *string,
181 GDebugKey *keys,
182 guint nkeys)
184 guint i;
185 guint result = 0;
187 g_return_val_if_fail (string != NULL, 0);
189 if (!g_strcasecmp (string, "all"))
191 for (i=0; i<nkeys; i++)
192 result |= keys[i].value;
194 else
196 gchar *str = g_strdup (string);
197 gchar *p = str;
198 gchar *q;
199 gboolean done = FALSE;
201 while (*p && !done)
203 q = strchr (p, ':');
204 if (!q)
206 q = p + strlen(p);
207 done = TRUE;
210 *q = 0;
212 for (i=0; i<nkeys; i++)
213 if (!g_strcasecmp(keys[i].key, p))
214 result |= keys[i].value;
216 p = q+1;
219 g_free (str);
222 return result;
225 gchar*
226 g_basename (const gchar *file_name)
228 register gchar *base;
230 g_return_val_if_fail (file_name != NULL, NULL);
232 base = strrchr (file_name, G_DIR_SEPARATOR);
233 if (base)
234 return base + 1;
236 #ifdef NATIVE_WIN32
237 if (isalpha (file_name[0]) && file_name[1] == ':')
238 return (gchar*) file_name + 2;
239 #endif /* NATIVE_WIN32 */
241 return (gchar*) file_name;
244 gboolean
245 g_path_is_absolute (const gchar *file_name)
247 g_return_val_if_fail (file_name != NULL, FALSE);
249 if (file_name[0] == G_DIR_SEPARATOR)
250 return TRUE;
252 #ifdef NATIVE_WIN32
253 if (isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
254 return TRUE;
255 #endif
257 return FALSE;
260 gchar*
261 g_path_skip_root (gchar *file_name)
263 g_return_val_if_fail (file_name != NULL, NULL);
265 if (file_name[0] == G_DIR_SEPARATOR)
266 return file_name + 1;
268 #ifdef NATIVE_WIN32
269 if (isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
270 return file_name + 3;
271 #endif
273 return NULL;
276 gchar*
277 g_dirname (const gchar *file_name)
279 register gchar *base;
280 register guint len;
282 g_return_val_if_fail (file_name != NULL, NULL);
284 base = strrchr (file_name, G_DIR_SEPARATOR);
285 if (!base)
286 return g_strdup (".");
287 while (base > file_name && *base == G_DIR_SEPARATOR)
288 base--;
289 len = (guint) 1 + base - file_name;
291 base = g_new (gchar, len + 1);
292 g_memmove (base, file_name, len);
293 base[len] = 0;
295 return base;
298 gchar*
299 g_get_current_dir (void)
301 gchar *buffer;
302 gchar *dir;
304 buffer = g_new (gchar, G_PATH_LENGTH);
305 *buffer = 0;
307 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
308 * and, if that wasn't bad enough, hangs in doing so.
310 #if defined (sun) && !defined (__SVR4)
311 dir = getwd (buffer);
312 #else /* !sun */
313 dir = getcwd (buffer, G_PATH_LENGTH - 1);
314 #endif /* !sun */
316 if (!dir || !*buffer)
318 /* hm, should we g_error() out here?
319 * this can happen if e.g. "./" has mode \0000
321 buffer[0] = G_DIR_SEPARATOR;
322 buffer[1] = 0;
325 dir = g_strdup (buffer);
326 g_free (buffer);
328 return dir;
331 gchar*
332 g_getenv (const gchar *variable)
334 #ifndef NATIVE_WIN32
335 g_return_val_if_fail (variable != NULL, NULL);
337 return getenv (variable);
338 #else
339 gchar *v;
340 guint k;
341 static gchar *p = NULL;
342 static gint l;
343 gchar dummy[2];
345 g_return_val_if_fail (variable != NULL, NULL);
347 v = getenv (variable);
348 if (!v)
349 return NULL;
351 /* On Windows NT, it is relatively typical that environment variables
352 * contain references to other environment variables. Handle that by
353 * calling ExpandEnvironmentStrings.
356 /* First check how much space we need */
357 k = ExpandEnvironmentStrings (v, dummy, 2);
358 /* Then allocate that much, and actualy do the expansion */
359 if (p == NULL)
361 p = g_malloc (k);
362 l = k;
364 else if (k > l)
366 p = g_realloc (p, k);
367 l = k;
369 ExpandEnvironmentStrings (v, p, k);
370 return p;
371 #endif
375 G_LOCK_DECLARE_STATIC (g_utils_global);
377 static gchar *g_tmp_dir = NULL;
378 static gchar *g_user_name = NULL;
379 static gchar *g_real_name = NULL;
380 static gchar *g_home_dir = NULL;
382 /* HOLDS: g_utils_global_lock */
383 static void
384 g_get_any_init (void)
386 if (!g_tmp_dir)
388 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
389 if (!g_tmp_dir)
390 g_tmp_dir = g_strdup (g_getenv ("TMP"));
391 if (!g_tmp_dir)
392 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
394 #ifdef P_tmpdir
395 if (!g_tmp_dir)
397 int k;
398 g_tmp_dir = g_strdup (P_tmpdir);
399 k = strlen (g_tmp_dir);
400 if (g_tmp_dir[k-1] == G_DIR_SEPARATOR)
401 g_tmp_dir[k-1] = '\0';
403 #endif
405 if (!g_tmp_dir)
407 #ifndef NATIVE_WIN32
408 g_tmp_dir = g_strdup ("/tmp");
409 #else /* NATIVE_WIN32 */
410 g_tmp_dir = g_strdup ("C:\\");
411 #endif /* NATIVE_WIN32 */
414 if (!g_home_dir)
415 g_home_dir = g_strdup (g_getenv ("HOME"));
417 #ifdef NATIVE_WIN32
418 if (!g_home_dir)
420 /* The official way to specify a home directory on NT is
421 * the HOMEDRIVE and HOMEPATH environment variables.
423 * This is inside #ifdef NATIVE_WIN32 because with the cygwin dll,
424 * HOME should be a POSIX style pathname.
427 if (getenv ("HOMEDRIVE") != NULL && getenv ("HOMEPATH") != NULL)
429 gchar *homedrive, *homepath;
431 homedrive = g_strdup (g_getenv ("HOMEDRIVE"));
432 homepath = g_strdup (g_getenv ("HOMEPATH"));
434 g_home_dir = g_strconcat (homedrive, homepath, NULL);
435 g_free (homedrive);
436 g_free (homepath);
439 #endif /* !NATIVE_WIN32 */
441 #ifdef HAVE_PWD_H
443 struct passwd *pw = NULL;
444 gpointer buffer = NULL;
446 # ifdef HAVE_GETPWUID_R
447 struct passwd pwd;
448 guint bufsize = 64;
449 gint error;
451 while (1)
453 g_free (buffer);
454 buffer = g_malloc (bufsize);
455 errno = 0;
457 # ifdef HAVE_GETPWUID_R_POSIX
458 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
459 error = error < 0 ? errno : error;
460 # else /* !HAVE_GETPWUID_R_POSIX */
461 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
462 error = pw ? 0 : errno;
463 # endif /* !HAVE_GETPWUID_R_POSIX */
465 /* Now there are actually only 3 cases to leave the loop:
466 1. pw != NULL -> all went fine.
467 2. pw == NULL && ( error == 0 || error == ENOENT )
468 -> no such user (unlikely in the case of getuid ())
469 3. bufsize > 32k -> the problem can't be of ERANGE type */
470 if (pw)
471 break;
473 if (pw == NULL && ( error == 0 || error == ENOENT))
475 g_warning ("getpwuid_r(): failed due to: No such user %d.",
476 getuid ());
477 break;
480 if (bufsize > 32 * 1024)
482 g_warning ("getpwuid_r(): failed due to: %s.",
483 g_strerror (error));
484 break;
487 bufsize *= 2;
489 # endif /* !HAVE_GETPWUID_R */
491 if (!pw)
493 setpwent ();
494 pw = getpwuid (getuid ());
495 endpwent ();
497 if (pw)
499 g_user_name = g_strdup (pw->pw_name);
500 g_real_name = g_strdup (pw->pw_gecos);
501 if (!g_home_dir)
502 g_home_dir = g_strdup (pw->pw_dir);
504 g_free (buffer);
507 #else /* !HAVE_PWD_H */
509 # ifdef NATIVE_WIN32
511 guint len = 17;
512 gchar buffer[17];
514 if (GetUserName (buffer, &len))
516 g_user_name = g_strdup (buffer);
517 g_real_name = g_strdup (buffer);
520 # endif /* NATIVE_WIN32 */
522 #endif /* !HAVE_PWD_H */
524 if (!g_user_name)
525 g_user_name = g_strdup ("somebody");
526 if (!g_real_name)
527 g_real_name = g_strdup ("Unknown");
531 gchar*
532 g_get_user_name (void)
534 G_LOCK (g_utils_global);
535 if (!g_tmp_dir)
536 g_get_any_init ();
537 G_UNLOCK (g_utils_global);
539 return g_user_name;
542 gchar*
543 g_get_real_name (void)
545 G_LOCK (g_utils_global);
546 if (!g_tmp_dir)
547 g_get_any_init ();
548 G_UNLOCK (g_utils_global);
550 return g_real_name;
553 /* Return the home directory of the user. If there is a HOME
554 * environment variable, its value is returned, otherwise use some
555 * system-dependent way of finding it out. If no home directory can be
556 * deduced, return NULL.
559 gchar*
560 g_get_home_dir (void)
562 G_LOCK (g_utils_global);
563 if (!g_tmp_dir)
564 g_get_any_init ();
565 G_UNLOCK (g_utils_global);
567 return g_home_dir;
570 /* Return a directory to be used to store temporary files. This is the
571 * value of the TMPDIR, TMP or TEMP environment variables (they are
572 * checked in that order). If none of those exist, use P_tmpdir from
573 * stdio.h. If that isn't defined, return "/tmp" on POSIXly systems,
574 * and C:\ on Windows.
577 gchar*
578 g_get_tmp_dir (void)
580 G_LOCK (g_utils_global);
581 if (!g_tmp_dir)
582 g_get_any_init ();
583 G_UNLOCK (g_utils_global);
585 return g_tmp_dir;
588 static gchar *g_prgname = NULL;
590 gchar*
591 g_get_prgname (void)
593 gchar* retval;
595 G_LOCK (g_utils_global);
596 retval = g_prgname;
597 G_UNLOCK (g_utils_global);
599 return retval;
602 void
603 g_set_prgname (const gchar *prgname)
605 gchar *c;
607 G_LOCK (g_utils_global);
608 c = g_prgname;
609 g_prgname = g_strdup (prgname);
610 g_free (c);
611 G_UNLOCK (g_utils_global);
614 guint
615 g_direct_hash (gconstpointer v)
617 return GPOINTER_TO_UINT (v);
620 gint
621 g_direct_equal (gconstpointer v1,
622 gconstpointer v2)
624 return GPOINTER_TO_UINT (v1) == GPOINTER_TO_UINT (v2);
627 gint
628 g_int_equal (gconstpointer v1,
629 gconstpointer v2)
631 return *((const gint*) v1) == *((const gint*) v2);
634 guint
635 g_int_hash (gconstpointer v)
637 return *(const gint*) v;
640 #if 0 /* Old IO Channels */
642 GIOChannel*
643 g_iochannel_new (gint fd)
645 GIOChannel *channel = g_new (GIOChannel, 1);
647 channel->fd = fd;
649 #ifdef NATIVE_WIN32
650 channel->peer = 0;
651 channel->peer_fd = 0;
652 channel->offset = 0;
653 channel->need_wakeups = 0;
654 #endif /* NATIVE_WIN32 */
656 return channel;
659 void
660 g_iochannel_free (GIOChannel *channel)
662 g_return_if_fail (channel != NULL);
664 g_free (channel);
667 void
668 g_iochannel_close_and_free (GIOChannel *channel)
670 g_return_if_fail (channel != NULL);
672 close (channel->fd);
674 g_iochannel_free (channel);
677 #undef g_iochannel_wakeup_peer
679 void
680 g_iochannel_wakeup_peer (GIOChannel *channel)
682 #ifdef NATIVE_WIN32
683 static guint message = 0;
684 #endif
686 g_return_if_fail (channel != NULL);
688 #ifdef NATIVE_WIN32
689 if (message == 0)
690 message = RegisterWindowMessage ("gdk-pipe-readable");
692 # if 0
693 g_print ("g_iochannel_wakeup_peer: calling PostThreadMessage (%#x, %d, %d, %d)\n",
694 channel->peer, message, channel->peer_fd, channel->offset);
695 # endif
696 PostThreadMessage (channel->peer, message,
697 channel->peer_fd, channel->offset);
698 #endif /* NATIVE_WIN32 */
701 #endif /* Old IO Channels */
703 #ifdef NATIVE_WIN32
704 #ifdef _MSC_VER
707 gwin_ftruncate (gint fd,
708 guint size)
710 HANDLE hfile;
711 guint curpos;
713 g_return_val_if_fail (fd >= 0, -1);
715 hfile = (HANDLE) _get_osfhandle (fd);
716 curpos = SetFilePointer (hfile, 0, NULL, FILE_CURRENT);
717 if (curpos == 0xFFFFFFFF
718 || SetFilePointer (hfile, size, NULL, FILE_BEGIN) == 0xFFFFFFFF
719 || !SetEndOfFile (hfile))
721 gint error = GetLastError ();
723 switch (error)
725 case ERROR_INVALID_HANDLE:
726 errno = EBADF;
727 break;
728 default:
729 errno = EIO;
730 break;
733 return -1;
736 return 0;
739 DIR*
740 gwin_opendir (const char *dirname)
742 DIR *result;
743 gchar *mask;
744 guint k;
746 g_return_val_if_fail (dirname != NULL, NULL);
748 result = g_new0 (DIR, 1);
749 result->find_file_data = g_new0 (WIN32_FIND_DATA, 1);
750 result->dir_name = g_strdup (dirname);
752 k = strlen (result->dir_name);
753 if (k && result->dir_name[k - 1] == '\\')
755 result->dir_name[k - 1] = '\0';
756 k--;
758 mask = g_strdup_printf ("%s\\*", result->dir_name);
760 result->find_file_handle = (guint) FindFirstFile (mask,
761 (LPWIN32_FIND_DATA) result->find_file_data);
762 g_free (mask);
764 if (result->find_file_handle == (guint) INVALID_HANDLE_VALUE)
766 int error = GetLastError ();
768 g_free (result->dir_name);
769 g_free (result->find_file_data);
770 g_free (result);
771 switch (error)
773 default:
774 errno = EIO;
775 return NULL;
778 result->just_opened = TRUE;
780 return result;
783 struct dirent*
784 gwin_readdir (DIR *dir)
786 static struct dirent result;
788 g_return_val_if_fail (dir != NULL, NULL);
790 if (dir->just_opened)
791 dir->just_opened = FALSE;
792 else
794 if (!FindNextFile ((HANDLE) dir->find_file_handle,
795 (LPWIN32_FIND_DATA) dir->find_file_data))
797 int error = GetLastError ();
799 switch (error)
801 case ERROR_NO_MORE_FILES:
802 return NULL;
803 default:
804 errno = EIO;
805 return NULL;
809 strcpy (result.d_name, g_basename (((LPWIN32_FIND_DATA) dir->find_file_data)->cFileName));
811 return &result;
814 void
815 gwin_rewinddir (DIR *dir)
817 gchar *mask;
819 g_return_if_fail (dir != NULL);
821 if (!FindClose ((HANDLE) dir->find_file_handle))
822 g_warning ("gwin_rewinddir(): FindClose() failed\n");
824 mask = g_strdup_printf ("%s\\*", dir->dir_name);
825 dir->find_file_handle = (guint) FindFirstFile (mask,
826 (LPWIN32_FIND_DATA) dir->find_file_data);
827 g_free (mask);
829 if (dir->find_file_handle == (guint) INVALID_HANDLE_VALUE)
831 int error = GetLastError ();
833 switch (error)
835 default:
836 errno = EIO;
837 return;
840 dir->just_opened = TRUE;
843 gint
844 gwin_closedir (DIR *dir)
846 g_return_val_if_fail (dir != NULL, -1);
848 if (!FindClose ((HANDLE) dir->find_file_handle))
850 int error = GetLastError ();
852 switch (error)
854 default:
855 errno = EIO; return -1;
859 g_free (dir->dir_name);
860 g_free (dir->find_file_data);
861 g_free (dir);
863 return 0;
866 #endif /* _MSC_VER */
868 #endif /* NATIVE_WIN32 */