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 */
83 const guint glib_major_version = GLIB_MAJOR_VERSION;
84 const guint glib_minor_version = GLIB_MINOR_VERSION;
85 const guint glib_micro_version = GLIB_MICRO_VERSION;
86 const guint glib_interface_age = GLIB_INTERFACE_AGE;
87 const guint glib_binary_age = GLIB_BINARY_AGE;
89 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
91 g_memmove (gpointer dest, gconstpointer src, gulong len)
93 gchar* destptr = dest;
94 const gchar* srcptr = src;
95 if (src + len < dest || dest + len < src)
97 bcopy (src, dest, len);
100 else if (dest <= src)
103 *(destptr++) = *(srcptr++);
110 *(--destptr) = *(--srcptr);
113 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
116 g_atexit (GVoidFunc func)
121 /* keep this in sync with glib.h */
123 #ifdef G_NATIVE_ATEXIT
124 result = ATEXIT (func);
126 error = g_strerror (errno);
127 #elif defined (HAVE_ATEXIT)
128 # ifdef NeXT /* @#%@! NeXTStep */
129 result = !atexit ((void (*)(void)) func);
131 error = g_strerror (errno);
133 result = atexit ((void (*)(void)) func);
135 error = g_strerror (errno);
137 #elif defined (HAVE_ON_EXIT)
138 result = on_exit ((void (*)(int, void *)) func, NULL);
140 error = g_strerror (errno);
143 error = "no implementation";
144 #endif /* G_NATIVE_ATEXIT */
147 g_error ("Could not register atexit() function: %s", error);
150 /* Based on execvp() from GNU Libc.
151 * Some of this code is cut-and-pasted into gspawn.c
155 my_strchrnul (const gchar *str, gchar c)
157 gchar *p = (gchar*)str;
158 while (*p && (*p != c))
165 * g_find_program_in_path:
166 * @file: a program name
168 * Locates the first executable named @file in the user's path, in the
169 * same way that execvp() would locate it. Returns an allocated string
170 * with the absolute path name, or NULL if the program is not found in
171 * the path. If @file is already an absolute path, returns a copy of
172 * @file if @file exists and is executable, and NULL otherwise.
174 * Return value: absolute path, or NULL
177 g_find_program_in_path (const gchar *file)
179 gchar *path, *p, *name, *freeme;
183 g_return_val_if_fail (file != NULL, NULL);
187 if (g_file_test (file, G_FILE_TEST_IS_EXECUTABLE))
188 return g_strdup (file);
193 path = g_getenv ("PATH");
196 /* There is no `PATH' in the environment. The default
197 * search path in libc is the current directory followed by
198 * the path `confstr' returns for `_CS_PATH'.
201 /* In GLib we put . last, for security, and don't use the
202 * unportable confstr(); UNIX98 does not actually specify
203 * what to search if PATH is unset. POSIX may, dunno.
206 path = "/bin:/usr/bin:.";
209 len = strlen (file) + 1;
210 pathlen = strlen (path);
211 freeme = name = g_malloc (pathlen + len + 1);
213 /* Copy the file name at the top, including '\0' */
214 memcpy (name + pathlen + 1, file, len);
215 name = name + pathlen;
216 /* And add the slash before the filename */
225 p = my_strchrnul (path, ':');
228 /* Two adjacent colons, or a colon at the beginning or the end
229 * of `PATH' means to search the current directory.
233 startp = memcpy (name - (p - path), path, p - path);
235 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE))
238 ret = g_strdup (startp);
243 while (*p++ != '\0');
251 g_snprintf (gchar *str,
256 #ifdef HAVE_VSNPRINTF
260 g_return_val_if_fail (str != NULL, 0);
261 g_return_val_if_fail (n > 0, 0);
262 g_return_val_if_fail (fmt != NULL, 0);
264 va_start (args, fmt);
265 retval = vsnprintf (str, n, fmt, args);
271 retval = strlen (str);
275 #else /* !HAVE_VSNPRINTF */
279 g_return_val_if_fail (str != NULL, 0);
280 g_return_val_if_fail (n > 0, 0);
281 g_return_val_if_fail (fmt != NULL, 0);
283 va_start (args, fmt);
284 printed = g_strdup_vprintf (fmt, args);
287 strncpy (str, printed, n);
293 #endif /* !HAVE_VSNPRINTF */
297 g_vsnprintf (gchar *str,
302 #ifdef HAVE_VSNPRINTF
305 g_return_val_if_fail (str != NULL, 0);
306 g_return_val_if_fail (n > 0, 0);
307 g_return_val_if_fail (fmt != NULL, 0);
309 retval = vsnprintf (str, n, fmt, args);
314 retval = strlen (str);
318 #else /* !HAVE_VSNPRINTF */
321 g_return_val_if_fail (str != NULL, 0);
322 g_return_val_if_fail (n > 0, 0);
323 g_return_val_if_fail (fmt != NULL, 0);
325 printed = g_strdup_vprintf (fmt, args);
326 strncpy (str, printed, n);
332 #endif /* !HAVE_VSNPRINTF */
336 g_parse_debug_string (const gchar *string,
343 g_return_val_if_fail (string != NULL, 0);
345 if (!g_strcasecmp (string, "all"))
347 for (i=0; i<nkeys; i++)
348 result |= keys[i].value;
352 gchar *str = g_strdup (string);
355 gboolean done = FALSE;
368 for (i=0; i<nkeys; i++)
369 if (!g_strcasecmp(keys[i].key, p))
370 result |= keys[i].value;
382 g_basename (const gchar *file_name)
384 register gchar *base;
385 #ifdef G_ENABLE_DEBUG
386 static gboolean first_call = TRUE;
390 g_warning("g_basename is deprecated. Use g_path_get_basename instead.");
391 g_warning("Watch out! You have to g_free the string returned by "
392 "g_path_get_basename.");
395 #endif /* G_ENABLE_DEBUG */
397 g_return_val_if_fail (file_name != NULL, NULL);
399 base = strrchr (file_name, G_DIR_SEPARATOR);
404 if (isalpha (file_name[0]) && file_name[1] == ':')
405 return (gchar*) file_name + 2;
406 #endif /* G_OS_WIN32 */
408 return (gchar*) file_name;
412 g_path_get_basename (const gchar *file_name)
415 register gint last_nonslash;
419 g_return_val_if_fail (file_name != NULL, NULL);
421 if (file_name[0] == '\0')
423 return g_strdup (".");
425 last_nonslash = strlen (file_name) - 1;
427 while (last_nonslash >= 0 && file_name [last_nonslash] == G_DIR_SEPARATOR)
430 if (last_nonslash == -1)
431 /* string only containing slashes */
432 return g_strdup (G_DIR_SEPARATOR_S);
435 if (last_nonslash == 1 && isalpha (file_name[0]) && file_name[1] == ':')
436 /* string only containing slashes and a drive */
437 return g_strdup (G_DIR_SEPARATOR_S);
438 #endif /* G_OS_WIN32 */
440 base = last_nonslash;
442 while (base >=0 && file_name [base] != G_DIR_SEPARATOR)
446 if (base == -1 && isalpha (file_name[0]) && file_name[1] == ':')
448 #endif /* G_OS_WIN32 */
450 len = last_nonslash - base;
451 retval = g_malloc (len + 1);
452 memcpy (retval, file_name + base + 1, len);
458 g_path_is_absolute (const gchar *file_name)
460 g_return_val_if_fail (file_name != NULL, FALSE);
462 if (file_name[0] == G_DIR_SEPARATOR)
466 if (isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
474 g_path_skip_root (gchar *file_name)
476 g_return_val_if_fail (file_name != NULL, NULL);
478 if (file_name[0] == G_DIR_SEPARATOR)
479 return file_name + 1;
482 if (isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
483 return file_name + 3;
490 g_path_get_dirname (const gchar *file_name)
492 register gchar *base;
495 g_return_val_if_fail (file_name != NULL, NULL);
497 base = strrchr (file_name, G_DIR_SEPARATOR);
499 return g_strdup (".");
500 while (base > file_name && *base == G_DIR_SEPARATOR)
502 len = (guint) 1 + base - file_name;
504 base = g_new (gchar, len + 1);
505 g_memmove (base, file_name, len);
512 g_dirname (const gchar *file_name)
514 #ifdef G_ENABLE_DEBUG
515 static gboolean first_call = TRUE;
519 g_warning("g_dirname is deprecated. Use g_path_get_dirname instead.");
522 #endif /* G_ENABLE_DEBUG */
524 return g_path_get_dirname (file_name);
528 g_get_current_dir (void)
530 gchar *buffer = NULL;
532 static gulong max_len = 0;
535 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
537 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
538 * and, if that wasn't bad enough, hangs in doing so.
540 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
541 buffer = g_new (gchar, max_len + 1);
543 dir = getwd (buffer);
544 #else /* !sun || !HAVE_GETCWD */
545 while (max_len < G_MAXULONG / 2)
547 buffer = g_new (gchar, max_len + 1);
549 dir = getcwd (buffer, max_len);
551 if (dir || errno != ERANGE)
557 #endif /* !sun || !HAVE_GETCWD */
559 if (!dir || !*buffer)
561 /* hm, should we g_error() out here?
562 * this can happen if e.g. "./" has mode \0000
564 buffer[0] = G_DIR_SEPARATOR;
568 dir = g_strdup (buffer);
575 g_getenv (const gchar *variable)
578 g_return_val_if_fail (variable != NULL, NULL);
580 return getenv (variable);
582 G_LOCK_DEFINE_STATIC (getenv);
588 static GArray *environs = NULL;
593 g_return_val_if_fail (variable != NULL, NULL);
598 environs = g_array_new (FALSE, FALSE, sizeof (struct env_struct));
600 /* First we try to find the envinronment variable inside the already
604 for (i = 0; i < environs->len; i++)
606 env = &g_array_index (environs, struct env_struct, i);
607 if (strcmp (env->key, variable) == 0)
609 g_assert (env->value);
615 /* If not found, we ask the system */
617 system_env = getenv (variable);
624 /* On Windows NT, it is relatively typical that environment variables
625 * contain references to other environment variables. Handle that by
626 * calling ExpandEnvironmentStrings.
629 g_array_set_size (environs, environs->len + 1);
631 env = &g_array_index (environs, struct env_struct, environs->len - 1);
633 /* First check how much space we need */
634 length = ExpandEnvironmentStrings (system_env, dummy, 2);
636 /* Then allocate that much, and actualy do the expansion and insert
637 * the new found pair into our buffer
640 env->value = g_malloc (length);
641 env->key = g_strdup (variable);
643 ExpandEnvironmentStrings (system_env, env->value, length);
651 G_LOCK_DEFINE_STATIC (g_utils_global);
653 static gchar *g_tmp_dir = NULL;
654 static gchar *g_user_name = NULL;
655 static gchar *g_real_name = NULL;
656 static gchar *g_home_dir = NULL;
658 /* HOLDS: g_utils_global_lock */
660 g_get_any_init (void)
664 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
666 g_tmp_dir = g_strdup (g_getenv ("TMP"));
668 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
674 g_tmp_dir = g_strdup (P_tmpdir);
675 k = strlen (g_tmp_dir);
676 if (g_tmp_dir[k-1] == G_DIR_SEPARATOR)
677 g_tmp_dir[k-1] = '\0';
684 g_tmp_dir = g_strdup ("/tmp");
685 #else /* G_OS_WIN32 */
686 g_tmp_dir = g_strdup ("C:\\");
687 #endif /* G_OS_WIN32 */
691 g_home_dir = g_strdup (g_getenv ("HOME"));
696 /* The official way to specify a home directory on NT is
697 * the HOMEDRIVE and HOMEPATH environment variables.
699 * This is inside #ifdef G_OS_WIN32 because with the cygwin dll,
700 * HOME should be a POSIX style pathname.
703 if (getenv ("HOMEDRIVE") != NULL && getenv ("HOMEPATH") != NULL)
705 gchar *homedrive, *homepath;
707 homedrive = g_strdup (g_getenv ("HOMEDRIVE"));
708 homepath = g_strdup (g_getenv ("HOMEPATH"));
710 g_home_dir = g_strconcat (homedrive, homepath, NULL);
715 #endif /* G_OS_WIN32 */
719 struct passwd *pw = NULL;
720 gpointer buffer = NULL;
722 # ifdef HAVE_GETPWUID_R
724 # ifdef _SC_GETPW_R_SIZE_MAX
725 /* This reurns the maximum length */
726 guint bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
727 # else /* _SC_GETPW_R_SIZE_MAX */
729 # endif /* _SC_GETPW_R_SIZE_MAX */
735 buffer = g_malloc (bufsize);
738 # ifdef HAVE_GETPWUID_R_POSIX
739 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
740 error = error < 0 ? errno : error;
741 # else /* !HAVE_GETPWUID_R_POSIX */
743 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
744 pw = error == 0 ? &pwd : NULL;
746 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
747 error = pw ? 0 : errno;
749 # endif /* !HAVE_GETPWUID_R_POSIX */
753 /* we bail out prematurely if the user id can't be found
754 * (should be pretty rare case actually), or if the buffer
755 * should be sufficiently big and lookups are still not
758 if (error == 0 || error == ENOENT)
760 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
764 if (bufsize > 32 * 1024)
766 g_warning ("getpwuid_r(): failed due to: %s.",
775 # endif /* !HAVE_GETPWUID_R */
780 pw = getpwuid (getuid ());
785 g_user_name = g_strdup (pw->pw_name);
786 g_real_name = g_strdup (pw->pw_gecos);
788 g_home_dir = g_strdup (pw->pw_dir);
793 #else /* !HAVE_PWD_H */
800 if (GetUserName ((LPTSTR) buffer, (LPDWORD) &len))
802 g_user_name = g_strdup (buffer);
803 g_real_name = g_strdup (buffer);
806 # endif /* G_OS_WIN32 */
808 #endif /* !HAVE_PWD_H */
811 /* change '\\' in %HOME% to '/' */
812 g_strdelimit (g_home_dir, "\\",'/');
815 g_user_name = g_strdup ("somebody");
817 g_real_name = g_strdup ("Unknown");
822 for (p = g_real_name; *p; p++)
826 p = g_strdup (g_real_name);
827 g_free (g_real_name);
836 g_get_user_name (void)
838 G_LOCK (g_utils_global);
841 G_UNLOCK (g_utils_global);
847 g_get_real_name (void)
849 G_LOCK (g_utils_global);
852 G_UNLOCK (g_utils_global);
857 /* Return the home directory of the user. If there is a HOME
858 * environment variable, its value is returned, otherwise use some
859 * system-dependent way of finding it out. If no home directory can be
860 * deduced, return NULL.
864 g_get_home_dir (void)
866 G_LOCK (g_utils_global);
869 G_UNLOCK (g_utils_global);
874 /* Return a directory to be used to store temporary files. This is the
875 * value of the TMPDIR, TMP or TEMP environment variables (they are
876 * checked in that order). If none of those exist, use P_tmpdir from
877 * stdio.h. If that isn't defined, return "/tmp" on POSIXly systems,
878 * and C:\ on Windows.
884 G_LOCK (g_utils_global);
887 G_UNLOCK (g_utils_global);
892 static gchar *g_prgname = NULL;
899 G_LOCK (g_utils_global);
901 G_UNLOCK (g_utils_global);
907 g_set_prgname (const gchar *prgname)
911 G_LOCK (g_utils_global);
913 g_prgname = g_strdup (prgname);
915 G_UNLOCK (g_utils_global);
919 g_direct_hash (gconstpointer v)
921 return GPOINTER_TO_UINT (v);
925 g_direct_equal (gconstpointer v1,
932 g_int_equal (gconstpointer v1,
935 return *((const gint*) v1) == *((const gint*) v2);
939 g_int_hash (gconstpointer v)
941 return *(const gint*) v;
947 * Get the codeset for the current locale.
949 * Return value: a newly allocated string containing the name
950 * of the codeset. This string must be freed with g_free().
956 char *result = nl_langinfo (CODESET);
957 return g_strdup (result);
960 /* FIXME: Do something more intelligent based on setlocale (LC_CTYPE, NULL)
962 return g_strdup ("ISO-8859-1");
964 /* On Win32 we always use UTF-8. At least in GDK. SO should we
965 * therefore return that?
967 return g_strdup ("UTF-8");