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