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)
115 const gchar *error = NULL;
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))
162 gchar *inner_find_program_in_path (const gchar *program);
165 g_find_program_in_path (const gchar *program)
167 const gchar *last_dot = strrchr (program, '.');
169 if (last_dot == NULL || strchr (last_dot, '\\') != NULL)
171 const gint program_length = strlen (program);
172 const gchar *pathext = getenv ("PATHEXT");
174 gchar *decorated_program;
178 pathext = ".com;.exe;.bat";
184 p = my_strchrnul (pathext, ';');
186 decorated_program = g_malloc (program_length + (p-pathext) + 1);
187 memcpy (decorated_program, program, program_length);
188 memcpy (decorated_program+program_length, pathext, p-pathext);
189 decorated_program [program_length + (p-pathext)] = '\0';
191 retval = inner_find_program_in_path (decorated_program);
192 g_free (decorated_program);
196 } while (*p++ != '\0');
200 return inner_find_program_in_path (program);
203 #define g_find_program_in_path inner_find_program_in_path
207 * g_find_program_in_path:
208 * @program: a program name
210 * Locates the first executable named @program in the user's path, in the
211 * same way that execvp() would locate it. Returns an allocated string
212 * with the absolute path name, or NULL if the program is not found in
213 * the path. If @program is already an absolute path, returns a copy of
214 * @program if @program exists and is executable, and NULL otherwise.
216 * On Windows, if @program does not have a file type suffix, tries to
217 * append the suffixes in the PATHEXT environment variable (if that
218 * doesn't exists, the suffixes .com, .exe, and .bat) in turn, and
219 * then look for the resulting file name in the same way as
220 * CreateProcess() would. This means first in the directory where the
221 * program was loaded from, then in the current directory, then in the
222 * Windows 32-bit system directory, then in the Windows directory, and
223 * finally in the directories in the PATH environment variable. If
224 * the program is found, the return value contains the full name
225 * including the type suffix.
227 * Return value: absolute path, or NULL
230 g_find_program_in_path (const gchar *program)
232 const gchar *path, *p;
233 gchar *name, *freeme;
240 g_return_val_if_fail (program != NULL, NULL);
242 /* If it is an absolute path, or a relative path including subdirectories,
243 * don't look in PATH.
245 if (g_path_is_absolute (program)
246 || strchr (program, G_DIR_SEPARATOR) != NULL)
248 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE))
249 return g_strdup (program);
254 path = g_getenv ("PATH");
258 /* There is no `PATH' in the environment. The default
259 * search path in GNU libc is the current directory followed by
260 * the path `confstr' returns for `_CS_PATH'.
263 /* In GLib we put . last, for security, and don't use the
264 * unportable confstr(); UNIX98 does not actually specify
265 * what to search if PATH is unset. POSIX may, dunno.
268 path = "/bin:/usr/bin:.";
273 gchar moddir[PATH_MAX], sysdir[PATH_MAX], windir[PATH_MAX];
275 GetModuleFileName (NULL, moddir, sizeof (moddir));
276 tmp = g_path_get_dirname (moddir);
277 GetSystemDirectory (sysdir, sizeof (sysdir));
278 GetWindowsDirectory (windir, sizeof (windir));
279 path_tmp = g_strconcat (tmp, ";.;", sysdir, ";", windir,
280 (path != NULL ? ";" : NULL),
281 (path != NULL ? path : NULL),
288 len = strlen (program) + 1;
289 pathlen = strlen (path);
290 freeme = name = g_malloc (pathlen + len + 1);
292 /* Copy the file name at the top, including '\0' */
293 memcpy (name + pathlen + 1, program, len);
294 name = name + pathlen;
295 /* And add the slash before the filename */
296 *name = G_DIR_SEPARATOR;
304 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
307 /* Two adjacent colons, or a colon at the beginning or the end
308 * of `PATH' means to search the current directory.
312 startp = memcpy (name - (p - path), path, p - path);
314 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE))
317 ret = g_strdup (startp);
325 while (*p++ != '\0');
336 g_snprintf (gchar *str,
341 #ifdef HAVE_VSNPRINTF
345 g_return_val_if_fail (str != NULL, 0);
346 g_return_val_if_fail (n > 0, 0);
347 g_return_val_if_fail (fmt != NULL, 0);
349 va_start (args, fmt);
350 retval = vsnprintf (str, n, fmt, args);
356 retval = strlen (str);
360 #else /* !HAVE_VSNPRINTF */
364 g_return_val_if_fail (str != NULL, 0);
365 g_return_val_if_fail (n > 0, 0);
366 g_return_val_if_fail (fmt != NULL, 0);
368 va_start (args, fmt);
369 printed = g_strdup_vprintf (fmt, args);
372 strncpy (str, printed, n);
378 #endif /* !HAVE_VSNPRINTF */
382 g_vsnprintf (gchar *str,
387 #ifdef HAVE_VSNPRINTF
390 g_return_val_if_fail (str != NULL, 0);
391 g_return_val_if_fail (n > 0, 0);
392 g_return_val_if_fail (fmt != NULL, 0);
394 retval = vsnprintf (str, n, fmt, args);
399 retval = strlen (str);
403 #else /* !HAVE_VSNPRINTF */
406 g_return_val_if_fail (str != NULL, 0);
407 g_return_val_if_fail (n > 0, 0);
408 g_return_val_if_fail (fmt != NULL, 0);
410 printed = g_strdup_vprintf (fmt, args);
411 strncpy (str, printed, n);
417 #endif /* !HAVE_VSNPRINTF */
421 g_parse_debug_string (const gchar *string,
428 g_return_val_if_fail (string != NULL, 0);
430 if (!g_strcasecmp (string, "all"))
432 for (i=0; i<nkeys; i++)
433 result |= keys[i].value;
437 gchar *str = g_strdup (string);
440 gboolean done = FALSE;
453 for (i=0; i<nkeys; i++)
454 if (!g_strcasecmp(keys[i].key, p))
455 result |= keys[i].value;
466 G_CONST_RETURN gchar*
467 g_basename (const gchar *file_name)
469 register gchar *base;
470 #if defined(G_ENABLE_DEBUG) && !defined(G_OS_WIN32)
471 static gboolean first_call = TRUE;
475 g_message ("g_basename is deprecated. Use g_path_get_basename instead. "
476 "Beware that the string returned by g_path_get_basename() has "
477 " to be g_free()ed.");
480 #endif /* G_ENABLE_DEBUG */
482 g_return_val_if_fail (file_name != NULL, NULL);
484 base = strrchr (file_name, G_DIR_SEPARATOR);
489 if (isalpha (file_name[0]) && file_name[1] == ':')
490 return (gchar*) file_name + 2;
491 #endif /* G_OS_WIN32 */
493 return (gchar*) file_name;
497 g_path_get_basename (const gchar *file_name)
500 register gint last_nonslash;
504 g_return_val_if_fail (file_name != NULL, NULL);
506 if (file_name[0] == '\0')
508 return g_strdup (".");
510 last_nonslash = strlen (file_name) - 1;
512 while (last_nonslash >= 0 && file_name [last_nonslash] == G_DIR_SEPARATOR)
515 if (last_nonslash == -1)
516 /* string only containing slashes */
517 return g_strdup (G_DIR_SEPARATOR_S);
520 if (last_nonslash == 1 && isalpha (file_name[0]) && file_name[1] == ':')
521 /* string only containing slashes and a drive */
522 return g_strdup (G_DIR_SEPARATOR_S);
523 #endif /* G_OS_WIN32 */
525 base = last_nonslash;
527 while (base >=0 && file_name [base] != G_DIR_SEPARATOR)
531 if (base == -1 && isalpha (file_name[0]) && file_name[1] == ':')
533 #endif /* G_OS_WIN32 */
535 len = last_nonslash - base;
536 retval = g_malloc (len + 1);
537 memcpy (retval, file_name + base + 1, len);
543 g_path_is_absolute (const gchar *file_name)
545 g_return_val_if_fail (file_name != NULL, FALSE);
547 if (file_name[0] == G_DIR_SEPARATOR)
551 if (isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
558 G_CONST_RETURN gchar*
559 g_path_skip_root (const gchar *file_name)
561 g_return_val_if_fail (file_name != NULL, NULL);
564 /* Skip \\server\share */
565 if (file_name[0] == G_DIR_SEPARATOR &&
566 file_name[1] == G_DIR_SEPARATOR &&
571 if ((p = strchr (file_name + 2, G_DIR_SEPARATOR)) > file_name + 2 &&
576 while (file_name[0] && file_name[0] != G_DIR_SEPARATOR)
579 /* Possibly skip a backslash after the share name */
580 if (file_name[0] == G_DIR_SEPARATOR)
583 return (gchar *)file_name;
588 /* Skip initial slashes */
589 if (file_name[0] == G_DIR_SEPARATOR)
591 while (file_name[0] == G_DIR_SEPARATOR)
593 return (gchar *)file_name;
598 if (isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
599 return (gchar *)file_name + 3;
606 g_path_get_dirname (const gchar *file_name)
608 register gchar *base;
611 g_return_val_if_fail (file_name != NULL, NULL);
613 base = strrchr (file_name, G_DIR_SEPARATOR);
615 return g_strdup (".");
616 while (base > file_name && *base == G_DIR_SEPARATOR)
618 len = (guint) 1 + base - file_name;
620 base = g_new (gchar, len + 1);
621 g_memmove (base, file_name, len);
628 g_dirname (const gchar *file_name)
630 #if defined(G_ENABLE_DEBUG) && !defined(G_OS_WIN32)
631 static gboolean first_call = TRUE;
635 g_message ("g_dirname() is deprecated. Use g_path_get_dirname() instead.");
638 #endif /* G_ENABLE_DEBUG */
640 return g_path_get_dirname (file_name);
644 g_get_current_dir (void)
646 gchar *buffer = NULL;
648 static gulong max_len = 0;
651 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
653 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
654 * and, if that wasn't bad enough, hangs in doing so.
656 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
657 buffer = g_new (gchar, max_len + 1);
659 dir = getwd (buffer);
660 #else /* !sun || !HAVE_GETCWD */
661 while (max_len < G_MAXULONG / 2)
663 buffer = g_new (gchar, max_len + 1);
665 dir = getcwd (buffer, max_len);
667 if (dir || errno != ERANGE)
673 #endif /* !sun || !HAVE_GETCWD */
675 if (!dir || !*buffer)
677 /* hm, should we g_error() out here?
678 * this can happen if e.g. "./" has mode \0000
680 buffer[0] = G_DIR_SEPARATOR;
684 dir = g_strdup (buffer);
690 G_CONST_RETURN gchar*
691 g_getenv (const gchar *variable)
694 g_return_val_if_fail (variable != NULL, NULL);
696 return getenv (variable);
698 G_LOCK_DEFINE_STATIC (getenv);
704 static GArray *environs = NULL;
709 g_return_val_if_fail (variable != NULL, NULL);
714 environs = g_array_new (FALSE, FALSE, sizeof (struct env_struct));
716 /* First we try to find the envinronment variable inside the already
720 for (i = 0; i < environs->len; i++)
722 env = &g_array_index (environs, struct env_struct, i);
723 if (strcmp (env->key, variable) == 0)
725 g_assert (env->value);
731 /* If not found, we ask the system */
733 system_env = getenv (variable);
740 /* On Windows NT, it is relatively typical that environment variables
741 * contain references to other environment variables. Handle that by
742 * calling ExpandEnvironmentStrings.
745 g_array_set_size (environs, environs->len + 1);
747 env = &g_array_index (environs, struct env_struct, environs->len - 1);
749 /* First check how much space we need */
750 length = ExpandEnvironmentStrings (system_env, dummy, 2);
752 /* Then allocate that much, and actualy do the expansion and insert
753 * the new found pair into our buffer
756 env->value = g_malloc (length);
757 env->key = g_strdup (variable);
759 ExpandEnvironmentStrings (system_env, env->value, length);
767 G_LOCK_DEFINE_STATIC (g_utils_global);
769 static gchar *g_tmp_dir = NULL;
770 static gchar *g_user_name = NULL;
771 static gchar *g_real_name = NULL;
772 static gchar *g_home_dir = NULL;
774 /* HOLDS: g_utils_global_lock */
776 g_get_any_init (void)
780 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
782 g_tmp_dir = g_strdup (g_getenv ("TMP"));
784 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
790 g_tmp_dir = g_strdup (P_tmpdir);
791 k = strlen (g_tmp_dir);
792 if (g_tmp_dir[k-1] == G_DIR_SEPARATOR)
793 g_tmp_dir[k-1] = '\0';
800 g_tmp_dir = g_strdup ("/tmp");
801 #else /* G_OS_WIN32 */
802 g_tmp_dir = g_strdup ("C:\\");
803 #endif /* G_OS_WIN32 */
807 g_home_dir = g_strdup (g_getenv ("HOME"));
810 /* In case HOME is Unix-style (it happens), convert it to
816 while ((p = strchr (g_home_dir, '/')) != NULL)
822 /* USERPROFILE is probably the closest equivalent to $HOME? */
823 if (getenv ("USERPROFILE") != NULL)
824 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
829 /* At least at some time, HOMEDRIVE and HOMEPATH were used
830 * to point to the home directory, I think. But on Windows
831 * 2000 HOMEDRIVE seems to be equal to SYSTEMDRIVE, and
832 * HOMEPATH is its root "\"?
834 if (getenv ("HOMEDRIVE") != NULL && getenv ("HOMEPATH") != NULL)
836 gchar *homedrive, *homepath;
838 homedrive = g_strdup (g_getenv ("HOMEDRIVE"));
839 homepath = g_strdup (g_getenv ("HOMEPATH"));
841 g_home_dir = g_strconcat (homedrive, homepath, NULL);
846 #endif /* G_OS_WIN32 */
850 struct passwd *pw = NULL;
851 gpointer buffer = NULL;
853 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
855 # ifdef _SC_GETPW_R_SIZE_MAX
856 /* This reurns the maximum length */
857 guint bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
858 # else /* _SC_GETPW_R_SIZE_MAX */
860 # endif /* _SC_GETPW_R_SIZE_MAX */
866 buffer = g_malloc (bufsize);
869 # ifdef HAVE_POSIX_GETPWUID_R
870 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
871 error = error < 0 ? errno : error;
872 # else /* HAVE_NONPOSIX_GETPWUID_R */
874 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
875 pw = error == 0 ? &pwd : NULL;
877 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
878 error = pw ? 0 : errno;
880 # endif /* HAVE_NONPOSIX_GETPWUID_R */
884 /* we bail out prematurely if the user id can't be found
885 * (should be pretty rare case actually), or if the buffer
886 * should be sufficiently big and lookups are still not
889 if (error == 0 || error == ENOENT)
891 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
895 if (bufsize > 32 * 1024)
897 g_warning ("getpwuid_r(): failed due to: %s.",
906 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
911 pw = getpwuid (getuid ());
916 g_user_name = g_strdup (pw->pw_name);
917 g_real_name = g_strdup (pw->pw_gecos);
919 g_home_dir = g_strdup (pw->pw_dir);
924 #else /* !HAVE_PWD_H */
931 if (GetUserName ((LPTSTR) buffer, (LPDWORD) &len))
933 g_user_name = g_strdup (buffer);
934 g_real_name = g_strdup (buffer);
937 # endif /* G_OS_WIN32 */
939 #endif /* !HAVE_PWD_H */
942 /* change '\\' in %HOME% to '/' */
943 g_strdelimit (g_home_dir, "\\",'/');
946 g_user_name = g_strdup ("somebody");
948 g_real_name = g_strdup ("Unknown");
953 for (p = g_real_name; *p; p++)
957 p = g_strdup (g_real_name);
958 g_free (g_real_name);
966 G_CONST_RETURN gchar*
967 g_get_user_name (void)
969 G_LOCK (g_utils_global);
972 G_UNLOCK (g_utils_global);
977 G_CONST_RETURN gchar*
978 g_get_real_name (void)
980 G_LOCK (g_utils_global);
983 G_UNLOCK (g_utils_global);
988 /* Return the home directory of the user. If there is a HOME
989 * environment variable, its value is returned, otherwise use some
990 * system-dependent way of finding it out. If no home directory can be
991 * deduced, return NULL.
994 G_CONST_RETURN gchar*
995 g_get_home_dir (void)
997 G_LOCK (g_utils_global);
1000 G_UNLOCK (g_utils_global);
1005 /* Return a directory to be used to store temporary files. This is the
1006 * value of the TMPDIR, TMP or TEMP environment variables (they are
1007 * checked in that order). If none of those exist, use P_tmpdir from
1008 * stdio.h. If that isn't defined, return "/tmp" on POSIXly systems,
1009 * and C:\ on Windows.
1012 G_CONST_RETURN gchar*
1013 g_get_tmp_dir (void)
1015 G_LOCK (g_utils_global);
1018 G_UNLOCK (g_utils_global);
1023 static gchar *g_prgname = NULL;
1026 g_get_prgname (void)
1030 G_LOCK (g_utils_global);
1032 G_UNLOCK (g_utils_global);
1038 g_set_prgname (const gchar *prgname)
1042 G_LOCK (g_utils_global);
1044 g_prgname = g_strdup (prgname);
1046 G_UNLOCK (g_utils_global);
1050 g_direct_hash (gconstpointer v)
1052 return GPOINTER_TO_UINT (v);
1056 g_direct_equal (gconstpointer v1,
1063 g_int_equal (gconstpointer v1,
1066 return *((const gint*) v1) == *((const gint*) v2);
1070 g_int_hash (gconstpointer v)
1072 return *(const gint*) v;
1078 * Get the codeset for the current locale.
1080 * Return value: a newly allocated string containing the name
1081 * of the codeset. This string must be freed with g_free().
1084 g_get_codeset (void)
1087 char *result = nl_langinfo (CODESET);
1088 return g_strdup (result);
1091 /* FIXME: Do something more intelligent based on setlocale (LC_CTYPE, NULL)
1093 return g_strdup ("ISO-8859-1");
1095 return g_strdup_printf ("CP%d", GetACP ());
1102 #include <libintl.h>
1107 #define GLIB_LOCALE_DIR \
1108 g_win32_get_package_installation_subdirectory \
1109 (GETTEXT_PACKAGE, g_strdup_printf ("glib-%d.%d.dll", \
1110 GLIB_MAJOR_VERSION, \
1111 GLIB_MINOR_VERSION), \
1114 #endif /* G_OS_WIN32 */
1116 G_CONST_RETURN gchar *
1117 _glib_gettext (const gchar *str)
1119 gboolean _glib_gettext_initialized = FALSE;
1121 if (!_glib_gettext_initialized)
1123 bindtextdomain(GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
1124 _glib_gettext_initialized = TRUE;
1127 return dgettext (GETTEXT_PACKAGE, str);
1130 #endif /* ENABLE_NLS */