xref: /petsc/config/PETSc/Configure.py (revision 5e3eff632f69d757b4e40cf4b86faff7dd69a706)
1import config.base
2
3import os
4import re
5
6# The sorted() builtin is not available with python-2.3
7try: sorted
8except NameError:
9  def sorted(lst):
10    lst.sort()
11    return lst
12
13class Configure(config.base.Configure):
14  def __init__(self, framework):
15    config.base.Configure.__init__(self, framework)
16    self.headerPrefix = 'PETSC'
17    self.substPrefix  = 'PETSC'
18    return
19
20  def __str2__(self):
21    desc = []
22    desc.append('xxx=========================================================================xxx')
23    if self.make.getMakeMacro('MAKE_IS_GNUMAKE'):
24      build_type = 'gnumake build'
25    elif self.getMakeMacro('PETSC_BUILD_USING_CMAKE'):
26      build_type = 'cmake build'
27    else:
28      build_type = 'legacy build'
29    desc.append(' Configure stage complete. Now build PETSc libraries with (%s):' % build_type)
30    desc.append('   make PETSC_DIR='+self.petscdir.dir+' PETSC_ARCH='+self.arch.arch+' all')
31    desc.append(' or (experimental with python):')
32    desc.append('   PETSC_DIR='+self.petscdir.dir+' PETSC_ARCH='+self.arch.arch+' ./config/builder.py')
33    desc.append('xxx=========================================================================xxx')
34    return '\n'.join(desc)+'\n'
35
36  def setupHelp(self, help):
37    import nargs
38    help.addArgument('PETSc',  '-prefix=<dir>',                  nargs.Arg(None, '', 'Specifiy location to install PETSc (eg. /usr/local)'))
39    help.addArgument('Windows','-with-windows-graphics=<bool>',   nargs.ArgBool(None, 1,'Enable check for Windows Graphics'))
40    help.addArgument('PETSc', '-with-default-arch=<bool>',        nargs.ArgBool(None, 1, 'Allow using the last configured arch without setting PETSC_ARCH'))
41    help.addArgument('PETSc','-with-single-library=<bool>',       nargs.ArgBool(None, 1,'Put all PETSc code into the single -lpetsc library'))
42    help.addArgument('PETSc', '-with-ios=<bool>',              nargs.ArgBool(None, 0, 'Build an iPhone/iPad version of PETSc library'))
43    return
44
45  def setupDependencies(self, framework):
46    config.base.Configure.setupDependencies(self, framework)
47    self.setCompilers  = framework.require('config.setCompilers',       self)
48    self.arch          = framework.require('PETSc.utilities.arch',      self.setCompilers)
49    self.petscdir      = framework.require('PETSc.utilities.petscdir',  self.setCompilers)
50    self.installdir    = framework.require('PETSc.utilities.installDir',self)
51    self.languages     = framework.require('PETSc.utilities.languages', self.setCompilers)
52    self.debugging     = framework.require('PETSc.utilities.debugging', self.setCompilers)
53    self.CHUD          = framework.require('PETSc.utilities.CHUD',      self)
54    self.compilers     = framework.require('config.compilers',          self)
55    self.types         = framework.require('config.types',              self)
56    self.headers       = framework.require('config.headers',            self)
57    self.functions     = framework.require('config.functions',          self)
58    self.libraries     = framework.require('config.libraries',          self)
59    self.atomics       = framework.require('config.atomics',            self)
60    self.make          = framework.require('config.packages.make',      self)
61    self.blasLapack    = framework.require('config.packages.BlasLapack',self)
62    self.externalpackagesdir = framework.require('PETSc.utilities.externalpackagesdir',self)
63
64    if os.path.isdir(os.path.join('config', 'PETSc')):
65      for d in ['utilities', 'packages']:
66        for utility in os.listdir(os.path.join('config', 'PETSc', d)):
67          (utilityName, ext) = os.path.splitext(utility)
68          if not utilityName.startswith('.') and not utilityName.startswith('#') and ext == '.py' and not utilityName == '__init__':
69            utilityObj                    = self.framework.require('PETSc.'+d+'.'+utilityName, self)
70            utilityObj.headerPrefix       = self.headerPrefix
71            utilityObj.archProvider       = self.arch
72            utilityObj.languageProvider   = self.languages
73            utilityObj.installDirProvider = self.installdir
74            utilityObj.externalPackagesDirProvider = self.externalpackagesdir
75            setattr(self, utilityName.lower(), utilityObj)
76
77    for package in config.packages.all:
78      if not package == 'PETSc':
79        packageObj                    = framework.require('config.packages.'+package, self)
80        packageObj.archProvider       = self.arch
81        packageObj.languageProvider   = self.languages
82        packageObj.installDirProvider = self.installdir
83        packageObj.externalPackagesDirProvider = self.externalpackagesdir
84        setattr(self, package.lower(), packageObj)
85    # Force blaslapack to depend on scalarType so precision is set before BlasLapack is built
86    framework.require('PETSc.utilities.scalarTypes', self.f2cblaslapack)
87    self.f2cblaslapack.precisionProvider = self.scalartypes
88    framework.require('PETSc.utilities.scalarTypes', self.blaslapack)
89    self.blaslapack.precisionProvider = self.scalartypes
90
91    self.compilers.headerPrefix  = self.headerPrefix
92    self.types.headerPrefix      = self.headerPrefix
93    self.headers.headerPrefix    = self.headerPrefix
94    self.functions.headerPrefix  = self.headerPrefix
95    self.libraries.headerPrefix  = self.headerPrefix
96    self.blaslapack.headerPrefix = self.headerPrefix
97    self.mpi.headerPrefix        = self.headerPrefix
98    headersC = map(lambda name: name+'.h', ['setjmp','dos', 'endian', 'fcntl', 'float', 'io', 'limits', 'malloc', 'pwd', 'search', 'strings',
99                                            'unistd', 'sys/sysinfo', 'machine/endian', 'sys/param', 'sys/procfs', 'sys/resource',
100                                            'sys/systeminfo', 'sys/times', 'sys/utsname','string', 'stdlib','memory',
101                                            'sys/socket','sys/wait','netinet/in','netdb','Direct','time','Ws2tcpip','sys/types',
102                                            'WindowsX', 'cxxabi','float','ieeefp','stdint','sched','pthread','mathimf'])
103    functions = ['access', '_access', 'clock', 'drand48', 'getcwd', '_getcwd', 'getdomainname', 'gethostname',
104                 'gettimeofday', 'getwd', 'memalign', 'memmove', 'mkstemp', 'popen', 'PXFGETARG', 'rand', 'getpagesize',
105                 'readlink', 'realpath',  'sigaction', 'signal', 'sigset', 'usleep', 'sleep', '_sleep', 'socket',
106                 'times', 'gethostbyname', 'uname','snprintf','_snprintf','lseek','_lseek','time','fork','stricmp',
107                 'strcasecmp', 'bzero', 'dlopen', 'dlsym', 'dlclose', 'dlerror','get_nprocs','sysctlbyname',
108                 '_intel_fast_memcpy','_intel_fast_memset']
109    libraries1 = [(['socket', 'nsl'], 'socket'), (['fpe'], 'handle_sigfpes')]
110    self.headers.headers.extend(headersC)
111    self.functions.functions.extend(functions)
112    self.libraries.libraries.extend(libraries1)
113
114    return
115
116  def DumpPkgconfig(self):
117    ''' Create a pkg-config file '''
118    if not os.path.exists(os.path.join(self.petscdir.dir,self.arch.arch,'lib','pkgconfig')):
119      os.makedirs(os.path.join(self.petscdir.dir,self.arch.arch,'lib','pkgconfig'))
120    fd = open(os.path.join(self.petscdir.dir,self.arch.arch,'lib','pkgconfig','PETSc.pc'),'w')
121    if self.framework.argDB['prefix']:
122      installdir = self.framework.argDB['prefix']
123      fd.write('prefix='+installdir+'\n')
124      fd.write('exec_prefix=${prefix}\n')
125      fd.write('includedir=${prefix}/include\n')
126      fd.write('libdir='+os.path.join(installdir,'lib')+'\n')
127    else:
128      fd.write('prefix='+self.petscdir.dir+'\n')
129      fd.write('exec_prefix=${prefix}\n')
130      fd.write('includedir=${prefix}/include\n')
131      fd.write('libdir='+os.path.join(self.petscdir.dir,self.arch.arch,'lib')+'\n')
132
133    self.setCompilers.pushLanguage('C')
134    fd.write('ccompiler='+self.setCompilers.getCompiler()+'\n')
135    self.setCompilers.popLanguage()
136    if hasattr(self.compilers, 'C++'):
137      self.setCompilers.pushLanguage('C++')
138      fd.write('cxxcompiler='+self.setCompilers.getCompiler()+'\n')
139      self.setCompilers.popLanguage()
140    if hasattr(self.compilers, 'FC'):
141      self.setCompilers.pushLanguage('FC')
142      fd.write('fcompiler='+self.setCompilers.getCompiler()+'\n')
143      self.setCompilers.popLanguage()
144    fd.write('blaslapacklibs='+self.libraries.toStringNoDupes(self.blaslapack.lib)+'\n')
145
146    fd.write('\n')
147    fd.write('Name: PETSc\n')
148    fd.write('Description: Library to solve ODEs and algebraic equations\n')
149    fd.write('Version: %s\n' % self.petscdir.version)
150
151    fd.write('Cflags: '+self.allincludes+'\n')
152
153    plibs = self.libraries.toStringNoDupes(['-L'+os.path.join(self.petscdir.dir,self.arch.arch,'lib'),' -lpetsc'])
154    if self.framework.argDB['prefix']:
155      fd.write('Libs: '+plibs.replace(os.path.join(self.petscdir.dir,self.arch.arch),self.framework.argDB['prefix'])+'\n')
156    else:
157      fd.write('Libs: '+plibs+'\n')
158    fd.write('Libs.private: '+' '.join(self.packagelibs+self.libraries.math+self.compilers.flibs+self.compilers.cxxlibs+self.compilers.LIBS.split(' ')))
159
160    fd.close()
161    return
162
163  def DumpModule(self):
164    ''' Create a module file '''
165    if not os.path.exists(os.path.join(self.petscdir.dir,self.arch.arch,'lib','modules')):
166      os.makedirs(os.path.join(self.petscdir.dir,self.arch.arch,'lib','modules'))
167    if self.framework.argDB['prefix']:
168      installdir  = self.framework.argDB['prefix']
169      installarch = ''
170      installpath = os.path.join(installdir,'bin')
171      fd = open(os.path.join(self.petscdir.dir,self.arch.arch,'lib','modules',self.petscdir.version),'w')
172    else:
173      installdir  = self.petscdir.dir
174      installarch = self.arch.arch
175      installpath = os.path.join(installdir,installarch,'bin')+':'+os.path.join(installdir,'bin')
176      fd = open(os.path.join(self.petscdir.dir,self.arch.arch,'lib','modules',self.petscdir.version+'-'+self.arch.arch),'w')
177    fd.write('''\
178#%%Module
179
180proc ModulesHelp { } {
181    puts stderr "This module sets the path and environment variables for petsc-%s"
182    puts stderr "     see http://www.mcs.anl.gov/petsc/ for more information      "
183    puts stderr ""
184}
185module-whatis "PETSc - Portable, Extensible Toolkit for Scientific Computation"
186
187set petsc_dir   %s
188set petsc_arch  %s
189
190setenv PETSC_ARCH $petsc_arch
191setenv PETSC_DIR $petsc_dir
192prepend-path PATH %s
193''' % (self.petscdir.version, installdir, installarch, installpath))
194    fd.close()
195    return
196
197  def Dump(self):
198    ''' Actually put the values into the configuration files '''
199    # eventually everything between -- should be gone
200#-----------------------------------------------------------------------------------------------------
201
202    # Sometimes we need C compiler, even if built with C++
203    self.setCompilers.pushLanguage('C')
204    self.addMakeMacro('CC_FLAGS',self.setCompilers.getCompilerFlags())
205    self.setCompilers.popLanguage()
206
207    # C preprocessor values
208    self.addMakeMacro('CPP_FLAGS',self.setCompilers.CPPFLAGS+self.CHUD.CPPFLAGS)
209
210    # compiler values
211    self.setCompilers.pushLanguage(self.languages.clanguage)
212    self.addMakeMacro('PCC',self.setCompilers.getCompiler())
213    self.addMakeMacro('PCC_FLAGS',self.setCompilers.getCompilerFlags())
214    self.setCompilers.popLanguage()
215    # .o or .obj
216    self.addMakeMacro('CC_SUFFIX','o')
217
218    # executable linker values
219    self.setCompilers.pushLanguage(self.languages.clanguage)
220    pcc_linker = self.setCompilers.getLinker()
221    self.addMakeMacro('PCC_LINKER',pcc_linker)
222    self.addMakeMacro('PCC_LINKER_FLAGS',self.setCompilers.getLinkerFlags())
223    self.setCompilers.popLanguage()
224    # '' for Unix, .exe for Windows
225    self.addMakeMacro('CC_LINKER_SUFFIX','')
226
227    if hasattr(self.compilers, 'FC'):
228      self.setCompilers.pushLanguage('FC')
229      # need FPPFLAGS in config/setCompilers
230      self.addDefine('HAVE_FORTRAN','1')
231      self.addMakeMacro('FPP_FLAGS',self.setCompilers.CPPFLAGS)
232
233      # compiler values
234      self.addMakeMacro('FC_FLAGS',self.setCompilers.getCompilerFlags())
235      self.setCompilers.popLanguage()
236      # .o or .obj
237      self.addMakeMacro('FC_SUFFIX','o')
238
239      # executable linker values
240      self.setCompilers.pushLanguage('FC')
241      # Cannot have NAG f90 as the linker - so use pcc_linker as fc_linker
242      fc_linker = self.setCompilers.getLinker()
243      if config.setCompilers.Configure.isNAG(fc_linker):
244        self.addMakeMacro('FC_LINKER',pcc_linker)
245      else:
246        self.addMakeMacro('FC_LINKER',fc_linker)
247      self.addMakeMacro('FC_LINKER_FLAGS',self.setCompilers.getLinkerFlags())
248      # apple requires this shared library linker flag on SOME versions of the os
249      if self.setCompilers.getLinkerFlags().find('-Wl,-commons,use_dylibs') > -1:
250        self.addMakeMacro('DARWIN_COMMONS_USE_DYLIBS',' -Wl,-commons,use_dylibs ')
251      self.setCompilers.popLanguage()
252
253      # F90 Modules
254      if self.setCompilers.fortranModuleIncludeFlag:
255        self.addMakeMacro('FC_MODULE_FLAG', self.setCompilers.fortranModuleIncludeFlag)
256      else: # for non-f90 compilers like g77
257        self.addMakeMacro('FC_MODULE_FLAG', '-I')
258      if self.setCompilers.fortranModuleIncludeFlag:
259        self.addMakeMacro('FC_MODULE_OUTPUT_FLAG', self.setCompilers.fortranModuleOutputFlag)
260    else:
261      self.addMakeMacro('FC','')
262
263    if hasattr(self.compilers, 'CUDAC'):
264      self.setCompilers.pushLanguage('CUDA')
265      self.addMakeMacro('CUDAC_FLAGS',self.setCompilers.getCompilerFlags())
266      self.setCompilers.popLanguage()
267
268    # shared library linker values
269    self.setCompilers.pushLanguage(self.languages.clanguage)
270    # need to fix BuildSystem to collect these separately
271    self.addMakeMacro('SL_LINKER',self.setCompilers.getLinker())
272    self.addMakeMacro('SL_LINKER_FLAGS','${PCC_LINKER_FLAGS}')
273    self.setCompilers.popLanguage()
274    # One of 'a', 'so', 'lib', 'dll', 'dylib' (perhaps others also?) depending on the library generator and architecture
275    # Note: . is not included in this macro, consistent with AR_LIB_SUFFIX
276    if self.setCompilers.sharedLibraryExt == self.setCompilers.AR_LIB_SUFFIX:
277      self.addMakeMacro('SL_LINKER_SUFFIX', '')
278      self.addDefine('SLSUFFIX','""')
279    else:
280      self.addMakeMacro('SL_LINKER_SUFFIX', self.setCompilers.sharedLibraryExt)
281      self.addDefine('SLSUFFIX','"'+self.setCompilers.sharedLibraryExt+'"')
282
283    self.addMakeMacro('SL_LINKER_LIBS','${PETSC_EXTERNAL_LIB_BASIC}')
284
285#-----------------------------------------------------------------------------------------------------
286
287    # CONLY or CPP. We should change the PETSc makefiles to do this better
288    if self.languages.clanguage == 'C': lang = 'CONLY'
289    else: lang = 'CXXONLY'
290    self.addMakeMacro('PETSC_LANGUAGE',lang)
291
292    # real or complex
293    self.addMakeMacro('PETSC_SCALAR',self.scalartypes.scalartype)
294    # double or float
295    self.addMakeMacro('PETSC_PRECISION',self.scalartypes.precision)
296
297    if self.framework.argDB['with-batch']:
298      self.addMakeMacro('PETSC_WITH_BATCH','1')
299
300    # Test for compiler-specific macros that need to be defined.
301    if self.setCompilers.isCrayVector('CC'):
302      self.addDefine('HAVE_CRAY_VECTOR','1')
303
304#-----------------------------------------------------------------------------------------------------
305    if self.functions.haveFunction('gethostbyname') and self.functions.haveFunction('socket') and self.headers.haveHeader('netinet/in.h'):
306      self.addDefine('USE_SOCKET_VIEWER','1')
307      if self.checkCompile('#include <sys/socket.h>','setsockopt(0,SOL_SOCKET,SO_REUSEADDR,0,0)'):
308        self.addDefine('HAVE_SO_REUSEADDR','1')
309
310#-----------------------------------------------------------------------------------------------------
311    # print include and lib for makefiles
312    self.framework.packages.reverse()
313    includes = [os.path.join(self.petscdir.dir,'include'),os.path.join(self.petscdir.dir,self.arch.arch,'include')]
314    libs = []
315    for i in self.framework.packages:
316      if i.useddirectly:
317        self.addDefine('HAVE_'+i.PACKAGE.replace('-','_'), 1)  # ONLY list package if it is used directly by PETSc (and not only by another package)
318      if not isinstance(i.lib, list):
319        i.lib = [i.lib]
320      libs.extend(i.lib)
321      self.addMakeMacro(i.PACKAGE.replace('-','_')+'_LIB', self.libraries.toStringNoDupes(i.lib))
322      if hasattr(i,'include'):
323        if not isinstance(i.include,list):
324          i.include = [i.include]
325        includes.extend(i.include)
326        self.addMakeMacro(i.PACKAGE.replace('-','_')+'_INCLUDE',self.headers.toStringNoDupes(i.include))
327    self.packagelibs = libs
328    if self.framework.argDB['with-single-library']:
329      self.alllibs = self.libraries.toStringNoDupes(['-L'+os.path.join(self.petscdir.dir,self.arch.arch,'lib'),' -lpetsc']+libs+self.libraries.math+self.compilers.flibs+self.compilers.cxxlibs+self.compilers.LIBS.split(' '))+self.CHUD.LIBS
330      self.addMakeMacro('PETSC_WITH_EXTERNAL_LIB',self.alllibs)
331    else:
332      self.alllibs = self.libraries.toStringNoDupes(['-L'+os.path.join(self.petscdir.dir,self.arch.arch,'lib'),'-lpetscts -lpetscsnes -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetscsys']+libs+self.libraries.math+self.compilers.flibs+self.compilers.cxxlibs+self.compilers.LIBS.split(' '))+self.CHUD.LIBS
333    self.addMakeMacro('PETSC_EXTERNAL_LIB_BASIC',self.libraries.toStringNoDupes(libs+self.libraries.math+self.compilers.flibs+self.compilers.cxxlibs+self.compilers.LIBS.split(' '))+self.CHUD.LIBS)
334    self.PETSC_EXTERNAL_LIB_BASIC = self.libraries.toStringNoDupes(libs+self.libraries.math+self.compilers.flibs+self.compilers.cxxlibs+self.compilers.LIBS.split(' '))+self.CHUD.LIBS
335    self.allincludes = self.headers.toStringNoDupes(includes)
336    self.addMakeMacro('PETSC_CC_INCLUDES',self.allincludes)
337    self.PETSC_CC_INCLUDES = self.allincludes
338    if hasattr(self.compilers, 'FC'):
339      if self.compilers.fortranIsF90:
340        self.addMakeMacro('PETSC_FC_INCLUDES',self.headers.toStringNoDupes(includes,includes))
341      else:
342        self.addMakeMacro('PETSC_FC_INCLUDES',self.headers.toStringNoDupes(includes))
343
344    self.addMakeMacro('DESTDIR',self.installdir)
345    self.addDefine('LIB_DIR','"'+os.path.join(self.installdir,'lib')+'"')
346
347    if self.framework.argDB['with-single-library']:
348      # overrides the values set in conf/variables
349      self.addMakeMacro('LIBNAME','${INSTALL_LIB_DIR}/libpetsc.${AR_LIB_SUFFIX}')
350      self.addMakeMacro('SHLIBS','libpetsc')
351      self.addMakeMacro('PETSC_LIB_BASIC','-lpetsc')
352      self.addMakeMacro('PETSC_KSP_LIB_BASIC','-lpetsc')
353      self.addMakeMacro('PETSC_TS_LIB_BASIC','-lpetsc')
354      self.addDefine('USE_SINGLE_LIBRARY', '1')
355      if self.sharedlibraries.useShared:
356        self.addMakeMacro('PETSC_SYS_LIB','${C_SH_LIB_PATH} ${PETSC_WITH_EXTERNAL_LIB}')
357        self.addMakeMacro('PETSC_VEC_LIB','${C_SH_LIB_PATH} ${PETSC_WITH_EXTERNAL_LIB}')
358        self.addMakeMacro('PETSC_MAT_LIB','${C_SH_LIB_PATH} ${PETSC_WITH_EXTERNAL_LIB}')
359        self.addMakeMacro('PETSC_DM_LIB','${C_SH_LIB_PATH} ${PETSC_WITH_EXTERNAL_LIB}')
360        self.addMakeMacro('PETSC_KSP_LIB','${C_SH_LIB_PATH} ${PETSC_WITH_EXTERNAL_LIB}')
361        self.addMakeMacro('PETSC_SNES_LIB','${C_SH_LIB_PATH} ${PETSC_WITH_EXTERNAL_LIB}')
362        self.addMakeMacro('PETSC_TS_LIB','${C_SH_LIB_PATH} ${PETSC_WITH_EXTERNAL_LIB}')
363        self.addMakeMacro('PETSC_CHARACTERISTIC_LIB','${C_SH_LIB_PATH} ${PETSC_WITH_EXTERNAL_LIB}')
364        self.addMakeMacro('PETSC_LIB','${C_SH_LIB_PATH} ${PETSC_WITH_EXTERNAL_LIB}')
365        self.addMakeMacro('PETSC_CONTRIB','${C_SH_LIB_PATH} ${PETSC_WITH_EXTERNAL_LIB}')
366      else:
367        self.addMakeMacro('PETSC_SYS_LIB','${PETSC_WITH_EXTERNAL_LIB}')
368        self.addMakeMacro('PETSC_VEC_LIB','${PETSC_WITH_EXTERNAL_LIB}')
369        self.addMakeMacro('PETSC_MAT_LIB','${PETSC_WITH_EXTERNAL_LIB}')
370        self.addMakeMacro('PETSC_DM_LIB','${PETSC_WITH_EXTERNAL_LIB}')
371        self.addMakeMacro('PETSC_KSP_LIB','${PETSC_WITH_EXTERNAL_LIB}')
372        self.addMakeMacro('PETSC_SNES_LIB','${PETSC_WITH_EXTERNAL_LIB}')
373        self.addMakeMacro('PETSC_TS_LIB','${PETSC_WITH_EXTERNAL_LIB}')
374        self.addMakeMacro('PETSC_CHARACTERISTIC_LIB','${PETSC_WITH_EXTERNAL_LIB}')
375        self.addMakeMacro('PETSC_LIB','${PETSC_WITH_EXTERNAL_LIB}')
376        self.addMakeMacro('PETSC_CONTRIB','${PETSC_WITH_EXTERNAL_LIB}')
377
378    if not os.path.exists(os.path.join(self.petscdir.dir,self.arch.arch,'lib')):
379      os.makedirs(os.path.join(self.petscdir.dir,self.arch.arch,'lib'))
380
381    # add a makefile entry for configure options
382    self.addMakeMacro('CONFIGURE_OPTIONS', self.framework.getOptionsString(['configModules', 'optionsModule']).replace('\"','\\"'))
383    return
384
385  def dumpConfigInfo(self):
386    import time
387    fd = file(os.path.join(self.arch.arch,'include','petscconfiginfo.h'),'w')
388    fd.write('static const char *petscconfigureruntime = "'+time.ctime(time.time())+'";\n')
389    fd.write('static const char *petscconfigureoptions = "'+self.framework.getOptionsString(['configModules', 'optionsModule']).replace('\"','\\"')+'";\n')
390    fd.close()
391    return
392
393  def dumpMachineInfo(self):
394    import platform
395    import time
396    import script
397    def escape(s):
398      return s.replace('"',r'\"').replace(r'\ ',r'\\ ')
399    fd = file(os.path.join(self.arch.arch,'include','petscmachineinfo.h'),'w')
400    fd.write('static const char *petscmachineinfo = \"\\n\"\n')
401    fd.write('\"-----------------------------------------\\n\"\n')
402    fd.write('\"Libraries compiled on %s on %s \\n\"\n' % (time.ctime(time.time()), platform.node()))
403    fd.write('\"Machine characteristics: %s\\n\"\n' % (platform.platform()))
404    fd.write('\"Using PETSc directory: %s\\n\"\n' % (escape(self.petscdir.dir)))
405    fd.write('\"Using PETSc arch: %s\\n\"\n' % (escape(self.arch.arch)))
406    fd.write('\"-----------------------------------------\\n\";\n')
407    fd.write('static const char *petsccompilerinfo = \"\\n\"\n')
408    self.setCompilers.pushLanguage(self.languages.clanguage)
409    fd.write('\"Using C compiler: %s %s ${COPTFLAGS} ${CFLAGS}\\n\"\n' % (escape(self.setCompilers.getCompiler()), escape(self.setCompilers.getCompilerFlags())))
410    self.setCompilers.popLanguage()
411    if hasattr(self.compilers, 'FC'):
412      self.setCompilers.pushLanguage('FC')
413      fd.write('\"Using Fortran compiler: %s %s ${FOPTFLAGS} ${FFLAGS} %s\\n\"\n' % (escape(self.setCompilers.getCompiler()), escape(self.setCompilers.getCompilerFlags()), escape(self.setCompilers.CPPFLAGS)))
414      self.setCompilers.popLanguage()
415    fd.write('\"-----------------------------------------\\n\";\n')
416    fd.write('static const char *petsccompilerflagsinfo = \"\\n\"\n')
417    fd.write('\"Using include paths: %s %s %s\\n\"\n' % ('-I'+escape(os.path.join(self.petscdir.dir, self.arch.arch, 'include')), '-I'+escape(os.path.join(self.petscdir.dir, 'include')), escape(self.PETSC_CC_INCLUDES)))
418    fd.write('\"-----------------------------------------\\n\";\n')
419    fd.write('static const char *petsclinkerinfo = \"\\n\"\n')
420    self.setCompilers.pushLanguage(self.languages.clanguage)
421    fd.write('\"Using C linker: %s\\n\"\n' % (escape(self.setCompilers.getLinker())))
422    self.setCompilers.popLanguage()
423    if hasattr(self.compilers, 'FC'):
424      self.setCompilers.pushLanguage('FC')
425      fd.write('\"Using Fortran linker: %s\\n\"\n' % (escape(self.setCompilers.getLinker())))
426      self.setCompilers.popLanguage()
427    if self.framework.argDB['with-single-library']:
428      petsclib = '-lpetsc'
429    else:
430      petsclib = '-lpetscts -lpetscsnes -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetscsys'
431    fd.write('\"Using libraries: %s%s -L%s %s %s\\n\"\n' % (escape(self.setCompilers.CSharedLinkerFlag), escape(os.path.join(self.petscdir.dir, self.arch.arch, 'lib')), escape(os.path.join(self.petscdir.dir, self.arch.arch, 'lib')), escape(petsclib), escape(self.PETSC_EXTERNAL_LIB_BASIC)))
432    fd.write('\"-----------------------------------------\\n\";\n')
433    fd.close()
434    return
435
436  def dumpCMakeConfig(self):
437    '''
438    Writes configuration-specific values to ${PETSC_ARCH}/conf/PETScConfig.cmake.
439    This file is private to PETSc and should not be included by third parties
440    (a suitable file can be produced later by CMake, but this is not it).
441    '''
442    def cmakeset(fd,key,val=True):
443      if val == True: val = 'YES'
444      if val == False: val = 'NO'
445      fd.write('set (' + key + ' ' + val + ')\n')
446    def ensurelist(a):
447      if isinstance(a,list):
448        return a
449      else:
450        return [a]
451    def libpath(lib):
452      'Returns a search path if that is what this item provides, else "" which will be cleaned out later'
453      if not isinstance(lib,str): return ''
454      if lib.startswith('-L'): return lib[2:]
455      if lib.startswith('-R'): return lib[2:]
456      if lib.startswith('-Wl,-rpath,'):
457        # This case occurs when an external package needs a specific system library that is normally provided by the compiler.
458        # In other words, the -L path is builtin to the wrapper or compiler, here we provide it so that CMake can locate the
459        # corresponding library.
460        return lib[len('-Wl,-rpath,'):]
461      if lib.startswith('-'): return ''
462      return os.path.dirname(lib)
463    def cleanlib(lib):
464      'Returns a library name if that is what this item provides, else "" which will be cleaned out later'
465      if not isinstance(lib,str): return ''
466      if lib.startswith('-l'):  return lib[2:]
467      if lib.startswith('-Wl') or lib.startswith('-L'): return ''
468      lib = os.path.splitext(os.path.basename(lib))[0]
469      if lib.startswith('lib'): return lib[3:]
470      return lib
471    def nub(lst):
472      'Return a list containing the first occurrence of each unique element'
473      unique = []
474      for elem in lst:
475        if elem not in unique and elem != '':
476          unique.append(elem)
477      return unique
478    try: reversed # reversed was added in Python-2.4
479    except NameError:
480      def reversed(lst): return lst[::-1]
481    def nublast(lst):
482      'Return a list containing the last occurrence of each unique entry in a list'
483      return reversed(nub(reversed(lst)))
484    def cmakeexpand(varname):
485      return r'"${' + varname + r'}"'
486    def uniqextend(lst,new):
487      for x in ensurelist(new):
488        if x not in lst:
489          lst.append(x)
490    def notstandardinclude(path):
491      return path not in '/usr/include'.split() # /usr/local/include is not automatically included on FreeBSD
492    def writeMacroDefinitions(fd):
493      if self.mpi.usingMPIUni:
494        cmakeset(fd,'PETSC_HAVE_MPIUNI')
495      for pkg in self.framework.packages:
496        if pkg.useddirectly:
497          cmakeset(fd,'PETSC_HAVE_' + pkg.PACKAGE.replace('-','_'))
498        for pair in pkg.defines.items():
499          if pair[0].startswith('HAVE_') and pair[1]:
500            cmakeset(fd, self.framework.getFullDefineName(pkg, pair[0]), pair[1])
501      for name,val in self.functions.defines.items():
502        cmakeset(fd,'PETSC_'+name,val)
503      for dct in [self.defines, self.libraryoptions.defines]:
504        for k,v in dct.items():
505          if k.startswith('USE_'):
506            cmakeset(fd,'PETSC_' + k, v)
507      cmakeset(fd,'PETSC_USE_COMPLEX', self.scalartypes.scalartype == 'complex')
508      cmakeset(fd,'PETSC_USE_REAL_' + self.scalartypes.precision.upper())
509      cmakeset(fd,'PETSC_CLANGUAGE_'+self.languages.clanguage)
510      if hasattr(self.compilers, 'FC'):
511        cmakeset(fd,'PETSC_HAVE_FORTRAN')
512        if self.compilers.fortranIsF90:
513          cmakeset(fd,'PETSC_USING_F90')
514        if self.compilers.fortranIsF2003:
515          cmakeset(fd,'PETSC_USING_F2003')
516      if hasattr(self.compilers, 'CXX'):
517        cmakeset(fd,'PETSC_HAVE_CXX')
518      if self.sharedlibraries.useShared:
519        cmakeset(fd,'BUILD_SHARED_LIBS')
520    def writeBuildFlags(fd):
521      def extendby(lib):
522        libs = ensurelist(lib)
523        lib_paths.extend(map(libpath,libs))
524        lib_libs.extend(map(cleanlib,libs))
525      lib_paths = []
526      lib_libs  = []
527      includes  = []
528      libvars   = []
529      for pkg in self.framework.packages:
530        extendby(pkg.lib)
531        uniqextend(includes,pkg.include)
532      extendby(self.libraries.math)
533      extendby(self.libraries.rt)
534      extendby(self.compilers.flibs)
535      extendby(self.compilers.cxxlibs)
536      extendby(self.compilers.LIBS.split())
537      for libname in nublast(lib_libs):
538        libvar = 'PETSC_' + libname.upper() + '_LIB'
539        addpath = ''
540        for lpath in nublast(lib_paths):
541          addpath += '"' + str(lpath) + '" '
542        fd.write('find_library (' + libvar + ' ' + libname + ' HINTS ' + addpath + ')\n')
543        libvars.append(libvar)
544      fd.write('mark_as_advanced (' + ' '.join(libvars) + ')\n')
545      fd.write('set (PETSC_PACKAGE_LIBS ' + ' '.join(map(cmakeexpand,libvars)) + ')\n')
546      includes = filter(notstandardinclude,includes)
547      fd.write('set (PETSC_PACKAGE_INCLUDES ' + ' '.join(map(lambda i: '"'+i+'"',includes)) + ')\n')
548    fd = open(os.path.join(self.arch.arch,'conf','PETScConfig.cmake'), 'w')
549    writeMacroDefinitions(fd)
550    writeBuildFlags(fd)
551    fd.close()
552    return
553
554  def dumpCMakeLists(self):
555    import sys
556    if sys.version_info >= (2,4):
557      import cmakegen
558      try:
559        cmakegen.main(self.petscdir.dir, log=self.framework.log)
560      except (OSError), e:
561        self.framework.logPrint('Generating CMakeLists.txt failed:\n' + str(e))
562    else:
563      self.framework.logPrint('Skipping cmakegen due to old python version: ' +str(sys.version_info) )
564
565  def cmakeBoot(self):
566    import sys
567    self.cmakeboot_success = False
568    if sys.version_info >= (2,4) and hasattr(self.cmake,'cmake'):
569      try:
570        import cmakeboot
571        self.cmakeboot_success = cmakeboot.main(petscdir=self.petscdir.dir,petscarch=self.arch.arch,argDB=self.argDB,framework=self.framework,log=self.framework.log)
572      except (OSError), e:
573        self.framework.logPrint('Booting CMake in PETSC_ARCH failed:\n' + str(e))
574      except (ImportError, KeyError), e:
575        self.framework.logPrint('Importing cmakeboot failed:\n' + str(e))
576      if self.cmakeboot_success:
577        if hasattr(self.compilers, 'FC') and self.compilers.fortranIsF90 and not self.setCompilers.fortranModuleOutputFlag:
578          self.framework.logPrint('CMake configured successfully, but could not be used by default because of missing fortranModuleOutputFlag\n')
579        else:
580          self.framework.logPrint('CMake configured successfully, using as default build\n')
581          self.addMakeMacro('PETSC_BUILD_USING_CMAKE',1)
582      else:
583        self.framework.logPrint('CMake configuration was unsuccessful\n')
584    else:
585      self.framework.logPrint('Skipping cmakeboot due to old python version: ' +str(sys.version_info) )
586    return
587
588  def configurePrefetch(self):
589    '''Sees if there are any prefetch functions supported'''
590    if config.setCompilers.Configure.isSolaris() or self.framework.argDB['with-ios']:
591      self.addDefine('Prefetch(a,b,c)', ' ')
592      return
593    self.pushLanguage(self.languages.clanguage)
594    if self.checkLink('#include <xmmintrin.h>', 'void *v = 0;_mm_prefetch((const char*)v,_MM_HINT_NTA);\n'):
595      # The Intel Intrinsics manual [1] specifies the prototype
596      #
597      #   void _mm_prefetch(char const *a, int sel);
598      #
599      # but other vendors seem to insist on using subtly different
600      # prototypes, including void* for the pointer, and an enum for
601      # sel.  These are both reasonable changes, but negatively impact
602      # portability.
603      #
604      # [1] http://software.intel.com/file/6373
605      self.addDefine('HAVE_XMMINTRIN_H', 1)
606      self.addDefine('Prefetch(a,b,c)', '_mm_prefetch((const char*)(a),(c))')
607      self.addDefine('PREFETCH_HINT_NTA', '_MM_HINT_NTA')
608      self.addDefine('PREFETCH_HINT_T0',  '_MM_HINT_T0')
609      self.addDefine('PREFETCH_HINT_T1',  '_MM_HINT_T1')
610      self.addDefine('PREFETCH_HINT_T2',  '_MM_HINT_T2')
611    elif self.checkLink('#include <xmmintrin.h>', 'void *v = 0;_mm_prefetch(v,_MM_HINT_NTA);\n'):
612      self.addDefine('HAVE_XMMINTRIN_H', 1)
613      self.addDefine('Prefetch(a,b,c)', '_mm_prefetch((const void*)(a),(c))')
614      self.addDefine('PREFETCH_HINT_NTA', '_MM_HINT_NTA')
615      self.addDefine('PREFETCH_HINT_T0',  '_MM_HINT_T0')
616      self.addDefine('PREFETCH_HINT_T1',  '_MM_HINT_T1')
617      self.addDefine('PREFETCH_HINT_T2',  '_MM_HINT_T2')
618    elif self.checkLink('', 'void *v = 0;__builtin_prefetch(v,0,0);\n'):
619      # From GCC docs: void __builtin_prefetch(const void *addr,int rw,int locality)
620      #
621      #   The value of rw is a compile-time constant one or zero; one
622      #   means that the prefetch is preparing for a write to the memory
623      #   address and zero, the default, means that the prefetch is
624      #   preparing for a read. The value locality must be a compile-time
625      #   constant integer between zero and three. A value of zero means
626      #   that the data has no temporal locality, so it need not be left
627      #   in the cache after the access. A value of three means that the
628      #   data has a high degree of temporal locality and should be left
629      #   in all levels of cache possible. Values of one and two mean,
630      #   respectively, a low or moderate degree of temporal locality.
631      #
632      # Here we adopt Intel's x86/x86-64 naming scheme for the locality
633      # hints.  Using macros for these values in necessary since some
634      # compilers require an enum.
635      self.addDefine('Prefetch(a,b,c)', '__builtin_prefetch((a),(b),(c))')
636      self.addDefine('PREFETCH_HINT_NTA', '0')
637      self.addDefine('PREFETCH_HINT_T0',  '3')
638      self.addDefine('PREFETCH_HINT_T1',  '2')
639      self.addDefine('PREFETCH_HINT_T2',  '1')
640    else:
641      self.addDefine('Prefetch(a,b,c)', ' ')
642    self.popLanguage()
643
644  def configureFeatureTestMacros(self):
645    '''Checks if certain feature test macros are support'''
646    if self.checkCompile('#define _POSIX_C_SOURCE 200112L\n#include <sysctl.h>',''):
647       self.addDefine('_POSIX_C_SOURCE_200112L', '1')
648    if self.checkCompile('#define _BSD_SOURCE\n#include<stdlib.h>',''):
649       self.addDefine('_BSD_SOURCE', '1')
650    if self.checkCompile('#define _GNU_SOURCE\n#include <sched.h>','cpu_set_t mset;\nCPU_ZERO(&mset);'):
651       self.addDefine('_GNU_SOURCE', '1')
652
653  def configureAtoll(self):
654    '''Checks if atoll exists'''
655    if self.checkLink('#define _POSIX_C_SOURCE 200112L\n#include <stdlib.h>','long v = atoll("25")') or self.checkLink ('#include <stdlib.h>','long v = atoll("25")'):
656       self.addDefine('HAVE_ATOLL', '1')
657
658  def configureUnused(self):
659    '''Sees if __attribute((unused)) is supported'''
660    if self.framework.argDB['with-ios']:
661      self.addDefine('UNUSED', ' ')
662      return
663    self.pushLanguage(self.languages.clanguage)
664    if self.checkLink('__attribute((unused)) static int myfunc(__attribute((unused)) void *name){ return 1;}', 'int i = 0;\nint j = myfunc(&i);\ntypedef void* atype;\n__attribute((unused))  atype a;\n'):
665      self.addDefine('UNUSED', '__attribute((unused))')
666    else:
667      self.addDefine('UNUSED', ' ')
668    self.popLanguage()
669
670  def configureDeprecated(self):
671    '''Check if __attribute((deprecated)) is supported'''
672    self.pushLanguage(self.languages.clanguage)
673    ## Recent versions of gcc and clang support __attribute((deprecated("string argument"))), which is very useful, but
674    ## Intel has conspired to make a supremely environment-sensitive compiler.  The Intel compiler looks at the gcc
675    ## executable in the environment to determine the language compatibility that it should attempt to emulate.  Some
676    ## important Cray installations have built PETSc using the Intel compiler, but with a newer gcc module loaded (e.g.,
677    ## 4.7).  Thus at PETSc configure time, the Intel compiler decides to support the string argument, but the the gcc
678    ## found in the default user environment is older and does not support the argument.  If GCC and Intel were cool
679    ## like Clang and supported __has_attribute, we could avoid configure tests entirely, but they don't.  And that is
680    ## why we can't have nice things.
681    #
682    # if self.checkCompile("""__attribute((deprecated("Why you shouldn't use myfunc"))) static int myfunc(void) { return 1;}""", ''):
683    #   self.addDefine('DEPRECATED(why)', '__attribute((deprecated(why)))')
684    if self.checkCompile("""__attribute((deprecated)) static int myfunc(void) { return 1;}""", ''):
685      self.addDefine('DEPRECATED(why)', '__attribute((deprecated))')
686    else:
687      self.addDefine('DEPRECATED(why)', ' ')
688    self.popLanguage()
689
690  def configureExpect(self):
691    '''Sees if the __builtin_expect directive is supported'''
692    self.pushLanguage(self.languages.clanguage)
693    if self.checkLink('', 'if (__builtin_expect(0,1)) return 1;'):
694      self.addDefine('HAVE_BUILTIN_EXPECT', 1)
695    self.popLanguage()
696
697  def configureFunctionName(self):
698    '''Sees if the compiler supports __func__ or a variant.  Falls back
699    on __FUNCT__ which PETSc source defines, but most users do not, thus
700    stack traces through user code are better when the compiler's
701    variant is used.'''
702    def getFunctionName(lang):
703      name = '__FUNCT__'
704      self.pushLanguage(lang)
705      if self.checkLink('', "if (__func__[0] != 'm') return 1;"):
706        name = '__func__'
707      elif self.checkLink('', "if (__FUNCTION__[0] != 'm') return 1;"):
708        name = '__FUNCTION__'
709      self.popLanguage()
710      return name
711    langs = []
712
713    self.addDefine('FUNCTION_NAME_C', getFunctionName('C'))
714    if hasattr(self.compilers, 'CXX'):
715      self.addDefine('FUNCTION_NAME_CXX', getFunctionName('Cxx'))
716    else:
717      self.addDefine('FUNCTION_NAME_CXX', '__FUNCT__')
718
719  def configureIntptrt(self):
720    '''Determine what to use for uintptr_t'''
721    def staticAssertSizeMatchesVoidStar(inc,typename):
722      # The declaration is an error if either array size is negative.
723      # It should be okay to use an int that is too large, but it would be very unlikely for this to be the case
724      return self.checkCompile(inc, ('#define STATIC_ASSERT(cond) char negative_length_if_false[2*(!!(cond))-1]\n'
725                                     + 'STATIC_ASSERT(sizeof(void*) == sizeof(%s));'%typename))
726    self.pushLanguage(self.languages.clanguage)
727    if self.checkCompile('#include <stdint.h>', 'int x; uintptr_t i = (uintptr_t)&x;'):
728      self.addDefine('UINTPTR_T', 'uintptr_t')
729    elif staticAssertSizeMatchesVoidStar('','unsigned long long'):
730      self.addDefine('UINTPTR_T', 'unsigned long long')
731    elif staticAssertSizeMatchesVoidStar('#include <stdlib.h>','size_t') or staticAssertSizeMatchesVoidStar('#include <string.h>', 'size_t'):
732      self.addDefine('UINTPTR_T', 'size_t')
733    elif staticAssertSizeMatchesVoidStar('','unsigned long'):
734      self.addDefine('UINTPTR_T', 'unsigned long')
735    elif staticAssertSizeMatchesVoidStar('','unsigned'):
736      self.addDefine('UINTPTR_T', 'unsigned')
737    else:
738      raise RuntimeError('Could not find any unsigned integer type matching void*')
739    self.popLanguage()
740
741  def configureRTLDDefault(self):
742    if self.checkCompile('#include <dlfcn.h>\n void *ptr =  RTLD_DEFAULT;'):
743      self.addDefine('RTLD_DEFAULT','1')
744    return
745
746  def configureSolaris(self):
747    '''Solaris specific stuff'''
748    if os.path.isdir(os.path.join('/usr','ucblib')):
749      try:
750        flag = getattr(self.setCompilers, self.language[-1]+'SharedLinkerFlag')
751      except AttributeError:
752        flag = None
753      if flag is None:
754        self.compilers.LIBS += ' -L/usr/ucblib'
755      else:
756        self.compilers.LIBS += ' '+flag+'/usr/ucblib'
757    return
758
759  def configureLinux(self):
760    '''Linux specific stuff'''
761    # TODO: Test for this by mallocing an odd number of floats and checking the address
762    self.addDefine('HAVE_DOUBLE_ALIGN_MALLOC', 1)
763    return
764
765  def configureWin32(self):
766    '''Win32 non-cygwin specific stuff'''
767    kernel32=0
768    if self.libraries.add('Kernel32.lib','GetComputerName',prototype='#include <Windows.h>', call='GetComputerName(NULL,NULL);'):
769      self.addDefine('HAVE_WINDOWS_H',1)
770      self.addDefine('HAVE_GETCOMPUTERNAME',1)
771      kernel32=1
772    elif self.libraries.add('kernel32','GetComputerName',prototype='#include <Windows.h>', call='GetComputerName(NULL,NULL);'):
773      self.addDefine('HAVE_WINDOWS_H',1)
774      self.addDefine('HAVE_GETCOMPUTERNAME',1)
775      kernel32=1
776    if kernel32:
777      if self.framework.argDB['with-windows-graphics']:
778        self.addDefine('USE_WINDOWS_GRAPHICS',1)
779      if self.checkLink('#include <Windows.h>','LoadLibrary(0)'):
780        self.addDefine('HAVE_LOADLIBRARY',1)
781      if self.checkLink('#include <Windows.h>','GetProcAddress(0,0)'):
782        self.addDefine('HAVE_GETPROCADDRESS',1)
783      if self.checkLink('#include <Windows.h>','FreeLibrary(0)'):
784        self.addDefine('HAVE_FREELIBRARY',1)
785      if self.checkLink('#include <Windows.h>','GetLastError()'):
786        self.addDefine('HAVE_GETLASTERROR',1)
787      if self.checkLink('#include <Windows.h>','SetLastError(0)'):
788        self.addDefine('HAVE_SETLASTERROR',1)
789      if self.checkLink('#include <Windows.h>\n','QueryPerformanceCounter(0);\n'):
790        self.addDefine('USE_MICROSOFT_TIME',1)
791    if self.libraries.add('Advapi32.lib','GetUserName',prototype='#include <Windows.h>', call='GetUserName(NULL,NULL);'):
792      self.addDefine('HAVE_GET_USER_NAME',1)
793    elif self.libraries.add('advapi32','GetUserName',prototype='#include <Windows.h>', call='GetUserName(NULL,NULL);'):
794      self.addDefine('HAVE_GET_USER_NAME',1)
795
796    if not self.libraries.add('User32.lib','GetDC',prototype='#include <Windows.h>',call='GetDC(0);'):
797      self.libraries.add('user32','GetDC',prototype='#include <Windows.h>',call='GetDC(0);')
798    if not self.libraries.add('Gdi32.lib','CreateCompatibleDC',prototype='#include <Windows.h>',call='CreateCompatibleDC(0);'):
799      self.libraries.add('gdi32','CreateCompatibleDC',prototype='#include <Windows.h>',call='CreateCompatibleDC(0);')
800
801    self.types.check('int32_t', 'int')
802    if not self.checkCompile('#include <sys/types.h>\n','uid_t u;\n'):
803      self.addTypedef('int', 'uid_t')
804      self.addTypedef('int', 'gid_t')
805    if not self.checkLink('#if defined(PETSC_HAVE_UNISTD_H)\n#include <unistd.h>\n#endif\n','int a=R_OK;\n'):
806      self.framework.addDefine('R_OK', '04')
807      self.framework.addDefine('W_OK', '02')
808      self.framework.addDefine('X_OK', '01')
809    if not self.checkLink('#include <sys/stat.h>\n','int a=0;\nif (S_ISDIR(a)){}\n'):
810      self.framework.addDefine('S_ISREG(a)', '(((a)&_S_IFMT) == _S_IFREG)')
811      self.framework.addDefine('S_ISDIR(a)', '(((a)&_S_IFMT) == _S_IFDIR)')
812    if self.checkCompile('#include <Windows.h>\n','LARGE_INTEGER a;\nDWORD b=a.u.HighPart;\n'):
813      self.addDefine('HAVE_LARGE_INTEGER_U',1)
814
815    # Windows requires a Binary file creation flag when creating/opening binary files.  Is a better test in order?
816    if self.checkCompile('#include <Windows.h>\n#include <fcntl.h>\n', 'int flags = O_BINARY;'):
817      self.addDefine('HAVE_O_BINARY',1)
818
819    if self.compilers.CC.find('win32fe') >= 0:
820      self.addDefine('PATH_SEPARATOR','\';\'')
821      self.addDefine('DIR_SEPARATOR','\'\\\\\'')
822      self.addDefine('REPLACE_DIR_SEPARATOR','\'/\'')
823      self.addDefine('CANNOT_START_DEBUGGER',1)
824    else:
825      self.addDefine('PATH_SEPARATOR','\':\'')
826      self.addDefine('REPLACE_DIR_SEPARATOR','\'\\\\\'')
827      self.addDefine('DIR_SEPARATOR','\'/\'')
828
829    return
830
831#-----------------------------------------------------------------------------------------------------
832  def configureCygwinBrokenPipe(self):
833    '''Cygwin version <= 1.7.18 had issues with pipes and long commands invoked from gnu-make
834    http://cygwin.com/ml/cygwin/2013-05/msg00340.html '''
835    if config.setCompilers.Configure.isCygwin():
836      import platform
837      import re
838      r=re.compile("([0-9]+).([0-9]+).([0-9]+)")
839      m=r.match(platform.release())
840      major=int(m.group(1))
841      minor=int(m.group(2))
842      subminor=int(m.group(3))
843      if ((major < 1) or (major == 1 and minor < 7) or (major == 1 and minor == 7 and subminor <= 18)):
844        self.addMakeMacro('PETSC_CYGWIN_BROKEN_PIPE','1')
845    return
846
847#-----------------------------------------------------------------------------------------------------
848  def configureDefaultArch(self):
849    conffile = os.path.join('conf', 'petscvariables')
850    if self.framework.argDB['with-default-arch']:
851      fd = file(conffile, 'w')
852      fd.write('PETSC_ARCH='+self.arch.arch+'\n')
853      fd.write('PETSC_DIR='+self.petscdir.dir+'\n')
854      fd.write('include '+os.path.join(self.petscdir.dir,self.arch.arch,'conf','petscvariables')+'\n')
855      fd.close()
856      self.framework.actions.addArgument('PETSc', 'Build', 'Set default architecture to '+self.arch.arch+' in '+conffile)
857    elif os.path.isfile(conffile):
858      try:
859        os.unlink(conffile)
860      except:
861        raise RuntimeError('Unable to remove file '+conffile+'. Did a different user create it?')
862    return
863
864#-----------------------------------------------------------------------------------------------------
865  def configureScript(self):
866    '''Output a script in the conf directory which will reproduce the configuration'''
867    import nargs
868    import sys
869    scriptName = os.path.join(self.arch.arch,'conf', 'reconfigure-'+self.arch.arch+'.py')
870    args = dict([(nargs.Arg.parseArgument(arg)[0], arg) for arg in self.framework.clArgs])
871    if 'with-clean' in args:
872      del args['with-clean']
873    if 'configModules' in args:
874      if nargs.Arg.parseArgument(args['configModules'])[1] == 'PETSc.Configure':
875        del args['configModules']
876    if 'optionsModule' in args:
877      if nargs.Arg.parseArgument(args['optionsModule'])[1] == 'PETSc.compilerOptions':
878        del args['optionsModule']
879    if not 'PETSC_ARCH' in args:
880      args['PETSC_ARCH'] = 'PETSC_ARCH='+str(self.arch.arch)
881    f = file(scriptName, 'w')
882    f.write('#!'+sys.executable+'\n')
883    f.write('if __name__ == \'__main__\':\n')
884    f.write('  import sys\n')
885    f.write('  import os\n')
886    f.write('  sys.path.insert(0, os.path.abspath(\'config\'))\n')
887    f.write('  import configure\n')
888    # pretty print repr(args.values())
889    f.write('  configure_options = [\n')
890    for itm in sorted(args.values()):
891      f.write('    \''+str(itm)+'\',\n')
892    f.write('  ]\n')
893    f.write('  configure.petsc_configure(configure_options)\n')
894    f.close()
895    try:
896      os.chmod(scriptName, 0775)
897    except OSError, e:
898      self.framework.logPrint('Unable to make reconfigure script executable:\n'+str(e))
899    self.framework.actions.addArgument('PETSc', 'File creation', 'Created '+scriptName+' for automatic reconfiguration')
900    return
901
902  def configureInstall(self):
903    '''Setup the directories for installation'''
904    if self.framework.argDB['prefix']:
905      self.installdir = self.framework.argDB['prefix']
906      self.addMakeRule('shared_install','',['-@echo "Now to install the libraries do:"',\
907                                              '-@echo "make PETSC_DIR=${PETSC_DIR} PETSC_ARCH=${PETSC_ARCH} install"',\
908                                              '-@echo "========================================="'])
909    else:
910      self.installdir = os.path.join(self.petscdir.dir,self.arch.arch)
911      self.addMakeRule('shared_install','',['-@echo "Now to check if the libraries are working do:"',\
912                                              '-@echo "make PETSC_DIR=${PETSC_DIR} PETSC_ARCH=${PETSC_ARCH} test"',\
913                                              '-@echo "========================================="'])
914      return
915
916  def configureGCOV(self):
917    if self.framework.argDB['with-gcov']:
918      self.addDefine('USE_GCOV','1')
919    return
920
921  def configureFortranFlush(self):
922    if hasattr(self.compilers, 'FC'):
923      for baseName in ['flush','flush_']:
924        if self.libraries.check('', baseName, otherLibs = self.compilers.flibs, fortranMangle = 1):
925          self.addDefine('HAVE_'+baseName.upper(), 1)
926          return
927
928  def postProcessPackages(self):
929    postPackages=[]
930    for i in self.framework.packages:
931      if hasattr(i,'postProcess'): postPackages.append(i)
932    if postPackages:
933      # ctetgen needs petsc conf files. so attempt to create them early
934      self.framework.dumpConfFiles()
935      for i in postPackages: i.postProcess()
936    return
937
938  def configure(self):
939    if not os.path.samefile(self.petscdir.dir, os.getcwd()):
940      raise RuntimeError('Wrong PETSC_DIR option specified: '+str(self.petscdir.dir) + '\n  Configure invoked in: '+os.path.realpath(os.getcwd()))
941    if self.framework.argDB['prefix'] and os.path.isdir(self.framework.argDB['prefix']) and os.path.samefile(self.framework.argDB['prefix'],self.petscdir.dir):
942      raise RuntimeError('Incorrect option --prefix='+self.framework.argDB['prefix']+' specified. It cannot be same as PETSC_DIR!')
943    if self.framework.argDB['prefix'] and os.path.isdir(self.framework.argDB['prefix']) and os.path.samefile(self.framework.argDB['prefix'],os.path.join(self.petscdir.dir,self.arch.arch)):
944      raise RuntimeError('Incorrect option --prefix='+self.framework.argDB['prefix']+' specified. It cannot be same as PETSC_DIR/PETSC_ARCH!')
945    self.framework.header          = os.path.join(self.arch.arch,'include','petscconf.h')
946    self.framework.cHeader         = os.path.join(self.arch.arch,'include','petscfix.h')
947    self.framework.makeMacroHeader = os.path.join(self.arch.arch,'conf','petscvariables')
948    self.framework.makeRuleHeader  = os.path.join(self.arch.arch,'conf','petscrules')
949    if self.libraries.math is None:
950      raise RuntimeError('PETSc requires a functional math library. Please send configure.log to petsc-maint@mcs.anl.gov.')
951    if self.languages.clanguage == 'Cxx' and not hasattr(self.compilers, 'CXX'):
952      raise RuntimeError('Cannot set C language to C++ without a functional C++ compiler.')
953    self.executeTest(self.configureRTLDDefault)
954    self.executeTest(self.configurePrefetch)
955    self.executeTest(self.configureUnused)
956    self.executeTest(self.configureDeprecated)
957    self.executeTest(self.configureExpect);
958    self.executeTest(self.configureFunctionName);
959    self.executeTest(self.configureIntptrt);
960    self.executeTest(self.configureSolaris)
961    self.executeTest(self.configureLinux)
962    self.executeTest(self.configureWin32)
963    self.executeTest(self.configureCygwinBrokenPipe)
964    self.executeTest(self.configureDefaultArch)
965    self.executeTest(self.configureScript)
966    self.executeTest(self.configureInstall)
967    self.executeTest(self.configureGCOV)
968    self.executeTest(self.configureFortranFlush)
969    self.executeTest(self.configureFeatureTestMacros)
970    self.executeTest(self.configureAtoll)
971    # dummy rules, always needed except for remote builds
972    self.addMakeRule('remote','')
973    self.addMakeRule('remoteclean','')
974
975    self.Dump()
976    self.dumpConfigInfo()
977    self.dumpMachineInfo()
978    self.postProcessPackages()
979    self.dumpCMakeConfig()
980    self.dumpCMakeLists()
981    self.cmakeBoot()
982    self.DumpPkgconfig()
983    self.DumpModule()
984    self.framework.log.write('================================================================================\n')
985    self.logClear()
986    return
987