Debian Codegraph @

scripts/mk_util.py

raw
1 ############################################
2 # Copyright (c) 2012 Microsoft Corporation
3 #
4 # Auxiliary scripts for generating Makefiles
5 # and Visual Studio project files.
6 #
7 # Author: Leonardo de Moura (leonardo)
8 ############################################
9 import io
10 import sys
11 import os
12 import re
13 import getopt
14 import shutil
15 from mk_exception import *
16 import mk_genfile_common
17 from fnmatch import fnmatch
18 import sysconfig
19 import compileall
20 import subprocess
21
22 def getenv(name, default):
23 try:
24 return os.environ[name].strip(' "\'')
25 except:
26 return default
27
28 CXX=getenv("CXX", None)
29 CC=getenv("CC", None)
30 CPPFLAGS=getenv("CPPFLAGS", "")
31 CXXFLAGS=getenv("CXXFLAGS", "")
32 AR=getenv("AR", "ar")
33 EXAMP_DEBUG_FLAG=''
34 LDFLAGS=getenv("LDFLAGS", "")
35 JNI_HOME=getenv("JNI_HOME", None)
36 OCAMLC=getenv("OCAMLC", "ocamlc")
37 OCAMLOPT=getenv("OCAMLOPT", "ocamlopt")
38 OCAML_LIB=getenv("OCAML_LIB", None)
39 OCAMLFIND=getenv("OCAMLFIND", "ocamlfind")
40 DOTNET="dotnet"
41 # Standard install directories relative to PREFIX
42 INSTALL_BIN_DIR=getenv("Z3_INSTALL_BIN_DIR", "bin")
43 INSTALL_LIB_DIR=getenv("Z3_INSTALL_LIB_DIR", "lib")
44 INSTALL_INCLUDE_DIR=getenv("Z3_INSTALL_INCLUDE_DIR", "include")
45 INSTALL_PKGCONFIG_DIR=getenv("Z3_INSTALL_PKGCONFIG_DIR", os.path.join(INSTALL_LIB_DIR, 'pkgconfig'))
46
47 CXX_COMPILERS=['g++', 'clang++']
48 C_COMPILERS=['gcc', 'clang']
49 JAVAC=None
50 JAR=None
51 PYTHON_PACKAGE_DIR=sysconfig.get_path('purelib')
52 BUILD_DIR='build'
53 REV_BUILD_DIR='..'
54 SRC_DIR='src'
55 EXAMPLE_DIR='examples'
56 # Required Components
57 Z3_DLL_COMPONENT='api_dll'
58 PATTERN_COMPONENT='pattern'
59 UTIL_COMPONENT='util'
60 API_COMPONENT='api'
61 DOTNET_COMPONENT='dotnet'
62 DOTNET_CORE_COMPONENT='dotnet'
63 JAVA_COMPONENT='java'
64 ML_COMPONENT='ml'
65 CPP_COMPONENT='cpp'
66 PYTHON_COMPONENT='python'
67 #####################
68 IS_WINDOWS=False
69 IS_LINUX=False
70 IS_HURD=False
71 IS_OSX=False
72 IS_ARCH_ARM64=False
73 IS_FREEBSD=False
74 IS_NETBSD=False
75 IS_OPENBSD=False
76 IS_SUNOS=False
77 IS_CYGWIN=False
78 IS_CYGWIN_MINGW=False
79 IS_MSYS2=False
80 VERBOSE=True
81 DEBUG_MODE=False
82 SHOW_CPPS = True
83 VS_X64 = False
84 VS_ARM = False
85 LINUX_X64 = True
86 ONLY_MAKEFILES = False
87 Z3PY_SRC_DIR=None
88 Z3JS_SRC_DIR=None
89 VS_PROJ = False
90 TRACE = False
91 PYTHON_ENABLED=False
92 DOTNET_CORE_ENABLED=False
93 DOTNET_KEY_FILE=getenv("Z3_DOTNET_KEY_FILE", None)
94 ASSEMBLY_VERSION=getenv("Z2_ASSEMBLY_VERSION", None)
95 JAVA_ENABLED=False
96 ML_ENABLED=False
97 PYTHON_INSTALL_ENABLED=False
98 STATIC_LIB=False
99 STATIC_BIN=False
100 VER_MAJOR=None
101 VER_MINOR=None
102 VER_BUILD=None
103 VER_TWEAK=None
104 PREFIX=sys.prefix
105 GMP=False
106 VS_PAR=False
107 VS_PAR_NUM=8
108 GPROF=False
109 GIT_HASH=False
110 GIT_DESCRIBE=False
111 SLOW_OPTIMIZE=False
112 LOG_SYNC=False
113 SINGLE_THREADED=False
114 GUARD_CF=False
115 ALWAYS_DYNAMIC_BASE=False
116
117 FPMATH="Default"
118 FPMATH_FLAGS="-mfpmath=sse -msse -msse2"
119 FPMATH_ENABLED=getenv("FPMATH_ENABLED", "True")
120
121
122 def check_output(cmd):
123 out = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
124 if out != None:
125 enc = sys.getdefaultencoding()
126 if enc != None: return out.decode(enc).rstrip('\r\n')
127 else: return out.rstrip('\r\n')
128 else:
129 return ""
130
131 def git_hash():
132 try:
133 branch = check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
134 r = check_output(['git', 'show-ref', '--abbrev=12', 'refs/heads/%s' % branch])
135 except:
136 raise MKException("Failed to retrieve git hash")
137 ls = r.split(' ')
138 if len(ls) != 2:
139 raise MKException("Unexpected git output " + r)
140 return ls[0]
141
142 def is_windows():
143 return IS_WINDOWS
144
145 def is_linux():
146 return IS_LINUX
147
148 def is_hurd():
149 return IS_HURD
150
151 def is_freebsd():
152 return IS_FREEBSD
153
154 def is_netbsd():
155 return IS_NETBSD
156
157 def is_openbsd():
158 return IS_OPENBSD
159
160 def is_sunos():
161 return IS_SUNOS
162
163 def is_osx():
164 return IS_OSX
165
166 def is_cygwin():
167 return IS_CYGWIN
168
169 def is_cygwin_mingw():
170 return IS_CYGWIN_MINGW
171
172 def is_msys2():
173 return IS_MSYS2
174
175 def norm_path(p):
176 return os.path.expanduser(os.path.normpath(p))
177
178 def which(program):
179 import os
180 def is_exe(fpath):
181 return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
182
183 fpath, fname = os.path.split(program)
184 if fpath:
185 if is_exe(program):
186 return program
187 else:
188 for path in getenv("PATH", "").split(os.pathsep):
189 exe_file = os.path.join(path, program)
190 if is_exe(exe_file):
191 return exe_file
192 return None
193
194 class TempFile:
195 def __init__(self, name):
196 try:
197 self.name = name
198 self.fname = open(name, 'w')
199 except:
200 raise MKException("Failed to create temporary file '%s'" % self.name)
201
202 def add(self, s):
203 self.fname.write(s)
204
205 def commit(self):
206 self.fname.close()
207
208 def __del__(self):
209 self.fname.close()
210 try:
211 os.remove(self.name)
212 except:
213 pass
214
215 def exec_cmd(cmd):
216 if isinstance(cmd, str):
217 cmd = cmd.split(' ')
218 new_cmd = []
219 first = True
220 for e in cmd:
221 if first:
222 first = False
223 new_cmd.append(e)
224 else:
225 if e != "":
226 se = e.split(' ')
227 if len(se) > 1:
228 for e2 in se:
229 if e2 != "":
230 new_cmd.append(e2)
231 else:
232 new_cmd.append(e)
233 cmd = new_cmd
234 null = open(os.devnull, 'wb')
235 try:
236 return subprocess.call(cmd, stdout=null, stderr=null)
237 except:
238 # Failed to create process
239 return 1
240 finally:
241 null.close()
242
243 # rm -f fname
244 def rmf(fname):
245 if os.path.exists(fname):
246 os.remove(fname)
247
248 def exec_compiler_cmd(cmd):
249 r = exec_cmd(cmd)
250 # Windows
251 rmf('a.exe')
252 # Unix
253 rmf('a.out')
254 # Emscripten
255 rmf('a.wasm')
256 rmf('a.worker.js')
257 return r
258
259 def test_cxx_compiler(cc):
260 if is_verbose():
261 print("Testing %s..." % cc)
262 t = TempFile('tst.cpp')
263 t.add('#include<iostream>\nint main() { return 0; }\n')
264 t.commit()
265 return exec_compiler_cmd([cc, CPPFLAGS, CXXFLAGS, 'tst.cpp', LDFLAGS]) == 0
266
267 def test_c_compiler(cc):
268 if is_verbose():
269 print("Testing %s..." % cc)
270 t = TempFile('tst.c')
271 t.add('#include<stdio.h>\nint main() { return 0; }\n')
272 t.commit()
273 return exec_compiler_cmd([cc, CPPFLAGS, 'tst.c', LDFLAGS]) == 0
274
275 def test_gmp(cc):
276 if is_verbose():
277 print("Testing GMP...")
278 t = TempFile('tstgmp.cpp')
279 t.add('#include<gmp.h>\nint main() { mpz_t t; mpz_init(t); mpz_clear(t); return 0; }\n')
280 t.commit()
281 return exec_compiler_cmd([cc, CPPFLAGS, 'tstgmp.cpp', LDFLAGS, '-lgmp']) == 0
282
283
284
285 def test_fpmath(cc):
286 global FPMATH_FLAGS, IS_ARCH_ARM64, IS_OSX
287 if FPMATH_ENABLED == "False":
288 FPMATH_FLAGS=""
289 return "Disabled"
290 if IS_ARCH_ARM64 and IS_OSX:
291 FPMATH_FLAGS = ""
292 return "Disabled-ARM64"
293 if is_verbose():
294 print("Testing floating point support...")
295 t = TempFile('tstsse.cpp')
296 t.add('int main() { return 42; }\n')
297 t.commit()
298 # -Werror is needed because some versions of clang warn about unrecognized
299 # -m flags.
300 # TODO(ritave): Safari doesn't allow SIMD WebAssembly extension, add a flag to build script
301 if exec_compiler_cmd([cc, CPPFLAGS, '-Werror', 'tstsse.cpp', LDFLAGS, '-msse -msse2 -msimd128']) == 0:
302 FPMATH_FLAGS='-msse -msse2 -msimd128'
303 return 'SSE2-EMSCRIPTEN'
304 if exec_compiler_cmd([cc, CPPFLAGS, '-Werror', 'tstsse.cpp', LDFLAGS, '-mfpmath=sse -msse -msse2']) == 0:
305 FPMATH_FLAGS="-mfpmath=sse -msse -msse2"
306 return "SSE2-GCC"
307 elif exec_compiler_cmd([cc, CPPFLAGS, '-Werror', 'tstsse.cpp', LDFLAGS, '-msse -msse2']) == 0:
308 FPMATH_FLAGS="-msse -msse2"
309 return "SSE2-CLANG"
310 elif exec_compiler_cmd([cc, CPPFLAGS, '-Werror', 'tstsse.cpp', LDFLAGS, '-mfpu=vfp -mfloat-abi=hard']) == 0:
311 FPMATH_FLAGS="-mfpu=vfp -mfloat-abi=hard"
312 return "ARM-VFP"
313 else:
314 FPMATH_FLAGS=""
315 return "UNKNOWN"
316
317 def test_atomic_required(cc):
318 t = TempFile('tstatomic.cpp')
319 t.add("""
320 #include <atomic>
321 std::atomic<int> x;
322 std::atomic<short> y;
323 std::atomic<char> z;
324 std::atomic<long long> w;
325 int main() {
326 ++z;
327 ++y;
328 ++w;
329 return ++x;
330 }
331 """)
332 t.commit()
333 fails_without = exec_compiler_cmd([cc, CPPFLAGS, '', 'tstatomic.cpp', LDFLAGS, '']) != 0
334 ok_with = exec_compiler_cmd([cc, CPPFLAGS, '', 'tstatomic.cpp', LDFLAGS + ' -latomic', '']) == 0
335 return fails_without and ok_with
336
337
338 def find_jni_h(path):
339 for root, dirs, files in os.walk(path):
340 for f in files:
341 if f == 'jni.h':
342 return root
343 return False
344
345 def check_java():
346 global JNI_HOME
347 global JAVAC
348 global JAR
349
350 JDK_HOME = getenv('JDK_HOME', None) # we only need to check this locally.
351
352 if is_verbose():
353 print("Finding javac ...")
354
355 if JDK_HOME is not None:
356 if IS_WINDOWS:
357 JAVAC = os.path.join(JDK_HOME, 'bin', 'javac.exe')
358 else:
359 JAVAC = os.path.join(JDK_HOME, 'bin', 'javac')
360
361 if not os.path.exists(JAVAC):
362 raise MKException("Failed to detect javac at '%s/bin'; the environment variable JDK_HOME is probably set to the wrong path." % os.path.join(JDK_HOME))
363 else:
364 # Search for javac in the path.
365 ind = 'javac'
366 if IS_WINDOWS:
367 ind = ind + '.exe'
368 paths = os.getenv('PATH', None)
369 if paths:
370 spaths = paths.split(os.pathsep)
371 for i in range(0, len(spaths)):
372 cmb = os.path.join(spaths[i], ind)
373 if os.path.exists(cmb):
374 JAVAC = cmb
375 break
376
377 if JAVAC is None:
378 raise MKException('No java compiler in the path, please adjust your PATH or set JDK_HOME to the location of the JDK.')
379
380 if is_verbose():
381 print("Finding jar ...")
382
383 if IS_WINDOWS:
384 JAR = os.path.join(os.path.dirname(JAVAC), 'jar.exe')
385 else:
386 JAR = os.path.join(os.path.dirname(JAVAC), 'jar')
387
388 if not os.path.exists(JAR):
389 raise MKException("Failed to detect jar at '%s'; the environment variable JDK_HOME is probably set to the wrong path." % os.path.join(JDK_HOME))
390
391 if is_verbose():
392 print("Testing %s..." % JAVAC)
393
394 t = TempFile('Hello.java')
395 t.add('public class Hello { public static void main(String[] args) { System.out.println("Hello, World"); }}\n')
396 t.commit()
397
398 oo = TempFile('output')
399 eo = TempFile('errout')
400 try:
401 subprocess.call([JAVAC, 'Hello.java', '-verbose', '-source', '1.8', '-target', '1.8' ], stdout=oo.fname, stderr=eo.fname)
402 oo.commit()
403 eo.commit()
404 except:
405 raise MKException('Found, but failed to run Java compiler at %s' % (JAVAC))
406
407 os.remove('Hello.class')
408
409 if is_verbose():
410 print("Finding jni.h...")
411
412 if JNI_HOME is not None:
413 if not os.path.exists(os.path.join(JNI_HOME, 'jni.h')):
414 raise MKException("Failed to detect jni.h '%s'; the environment variable JNI_HOME is probably set to the wrong path." % os.path.join(JNI_HOME))
415 else:
416 # Search for jni.h in the library directories...
417 t = open('errout', 'r')
418 open_pat = re.compile(r"\[search path for class files: (.*)\]")
419 cdirs = []
420 for line in t:
421 m = open_pat.match(line)
422 if m:
423 libdirs = m.group(1).split(',')
424 for libdir in libdirs:
425 q = os.path.dirname(libdir)
426 if cdirs.count(q) == 0 and len(q) > 0:
427 cdirs.append(q)
428 t.close()
429
430 # ... plus some heuristic ones.
431 extra_dirs = []
432
433 # For the libraries, even the JDK usually uses a JRE that comes with it. To find the
434 # headers we have to go a little bit higher up.
435 for dir in cdirs:
436 extra_dirs.append(os.path.abspath(os.path.join(dir, '..')))
437
438 if IS_OSX: # Apparently Apple knows best where to put stuff...
439 extra_dirs.append('/System/Library/Frameworks/JavaVM.framework/Headers/')
440
441 cdirs[len(cdirs):] = extra_dirs
442
443 for dir in cdirs:
444 q = find_jni_h(dir)
445 if q is not False:
446 JNI_HOME = q
447
448 if JNI_HOME is None:
449 raise MKException("Failed to detect jni.h. Possible solution: set JNI_HOME with the path to JDK.")
450
451 def test_csc_compiler(c):
452 t = TempFile('hello.cs')
453 t.add('public class hello { public static void Main() {} }')
454 t.commit()
455 if is_verbose():
456 print ('Testing %s...' % c)
457 r = exec_cmd([c, 'hello.cs'])
458 try:
459 rmf('hello.cs')
460 rmf('hello.exe')
461 except:
462 pass
463 return r == 0
464
465 def check_dotnet_core():
466 if not IS_WINDOWS:
467 return
468 r = exec_cmd([DOTNET, '--help'])
469 if r != 0:
470 raise MKException('Failed testing dotnet. Make sure to install and configure dotnet core utilities')
471
472 def check_ml():
473 t = TempFile('hello.ml')
474 t.add('print_string "Hello world!\n";;')
475 t.commit()
476 if is_verbose():
477 print ('Testing %s...' % OCAMLC)
478 r = exec_cmd([OCAMLC, '-o', 'a.out', 'hello.ml'])
479 if r != 0:
480 raise MKException('Failed testing ocamlc compiler. Set environment variable OCAMLC with the path to the Ocaml compiler')
481 if is_verbose():
482 print ('Testing %s...' % OCAMLOPT)
483 r = exec_cmd([OCAMLOPT, '-o', 'a.out', 'hello.ml'])
484 if r != 0:
485 raise MKException('Failed testing ocamlopt compiler. Set environment variable OCAMLOPT with the path to the Ocaml native compiler. Note that ocamlopt may require flexlink to be in your path.')
486 try:
487 rmf('hello.cmi')
488 rmf('hello.cmo')
489 rmf('hello.cmx')
490 rmf('a.out')
491 rmf('hello.o')
492 except:
493 pass
494 find_ml_lib()
495 find_ocaml_find()
496
497 def find_ocaml_find():
498 global OCAMLFIND
499 if is_verbose():
500 print ("Testing %s..." % OCAMLFIND)
501 r = exec_cmd([OCAMLFIND, 'printconf'])
502 if r != 0:
503 OCAMLFIND = ''
504
505 def find_ml_lib():
506 global OCAML_LIB
507 if is_verbose():
508 print ('Finding OCAML_LIB...')
509 t = TempFile('output')
510 null = open(os.devnull, 'wb')
511 try:
512 subprocess.call([OCAMLC, '-where'], stdout=t.fname, stderr=null)
513 t.commit()
514 except:
515 raise MKException('Failed to find Ocaml library; please set OCAML_LIB')
516 finally:
517 null.close()
518
519 t = open('output', 'r')
520 for line in t:
521 OCAML_LIB = line[:-1]
522 if is_verbose():
523 print ('OCAML_LIB=%s' % OCAML_LIB)
524 t.close()
525 rmf('output')
526 return
527
528 def is64():
529 global LINUX_X64
530 if is_sunos() and sys.version_info.major < 3:
531 return LINUX_X64
532 else:
533 return LINUX_X64 and sys.maxsize >= 2**32
534
535 def check_ar():
536 if is_verbose():
537 print("Testing ar...")
538 if which(AR) is None:
539 raise MKException('%s (archive tool) was not found' % AR)
540
541 def find_cxx_compiler():
542 global CXX, CXX_COMPILERS
543 if CXX is not None:
544 if test_cxx_compiler(CXX):
545 return CXX
546 for cxx in CXX_COMPILERS:
547 if test_cxx_compiler(cxx):
548 CXX = cxx
549 return CXX
550 raise MKException('C++ compiler was not found. Try to set the environment variable CXX with the C++ compiler available in your system.')
551
552 def find_c_compiler():
553 global CC, C_COMPILERS
554 if CC is not None:
555 if test_c_compiler(CC):
556 return CC
557 for c in C_COMPILERS:
558 if test_c_compiler(c):
559 CC = c
560 return CC
561 raise MKException('C compiler was not found. Try to set the environment variable CC with the C compiler available in your system.')
562
563 def set_version(major, minor, build, revision):
564 global ASSEMBLY_VERSION, VER_MAJOR, VER_MINOR, VER_BUILD, VER_TWEAK, GIT_DESCRIBE
565
566 # We need to give the assembly a build specific version
567 # global version overrides local default expression
568 if ASSEMBLY_VERSION is not None:
569 versionSplits = ASSEMBLY_VERSION.split('.')
570 if len(versionSplits) > 3:
571 VER_MAJOR = versionSplits[0]
572 VER_MINOR = versionSplits[1]
573 VER_BUILD = versionSplits[2]
574 VER_TWEAK = versionSplits[3]
575 print("Set Assembly Version (BUILD):", VER_MAJOR, VER_MINOR, VER_BUILD, VER_TWEAK)
576 return
577
578 # use parameters to set up version if not provided by script args
579 VER_MAJOR = major
580 VER_MINOR = minor
581 VER_BUILD = build
582 VER_TWEAK = revision
583
584 # update VER_TWEAK base on github
585 if GIT_DESCRIBE:
586 branch = check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
587 VER_TWEAK = int(check_output(['git', 'rev-list', '--count', 'HEAD']))
588
589 print("Set Assembly Version (DEFAULT):", VER_MAJOR, VER_MINOR, VER_BUILD, VER_TWEAK)
590
591 def get_version():
592 return (VER_MAJOR, VER_MINOR, VER_BUILD, VER_TWEAK)
593
594 def get_version_string(n):
595 if n == 3:
596 return "{}.{}.{}".format(VER_MAJOR,VER_MINOR,VER_BUILD)
597 return "{}.{}.{}.{}".format(VER_MAJOR,VER_MINOR,VER_BUILD,VER_TWEAK)
598
599 def build_static_lib():
600 return STATIC_LIB
601
602 def build_static_bin():
603 return STATIC_BIN
604
605 def is_cr_lf(fname):
606 # Check whether text files use cr/lf
607 f = open(fname, 'r')
608 line = f.readline()
609 f.close()
610 sz = len(line)
611 return sz >= 2 and line[sz-2] == '\r' and line[sz-1] == '\n'
612
613 # dos2unix in python
614 # cr/lf --> lf
615 def dos2unix(fname):
616 if is_cr_lf(fname):
617 fin = open(fname, 'r')
618 fname_new = '%s.new' % fname
619 fout = open(fname_new, 'w')
620 for line in fin:
621 line = line.rstrip('\r\n')
622 fout.write(line)
623 fout.write('\n')
624 fin.close()
625 fout.close()
626 shutil.move(fname_new, fname)
627 if is_verbose():
628 print("dos2unix '%s'" % fname)
629
630 def dos2unix_tree():
631 for root, dirs, files in os.walk('src'):
632 for f in files:
633 dos2unix(os.path.join(root, f))
634
635
636 def check_eol():
637 if not IS_WINDOWS:
638 # Linux/OSX/BSD check if the end-of-line is cr/lf
639 if is_cr_lf('LICENSE.txt'):
640 if is_verbose():
641 print("Fixing end of line...")
642 dos2unix_tree()
643
644 if os.name == 'nt':
645 IS_WINDOWS=True
646 # Visual Studio already displays the files being compiled
647 SHOW_CPPS=False
648 elif os.name == 'posix':
649 if os.uname()[0] == 'Darwin':
650 IS_OSX=True
651 elif os.uname()[0] == 'Linux':
652 IS_LINUX=True
653 elif os.uname()[0] == 'GNU':
654 IS_HURD=True
655 elif os.uname()[0] == 'FreeBSD':
656 IS_FREEBSD=True
657 elif os.uname()[0] == 'NetBSD':
658 IS_NETBSD=True
659 elif os.uname()[0] == 'OpenBSD':
660 IS_OPENBSD=True
661 elif os.uname()[0] == 'SunOS':
662 IS_SUNOS=True
663 elif os.uname()[0][:6] == 'CYGWIN':
664 IS_CYGWIN=True
665 if (CC != None and "mingw" in CC):
666 IS_CYGWIN_MINGW=True
667 elif os.uname()[0].startswith('MSYS_NT') or os.uname()[0].startswith('MINGW'):
668 IS_MSYS2=True
669 if os.uname()[4] == 'x86_64':
670 LINUX_X64=True
671 else:
672 LINUX_X64=False
673
674
675 if os.name == 'posix' and os.uname()[4] == 'arm64':
676 IS_ARCH_ARM64 = True
677
678
679 def display_help(exit_code):
680 print("mk_make.py: Z3 Makefile generator\n")
681 print("This script generates the Makefile for the Z3 theorem prover.")
682 print("It must be executed from the Z3 root directory.")
683 print("\nOptions:")
684 print(" -h, --help display this message.")
685 print(" -s, --silent do not print verbose messages.")
686 if not IS_WINDOWS:
687 print(" -p <dir>, --prefix=<dir> installation prefix (default: %s)." % PREFIX)
688 else:
689 print(" --parallel=num use cl option /MP with 'num' parallel processes")
690 print(" --pypkgdir=<dir> Force a particular Python package directory (default %s)" % PYTHON_PACKAGE_DIR)
691 print(" -b <subdir>, --build=<subdir> subdirectory where Z3 will be built (default: %s)." % BUILD_DIR)
692 print(" --githash=hash include the given hash in the binaries.")
693 print(" --git-describe include the output of 'git describe' in the version information.")
694 print(" -d, --debug compile Z3 in debug mode.")
695 print(" -t, --trace enable tracing in release mode.")
696 if IS_WINDOWS:
697 print(" --guardcf enable Control Flow Guard runtime checks.")
698 print(" -x, --x64 create 64 binary when using Visual Studio.")
699 else:
700 print(" --x86 force 32-bit x86 build on x64 systems.")
701 print(" --arm64=<bool> forcearm64 bit build on/off (supported for Darwin).")
702 print(" -m, --makefiles generate only makefiles.")
703 if IS_WINDOWS:
704 print(" -v, --vsproj generate Visual Studio Project Files.")
705 print(" --optimize generate optimized code during linking.")
706 print(" --dotnet generate .NET platform bindings.")
707 print(" --dotnet-key=<file> sign the .NET assembly using the private key in <file>.")
708 print(" --assembly-version=<x.x.x.x> provide version number for build")
709 print(" --java generate Java bindings.")
710 print(" --ml generate OCaml bindings.")
711 print(" --js generate JScript bindings.")
712 print(" --python generate Python bindings.")
713 print(" --staticlib build Z3 static library.")
714 print(" --staticbin build a statically linked Z3 binary.")
715 if not IS_WINDOWS:
716 print(" -g, --gmp use GMP.")
717 print(" --gprof enable gprof")
718 print(" --log-sync synchronize access to API log files to enable multi-thread API logging.")
719 print(" --single-threaded non-thread-safe build")
720 print("")
721 print("Some influential environment variables:")
722 if not IS_WINDOWS:
723 print(" CXX C++ compiler")
724 print(" CC C compiler")
725 print(" LDFLAGS Linker flags, e.g., -L<lib dir> if you have libraries in a non-standard directory")
726 print(" CPPFLAGS Preprocessor flags, e.g., -I<include dir> if you have header files in a non-standard directory")
727 print(" CXXFLAGS C++ compiler flags")
728 print(" JDK_HOME JDK installation directory (only relevant if -j or --java option is provided)")
729 print(" JNI_HOME JNI bindings directory (only relevant if -j or --java option is provided)")
730 print(" OCAMLC Ocaml byte-code compiler (only relevant with --ml)")
731 print(" OCAMLFIND Ocaml find tool (only relevant with --ml)")
732 print(" OCAMLOPT Ocaml native compiler (only relevant with --ml)")
733 print(" OCAML_LIB Ocaml library directory (only relevant with --ml)")
734 print(" Z3_INSTALL_BIN_DIR Install directory for binaries relative to install prefix")
735 print(" Z3_INSTALL_LIB_DIR Install directory for libraries relative to install prefix")
736 print(" Z3_INSTALL_INCLUDE_DIR Install directory for header files relative to install prefix")
737 print(" Z3_INSTALL_PKGCONFIG_DIR Install directory for pkgconfig files relative to install prefix")
738 exit(exit_code)
739
740 # Parse configuration option for mk_make script
741 def parse_options():
742 global VERBOSE, DEBUG_MODE, IS_WINDOWS, VS_X64, ONLY_MAKEFILES, SHOW_CPPS, VS_PROJ, TRACE, VS_PAR, VS_PAR_NUM
743 global DOTNET_CORE_ENABLED, DOTNET_KEY_FILE, ASSEMBLY_VERSION, JAVA_ENABLED, ML_ENABLED, STATIC_LIB, STATIC_BIN, PREFIX, GMP, PYTHON_PACKAGE_DIR, GPROF, GIT_HASH, GIT_DESCRIBE, PYTHON_INSTALL_ENABLED, PYTHON_ENABLED
744 global LINUX_X64, SLOW_OPTIMIZE, LOG_SYNC, SINGLE_THREADED
745 global GUARD_CF, ALWAYS_DYNAMIC_BASE, IS_ARCH_ARM64
746 try:
747 options, remainder = getopt.gnu_getopt(sys.argv[1:],
748 'b:df:sxa:hmcvtnp:gj',
749 ['build=', 'debug', 'silent', 'x64', 'arm64=', 'help', 'makefiles', 'showcpp', 'vsproj', 'guardcf',
750 'trace', 'dotnet', 'dotnet-key=', 'assembly-version=', 'staticlib', 'prefix=', 'gmp', 'java', 'parallel=', 'gprof', 'js',
751 'githash=', 'git-describe', 'x86', 'ml', 'optimize', 'pypkgdir=', 'python', 'staticbin', 'log-sync', 'single-threaded'])
752 except:
753 print("ERROR: Invalid command line option")
754 display_help(1)
755
756 for opt, arg in options:
757 print('opt = %s, arg = %s' % (opt, arg))
758 if opt in ('-b', '--build'):
759 if arg == 'src':
760 raise MKException('The src directory should not be used to host the Makefile')
761 set_build_dir(arg)
762 elif opt in ('-s', '--silent'):
763 VERBOSE = False
764 elif opt in ('-d', '--debug'):
765 DEBUG_MODE = True
766 elif opt in ('-x', '--x64'):
767 if not IS_WINDOWS:
768 raise MKException('x64 compilation mode can only be specified when using Visual Studio')
769 VS_X64 = True
770 elif opt in ('--x86'):
771 LINUX_X64=False
772 elif opt in ('--arm64'):
773 IS_ARCH_ARM64 = arg in ('true','on','True','TRUE')
774 elif opt in ('-h', '--help'):
775 display_help(0)
776 elif opt in ('-m', '--makefiles'):
777 ONLY_MAKEFILES = True
778 elif opt in ('-c', '--showcpp'):
779 SHOW_CPPS = True
780 elif opt in ('-v', '--vsproj'):
781 VS_PROJ = True
782 elif opt in ('-t', '--trace'):
783 TRACE = True
784 elif opt in ('--dotnet',):
785 DOTNET_CORE_ENABLED = True
786 elif opt in ('--dotnet-key'):
787 DOTNET_KEY_FILE = arg
788 elif opt in ('--assembly-version'):
789 ASSEMBLY_VERSION = arg
790 elif opt in ('--staticlib'):
791 STATIC_LIB = True
792 elif opt in ('--staticbin'):
793 STATIC_BIN = True
794 elif opt in ('--optimize'):
795 SLOW_OPTIMIZE = True
796 elif not IS_WINDOWS and opt in ('-p', '--prefix'):
797 PREFIX = arg
798 elif opt in ('--pypkgdir'):
799 PYTHON_PACKAGE_DIR = arg
800 elif IS_WINDOWS and opt == '--parallel':
801 VS_PAR = True
802 VS_PAR_NUM = int(arg)
803 elif opt in ('-g', '--gmp'):
804 GMP = True
805 elif opt in ('-j', '--java'):
806 JAVA_ENABLED = True
807 elif opt == '--gprof':
808 GPROF = True
809 elif opt == '--githash':
810 GIT_HASH=arg
811 elif opt == '--git-describe':
812 GIT_DESCRIBE = True
813 elif opt in ('', '--ml'):
814 ML_ENABLED = True
815 elif opt in ('', '--log-sync'):
816 LOG_SYNC = True
817 elif opt == '--single-threaded':
818 SINGLE_THREADED = True
819 elif opt in ('--python'):
820 PYTHON_ENABLED = True
821 PYTHON_INSTALL_ENABLED = True
822 elif opt == '--guardcf':
823 GUARD_CF = True
824 ALWAYS_DYNAMIC_BASE = True # /GUARD:CF requires /DYNAMICBASE
825 else:
826 print("ERROR: Invalid command line option '%s'" % opt)
827 display_help(1)
828
829
830 # Return a list containing a file names included using '#include' in
831 # the given C/C++ file named fname.
832 def extract_c_includes(fname):
833 result = {}
834 # We look for well behaved #include directives
835 std_inc_pat = re.compile(r"[ \t]*#include[ \t]*\"(.*)\"[ \t]*")
836 system_inc_pat = re.compile(r"[ \t]*#include[ \t]*\<.*\>[ \t]*")
837 # We should generate and error for any occurrence of #include that does not match the previous pattern.
838 non_std_inc_pat = re.compile(".*#include.*")
839
840 f = io.open(fname, encoding='utf-8', mode='r')
841 linenum = 1
842 for line in f:
843 m1 = std_inc_pat.match(line)
844 if m1:
845 root_file_name = m1.group(1)
846 slash_pos = root_file_name.rfind('/')
847 if slash_pos >= 0 and root_file_name.find("..") < 0 : #it is a hack for lp include files that behave as continued from "src"
848 # print(root_file_name)
849 root_file_name = root_file_name[slash_pos+1:]
850 result[root_file_name] = m1.group(1)
851 elif not system_inc_pat.match(line) and non_std_inc_pat.match(line):
852 raise MKException("Invalid #include directive at '%s':%s" % (fname, line))
853 linenum = linenum + 1
854 f.close()
855 return result
856
857
858 # Given a path dir1/subdir2/subdir3 returns ../../..
859 def reverse_path(p):
860 # Filter out empty components (e.g. will have one if path ends in a slash)
861 l = list(filter(lambda x: len(x) > 0, p.split(os.sep)))
862 n = len(l)
863 r = '..'
864 for i in range(1, n):
865 r = os.path.join(r, '..')
866 return r
867
868 def mk_dir(d):
869 if not os.path.exists(d):
870 os.makedirs(d)
871
872 def set_build_dir(d):
873 global BUILD_DIR, REV_BUILD_DIR
874 BUILD_DIR = norm_path(d)
875 REV_BUILD_DIR = reverse_path(d)
876
877 def set_z3py_dir(p):
878 global SRC_DIR, Z3PY_SRC_DIR
879 p = norm_path(p)
880 full = os.path.join(SRC_DIR, p)
881 if not os.path.exists(full):
882 raise MKException("Python bindings directory '%s' does not exist" % full)
883 Z3PY_SRC_DIR = full
884 if VERBOSE:
885 print("Python bindings directory was detected.")
886
887 _UNIQ_ID = 0
888
889 def mk_fresh_name(prefix):
890 global _UNIQ_ID
891 r = '%s_%s' % (prefix, _UNIQ_ID)
892 _UNIQ_ID = _UNIQ_ID + 1
893 return r
894
895 _Id = 0
896 _Components = []
897 _ComponentNames = set()
898 _Name2Component = {}
899 _Processed_Headers = set()
900
901 # Return the Component object named name
902 def get_component(name):
903 return _Name2Component[name]
904
905 def get_components():
906 return _Components
907
908 # Return the directory where the python bindings are located.
909 def get_z3py_dir():
910 return Z3PY_SRC_DIR
911
912
913 # Return true if in verbose mode
914 def is_verbose():
915 return VERBOSE
916
917 def is_java_enabled():
918 return JAVA_ENABLED
919
920 def is_ml_enabled():
921 return ML_ENABLED
922
923 def is_dotnet_core_enabled():
924 return DOTNET_CORE_ENABLED
925
926 def is_python_enabled():
927 return PYTHON_ENABLED
928
929 def is_python_install_enabled():
930 return PYTHON_INSTALL_ENABLED
931
932 def is_compiler(given, expected):
933 """
934 Return True if the 'given' compiler is the expected one.
935 >>> is_compiler('g++', 'g++')
936 True
937 >>> is_compiler('/home/g++', 'g++')
938 True
939 >>> is_compiler(os.path.join('home', 'g++'), 'g++')
940 True
941 >>> is_compiler('clang++', 'g++')
942 False
943 >>> is_compiler(os.path.join('home', 'clang++'), 'clang++')
944 True
945 """
946 if given == expected:
947 return True
948 if len(expected) < len(given):
949 return given[len(given) - len(expected) - 1] == os.sep and given[len(given) - len(expected):] == expected
950 return False
951
952 def is_CXX_gpp():
953 return is_compiler(CXX, 'g++')
954
955 def is_clang_in_gpp_form(cc):
956 str = check_output([cc, '--version'])
957 try:
958 version_string = str.encode('utf-8')
959 except:
960 version_string = str
961 clang = 'clang'.encode('utf-8')
962 return version_string.find(clang) != -1
963
964 def is_CXX_clangpp():
965 if is_compiler(CXX, 'g++'):
966 return is_clang_in_gpp_form(CXX)
967 return is_compiler(CXX, 'clang++')
968
969 def get_files_with_ext(path, ext):
970 return filter(lambda f: f.endswith(ext), os.listdir(path))
971
972 def get_cpp_files(path):
973 return get_files_with_ext(path,'.cpp')
974
975 def get_c_files(path):
976 return get_files_with_ext(path,'.c')
977
978 def get_cs_files(path):
979 return get_files_with_ext(path,'.cs')
980
981 def get_java_files(path):
982 return get_files_with_ext(path,'.java')
983
984 def get_ml_files(path):
985 return get_files_with_ext(path,'.ml')
986
987 def find_all_deps(name, deps):
988 new_deps = []
989 for dep in deps:
990 if dep in _ComponentNames:
991 if not (dep in new_deps):
992 new_deps.append(dep)
993 for dep_dep in get_component(dep).deps:
994 if not (dep_dep in new_deps):
995 new_deps.append(dep_dep)
996 else:
997 raise MKException("Unknown component '%s' at '%s'." % (dep, name))
998 return new_deps
999
1000 class Component:
1001 def __init__(self, name, path, deps):
1002 global BUILD_DIR, SRC_DIR, REV_BUILD_DIR
1003 if name in _ComponentNames:
1004 raise MKException("Component '%s' was already defined." % name)
1005 if path is None:
1006 path = name
1007 self.name = name
1008 path = norm_path(path)
1009 self.path = path
1010 self.deps = find_all_deps(name, deps)
1011 self.build_dir = path
1012 self.src_dir = os.path.join(SRC_DIR, path)
1013 self.to_src_dir = os.path.join(REV_BUILD_DIR, self.src_dir)
1014
1015 def get_link_name(self):
1016 return os.path.join(self.build_dir, self.name) + '$(LIB_EXT)'
1017
1018
1019 # Find fname in the include paths for the given component.
1020 # ownerfile is only used for creating error messages.
1021 # That is, we were looking for fname when processing ownerfile
1022 def find_file(self, fname, ownerfile, orig_include=None):
1023 full_fname = os.path.join(self.src_dir, fname)
1024
1025 # Store all our possible locations
1026 possibilities = set()
1027
1028 # If the our file exists in the current directory, then we store it
1029 if os.path.exists(full_fname):
1030
1031 # We cannot return here, as we might have files with the same
1032 # basename, but different include paths
1033 possibilities.add(self)
1034
1035 for dep in self.deps:
1036 c_dep = get_component(dep)
1037 full_fname = os.path.join(c_dep.src_dir, fname)
1038 if os.path.exists(full_fname):
1039 possibilities.add(c_dep)
1040
1041 if possibilities:
1042
1043 # We have ambiguity
1044 if len(possibilities) > 1:
1045
1046 # We expect orig_path to be non-None here, so we can disambiguate
1047 assert orig_include is not None
1048
1049 # Get the original directory name
1050 orig_dir = os.path.dirname(orig_include)
1051
1052 # Iterate through all of the possibilities
1053 for possibility in possibilities:
1054
1055 path = possibility.path.replace("\\","/")
1056 # If we match the suffix of the path ...
1057 if path.endswith(orig_dir):
1058
1059 # ... use our new match
1060 return possibility
1061
1062 # This means we didn't make an exact match ...
1063 #
1064 # We return any one possibility, just to ensure we don't break Z3's
1065 # builds
1066 return possibilities.pop()
1067
1068 raise MKException("Failed to find include file '%s' for '%s' when processing '%s'." % (fname, ownerfile, self.name))
1069
1070 # Display all dependencies of file basename located in the given component directory.
1071 # The result is displayed at out
1072 def add_cpp_h_deps(self, out, basename):
1073 includes = extract_c_includes(os.path.join(self.src_dir, basename))
1074 out.write(os.path.join(self.to_src_dir, basename))
1075 for include, orig_include in includes.items():
1076 owner = self.find_file(include, basename, orig_include)
1077 out.write(' %s.node' % os.path.join(owner.build_dir, include))
1078
1079 # Add a rule for each #include directive in the file basename located at the current component.
1080 def add_rule_for_each_include(self, out, basename):
1081 fullname = os.path.join(self.src_dir, basename)
1082 includes = extract_c_includes(fullname)
1083 for include, orig_include in includes.items():
1084 owner = self.find_file(include, fullname, orig_include)
1085 owner.add_h_rule(out, include)
1086
1087 # Display a Makefile rule for an include file located in the given component directory.
1088 # 'include' is something of the form: ast.h, polynomial.h
1089 # The rule displayed at out is of the form
1090 # ast/ast_pp.h.node : ../src/util/ast_pp.h util/util.h.node ast/ast.h.node
1091 # @echo "done" > ast/ast_pp.h.node
1092 def add_h_rule(self, out, include):
1093 include_src_path = os.path.join(self.to_src_dir, include)
1094 if include_src_path in _Processed_Headers:
1095 return
1096 _Processed_Headers.add(include_src_path)
1097 self.add_rule_for_each_include(out, include)
1098 include_node = '%s.node' % os.path.join(self.build_dir, include)
1099 out.write('%s: ' % include_node)
1100 self.add_cpp_h_deps(out, include)
1101 out.write('\n')
1102 out.write('\t@echo done > %s\n' % include_node)
1103
1104 def add_cpp_rules(self, out, include_defs, cppfile):
1105 self.add_rule_for_each_include(out, cppfile)
1106 objfile = '%s$(OBJ_EXT)' % os.path.join(self.build_dir, os.path.splitext(cppfile)[0])
1107 srcfile = os.path.join(self.to_src_dir, cppfile)
1108 out.write('%s: ' % objfile)
1109 self.add_cpp_h_deps(out, cppfile)
1110 out.write('\n')
1111 if SHOW_CPPS:
1112 out.write('\t@echo %s\n' % os.path.join(self.src_dir, cppfile))
1113 out.write('\t@$(CXX) $(CXXFLAGS) $(%s) $(CXX_OUT_FLAG)%s %s\n' % (include_defs, objfile, srcfile))
1114
1115 def mk_makefile(self, out):
1116 include_defs = mk_fresh_name('includes')
1117 out.write('%s =' % include_defs)
1118 for dep in self.deps:
1119 out.write(' -I%s' % get_component(dep).to_src_dir)
1120 out.write(' -I%s' % os.path.join(REV_BUILD_DIR,"src"))
1121 out.write('\n')
1122 mk_dir(os.path.join(BUILD_DIR, self.build_dir))
1123 if VS_PAR and IS_WINDOWS:
1124 cppfiles = list(get_cpp_files(self.src_dir))
1125 dependencies = set()
1126 for cppfile in cppfiles:
1127 dependencies.add(os.path.join(self.to_src_dir, cppfile))
1128 self.add_rule_for_each_include(out, cppfile)
1129 includes = extract_c_includes(os.path.join(self.src_dir, cppfile))
1130 for include, orig_include in includes.items():
1131 owner = self.find_file(include, cppfile, orig_include)
1132 dependencies.add('%s.node' % os.path.join(owner.build_dir, include))
1133 for cppfile in cppfiles:
1134 out.write('%s$(OBJ_EXT) ' % os.path.join(self.build_dir, os.path.splitext(cppfile)[0]))
1135 out.write(': ')
1136 for dep in dependencies:
1137 out.write(dep)
1138 out.write(' ')
1139 out.write('\n')
1140 out.write('\t@$(CXX) $(CXXFLAGS) /MP%s $(%s)' % (VS_PAR_NUM, include_defs))
1141 for cppfile in cppfiles:
1142 out.write(' ')
1143 out.write(os.path.join(self.to_src_dir, cppfile))
1144 out.write('\n')
1145 out.write('\tmove *.obj %s\n' % self.build_dir)
1146 else:
1147 for cppfile in get_cpp_files(self.src_dir):
1148 self.add_cpp_rules(out, include_defs, cppfile)
1149
1150 # Return true if the component should be included in the all: rule
1151 def main_component(self):
1152 return False
1153
1154 # Return true if the component contains an AssemblyInfo.cs file that needs to be updated.
1155 def has_assembly_info(self):
1156 return False
1157
1158 # Return true if the component needs builder to generate an install_tactics.cpp file
1159 def require_install_tactics(self):
1160 return False
1161
1162 # Return true if the component needs a def file
1163 def require_def_file(self):
1164 return False
1165
1166 # Return true if the component needs builder to generate a mem_initializer.cpp file with mem_initialize() and mem_finalize() functions.
1167 def require_mem_initializer(self):
1168 return False
1169
1170 def mk_install_deps(self, out):
1171 return
1172
1173 def mk_install(self, out):
1174 return
1175
1176 def mk_uninstall(self, out):
1177 return
1178
1179 def is_example(self):
1180 return False
1181
1182 # Invoked when creating a (windows) distribution package using components at build_path, and
1183 # storing them at dist_path
1184 def mk_win_dist(self, build_path, dist_path):
1185 return
1186
1187 def mk_unix_dist(self, build_path, dist_path):
1188 return
1189
1190 # Used to print warnings or errors after mk_make.py is done, so that they
1191 # are not quite as easy to miss.
1192 def final_info(self):
1193 pass
1194
1195 class LibComponent(Component):
1196 def __init__(self, name, path, deps, includes2install):
1197 Component.__init__(self, name, path, deps)
1198 self.includes2install = includes2install
1199
1200 def mk_makefile(self, out):
1201 Component.mk_makefile(self, out)
1202 # generate rule for lib
1203 objs = []
1204 for cppfile in get_cpp_files(self.src_dir):
1205 objfile = '%s$(OBJ_EXT)' % os.path.join(self.build_dir, os.path.splitext(cppfile)[0])
1206 objs.append(objfile)
1207
1208 libfile = '%s$(LIB_EXT)' % os.path.join(self.build_dir, self.name)
1209 out.write('%s:' % libfile)
1210 for obj in objs:
1211 out.write(' ')
1212 out.write(obj)
1213 out.write('\n')
1214 out.write('\t@$(AR) $(AR_FLAGS) $(AR_OUTFLAG)%s' % libfile)
1215 for obj in objs:
1216 out.write(' ')
1217 out.write(obj)
1218 out.write('\n')
1219 out.write('%s: %s\n\n' % (self.name, libfile))
1220
1221 def mk_install_deps(self, out):
1222 return
1223
1224 def mk_install(self, out):
1225 for include in self.includes2install:
1226 MakeRuleCmd.install_files(
1227 out,
1228 os.path.join(self.to_src_dir, include),
1229 os.path.join(INSTALL_INCLUDE_DIR, include)
1230 )
1231
1232 def mk_uninstall(self, out):
1233 for include in self.includes2install:
1234 MakeRuleCmd.remove_installed_files(out, os.path.join(INSTALL_INCLUDE_DIR, include))
1235
1236 def mk_win_dist(self, build_path, dist_path):
1237 mk_dir(os.path.join(dist_path, INSTALL_INCLUDE_DIR))
1238 for include in self.includes2install:
1239 shutil.copy(os.path.join(self.src_dir, include),
1240 os.path.join(dist_path, INSTALL_INCLUDE_DIR, include))
1241
1242 def mk_unix_dist(self, build_path, dist_path):
1243 self.mk_win_dist(build_path, dist_path)
1244
1245 # "Library" containing only .h files. This is just a placeholder for includes files to be installed.
1246 class HLibComponent(LibComponent):
1247 def __init__(self, name, path, includes2install):
1248 LibComponent.__init__(self, name, path, [], includes2install)
1249
1250 def mk_makefile(self, out):
1251 return
1252
1253 # Auxiliary function for sort_components
1254 def comp_components(c1, c2):
1255 id1 = get_component(c1).id
1256 id2 = get_component(c2).id
1257 return id2 - id1
1258
1259 # Sort components based on (reverse) definition time
1260 def sort_components(cnames):
1261 return sorted(cnames, key=lambda c: get_component(c).id, reverse=True)
1262
1263 class ExeComponent(Component):
1264 def __init__(self, name, exe_name, path, deps, install):
1265 Component.__init__(self, name, path, deps)
1266 if exe_name is None:
1267 exe_name = name
1268 self.exe_name = exe_name
1269 self.install = install
1270
1271 def mk_makefile(self, out):
1272 Component.mk_makefile(self, out)
1273 # generate rule for exe
1274
1275 exefile = '%s$(EXE_EXT)' % self.exe_name
1276 out.write('%s:' % exefile)
1277 deps = sort_components(self.deps)
1278 objs = []
1279 for cppfile in get_cpp_files(self.src_dir):
1280 objfile = '%s$(OBJ_EXT)' % os.path.join(self.build_dir, os.path.splitext(cppfile)[0])
1281 objs.append(objfile)
1282 for obj in objs:
1283 out.write(' ')
1284 out.write(obj)
1285 for dep in deps:
1286 c_dep = get_component(dep)
1287 out.write(' ' + c_dep.get_link_name())
1288 out.write('\n')
1289 extra_opt = '-static' if not IS_WINDOWS and STATIC_BIN else ''
1290 out.write('\t$(LINK) %s $(LINK_OUT_FLAG)%s $(LINK_FLAGS)' % (extra_opt, exefile))
1291 for obj in objs:
1292 out.write(' ')
1293 out.write(obj)
1294 for dep in deps:
1295 c_dep = get_component(dep)
1296 out.write(' ' + c_dep.get_link_name())
1297 out.write(' $(LINK_EXTRA_FLAGS)\n')
1298 out.write('%s: %s\n\n' % (self.name, exefile))
1299
1300 def require_install_tactics(self):
1301 return ('tactic' in self.deps) and ('cmd_context' in self.deps)
1302
1303 def require_mem_initializer(self):
1304 return True
1305
1306 # All executables (to be installed) are included in the all: rule
1307 def main_component(self):
1308 return self.install
1309
1310 def mk_install_deps(self, out):
1311 if self.install:
1312 exefile = '%s$(EXE_EXT)' % self.exe_name
1313 out.write('%s' % exefile)
1314
1315 def mk_install(self, out):
1316 if self.install:
1317 exefile = '%s$(EXE_EXT)' % self.exe_name
1318 MakeRuleCmd.install_files(out, exefile, os.path.join(INSTALL_BIN_DIR, exefile))
1319
1320 def mk_uninstall(self, out):
1321 if self.install:
1322 exefile = '%s$(EXE_EXT)' % self.exe_name
1323 MakeRuleCmd.remove_installed_files(out, os.path.join(INSTALL_BIN_DIR, exefile))
1324
1325 def mk_win_dist(self, build_path, dist_path):
1326 if self.install:
1327 mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR))
1328 shutil.copy('%s.exe' % os.path.join(build_path, self.exe_name),
1329 '%s.exe' % os.path.join(dist_path, INSTALL_BIN_DIR, self.exe_name))
1330
1331 def mk_unix_dist(self, build_path, dist_path):
1332 if self.install:
1333 mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR))
1334 shutil.copy(os.path.join(build_path, self.exe_name),
1335 os.path.join(dist_path, INSTALL_BIN_DIR, self.exe_name))
1336
1337
1338 class ExtraExeComponent(ExeComponent):
1339 def __init__(self, name, exe_name, path, deps, install):
1340 ExeComponent.__init__(self, name, exe_name, path, deps, install)
1341
1342 def main_component(self):
1343 return False
1344
1345 def require_mem_initializer(self):
1346 return False
1347
1348 def get_so_ext():
1349 sysname = os.uname()[0]
1350 if sysname == 'Darwin':
1351 return 'dylib'
1352 elif sysname == 'Linux' or sysname == 'GNU' or sysname == 'FreeBSD' or sysname == 'NetBSD' or sysname == 'OpenBSD':
1353 return 'so'
1354 elif sysname == 'CYGWIN' or sysname.startswith('MSYS_NT') or sysname.startswith('MINGW'):
1355 return 'dll'
1356 else:
1357 assert(False)
1358 return 'dll'
1359
1360 class DLLComponent(Component):
1361 def __init__(self, name, dll_name, path, deps, export_files, reexports, install, static, staging_link=None):
1362 Component.__init__(self, name, path, deps)
1363 if dll_name is None:
1364 dll_name = name
1365 self.dll_name = dll_name
1366 self.export_files = export_files
1367 self.reexports = reexports
1368 self.install = install
1369 self.static = static
1370 self.staging_link = staging_link # link a copy of the shared object into this directory on build
1371
1372 def get_link_name(self):
1373 if self.static:
1374 return os.path.join(self.build_dir, self.name) + '$(LIB_EXT)'
1375 else:
1376 return self.name + '$(SO_EXT)'
1377
1378 def dll_file(self):
1379 """
1380 Return file name of component suitable for use in a Makefile
1381 """
1382 return '%s$(SO_EXT)' % self.dll_name
1383
1384 def install_path(self):
1385 """
1386 Return install location of component (relative to prefix)
1387 suitable for use in a Makefile
1388 """
1389 return os.path.join(INSTALL_LIB_DIR, self.dll_file())
1390
1391 def mk_makefile(self, out):
1392 Component.mk_makefile(self, out)
1393 # generate rule for (SO_EXT)
1394 out.write('%s:' % self.dll_file())
1395 deps = sort_components(self.deps)
1396 objs = []
1397 for cppfile in get_cpp_files(self.src_dir):
1398 objfile = '%s$(OBJ_EXT)' % os.path.join(self.build_dir, os.path.splitext(cppfile)[0])
1399 objs.append(objfile)
1400 # Explicitly include obj files of reexport. This fixes problems with exported symbols on Linux and OSX.
1401 for reexport in self.reexports:
1402 reexport = get_component(reexport)
1403 for cppfile in get_cpp_files(reexport.src_dir):
1404 objfile = '%s$(OBJ_EXT)' % os.path.join(reexport.build_dir, os.path.splitext(cppfile)[0])
1405 objs.append(objfile)
1406 for obj in objs:
1407 out.write(' ')
1408 out.write(obj)
1409 for dep in deps:
1410 if dep not in self.reexports:
1411 c_dep = get_component(dep)
1412 out.write(' ' + c_dep.get_link_name())
1413 out.write('\n')
1414 out.write('\t$(LINK) $(SLINK_OUT_FLAG)%s $(SLINK_FLAGS)' % self.dll_file())
1415 for obj in objs:
1416 out.write(' ')
1417 out.write(obj)
1418 for dep in deps:
1419 if dep not in self.reexports:
1420 c_dep = get_component(dep)
1421 out.write(' ' + c_dep.get_link_name())
1422 out.write(' $(SLINK_EXTRA_FLAGS)')
1423 if IS_WINDOWS:
1424 out.write(' /DEF:%s.def' % os.path.join(self.to_src_dir, self.name))
1425 if self.staging_link:
1426 if IS_WINDOWS:
1427 out.write('\n\tcopy %s %s' % (self.dll_file(), self.staging_link))
1428 elif IS_OSX:
1429 out.write('\n\tcp %s %s' % (self.dll_file(), self.staging_link))
1430 else:
1431 out.write('\n\tln -f -s %s %s' % (os.path.join(reverse_path(self.staging_link), self.dll_file()), self.staging_link))
1432 out.write('\n')
1433 if self.static:
1434 if IS_WINDOWS:
1435 libfile = '%s-static$(LIB_EXT)' % self.dll_name
1436 else:
1437 libfile = '%s$(LIB_EXT)' % self.dll_name
1438 self.mk_static(out, libfile)
1439 out.write('%s: %s %s\n\n' % (self.name, self.dll_file(), libfile))
1440 else:
1441 out.write('%s: %s\n\n' % (self.name, self.dll_file()))
1442
1443 def mk_static(self, out, libfile):
1444 # generate rule for lib
1445 objs = []
1446 for cppfile in get_cpp_files(self.src_dir):
1447 objfile = '%s$(OBJ_EXT)' % os.path.join(self.build_dir, os.path.splitext(cppfile)[0])
1448 objs.append(objfile)
1449 # we have to "reexport" all object files
1450 for dep in self.deps:
1451 dep = get_component(dep)
1452 for cppfile in get_cpp_files(dep.src_dir):
1453 objfile = '%s$(OBJ_EXT)' % os.path.join(dep.build_dir, os.path.splitext(cppfile)[0])
1454 objs.append(objfile)
1455 out.write('%s:' % libfile)
1456 for obj in objs:
1457 out.write(' ')
1458 out.write(obj)
1459 out.write('\n')
1460 out.write('\t@$(AR) $(AR_FLAGS) $(AR_OUTFLAG)%s' % libfile)
1461 for obj in objs:
1462 out.write(' ')
1463 out.write(obj)
1464 out.write('\n')
1465
1466 def main_component(self):
1467 return self.install
1468
1469 def require_install_tactics(self):
1470 return ('tactic' in self.deps) and ('cmd_context' in self.deps)
1471
1472 def require_mem_initializer(self):
1473 return True
1474
1475 def require_def_file(self):
1476 return IS_WINDOWS and self.export_files
1477
1478 def mk_install_deps(self, out):
1479 out.write('%s$(SO_EXT)' % self.dll_name)
1480 if self.static:
1481 out.write(' %s$(LIB_EXT)' % self.dll_name)
1482
1483 def mk_install(self, out):
1484 if self.install:
1485 MakeRuleCmd.install_files(out, self.dll_file(), self.install_path())
1486 if self.static:
1487 libfile = '%s$(LIB_EXT)' % self.dll_name
1488 MakeRuleCmd.install_files(out, libfile, os.path.join(INSTALL_LIB_DIR, libfile))
1489
1490 def mk_uninstall(self, out):
1491 MakeRuleCmd.remove_installed_files(out, self.install_path())
1492 libfile = '%s$(LIB_EXT)' % self.dll_name
1493 MakeRuleCmd.remove_installed_files(out, os.path.join(INSTALL_LIB_DIR, libfile))
1494
1495 def mk_win_dist(self, build_path, dist_path):
1496 if self.install:
1497 mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR))
1498 shutil.copy('%s.dll' % os.path.join(build_path, self.dll_name),
1499 '%s.dll' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name))
1500 shutil.copy('%s.pdb' % os.path.join(build_path, self.dll_name),
1501 '%s.pdb' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name))
1502 shutil.copy('%s.lib' % os.path.join(build_path, self.dll_name),
1503 '%s.lib' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name))
1504
1505 def mk_unix_dist(self, build_path, dist_path):
1506 if self.install:
1507 mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR))
1508 so = get_so_ext()
1509 shutil.copy('%s.%s' % (os.path.join(build_path, self.dll_name), so),
1510 '%s.%s' % (os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name), so))
1511 shutil.copy('%s.a' % os.path.join(build_path, self.dll_name),
1512 '%s.a' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name))
1513
1514 class JsComponent(Component):
1515 def __init__(self):
1516 Component.__init__(self, "js", None, [])
1517
1518 def main_component(self):
1519 return False
1520
1521 def mk_win_dist(self, build_path, dist_path):
1522 return
1523
1524 def mk_unix_dist(self, build_path, dist_path):
1525 return
1526
1527 def mk_makefile(self, out):
1528 return
1529
1530 class PythonComponent(Component):
1531 def __init__(self, name, libz3Component):
1532 assert isinstance(libz3Component, DLLComponent)
1533 global PYTHON_ENABLED
1534 Component.__init__(self, name, None, [])
1535 self.libz3Component = libz3Component
1536
1537 def main_component(self):
1538 return False
1539
1540 def mk_win_dist(self, build_path, dist_path):
1541 if not is_python_enabled():
1542 return
1543
1544 src = os.path.join(build_path, 'python', 'z3')
1545 dst = os.path.join(dist_path, INSTALL_BIN_DIR, 'python', 'z3')
1546 if os.path.exists(dst):
1547 shutil.rmtree(dst)
1548 shutil.copytree(src, dst)
1549
1550 def mk_unix_dist(self, build_path, dist_path):
1551 self.mk_win_dist(build_path, dist_path)
1552
1553 def mk_makefile(self, out):
1554 return
1555
1556 class PythonInstallComponent(Component):
1557 def __init__(self, name, libz3Component):
1558 assert isinstance(libz3Component, DLLComponent)
1559 global PYTHON_INSTALL_ENABLED
1560 Component.__init__(self, name, None, [])
1561 self.pythonPkgDir = None
1562 self.in_prefix_install = True
1563 self.libz3Component = libz3Component
1564
1565 if not PYTHON_INSTALL_ENABLED:
1566 return
1567
1568 if IS_WINDOWS:
1569 # Installing under Windows doesn't make sense as the install prefix is used
1570 # but that doesn't make sense under Windows
1571 # CMW: It makes perfectly good sense; the prefix is Python's sys.prefix,
1572 # i.e., something along the lines of C:\Python\... At the moment we are not
1573 # sure whether we would want to install libz3.dll into that directory though.
1574 PYTHON_INSTALL_ENABLED = False
1575 return
1576 else:
1577 PYTHON_INSTALL_ENABLED = True
1578
1579 if IS_WINDOWS or IS_OSX:
1580 # Use full path that is possibly outside of install prefix
1581 self.in_prefix_install = PYTHON_PACKAGE_DIR.startswith(PREFIX)
1582 self.pythonPkgDir = strip_path_prefix(PYTHON_PACKAGE_DIR, PREFIX)
1583 else:
1584 # Use path inside the prefix (should be the normal case on Linux)
1585 # CMW: Also normal on *BSD?
1586 if not PYTHON_PACKAGE_DIR.startswith(PREFIX):
1587 raise MKException(('The python package directory ({}) must live ' +
1588 'under the install prefix ({}) to install the python bindings.' +
1589 'Use --pypkgdir and --prefix to set the python package directory ' +
1590 'and install prefix respectively. Note that the python package ' +
1591 'directory does not need to exist and will be created if ' +
1592 'necessary during install.').format(
1593 PYTHON_PACKAGE_DIR,
1594 PREFIX))
1595 self.pythonPkgDir = strip_path_prefix(PYTHON_PACKAGE_DIR, PREFIX)
1596 self.in_prefix_install = True
1597
1598 if self.in_prefix_install:
1599 assert not os.path.isabs(self.pythonPkgDir)
1600
1601 def final_info(self):
1602 if not PYTHON_PACKAGE_DIR.startswith(PREFIX) and PYTHON_INSTALL_ENABLED:
1603 print("Warning: The detected Python package directory (%s) is not "
1604 "in the installation prefix (%s). This can lead to a broken "
1605 "Python API installation. Use --pypkgdir= to change the "
1606 "Python package directory." % (PYTHON_PACKAGE_DIR, PREFIX))
1607
1608 def main_component(self):
1609 return False
1610
1611 def mk_install(self, out):
1612 if not is_python_install_enabled():
1613 return
1614 MakeRuleCmd.make_install_directory(out,
1615 os.path.join(self.pythonPkgDir, 'z3'),
1616 in_prefix=self.in_prefix_install)
1617 MakeRuleCmd.make_install_directory(out,
1618 os.path.join(self.pythonPkgDir, 'z3', 'lib'),
1619 in_prefix=self.in_prefix_install)
1620
1621 # Sym-link or copy libz3 into python package directory
1622 if IS_WINDOWS or IS_OSX:
1623 MakeRuleCmd.install_files(out,
1624 self.libz3Component.dll_file(),
1625 os.path.join(self.pythonPkgDir, 'z3', 'lib',
1626 self.libz3Component.dll_file()),
1627 in_prefix=self.in_prefix_install
1628 )
1629 else:
1630 # Create symbolic link to save space.
1631 # It's important that this symbolic link be relative (rather
1632 # than absolute) so that the install is relocatable (needed for
1633 # staged installs that use DESTDIR).
1634 MakeRuleCmd.create_relative_symbolic_link(out,
1635 self.libz3Component.install_path(),
1636 os.path.join(self.pythonPkgDir, 'z3', 'lib',
1637 self.libz3Component.dll_file()
1638 ),
1639 )
1640
1641 MakeRuleCmd.install_files(out, os.path.join('python', 'z3', '*.py'),
1642 os.path.join(self.pythonPkgDir, 'z3'),
1643 in_prefix=self.in_prefix_install)
1644 if sys.version >= "3":
1645 pythonPycacheDir = os.path.join(self.pythonPkgDir, 'z3', '__pycache__')
1646 MakeRuleCmd.make_install_directory(out,
1647 pythonPycacheDir,
1648 in_prefix=self.in_prefix_install)
1649 MakeRuleCmd.install_files(out,
1650 os.path.join('python', 'z3', '__pycache__', '*.pyc'),
1651 pythonPycacheDir,
1652 in_prefix=self.in_prefix_install)
1653 else:
1654 MakeRuleCmd.install_files(out,
1655 os.path.join('python', 'z3', '*.pyc'),
1656 os.path.join(self.pythonPkgDir,'z3'),
1657 in_prefix=self.in_prefix_install)
1658
1659 if PYTHON_PACKAGE_DIR != sysconfig.get_path('purelib'):
1660 out.write('\t@echo Z3Py was installed at \'%s\', make sure this directory is in your PYTHONPATH environment variable.' % PYTHON_PACKAGE_DIR)
1661
1662 def mk_uninstall(self, out):
1663 if not is_python_install_enabled():
1664 return
1665 MakeRuleCmd.remove_installed_files(out,
1666 os.path.join(self.pythonPkgDir,
1667 self.libz3Component.dll_file()),
1668 in_prefix=self.in_prefix_install
1669 )
1670 MakeRuleCmd.remove_installed_files(out,
1671 os.path.join(self.pythonPkgDir, 'z3', '*.py'),
1672 in_prefix=self.in_prefix_install)
1673 MakeRuleCmd.remove_installed_files(out,
1674 os.path.join(self.pythonPkgDir, 'z3', '*.pyc'),
1675 in_prefix=self.in_prefix_install)
1676 MakeRuleCmd.remove_installed_files(out,
1677 os.path.join(self.pythonPkgDir, 'z3', '__pycache__', '*.pyc'),
1678 in_prefix=self.in_prefix_install
1679 )
1680 MakeRuleCmd.remove_installed_files(out,
1681 os.path.join(self.pythonPkgDir, 'z3', 'lib',
1682 self.libz3Component.dll_file()))
1683
1684 def mk_makefile(self, out):
1685 return
1686
1687 def set_key_file(self):
1688 global DOTNET_KEY_FILE
1689 # We need to give the assembly a strong name so that it
1690 # can be installed into the GAC with ``make install``
1691 if not DOTNET_KEY_FILE is None:
1692 self.key_file = DOTNET_KEY_FILE
1693
1694 if not self.key_file is None:
1695 if os.path.isfile(self.key_file):
1696 self.key_file = os.path.abspath(self.key_file)
1697 elif os.path.isfile(os.path.join(self.src_dir, self.key_file)):
1698 self.key_file = os.path.abspath(os.path.join(self.src_dir, self.key_file))
1699 else:
1700 print("Keyfile '%s' could not be found; %s.dll will be unsigned." % (self.key_file, self.dll_name))
1701 self.key_file = None
1702
1703
1704 # build for dotnet core
1705 class DotNetDLLComponent(Component):
1706 def __init__(self, name, dll_name, path, deps, assembly_info_dir, default_key_file):
1707 Component.__init__(self, name, path, deps)
1708 if dll_name is None:
1709 dll_name = name
1710 if assembly_info_dir is None:
1711 assembly_info_dir = "."
1712 self.dll_name = dll_name
1713 self.assembly_info_dir = assembly_info_dir
1714 self.key_file = default_key_file
1715
1716
1717 def mk_makefile(self, out):
1718 if not is_dotnet_core_enabled():
1719 return
1720 cs_fp_files = []
1721 for cs_file in get_cs_files(self.src_dir):
1722 cs_fp_files.append(os.path.join(self.to_src_dir, cs_file))
1723 if self.assembly_info_dir != '.':
1724 for cs_file in get_cs_files(os.path.join(self.src_dir, self.assembly_info_dir)):
1725 cs_fp_files.append(os.path.join(self.to_src_dir, self.assembly_info_dir, cs_file))
1726 dllfile = '%s.dll' % self.dll_name
1727 out.write('%s: %s$(SO_EXT)' % (dllfile, get_component(Z3_DLL_COMPONENT).dll_name))
1728 for cs_file in cs_fp_files:
1729 out.write(' ')
1730 out.write(cs_file)
1731 out.write('\n')
1732
1733 set_key_file(self)
1734 key = ""
1735 if not self.key_file is None:
1736 key = "<AssemblyOriginatorKeyFile>%s</AssemblyOriginatorKeyFile>" % self.key_file
1737 key += "\n<SignAssembly>true</SignAssembly>"
1738
1739 version = get_version_string(4)
1740
1741 print("Version output to csproj:", version)
1742
1743 core_csproj_str = r"""<Project Sdk="Microsoft.NET.Sdk">
1744
1745 <PropertyGroup>
1746 <TargetFramework>netstandard1.4</TargetFramework>
1747 <LangVersion>8.0</LangVersion>
1748 <DefineConstants>$(DefineConstants);DOTNET_CORE</DefineConstants>
1749 <DebugType>full</DebugType>
1750 <AssemblyName>Microsoft.Z3</AssemblyName>
1751 <OutputType>Library</OutputType>
1752 <PackageId>Microsoft.Z3</PackageId>
1753 <GenerateDocumentationFile>true</GenerateDocumentationFile>
1754 <RuntimeFrameworkVersion>1.0.4</RuntimeFrameworkVersion>
1755 <Version>%s</Version>
1756 <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
1757 <Authors>Microsoft</Authors>
1758 <Company>Microsoft</Company>
1759 <PackageReadmeFile>README.md</PackageReadmeFile>
1760 <EnableDefaultCompileItems>false</EnableDefaultCompileItems>
1761 <Description>Z3 is a satisfiability modulo theories solver from Microsoft Research.</Description>
1762 <Copyright>Copyright Microsoft Corporation. All rights reserved.</Copyright>
1763 <PackageTags>smt constraint solver theorem prover</PackageTags>
1764 %s
1765 </PropertyGroup>
1766
1767 <ItemGroup>
1768 <Compile Include="..\%s\*.cs;*.cs" Exclude="bin\**;obj\**;**\*.xproj;packages\**" />
1769 <None Include="..\%s\README.md" Pack="true" PackagePath="/"/>
1770 </ItemGroup>
1771
1772 </Project>""" % (version, key, self.to_src_dir, self.to_src_dir)
1773
1774 mk_dir(os.path.join(BUILD_DIR, 'dotnet'))
1775 csproj = os.path.join('dotnet', 'z3.csproj')
1776 with open(os.path.join(BUILD_DIR, csproj), 'w') as ous:
1777 ous.write(core_csproj_str)
1778
1779 dotnetCmdLine = [DOTNET, "build", csproj]
1780
1781 dotnetCmdLine.extend(['-c'])
1782 if DEBUG_MODE:
1783 dotnetCmdLine.extend(['Debug'])
1784 else:
1785 dotnetCmdLine.extend(['Release'])
1786
1787 path = os.path.join(os.path.abspath(BUILD_DIR), ".")
1788 dotnetCmdLine.extend(['-o', "\"%s\"" % path])
1789
1790 MakeRuleCmd.write_cmd(out, ' '.join(dotnetCmdLine))
1791 out.write('\n')
1792 out.write('%s: %s\n\n' % (self.name, dllfile))
1793
1794 def main_component(self):
1795 return is_dotnet_core_enabled()
1796
1797 def has_assembly_info(self):
1798 # TBD: is this required for dotnet core given that version numbers are in z3.csproj file?
1799 return False
1800
1801
1802 def mk_win_dist(self, build_path, dist_path):
1803 if is_dotnet_core_enabled():
1804 mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR))
1805 shutil.copy('%s.dll' % os.path.join(build_path, self.dll_name),
1806 '%s.dll' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name))
1807 shutil.copy('%s.pdb' % os.path.join(build_path, self.dll_name),
1808 '%s.pdb' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name))
1809 shutil.copy('%s.xml' % os.path.join(build_path, self.dll_name),
1810 '%s.xml' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name))
1811 shutil.copy('%s.deps.json' % os.path.join(build_path, self.dll_name),
1812 '%s.deps.json' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name))
1813 if DEBUG_MODE:
1814 shutil.copy('%s.pdb' % os.path.join(build_path, self.dll_name),
1815 '%s.pdb' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name))
1816
1817 def mk_unix_dist(self, build_path, dist_path):
1818 if is_dotnet_core_enabled():
1819 mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR))
1820 shutil.copy('%s.dll' % os.path.join(build_path, self.dll_name),
1821 '%s.dll' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name))
1822 shutil.copy('%s.xml' % os.path.join(build_path, self.dll_name),
1823 '%s.xml' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name))
1824 shutil.copy('%s.deps.json' % os.path.join(build_path, self.dll_name),
1825 '%s.deps.json' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name))
1826
1827 def mk_install_deps(self, out):
1828 pass
1829
1830 def mk_install(self, out):
1831 pass
1832
1833 def mk_uninstall(self, out):
1834 pass
1835
1836 class JavaDLLComponent(Component):
1837 def __init__(self, name, dll_name, package_name, manifest_file, path, deps):
1838 Component.__init__(self, name, path, deps)
1839 if dll_name is None:
1840 dll_name = name
1841 self.dll_name = dll_name
1842 self.package_name = package_name
1843 self.manifest_file = manifest_file
1844 self.install = not is_windows()
1845
1846 def mk_makefile(self, out):
1847 global JAVAC
1848 global JAR
1849
1850 if is_java_enabled():
1851 mk_dir(os.path.join(BUILD_DIR, 'api', 'java', 'classes'))
1852 dllfile = '%s$(SO_EXT)' % self.dll_name
1853 out.write('libz3java$(SO_EXT): libz3$(SO_EXT) %s\n' % os.path.join(self.to_src_dir, 'Native.cpp'))
1854 t = '\t$(CXX) $(CXXFLAGS) $(CXX_OUT_FLAG)api/java/Native$(OBJ_EXT) -I"%s" -I"%s/PLATFORM" -I%s %s/Native.cpp\n' % (JNI_HOME, JNI_HOME, get_component('api').to_src_dir, self.to_src_dir)
1855 if IS_OSX:
1856 t = t.replace('PLATFORM', 'darwin')
1857 elif is_linux():
1858 t = t.replace('PLATFORM', 'linux')
1859 elif is_hurd():
1860 t = t.replace('PLATFORM', 'hurd')
1861 elif IS_FREEBSD:
1862 t = t.replace('PLATFORM', 'freebsd')
1863 elif IS_NETBSD:
1864 t = t.replace('PLATFORM', 'netbsd')
1865 elif IS_OPENBSD:
1866 t = t.replace('PLATFORM', 'openbsd')
1867 elif IS_SUNOS:
1868 t = t.replace('PLATFORM', 'SunOS')
1869 elif IS_CYGWIN:
1870 t = t.replace('PLATFORM', 'cygwin')
1871 elif IS_MSYS2:
1872 t = t.replace('PLATFORM', 'win32')
1873 else:
1874 t = t.replace('PLATFORM', 'win32')
1875 out.write(t)
1876 if IS_WINDOWS: # On Windows, CL creates a .lib file to link against.
1877 out.write('\t$(SLINK) $(SLINK_OUT_FLAG)libz3java$(SO_EXT) $(SLINK_FLAGS) %s$(OBJ_EXT) libz3$(LIB_EXT)\n' %
1878 os.path.join('api', 'java', 'Native'))
1879 elif IS_OSX and IS_ARCH_ARM64:
1880 out.write('\t$(SLINK) $(SLINK_OUT_FLAG)libz3java$(SO_EXT) $(SLINK_FLAGS) -arch arm64 %s$(OBJ_EXT) libz3$(SO_EXT)\n' %
1881 os.path.join('api', 'java', 'Native'))
1882 else:
1883 out.write('\t$(SLINK) $(SLINK_OUT_FLAG)libz3java$(SO_EXT) $(SLINK_FLAGS) %s$(OBJ_EXT) libz3$(SO_EXT)\n' %
1884 os.path.join('api', 'java', 'Native'))
1885 out.write('%s.jar: libz3java$(SO_EXT) ' % self.package_name)
1886 deps = ''
1887 for jfile in get_java_files(self.src_dir):
1888 deps += ('%s ' % os.path.join(self.to_src_dir, jfile))
1889 for jfile in get_java_files(os.path.join(self.src_dir, "enumerations")):
1890 deps += '%s ' % os.path.join(self.to_src_dir, 'enumerations', jfile)
1891 out.write(deps)
1892 out.write('\n')
1893 #if IS_WINDOWS:
1894 JAVAC = '"%s"' % JAVAC
1895 JAR = '"%s"' % JAR
1896 t = ('\t%s -source 1.8 -target 1.8 %s.java -d %s\n' % (JAVAC, os.path.join(self.to_src_dir, 'enumerations', '*'), os.path.join('api', 'java', 'classes')))
1897 out.write(t)
1898 t = ('\t%s -source 1.8 -target 1.8 -cp %s %s.java -d %s\n' % (JAVAC,
1899 os.path.join('api', 'java', 'classes'),
1900 os.path.join(self.to_src_dir, '*'),
1901 os.path.join('api', 'java', 'classes')))
1902 out.write(t)
1903 out.write('\t%s cfm %s.jar %s -C %s .\n' % (JAR, self.package_name,
1904 os.path.join(self.to_src_dir, 'manifest'),
1905 os.path.join('api', 'java', 'classes')))
1906 out.write('java: %s.jar\n\n' % self.package_name)
1907
1908 def main_component(self):
1909 return is_java_enabled()
1910
1911 def mk_win_dist(self, build_path, dist_path):
1912 if JAVA_ENABLED:
1913 mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR))
1914 shutil.copy('%s.jar' % os.path.join(build_path, self.package_name),
1915 '%s.jar' % os.path.join(dist_path, INSTALL_BIN_DIR, self.package_name))
1916 shutil.copy(os.path.join(build_path, 'libz3java.dll'),
1917 os.path.join(dist_path, INSTALL_BIN_DIR, 'libz3java.dll'))
1918 shutil.copy(os.path.join(build_path, 'libz3java.lib'),
1919 os.path.join(dist_path, INSTALL_BIN_DIR, 'libz3java.lib'))
1920
1921 def mk_unix_dist(self, build_path, dist_path):
1922 if JAVA_ENABLED:
1923 mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR))
1924 shutil.copy('%s.jar' % os.path.join(build_path, self.package_name),
1925 '%s.jar' % os.path.join(dist_path, INSTALL_BIN_DIR, self.package_name))
1926 so = get_so_ext()
1927 shutil.copy(os.path.join(build_path, 'libz3java.%s' % so),
1928 os.path.join(dist_path, INSTALL_BIN_DIR, 'libz3java.%s' % so))
1929
1930 def mk_install(self, out):
1931 if is_java_enabled() and self.install:
1932 dllfile = '%s$(SO_EXT)' % self.dll_name
1933 MakeRuleCmd.install_files(out, dllfile, os.path.join(INSTALL_LIB_DIR, dllfile))
1934 jarfile = '{}.jar'.format(self.package_name)
1935 MakeRuleCmd.install_files(out, jarfile, os.path.join(INSTALL_LIB_DIR, jarfile))
1936
1937 def mk_uninstall(self, out):
1938 if is_java_enabled() and self.install:
1939 dllfile = '%s$(SO_EXT)' % self.dll_name
1940 MakeRuleCmd.remove_installed_files(out, os.path.join(INSTALL_LIB_DIR, dllfile))
1941 jarfile = '{}.jar'.format(self.package_name)
1942 MakeRuleCmd.remove_installed_files(out, os.path.join(INSTALL_LIB_DIR, jarfile))
1943
1944 class MLComponent(Component):
1945
1946 def __init__(self, name, lib_name, path, deps):
1947 Component.__init__(self, name, path, deps)
1948 if lib_name is None:
1949 lib_name = name
1950 self.lib_name = lib_name
1951 self.modules = ["z3enums", "z3native", "z3"] # dependencies in this order!
1952 self.stubs = "z3native_stubs"
1953 self.sub_dir = os.path.join('api', 'ml')
1954
1955 self.destdir = ""
1956 self.ldconf = ""
1957 # Calling _init_ocamlfind_paths() is postponed to later because
1958 # OCAMLFIND hasn't been checked yet.
1959
1960 def _install_bindings(self):
1961 # FIXME: Depending on global state is gross. We can't pre-compute this
1962 # in the constructor because we haven't tested for ocamlfind yet
1963 return OCAMLFIND != ''
1964
1965 def _init_ocamlfind_paths(self):
1966 """
1967 Initialises self.destdir and self.ldconf
1968 Do not call this from the MLComponent constructor because OCAMLFIND
1969 has not been checked at that point
1970 """
1971 if self.destdir != "" and self.ldconf != "":
1972 # Initialisation already done
1973 return
1974 # Use Ocamlfind to get the default destdir and ldconf path
1975 self.destdir = check_output([OCAMLFIND, 'printconf', 'destdir'])
1976 if self.destdir == "":
1977 raise MKException('Failed to get OCaml destdir')
1978
1979 if not os.path.isdir(self.destdir):
1980 raise MKException('The destdir reported by {ocamlfind} ({destdir}) does not exist'.format(ocamlfind=OCAMLFIND, destdir=self.destdir))
1981
1982 self.ldconf = check_output([OCAMLFIND, 'printconf', 'ldconf'])
1983 if self.ldconf == "":
1984 raise MKException('Failed to get OCaml ldconf path')
1985
1986 def final_info(self):
1987 if not self._install_bindings():
1988 print("WARNING: Could not find ocamlfind utility. OCaml bindings will not be installed")
1989
1990 def mk_makefile(self, out):
1991 if is_ml_enabled():
1992 CP_CMD = 'cp'
1993 if IS_WINDOWS:
1994 CP_CMD='copy'
1995
1996 OCAML_FLAGS = ''
1997 if DEBUG_MODE:
1998 OCAML_FLAGS += '-g'
1999
2000 if OCAMLFIND:
2001 OCAMLCF = OCAMLFIND + ' ' + 'ocamlc -package zarith' + ' ' + OCAML_FLAGS
2002 OCAMLOPTF = OCAMLFIND + ' ' + 'ocamlopt -package zarith' + ' ' + OCAML_FLAGS
2003 else:
2004 OCAMLCF = OCAMLC + ' ' + OCAML_FLAGS
2005 OCAMLOPTF = OCAMLOPT + ' ' + OCAML_FLAGS
2006
2007 src_dir = self.to_src_dir
2008 mk_dir(os.path.join(BUILD_DIR, self.sub_dir))
2009 api_src = get_component(API_COMPONENT).to_src_dir
2010 # remove /GL and -std=c++20; the ocaml tools don't like them.
2011 if IS_WINDOWS:
2012 out.write('CXXFLAGS_OCAML=$(CXXFLAGS:/GL=)\n')
2013 else:
2014 out.write('CXXFLAGS_OCAML=$(subst -std=c++20,,$(CXXFLAGS))\n')
2015
2016 substitutions = { 'VERSION': "{}.{}.{}.{}".format(VER_MAJOR, VER_MINOR, VER_BUILD, VER_TWEAK) }
2017
2018 configure_file(os.path.join(self.src_dir, 'META.in'),
2019 os.path.join(BUILD_DIR, self.sub_dir, 'META'),
2020 substitutions)
2021
2022 stubsc = os.path.join(src_dir, self.stubs + '.c')
2023 stubso = os.path.join(self.sub_dir, self.stubs) + '$(OBJ_EXT)'
2024 base_dll_name = get_component(Z3_DLL_COMPONENT).dll_name
2025 if STATIC_LIB:
2026 z3link = 'z3-static'
2027 z3linkdep = base_dll_name + '-static$(LIB_EXT)'
2028 out.write('%s: %s\n' % (z3linkdep, base_dll_name + '$(LIB_EXT)'))
2029 out.write('\tcp $< $@\n')
2030 else:
2031 z3link = 'z3'
2032 z3linkdep = base_dll_name + '$(SO_EXT)'
2033 out.write('%s: %s %s\n' % (stubso, stubsc, z3linkdep))
2034 out.write('\t%s -ccopt "$(CXXFLAGS_OCAML) -I %s -I %s -I %s $(CXX_OUT_FLAG)%s" -c %s\n' %
2035 (OCAMLCF, OCAML_LIB, api_src, src_dir, stubso, stubsc))
2036
2037 cmos = ''
2038 for m in self.modules:
2039 ml = os.path.join(src_dir, m + '.ml')
2040 cmo = os.path.join(self.sub_dir, m + '.cmo')
2041 existing_mli = os.path.join(src_dir, m + '.mli')
2042 mli = os.path.join(self.sub_dir, m + '.mli')
2043 cmi = os.path.join(self.sub_dir, m + '.cmi')
2044 out.write('%s: %s %s\n' % (cmo, ml, cmos))
2045 if (os.path.exists(existing_mli[3:])):
2046 out.write('\t%s %s %s\n' % (CP_CMD, existing_mli, mli))
2047 else:
2048 out.write('\t%s -i -I %s -c %s > %s\n' % (OCAMLCF, self.sub_dir, ml, mli))
2049 out.write('\t%s -I %s -o %s -c %s\n' % (OCAMLCF, self.sub_dir, cmi, mli))
2050 out.write('\t%s -I %s -o %s -c %s\n' % (OCAMLCF, self.sub_dir, cmo, ml))
2051 cmos = cmos + cmo + ' '
2052
2053 cmxs = ''
2054 for m in self.modules:
2055 ff = os.path.join(src_dir, m + '.ml')
2056 ft = os.path.join(self.sub_dir, m + '.cmx')
2057 out.write('%s: %s %s %s\n' % (ft, ff, cmos, cmxs))
2058 out.write('\t%s -I %s -o %s -c %s\n' % (OCAMLOPTF, self.sub_dir, ft, ff))
2059 cmxs = cmxs + ' ' + ft
2060
2061
2062 OCAMLMKLIB = 'ocamlmklib'
2063
2064 LIBZ3 = '-l' + z3link + ' -lstdc++'
2065 if is_cygwin() and not(is_cygwin_mingw()):
2066 LIBZ3 = z3linkdep
2067
2068 LIBZ3 = LIBZ3 + ' ' + ' '.join(map(lambda x: '-cclib ' + x, LDFLAGS.split()))
2069
2070 stubs_install_path = '$$(%s printconf destdir)/stublibs' % OCAMLFIND
2071 if not STATIC_LIB:
2072 loadpath = '-ccopt -L' + stubs_install_path
2073 dllpath = '-dllpath ' + stubs_install_path
2074 LIBZ3 = LIBZ3 + ' ' + loadpath + ' ' + dllpath
2075
2076 if DEBUG_MODE and not(is_cygwin()):
2077 # Some ocamlmklib's don't like -g; observed on cygwin, but may be others as well.
2078 OCAMLMKLIB += ' -g'
2079
2080 z3mls = os.path.join(self.sub_dir, 'z3ml')
2081
2082 LIBZ3ML = ''
2083 if STATIC_LIB:
2084 LIBZ3ML = '-oc ' + os.path.join(self.sub_dir, 'z3ml-static')
2085
2086 out.write('%s.cma: %s %s %s\n' % (z3mls, cmos, stubso, z3linkdep))
2087 out.write('\t%s -o %s %s -I %s -L. %s %s %s\n' % (OCAMLMKLIB, z3mls, LIBZ3ML, self.sub_dir, stubso, cmos, LIBZ3))
2088 out.write('%s.cmxa: %s %s %s %s.cma\n' % (z3mls, cmxs, stubso, z3linkdep, z3mls))
2089 out.write('\t%s -o %s %s -I %s -L. %s %s %s\n' % (OCAMLMKLIB, z3mls, LIBZ3ML, self.sub_dir, stubso, cmxs, LIBZ3))
2090 out.write('%s.cmxs: %s.cmxa\n' % (z3mls, z3mls))
2091 out.write('\t%s -linkall -shared -o %s.cmxs -I . -I %s %s.cmxa\n' % (OCAMLOPTF, z3mls, self.sub_dir, z3mls))
2092
2093 out.write('\n')
2094 out.write('ml: %s.cma %s.cmxa %s.cmxs\n' % (z3mls, z3mls, z3mls))
2095 if IS_OSX:
2096 out.write('\tinstall_name_tool -id %s/libz3.dylib libz3.dylib\n' % (stubs_install_path))
2097 out.write('\tinstall_name_tool -change libz3.dylib %s/libz3.dylib api/ml/dllz3ml.so\n' % (stubs_install_path))
2098 out.write('\n')
2099
2100 if IS_WINDOWS:
2101 out.write('ocamlfind_install: ')
2102 self.mk_install_deps(out)
2103 out.write('\n')
2104 self.mk_install(out)
2105 out.write('\n')
2106 out.write('ocamlfind_uninstall:\n')
2107 self.mk_uninstall(out)
2108 out.write('\n')
2109
2110 # The following three functions may be out of date.
2111 def mk_install_deps(self, out):
2112 if is_ml_enabled() and self._install_bindings():
2113 out.write(get_component(Z3_DLL_COMPONENT).dll_name + '$(SO_EXT) ')
2114 out.write(os.path.join(self.sub_dir, 'META '))
2115 out.write(os.path.join(self.sub_dir, 'z3ml.cma '))
2116 out.write(os.path.join(self.sub_dir, 'z3ml.cmxa '))
2117 out.write(os.path.join(self.sub_dir, 'z3ml.cmxs '))
2118
2119 def mk_install(self, out):
2120 if is_ml_enabled() and self._install_bindings():
2121 self._init_ocamlfind_paths()
2122 in_prefix = self.destdir.startswith(PREFIX)
2123 maybe_stripped_destdir = strip_path_prefix(self.destdir, PREFIX)
2124 # Note that when doing a staged install with DESTDIR that modifying
2125 # OCaml's ``ld.conf`` may fail. Therefore packagers will need to
2126 # make their packages modify it manually at package install time
2127 # as opposed to ``make install`` time.
2128 MakeRuleCmd.make_install_directory(out,
2129 maybe_stripped_destdir,
2130 in_prefix=in_prefix)
2131 out.write('\t@{ocamlfind} install -ldconf $(DESTDIR){ldconf} -destdir $(DESTDIR){ocaml_destdir} Z3 {metafile}'.format(
2132 ldconf=self.ldconf,
2133 ocamlfind=OCAMLFIND,
2134 ocaml_destdir=self.destdir,
2135 metafile=os.path.join(self.sub_dir, 'META')))
2136
2137 for m in self.modules:
2138 mli = os.path.join(self.src_dir, m) + '.mli'
2139 if os.path.exists(mli):
2140 out.write(' ' + os.path.join(self.to_src_dir, m) + '.mli')
2141 else:
2142 out.write(' ' + os.path.join(self.sub_dir, m) + '.mli')
2143 out.write(' ' + os.path.join(self.sub_dir, m) + '.cmi')
2144 out.write(' ' + os.path.join(self.sub_dir, m) + '.cmx')
2145 out.write(' %s' % ((os.path.join(self.sub_dir, 'libz3ml$(LIB_EXT)'))))
2146 out.write(' %s' % ((os.path.join(self.sub_dir, 'z3ml$(LIB_EXT)'))))
2147 out.write(' %s' % ((os.path.join(self.sub_dir, 'z3ml.cma'))))
2148 out.write(' %s' % ((os.path.join(self.sub_dir, 'z3ml.cmxa'))))
2149 out.write(' %s' % ((os.path.join(self.sub_dir, 'z3ml.cmxs'))))
2150 out.write(' %s' % ((os.path.join(self.sub_dir, 'dllz3ml'))))
2151 if is_windows() or is_cygwin_mingw() or is_msys2():
2152 out.write('.dll')
2153 else:
2154 out.write('.so') # .so also on OSX!
2155 out.write('\n')
2156
2157 def mk_uninstall(self, out):
2158 if is_ml_enabled() and self._install_bindings():
2159 self._init_ocamlfind_paths()
2160 out.write('\t@{ocamlfind} remove -ldconf $(DESTDIR){ldconf} -destdir $(DESTDIR){ocaml_destdir} Z3\n'.format(
2161 ldconf=self.ldconf,
2162 ocamlfind=OCAMLFIND,
2163 ocaml_destdir=self.destdir))
2164
2165 def main_component(self):
2166 return is_ml_enabled()
2167
2168 class ExampleComponent(Component):
2169 def __init__(self, name, path):
2170 Component.__init__(self, name, path, [])
2171 self.ex_dir = os.path.join(EXAMPLE_DIR, self.path)
2172 self.to_ex_dir = os.path.join(REV_BUILD_DIR, self.ex_dir)
2173
2174 def is_example(self):
2175 return True
2176
2177 class CppExampleComponent(ExampleComponent):
2178 def __init__(self, name, path):
2179 ExampleComponent.__init__(self, name, path)
2180
2181 def compiler(self):
2182 return "$(CXX)"
2183
2184 def src_files(self):
2185 return get_cpp_files(self.ex_dir)
2186
2187 def mk_makefile(self, out):
2188 dll_name = get_component(Z3_DLL_COMPONENT).dll_name
2189 dll = '%s$(SO_EXT)' % dll_name
2190
2191 objfiles = ''
2192 for cppfile in self.src_files():
2193 objfile = '%s$(OBJ_EXT)' % (cppfile[:cppfile.rfind('.')])
2194 objfiles = objfiles + ('%s ' % objfile)
2195 out.write('%s: %s\n' % (objfile, os.path.join(self.to_ex_dir, cppfile)));
2196 out.write('\t%s $(CXXFLAGS) $(OS_DEFINES) $(EXAMP_DEBUG_FLAG) $(CXX_OUT_FLAG)%s $(LINK_FLAGS)' % (self.compiler(), objfile))
2197 # Add include dir components
2198 out.write(' -I%s' % get_component(API_COMPONENT).to_src_dir)
2199 out.write(' -I%s' % get_component(CPP_COMPONENT).to_src_dir)
2200 out.write(' %s' % os.path.join(self.to_ex_dir, cppfile))
2201 out.write('\n')
2202
2203 exefile = '%s$(EXE_EXT)' % self.name
2204 out.write('%s: %s %s\n' % (exefile, dll, objfiles))
2205 out.write('\t$(LINK) $(LINK_OUT_FLAG)%s $(LINK_FLAGS) %s ' % (exefile, objfiles))
2206 if IS_WINDOWS:
2207 out.write('%s.lib' % dll_name)
2208 else:
2209 out.write(dll)
2210 out.write(' $(LINK_EXTRA_FLAGS)\n')
2211 out.write('_ex_%s: %s\n\n' % (self.name, exefile))
2212
2213 class CExampleComponent(CppExampleComponent):
2214 def __init__(self, name, path):
2215 CppExampleComponent.__init__(self, name, path)
2216
2217 def compiler(self):
2218 return "$(CC)"
2219
2220 def src_files(self):
2221 return get_c_files(self.ex_dir)
2222
2223 def mk_makefile(self, out):
2224 dll_name = get_component(Z3_DLL_COMPONENT).dll_name
2225 dll = '%s$(SO_EXT)' % dll_name
2226
2227 objfiles = ''
2228 for cfile in self.src_files():
2229 objfile = '%s$(OBJ_EXT)' % (cfile[:cfile.rfind('.')])
2230 objfiles = objfiles + ('%s ' % objfile)
2231 out.write('%s: %s\n' % (objfile, os.path.join(self.to_ex_dir, cfile)));
2232 out.write('\t%s $(CFLAGS) $(OS_DEFINES) $(EXAMP_DEBUG_FLAG) $(C_OUT_FLAG)%s $(LINK_FLAGS)' % (self.compiler(), objfile))
2233 out.write(' -I%s' % get_component(API_COMPONENT).to_src_dir)
2234 out.write(' %s' % os.path.join(self.to_ex_dir, cfile))
2235 out.write('\n')
2236
2237 exefile = '%s$(EXE_EXT)' % self.name
2238 out.write('%s: %s %s\n' % (exefile, dll, objfiles))
2239 out.write('\t$(LINK) $(LINK_OUT_FLAG)%s $(LINK_FLAGS) %s ' % (exefile, objfiles))
2240 if IS_WINDOWS:
2241 out.write('%s.lib' % dll_name)
2242 else:
2243 out.write(dll)
2244 out.write(' $(LINK_EXTRA_FLAGS)\n')
2245 out.write('_ex_%s: %s\n\n' % (self.name, exefile))
2246
2247 class DotNetExampleComponent(ExampleComponent):
2248 def __init__(self, name, path):
2249 ExampleComponent.__init__(self, name, path)
2250
2251 def is_example(self):
2252 return is_dotnet_core_enabled()
2253
2254 def mk_makefile(self, out):
2255 if is_dotnet_core_enabled():
2256 proj_name = 'dotnet_example.csproj'
2257 out.write('_ex_%s:' % self.name)
2258 for csfile in get_cs_files(self.ex_dir):
2259 out.write(' ')
2260 out.write(os.path.join(self.to_ex_dir, csfile))
2261
2262 mk_dir(os.path.join(BUILD_DIR, 'dotnet_example'))
2263 csproj = os.path.join('dotnet_example', proj_name)
2264 if VS_X64:
2265 platform = 'x64'
2266 elif VS_ARM:
2267 platform = 'ARM'
2268 else:
2269 platform = 'x86'
2270
2271 dotnet_proj_str = r"""<Project Sdk="Microsoft.NET.Sdk">
2272 <PropertyGroup>
2273 <OutputType>Exe</OutputType>
2274 <TargetFramework>netcoreapp2.0</TargetFramework>
2275 <PlatformTarget>%s</PlatformTarget>
2276 </PropertyGroup>
2277 <ItemGroup>
2278 <Compile Include="..\%s/*.cs" />
2279 <Reference Include="Microsoft.Z3">
2280 <HintPath>..\Microsoft.Z3.dll</HintPath>
2281 </Reference>
2282 </ItemGroup>
2283 </Project>""" % (platform, self.to_ex_dir)
2284
2285 with open(os.path.join(BUILD_DIR, csproj), 'w') as ous:
2286 ous.write(dotnet_proj_str)
2287
2288 out.write('\n')
2289 dotnetCmdLine = [DOTNET, "build", csproj]
2290 dotnetCmdLine.extend(['-c'])
2291 if DEBUG_MODE:
2292 dotnetCmdLine.extend(['Debug'])
2293 else:
2294 dotnetCmdLine.extend(['Release'])
2295 MakeRuleCmd.write_cmd(out, ' '.join(dotnetCmdLine))
2296 out.write('\n')
2297
2298 class JavaExampleComponent(ExampleComponent):
2299 def __init__(self, name, path):
2300 ExampleComponent.__init__(self, name, path)
2301
2302 def is_example(self):
2303 return JAVA_ENABLED
2304
2305 def mk_makefile(self, out):
2306 if JAVA_ENABLED:
2307 pkg = get_component(JAVA_COMPONENT).package_name + '.jar'
2308 out.write('JavaExample.class: %s' % (pkg))
2309 deps = ''
2310 for jfile in get_java_files(self.ex_dir):
2311 out.write(' %s' % os.path.join(self.to_ex_dir, jfile))
2312 if IS_WINDOWS:
2313 deps = deps.replace('/', '\\')
2314 out.write('%s\n' % deps)
2315 out.write('\t%s -cp %s ' % (JAVAC, pkg))
2316 win_ex_dir = self.to_ex_dir
2317 for javafile in get_java_files(self.ex_dir):
2318 out.write(' ')
2319 out.write(os.path.join(win_ex_dir, javafile))
2320 out.write(' -d .\n')
2321 out.write('_ex_%s: JavaExample.class\n\n' % (self.name))
2322
2323 class MLExampleComponent(ExampleComponent):
2324 def __init__(self, name, path):
2325 ExampleComponent.__init__(self, name, path)
2326
2327 def is_example(self):
2328 return ML_ENABLED
2329
2330 def mk_makefile(self, out):
2331 if ML_ENABLED:
2332 out.write('ml_example.byte: api/ml/z3ml.cma')
2333 for mlfile in get_ml_files(self.ex_dir):
2334 out.write(' %s' % os.path.join(self.to_ex_dir, mlfile))
2335 out.write('\n')
2336 out.write('\tocamlfind %s ' % OCAMLC)
2337 if DEBUG_MODE:
2338 out.write('-g ')
2339 out.write('-custom -o ml_example.byte -package zarith -I api/ml -cclib "-L. -lpthread -lstdc++ -lz3" -linkpkg z3ml.cma')
2340 for mlfile in get_ml_files(self.ex_dir):
2341 out.write(' %s/%s' % (self.to_ex_dir, mlfile))
2342 out.write('\n')
2343 out.write('ml_example$(EXE_EXT): api/ml/z3ml.cmxa')
2344 for mlfile in get_ml_files(self.ex_dir):
2345 out.write(' %s' % os.path.join(self.to_ex_dir, mlfile))
2346 out.write('\n')
2347 out.write('\tocamlfind %s ' % OCAMLOPT)
2348 if DEBUG_MODE:
2349 out.write('-g ')
2350 out.write('-o ml_example$(EXE_EXT) -package zarith -I api/ml -cclib "-L. -lpthread -lstdc++ -lz3" -linkpkg z3ml.cmxa')
2351 for mlfile in get_ml_files(self.ex_dir):
2352 out.write(' %s/%s' % (self.to_ex_dir, mlfile))
2353 out.write('\n')
2354 out.write('_ex_%s: ml_example.byte ml_example$(EXE_EXT)\n\n' % self.name)
2355
2356 debug_opt = '-g ' if DEBUG_MODE else ''
2357
2358 if STATIC_LIB:
2359 opam_z3_opts = '-thread -package z3-static -linkpkg'
2360 ml_post_install_tests = [
2361 (OCAMLC, 'ml_example_static.byte'),
2362 (OCAMLC + ' -custom', 'ml_example_static_custom.byte'),
2363 (OCAMLOPT, 'ml_example_static$(EXE_EXT)')
2364 ]
2365 else:
2366 opam_z3_opts = '-thread -package z3 -linkpkg'
2367 ml_post_install_tests = [
2368 (OCAMLC, 'ml_example_shared.byte'),
2369 (OCAMLC + ' -custom', 'ml_example_shared_custom.byte'),
2370 (OCAMLOPT, 'ml_example_shared$(EXE_EXT)')
2371 ]
2372
2373 for ocaml_compiler, testname in ml_post_install_tests:
2374 out.write(testname + ':')
2375 for mlfile in get_ml_files(self.ex_dir):
2376 out.write(' %s' % os.path.join(self.to_ex_dir, mlfile))
2377 out.write('\n')
2378 out.write('\tocamlfind %s -o %s %s %s ' % (ocaml_compiler, debug_opt, testname, opam_z3_opts))
2379 for mlfile in get_ml_files(self.ex_dir):
2380 out.write(' %s/%s' % (self.to_ex_dir, mlfile))
2381 out.write('\n')
2382
2383 if STATIC_LIB:
2384 out.write('_ex_ml_example_post_install: ml_example_static.byte ml_example_static_custom.byte ml_example_static$(EXE_EXT)\n')
2385 else:
2386 out.write('_ex_ml_example_post_install: ml_example_shared.byte ml_example_shared_custom.byte ml_example_shared$(EXE_EXT)\n')
2387
2388 out.write('\n')
2389
2390
2391 class PythonExampleComponent(ExampleComponent):
2392 def __init__(self, name, path):
2393 ExampleComponent.__init__(self, name, path)
2394
2395 # Python examples are just placeholders, we just copy the *.py files when mk_makefile is invoked.
2396 # We don't need to include them in the :examples rule
2397 def mk_makefile(self, out):
2398 full = os.path.join(EXAMPLE_DIR, self.path)
2399 for py in filter(lambda f: f.endswith('.py'), os.listdir(full)):
2400 shutil.copyfile(os.path.join(full, py), os.path.join(BUILD_DIR, 'python', py))
2401 if is_verbose():
2402 print("Copied Z3Py example '%s' to '%s'" % (py, os.path.join(BUILD_DIR, 'python')))
2403 out.write('_ex_%s: \n\n' % self.name)
2404
2405 def mk_win_dist(self, build_path, dist_path):
2406 full = os.path.join(EXAMPLE_DIR, self.path)
2407 py = 'example.py'
2408 shutil.copyfile(os.path.join(full, py),
2409 os.path.join(dist_path, INSTALL_BIN_DIR, 'python', py))
2410
2411 def mk_unix_dist(self, build_path, dist_path):
2412 self.mk_win_dist(build_path, dist_path)
2413
2414
2415 def reg_component(name, c):
2416 global _Id, _Components, _ComponentNames, _Name2Component
2417 c.id = _Id
2418 _Id = _Id + 1
2419 _Components.append(c)
2420 _ComponentNames.add(name)
2421 _Name2Component[name] = c
2422 if VERBOSE:
2423 print("New component: '%s'" % name)
2424
2425 def add_lib(name, deps=[], path=None, includes2install=[]):
2426 c = LibComponent(name, path, deps, includes2install)
2427 reg_component(name, c)
2428
2429 def add_clib(name, deps=[], path=None, includes2install=[]):
2430 c = CLibComponent(name, path, deps, includes2install)
2431 reg_component(name, c)
2432
2433 def add_hlib(name, path=None, includes2install=[]):
2434 c = HLibComponent(name, path, includes2install)
2435 reg_component(name, c)
2436
2437 def add_exe(name, deps=[], path=None, exe_name=None, install=True):
2438 c = ExeComponent(name, exe_name, path, deps, install)
2439 reg_component(name, c)
2440
2441 def add_extra_exe(name, deps=[], path=None, exe_name=None, install=True):
2442 c = ExtraExeComponent(name, exe_name, path, deps, install)
2443 reg_component(name, c)
2444
2445 def add_dll(name, deps=[], path=None, dll_name=None, export_files=[], reexports=[], install=True, static=False, staging_link=None):
2446 c = DLLComponent(name, dll_name, path, deps, export_files, reexports, install, static, staging_link)
2447 reg_component(name, c)
2448 return c
2449
2450 def add_dot_net_core_dll(name, deps=[], path=None, dll_name=None, assembly_info_dir=None, default_key_file=None):
2451 c = DotNetDLLComponent(name, dll_name, path, deps, assembly_info_dir, default_key_file)
2452 reg_component(name, c)
2453
2454 def add_java_dll(name, deps=[], path=None, dll_name=None, package_name=None, manifest_file=None):
2455 c = JavaDLLComponent(name, dll_name, package_name, manifest_file, path, deps)
2456 reg_component(name, c)
2457
2458 def add_python(libz3Component):
2459 name = 'python'
2460 reg_component(name, PythonComponent(name, libz3Component))
2461
2462 def add_js():
2463 reg_component('js', JsComponent())
2464
2465 def add_python_install(libz3Component):
2466 name = 'python_install'
2467 reg_component(name, PythonInstallComponent(name, libz3Component))
2468
2469 def add_ml_lib(name, deps=[], path=None, lib_name=None):
2470 c = MLComponent(name, lib_name, path, deps)
2471 reg_component(name, c)
2472
2473 def add_cpp_example(name, path=None):
2474 c = CppExampleComponent(name, path)
2475 reg_component(name, c)
2476
2477 def add_c_example(name, path=None):
2478 c = CExampleComponent(name, path)
2479 reg_component(name, c)
2480
2481 def add_dotnet_example(name, path=None):
2482 c = DotNetExampleComponent(name, path)
2483 reg_component(name, c)
2484
2485 def add_java_example(name, path=None):
2486 c = JavaExampleComponent(name, path)
2487 reg_component(name, c)
2488
2489 def add_ml_example(name, path=None):
2490 c = MLExampleComponent(name, path)
2491 reg_component(name, c)
2492
2493 def add_z3py_example(name, path=None):
2494 c = PythonExampleComponent(name, path)
2495 reg_component(name, c)
2496
2497 def mk_config():
2498 if ONLY_MAKEFILES:
2499 return
2500 config = open(os.path.join(BUILD_DIR, 'config.mk'), 'w')
2501 global CXX, CC, GMP, GUARD_CF, STATIC_BIN, GIT_HASH, CPPFLAGS, CXXFLAGS, LDFLAGS, EXAMP_DEBUG_FLAG, FPMATH_FLAGS, LOG_SYNC, SINGLE_THREADED, IS_ARCH_ARM64
2502 if IS_WINDOWS:
2503 CXXFLAGS = '/nologo /Zi /D WIN32 /D _WINDOWS /EHsc /GS /Gd /std:c++20'
2504 config.write(
2505 'CC=cl\n'
2506 'CXX=cl\n'
2507 'CXX_OUT_FLAG=/Fo\n'
2508 'C_OUT_FLAG=/Fo\n'
2509 'OBJ_EXT=.obj\n'
2510 'LIB_EXT=.lib\n'
2511 'AR=lib\n'
2512 'AR_OUTFLAG=/OUT:\n'
2513 'EXE_EXT=.exe\n'
2514 'LINK=cl\n'
2515 'LINK_OUT_FLAG=/Fe\n'
2516 'SO_EXT=.dll\n'
2517 'SLINK=cl\n'
2518 'SLINK_OUT_FLAG=/Fe\n'
2519 'OS_DEFINES=/D _WINDOWS\n')
2520 extra_opt = ''
2521 link_extra_opt = ''
2522 if LOG_SYNC:
2523 extra_opt = '%s /DZ3_LOG_SYNC' % extra_opt
2524 if SINGLE_THREADED:
2525 extra_opt = '%s /DSINGLE_THREAD' % extra_opt
2526 if GIT_HASH:
2527 extra_opt = ' %s /D Z3GITHASH=%s' % (extra_opt, GIT_HASH)
2528 if GUARD_CF:
2529 extra_opt = ' %s /guard:cf' % extra_opt
2530 link_extra_opt = ' %s /GUARD:CF' % link_extra_opt
2531 if STATIC_BIN:
2532 static_opt = '/MT'
2533 else:
2534 static_opt = '/MD'
2535 maybe_disable_dynamic_base = '/DYNAMICBASE' if ALWAYS_DYNAMIC_BASE else '/DYNAMICBASE:NO'
2536 if DEBUG_MODE:
2537 static_opt = static_opt + 'd'
2538 config.write(
2539 'AR_FLAGS=/nologo\n'
2540 'LINK_FLAGS=/nologo %s\n'
2541 'SLINK_FLAGS=/nologo /LDd\n' % static_opt)
2542 if VS_X64:
2543 config.write(
2544 'CXXFLAGS=/c %s /Zi /W3 /WX- /Od /Oy- /D _DEBUG /D Z3DEBUG /D _CONSOLE /D _TRACE /Gm- /RTC1 %s %s\n' % (CXXFLAGS, extra_opt, static_opt))
2545 config.write(
2546 'LINK_EXTRA_FLAGS=/link /PROFILE /DEBUG:full /MACHINE:X64 /SUBSYSTEM:CONSOLE /INCREMENTAL:NO /STACK:8388608 /OPT:REF /OPT:ICF /TLBID:1 /DYNAMICBASE /NXCOMPAT %s\n'
2547 'SLINK_EXTRA_FLAGS=/link /PROFILE /DEBUG:full /MACHINE:X64 /SUBSYSTEM:WINDOWS /INCREMENTAL:NO /STACK:8388608 /OPT:REF /OPT:ICF /TLBID:1 %s %s\n' % (link_extra_opt, maybe_disable_dynamic_base, link_extra_opt))
2548 elif VS_ARM:
2549 print("ARM on VS is unsupported")
2550 exit(1)
2551 else:
2552 config.write(
2553 'CXXFLAGS=/c %s /Zi /W3 /WX- /Od /Oy- /D _DEBUG /D Z3DEBUG /D _CONSOLE /D _TRACE /Gm- /RTC1 /arch:SSE2 %s %s\n' % (CXXFLAGS, extra_opt, static_opt))
2554 config.write(
2555 'LINK_EXTRA_FLAGS=/link /PROFILE /DEBUG:full /MACHINE:X86 /SUBSYSTEM:CONSOLE /INCREMENTAL:NO /STACK:8388608 /OPT:REF /OPT:ICF /TLBID:1 /DYNAMICBASE /NXCOMPAT %s\n'
2556 'SLINK_EXTRA_FLAGS=/link /PROFILE /DEBUG:full /MACHINE:X86 /SUBSYSTEM:WINDOWS /INCREMENTAL:NO /STACK:8388608 /OPT:REF /OPT:ICF /TLBID:1 %s %s\n' % (link_extra_opt, maybe_disable_dynamic_base, link_extra_opt))
2557 else:
2558 # Windows Release mode
2559 LTCG=' /LTCG' if SLOW_OPTIMIZE else ''
2560 GL = ' /GL' if SLOW_OPTIMIZE else ''
2561 config.write(
2562 'AR_FLAGS=/nologo %s\n'
2563 'LINK_FLAGS=/nologo %s\n'
2564 'SLINK_FLAGS=/nologo /LD\n' % (LTCG, static_opt))
2565 if TRACE:
2566 extra_opt = '%s /D _TRACE ' % extra_opt
2567 if VS_X64:
2568 config.write(
2569 'CXXFLAGS=/c%s %s /Zi /W3 /WX- /O2 /D _EXTERNAL_RELEASE /D NDEBUG /D _LIB /D UNICODE /Gm- /GF /Gy /TP %s %s\n' % (GL, CXXFLAGS, extra_opt, static_opt))
2570 config.write(
2571 'LINK_EXTRA_FLAGS=/link%s /PROFILE /DEBUG:full /profile /MACHINE:X64 /SUBSYSTEM:CONSOLE /STACK:8388608 %s\n'
2572 'SLINK_EXTRA_FLAGS=/link%s /PROFILE /DEBUG:full /profile /MACHINE:X64 /SUBSYSTEM:WINDOWS /STACK:8388608 %s\n' % (LTCG, link_extra_opt, LTCG, link_extra_opt))
2573 elif VS_ARM:
2574 print("ARM on VS is unsupported")
2575 exit(1)
2576 else:
2577 config.write(
2578 'CXXFLAGS=/c%s %s /Zi /WX- /O2 /Oy- /D _EXTERNAL_RELEASE /D NDEBUG /D _CONSOLE /D ASYNC_COMMANDS /Gm- /arch:SSE2 %s %s\n' % (GL, CXXFLAGS, extra_opt, static_opt))
2579 config.write(
2580 'LINK_EXTRA_FLAGS=/link%s /PROFILE /DEBUG:full /MACHINE:X86 /SUBSYSTEM:CONSOLE /INCREMENTAL:NO /STACK:8388608 /OPT:REF /OPT:ICF /TLBID:1 /DYNAMICBASE /NXCOMPAT %s\n'
2581 'SLINK_EXTRA_FLAGS=/link%s /PROFILE /DEBUG:full /MACHINE:X86 /SUBSYSTEM:WINDOWS /INCREMENTAL:NO /STACK:8388608 /OPT:REF /OPT:ICF /TLBID:1 %s %s\n' % (LTCG, link_extra_opt, LTCG, maybe_disable_dynamic_base, link_extra_opt))
2582
2583 config.write('CFLAGS=$(CXXFLAGS)\n')
2584
2585 # End of Windows VS config.mk
2586 if is_verbose():
2587 print('64-bit: %s' % is64())
2588 if is_java_enabled():
2589 print('JNI Bindings: %s' % JNI_HOME)
2590 print('Java Compiler: %s' % JAVAC)
2591 if is_ml_enabled():
2592 print('OCaml Compiler: %s' % OCAMLC)
2593 print('OCaml Find tool: %s' % OCAMLFIND)
2594 print('OCaml Native: %s' % OCAMLOPT)
2595 print('OCaml Library: %s' % OCAML_LIB)
2596 else:
2597 OS_DEFINES = ""
2598 ARITH = "internal"
2599 check_ar()
2600 CXX = find_cxx_compiler()
2601 CC = find_c_compiler()
2602 SLIBEXTRAFLAGS = ''
2603 # SLIBEXTRAFLAGS = '%s -Wl,-soname,libz3.so.0' % LDFLAGS
2604 EXE_EXT = ''
2605 LIB_EXT = '.a'
2606 if GPROF:
2607 CXXFLAGS = '%s -pg' % CXXFLAGS
2608 LDFLAGS = '%s -pg' % LDFLAGS
2609 if GMP:
2610 test_gmp(CXX)
2611 ARITH = "gmp"
2612 CPPFLAGS = '%s -D_MP_GMP' % CPPFLAGS
2613 LDFLAGS = '%s -lgmp' % LDFLAGS
2614 SLIBEXTRAFLAGS = '%s -lgmp' % SLIBEXTRAFLAGS
2615 else:
2616 CPPFLAGS = '%s -D_MP_INTERNAL' % CPPFLAGS
2617 if GIT_HASH:
2618 CPPFLAGS = '%s -DZ3GITHASH=%s' % (CPPFLAGS, GIT_HASH)
2619 CXXFLAGS = '%s -std=c++20' % CXXFLAGS
2620 CXXFLAGS = '%s -fvisibility=hidden -fvisibility-inlines-hidden -c' % CXXFLAGS
2621 FPMATH = test_fpmath(CXX)
2622 CXXFLAGS = '%s %s' % (CXXFLAGS, FPMATH_FLAGS)
2623 atomic_required = test_atomic_required(CXX)
2624 if atomic_required:
2625 LDFLAGS = '%s -latomic' % LDFLAGS
2626 if LOG_SYNC:
2627 CXXFLAGS = '%s -DZ3_LOG_SYNC' % CXXFLAGS
2628 if SINGLE_THREADED:
2629 CXXFLAGS = '%s -DSINGLE_THREAD' % CXXFLAGS
2630 if DEBUG_MODE:
2631 CXXFLAGS = '%s -g -Wall' % CXXFLAGS
2632 EXAMP_DEBUG_FLAG = '-g'
2633 CPPFLAGS = '%s -DZ3DEBUG -D_DEBUG' % CPPFLAGS
2634 else:
2635 CXXFLAGS = '%s -O3' % CXXFLAGS
2636 if GPROF:
2637 CXXFLAGS += '-fomit-frame-pointer'
2638 CPPFLAGS = '%s -DNDEBUG -D_EXTERNAL_RELEASE' % CPPFLAGS
2639 if is_CXX_clangpp():
2640 CXXFLAGS = '%s -Wno-unknown-pragmas -Wno-overloaded-virtual -Wno-unused-value' % CXXFLAGS
2641 sysname, _, _, _, machine = os.uname()
2642 if sysname == 'Darwin':
2643 SO_EXT = '.dylib'
2644 SLIBFLAGS = '-dynamiclib'
2645 elif sysname == 'Linux':
2646 SO_EXT = '.so'
2647 SLIBFLAGS = '-shared'
2648 SLIBEXTRAFLAGS = '%s -Wl,-soname,libz3.so' % SLIBEXTRAFLAGS
2649 elif sysname == 'GNU':
2650 SO_EXT = '.so'
2651 SLIBFLAGS = '-shared'
2652 elif sysname == 'FreeBSD':
2653 SO_EXT = '.so'
2654 SLIBFLAGS = '-shared'
2655 SLIBEXTRAFLAGS = '%s -Wl,-soname,libz3.so' % SLIBEXTRAFLAGS
2656 elif sysname == 'NetBSD':
2657 SO_EXT = '.so'
2658 SLIBFLAGS = '-shared'
2659 elif sysname == 'OpenBSD':
2660 SO_EXT = '.so'
2661 SLIBFLAGS = '-shared'
2662 elif sysname == 'SunOS':
2663 SO_EXT = '.so'
2664 SLIBFLAGS = '-shared'
2665 SLIBEXTRAFLAGS = '%s -mimpure-text' % SLIBEXTRAFLAGS
2666 elif sysname.startswith('CYGWIN'):
2667 SO_EXT = '.dll'
2668 SLIBFLAGS = '-shared'
2669 elif sysname.startswith('MSYS_NT') or sysname.startswith('MINGW'):
2670 SO_EXT = '.dll'
2671 SLIBFLAGS = '-shared'
2672 EXE_EXT = '.exe'
2673 LIB_EXT = '.lib'
2674 else:
2675 raise MKException('Unsupported platform: %s' % sysname)
2676 if is64():
2677 if not sysname.startswith('CYGWIN') and not sysname.startswith('MSYS') and not sysname.startswith('MINGW'):
2678 CXXFLAGS = '%s -fPIC' % CXXFLAGS
2679 elif not LINUX_X64:
2680 CXXFLAGS = '%s -m32' % CXXFLAGS
2681 LDFLAGS = '%s -m32' % LDFLAGS
2682 SLIBFLAGS = '%s -m32' % SLIBFLAGS
2683 if TRACE or DEBUG_MODE:
2684 CPPFLAGS = '%s -D_TRACE' % CPPFLAGS
2685 if is_cygwin_mingw() or is_msys2():
2686 # when cross-compiling with MinGW, we need to statically link its standard libraries
2687 # and to make it create an import library.
2688 SLIBEXTRAFLAGS = '%s -static-libgcc -static-libstdc++ -Wl,--out-implib,libz3.dll.a' % SLIBEXTRAFLAGS
2689 LDFLAGS = '%s -static-libgcc -static-libstdc++' % LDFLAGS
2690 if sysname == 'Linux' and machine.startswith('armv7') or machine.startswith('armv8'):
2691 CXXFLAGS = '%s -fpic' % CXXFLAGS
2692 if IS_ARCH_ARM64 and IS_OSX:
2693 print("Setting arm64")
2694 CXXFLAGS = '%s -arch arm64' % CXXFLAGS
2695 LDFLAGS = '%s -arch arm64' % LDFLAGS
2696 SLIBEXTRAFLAGS = '%s -arch arm64' % SLIBEXTRAFLAGS
2697
2698 config.write('PREFIX=%s\n' % PREFIX)
2699 config.write('CC=%s\n' % CC)
2700 config.write('CXX=%s\n' % CXX)
2701 config.write('CXXFLAGS=%s %s\n' % (CPPFLAGS, CXXFLAGS))
2702 config.write('CFLAGS=%s %s\n' % (CPPFLAGS, CXXFLAGS.replace('-std=c++20', '')))
2703 config.write('EXAMP_DEBUG_FLAG=%s\n' % EXAMP_DEBUG_FLAG)
2704 config.write('CXX_OUT_FLAG=-o \n')
2705 config.write('C_OUT_FLAG=-o \n')
2706 config.write('OBJ_EXT=.o\n')
2707 config.write('LIB_EXT=%s\n' % LIB_EXT)
2708 config.write('AR=%s\n' % AR)
2709 config.write('AR_FLAGS=rcs\n')
2710 config.write('AR_OUTFLAG=\n')
2711 config.write('EXE_EXT=%s\n' % EXE_EXT)
2712 config.write('LINK=%s\n' % CXX)
2713 config.write('LINK_FLAGS=\n')
2714 config.write('LINK_OUT_FLAG=-o \n')
2715 if is_linux() and (build_static_lib() or build_static_bin()):
2716 config.write('LINK_EXTRA_FLAGS=-Wl,--whole-archive -lrt -lpthread -Wl,--no-whole-archive %s\n' % LDFLAGS)
2717 else:
2718 config.write('LINK_EXTRA_FLAGS=-lpthread %s\n' % LDFLAGS)
2719 config.write('SO_EXT=%s\n' % SO_EXT)
2720 config.write('SLINK=%s\n' % CXX)
2721 config.write('SLINK_FLAGS=%s\n' % SLIBFLAGS)
2722 config.write('SLINK_EXTRA_FLAGS=-lpthread %s\n' % SLIBEXTRAFLAGS)
2723 config.write('SLINK_OUT_FLAG=-o \n')
2724 config.write('OS_DEFINES=%s\n' % OS_DEFINES)
2725 if is_verbose():
2726 print('Host platform: %s' % sysname)
2727 print('C++ Compiler: %s' % CXX)
2728 print('C Compiler : %s' % CC)
2729 if is_cygwin_mingw():
2730 print('MinGW32 cross: %s' % (is_cygwin_mingw()))
2731 print('Archive Tool: %s' % AR)
2732 print('Arithmetic: %s' % ARITH)
2733 print('Prefix: %s' % PREFIX)
2734 print('64-bit: %s' % is64())
2735 print('FP math: %s' % FPMATH)
2736 print('libatomic: %s' % ('required' if atomic_required else 'not required'))
2737 print("Python pkg dir: %s" % PYTHON_PACKAGE_DIR)
2738 if GPROF:
2739 print('gprof: enabled')
2740 print('Python version: %s' % sysconfig.get_python_version())
2741 if is_java_enabled():
2742 print('JNI Bindings: %s' % JNI_HOME)
2743 print('Java Compiler: %s' % JAVAC)
2744 if is_ml_enabled():
2745 print('OCaml Compiler: %s' % OCAMLC)
2746 print('OCaml Find tool: %s' % OCAMLFIND)
2747 print('OCaml Native: %s' % OCAMLOPT)
2748 print('OCaml Library: %s' % OCAML_LIB)
2749 if is_dotnet_core_enabled():
2750 print('C# Compiler: %s' % DOTNET)
2751
2752 config.close()
2753
2754 def mk_install(out):
2755 out.write('install: ')
2756 for c in get_components():
2757 c.mk_install_deps(out)
2758 out.write(' ')
2759 out.write('\n')
2760 MakeRuleCmd.make_install_directory(out, INSTALL_BIN_DIR)
2761 MakeRuleCmd.make_install_directory(out, INSTALL_INCLUDE_DIR)
2762 MakeRuleCmd.make_install_directory(out, INSTALL_LIB_DIR)
2763 for c in get_components():
2764 c.mk_install(out)
2765 out.write('\t@echo Z3 was successfully installed.\n')
2766 out.write('\n')
2767
2768 def mk_uninstall(out):
2769 out.write('uninstall:\n')
2770 for c in get_components():
2771 c.mk_uninstall(out)
2772 out.write('\t@echo Z3 was successfully uninstalled.\n')
2773 out.write('\n')
2774
2775 # Generate the Z3 makefile
2776 def mk_makefile():
2777 mk_dir(BUILD_DIR)
2778 mk_config()
2779 if VERBOSE:
2780 print("Writing %s" % os.path.join(BUILD_DIR, 'Makefile'))
2781 out = open(os.path.join(BUILD_DIR, 'Makefile'), 'w')
2782 out.write('# Automatically generated file.\n')
2783 out.write('include config.mk\n')
2784 # Generate :all rule
2785 out.write('all:')
2786 for c in get_components():
2787 if c.main_component():
2788 out.write(' %s' % c.name)
2789 out.write('\n\t@echo Z3 was successfully built.\n')
2790 out.write("\t@echo \"Z3Py scripts can already be executed in the \'%s\' directory.\"\n" % os.path.join(BUILD_DIR, 'python'))
2791 pathvar = "DYLD_LIBRARY_PATH" if IS_OSX else "PATH" if IS_WINDOWS else "LD_LIBRARY_PATH"
2792 out.write("\t@echo \"Z3Py scripts stored in arbitrary directories can be executed if the \'%s\' directory is added to the PYTHONPATH environment variable and the \'%s\' directory is added to the %s environment variable.\"\n" % (os.path.join(BUILD_DIR, 'python'), BUILD_DIR, pathvar))
2793 if not IS_WINDOWS:
2794 out.write("\t@echo Use the following command to install Z3 at prefix $(PREFIX).\n")
2795 out.write('\t@echo " sudo make install"\n\n')
2796 # out.write("\t@echo If you are doing a staged install you can use DESTDIR.\n")
2797 # out.write('\t@echo " make DESTDIR=/some/temp/directory install"\n')
2798 # Generate :examples rule
2799 out.write('examples:')
2800 for c in get_components():
2801 if c.is_example():
2802 out.write(' _ex_%s' % c.name)
2803 out.write('\n\t@echo Z3 examples were successfully built.\n')
2804 # Generate components
2805 for c in get_components():
2806 c.mk_makefile(out)
2807 # Generate install/uninstall rules if not WINDOWS
2808 if not IS_WINDOWS:
2809 mk_install(out)
2810 mk_uninstall(out)
2811 for c in get_components():
2812 c.final_info()
2813 out.close()
2814 # Finalize
2815 if VERBOSE:
2816 print("Makefile was successfully generated.")
2817 if DEBUG_MODE:
2818 print(" compilation mode: Debug")
2819 else:
2820 print(" compilation mode: Release")
2821 if IS_WINDOWS:
2822 if VS_X64:
2823 print(" platform: x64\n")
2824 print("To build Z3, open a [Visual Studio x64 Command Prompt], then")
2825 elif VS_ARM:
2826 print(" platform: ARM\n")
2827 print("To build Z3, open a [Visual Studio ARM Command Prompt], then")
2828 else:
2829 print(" platform: x86")
2830 print("To build Z3, open a [Visual Studio Command Prompt], then")
2831 print("type 'cd %s && nmake'\n" % os.path.join(os.getcwd(), BUILD_DIR))
2832 print('Remark: to open a Visual Studio Command Prompt, go to: "Start > All Programs > Visual Studio > Visual Studio Tools"')
2833 else:
2834 print("Type 'cd %s; make' to build Z3" % BUILD_DIR)
2835
2836 # Generate automatically generated source code
2837 def mk_auto_src():
2838 if not ONLY_MAKEFILES:
2839 exec_pyg_scripts()
2840 mk_pat_db()
2841 mk_all_install_tactic_cpps()
2842 mk_all_mem_initializer_cpps()
2843 mk_all_gparams_register_modules()
2844
2845
2846 def _execfile(file, globals=globals(), locals=locals()):
2847 if sys.version < "2.7":
2848 execfile(file, globals, locals)
2849 else:
2850 with open(file, "r") as fh:
2851 exec(fh.read()+"\n", globals, locals)
2852
2853 # Execute python auxiliary scripts that generate extra code for Z3.
2854 def exec_pyg_scripts():
2855 for root, dirs, files in os.walk('src'):
2856 for f in files:
2857 if f.endswith('.pyg'):
2858 script = os.path.join(root, f)
2859 generated_file = mk_genfile_common.mk_hpp_from_pyg(script, root)
2860 if is_verbose():
2861 print("Generated '{}'".format(generated_file))
2862
2863 # TODO: delete after src/ast/pattern/expr_pattern_match
2864 # database.smt ==> database.h
2865 def mk_pat_db():
2866 c = get_component(PATTERN_COMPONENT)
2867 fin = os.path.join(c.src_dir, 'database.smt2')
2868 fout = os.path.join(c.src_dir, 'database.h')
2869 mk_genfile_common.mk_pat_db_internal(fin, fout)
2870 if VERBOSE:
2871 print("Generated '{}'".format(fout))
2872
2873 # Update version numbers
2874 def update_version():
2875 major = VER_MAJOR
2876 minor = VER_MINOR
2877 build = VER_BUILD
2878 revision = VER_TWEAK
2879
2880 print("UpdateVersion:", get_full_version_string(major, minor, build, revision))
2881
2882 if major is None or minor is None or build is None or revision is None:
2883 raise MKException("set_version(major, minor, build, revision) must be used before invoking update_version()")
2884 if not ONLY_MAKEFILES:
2885 mk_version_dot_h(major, minor, build, revision)
2886 mk_all_assembly_infos(major, minor, build, revision)
2887 mk_def_files()
2888
2889 def get_full_version_string(major, minor, build, revision):
2890 global GIT_HASH, GIT_DESCRIBE
2891 res = "Z3 %s.%s.%s.%s" % (major, minor, build, revision)
2892 if GIT_HASH:
2893 res += " " + GIT_HASH
2894 if GIT_DESCRIBE:
2895 branch = check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
2896 res += " " + branch + " " + check_output(['git', 'describe'])
2897 return '"' + res + '"'
2898
2899 # Update files with the version number
2900 def mk_version_dot_h(major, minor, build, revision):
2901 c = get_component(UTIL_COMPONENT)
2902 version_template = os.path.join(c.src_dir, 'z3_version.h.in')
2903 version_header_output = os.path.join(c.src_dir, 'z3_version.h')
2904 # Note the substitution names are what is used by the CMake
2905 # builds system. If you change these you should change them
2906 # in the CMake build too
2907 configure_file(version_template, version_header_output,
2908 { 'Z3_VERSION_MAJOR': str(major),
2909 'Z3_VERSION_MINOR': str(minor),
2910 'Z3_VERSION_PATCH': str(build),
2911 'Z3_VERSION_TWEAK': str(revision),
2912 'Z3_FULL_VERSION': get_full_version_string(major, minor, build, revision)
2913 }
2914 )
2915 if VERBOSE:
2916 print("Generated '%s'" % version_header_output)
2917
2918 # Generate AssemblyInfo.cs files with the right version numbers by using ``AssemblyInfo.cs.in`` files as a template
2919 def mk_all_assembly_infos(major, minor, build, revision):
2920 for c in get_components():
2921 if c.has_assembly_info():
2922 c.make_assembly_info(major, minor, build, revision)
2923
2924 def get_header_files_for_components(component_src_dirs):
2925 assert isinstance(component_src_dirs, list)
2926 h_files_full_path = []
2927 for component_src_dir in sorted(component_src_dirs):
2928 h_files = filter(lambda f: f.endswith('.h') or f.endswith('.hpp'), os.listdir(component_src_dir))
2929 h_files = list(map(lambda p: os.path.join(component_src_dir, p), h_files))
2930 h_files_full_path.extend(h_files)
2931 return h_files_full_path
2932
2933 def mk_install_tactic_cpp(cnames, path):
2934 component_src_dirs = []
2935 for cname in cnames:
2936 print("Component %s" % cname)
2937 c = get_component(cname)
2938 component_src_dirs.append(c.src_dir)
2939 h_files_full_path = get_header_files_for_components(component_src_dirs)
2940 generated_file = mk_genfile_common.mk_install_tactic_cpp_internal(h_files_full_path, path)
2941 if VERBOSE:
2942 print("Generated '{}'".format(generated_file))
2943
2944 def mk_all_install_tactic_cpps():
2945 if not ONLY_MAKEFILES:
2946 for c in get_components():
2947 if c.require_install_tactics():
2948 cnames = []
2949 cnames.extend(c.deps)
2950 cnames.append(c.name)
2951 mk_install_tactic_cpp(cnames, c.src_dir)
2952
2953 def mk_mem_initializer_cpp(cnames, path):
2954 component_src_dirs = []
2955 for cname in cnames:
2956 c = get_component(cname)
2957 component_src_dirs.append(c.src_dir)
2958 h_files_full_path = get_header_files_for_components(component_src_dirs)
2959 generated_file = mk_genfile_common.mk_mem_initializer_cpp_internal(h_files_full_path, path)
2960 if VERBOSE:
2961 print("Generated '{}'".format(generated_file))
2962
2963 def mk_all_mem_initializer_cpps():
2964 if not ONLY_MAKEFILES:
2965 for c in get_components():
2966 if c.require_mem_initializer():
2967 cnames = []
2968 cnames.extend(c.deps)
2969 cnames.append(c.name)
2970 mk_mem_initializer_cpp(cnames, c.src_dir)
2971
2972 def mk_gparams_register_modules(cnames, path):
2973 component_src_dirs = []
2974 for cname in cnames:
2975 c = get_component(cname)
2976 component_src_dirs.append(c.src_dir)
2977 h_files_full_path = get_header_files_for_components(component_src_dirs)
2978 generated_file = mk_genfile_common.mk_gparams_register_modules_internal(h_files_full_path, path)
2979 if VERBOSE:
2980 print("Generated '{}'".format(generated_file))
2981
2982 def mk_all_gparams_register_modules():
2983 if not ONLY_MAKEFILES:
2984 for c in get_components():
2985 if c.require_mem_initializer():
2986 cnames = []
2987 cnames.extend(c.deps)
2988 cnames.append(c.name)
2989 mk_gparams_register_modules(cnames, c.src_dir)
2990
2991 # Generate a .def based on the files at c.export_files slot.
2992 def mk_def_file(c):
2993 defname = '%s.def' % os.path.join(c.src_dir, c.name)
2994 dll_name = c.dll_name
2995 export_header_files = []
2996 for dot_h in c.export_files:
2997 dot_h_c = c.find_file(dot_h, c.name)
2998 api = os.path.join(dot_h_c.src_dir, dot_h)
2999 export_header_files.append(api)
3000 mk_genfile_common.mk_def_file_internal(defname, dll_name, export_header_files)
3001 if VERBOSE:
3002 print("Generated '%s'" % defname)
3003
3004 def mk_def_files():
3005 if not ONLY_MAKEFILES:
3006 for c in get_components():
3007 if c.require_def_file():
3008 mk_def_file(c)
3009
3010 def cp_z3py_to_build():
3011 mk_dir(BUILD_DIR)
3012 mk_dir(os.path.join(BUILD_DIR, 'python'))
3013 z3py_dest = os.path.join(BUILD_DIR, 'python', 'z3')
3014 z3py_src = os.path.join(Z3PY_SRC_DIR, 'z3')
3015
3016 # Erase existing .pyc files
3017 for root, dirs, files in os.walk(Z3PY_SRC_DIR):
3018 for f in files:
3019 if f.endswith('.pyc'):
3020 rmf(os.path.join(root, f))
3021 # We do not want a second copy of the compiled files in the system-wide cache,
3022 # so we disable it temporarily. This is an issue with recent versions of MacOS
3023 # where XCode's Python has a cache, but the build scripts don't have access to
3024 # it (e.g. during OPAM package installation).
3025 have_cache = hasattr(sys, 'pycache_prefix') and sys.pycache_prefix is not None
3026 if have_cache:
3027 pycache_prefix_before = sys.pycache_prefix
3028 sys.pycache_prefix = None
3029 # Compile Z3Py files
3030 if compileall.compile_dir(z3py_src, force=1) != 1:
3031 raise MKException("failed to compile Z3Py sources")
3032 if have_cache:
3033 sys.pycache_prefix = pycache_prefix_before
3034 if is_verbose:
3035 print("Generated python bytecode")
3036 # Copy sources to build
3037 mk_dir(z3py_dest)
3038 for py in filter(lambda f: f.endswith('.py'), os.listdir(z3py_src)):
3039 shutil.copyfile(os.path.join(z3py_src, py), os.path.join(z3py_dest, py))
3040 if is_verbose():
3041 print("Copied '%s'" % py)
3042 # Python 2.x support
3043 for pyc in filter(lambda f: f.endswith('.pyc'), os.listdir(z3py_src)):
3044 shutil.copyfile(os.path.join(z3py_src, pyc), os.path.join(z3py_dest, pyc))
3045 if is_verbose():
3046 print("Copied '%s'" % pyc)
3047 # Python 3.x support
3048 src_pycache = os.path.join(z3py_src, '__pycache__')
3049 target_pycache = os.path.join(z3py_dest, '__pycache__')
3050 if os.path.exists(src_pycache):
3051 for pyc in filter(lambda f: f.endswith('.pyc'), os.listdir(src_pycache)):
3052 mk_dir(target_pycache)
3053 shutil.copyfile(os.path.join(src_pycache, pyc), os.path.join(target_pycache, pyc))
3054 if is_verbose():
3055 print("Copied '%s'" % pyc)
3056 # Copy z3test.py
3057 shutil.copyfile(os.path.join(Z3PY_SRC_DIR, 'z3test.py'), os.path.join(BUILD_DIR, 'python', 'z3test.py'))
3058
3059 def mk_bindings(api_files):
3060 if not ONLY_MAKEFILES:
3061 mk_z3consts_py(api_files)
3062 new_api_files = []
3063 api = get_component(API_COMPONENT)
3064 for api_file in api_files:
3065 api_file_path = api.find_file(api_file, api.name)
3066 new_api_files.append(os.path.join(api_file_path.src_dir, api_file))
3067 g = globals()
3068 g["API_FILES"] = new_api_files
3069 if is_java_enabled():
3070 check_java()
3071 mk_z3consts_java(api_files)
3072 # Generate some of the bindings and "api" module files
3073 import update_api
3074 dotnet_output_dir = None
3075 if is_dotnet_core_enabled():
3076 dotnet_output_dir = os.path.join(BUILD_DIR, 'dotnet')
3077 mk_dir(dotnet_output_dir)
3078 java_input_dir = None
3079 java_output_dir = None
3080 java_package_name = None
3081 if is_java_enabled():
3082 java_output_dir = get_component('java').src_dir
3083 java_input_dir = get_component('java').src_dir
3084 java_package_name = get_component('java').package_name
3085 ml_output_dir = None
3086 if is_ml_enabled():
3087 ml_output_dir = get_component('ml').src_dir
3088 # Get the update_api module to do the work for us
3089 update_api.VERBOSE = is_verbose()
3090 update_api.generate_files(api_files=new_api_files,
3091 api_output_dir=get_component('api').src_dir,
3092 z3py_output_dir=get_z3py_dir(),
3093 dotnet_output_dir=dotnet_output_dir,
3094 java_input_dir=java_input_dir,
3095 java_output_dir=java_output_dir,
3096 java_package_name=java_package_name,
3097 ml_output_dir=ml_output_dir,
3098 ml_src_dir=ml_output_dir
3099 )
3100 cp_z3py_to_build()
3101 if is_ml_enabled():
3102 check_ml()
3103 mk_z3consts_ml(api_files)
3104 if is_dotnet_core_enabled():
3105 check_dotnet_core()
3106 mk_z3consts_dotnet(api_files, dotnet_output_dir)
3107
3108 # Extract enumeration types from API files, and add python definitions.
3109 def mk_z3consts_py(api_files):
3110 if Z3PY_SRC_DIR is None:
3111 raise MKException("You must invoke set_z3py_dir(path):")
3112 full_path_api_files = []
3113 api_dll = get_component(Z3_DLL_COMPONENT)
3114 for api_file in api_files:
3115 api_file_c = api_dll.find_file(api_file, api_dll.name)
3116 api_file = os.path.join(api_file_c.src_dir, api_file)
3117 full_path_api_files.append(api_file)
3118 generated_file = mk_genfile_common.mk_z3consts_py_internal(full_path_api_files, Z3PY_SRC_DIR)
3119 if VERBOSE:
3120 print("Generated '{}".format(generated_file))
3121
3122 # Extract enumeration types from z3_api.h, and add .Net definitions
3123 def mk_z3consts_dotnet(api_files, output_dir):
3124 dotnet = get_component(DOTNET_COMPONENT)
3125 if not dotnet:
3126 dotnet = get_component(DOTNET_CORE_COMPONENT)
3127 full_path_api_files = []
3128 for api_file in api_files:
3129 api_file_c = dotnet.find_file(api_file, dotnet.name)
3130 api_file = os.path.join(api_file_c.src_dir, api_file)
3131 full_path_api_files.append(api_file)
3132 generated_file = mk_genfile_common.mk_z3consts_dotnet_internal(full_path_api_files, output_dir)
3133 if VERBOSE:
3134 print("Generated '{}".format(generated_file))
3135
3136 # Extract enumeration types from z3_api.h, and add Java definitions
3137 def mk_z3consts_java(api_files):
3138 java = get_component(JAVA_COMPONENT)
3139 full_path_api_files = []
3140 for api_file in api_files:
3141 api_file_c = java.find_file(api_file, java.name)
3142 api_file = os.path.join(api_file_c.src_dir, api_file)
3143 full_path_api_files.append(api_file)
3144 generated_files = mk_genfile_common.mk_z3consts_java_internal(
3145 full_path_api_files,
3146 java.package_name,
3147 java.src_dir)
3148 if VERBOSE:
3149 for generated_file in generated_files:
3150 print("Generated '{}'".format(generated_file))
3151
3152 # Extract enumeration types from z3_api.h, and add ML definitions
3153 def mk_z3consts_ml(api_files):
3154 ml = get_component(ML_COMPONENT)
3155 full_path_api_files = []
3156 for api_file in api_files:
3157 api_file_c = ml.find_file(api_file, ml.name)
3158 api_file = os.path.join(api_file_c.src_dir, api_file)
3159 full_path_api_files.append(api_file)
3160 generated_file = mk_genfile_common.mk_z3consts_ml_internal(
3161 full_path_api_files,
3162 ml.src_dir)
3163 if VERBOSE:
3164 print ('Generated "%s"' % generated_file)
3165
3166 def mk_gui_str(id):
3167 return '4D2F40D8-E5F9-473B-B548-%012d' % id
3168
3169 def get_platform_toolset_str():
3170 default = 'v110';
3171 vstr = check_output(['msbuild', '/ver'])
3172 lines = vstr.split('\n')
3173 lline = lines[-1]
3174 tokens = lline.split('.')
3175 if len(tokens) < 2:
3176 return default
3177 else:
3178 if tokens[0] == "15":
3179 # Visual Studio 2017 reports 15.* but the PlatformToolsetVersion is 141
3180 return "v141"
3181 else:
3182 return 'v' + tokens[0] + tokens[1]
3183
3184 def mk_vs_proj_property_groups(f, name, target_ext, type):
3185 f.write(' <ItemGroup Label="ProjectConfigurations">\n')
3186 f.write(' <ProjectConfiguration Include="Debug|Win32">\n')
3187 f.write(' <Configuration>Debug</Configuration>\n')
3188 f.write(' <Platform>Win32</Platform>\n')
3189 f.write(' </ProjectConfiguration>\n')
3190 f.write(' <ProjectConfiguration Include="Release|Win32">\n')
3191 f.write(' <Configuration>Release</Configuration>\n')
3192 f.write(' <Platform>Win32</Platform>\n')
3193 f.write(' </ProjectConfiguration>\n')
3194 f.write(' </ItemGroup>\n')
3195 f.write(' <PropertyGroup Label="Globals">\n')
3196 f.write(' <ProjectGuid>{%s}</ProjectGuid>\n' % mk_gui_str(0))
3197 f.write(' <ProjectName>%s</ProjectName>\n' % name)
3198 f.write(' <Keyword>Win32Proj</Keyword>\n')
3199 f.write(' <PlatformToolset>%s</PlatformToolset>\n' % get_platform_toolset_str())
3200 f.write(' </PropertyGroup>\n')
3201 f.write(' <Import Project="$(VCTargetsPath)\\Microsoft.Cpp.Default.props" />\n')
3202 f.write(' <PropertyGroup Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'" Label="Configuration">\n')
3203 f.write(' <ConfigurationType>%s</ConfigurationType>\n' % type)
3204 f.write(' <CharacterSet>Unicode</CharacterSet>\n')
3205 f.write(' <UseOfMfc>false</UseOfMfc>\n')
3206 f.write(' </PropertyGroup>\n')
3207 f.write(' <PropertyGroup Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'" Label="Configuration">\n')
3208 f.write(' <ConfigurationType>%s</ConfigurationType>\n' % type)
3209 f.write(' <CharacterSet>Unicode</CharacterSet>\n')
3210 f.write(' <UseOfMfc>false</UseOfMfc>\n')
3211 f.write(' </PropertyGroup>\n')
3212 f.write(' <Import Project="$(VCTargetsPath)\\Microsoft.Cpp.props" />\n')
3213 f.write(' <ImportGroup Label="ExtensionSettings" />\n')
3214 f.write(' <ImportGroup Label="PropertySheets">\n')
3215 f.write(' <Import Project="$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props" Condition="exists(\'$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\')" Label="LocalAppDataPlatform" /> </ImportGroup>\n')
3216 f.write(' <PropertyGroup Label="UserMacros" />\n')
3217 f.write(' <PropertyGroup>\n')
3218 f.write(' <OutDir Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'">$(SolutionDir)\\$(ProjectName)\\$(Configuration)\\</OutDir>\n')
3219 f.write(' <TargetName Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'">%s</TargetName>\n' % name)
3220 f.write(' <TargetExt Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'">.%s</TargetExt>\n' % target_ext)
3221 f.write(' <OutDir Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'">$(SolutionDir)\\$(ProjectName)\\$(Configuration)\\</OutDir>\n')
3222 f.write(' <TargetName Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'">%s</TargetName>\n' % name)
3223 f.write(' <TargetExt Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'">.%s</TargetExt>\n' % target_ext)
3224 f.write(' </PropertyGroup>\n')
3225 f.write(' <PropertyGroup Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'">\n')
3226 f.write(' <IntDir>$(ProjectName)\\$(Configuration)\\</IntDir>\n')
3227 f.write(' </PropertyGroup>\n')
3228 f.write(' <PropertyGroup Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'">\n')
3229 f.write(' <IntDir>$(ProjectName)\\$(Configuration)\\</IntDir>\n')
3230 f.write(' </PropertyGroup>\n')
3231
3232
3233 def mk_vs_proj_cl_compile(f, name, components, debug):
3234 f.write(' <ClCompile>\n')
3235 f.write(' <Optimization>Disabled</Optimization>\n')
3236 if debug:
3237 f.write(' <PreprocessorDefinitions>WIN32;_DEBUG;Z3DEBUG;_TRACE;_MP_INTERNAL;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n')
3238 else:
3239 f.write(' <PreprocessorDefinitions>WIN32;NDEBUG;_MP_INTERNAL;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n')
3240 if VS_PAR:
3241 f.write(' <MinimalRebuild>false</MinimalRebuild>\n')
3242 f.write(' <MultiProcessorCompilation>true</MultiProcessorCompilation>\n')
3243 else:
3244 f.write(' <MinimalRebuild>true</MinimalRebuild>\n')
3245 f.write(' <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>\n')
3246 f.write(' <WarningLevel>Level3</WarningLevel>\n')
3247 if debug:
3248 f.write(' <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>\n')
3249 else:
3250 f.write(' <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\n')
3251 f.write(' <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\n')
3252 f.write(' <AdditionalIncludeDirectories>')
3253 deps = find_all_deps(name, components)
3254 first = True
3255 for dep in deps:
3256 if first:
3257 first = False
3258 else:
3259 f.write(';')
3260 f.write(get_component(dep).to_src_dir)
3261 f.write(';%s\n' % os.path.join(REV_BUILD_DIR, SRC_DIR))
3262 f.write('</AdditionalIncludeDirectories>\n')
3263 f.write(' </ClCompile>\n')
3264
3265 def mk_vs_proj_dep_groups(f, name, components):
3266 f.write(' <ItemGroup>\n')
3267 deps = find_all_deps(name, components)
3268 for dep in deps:
3269 dep = get_component(dep)
3270 for cpp in filter(lambda f: f.endswith('.cpp'), os.listdir(dep.src_dir)):
3271 f.write(' <ClCompile Include="%s" />\n' % os.path.join(dep.to_src_dir, cpp))
3272 f.write(' </ItemGroup>\n')
3273
3274 def mk_vs_proj_link_exe(f, name, debug):
3275 f.write(' <Link>\n')
3276 f.write(' <OutputFile>$(OutDir)%s.exe</OutputFile>\n' % name)
3277 f.write(' <GenerateDebugInformation>true</GenerateDebugInformation>\n')
3278 f.write(' <SubSystem>Console</SubSystem>\n')
3279 f.write(' <StackReserveSize>8388608</StackReserveSize>\n')
3280 f.write(' <RandomizedBaseAddress>false</RandomizedBaseAddress>\n')
3281 f.write(' <DataExecutionPrevention/>\n')
3282 f.write(' <TargetMachine>MachineX86</TargetMachine>\n')
3283 f.write(' <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n')
3284 f.write(' <AdditionalDependencies>psapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>\n')
3285 f.write(' </Link>\n')
3286
3287 def mk_vs_proj(name, components):
3288 if not VS_PROJ:
3289 return
3290 proj_name = '%s.vcxproj' % os.path.join(BUILD_DIR, name)
3291 modes=['Debug', 'Release']
3292 PLATFORMS=['Win32']
3293 f = open(proj_name, 'w')
3294 f.write('<?xml version="1.0" encoding="utf-8"?>\n')
3295 f.write('<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\n')
3296 mk_vs_proj_property_groups(f, name, 'exe', 'Application')
3297 f.write(' <ItemDefinitionGroup Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'">\n')
3298 mk_vs_proj_cl_compile(f, name, components, debug=True)
3299 mk_vs_proj_link_exe(f, name, debug=True)
3300 f.write(' </ItemDefinitionGroup>\n')
3301 f.write(' <ItemDefinitionGroup Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'">\n')
3302 mk_vs_proj_cl_compile(f, name, components, debug=False)
3303 mk_vs_proj_link_exe(f, name, debug=False)
3304 f.write(' </ItemDefinitionGroup>\n')
3305 mk_vs_proj_dep_groups(f, name, components)
3306 f.write(' <Import Project="$(VCTargetsPath)\\Microsoft.Cpp.targets" />\n')
3307 f.write(' <ImportGroup Label="ExtensionTargets">\n')
3308 f.write(' </ImportGroup>\n')
3309 f.write('</Project>\n')
3310 f.close()
3311 if is_verbose():
3312 print("Generated '%s'" % proj_name)
3313
3314 def mk_vs_proj_link_dll(f, name, debug):
3315 f.write(' <Link>\n')
3316 f.write(' <OutputFile>$(OutDir)%s.dll</OutputFile>\n' % name)
3317 f.write(' <GenerateDebugInformation>true</GenerateDebugInformation>\n')
3318 f.write(' <SubSystem>Console</SubSystem>\n')
3319 f.write(' <StackReserveSize>8388608</StackReserveSize>\n')
3320 f.write(' <RandomizedBaseAddress>false</RandomizedBaseAddress>\n')
3321 f.write(' <DataExecutionPrevention/>\n')
3322 f.write(' <TargetMachine>MachineX86</TargetMachine>\n')
3323 f.write(' <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n')
3324 f.write(' <AdditionalDependencies>psapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>\n')
3325 f.write(' <ModuleDefinitionFile>%s</ModuleDefinitionFile>' % os.path.join(get_component('api_dll').to_src_dir, 'api_dll.def'))
3326 f.write(' </Link>\n')
3327
3328 def mk_vs_proj_dll(name, components):
3329 if not VS_PROJ:
3330 return
3331 proj_name = '%s.vcxproj' % os.path.join(BUILD_DIR, name)
3332 modes=['Debug', 'Release']
3333 PLATFORMS=['Win32']
3334 f = open(proj_name, 'w')
3335 f.write('<?xml version="1.0" encoding="utf-8"?>\n')
3336 f.write('<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\n')
3337 mk_vs_proj_property_groups(f, name, 'dll', 'DynamicLibrary')
3338 f.write(' <ItemDefinitionGroup Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'">\n')
3339 mk_vs_proj_cl_compile(f, name, components, debug=True)
3340 mk_vs_proj_link_dll(f, name, debug=True)
3341 f.write(' </ItemDefinitionGroup>\n')
3342 f.write(' <ItemDefinitionGroup Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'">\n')
3343 mk_vs_proj_cl_compile(f, name, components, debug=False)
3344 mk_vs_proj_link_dll(f, name, debug=False)
3345 f.write(' </ItemDefinitionGroup>\n')
3346 mk_vs_proj_dep_groups(f, name, components)
3347 f.write(' <Import Project="$(VCTargetsPath)\\Microsoft.Cpp.targets" />\n')
3348 f.write(' <ImportGroup Label="ExtensionTargets">\n')
3349 f.write(' </ImportGroup>\n')
3350 f.write('</Project>\n')
3351 f.close()
3352 if is_verbose():
3353 print("Generated '%s'" % proj_name)
3354
3355 def mk_win_dist(build_path, dist_path):
3356 for c in get_components():
3357 c.mk_win_dist(build_path, dist_path)
3358
3359 def mk_unix_dist(build_path, dist_path):
3360 for c in get_components():
3361 c.mk_unix_dist(build_path, dist_path)
3362 # Add Z3Py to bin directory
3363 for pyc in filter(lambda f: f.endswith('.pyc') or f.endswith('.py'), os.listdir(build_path)):
3364 shutil.copy(os.path.join(build_path, pyc),
3365 os.path.join(dist_path, INSTALL_BIN_DIR, pyc))
3366
3367 class MakeRuleCmd(object):
3368 """
3369 These class methods provide a convenient way to emit frequently
3370 needed commands used in Makefile rules
3371 Note that several of the method are meant for use during ``make
3372 install`` and ``make uninstall``. These methods correctly use
3373 ``$(PREFIX)`` and ``$(DESTDIR)`` and therefore are preferable
3374 to writing commands manually which can be error prone.
3375 """
3376 @classmethod
3377 def install_root(cls):
3378 """
3379 Returns a string that will expand to the
3380 install location when used in a makefile rule.
3381 """
3382 # Note: DESTDIR is to support staged installs
3383 return "$(DESTDIR)$(PREFIX)/"
3384
3385 @classmethod
3386 def _is_str(cls, obj):
3387 if sys.version_info.major > 2:
3388 # Python 3 or newer. Strings are always unicode and of type str
3389 return isinstance(obj, str)
3390 else:
3391 # Python 2. Has byte-string and unicode representation, allow both
3392 return isinstance(obj, str) or isinstance(obj, unicode)
3393
3394 @classmethod
3395 def _install_root(cls, path, in_prefix, out, is_install=True):
3396 if not in_prefix:
3397 # The Python bindings on OSX are sometimes not installed inside the prefix.
3398 install_root = "$(DESTDIR)"
3399 action_string = 'install' if is_install else 'uninstall'
3400 cls.write_cmd(out, 'echo "WARNING: {}ing files/directories ({}) that are not in the install prefix ($(PREFIX))."'.format(
3401 action_string, path))
3402 #print("WARNING: Generating makefile rule that {}s {} '{}' which is outside the installation prefix '{}'.".format(
3403 # action_string, 'to' if is_install else 'from', path, PREFIX))
3404 else:
3405 # assert not os.path.isabs(path)
3406 install_root = cls.install_root()
3407 return install_root
3408
3409 @classmethod
3410 def install_files(cls, out, src_pattern, dest, in_prefix=True):
3411 assert len(dest) > 0
3412 assert cls._is_str(src_pattern)
3413 assert not ' ' in src_pattern
3414 assert cls._is_str(dest)
3415 assert not ' ' in dest
3416 assert not os.path.isabs(src_pattern)
3417 install_root = cls._install_root(dest, in_prefix, out)
3418
3419 cls.write_cmd(out, "cp {src_pattern} {install_root}{dest}".format(
3420 src_pattern=src_pattern,
3421 install_root=install_root,
3422 dest=dest))
3423
3424 @classmethod
3425 def remove_installed_files(cls, out, pattern, in_prefix=True):
3426 assert len(pattern) > 0
3427 assert cls._is_str(pattern)
3428 assert not ' ' in pattern
3429 install_root = cls._install_root(pattern, in_prefix, out, is_install=False)
3430
3431 cls.write_cmd(out, "rm -f {install_root}{pattern}".format(
3432 install_root=install_root,
3433 pattern=pattern))
3434
3435 @classmethod
3436 def make_install_directory(cls, out, dir, in_prefix=True):
3437 assert len(dir) > 0
3438 assert cls._is_str(dir)
3439 assert not ' ' in dir
3440 install_root = cls._install_root(dir, in_prefix, out)
3441
3442 if is_windows():
3443 cls.write_cmd(out, "IF NOT EXIST {dir} (mkdir {dir})".format(
3444 install_root=install_root,
3445 dir=dir))
3446 else:
3447 cls.write_cmd(out, "mkdir -p {install_root}{dir}".format(
3448 install_root=install_root,
3449 dir=dir))
3450
3451 @classmethod
3452 def _is_path_prefix_of(cls, temp_path, target_as_abs):
3453 """
3454 Returns True iff ``temp_path`` is a path prefix
3455 of ``target_as_abs``
3456 """
3457 assert cls._is_str(temp_path)
3458 assert cls._is_str(target_as_abs)
3459 assert len(temp_path) > 0
3460 assert len(target_as_abs) > 0
3461 assert os.path.isabs(temp_path)
3462 assert os.path.isabs(target_as_abs)
3463
3464 # Need to stick extra slash in front otherwise we might think that
3465 # ``/lib`` is a prefix of ``/lib64``. Of course if ``temp_path ==
3466 # '/'`` then we shouldn't else we would check if ``//`` (rather than
3467 # ``/``) is a prefix of ``/lib64``, which would fail.
3468 if len(temp_path) > 1:
3469 temp_path += os.sep
3470 return target_as_abs.startswith(temp_path)
3471
3472 @classmethod
3473 def create_relative_symbolic_link(cls, out, target, link_name):
3474 assert cls._is_str(target)
3475 assert cls._is_str(link_name)
3476 assert len(target) > 0
3477 assert len(link_name) > 0
3478 assert not os.path.isabs(target)
3479 assert not os.path.isabs(link_name)
3480
3481 # We can't test to see if link_name is a file or directory
3482 # because it may not exist yet. Instead follow the convention
3483 # that if there is a leading slash target is a directory otherwise
3484 # it's a file
3485 if link_name[-1] != '/':
3486 # link_name is a file
3487 temp_path = os.path.dirname(link_name)
3488 else:
3489 # link_name is a directory
3490 temp_path = link_name[:-1]
3491 temp_path = '/' + temp_path
3492 relative_path = ""
3493 targetAsAbs = '/' + target
3494 assert os.path.isabs(targetAsAbs)
3495 assert os.path.isabs(temp_path)
3496 # Keep walking up the directory tree until temp_path
3497 # is a prefix of targetAsAbs
3498 while not cls._is_path_prefix_of(temp_path, targetAsAbs):
3499 assert temp_path != '/'
3500 temp_path = os.path.dirname(temp_path)
3501 relative_path += '../'
3502
3503 # Now get the path from the common prefix directory to the target
3504 target_from_prefix = targetAsAbs[len(temp_path):]
3505 relative_path += target_from_prefix
3506 # Remove any double slashes
3507 relative_path = relative_path.replace('//','/')
3508 cls.create_symbolic_link(out, relative_path, link_name)
3509
3510 @classmethod
3511 def create_symbolic_link(cls, out, target, link_name):
3512 assert cls._is_str(target)
3513 assert cls._is_str(link_name)
3514 assert not os.path.isabs(target)
3515
3516 cls.write_cmd(out, 'ln -s {target} {install_root}{link_name}'.format(
3517 target=target,
3518 install_root=cls.install_root(),
3519 link_name=link_name))
3520
3521 # TODO: Refactor all of the build system to emit commands using this
3522 # helper to simplify code. This will also let us replace ``@`` with
3523 # ``$(Verb)`` and have it set to ``@`` or empty at build time depending on
3524 # a variable (e.g. ``VERBOSE``) passed to the ``make`` invocation. This
3525 # would be very helpful for debugging.
3526 @classmethod
3527 def write_cmd(cls, out, line):
3528 out.write("\t@{}\n".format(line))
3529
3530 def strip_path_prefix(path, prefix):
3531 if path.startswith(prefix):
3532 stripped_path = path[len(prefix):]
3533 stripped_path.replace('//','/')
3534 if stripped_path[0] == '/':
3535 stripped_path = stripped_path[1:]
3536 assert not os.path.isabs(stripped_path)
3537 return stripped_path
3538 else:
3539 return path
3540
3541 def configure_file(template_file_path, output_file_path, substitutions):
3542 """
3543 Read a template file ``template_file_path``, perform substitutions
3544 found in the ``substitutions`` dictionary and write the result to
3545 the output file ``output_file_path``.
3546 The template file should contain zero or more template strings of the
3547 form ``@NAME@``.
3548 The substitutions dictionary maps old strings (without the ``@``
3549 symbols) to their replacements.
3550 """
3551 assert isinstance(template_file_path, str)
3552 assert isinstance(output_file_path, str)
3553 assert isinstance(substitutions, dict)
3554 assert len(template_file_path) > 0
3555 assert len(output_file_path) > 0
3556 print("Generating {} from {}".format(output_file_path, template_file_path))
3557
3558 if not os.path.exists(template_file_path):
3559 raise MKException('Could not find template file "{}"'.format(template_file_path))
3560
3561 # Read whole template file into string
3562 template_string = None
3563 with open(template_file_path, 'r') as f:
3564 template_string = f.read()
3565
3566 # Do replacements
3567 for (old_string, replacement) in substitutions.items():
3568 template_string = template_string.replace('@{}@'.format(old_string), replacement)
3569
3570 # Write the string to the file
3571 with open(output_file_path, 'w') as f:
3572 f.write(template_string)
3573
3574 if __name__ == '__main__':
3575 import doctest
3576 doctest.testmod()