2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5 * Copyright (c) 2001-2004, The GROMACS development team,
6 * Copyright (c) 2013, by the GROMACS development team, led by
7 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8 * and including many others, as listed in the AUTHORS file in the
9 * top-level source directory and at http://www.gromacs.org.
11 * GROMACS is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public License
13 * as published by the Free Software Foundation; either version 2.1
14 * of the License, or (at your option) any later version.
16 * GROMACS is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with GROMACS; if not, see
23 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 * If you want to redistribute modifications to GROMACS, please
27 * consider that scientific software is very special. Version
28 * control is crucial - bugs must be traceable. We will be happy to
29 * consider code for inclusion in the official distribution, but
30 * derived work must not be called official GROMACS. Details are found
31 * in the README & COPYING files - if they are missing, get the
32 * official version at http://www.gromacs.org.
34 * To help us fund GROMACS development, we humbly ask that you cite
35 * the research papers on the package. Check out http://www.gromacs.org.
44 #include <sys/types.h>
57 #ifdef GMX_NATIVE_WINDOWS
66 #include "gmx_fatal.h"
72 #include "thread_mpi.h"
75 /* Windows file stuff, only necessary for visual studio */
80 /* we keep a linked list of all files opened through pipes (i.e.
81 compressed or .gzipped files. This way we can distinguish between them
82 without having to change the semantics of reading from/writing to files)
84 typedef struct t_pstack {
86 struct t_pstack *prev;
89 static t_pstack *pstack = NULL;
90 static gmx_bool bUnbuffered = FALSE;
93 /* this linked list is an intrinsically globally shared object, so we have
94 to protect it with mutexes */
95 static tMPI_Thread_mutex_t pstack_mutex = TMPI_THREAD_MUTEX_INITIALIZER;
103 void push_ps(FILE *fp)
107 #ifdef GMX_THREAD_MPI
108 tMPI_Thread_mutex_lock(&pstack_mutex);
115 #ifdef GMX_THREAD_MPI
116 tMPI_Thread_mutex_unlock(&pstack_mutex);
121 /* don't use pipes!*/
122 #define popen fah_fopen
123 #define pclose fah_fclose
133 static FILE *popen(const char *nm, const char *mode)
135 gmx_impl("Sorry no pipes...");
140 static int pclose(FILE *fp)
142 gmx_impl("Sorry no pipes...");
149 int ffclose(FILE *fp)
156 #ifdef GMX_THREAD_MPI
157 tMPI_Thread_mutex_lock(&pstack_mutex);
168 else if (ps->fp == fp)
174 pstack = pstack->prev;
179 while ((ps->prev != NULL) && (ps->prev->fp != fp))
183 if ((ps->prev != NULL) && ps->prev->fp == fp)
185 if (ps->prev->fp != NULL)
187 ret = pclose(ps->prev->fp);
190 ps->prev = ps->prev->prev;
201 #ifdef GMX_THREAD_MPI
202 tMPI_Thread_mutex_unlock(&pstack_mutex);
213 void frewind(FILE *fp)
216 #ifdef GMX_THREAD_MPI
217 tMPI_Thread_mutex_lock(&pstack_mutex);
225 fprintf(stderr, "Cannot rewind compressed file!\n");
226 #ifdef GMX_THREAD_MPI
227 tMPI_Thread_mutex_unlock(&pstack_mutex);
234 #ifdef GMX_THREAD_MPI
235 tMPI_Thread_mutex_unlock(&pstack_mutex);
239 int gmx_fseek(FILE *stream, gmx_off_t offset, int whence)
242 return fseeko(stream, offset, whence);
244 #ifdef HAVE__FSEEKI64
245 return _fseeki64(stream, offset, whence);
247 return fseek(stream, offset, whence);
252 gmx_off_t gmx_ftell(FILE *stream)
255 return ftello(stream);
257 #ifdef HAVE__FSEEKI64
258 return _ftelli64(stream);
260 return ftell(stream);
266 gmx_bool is_pipe(FILE *fp)
269 #ifdef GMX_THREAD_MPI
270 tMPI_Thread_mutex_lock(&pstack_mutex);
278 #ifdef GMX_THREAD_MPI
279 tMPI_Thread_mutex_unlock(&pstack_mutex);
285 #ifdef GMX_THREAD_MPI
286 tMPI_Thread_mutex_unlock(&pstack_mutex);
292 static FILE *uncompress(const char *fn, const char *mode)
297 sprintf(buf, "uncompress -c < %s", fn);
298 fprintf(stderr, "Going to execute '%s'\n", buf);
299 if ((fp = popen(buf, mode)) == NULL)
308 static FILE *gunzip(const char *fn, const char *mode)
313 sprintf(buf, "gunzip -c < %s", fn);
314 fprintf(stderr, "Going to execute '%s'\n", buf);
315 if ((fp = popen(buf, mode)) == NULL)
324 gmx_bool gmx_fexist(const char *fname)
332 test = fopen(fname, "r");
335 /*Windows doesn't allow fopen of directory - so we need to check this seperately */
336 #ifdef GMX_NATIVE_WINDOWS
337 DWORD attr = GetFileAttributes(fname);
338 return (attr != INVALID_FILE_ATTRIBUTES) && (attr & FILE_ATTRIBUTE_DIRECTORY);
350 static gmx_bool gmx_is_file(const char *fname)
358 test = fopen(fname, "r");
366 /*Windows doesn't allow fopen of directory - so we don't need to check this seperately */
367 #if (!((defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64) && !defined __CYGWIN__ && !defined __CYGWIN32__))
371 status = stat (fname, &st_buf);
372 if (status != 0 || !S_ISREG(st_buf.st_mode))
383 gmx_bool gmx_fexist_master(const char *fname, t_commrec *cr)
389 bExist = gmx_fexist(fname);
393 gmx_bcast(sizeof(bExist), &bExist, cr);
398 gmx_bool gmx_eof(FILE *fp)
409 if ((beof = fread(data, 1, 1, fp)) == 1)
411 gmx_fseek(fp, -1, SEEK_CUR);
417 static char *backup_fn(const char *file, int count_max)
419 /* Use a reasonably low value for countmax; we might
420 * generate 4-5 files in each round, and we dont
421 * want to hit directory limits of 1024 or 2048 files.
425 char *directory, *fn;
430 count_max = COUNTMAX;
433 smalloc(buf, GMX_PATH_MAX);
435 for (i = strlen(file)-1; ((i > 0) && (file[i] != DIR_SEPARATOR)); i--)
439 /* Must check whether i > 0, i.e. whether there is a directory
440 * in the file name. In that case we overwrite the / sign with
441 * a '\0' to end the directory string .
445 directory = gmx_strdup(file);
447 fn = gmx_strdup(file+i+1);
451 directory = gmx_strdup(".");
452 fn = gmx_strdup(file);
456 sprintf(buf, "%s/#%s.%d#", directory, fn, count);
459 while ((count <= count_max) && gmx_fexist(buf));
461 /* Arbitrarily bail out */
462 if (count > count_max)
464 gmx_fatal(FARGS, "Won't make more than %d backups of %s for you.\n"
465 "The env.var. GMX_MAXBACKUP controls this maximum, -1 disables backups.",
475 gmx_bool make_backup(const char * name)
482 return FALSE; /* skip making backups */
485 if (gmx_fexist(name))
487 env = getenv("GMX_MAXBACKUP");
490 count_max = strtol(env, NULL, 10);
493 /* Do not make backups and possibly overwrite old files */
499 /* Use the default maximum */
502 backup = backup_fn(name, count_max);
503 if (rename(name, backup) == 0)
505 fprintf(stderr, "\nBack Off! I just backed up %s to %s\n",
510 fprintf(stderr, "Sorry couldn't backup %s to %s\n", name, backup);
519 FILE *ffopen(const char *file, const char *mode)
522 return fopen(file, mode);
525 char buf[256], *bufsize = 0, *ptr;
540 bRead = (mode[0] == 'r' && mode[1] != '+');
542 if (!bRead || gmx_fexist(buf))
544 if ((ff = fopen(buf, mode)) == NULL)
549 /* Check whether we should be using buffering (default) or not
552 if (bUnbuffered || ((bufsize = getenv("LOG_BUFS")) != NULL))
554 /* Check whether to use completely unbuffered */
561 bs = strtol(bufsize, NULL, 10);
570 if (setvbuf(ff, ptr, _IOFBF, bs) != 0)
572 gmx_file("Buffering File");
580 sprintf(buf, "%s.Z", file);
583 ff = uncompress(buf, mode);
587 sprintf(buf, "%s.gz", file);
590 ff = gunzip(buf, mode);
602 /* Our own implementation of dirent-like functionality to scan directories. */
607 #elif (defined GMX_NATIVE_WINDOWS)
608 intptr_t windows_handle;
609 struct _finddata_t finddata;
618 gmx_directory_open(gmx_directory_t *p_gmxdir, const char *dirname)
620 struct gmx_directory * gmxdir;
628 if ( (gmxdir->dirent_handle = opendir(dirname)) != NULL)
638 #elif (defined GMX_NATIVE_WINDOWS)
640 if (dirname != NULL && strlen(dirname) > 0)
646 len = strlen(dirname);
647 snew(tmpname, len+3);
649 strncpy(tmpname, dirname, len+1);
651 /* Remove possible trailing directory separator */
652 if (tmpname[len] == '/' || tmpname[len] == '\\')
658 strcat(tmpname, "/*");
661 if ( (gmxdir->windows_handle = _findfirst(tmpname, &gmxdir->finddata)) > 0L)
685 "Source compiled without POSIX dirent or windows support - cannot scan directories.\n"
686 "In the very unlikely event this is not a compile-time mistake you could consider\n"
687 "implementing support for your platform in futil.c, but contact the developers\n"
688 "to make sure it's really necessary!\n");
696 gmx_directory_nextfile(gmx_directory_t gmxdir, char *name, int maxlength_name)
702 struct dirent * direntp_large;
706 if (gmxdir != NULL && gmxdir->dirent_handle != NULL)
708 /* On some platforms no space is present for d_name in dirent.
709 * Since d_name is guaranteed to be the last entry, allocating
710 * extra space for dirent will allow more size for d_name.
711 * GMX_MAX_PATH should always be >= the max possible d_name.
713 smalloc(direntp_large, sizeof(*direntp_large) + GMX_PATH_MAX);
714 rc = readdir_r(gmxdir->dirent_handle, direntp_large, &p);
716 if (p != NULL && rc == 0)
718 strncpy(name, direntp_large->d_name, maxlength_name);
725 sfree(direntp_large);
733 #elif (defined GMX_NATIVE_WINDOWS)
737 if (gmxdir->windows_handle <= 0)
743 else if (gmxdir->first == 1)
745 strncpy(name, gmxdir->finddata.name, maxlength_name);
751 if (_findnext(gmxdir->windows_handle, &gmxdir->finddata) == 0)
753 strncpy(name, gmxdir->finddata.name, maxlength_name);
766 "Source compiled without POSIX dirent or windows support - cannot scan directories.\n");
774 gmx_directory_close(gmx_directory_t gmxdir)
778 rc = (gmxdir != NULL) ? closedir(gmxdir->dirent_handle) : EINVAL;
779 #elif (defined GMX_NATIVE_WINDOWS)
780 rc = (gmxdir != NULL) ? _findclose(gmxdir->windows_handle) : EINVAL;
783 "Source compiled without POSIX dirent or windows support - cannot scan directories.\n");
792 static gmx_bool search_subdirs(const char *parent, char *libdir)
797 /* Search a few common subdirectory names for the gromacs library dir */
798 sprintf(libdir, "%s%cshare%ctop%cgurgle.dat", parent,
799 DIR_SEPARATOR, DIR_SEPARATOR, DIR_SEPARATOR);
800 found = gmx_fexist(libdir);
803 sprintf(libdir, "%s%c%s%cgurgle.dat", parent,
804 DIR_SEPARATOR, GMXLIB_SEARCH_DIR, DIR_SEPARATOR);
805 found = gmx_fexist(libdir);
808 /* Remove the gurgle.dat part from libdir if we found something */
811 ptr = strrchr(libdir, DIR_SEPARATOR); /* slash or backslash always present, no check necessary */
818 /* Check if the program name begins with "/" on unix/cygwin, or
819 * with "\" or "X:\" on windows. If not, the program name
820 * is relative to the current directory.
822 static gmx_bool filename_is_absolute(char *name)
824 #ifdef GMX_NATIVE_WINDOWS
825 return ((name[0] == DIR_SEPARATOR) || ((strlen(name) > 3) && strncmp(name+1, ":\\", 2)) == 0);
827 return (name[0] == DIR_SEPARATOR);
831 void get_libdir(char *libdir)
833 #define GMX_BINNAME_MAX 512
834 char bin_name[GMX_BINNAME_MAX];
835 char buf[GMX_BINNAME_MAX];
836 char full_path[GMX_PATH_MAX+GMX_BINNAME_MAX];
837 char system_path[GMX_PATH_MAX];
839 gmx_bool found = FALSE;
842 if (Program() != NULL)
845 /* First - detect binary name */
846 if (strlen(Program()) >= GMX_BINNAME_MAX)
848 gmx_fatal(FARGS, "The name of the binary is longer than the allowed buffer size (%d):\n'%s'", GMX_BINNAME_MAX, Program());
850 strncpy(bin_name, Program(), GMX_BINNAME_MAX-1);
852 /* On windows & cygwin we need to add the .exe extension
853 * too, or we wont be able to detect that the file exists
855 #if (defined GMX_NATIVE_WINDOWS || defined GMX_CYGWIN)
856 if (strlen(bin_name) < 3 || gmx_strncasecmp(bin_name+strlen(bin_name)-4, ".exe", 4))
858 strcat(bin_name, ".exe");
862 /* Only do the smart search part if we got a real name */
863 if (NULL != bin_name && strncmp(bin_name, "GROMACS", GMX_BINNAME_MAX))
866 if (!strchr(bin_name, DIR_SEPARATOR))
868 /* No slash or backslash in name means it must be in the path - search it! */
869 /* Add the local dir since it is not in the path on windows */
870 gmx_getcwd(system_path, sizeof(system_path));
871 sprintf(full_path, "%s%c%s", system_path, DIR_SEPARATOR, bin_name);
872 found = gmx_is_file(full_path);
873 if (!found && (s = getenv("PATH")) != NULL)
877 dupped = gmx_strdup(s);
879 while (!found && (dir = gmx_strsep(&s, PATH_SEPARATOR)) != NULL)
881 sprintf(full_path, "%s%c%s", dir, DIR_SEPARATOR, bin_name);
882 found = gmx_is_file(full_path);
888 strcpy(libdir, GMXLIB_FALLBACK);
892 else if (!filename_is_absolute(bin_name))
894 /* name contains directory separators, but
895 * it does not start at the root, i.e.
896 * name is relative to the current dir
898 gmx_getcwd(buf, sizeof(buf));
899 sprintf(full_path, "%s%c%s", buf, DIR_SEPARATOR, bin_name);
903 strncpy(full_path, bin_name, GMX_PATH_MAX);
906 /* Now we should have a full path and name in full_path,
907 * but on unix it might be a link, or a link to a link to a link..
909 #ifndef GMX_NATIVE_WINDOWS
910 while ( (i = readlink(full_path, buf, sizeof(buf)-1)) > 0)
913 /* If it doesn't start with "/" it is relative */
914 if (buf[0] != DIR_SEPARATOR)
916 strncpy(strrchr(full_path, DIR_SEPARATOR)+1, buf, GMX_PATH_MAX);
920 strncpy(full_path, buf, GMX_PATH_MAX);
925 /* If running directly from the build tree, try to use the source
928 #if (defined CMAKE_SOURCE_DIR && defined CMAKE_BINARY_DIR)
929 if (strncmp(full_path, CMAKE_BINARY_DIR, strlen(CMAKE_BINARY_DIR)) == 0)
931 if (search_subdirs(CMAKE_SOURCE_DIR, libdir))
938 /* Remove the executable name - it always contains at least one slash */
939 *(strrchr(full_path, DIR_SEPARATOR)+1) = '\0';
940 /* Now we have the full path to the gromacs executable.
941 * Use it to find the library dir.
944 while (!found && ( (ptr = strrchr(full_path, DIR_SEPARATOR)) != NULL ) )
947 found = search_subdirs(full_path, libdir);
951 /* End of smart searching. If we didn't find it in our parent tree,
952 * or if the program name wasn't set, at least try some standard
953 * locations before giving up, in case we are running from e.g.
954 * a users home directory. This only works on unix or cygwin...
956 #ifndef GMX_NATIVE_WINDOWS
959 found = search_subdirs("/usr/local", libdir);
963 found = search_subdirs("/usr", libdir);
967 found = search_subdirs("/opt", libdir);
972 strcpy(libdir, GMXLIB_FALLBACK);
977 char *low_gmxlibfn(const char *file, gmx_bool bAddCWD, gmx_bool bFatal)
982 char libpath[GMX_PATH_MAX];
983 gmx_bool env_is_set = FALSE;
984 char *s, tmppath[GMX_PATH_MAX];
986 /* GMXLIB can be a path now */
987 lib = getenv("GMXLIB");
991 strncpy(libpath, lib, GMX_PATH_MAX);
999 if (bAddCWD && gmx_fexist(file))
1001 ret = gmx_strdup(file);
1005 strncpy(tmppath, libpath, GMX_PATH_MAX);
1007 while (ret == NULL && (dir = gmx_strsep(&s, PATH_SEPARATOR)) != NULL)
1009 sprintf(buf, "%s%c%s", dir, DIR_SEPARATOR, file);
1010 if (gmx_fexist(buf))
1012 ret = gmx_strdup(buf);
1015 if (ret == NULL && bFatal)
1020 "Library file %s not found %sin your GMXLIB path.",
1021 file, bAddCWD ? "in current dir nor " : "");
1026 "Library file %s not found %sin default directories.\n"
1027 "(You can set the directories to search with the GMXLIB path variable)",
1028 file, bAddCWD ? "in current dir nor " : "");
1040 FILE *low_libopen(const char *file, gmx_bool bFatal)
1045 fn = low_gmxlibfn(file, TRUE, bFatal);
1055 fprintf(debug, "Opening library file %s\n", fn);
1057 ff = fopen(fn, "r");
1064 char *gmxlibfn(const char *file)
1066 return low_gmxlibfn(file, TRUE, TRUE);
1069 FILE *libopen(const char *file)
1071 return low_libopen(file, TRUE);
1074 void gmx_tmpnam(char *buf)
1078 if ((len = strlen(buf)) < 7)
1080 gmx_fatal(FARGS, "Buf passed to gmx_tmpnam must be at least 7 bytes long");
1082 for (i = len-6; (i < len); i++)
1086 /* mktemp is dangerous and we should use mkstemp instead, but
1087 * since windows doesnt support it we have to separate the cases.
1088 * 20090307: mktemp deprecated, use iso c++ _mktemp instead.
1090 #ifdef GMX_NATIVE_WINDOWS
1098 gmx_fatal(FARGS, "Invalid template %s for mkstemp", buf);
1101 gmx_fatal(FARGS, "mkstemp created existing file", buf);
1104 gmx_fatal(FARGS, "Permission denied for opening %s", buf);
1111 /* name in Buf should now be OK */
1114 int gmx_truncatefile(char *path, gmx_off_t length)
1117 /* Microsoft visual studio does not have "truncate" */
1119 LARGE_INTEGER win_length;
1121 win_length.QuadPart = length;
1123 fh = CreateFile(path, GENERIC_READ | GENERIC_WRITE, 0, NULL,
1124 OPEN_EXISTING, 0, NULL);
1125 SetFilePointerEx(fh, win_length, NULL, FILE_BEGIN);
1131 return truncate(path, length);
1136 int gmx_file_rename(const char *oldname, const char *newname)
1138 #ifndef GMX_NATIVE_WINDOWS
1139 /* under unix, rename() is atomic (at least, it should be). */
1140 return rename(oldname, newname);
1142 if (MoveFileEx(oldname, newname,
1143 MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH))
1154 int gmx_file_copy(const char *oldname, const char *newname, gmx_bool copy_if_empty)
1156 /* the full copy buffer size: */
1157 #define FILECOPY_BUFSIZE (1<<16)
1162 snew(buf, FILECOPY_BUFSIZE);
1164 in = fopen(oldname, "rb");
1170 /* If we don't copy when empty, we postpone opening the file
1171 until we're actually ready to write. */
1174 out = fopen(newname, "wb");
1185 nread = fread(buf, sizeof(char), FILECOPY_BUFSIZE, in);
1191 /* so this is where we open when copy_if_empty is false:
1192 here we know we read something. */
1193 out = fopen(newname, "wb");
1199 ret = fwrite(buf, sizeof(char), nread, out);
1225 #undef FILECOPY_BUFSIZE
1229 int gmx_fsync(FILE *fp)
1234 /* the fahcore defines its own os-independent fsync */
1236 #else /* GMX_FAHCORE */
1240 /* get the file number */
1241 #if defined(HAVE_FILENO)
1243 #elif defined(HAVE__FILENO)
1247 /* do the actual fsync */
1250 #if (defined(HAVE_FSYNC))
1252 #elif (defined(HAVE__COMMIT))
1257 #endif /* GMX_FAHCORE */
1259 /* We check for these error codes this way because POSIX requires them
1260 to be defined, and using anything other than macros is unlikely: */
1262 /* we don't want to report an error just because fsync() caught a signal.
1263 For our purposes, we can just ignore this. */
1264 if (rc && errno == EINTR)
1270 /* we don't want to report an error just because we tried to fsync()
1271 stdout, a socket or a pipe. */
1272 if (rc && errno == EINVAL)
1280 void gmx_chdir(const char *directory)
1282 #ifdef GMX_NATIVE_WINDOWS
1283 int rc = _chdir(directory);
1285 int rc = chdir(directory);
1289 gmx_fatal(FARGS, "Cannot change directory to '%s'. Reason: %s",
1290 directory, strerror(errno));
1294 void gmx_getcwd(char *buffer, size_t size)
1296 #ifdef GMX_NATIVE_WINDOWS
1297 char *pdum = _getcwd(buffer, size);
1299 char *pdum = getcwd(buffer, size);
1303 gmx_fatal(FARGS, "Cannot get working directory. Reason: %s",