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 gutils'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
67 #ifdef G_PLATFORM_WIN32
68 # define STRICT /* Strict typing, please */
71 # include <lmcons.h> /* For UNLEN */
73 #endif /* G_PLATFORM_WIN32 */
83 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
87 const guint glib_major_version = GLIB_MAJOR_VERSION;
88 const guint glib_minor_version = GLIB_MINOR_VERSION;
89 const guint glib_micro_version = GLIB_MICRO_VERSION;
90 const guint glib_interface_age = GLIB_INTERFACE_AGE;
91 const guint glib_binary_age = GLIB_BINARY_AGE;
93 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
95 g_memmove (gpointer dest, gconstpointer src, gulong len)
97 gchar* destptr = dest;
98 const gchar* srcptr = src;
99 if (src + len < dest || dest + len < src)
101 bcopy (src, dest, len);
104 else if (dest <= src)
107 *(destptr++) = *(srcptr++);
114 *(--destptr) = *(--srcptr);
117 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
120 g_atexit (GVoidFunc func)
123 const gchar *error = NULL;
125 /* keep this in sync with glib.h */
127 #ifdef G_NATIVE_ATEXIT
128 result = ATEXIT (func);
130 error = g_strerror (errno);
131 #elif defined (HAVE_ATEXIT)
132 # ifdef NeXT /* @#%@! NeXTStep */
133 result = !atexit ((void (*)(void)) func);
135 error = g_strerror (errno);
137 result = atexit ((void (*)(void)) func);
139 error = g_strerror (errno);
141 #elif defined (HAVE_ON_EXIT)
142 result = on_exit ((void (*)(int, void *)) func, NULL);
144 error = g_strerror (errno);
147 error = "no implementation";
148 #endif /* G_NATIVE_ATEXIT */
151 g_error ("Could not register atexit() function: %s", error);
154 /* Based on execvp() from GNU Libc.
155 * Some of this code is cut-and-pasted into gspawn.c
159 my_strchrnul (const gchar *str, gchar c)
161 gchar *p = (gchar*)str;
162 while (*p && (*p != c))
170 gchar *inner_find_program_in_path (const gchar *program);
173 g_find_program_in_path (const gchar *program)
175 const gchar *last_dot = strrchr (program, '.');
177 if (last_dot == NULL || strchr (last_dot, '\\') != NULL)
179 const gint program_length = strlen (program);
180 const gchar *pathext = getenv ("PATHEXT");
182 gchar *decorated_program;
186 pathext = ".com;.exe;.bat";
192 p = my_strchrnul (pathext, ';');
194 decorated_program = g_malloc (program_length + (p-pathext) + 1);
195 memcpy (decorated_program, program, program_length);
196 memcpy (decorated_program+program_length, pathext, p-pathext);
197 decorated_program [program_length + (p-pathext)] = '\0';
199 retval = inner_find_program_in_path (decorated_program);
200 g_free (decorated_program);
204 } while (*p++ != '\0');
208 return inner_find_program_in_path (program);
211 #define g_find_program_in_path inner_find_program_in_path
215 * g_find_program_in_path:
216 * @program: a program name
218 * Locates the first executable named @program in the user's path, in the
219 * same way that execvp() would locate it. Returns an allocated string
220 * with the absolute path name, or NULL if the program is not found in
221 * the path. If @program is already an absolute path, returns a copy of
222 * @program if @program exists and is executable, and NULL otherwise.
224 * On Windows, if @program does not have a file type suffix, tries to
225 * append the suffixes in the PATHEXT environment variable (if that
226 * doesn't exists, the suffixes .com, .exe, and .bat) in turn, and
227 * then look for the resulting file name in the same way as
228 * CreateProcess() would. This means first in the directory where the
229 * program was loaded from, then in the current directory, then in the
230 * Windows 32-bit system directory, then in the Windows directory, and
231 * finally in the directories in the PATH environment variable. If
232 * the program is found, the return value contains the full name
233 * including the type suffix.
235 * Return value: absolute path, or NULL
238 g_find_program_in_path (const gchar *program)
240 const gchar *path, *p;
241 gchar *name, *freeme;
248 g_return_val_if_fail (program != NULL, NULL);
250 /* If it is an absolute path, or a relative path including subdirectories,
251 * don't look in PATH.
253 if (g_path_is_absolute (program)
254 || strchr (program, G_DIR_SEPARATOR) != NULL)
256 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE))
257 return g_strdup (program);
262 path = g_getenv ("PATH");
266 /* There is no `PATH' in the environment. The default
267 * search path in GNU libc is the current directory followed by
268 * the path `confstr' returns for `_CS_PATH'.
271 /* In GLib we put . last, for security, and don't use the
272 * unportable confstr(); UNIX98 does not actually specify
273 * what to search if PATH is unset. POSIX may, dunno.
276 path = "/bin:/usr/bin:.";
281 gchar moddir[MAXPATHLEN], sysdir[MAXPATHLEN], windir[MAXPATHLEN];
283 GetModuleFileName (NULL, moddir, sizeof (moddir));
284 tmp = g_path_get_dirname (moddir);
285 GetSystemDirectory (sysdir, sizeof (sysdir));
286 GetWindowsDirectory (windir, sizeof (windir));
287 path_tmp = g_strconcat (tmp, ";.;", sysdir, ";", windir,
288 (path != NULL ? ";" : NULL),
289 (path != NULL ? path : NULL),
296 len = strlen (program) + 1;
297 pathlen = strlen (path);
298 freeme = name = g_malloc (pathlen + len + 1);
300 /* Copy the file name at the top, including '\0' */
301 memcpy (name + pathlen + 1, program, len);
302 name = name + pathlen;
303 /* And add the slash before the filename */
304 *name = G_DIR_SEPARATOR;
312 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
315 /* Two adjacent colons, or a colon at the beginning or the end
316 * of `PATH' means to search the current directory.
320 startp = memcpy (name - (p - path), path, p - path);
322 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE))
325 ret = g_strdup (startp);
333 while (*p++ != '\0');
344 g_snprintf (gchar *str,
352 va_start (args, fmt);
353 retval = g_vsnprintf (str, n, fmt, args);
360 g_vsnprintf (gchar *str,
365 #ifdef HAVE_VSNPRINTF_C99
366 g_return_val_if_fail (n == 0 || str != NULL, 0);
367 g_return_val_if_fail (fmt != NULL, 0);
369 return vsnprintf (str, n, fmt, args);
370 #else /* !HAVE_VSNPRINTF_C99 */
374 g_return_val_if_fail (n == 0 || str != NULL, 0);
375 g_return_val_if_fail (fmt != NULL, 0);
377 printed = g_strdup_vprintf (fmt, args);
378 retval = strlen (printed);
381 strncpy (str, printed, n - 1);
388 #endif /* !HAVE_VSNPRINTF_C99 */
392 g_parse_debug_string (const gchar *string,
393 const GDebugKey *keys,
399 g_return_val_if_fail (string != NULL, 0);
401 if (!g_ascii_strcasecmp (string, "all"))
403 for (i=0; i<nkeys; i++)
404 result |= keys[i].value;
408 const gchar *p = string;
410 gboolean done = FALSE;
421 for (i=0; i<nkeys; i++)
422 if (g_ascii_strncasecmp(keys[i].key, p, q - p) == 0 &&
423 keys[i].key[q - p] == '\0')
424 result |= keys[i].value;
433 G_CONST_RETURN gchar*
434 g_basename (const gchar *file_name)
436 register gchar *base;
438 g_return_val_if_fail (file_name != NULL, NULL);
440 base = strrchr (file_name, G_DIR_SEPARATOR);
445 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
446 return (gchar*) file_name + 2;
447 #endif /* G_OS_WIN32 */
449 return (gchar*) file_name;
453 g_path_get_basename (const gchar *file_name)
455 register gssize base;
456 register gssize last_nonslash;
460 g_return_val_if_fail (file_name != NULL, NULL);
462 if (file_name[0] == '\0')
464 return g_strdup (".");
466 last_nonslash = strlen (file_name) - 1;
468 while (last_nonslash >= 0 && file_name [last_nonslash] == G_DIR_SEPARATOR)
471 if (last_nonslash == -1)
472 /* string only containing slashes */
473 return g_strdup (G_DIR_SEPARATOR_S);
476 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
477 /* string only containing slashes and a drive */
478 return g_strdup (G_DIR_SEPARATOR_S);
479 #endif /* G_OS_WIN32 */
481 base = last_nonslash;
483 while (base >=0 && file_name [base] != G_DIR_SEPARATOR)
487 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
489 #endif /* G_OS_WIN32 */
491 len = last_nonslash - base;
492 retval = g_malloc (len + 1);
493 memcpy (retval, file_name + base + 1, len);
499 g_path_is_absolute (const gchar *file_name)
501 g_return_val_if_fail (file_name != NULL, FALSE);
503 if (file_name[0] == G_DIR_SEPARATOR
505 || file_name[0] == '/'
511 /* Recognize drive letter on native Windows */
512 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && (file_name[2] == G_DIR_SEPARATOR || file_name[2] == '/'))
514 #endif /* G_OS_WIN32 */
519 G_CONST_RETURN gchar*
520 g_path_skip_root (const gchar *file_name)
522 g_return_val_if_fail (file_name != NULL, NULL);
524 #ifdef G_PLATFORM_WIN32
525 /* Skip \\server\share (Win32) or //server/share (Cygwin) */
526 if (file_name[0] == G_DIR_SEPARATOR &&
527 file_name[1] == G_DIR_SEPARATOR &&
532 if ((p = strchr (file_name + 2, G_DIR_SEPARATOR)) > file_name + 2 &&
537 while (file_name[0] && file_name[0] != G_DIR_SEPARATOR)
540 /* Possibly skip a backslash after the share name */
541 if (file_name[0] == G_DIR_SEPARATOR)
544 return (gchar *)file_name;
549 /* Skip initial slashes */
550 if (file_name[0] == G_DIR_SEPARATOR)
552 while (file_name[0] == G_DIR_SEPARATOR)
554 return (gchar *)file_name;
559 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
560 return (gchar *)file_name + 3;
567 g_path_get_dirname (const gchar *file_name)
569 register gchar *base;
572 g_return_val_if_fail (file_name != NULL, NULL);
574 base = strrchr (file_name, G_DIR_SEPARATOR);
576 return g_strdup (".");
577 while (base > file_name && *base == G_DIR_SEPARATOR)
579 len = (guint) 1 + base - file_name;
581 base = g_new (gchar, len + 1);
582 g_memmove (base, file_name, len);
589 g_get_current_dir (void)
591 gchar *buffer = NULL;
593 static gulong max_len = 0;
596 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
598 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
599 * and, if that wasn't bad enough, hangs in doing so.
601 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
602 buffer = g_new (gchar, max_len + 1);
604 dir = getwd (buffer);
605 #else /* !sun || !HAVE_GETCWD */
606 while (max_len < G_MAXULONG / 2)
608 buffer = g_new (gchar, max_len + 1);
610 dir = getcwd (buffer, max_len);
612 if (dir || errno != ERANGE)
618 #endif /* !sun || !HAVE_GETCWD */
620 if (!dir || !*buffer)
622 /* hm, should we g_error() out here?
623 * this can happen if e.g. "./" has mode \0000
625 buffer[0] = G_DIR_SEPARATOR;
629 dir = g_strdup (buffer);
635 G_CONST_RETURN gchar*
636 g_getenv (const gchar *variable)
639 g_return_val_if_fail (variable != NULL, NULL);
641 return getenv (variable);
643 G_LOCK_DEFINE_STATIC (getenv);
649 static GArray *environs = NULL;
654 g_return_val_if_fail (variable != NULL, NULL);
659 environs = g_array_new (FALSE, FALSE, sizeof (struct env_struct));
661 /* First we try to find the envinronment variable inside the already
665 for (i = 0; i < environs->len; i++)
667 env = &g_array_index (environs, struct env_struct, i);
668 if (strcmp (env->key, variable) == 0)
670 g_assert (env->value);
676 /* If not found, we ask the system */
678 system_env = getenv (variable);
685 /* On Windows NT, it is relatively typical that environment variables
686 * contain references to other environment variables. Handle that by
687 * calling ExpandEnvironmentStrings.
690 g_array_set_size (environs, environs->len + 1);
692 env = &g_array_index (environs, struct env_struct, environs->len - 1);
694 /* First check how much space we need */
695 length = ExpandEnvironmentStrings (system_env, dummy, 2);
697 /* Then allocate that much, and actualy do the expansion and insert
698 * the new found pair into our buffer
701 env->value = g_malloc (length);
702 env->key = g_strdup (variable);
704 ExpandEnvironmentStrings (system_env, env->value, length);
712 G_LOCK_DEFINE_STATIC (g_utils_global);
714 static gchar *g_tmp_dir = NULL;
715 static gchar *g_user_name = NULL;
716 static gchar *g_real_name = NULL;
717 static gchar *g_home_dir = NULL;
719 /* HOLDS: g_utils_global_lock */
721 g_get_any_init (void)
725 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
727 g_tmp_dir = g_strdup (g_getenv ("TMP"));
729 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
735 g_tmp_dir = g_strdup (P_tmpdir);
736 k = strlen (g_tmp_dir);
737 if (k > 1 && g_tmp_dir[k - 1] == G_DIR_SEPARATOR)
738 g_tmp_dir[k - 1] = '\0';
745 g_tmp_dir = g_strdup ("/tmp");
746 #else /* G_OS_WIN32 */
747 g_tmp_dir = g_strdup ("C:\\");
748 #endif /* G_OS_WIN32 */
752 /* We check $HOME first for Win32, though it is a last resort for Unix
753 * where we prefer the results of getpwuid().
755 g_home_dir = g_strdup (g_getenv ("HOME"));
757 /* In case HOME is Unix-style (it happens), convert it to
763 while ((p = strchr (g_home_dir, '/')) != NULL)
769 /* USERPROFILE is probably the closest equivalent to $HOME? */
770 if (getenv ("USERPROFILE") != NULL)
771 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
776 /* At least at some time, HOMEDRIVE and HOMEPATH were used
777 * to point to the home directory, I think. But on Windows
778 * 2000 HOMEDRIVE seems to be equal to SYSTEMDRIVE, and
779 * HOMEPATH is its root "\"?
781 if (getenv ("HOMEDRIVE") != NULL && getenv ("HOMEPATH") != NULL)
783 gchar *homedrive, *homepath;
785 homedrive = g_strdup (g_getenv ("HOMEDRIVE"));
786 homepath = g_strdup (g_getenv ("HOMEPATH"));
788 g_home_dir = g_strconcat (homedrive, homepath, NULL);
793 #endif /* G_OS_WIN32 */
797 struct passwd *pw = NULL;
798 gpointer buffer = NULL;
801 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
803 # ifdef _SC_GETPW_R_SIZE_MAX
804 /* This reurns the maximum length */
805 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
809 # else /* _SC_GETPW_R_SIZE_MAX */
811 # endif /* _SC_GETPW_R_SIZE_MAX */
816 buffer = g_malloc (bufsize);
819 # ifdef HAVE_POSIX_GETPWUID_R
820 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
821 error = error < 0 ? errno : error;
822 # else /* HAVE_NONPOSIX_GETPWUID_R */
824 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
825 pw = error == 0 ? &pwd : NULL;
827 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
828 error = pw ? 0 : errno;
830 # endif /* HAVE_NONPOSIX_GETPWUID_R */
834 /* we bail out prematurely if the user id can't be found
835 * (should be pretty rare case actually), or if the buffer
836 * should be sufficiently big and lookups are still not
839 if (error == 0 || error == ENOENT)
841 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
845 if (bufsize > 32 * 1024)
847 g_warning ("getpwuid_r(): failed due to: %s.",
856 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
861 pw = getpwuid (getuid ());
866 g_user_name = g_strdup (pw->pw_name);
867 g_real_name = g_strdup (pw->pw_gecos);
869 g_home_dir = g_strdup (pw->pw_dir);
874 #else /* !HAVE_PWD_H */
879 gchar buffer[UNLEN+1];
881 if (GetUserName ((LPTSTR) buffer, (LPDWORD) &len))
883 g_user_name = g_strdup (buffer);
884 g_real_name = g_strdup (buffer);
887 # endif /* G_OS_WIN32 */
889 #endif /* !HAVE_PWD_H */
892 g_home_dir = g_strdup (g_getenv ("HOME"));
895 /* change '\\' in %HOME% to '/' */
896 g_strdelimit (g_home_dir, "\\",'/');
899 g_user_name = g_strdup ("somebody");
901 g_real_name = g_strdup ("Unknown");
906 for (p = g_real_name; *p; p++)
910 p = g_strdup (g_real_name);
911 g_free (g_real_name);
919 G_CONST_RETURN gchar*
920 g_get_user_name (void)
922 G_LOCK (g_utils_global);
925 G_UNLOCK (g_utils_global);
930 G_CONST_RETURN gchar*
931 g_get_real_name (void)
933 G_LOCK (g_utils_global);
936 G_UNLOCK (g_utils_global);
941 /* Return the home directory of the user. If there is a HOME
942 * environment variable, its value is returned, otherwise use some
943 * system-dependent way of finding it out. If no home directory can be
944 * deduced, return NULL.
947 G_CONST_RETURN gchar*
948 g_get_home_dir (void)
950 G_LOCK (g_utils_global);
953 G_UNLOCK (g_utils_global);
958 /* Return a directory to be used to store temporary files. This is the
959 * value of the TMPDIR, TMP or TEMP environment variables (they are
960 * checked in that order). If none of those exist, use P_tmpdir from
961 * stdio.h. If that isn't defined, return "/tmp" on POSIXly systems,
962 * and C:\ on Windows.
965 G_CONST_RETURN gchar*
968 G_LOCK (g_utils_global);
971 G_UNLOCK (g_utils_global);
976 G_LOCK_DEFINE (g_prgname);
977 static gchar *g_prgname = NULL;
986 G_UNLOCK (g_prgname);
992 g_set_prgname (const gchar *prgname)
996 g_prgname = g_strdup (prgname);
997 G_UNLOCK (g_prgname);
1001 g_direct_hash (gconstpointer v)
1003 return GPOINTER_TO_UINT (v);
1007 g_direct_equal (gconstpointer v1,
1014 g_int_equal (gconstpointer v1,
1017 return *((const gint*) v1) == *((const gint*) v2);
1021 g_int_hash (gconstpointer v)
1023 return *(const gint*) v;
1027 * g_nullify_pointer:
1028 * @nullify_location: the memory address of the pointer.
1030 * Set the pointer at the specified location to %NULL.
1033 g_nullify_pointer (gpointer *nullify_location)
1035 g_return_if_fail (nullify_location != NULL);
1037 *nullify_location = NULL;
1043 * Get the codeset for the current locale.
1045 * Return value: a newly allocated string containing the name
1046 * of the codeset. This string must be freed with g_free().
1049 g_get_codeset (void)
1052 char *result = nl_langinfo (CODESET);
1053 return g_strdup (result);
1055 #ifdef G_PLATFORM_WIN32
1056 return g_strdup_printf ("CP%d", GetACP ());
1058 /* FIXME: Do something more intelligent based on setlocale (LC_CTYPE, NULL)
1060 return g_strdup ("ISO-8859-1");
1067 #include <libintl.h>
1069 #ifdef G_PLATFORM_WIN32
1071 G_WIN32_DLLMAIN_FOR_DLL_NAME (static, dll_name)
1073 static const gchar *
1074 _glib_get_locale_dir (void)
1076 static const gchar *cache = NULL;
1078 cache = g_win32_get_package_installation_subdirectory
1079 (GETTEXT_PACKAGE, dll_name, "lib\\locale");
1084 #undef GLIB_LOCALE_DIR
1085 #define GLIB_LOCALE_DIR _glib_get_locale_dir ()
1087 #endif /* G_PLATFORM_WIN32 */
1089 G_CONST_RETURN gchar *
1090 _glib_gettext (const gchar *str)
1092 static gboolean _glib_gettext_initialized = FALSE;
1094 if (!_glib_gettext_initialized)
1096 bindtextdomain(GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
1097 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
1098 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
1100 _glib_gettext_initialized = TRUE;
1103 return dgettext (GETTEXT_PACKAGE, str);
1106 #endif /* ENABLE_NLS */