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