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 * check out http://www.gromacs.org for more information.
7 * Copyright (c) 2012, by the GROMACS development team, led by
8 * David van der Spoel, Berk Hess, Erik Lindahl, and including many
9 * others, as listed in the AUTHORS file in the top-level source
10 * directory and at http://www.gromacs.org.
12 * GROMACS is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public License
14 * as published by the Free Software Foundation; either version 2.1
15 * of the License, or (at your option) any later version.
17 * GROMACS is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with GROMACS; if not, see
24 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
25 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 * If you want to redistribute modifications to GROMACS, please
28 * consider that scientific software is very special. Version
29 * control is crucial - bugs must be traceable. We will be happy to
30 * consider code for inclusion in the official distribution, but
31 * derived work must not be called official GROMACS. Details are found
32 * in the README & COPYING files - if they are missing, get the
33 * official version at http://www.gromacs.org.
35 * To help us fund GROMACS development, we humbly ask that you cite
36 * the research papers on the package. Check out http://www.gromacs.org.
45 #include <sys/types.h>
55 #ifdef GMX_NATIVE_WINDOWS
64 #include "gmx_fatal.h"
70 #include "thread_mpi.h"
73 /* Windows file stuff, only necessary for visual studio */
78 /* we keep a linked list of all files opened through pipes (i.e.
79 compressed or .gzipped files. This way we can distinguish between them
80 without having to change the semantics of reading from/writing to files)
82 typedef struct t_pstack {
84 struct t_pstack *prev;
87 static t_pstack *pstack=NULL;
88 static gmx_bool bUnbuffered=FALSE;
91 /* this linked list is an intrinsically globally shared object, so we have
92 to protect it with mutexes */
93 static tMPI_Thread_mutex_t pstack_mutex=TMPI_THREAD_MUTEX_INITIALIZER;
101 void push_ps(FILE *fp)
105 #ifdef GMX_THREAD_MPI
106 tMPI_Thread_mutex_lock(&pstack_mutex);
113 #ifdef GMX_THREAD_MPI
114 tMPI_Thread_mutex_unlock(&pstack_mutex);
119 /* don't use pipes!*/
120 #define popen fah_fopen
121 #define pclose fah_fclose
131 static FILE *popen(const char *nm,const char *mode)
133 gmx_impl("Sorry no pipes...");
138 static int pclose(FILE *fp)
140 gmx_impl("Sorry no pipes...");
147 int ffclose(FILE *fp)
154 #ifdef GMX_THREAD_MPI
155 tMPI_Thread_mutex_lock(&pstack_mutex);
163 else if (ps->fp == fp) {
170 while ((ps->prev != NULL) && (ps->prev->fp != fp))
172 if ((ps->prev != NULL) && ps->prev->fp == fp) {
173 if (ps->prev->fp != NULL)
174 ret = pclose(ps->prev->fp);
176 ps->prev=ps->prev->prev;
184 #ifdef GMX_THREAD_MPI
185 tMPI_Thread_mutex_unlock(&pstack_mutex);
196 void frewind(FILE *fp)
199 #ifdef GMX_THREAD_MPI
200 tMPI_Thread_mutex_lock(&pstack_mutex);
206 fprintf(stderr,"Cannot rewind compressed file!\n");
207 #ifdef GMX_THREAD_MPI
208 tMPI_Thread_mutex_unlock(&pstack_mutex);
215 #ifdef GMX_THREAD_MPI
216 tMPI_Thread_mutex_unlock(&pstack_mutex);
220 int gmx_fseek(FILE *stream, gmx_off_t offset, int whence)
223 return fseeko(stream, offset, whence);
225 #ifdef HAVE__FSEEKI64
226 return _fseeki64(stream, offset, whence);
228 return fseek(stream, offset, whence);
233 gmx_off_t gmx_ftell(FILE *stream)
236 return ftello(stream);
238 #ifdef HAVE__FSEEKI64
239 return _ftelli64(stream);
241 return ftell(stream);
247 gmx_bool is_pipe(FILE *fp)
250 #ifdef GMX_THREAD_MPI
251 tMPI_Thread_mutex_lock(&pstack_mutex);
257 #ifdef GMX_THREAD_MPI
258 tMPI_Thread_mutex_unlock(&pstack_mutex);
264 #ifdef GMX_THREAD_MPI
265 tMPI_Thread_mutex_unlock(&pstack_mutex);
271 static FILE *uncompress(const char *fn,const char *mode)
276 sprintf(buf,"uncompress -c < %s",fn);
277 fprintf(stderr,"Going to execute '%s'\n",buf);
278 if ((fp=popen(buf,mode)) == NULL)
285 static FILE *gunzip(const char *fn,const char *mode)
290 sprintf(buf,"gunzip -c < %s",fn);
291 fprintf(stderr,"Going to execute '%s'\n",buf);
292 if ((fp=popen(buf,mode)) == NULL)
299 gmx_bool gmx_fexist(const char *fname)
305 test=fopen(fname,"r");
307 /*Windows doesn't allow fopen of directory - so we need to check this seperately */
308 #ifdef GMX_NATIVE_WINDOWS
309 DWORD attr = GetFileAttributes(fname);
310 return (attr != INVALID_FILE_ATTRIBUTES) && (attr & FILE_ATTRIBUTE_DIRECTORY);
320 static gmx_bool gmx_is_file(const char *fname)
326 test=fopen(fname,"r");
334 /*Windows doesn't allow fopen of directory - so we don't need to check this seperately */
335 #if (!((defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64) && !defined __CYGWIN__ && !defined __CYGWIN32__))
339 status = stat (fname, &st_buf);
340 if (status != 0 || !S_ISREG(st_buf.st_mode))
351 gmx_bool gmx_fexist_master(const char *fname, t_commrec *cr)
357 bExist = gmx_fexist(fname);
361 gmx_bcast(sizeof(bExist),&bExist,cr);
366 gmx_bool gmx_eof(FILE *fp)
374 if ((beof=fread(data,1,1,fp))==1)
375 gmx_fseek(fp,-1,SEEK_CUR);
380 static char *backup_fn(const char *file,int count_max)
382 /* Use a reasonably low value for countmax; we might
383 * generate 4-5 files in each round, and we dont
384 * want to hit directory limits of 1024 or 2048 files.
393 count_max = COUNTMAX;
396 smalloc(buf, GMX_PATH_MAX);
398 for(i=strlen(file)-1; ((i > 0) && (file[i] != DIR_SEPARATOR)); i--)
400 /* Must check whether i > 0, i.e. whether there is a directory
401 * in the file name. In that case we overwrite the / sign with
402 * a '\0' to end the directory string .
405 directory = gmx_strdup(file);
407 fn = gmx_strdup(file+i+1);
410 directory = gmx_strdup(".");
411 fn = gmx_strdup(file);
414 sprintf(buf,"%s/#%s.%d#",directory,fn,count);
416 } while ((count <= count_max) && gmx_fexist(buf));
418 /* Arbitrarily bail out */
419 if (count > count_max)
420 gmx_fatal(FARGS,"Won't make more than %d backups of %s for you.\n"
421 "The env.var. GMX_MAXBACKUP controls this maximum, -1 disables backups.",
430 gmx_bool make_backup(const char * name)
437 return FALSE; /* skip making backups */
440 if (gmx_fexist(name))
442 env = getenv("GMX_MAXBACKUP");
446 sscanf(env,"%d",&count_max);
449 /* Do not make backups and possibly overwrite old files */
455 /* Use the default maximum */
458 backup = backup_fn(name,count_max);
459 if(rename(name, backup) == 0) {
460 fprintf(stderr, "\nBack Off! I just backed up %s to %s\n",
463 fprintf(stderr, "Sorry couldn't backup %s to %s\n", name, backup);
472 FILE *ffopen(const char *file,const char *mode)
475 return fopen(file,mode);
478 char buf[256],*bf,*bufsize=0,*ptr;
492 bRead= (mode[0]=='r'&&mode[1]!='+');
494 if (!bRead || gmx_fexist(buf)) {
495 if ((ff=fopen(buf,mode))==NULL)
498 /* Check whether we should be using buffering (default) or not
501 if (bUnbuffered || ((bufsize=getenv("LOG_BUFS")) != NULL)) {
502 /* Check whether to use completely unbuffered */
506 bs=strtol(bufsize, NULL, 10);
511 if (setvbuf(ff,ptr,_IOFBF,bs) != 0)
512 gmx_file("Buffering File");
518 sprintf(buf,"%s.Z",file);
519 if (gmx_fexist(buf)) {
520 ff=uncompress(buf,mode);
523 sprintf(buf,"%s.gz",file);
524 if (gmx_fexist(buf)) {
535 /* Our own implementation of dirent-like functionality to scan directories. */
540 #elif (defined GMX_NATIVE_WINDOWS)
541 intptr_t windows_handle;
542 struct _finddata_t finddata;
551 gmx_directory_open(gmx_directory_t *p_gmxdir,const char *dirname)
553 struct gmx_directory * gmxdir;
561 if( (gmxdir->dirent_handle = opendir(dirname)) != NULL)
571 #elif (defined GMX_NATIVE_WINDOWS)
573 if(dirname!=NULL && strlen(dirname)>0)
579 len = strlen(dirname);
582 strncpy(tmpname,dirname,len+1);
584 /* Remove possible trailing directory separator */
585 if(tmpname[len]=='/' || tmpname[len]=='\\')
591 strcat(tmpname,"/*");
594 if( (gmxdir->windows_handle=_findfirst(tmpname,&gmxdir->finddata))>0L)
618 "Source compiled without POSIX dirent or windows support - cannot scan directories.\n"
619 "In the very unlikely event this is not a compile-time mistake you could consider\n"
620 "implementing support for your platform in futil.c, but contact the developers\n"
621 "to make sure it's really necessary!\n");
629 gmx_directory_nextfile(gmx_directory_t gmxdir,char *name,int maxlength_name)
635 struct dirent * direntp_large;
639 if(gmxdir!=NULL && gmxdir->dirent_handle!=NULL)
641 /* On some platforms no space is present for d_name in dirent.
642 * Since d_name is guaranteed to be the last entry, allocating
643 * extra space for dirent will allow more size for d_name.
644 * GMX_MAX_PATH should always be >= the max possible d_name.
646 smalloc(direntp_large, sizeof(*direntp_large) + GMX_PATH_MAX);
647 rc = readdir_r(gmxdir->dirent_handle,direntp_large,&p);
651 strncpy(name,direntp_large->d_name,maxlength_name);
658 sfree(direntp_large);
666 #elif (defined GMX_NATIVE_WINDOWS)
670 if(gmxdir->windows_handle<=0)
676 else if(gmxdir->first==1)
678 strncpy(name,gmxdir->finddata.name,maxlength_name);
684 if(_findnext(gmxdir->windows_handle,&gmxdir->finddata)==0)
686 strncpy(name,gmxdir->finddata.name,maxlength_name);
699 "Source compiled without POSIX dirent or windows support - cannot scan directories.\n");
707 gmx_directory_close(gmx_directory_t gmxdir)
711 rc = (gmxdir != NULL) ? closedir(gmxdir->dirent_handle) : EINVAL;
712 #elif (defined GMX_NATIVE_WINDOWS)
713 rc = (gmxdir != NULL) ? _findclose(gmxdir->windows_handle) : EINVAL;
716 "Source compiled without POSIX dirent or windows support - cannot scan directories.\n");
727 gmx_bool search_subdirs(const char *parent, char *libdir)
732 /* Search a few common subdirectory names for the gromacs library dir */
733 sprintf(libdir,"%s%cshare%ctop%cgurgle.dat",parent,
734 DIR_SEPARATOR,DIR_SEPARATOR,DIR_SEPARATOR);
735 found=gmx_fexist(libdir);
737 sprintf(libdir,"%s%cshare%cgromacs%ctop%cgurgle.dat",parent,
738 DIR_SEPARATOR,DIR_SEPARATOR,
739 DIR_SEPARATOR,DIR_SEPARATOR);
740 found=gmx_fexist(libdir);
743 sprintf(libdir,"%s%cshare%cgromacs-%s%ctop%cgurgle.dat",parent,
744 DIR_SEPARATOR,DIR_SEPARATOR,VERSION,
745 DIR_SEPARATOR,DIR_SEPARATOR);
746 found=gmx_fexist(libdir);
749 sprintf(libdir,"%s%cshare%cgromacs%cgromacs-%s%ctop%cgurgle.dat",parent,
750 DIR_SEPARATOR,DIR_SEPARATOR,DIR_SEPARATOR,
751 VERSION,DIR_SEPARATOR,DIR_SEPARATOR);
752 found=gmx_fexist(libdir);
755 /* Remove the gurgle.dat part from libdir if we found something */
757 ptr=strrchr(libdir,DIR_SEPARATOR); /* slash or backslash always present, no check necessary */
764 /* Check if the program name begins with "/" on unix/cygwin, or
765 * with "\" or "X:\" on windows. If not, the program name
766 * is relative to the current directory.
768 static gmx_bool filename_is_absolute(char *name)
770 #ifdef GMX_NATIVE_WINDOWS
771 return ((name[0] == DIR_SEPARATOR) || ((strlen(name)>3) && strncmp(name+1,":\\",2)) == 0);
773 return (name[0] == DIR_SEPARATOR);
777 gmx_bool get_libdir(char *libdir)
779 #define GMX_BINNAME_MAX 512
780 char bin_name[GMX_BINNAME_MAX];
781 char buf[GMX_BINNAME_MAX];
782 char full_path[GMX_PATH_MAX+GMX_BINNAME_MAX];
783 char system_path[GMX_PATH_MAX];
784 char *dir,*ptr,*s,*pdum;
785 gmx_bool found=FALSE;
788 if (Program() != NULL)
791 /* First - detect binary name */
792 if (strlen(Program()) >= GMX_BINNAME_MAX)
794 gmx_fatal(FARGS,"The name of the binary is longer than the allowed buffer size (%d):\n'%s'",GMX_BINNAME_MAX,Program());
796 strncpy(bin_name,Program(),GMX_BINNAME_MAX-1);
798 /* On windows & cygwin we need to add the .exe extension
799 * too, or we wont be able to detect that the file exists
801 #if (defined GMX_NATIVE_WINDOWS || defined GMX_CYGWIN)
802 if(strlen(bin_name)<3 || gmx_strncasecmp(bin_name+strlen(bin_name)-4,".exe",4))
803 strcat(bin_name,".exe");
806 /* Only do the smart search part if we got a real name */
807 if (NULL!=bin_name && strncmp(bin_name,"GROMACS",GMX_BINNAME_MAX)) {
809 if (!strchr(bin_name,DIR_SEPARATOR)) {
810 /* No slash or backslash in name means it must be in the path - search it! */
811 /* Add the local dir since it is not in the path on windows */
812 #ifdef GMX_NATIVE_WINDOWS
813 pdum=_getcwd(system_path,sizeof(system_path)-1);
815 pdum=getcwd(system_path,sizeof(system_path)-1);
817 sprintf(full_path,"%s%c%s",system_path,DIR_SEPARATOR,bin_name);
818 found = gmx_is_file(full_path);
819 if (!found && (s=getenv("PATH")) != NULL)
823 dupped=gmx_strdup(s);
825 while(!found && (dir=gmx_strsep(&s, PATH_SEPARATOR)) != NULL)
827 sprintf(full_path,"%s%c%s",dir,DIR_SEPARATOR,bin_name);
828 found = gmx_is_file(full_path);
836 } else if (!filename_is_absolute(bin_name)) {
837 /* name contains directory separators, but
838 * it does not start at the root, i.e.
839 * name is relative to the current dir
841 #ifdef GMX_NATIVE_WINDOWS
842 pdum=_getcwd(buf,sizeof(buf)-1);
844 pdum=getcwd(buf,sizeof(buf)-1);
846 sprintf(full_path,"%s%c%s",buf,DIR_SEPARATOR,bin_name);
848 strncpy(full_path,bin_name,GMX_PATH_MAX);
851 /* Now we should have a full path and name in full_path,
852 * but on unix it might be a link, or a link to a link to a link..
854 #ifndef GMX_NATIVE_WINDOWS
855 while( (i=readlink(full_path,buf,sizeof(buf)-1)) > 0 ) {
857 /* If it doesn't start with "/" it is relative */
858 if (buf[0]!=DIR_SEPARATOR) {
859 strncpy(strrchr(full_path,DIR_SEPARATOR)+1,buf,GMX_PATH_MAX);
861 strncpy(full_path,buf,GMX_PATH_MAX);
865 /* Remove the executable name - it always contains at least one slash */
866 *(strrchr(full_path,DIR_SEPARATOR)+1)='\0';
867 /* Now we have the full path to the gromacs executable.
868 * Use it to find the library dir.
871 while(!found && ( (ptr=strrchr(full_path,DIR_SEPARATOR)) != NULL ) ) {
873 found=search_subdirs(full_path,libdir);
877 /* End of smart searching. If we didn't find it in our parent tree,
878 * or if the program name wasn't set, at least try some standard
879 * locations before giving up, in case we are running from e.g.
880 * a users home directory. This only works on unix or cygwin...
882 #ifndef GMX_NATIVE_WINDOWS
884 found=search_subdirs("/usr/local",libdir);
886 found=search_subdirs("/usr",libdir);
888 found=search_subdirs("/opt",libdir);
894 char *low_gmxlibfn(const char *file, gmx_bool bAddCWD, gmx_bool bFatal)
899 char libpath[GMX_PATH_MAX];
900 gmx_bool env_is_set=FALSE;
901 char *s,tmppath[GMX_PATH_MAX];
903 /* GMXLIB can be a path now */
904 lib=getenv("GMXLIB");
908 strncpy(libpath,lib,GMX_PATH_MAX);
910 else if (!get_libdir(libpath))
912 strncpy(libpath,GMXLIBDIR,GMX_PATH_MAX);
916 if (bAddCWD && gmx_fexist(file))
918 ret = gmx_strdup(file);
922 strncpy(tmppath,libpath,GMX_PATH_MAX);
924 while(ret == NULL && (dir=gmx_strsep(&s, PATH_SEPARATOR)) != NULL )
926 sprintf(buf,"%s%c%s",dir,DIR_SEPARATOR,file);
929 ret = gmx_strdup(buf);
932 if (ret == NULL && bFatal)
937 "Library file %s not found %sin your GMXLIB path.",
938 file, bAddCWD ? "in current dir nor " : "");
943 "Library file %s not found %sin default directories.\n"
944 "(You can set the directories to search with the GMXLIB path variable)",
945 file, bAddCWD ? "in current dir nor " : "");
957 FILE *low_libopen(const char *file,gmx_bool bFatal)
962 fn=low_gmxlibfn(file,TRUE,bFatal);
968 fprintf(debug,"Opening library file %s\n",fn);
976 char *gmxlibfn(const char *file)
978 return low_gmxlibfn(file,TRUE,TRUE);
981 FILE *libopen(const char *file)
983 return low_libopen(file,TRUE);
986 void gmx_tmpnam(char *buf)
990 if ((len = strlen(buf)) < 7)
991 gmx_fatal(FARGS,"Buf passed to gmx_tmpnam must be at least 7 bytes long");
992 for(i=len-6; (i<len); i++) {
995 /* mktemp is dangerous and we should use mkstemp instead, but
996 * since windows doesnt support it we have to separate the cases.
997 * 20090307: mktemp deprecated, use iso c++ _mktemp instead.
999 #ifdef GMX_NATIVE_WINDOWS
1006 gmx_fatal(FARGS,"Invalid template %s for mkstemp",buf);
1009 gmx_fatal(FARGS,"mkstemp created existing file",buf);
1012 gmx_fatal(FARGS,"Permission denied for opening %s",buf);
1019 /* name in Buf should now be OK */
1022 int gmx_truncatefile(char *path, gmx_off_t length)
1025 /* Microsoft visual studio does not have "truncate" */
1027 LARGE_INTEGER win_length;
1029 win_length.QuadPart = length;
1031 fh = CreateFile(path,GENERIC_READ | GENERIC_WRITE,0,NULL,
1032 OPEN_EXISTING,0,NULL);
1033 SetFilePointerEx(fh,win_length,NULL,FILE_BEGIN);
1039 return truncate(path,length);
1044 int gmx_file_rename(const char *oldname, const char *newname)
1046 #ifndef GMX_NATIVE_WINDOWS
1047 /* under unix, rename() is atomic (at least, it should be). */
1048 return rename(oldname, newname);
1050 if (MoveFileEx(oldname, newname,
1051 MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH))
1058 int gmx_file_copy(const char *oldname, const char *newname, gmx_bool copy_if_empty)
1060 /* the full copy buffer size: */
1061 #define FILECOPY_BUFSIZE (1<<16)
1066 snew(buf, FILECOPY_BUFSIZE);
1068 in=fopen(oldname, "rb");
1072 /* If we don't copy when empty, we postpone opening the file
1073 until we're actually ready to write. */
1076 out=fopen(newname, "wb");
1085 nread=fread(buf, sizeof(char), FILECOPY_BUFSIZE, in);
1091 /* so this is where we open when copy_if_empty is false:
1092 here we know we read something. */
1093 out=fopen(newname, "wb");
1097 ret=fwrite(buf, sizeof(char), nread, out);
1117 #undef FILECOPY_BUFSIZE
1121 int gmx_fsync(FILE *fp)
1126 /* the fahcore defines its own os-independent fsync */
1128 #else /* GMX_FAHCORE */
1132 /* get the file number */
1133 #if defined(HAVE_FILENO)
1135 #elif defined(HAVE__FILENO)
1139 /* do the actual fsync */
1142 #if (defined(HAVE_FSYNC))
1144 #elif (defined(HAVE__COMMIT))
1149 #endif /* GMX_FAHCORE */
1151 /* We check for these error codes this way because POSIX requires them
1152 to be defined, and using anything other than macros is unlikely: */
1154 /* we don't want to report an error just because fsync() caught a signal.
1155 For our purposes, we can just ignore this. */
1156 if (rc && errno==EINTR)
1160 /* we don't want to report an error just because we tried to fsync()
1161 stdout, a socket or a pipe. */
1162 if (rc && errno==EINVAL)