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%cshare%cgromacs%ctop%cgurgle.dat", parent,
803 DIR_SEPARATOR, DIR_SEPARATOR,
804 DIR_SEPARATOR, DIR_SEPARATOR);
805 found = gmx_fexist(libdir);
809 sprintf(libdir, "%s%cshare%cgromacs-%s%ctop%cgurgle.dat", parent,
810 DIR_SEPARATOR, DIR_SEPARATOR, VERSION,
811 DIR_SEPARATOR, DIR_SEPARATOR);
812 found = gmx_fexist(libdir);
816 sprintf(libdir, "%s%cshare%cgromacs%cgromacs-%s%ctop%cgurgle.dat", parent,
817 DIR_SEPARATOR, DIR_SEPARATOR, DIR_SEPARATOR,
818 VERSION, DIR_SEPARATOR, DIR_SEPARATOR);
819 found = gmx_fexist(libdir);
822 /* Remove the gurgle.dat part from libdir if we found something */
825 ptr = strrchr(libdir, DIR_SEPARATOR); /* slash or backslash always present, no check necessary */
832 /* Check if the program name begins with "/" on unix/cygwin, or
833 * with "\" or "X:\" on windows. If not, the program name
834 * is relative to the current directory.
836 static gmx_bool filename_is_absolute(char *name)
838 #ifdef GMX_NATIVE_WINDOWS
839 return ((name[0] == DIR_SEPARATOR) || ((strlen(name) > 3) && strncmp(name+1, ":\\", 2)) == 0);
841 return (name[0] == DIR_SEPARATOR);
845 gmx_bool get_libdir(char *libdir)
847 #define GMX_BINNAME_MAX 512
848 char bin_name[GMX_BINNAME_MAX];
849 char buf[GMX_BINNAME_MAX];
850 char full_path[GMX_PATH_MAX+GMX_BINNAME_MAX];
851 char system_path[GMX_PATH_MAX];
853 gmx_bool found = FALSE;
856 if (Program() != NULL)
859 /* First - detect binary name */
860 if (strlen(Program()) >= GMX_BINNAME_MAX)
862 gmx_fatal(FARGS, "The name of the binary is longer than the allowed buffer size (%d):\n'%s'", GMX_BINNAME_MAX, Program());
864 strncpy(bin_name, Program(), GMX_BINNAME_MAX-1);
866 /* On windows & cygwin we need to add the .exe extension
867 * too, or we wont be able to detect that the file exists
869 #if (defined GMX_NATIVE_WINDOWS || defined GMX_CYGWIN)
870 if (strlen(bin_name) < 3 || gmx_strncasecmp(bin_name+strlen(bin_name)-4, ".exe", 4))
872 strcat(bin_name, ".exe");
876 /* Only do the smart search part if we got a real name */
877 if (NULL != bin_name && strncmp(bin_name, "GROMACS", GMX_BINNAME_MAX))
880 if (!strchr(bin_name, DIR_SEPARATOR))
882 /* No slash or backslash in name means it must be in the path - search it! */
883 /* Add the local dir since it is not in the path on windows */
884 gmx_getcwd(system_path, sizeof(system_path));
885 sprintf(full_path, "%s%c%s", system_path, DIR_SEPARATOR, bin_name);
886 found = gmx_is_file(full_path);
887 if (!found && (s = getenv("PATH")) != NULL)
891 dupped = gmx_strdup(s);
893 while (!found && (dir = gmx_strsep(&s, PATH_SEPARATOR)) != NULL)
895 sprintf(full_path, "%s%c%s", dir, DIR_SEPARATOR, bin_name);
896 found = gmx_is_file(full_path);
905 else if (!filename_is_absolute(bin_name))
907 /* name contains directory separators, but
908 * it does not start at the root, i.e.
909 * name is relative to the current dir
911 gmx_getcwd(buf, sizeof(buf));
912 sprintf(full_path, "%s%c%s", buf, DIR_SEPARATOR, bin_name);
916 strncpy(full_path, bin_name, GMX_PATH_MAX);
919 /* Now we should have a full path and name in full_path,
920 * but on unix it might be a link, or a link to a link to a link..
922 #ifndef GMX_NATIVE_WINDOWS
923 while ( (i = readlink(full_path, buf, sizeof(buf)-1)) > 0)
926 /* If it doesn't start with "/" it is relative */
927 if (buf[0] != DIR_SEPARATOR)
929 strncpy(strrchr(full_path, DIR_SEPARATOR)+1, buf, GMX_PATH_MAX);
933 strncpy(full_path, buf, GMX_PATH_MAX);
938 /* If running directly from the build tree, try to use the source
941 #if (defined CMAKE_SOURCE_DIR && defined CMAKE_BINARY_DIR)
942 if (strncmp(full_path, CMAKE_BINARY_DIR, strlen(CMAKE_BINARY_DIR)) == 0)
944 if (search_subdirs(CMAKE_SOURCE_DIR, libdir))
951 /* Remove the executable name - it always contains at least one slash */
952 *(strrchr(full_path, DIR_SEPARATOR)+1) = '\0';
953 /* Now we have the full path to the gromacs executable.
954 * Use it to find the library dir.
957 while (!found && ( (ptr = strrchr(full_path, DIR_SEPARATOR)) != NULL ) )
960 found = search_subdirs(full_path, libdir);
964 /* End of smart searching. If we didn't find it in our parent tree,
965 * or if the program name wasn't set, at least try some standard
966 * locations before giving up, in case we are running from e.g.
967 * a users home directory. This only works on unix or cygwin...
969 #ifndef GMX_NATIVE_WINDOWS
972 found = search_subdirs("/usr/local", libdir);
976 found = search_subdirs("/usr", libdir);
980 found = search_subdirs("/opt", libdir);
987 char *low_gmxlibfn(const char *file, gmx_bool bAddCWD, gmx_bool bFatal)
992 char libpath[GMX_PATH_MAX];
993 gmx_bool env_is_set = FALSE;
994 char *s, tmppath[GMX_PATH_MAX];
996 /* GMXLIB can be a path now */
997 lib = getenv("GMXLIB");
1001 strncpy(libpath, lib, GMX_PATH_MAX);
1003 else if (!get_libdir(libpath))
1005 strncpy(libpath, GMXLIBDIR, GMX_PATH_MAX);
1009 if (bAddCWD && gmx_fexist(file))
1011 ret = gmx_strdup(file);
1015 strncpy(tmppath, libpath, GMX_PATH_MAX);
1017 while (ret == NULL && (dir = gmx_strsep(&s, PATH_SEPARATOR)) != NULL)
1019 sprintf(buf, "%s%c%s", dir, DIR_SEPARATOR, file);
1020 if (gmx_fexist(buf))
1022 ret = gmx_strdup(buf);
1025 if (ret == NULL && bFatal)
1030 "Library file %s not found %sin your GMXLIB path.",
1031 file, bAddCWD ? "in current dir nor " : "");
1036 "Library file %s not found %sin default directories.\n"
1037 "(You can set the directories to search with the GMXLIB path variable)",
1038 file, bAddCWD ? "in current dir nor " : "");
1050 FILE *low_libopen(const char *file, gmx_bool bFatal)
1055 fn = low_gmxlibfn(file, TRUE, bFatal);
1065 fprintf(debug, "Opening library file %s\n", fn);
1067 ff = fopen(fn, "r");
1074 char *gmxlibfn(const char *file)
1076 return low_gmxlibfn(file, TRUE, TRUE);
1079 FILE *libopen(const char *file)
1081 return low_libopen(file, TRUE);
1084 void gmx_tmpnam(char *buf)
1088 if ((len = strlen(buf)) < 7)
1090 gmx_fatal(FARGS, "Buf passed to gmx_tmpnam must be at least 7 bytes long");
1092 for (i = len-6; (i < len); i++)
1096 /* mktemp is dangerous and we should use mkstemp instead, but
1097 * since windows doesnt support it we have to separate the cases.
1098 * 20090307: mktemp deprecated, use iso c++ _mktemp instead.
1100 #ifdef GMX_NATIVE_WINDOWS
1108 gmx_fatal(FARGS, "Invalid template %s for mkstemp", buf);
1111 gmx_fatal(FARGS, "mkstemp created existing file", buf);
1114 gmx_fatal(FARGS, "Permission denied for opening %s", buf);
1121 /* name in Buf should now be OK */
1124 int gmx_truncatefile(char *path, gmx_off_t length)
1127 /* Microsoft visual studio does not have "truncate" */
1129 LARGE_INTEGER win_length;
1131 win_length.QuadPart = length;
1133 fh = CreateFile(path, GENERIC_READ | GENERIC_WRITE, 0, NULL,
1134 OPEN_EXISTING, 0, NULL);
1135 SetFilePointerEx(fh, win_length, NULL, FILE_BEGIN);
1141 return truncate(path, length);
1146 int gmx_file_rename(const char *oldname, const char *newname)
1148 #ifndef GMX_NATIVE_WINDOWS
1149 /* under unix, rename() is atomic (at least, it should be). */
1150 return rename(oldname, newname);
1152 if (MoveFileEx(oldname, newname,
1153 MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH))
1164 int gmx_file_copy(const char *oldname, const char *newname, gmx_bool copy_if_empty)
1166 /* the full copy buffer size: */
1167 #define FILECOPY_BUFSIZE (1<<16)
1172 snew(buf, FILECOPY_BUFSIZE);
1174 in = fopen(oldname, "rb");
1180 /* If we don't copy when empty, we postpone opening the file
1181 until we're actually ready to write. */
1184 out = fopen(newname, "wb");
1195 nread = fread(buf, sizeof(char), FILECOPY_BUFSIZE, in);
1201 /* so this is where we open when copy_if_empty is false:
1202 here we know we read something. */
1203 out = fopen(newname, "wb");
1209 ret = fwrite(buf, sizeof(char), nread, out);
1235 #undef FILECOPY_BUFSIZE
1239 int gmx_fsync(FILE *fp)
1244 /* the fahcore defines its own os-independent fsync */
1246 #else /* GMX_FAHCORE */
1250 /* get the file number */
1251 #if defined(HAVE_FILENO)
1253 #elif defined(HAVE__FILENO)
1257 /* do the actual fsync */
1260 #if (defined(HAVE_FSYNC))
1262 #elif (defined(HAVE__COMMIT))
1267 #endif /* GMX_FAHCORE */
1269 /* We check for these error codes this way because POSIX requires them
1270 to be defined, and using anything other than macros is unlikely: */
1272 /* we don't want to report an error just because fsync() caught a signal.
1273 For our purposes, we can just ignore this. */
1274 if (rc && errno == EINTR)
1280 /* we don't want to report an error just because we tried to fsync()
1281 stdout, a socket or a pipe. */
1282 if (rc && errno == EINVAL)
1290 void gmx_chdir(const char *directory)
1292 #ifdef GMX_NATIVE_WINDOWS
1293 int rc = _chdir(directory);
1295 int rc = chdir(directory);
1299 gmx_fatal(FARGS, "Cannot change directory to '%s'. Reason: %s",
1300 directory, strerror(errno));
1304 void gmx_getcwd(char *buffer, size_t size)
1306 #ifdef GMX_NATIVE_WINDOWS
1307 char *pdum = _getcwd(buffer, size);
1309 char *pdum = getcwd(buffer, size);
1313 gmx_fatal(FARGS, "Cannot get working directory. Reason: %s",