1 /* -*- mode: c; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup"; -*-
4 * This source code is part of
8 * GROningen MAchine for Chemical Simulations
11 * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
12 * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
13 * Copyright (c) 2001-2004, The GROMACS development team,
14 * check out http://www.gromacs.org for more information.
16 * This program is free software; you can redistribute it and/or
17 * modify it under the terms of the GNU General Public License
18 * as published by the Free Software Foundation; either version 2
19 * of the License, or (at your option) any later version.
21 * If you want to redistribute modifications, please consider that
22 * scientific software is very special. Version control is crucial -
23 * bugs must be traceable. We will be happy to consider code for
24 * inclusion in the official distribution, but derived work must not
25 * be called official GROMACS. Details are found in the README & COPYING
26 * files - if they are missing, get the official version at www.gromacs.org.
28 * To help us fund GROMACS development, we humbly ask that you cite
29 * the papers on the package - you can find them in the top README file.
31 * For more info, check our website at http://www.gromacs.org
34 * GROningen Mixture of Alchemy and Childrens' Stories
43 #include <sys/types.h>
56 #ifdef GMX_NATIVE_WINDOWS
65 #include "gmx_fatal.h"
71 #include "thread_mpi.h"
74 /* Windows file stuff, only necessary for visual studio */
79 /* we keep a linked list of all files opened through pipes (i.e.
80 compressed or .gzipped files. This way we can distinguish between them
81 without having to change the semantics of reading from/writing to files)
83 typedef struct t_pstack {
85 struct t_pstack *prev;
88 static t_pstack *pstack = NULL;
89 static gmx_bool bUnbuffered = FALSE;
92 /* this linked list is an intrinsically globally shared object, so we have
93 to protect it with mutexes */
94 static tMPI_Thread_mutex_t pstack_mutex = TMPI_THREAD_MUTEX_INITIALIZER;
102 void push_ps(FILE *fp)
106 #ifdef GMX_THREAD_MPI
107 tMPI_Thread_mutex_lock(&pstack_mutex);
114 #ifdef GMX_THREAD_MPI
115 tMPI_Thread_mutex_unlock(&pstack_mutex);
120 /* don't use pipes!*/
121 #define popen fah_fopen
122 #define pclose fah_fclose
132 static FILE *popen(const char *nm, const char *mode)
134 gmx_impl("Sorry no pipes...");
139 static int pclose(FILE *fp)
141 gmx_impl("Sorry no pipes...");
148 int ffclose(FILE *fp)
155 #ifdef GMX_THREAD_MPI
156 tMPI_Thread_mutex_lock(&pstack_mutex);
167 else if (ps->fp == fp)
173 pstack = pstack->prev;
178 while ((ps->prev != NULL) && (ps->prev->fp != fp))
182 if ((ps->prev != NULL) && ps->prev->fp == fp)
184 if (ps->prev->fp != NULL)
186 ret = pclose(ps->prev->fp);
189 ps->prev = ps->prev->prev;
200 #ifdef GMX_THREAD_MPI
201 tMPI_Thread_mutex_unlock(&pstack_mutex);
212 void frewind(FILE *fp)
215 #ifdef GMX_THREAD_MPI
216 tMPI_Thread_mutex_lock(&pstack_mutex);
224 fprintf(stderr, "Cannot rewind compressed file!\n");
225 #ifdef GMX_THREAD_MPI
226 tMPI_Thread_mutex_unlock(&pstack_mutex);
233 #ifdef GMX_THREAD_MPI
234 tMPI_Thread_mutex_unlock(&pstack_mutex);
238 int gmx_fseek(FILE *stream, gmx_off_t offset, int whence)
241 return fseeko(stream, offset, whence);
243 #ifdef HAVE__FSEEKI64
244 return _fseeki64(stream, offset, whence);
246 return fseek(stream, offset, whence);
251 gmx_off_t gmx_ftell(FILE *stream)
254 return ftello(stream);
256 #ifdef HAVE__FSEEKI64
257 return _ftelli64(stream);
259 return ftell(stream);
265 gmx_bool is_pipe(FILE *fp)
268 #ifdef GMX_THREAD_MPI
269 tMPI_Thread_mutex_lock(&pstack_mutex);
277 #ifdef GMX_THREAD_MPI
278 tMPI_Thread_mutex_unlock(&pstack_mutex);
284 #ifdef GMX_THREAD_MPI
285 tMPI_Thread_mutex_unlock(&pstack_mutex);
291 static FILE *uncompress(const char *fn, const char *mode)
296 sprintf(buf, "uncompress -c < %s", fn);
297 fprintf(stderr, "Going to execute '%s'\n", buf);
298 if ((fp = popen(buf, mode)) == NULL)
307 static FILE *gunzip(const char *fn, const char *mode)
312 sprintf(buf, "gunzip -c < %s", fn);
313 fprintf(stderr, "Going to execute '%s'\n", buf);
314 if ((fp = popen(buf, mode)) == NULL)
323 gmx_bool gmx_fexist(const char *fname)
331 test = fopen(fname, "r");
334 /*Windows doesn't allow fopen of directory - so we need to check this seperately */
335 #ifdef GMX_NATIVE_WINDOWS
336 DWORD attr = GetFileAttributes(fname);
337 return (attr != INVALID_FILE_ATTRIBUTES) && (attr & FILE_ATTRIBUTE_DIRECTORY);
349 static gmx_bool gmx_is_file(const char *fname)
357 test = fopen(fname, "r");
365 /*Windows doesn't allow fopen of directory - so we don't need to check this seperately */
366 #if (!((defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64) && !defined __CYGWIN__ && !defined __CYGWIN32__))
370 status = stat (fname, &st_buf);
371 if (status != 0 || !S_ISREG(st_buf.st_mode))
382 gmx_bool gmx_fexist_master(const char *fname, t_commrec *cr)
388 bExist = gmx_fexist(fname);
392 gmx_bcast(sizeof(bExist), &bExist, cr);
397 gmx_bool gmx_eof(FILE *fp)
408 if ((beof = fread(data, 1, 1, fp)) == 1)
410 gmx_fseek(fp, -1, SEEK_CUR);
416 static char *backup_fn(const char *file, int count_max)
418 /* Use a reasonably low value for countmax; we might
419 * generate 4-5 files in each round, and we dont
420 * want to hit directory limits of 1024 or 2048 files.
424 char *directory, *fn;
429 count_max = COUNTMAX;
432 smalloc(buf, GMX_PATH_MAX);
434 for (i = strlen(file)-1; ((i > 0) && (file[i] != DIR_SEPARATOR)); i--)
438 /* Must check whether i > 0, i.e. whether there is a directory
439 * in the file name. In that case we overwrite the / sign with
440 * a '\0' to end the directory string .
444 directory = gmx_strdup(file);
446 fn = gmx_strdup(file+i+1);
450 directory = gmx_strdup(".");
451 fn = gmx_strdup(file);
455 sprintf(buf, "%s/#%s.%d#", directory, fn, count);
458 while ((count <= count_max) && gmx_fexist(buf));
460 /* Arbitrarily bail out */
461 if (count > count_max)
463 gmx_fatal(FARGS, "Won't make more than %d backups of %s for you.\n"
464 "The env.var. GMX_MAXBACKUP controls this maximum, -1 disables backups.",
474 gmx_bool make_backup(const char * name)
481 return FALSE; /* skip making backups */
484 if (gmx_fexist(name))
486 env = getenv("GMX_MAXBACKUP");
489 count_max = strtol(env, NULL, 10);
492 /* Do not make backups and possibly overwrite old files */
498 /* Use the default maximum */
501 backup = backup_fn(name, count_max);
502 if (rename(name, backup) == 0)
504 fprintf(stderr, "\nBack Off! I just backed up %s to %s\n",
509 fprintf(stderr, "Sorry couldn't backup %s to %s\n", name, backup);
518 FILE *ffopen(const char *file, const char *mode)
521 return fopen(file, mode);
524 char buf[256], *bufsize = 0, *ptr;
539 bRead = (mode[0] == 'r' && mode[1] != '+');
541 if (!bRead || gmx_fexist(buf))
543 if ((ff = fopen(buf, mode)) == NULL)
548 /* Check whether we should be using buffering (default) or not
551 if (bUnbuffered || ((bufsize = getenv("LOG_BUFS")) != NULL))
553 /* Check whether to use completely unbuffered */
560 bs = strtol(bufsize, NULL, 10);
569 if (setvbuf(ff, ptr, _IOFBF, bs) != 0)
571 gmx_file("Buffering File");
579 sprintf(buf, "%s.Z", file);
582 ff = uncompress(buf, mode);
586 sprintf(buf, "%s.gz", file);
589 ff = gunzip(buf, mode);
601 /* Our own implementation of dirent-like functionality to scan directories. */
606 #elif (defined GMX_NATIVE_WINDOWS)
607 intptr_t windows_handle;
608 struct _finddata_t finddata;
617 gmx_directory_open(gmx_directory_t *p_gmxdir, const char *dirname)
619 struct gmx_directory * gmxdir;
627 if ( (gmxdir->dirent_handle = opendir(dirname)) != NULL)
637 #elif (defined GMX_NATIVE_WINDOWS)
639 if (dirname != NULL && strlen(dirname) > 0)
645 len = strlen(dirname);
646 snew(tmpname, len+3);
648 strncpy(tmpname, dirname, len+1);
650 /* Remove possible trailing directory separator */
651 if (tmpname[len] == '/' || tmpname[len] == '\\')
657 strcat(tmpname, "/*");
660 if ( (gmxdir->windows_handle = _findfirst(tmpname, &gmxdir->finddata)) > 0L)
684 "Source compiled without POSIX dirent or windows support - cannot scan directories.\n"
685 "In the very unlikely event this is not a compile-time mistake you could consider\n"
686 "implementing support for your platform in futil.c, but contact the developers\n"
687 "to make sure it's really necessary!\n");
695 gmx_directory_nextfile(gmx_directory_t gmxdir, char *name, int maxlength_name)
701 struct dirent * direntp_large;
705 if (gmxdir != NULL && gmxdir->dirent_handle != NULL)
707 /* On some platforms no space is present for d_name in dirent.
708 * Since d_name is guaranteed to be the last entry, allocating
709 * extra space for dirent will allow more size for d_name.
710 * GMX_MAX_PATH should always be >= the max possible d_name.
712 smalloc(direntp_large, sizeof(*direntp_large) + GMX_PATH_MAX);
713 rc = readdir_r(gmxdir->dirent_handle, direntp_large, &p);
715 if (p != NULL && rc == 0)
717 strncpy(name, direntp_large->d_name, maxlength_name);
724 sfree(direntp_large);
732 #elif (defined GMX_NATIVE_WINDOWS)
736 if (gmxdir->windows_handle <= 0)
742 else if (gmxdir->first == 1)
744 strncpy(name, gmxdir->finddata.name, maxlength_name);
750 if (_findnext(gmxdir->windows_handle, &gmxdir->finddata) == 0)
752 strncpy(name, gmxdir->finddata.name, maxlength_name);
765 "Source compiled without POSIX dirent or windows support - cannot scan directories.\n");
773 gmx_directory_close(gmx_directory_t gmxdir)
777 rc = (gmxdir != NULL) ? closedir(gmxdir->dirent_handle) : EINVAL;
778 #elif (defined GMX_NATIVE_WINDOWS)
779 rc = (gmxdir != NULL) ? _findclose(gmxdir->windows_handle) : EINVAL;
782 "Source compiled without POSIX dirent or windows support - cannot scan directories.\n");
791 static gmx_bool search_subdirs(const char *parent, char *libdir)
796 /* Search a few common subdirectory names for the gromacs library dir */
797 sprintf(libdir, "%s%cshare%ctop%cgurgle.dat", parent,
798 DIR_SEPARATOR, DIR_SEPARATOR, DIR_SEPARATOR);
799 found = gmx_fexist(libdir);
802 sprintf(libdir, "%s%c%s%cgurgle.dat", parent,
803 DIR_SEPARATOR, GMXLIB_SEARCH_DIR, DIR_SEPARATOR);
804 found = gmx_fexist(libdir);
807 /* Remove the gurgle.dat part from libdir if we found something */
810 ptr = strrchr(libdir, DIR_SEPARATOR); /* slash or backslash always present, no check necessary */
817 /* Check if the program name begins with "/" on unix/cygwin, or
818 * with "\" or "X:\" on windows. If not, the program name
819 * is relative to the current directory.
821 static gmx_bool filename_is_absolute(char *name)
823 #ifdef GMX_NATIVE_WINDOWS
824 return ((name[0] == DIR_SEPARATOR) || ((strlen(name) > 3) && strncmp(name+1, ":\\", 2)) == 0);
826 return (name[0] == DIR_SEPARATOR);
830 void get_libdir(char *libdir)
832 #define GMX_BINNAME_MAX 512
833 char bin_name[GMX_BINNAME_MAX];
834 char buf[GMX_BINNAME_MAX];
835 char full_path[GMX_PATH_MAX+GMX_BINNAME_MAX];
836 char system_path[GMX_PATH_MAX];
838 gmx_bool found = FALSE;
841 if (Program() != NULL)
844 /* First - detect binary name */
845 if (strlen(Program()) >= GMX_BINNAME_MAX)
847 gmx_fatal(FARGS, "The name of the binary is longer than the allowed buffer size (%d):\n'%s'", GMX_BINNAME_MAX, Program());
849 strncpy(bin_name, Program(), GMX_BINNAME_MAX-1);
851 /* On windows & cygwin we need to add the .exe extension
852 * too, or we wont be able to detect that the file exists
854 #if (defined GMX_NATIVE_WINDOWS || defined GMX_CYGWIN)
855 if (strlen(bin_name) < 3 || gmx_strncasecmp(bin_name+strlen(bin_name)-4, ".exe", 4))
857 strcat(bin_name, ".exe");
861 /* Only do the smart search part if we got a real name */
862 if (NULL != bin_name && strncmp(bin_name, "GROMACS", GMX_BINNAME_MAX))
865 if (!strchr(bin_name, DIR_SEPARATOR))
867 /* No slash or backslash in name means it must be in the path - search it! */
868 /* Add the local dir since it is not in the path on windows */
869 gmx_getcwd(system_path, sizeof(system_path));
870 sprintf(full_path, "%s%c%s", system_path, DIR_SEPARATOR, bin_name);
871 found = gmx_is_file(full_path);
872 if (!found && (s = getenv("PATH")) != NULL)
876 dupped = gmx_strdup(s);
878 while (!found && (dir = gmx_strsep(&s, PATH_SEPARATOR)) != NULL)
880 sprintf(full_path, "%s%c%s", dir, DIR_SEPARATOR, bin_name);
881 found = gmx_is_file(full_path);
887 strcpy(libdir, GMXLIB_FALLBACK);
891 else if (!filename_is_absolute(bin_name))
893 /* name contains directory separators, but
894 * it does not start at the root, i.e.
895 * name is relative to the current dir
897 gmx_getcwd(buf, sizeof(buf));
898 sprintf(full_path, "%s%c%s", buf, DIR_SEPARATOR, bin_name);
902 strncpy(full_path, bin_name, GMX_PATH_MAX);
905 /* Now we should have a full path and name in full_path,
906 * but on unix it might be a link, or a link to a link to a link..
908 #ifndef GMX_NATIVE_WINDOWS
909 while ( (i = readlink(full_path, buf, sizeof(buf)-1)) > 0)
912 /* If it doesn't start with "/" it is relative */
913 if (buf[0] != DIR_SEPARATOR)
915 strncpy(strrchr(full_path, DIR_SEPARATOR)+1, buf, GMX_PATH_MAX);
919 strncpy(full_path, buf, GMX_PATH_MAX);
924 /* If running directly from the build tree, try to use the source
927 #if (defined CMAKE_SOURCE_DIR && defined CMAKE_BINARY_DIR)
928 if (strncmp(full_path, CMAKE_BINARY_DIR, strlen(CMAKE_BINARY_DIR)) == 0)
930 if (search_subdirs(CMAKE_SOURCE_DIR, libdir))
937 /* Remove the executable name - it always contains at least one slash */
938 *(strrchr(full_path, DIR_SEPARATOR)+1) = '\0';
939 /* Now we have the full path to the gromacs executable.
940 * Use it to find the library dir.
943 while (!found && ( (ptr = strrchr(full_path, DIR_SEPARATOR)) != NULL ) )
946 found = search_subdirs(full_path, libdir);
950 /* End of smart searching. If we didn't find it in our parent tree,
951 * or if the program name wasn't set, at least try some standard
952 * locations before giving up, in case we are running from e.g.
953 * a users home directory. This only works on unix or cygwin...
955 #ifndef GMX_NATIVE_WINDOWS
958 found = search_subdirs("/usr/local", libdir);
962 found = search_subdirs("/usr", libdir);
966 found = search_subdirs("/opt", libdir);
971 strcpy(libdir, GMXLIB_FALLBACK);
976 char *low_gmxlibfn(const char *file, gmx_bool bAddCWD, gmx_bool bFatal)
981 char libpath[GMX_PATH_MAX];
982 gmx_bool env_is_set = FALSE;
983 char *s, tmppath[GMX_PATH_MAX];
985 /* GMXLIB can be a path now */
986 lib = getenv("GMXLIB");
990 strncpy(libpath, lib, GMX_PATH_MAX);
998 if (bAddCWD && gmx_fexist(file))
1000 ret = gmx_strdup(file);
1004 strncpy(tmppath, libpath, GMX_PATH_MAX);
1006 while (ret == NULL && (dir = gmx_strsep(&s, PATH_SEPARATOR)) != NULL)
1008 sprintf(buf, "%s%c%s", dir, DIR_SEPARATOR, file);
1009 if (gmx_fexist(buf))
1011 ret = gmx_strdup(buf);
1014 if (ret == NULL && bFatal)
1019 "Library file %s not found %sin your GMXLIB path.",
1020 file, bAddCWD ? "in current dir nor " : "");
1025 "Library file %s not found %sin default directories.\n"
1026 "(You can set the directories to search with the GMXLIB path variable)",
1027 file, bAddCWD ? "in current dir nor " : "");
1039 FILE *low_libopen(const char *file, gmx_bool bFatal)
1044 fn = low_gmxlibfn(file, TRUE, bFatal);
1054 fprintf(debug, "Opening library file %s\n", fn);
1056 ff = fopen(fn, "r");
1063 char *gmxlibfn(const char *file)
1065 return low_gmxlibfn(file, TRUE, TRUE);
1068 FILE *libopen(const char *file)
1070 return low_libopen(file, TRUE);
1073 void gmx_tmpnam(char *buf)
1077 if ((len = strlen(buf)) < 7)
1079 gmx_fatal(FARGS, "Buf passed to gmx_tmpnam must be at least 7 bytes long");
1081 for (i = len-6; (i < len); i++)
1085 /* mktemp is dangerous and we should use mkstemp instead, but
1086 * since windows doesnt support it we have to separate the cases.
1087 * 20090307: mktemp deprecated, use iso c++ _mktemp instead.
1089 #ifdef GMX_NATIVE_WINDOWS
1097 gmx_fatal(FARGS, "Invalid template %s for mkstemp", buf);
1100 gmx_fatal(FARGS, "mkstemp created existing file", buf);
1103 gmx_fatal(FARGS, "Permission denied for opening %s", buf);
1110 /* name in Buf should now be OK */
1113 int gmx_truncatefile(char *path, gmx_off_t length)
1116 /* Microsoft visual studio does not have "truncate" */
1118 LARGE_INTEGER win_length;
1120 win_length.QuadPart = length;
1122 fh = CreateFile(path, GENERIC_READ | GENERIC_WRITE, 0, NULL,
1123 OPEN_EXISTING, 0, NULL);
1124 SetFilePointerEx(fh, win_length, NULL, FILE_BEGIN);
1130 return truncate(path, length);
1135 int gmx_file_rename(const char *oldname, const char *newname)
1137 #ifndef GMX_NATIVE_WINDOWS
1138 /* under unix, rename() is atomic (at least, it should be). */
1139 return rename(oldname, newname);
1141 if (MoveFileEx(oldname, newname,
1142 MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH))
1153 int gmx_file_copy(const char *oldname, const char *newname, gmx_bool copy_if_empty)
1155 /* the full copy buffer size: */
1156 #define FILECOPY_BUFSIZE (1<<16)
1161 snew(buf, FILECOPY_BUFSIZE);
1163 in = fopen(oldname, "rb");
1169 /* If we don't copy when empty, we postpone opening the file
1170 until we're actually ready to write. */
1173 out = fopen(newname, "wb");
1184 nread = fread(buf, sizeof(char), FILECOPY_BUFSIZE, in);
1190 /* so this is where we open when copy_if_empty is false:
1191 here we know we read something. */
1192 out = fopen(newname, "wb");
1198 ret = fwrite(buf, sizeof(char), nread, out);
1224 #undef FILECOPY_BUFSIZE
1228 int gmx_fsync(FILE *fp)
1233 /* the fahcore defines its own os-independent fsync */
1235 #else /* GMX_FAHCORE */
1239 /* get the file number */
1240 #if defined(HAVE_FILENO)
1242 #elif defined(HAVE__FILENO)
1246 /* do the actual fsync */
1249 #if (defined(HAVE_FSYNC))
1251 #elif (defined(HAVE__COMMIT))
1256 #endif /* GMX_FAHCORE */
1258 /* We check for these error codes this way because POSIX requires them
1259 to be defined, and using anything other than macros is unlikely: */
1261 /* we don't want to report an error just because fsync() caught a signal.
1262 For our purposes, we can just ignore this. */
1263 if (rc && errno == EINTR)
1269 /* we don't want to report an error just because we tried to fsync()
1270 stdout, a socket or a pipe. */
1271 if (rc && errno == EINVAL)
1279 void gmx_chdir(const char *directory)
1281 #ifdef GMX_NATIVE_WINDOWS
1282 int rc = _chdir(directory);
1284 int rc = chdir(directory);
1288 gmx_fatal(FARGS, "Cannot change directory to '%s'. Reason: %s",
1289 directory, strerror(errno));
1293 void gmx_getcwd(char *buffer, size_t size)
1295 #ifdef GMX_NATIVE_WINDOWS
1296 char *pdum = _getcwd(buffer, size);
1298 char *pdum = getcwd(buffer, size);
1302 gmx_fatal(FARGS, "Cannot get working directory. Reason: %s",