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 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.
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.
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.
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/.
28 * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
46 #include <sys/types.h>
47 #ifdef HAVE_SYS_PARAM_H
48 #include <sys/param.h>
51 /* implement Glib's inline functions
53 #define G_IMPLEMENT_INLINES 1
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)
64 #define G_PATH_LENGTH 2048
68 # define STRICT /* Strict typing, please */
73 #endif /* G_OS_WIN32 */
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;
85 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
87 g_memmove (gpointer dest, gconstpointer src, gulong len)
89 gchar* destptr = dest;
90 const gchar* srcptr = src;
91 if (src + len < dest || dest + len < src)
93 bcopy (src, dest, len);
99 *(destptr++) = *(srcptr++);
106 *(--destptr) = *(--srcptr);
109 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
112 g_atexit (GVoidFunc func)
117 /* keep this in sync with glib.h */
119 #ifdef G_NATIVE_ATEXIT
120 result = ATEXIT (func);
122 error = g_strerror (errno);
123 #elif defined (HAVE_ATEXIT)
124 # ifdef NeXT /* @#%@! NeXTStep */
125 result = !atexit ((void (*)(void)) func);
127 error = g_strerror (errno);
129 result = atexit ((void (*)(void)) func);
131 error = g_strerror (errno);
133 #elif defined (HAVE_ON_EXIT)
134 result = on_exit ((void (*)(int, void *)) func, NULL);
136 error = g_strerror (errno);
139 error = "no implementation";
140 #endif /* G_NATIVE_ATEXIT */
143 g_error ("Could not register atexit() function: %s", error);
146 /* Based on execvp() from GNU Libc.
147 * Some of this code is cut-and-pasted into gspawn.c
151 my_strchrnul (const gchar *str, gchar c)
153 gchar *p = (gchar*)str;
154 while (*p && (*p != c))
161 * g_find_program_in_path:
162 * @file: a program name
164 * Locates the first executable named @file in the user's path, in the
165 * same way that execvp() would locate it. Returns an allocated string
166 * with the absolute path name, or NULL if the program is not found in
167 * the path. If @file is already an absolute path, returns a copy of
168 * @file if @file exists and is executable, and NULL otherwise.
170 * Return value: absolute path, or NULL
173 g_find_program_in_path (const gchar *file)
175 gchar *path, *p, *name, *freeme;
179 g_return_val_if_fail (file != NULL, NULL);
183 if (g_file_test (file, G_FILE_TEST_IS_EXECUTABLE))
184 return g_strdup (file);
189 path = g_getenv ("PATH");
192 /* There is no `PATH' in the environment. The default
193 * search path in libc is the current directory followed by
194 * the path `confstr' returns for `_CS_PATH'.
197 /* In GLib we put . last, for security, and don't use the
198 * unportable confstr(); UNIX98 does not actually specify
199 * what to search if PATH is unset. POSIX may, dunno.
202 path = "/bin:/usr/bin:.";
205 len = strlen (file) + 1;
206 pathlen = strlen (path);
207 freeme = name = g_malloc (pathlen + len + 1);
209 /* Copy the file name at the top, including '\0' */
210 memcpy (name + pathlen + 1, file, len);
211 name = name + pathlen;
212 /* And add the slash before the filename */
221 p = my_strchrnul (path, ':');
224 /* Two adjacent colons, or a colon at the beginning or the end
225 * of `PATH' means to search the current directory.
229 startp = memcpy (name - (p - path), path, p - path);
231 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE))
234 ret = g_strdup (startp);
239 while (*p++ != '\0');
247 g_snprintf (gchar *str,
252 #ifdef HAVE_VSNPRINTF
256 g_return_val_if_fail (str != NULL, 0);
257 g_return_val_if_fail (n > 0, 0);
258 g_return_val_if_fail (fmt != NULL, 0);
260 va_start (args, fmt);
261 retval = vsnprintf (str, n, fmt, args);
267 retval = strlen (str);
271 #else /* !HAVE_VSNPRINTF */
275 g_return_val_if_fail (str != NULL, 0);
276 g_return_val_if_fail (n > 0, 0);
277 g_return_val_if_fail (fmt != NULL, 0);
279 va_start (args, fmt);
280 printed = g_strdup_vprintf (fmt, args);
283 strncpy (str, printed, n);
289 #endif /* !HAVE_VSNPRINTF */
293 g_vsnprintf (gchar *str,
298 #ifdef HAVE_VSNPRINTF
301 g_return_val_if_fail (str != NULL, 0);
302 g_return_val_if_fail (n > 0, 0);
303 g_return_val_if_fail (fmt != NULL, 0);
305 retval = vsnprintf (str, n, fmt, args);
310 retval = strlen (str);
314 #else /* !HAVE_VSNPRINTF */
317 g_return_val_if_fail (str != NULL, 0);
318 g_return_val_if_fail (n > 0, 0);
319 g_return_val_if_fail (fmt != NULL, 0);
321 printed = g_strdup_vprintf (fmt, args);
322 strncpy (str, printed, n);
328 #endif /* !HAVE_VSNPRINTF */
332 g_parse_debug_string (const gchar *string,
339 g_return_val_if_fail (string != NULL, 0);
341 if (!g_strcasecmp (string, "all"))
343 for (i=0; i<nkeys; i++)
344 result |= keys[i].value;
348 gchar *str = g_strdup (string);
351 gboolean done = FALSE;
364 for (i=0; i<nkeys; i++)
365 if (!g_strcasecmp(keys[i].key, p))
366 result |= keys[i].value;
378 g_basename (const gchar *file_name)
380 register gchar *base;
381 #ifdef G_ENABLE_DEBUG
382 static gboolean first_call = TRUE;
386 g_warning("g_basename is deprecated. Use g_path_get_basename instead.");
387 g_warning("Watch out! You have to g_free the string returned by "
388 "g_path_get_basename.");
391 #endif /* G_ENABLE_DEBUG */
393 g_return_val_if_fail (file_name != NULL, NULL);
395 base = strrchr (file_name, G_DIR_SEPARATOR);
400 if (isalpha (file_name[0]) && file_name[1] == ':')
401 return (gchar*) file_name + 2;
402 #endif /* G_OS_WIN32 */
404 return (gchar*) file_name;
408 g_path_get_basename (const gchar *file_name)
411 register gint last_nonslash;
415 g_return_val_if_fail (file_name != NULL, NULL);
417 if (file_name[0] == '\0')
419 return g_strdup (".");
421 last_nonslash = strlen (file_name) - 1;
423 while (last_nonslash >= 0 && file_name [last_nonslash] == G_DIR_SEPARATOR)
426 if (last_nonslash == -1)
427 /* string only containing slashes */
428 return g_strdup (G_DIR_SEPARATOR_S);
431 if (last_nonslash == 1 && isalpha (file_name[0]) && file_name[1] == ':')
432 /* string only containing slashes and a drive */
433 return g_strdup (G_DIR_SEPARATOR_S);
434 #endif /* G_OS_WIN32 */
436 base = last_nonslash;
438 while (base >=0 && file_name [base] != G_DIR_SEPARATOR)
442 if (base == -1 && isalpha (file_name[0]) && file_name[1] == ':')
444 #endif /* G_OS_WIN32 */
446 len = last_nonslash - base;
447 retval = g_malloc (len + 1);
448 memcpy (retval, file_name + base + 1, len);
454 g_path_is_absolute (const gchar *file_name)
456 g_return_val_if_fail (file_name != NULL, FALSE);
458 if (file_name[0] == G_DIR_SEPARATOR)
462 if (isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
470 g_path_skip_root (gchar *file_name)
472 g_return_val_if_fail (file_name != NULL, NULL);
474 if (file_name[0] == G_DIR_SEPARATOR)
475 return file_name + 1;
478 if (isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
479 return file_name + 3;
486 g_path_get_dirname (const gchar *file_name)
488 register gchar *base;
491 g_return_val_if_fail (file_name != NULL, NULL);
493 base = strrchr (file_name, G_DIR_SEPARATOR);
495 return g_strdup (".");
496 while (base > file_name && *base == G_DIR_SEPARATOR)
498 len = (guint) 1 + base - file_name;
500 base = g_new (gchar, len + 1);
501 g_memmove (base, file_name, len);
508 g_dirname (const gchar *file_name)
510 #ifdef G_ENABLE_DEBUG
511 static gboolean first_call = TRUE;
515 g_warning("g_dirname is deprecated. Use g_path_get_dirname instead.");
518 #endif /* G_ENABLE_DEBUG */
520 return g_path_get_dirname (file_name);
524 g_get_current_dir (void)
526 gchar *buffer = NULL;
528 static gulong max_len = 0;
531 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
533 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
534 * and, if that wasn't bad enough, hangs in doing so.
536 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
537 buffer = g_new (gchar, max_len + 1);
539 dir = getwd (buffer);
540 #else /* !sun || !HAVE_GETCWD */
541 while (max_len < G_MAXULONG / 2)
543 buffer = g_new (gchar, max_len + 1);
545 dir = getcwd (buffer, max_len);
547 if (dir || errno != ERANGE)
553 #endif /* !sun || !HAVE_GETCWD */
555 if (!dir || !*buffer)
557 /* hm, should we g_error() out here?
558 * this can happen if e.g. "./" has mode \0000
560 buffer[0] = G_DIR_SEPARATOR;
564 dir = g_strdup (buffer);
571 g_getenv (const gchar *variable)
574 g_return_val_if_fail (variable != NULL, NULL);
576 return getenv (variable);
578 G_LOCK_DEFINE_STATIC (getenv);
584 static GArray *environs = NULL;
589 g_return_val_if_fail (variable != NULL, NULL);
594 environs = g_array_new (FALSE, FALSE, sizeof (struct env_struct));
596 /* First we try to find the envinronment variable inside the already
600 for (i = 0; i < environs->len; i++)
602 env = &g_array_index (environs, struct env_struct, i);
603 if (strcmp (env->key, variable) == 0)
605 g_assert (env->value);
611 /* If not found, we ask the system */
613 system_env = getenv (variable);
620 /* On Windows NT, it is relatively typical that environment variables
621 * contain references to other environment variables. Handle that by
622 * calling ExpandEnvironmentStrings.
625 g_array_set_size (environs, environs->len + 1);
627 env = &g_array_index (environs, struct env_struct, environs->len - 1);
629 /* First check how much space we need */
630 length = ExpandEnvironmentStrings (system_env, dummy, 2);
632 /* Then allocate that much, and actualy do the expansion and insert
633 * the new found pair into our buffer
636 env->value = g_malloc (length);
637 env->key = g_strdup (variable);
639 ExpandEnvironmentStrings (system_env, env->value, length);
647 G_LOCK_DEFINE_STATIC (g_utils_global);
649 static gchar *g_tmp_dir = NULL;
650 static gchar *g_user_name = NULL;
651 static gchar *g_real_name = NULL;
652 static gchar *g_home_dir = NULL;
654 /* HOLDS: g_utils_global_lock */
656 g_get_any_init (void)
660 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
662 g_tmp_dir = g_strdup (g_getenv ("TMP"));
664 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
670 g_tmp_dir = g_strdup (P_tmpdir);
671 k = strlen (g_tmp_dir);
672 if (g_tmp_dir[k-1] == G_DIR_SEPARATOR)
673 g_tmp_dir[k-1] = '\0';
680 g_tmp_dir = g_strdup ("/tmp");
681 #else /* G_OS_WIN32 */
682 g_tmp_dir = g_strdup ("C:\\");
683 #endif /* G_OS_WIN32 */
687 g_home_dir = g_strdup (g_getenv ("HOME"));
692 /* The official way to specify a home directory on NT is
693 * the HOMEDRIVE and HOMEPATH environment variables.
695 * This is inside #ifdef G_OS_WIN32 because with the cygwin dll,
696 * HOME should be a POSIX style pathname.
699 if (getenv ("HOMEDRIVE") != NULL && getenv ("HOMEPATH") != NULL)
701 gchar *homedrive, *homepath;
703 homedrive = g_strdup (g_getenv ("HOMEDRIVE"));
704 homepath = g_strdup (g_getenv ("HOMEPATH"));
706 g_home_dir = g_strconcat (homedrive, homepath, NULL);
711 #endif /* G_OS_WIN32 */
715 struct passwd *pw = NULL;
716 gpointer buffer = NULL;
718 # ifdef HAVE_GETPWUID_R
720 # ifdef _SC_GETPW_R_SIZE_MAX
721 /* This reurns the maximum length */
722 guint bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
723 # else /* _SC_GETPW_R_SIZE_MAX */
725 # endif /* _SC_GETPW_R_SIZE_MAX */
731 buffer = g_malloc (bufsize);
734 # ifdef HAVE_GETPWUID_R_POSIX
735 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
736 error = error < 0 ? errno : error;
737 # else /* !HAVE_GETPWUID_R_POSIX */
739 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
740 pw = error == 0 ? &pwd : NULL;
742 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
743 error = pw ? 0 : errno;
745 # endif /* !HAVE_GETPWUID_R_POSIX */
749 /* we bail out prematurely if the user id can't be found
750 * (should be pretty rare case actually), or if the buffer
751 * should be sufficiently big and lookups are still not
754 if (error == 0 || error == ENOENT)
756 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
760 if (bufsize > 32 * 1024)
762 g_warning ("getpwuid_r(): failed due to: %s.",
771 # endif /* !HAVE_GETPWUID_R */
776 pw = getpwuid (getuid ());
781 g_user_name = g_strdup (pw->pw_name);
782 g_real_name = g_strdup (pw->pw_gecos);
784 g_home_dir = g_strdup (pw->pw_dir);
789 #else /* !HAVE_PWD_H */
796 if (GetUserName ((LPTSTR) buffer, (LPDWORD) &len))
798 g_user_name = g_strdup (buffer);
799 g_real_name = g_strdup (buffer);
802 # endif /* G_OS_WIN32 */
804 #endif /* !HAVE_PWD_H */
807 /* change '\\' in %HOME% to '/' */
808 g_strdelimit (g_home_dir, "\\",'/');
811 g_user_name = g_strdup ("somebody");
813 g_real_name = g_strdup ("Unknown");
818 for (p = g_real_name; *p; p++)
822 p = g_strdup (g_real_name);
823 g_free (g_real_name);
832 g_get_user_name (void)
834 G_LOCK (g_utils_global);
837 G_UNLOCK (g_utils_global);
843 g_get_real_name (void)
845 G_LOCK (g_utils_global);
848 G_UNLOCK (g_utils_global);
853 /* Return the home directory of the user. If there is a HOME
854 * environment variable, its value is returned, otherwise use some
855 * system-dependent way of finding it out. If no home directory can be
856 * deduced, return NULL.
860 g_get_home_dir (void)
862 G_LOCK (g_utils_global);
865 G_UNLOCK (g_utils_global);
870 /* Return a directory to be used to store temporary files. This is the
871 * value of the TMPDIR, TMP or TEMP environment variables (they are
872 * checked in that order). If none of those exist, use P_tmpdir from
873 * stdio.h. If that isn't defined, return "/tmp" on POSIXly systems,
874 * and C:\ on Windows.
880 G_LOCK (g_utils_global);
883 G_UNLOCK (g_utils_global);
888 static gchar *g_prgname = NULL;
895 G_LOCK (g_utils_global);
897 G_UNLOCK (g_utils_global);
903 g_set_prgname (const gchar *prgname)
907 G_LOCK (g_utils_global);
909 g_prgname = g_strdup (prgname);
911 G_UNLOCK (g_utils_global);
915 g_direct_hash (gconstpointer v)
917 return GPOINTER_TO_UINT (v);
921 g_direct_equal (gconstpointer v1,
928 g_int_equal (gconstpointer v1,
931 return *((const gint*) v1) == *((const gint*) v2);
935 g_int_hash (gconstpointer v)
937 return *(const gint*) v;
943 * Get the codeset for the current locale.
945 * Return value: a newly allocated string containing the name
946 * of the codeset. This string must be freed with g_free().
952 char *result = nl_langinfo (CODESET);
953 return g_strdup (result);
956 /* FIXME: Do something more intelligent based on setlocale (LC_CTYPE, NULL)
958 return g_strdup ("ISO-8859-1");
960 /* On Win32 we always use UTF-8. At least in GDK. SO should we
961 * therefore return that?
963 return g_strdup ("UTF-8");