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
56 #include "gprintfint.h"
59 #define G_PATH_LENGTH MAXPATHLEN
60 #elif defined (PATH_MAX)
61 #define G_PATH_LENGTH PATH_MAX
62 #elif defined (_PC_PATH_MAX)
63 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
65 #define G_PATH_LENGTH 2048
68 #ifdef G_PLATFORM_WIN32
69 # define STRICT /* Strict typing, please */
72 # include <lmcons.h> /* For UNLEN */
74 #endif /* G_PLATFORM_WIN32 */
84 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
88 const guint glib_major_version = GLIB_MAJOR_VERSION;
89 const guint glib_minor_version = GLIB_MINOR_VERSION;
90 const guint glib_micro_version = GLIB_MICRO_VERSION;
91 const guint glib_interface_age = GLIB_INTERFACE_AGE;
92 const guint glib_binary_age = GLIB_BINARY_AGE;
94 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
96 g_memmove (gpointer dest, gconstpointer src, gulong len)
98 gchar* destptr = dest;
99 const gchar* srcptr = src;
100 if (src + len < dest || dest + len < src)
102 bcopy (src, dest, len);
105 else if (dest <= src)
108 *(destptr++) = *(srcptr++);
115 *(--destptr) = *(--srcptr);
118 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
121 g_atexit (GVoidFunc func)
124 const gchar *error = NULL;
126 /* keep this in sync with glib.h */
128 #ifdef G_NATIVE_ATEXIT
129 result = ATEXIT (func);
131 error = g_strerror (errno);
132 #elif defined (HAVE_ATEXIT)
133 # ifdef NeXT /* @#%@! NeXTStep */
134 result = !atexit ((void (*)(void)) func);
136 error = g_strerror (errno);
138 result = atexit ((void (*)(void)) func);
140 error = g_strerror (errno);
142 #elif defined (HAVE_ON_EXIT)
143 result = on_exit ((void (*)(int, void *)) func, NULL);
145 error = g_strerror (errno);
148 error = "no implementation";
149 #endif /* G_NATIVE_ATEXIT */
152 g_error ("Could not register atexit() function: %s", error);
155 /* Based on execvp() from GNU Libc.
156 * Some of this code is cut-and-pasted into gspawn.c
160 my_strchrnul (const gchar *str, gchar c)
162 gchar *p = (gchar*)str;
163 while (*p && (*p != c))
171 gchar *inner_find_program_in_path (const gchar *program);
174 g_find_program_in_path (const gchar *program)
176 const gchar *last_dot = strrchr (program, '.');
178 if (last_dot == NULL || strchr (last_dot, '\\') != NULL)
180 const gint program_length = strlen (program);
181 const gchar *pathext = getenv ("PATHEXT");
183 gchar *decorated_program;
187 pathext = ".com;.exe;.bat";
193 p = my_strchrnul (pathext, ';');
195 decorated_program = g_malloc (program_length + (p-pathext) + 1);
196 memcpy (decorated_program, program, program_length);
197 memcpy (decorated_program+program_length, pathext, p-pathext);
198 decorated_program [program_length + (p-pathext)] = '\0';
200 retval = inner_find_program_in_path (decorated_program);
201 g_free (decorated_program);
205 } while (*p++ != '\0');
209 return inner_find_program_in_path (program);
212 #define g_find_program_in_path inner_find_program_in_path
216 * g_find_program_in_path:
217 * @program: a program name
219 * Locates the first executable named @program in the user's path, in the
220 * same way that execvp() would locate it. Returns an allocated string
221 * with the absolute path name, or NULL if the program is not found in
222 * the path. If @program is already an absolute path, returns a copy of
223 * @program if @program exists and is executable, and NULL otherwise.
225 * On Windows, if @program does not have a file type suffix, tries to
226 * append the suffixes in the PATHEXT environment variable (if that
227 * doesn't exists, the suffixes .com, .exe, and .bat) in turn, and
228 * then look for the resulting file name in the same way as
229 * CreateProcess() would. This means first in the directory where the
230 * program was loaded from, then in the current directory, then in the
231 * Windows 32-bit system directory, then in the Windows directory, and
232 * finally in the directories in the PATH environment variable. If
233 * the program is found, the return value contains the full name
234 * including the type suffix.
236 * Return value: absolute path, or NULL
239 g_find_program_in_path (const gchar *program)
241 const gchar *path, *p;
242 gchar *name, *freeme;
249 g_return_val_if_fail (program != NULL, NULL);
251 /* If it is an absolute path, or a relative path including subdirectories,
252 * don't look in PATH.
254 if (g_path_is_absolute (program)
255 || strchr (program, G_DIR_SEPARATOR) != NULL)
257 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE))
258 return g_strdup (program);
263 path = g_getenv ("PATH");
267 /* There is no `PATH' in the environment. The default
268 * search path in GNU libc is the current directory followed by
269 * the path `confstr' returns for `_CS_PATH'.
272 /* In GLib we put . last, for security, and don't use the
273 * unportable confstr(); UNIX98 does not actually specify
274 * what to search if PATH is unset. POSIX may, dunno.
277 path = "/bin:/usr/bin:.";
282 gchar moddir[MAXPATHLEN], sysdir[MAXPATHLEN], windir[MAXPATHLEN];
284 GetModuleFileName (NULL, moddir, sizeof (moddir));
285 tmp = g_path_get_dirname (moddir);
286 GetSystemDirectory (sysdir, sizeof (sysdir));
287 GetWindowsDirectory (windir, sizeof (windir));
288 path_tmp = g_strconcat (tmp, ";.;", sysdir, ";", windir,
289 (path != NULL ? ";" : NULL),
290 (path != NULL ? path : NULL),
297 len = strlen (program) + 1;
298 pathlen = strlen (path);
299 freeme = name = g_malloc (pathlen + len + 1);
301 /* Copy the file name at the top, including '\0' */
302 memcpy (name + pathlen + 1, program, len);
303 name = name + pathlen;
304 /* And add the slash before the filename */
305 *name = G_DIR_SEPARATOR;
313 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
316 /* Two adjacent colons, or a colon at the beginning or the end
317 * of `PATH' means to search the current directory.
321 startp = memcpy (name - (p - path), path, p - path);
323 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE))
326 ret = g_strdup (startp);
334 while (*p++ != '\0');
345 g_parse_debug_string (const gchar *string,
346 const GDebugKey *keys,
352 g_return_val_if_fail (string != NULL, 0);
354 if (!g_ascii_strcasecmp (string, "all"))
356 for (i=0; i<nkeys; i++)
357 result |= keys[i].value;
361 const gchar *p = string;
363 gboolean done = FALSE;
374 for (i=0; i<nkeys; i++)
375 if (g_ascii_strncasecmp(keys[i].key, p, q - p) == 0 &&
376 keys[i].key[q - p] == '\0')
377 result |= keys[i].value;
386 G_CONST_RETURN gchar*
387 g_basename (const gchar *file_name)
389 register gchar *base;
391 g_return_val_if_fail (file_name != NULL, NULL);
393 base = strrchr (file_name, G_DIR_SEPARATOR);
398 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
399 return (gchar*) file_name + 2;
400 #endif /* G_OS_WIN32 */
402 return (gchar*) file_name;
406 g_path_get_basename (const gchar *file_name)
408 register gssize base;
409 register gssize last_nonslash;
413 g_return_val_if_fail (file_name != NULL, NULL);
415 if (file_name[0] == '\0')
417 return g_strdup (".");
419 last_nonslash = strlen (file_name) - 1;
421 while (last_nonslash >= 0 && file_name [last_nonslash] == G_DIR_SEPARATOR)
424 if (last_nonslash == -1)
425 /* string only containing slashes */
426 return g_strdup (G_DIR_SEPARATOR_S);
429 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
430 /* string only containing slashes and a drive */
431 return g_strdup (G_DIR_SEPARATOR_S);
432 #endif /* G_OS_WIN32 */
434 base = last_nonslash;
436 while (base >=0 && file_name [base] != G_DIR_SEPARATOR)
440 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
442 #endif /* G_OS_WIN32 */
444 len = last_nonslash - base;
445 retval = g_malloc (len + 1);
446 memcpy (retval, file_name + base + 1, len);
452 g_path_is_absolute (const gchar *file_name)
454 g_return_val_if_fail (file_name != NULL, FALSE);
456 if (file_name[0] == G_DIR_SEPARATOR
458 || file_name[0] == '/'
464 /* Recognize drive letter on native Windows */
465 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && (file_name[2] == G_DIR_SEPARATOR || file_name[2] == '/'))
467 #endif /* G_OS_WIN32 */
472 G_CONST_RETURN gchar*
473 g_path_skip_root (const gchar *file_name)
475 g_return_val_if_fail (file_name != NULL, NULL);
477 #ifdef G_PLATFORM_WIN32
478 /* Skip \\server\share (Win32) or //server/share (Cygwin) */
479 if (file_name[0] == G_DIR_SEPARATOR &&
480 file_name[1] == G_DIR_SEPARATOR &&
485 if ((p = strchr (file_name + 2, G_DIR_SEPARATOR)) > file_name + 2 &&
490 while (file_name[0] && file_name[0] != G_DIR_SEPARATOR)
493 /* Possibly skip a backslash after the share name */
494 if (file_name[0] == G_DIR_SEPARATOR)
497 return (gchar *)file_name;
502 /* Skip initial slashes */
503 if (file_name[0] == G_DIR_SEPARATOR)
505 while (file_name[0] == G_DIR_SEPARATOR)
507 return (gchar *)file_name;
512 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
513 return (gchar *)file_name + 3;
520 g_path_get_dirname (const gchar *file_name)
522 register gchar *base;
525 g_return_val_if_fail (file_name != NULL, NULL);
527 base = strrchr (file_name, G_DIR_SEPARATOR);
529 return g_strdup (".");
530 while (base > file_name && *base == G_DIR_SEPARATOR)
532 len = (guint) 1 + base - file_name;
534 base = g_new (gchar, len + 1);
535 g_memmove (base, file_name, len);
542 g_get_current_dir (void)
544 gchar *buffer = NULL;
546 static gulong max_len = 0;
549 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
551 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
552 * and, if that wasn't bad enough, hangs in doing so.
554 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
555 buffer = g_new (gchar, max_len + 1);
557 dir = getwd (buffer);
558 #else /* !sun || !HAVE_GETCWD */
559 while (max_len < G_MAXULONG / 2)
561 buffer = g_new (gchar, max_len + 1);
563 dir = getcwd (buffer, max_len);
565 if (dir || errno != ERANGE)
571 #endif /* !sun || !HAVE_GETCWD */
573 if (!dir || !*buffer)
575 /* hm, should we g_error() out here?
576 * this can happen if e.g. "./" has mode \0000
578 buffer[0] = G_DIR_SEPARATOR;
582 dir = g_strdup (buffer);
588 G_CONST_RETURN gchar*
589 g_getenv (const gchar *variable)
592 g_return_val_if_fail (variable != NULL, NULL);
594 return getenv (variable);
596 G_LOCK_DEFINE_STATIC (getenv);
602 static GArray *environs = NULL;
607 g_return_val_if_fail (variable != NULL, NULL);
612 environs = g_array_new (FALSE, FALSE, sizeof (struct env_struct));
614 /* First we try to find the envinronment variable inside the already
618 for (i = 0; i < environs->len; i++)
620 env = &g_array_index (environs, struct env_struct, i);
621 if (strcmp (env->key, variable) == 0)
623 g_assert (env->value);
629 /* If not found, we ask the system */
631 system_env = getenv (variable);
638 /* On Windows NT, it is relatively typical that environment variables
639 * contain references to other environment variables. Handle that by
640 * calling ExpandEnvironmentStrings.
643 g_array_set_size (environs, environs->len + 1);
645 env = &g_array_index (environs, struct env_struct, environs->len - 1);
647 /* First check how much space we need */
648 length = ExpandEnvironmentStrings (system_env, dummy, 2);
650 /* Then allocate that much, and actualy do the expansion and insert
651 * the new found pair into our buffer
654 env->value = g_malloc (length);
655 env->key = g_strdup (variable);
657 ExpandEnvironmentStrings (system_env, env->value, length);
665 G_LOCK_DEFINE_STATIC (g_utils_global);
667 static gchar *g_tmp_dir = NULL;
668 static gchar *g_user_name = NULL;
669 static gchar *g_real_name = NULL;
670 static gchar *g_home_dir = NULL;
672 /* HOLDS: g_utils_global_lock */
674 g_get_any_init (void)
678 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
680 g_tmp_dir = g_strdup (g_getenv ("TMP"));
682 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
688 g_tmp_dir = g_strdup (P_tmpdir);
689 k = strlen (g_tmp_dir);
690 if (k > 1 && g_tmp_dir[k - 1] == G_DIR_SEPARATOR)
691 g_tmp_dir[k - 1] = '\0';
698 g_tmp_dir = g_strdup ("/tmp");
699 #else /* G_OS_WIN32 */
700 g_tmp_dir = g_strdup ("C:\\");
701 #endif /* G_OS_WIN32 */
705 /* We check $HOME first for Win32, though it is a last resort for Unix
706 * where we prefer the results of getpwuid().
708 g_home_dir = g_strdup (g_getenv ("HOME"));
710 /* In case HOME is Unix-style (it happens), convert it to
716 while ((p = strchr (g_home_dir, '/')) != NULL)
722 /* USERPROFILE is probably the closest equivalent to $HOME? */
723 if (getenv ("USERPROFILE") != NULL)
724 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
729 /* At least at some time, HOMEDRIVE and HOMEPATH were used
730 * to point to the home directory, I think. But on Windows
731 * 2000 HOMEDRIVE seems to be equal to SYSTEMDRIVE, and
732 * HOMEPATH is its root "\"?
734 if (getenv ("HOMEDRIVE") != NULL && getenv ("HOMEPATH") != NULL)
736 gchar *homedrive, *homepath;
738 homedrive = g_strdup (g_getenv ("HOMEDRIVE"));
739 homepath = g_strdup (g_getenv ("HOMEPATH"));
741 g_home_dir = g_strconcat (homedrive, homepath, NULL);
746 #endif /* G_OS_WIN32 */
750 struct passwd *pw = NULL;
751 gpointer buffer = NULL;
754 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
756 # ifdef _SC_GETPW_R_SIZE_MAX
757 /* This reurns the maximum length */
758 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
762 # else /* _SC_GETPW_R_SIZE_MAX */
764 # endif /* _SC_GETPW_R_SIZE_MAX */
769 buffer = g_malloc (bufsize);
772 # ifdef HAVE_POSIX_GETPWUID_R
773 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
774 error = error < 0 ? errno : error;
775 # else /* HAVE_NONPOSIX_GETPWUID_R */
777 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
778 pw = error == 0 ? &pwd : NULL;
780 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
781 error = pw ? 0 : errno;
783 # endif /* HAVE_NONPOSIX_GETPWUID_R */
787 /* we bail out prematurely if the user id can't be found
788 * (should be pretty rare case actually), or if the buffer
789 * should be sufficiently big and lookups are still not
792 if (error == 0 || error == ENOENT)
794 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
798 if (bufsize > 32 * 1024)
800 g_warning ("getpwuid_r(): failed due to: %s.",
809 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
814 pw = getpwuid (getuid ());
819 g_user_name = g_strdup (pw->pw_name);
820 g_real_name = g_strdup (pw->pw_gecos);
822 g_home_dir = g_strdup (pw->pw_dir);
827 #else /* !HAVE_PWD_H */
832 gchar buffer[UNLEN+1];
834 if (GetUserName ((LPTSTR) buffer, (LPDWORD) &len))
836 g_user_name = g_strdup (buffer);
837 g_real_name = g_strdup (buffer);
840 # endif /* G_OS_WIN32 */
842 #endif /* !HAVE_PWD_H */
845 g_home_dir = g_strdup (g_getenv ("HOME"));
848 /* change '\\' in %HOME% to '/' */
849 g_strdelimit (g_home_dir, "\\",'/');
852 g_user_name = g_strdup ("somebody");
854 g_real_name = g_strdup ("Unknown");
859 for (p = g_real_name; *p; p++)
863 p = g_strdup (g_real_name);
864 g_free (g_real_name);
872 G_CONST_RETURN gchar*
873 g_get_user_name (void)
875 G_LOCK (g_utils_global);
878 G_UNLOCK (g_utils_global);
883 G_CONST_RETURN gchar*
884 g_get_real_name (void)
886 G_LOCK (g_utils_global);
889 G_UNLOCK (g_utils_global);
894 /* Return the home directory of the user. If there is a HOME
895 * environment variable, its value is returned, otherwise use some
896 * system-dependent way of finding it out. If no home directory can be
897 * deduced, return NULL.
900 G_CONST_RETURN gchar*
901 g_get_home_dir (void)
903 G_LOCK (g_utils_global);
906 G_UNLOCK (g_utils_global);
911 /* Return a directory to be used to store temporary files. This is the
912 * value of the TMPDIR, TMP or TEMP environment variables (they are
913 * checked in that order). If none of those exist, use P_tmpdir from
914 * stdio.h. If that isn't defined, return "/tmp" on POSIXly systems,
915 * and C:\ on Windows.
918 G_CONST_RETURN gchar*
921 G_LOCK (g_utils_global);
924 G_UNLOCK (g_utils_global);
929 G_LOCK_DEFINE (g_prgname);
930 static gchar *g_prgname = NULL;
939 G_UNLOCK (g_prgname);
945 g_set_prgname (const gchar *prgname)
949 g_prgname = g_strdup (prgname);
950 G_UNLOCK (g_prgname);
953 G_LOCK_DEFINE (g_application_name);
954 static gchar *g_application_name = NULL;
957 * g_get_application_name:
959 * Gets a human-readable name for the application, as set by
960 * g_set_application_name(). This name should be localized if
961 * possible, and is intended for display to the user. Contrast with
962 * g_get_prgname(), which gets a non-localized name. If
963 * g_set_application_name() has not been called, returns the result of
964 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
967 * Return value: human-readable application name. may return %NULL
969 G_CONST_RETURN gchar*
970 g_get_application_name (void)
974 G_LOCK (g_application_name);
975 retval = g_application_name;
976 G_UNLOCK (g_application_name);
979 return g_get_prgname ();
985 * g_set_application_name:
986 * @application_name: localized name of the application
988 * Sets a human-readable name for the application. This name should be
989 * localized if possible, and is intended for display to the user.
990 * Contrast with g_set_prgname(), which sets a non-localized name.
991 * g_set_prgname() will be called automatically by gtk_init(),
992 * but g_set_application_name() will not.
994 * Note that for thread safety reasons, this function can only
997 * The application name will be used in contexts such as error messages,
998 * or when displaying an application's name in the task list.
1002 g_set_application_name (const gchar *application_name)
1004 gboolean already_set = FALSE;
1006 G_LOCK (g_application_name);
1007 if (g_application_name)
1010 g_application_name = g_strdup (application_name);
1011 G_UNLOCK (g_application_name);
1014 g_warning ("g_set_application() name called multiple times");
1018 g_direct_hash (gconstpointer v)
1020 return GPOINTER_TO_UINT (v);
1024 g_direct_equal (gconstpointer v1,
1031 g_int_equal (gconstpointer v1,
1034 return *((const gint*) v1) == *((const gint*) v2);
1038 g_int_hash (gconstpointer v)
1040 return *(const gint*) v;
1044 * g_nullify_pointer:
1045 * @nullify_location: the memory address of the pointer.
1047 * Set the pointer at the specified location to %NULL.
1050 g_nullify_pointer (gpointer *nullify_location)
1052 g_return_if_fail (nullify_location != NULL);
1054 *nullify_location = NULL;
1060 * Get the codeset for the current locale.
1062 * Return value: a newly allocated string containing the name
1063 * of the codeset. This string must be freed with g_free().
1066 g_get_codeset (void)
1069 char *result = nl_langinfo (CODESET);
1070 return g_strdup (result);
1072 #ifdef G_PLATFORM_WIN32
1073 return g_strdup_printf ("CP%d", GetACP ());
1075 /* FIXME: Do something more intelligent based on setlocale (LC_CTYPE, NULL)
1077 return g_strdup ("ISO-8859-1");
1084 #include <libintl.h>
1086 #ifdef G_PLATFORM_WIN32
1088 G_WIN32_DLLMAIN_FOR_DLL_NAME (static, dll_name)
1090 static const gchar *
1091 _glib_get_locale_dir (void)
1093 static const gchar *cache = NULL;
1095 cache = g_win32_get_package_installation_subdirectory
1096 (GETTEXT_PACKAGE, dll_name, "lib\\locale");
1101 #undef GLIB_LOCALE_DIR
1102 #define GLIB_LOCALE_DIR _glib_get_locale_dir ()
1104 #endif /* G_PLATFORM_WIN32 */
1106 G_CONST_RETURN gchar *
1107 _glib_gettext (const gchar *str)
1109 static gboolean _glib_gettext_initialized = FALSE;
1111 if (!_glib_gettext_initialized)
1113 bindtextdomain(GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
1114 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
1115 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
1117 _glib_gettext_initialized = TRUE;
1120 return dgettext (GETTEXT_PACKAGE, str);
1123 #endif /* ENABLE_NLS */