]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/configure.py
Add --enable-overflow-checks-std option to configure script.
[rust.git] / src / bootstrap / configure.py
1 #!/usr/bin/env python
2
3 # ignore-tidy-linelength
4
5 from __future__ import absolute_import, division, print_function
6 import sys
7 import os
8 rust_dir = os.path.dirname(os.path.abspath(__file__))
9 rust_dir = os.path.dirname(rust_dir)
10 rust_dir = os.path.dirname(rust_dir)
11 sys.path.append(os.path.join(rust_dir, "src", "bootstrap"))
12 import bootstrap
13
14
15 class Option(object):
16     def __init__(self, name, rustbuild, desc, value):
17         self.name = name
18         self.rustbuild = rustbuild
19         self.desc = desc
20         self.value = value
21
22
23 options = []
24
25
26 def o(*args):
27     options.append(Option(*args, value=False))
28
29
30 def v(*args):
31     options.append(Option(*args, value=True))
32
33
34 o("debug", "rust.debug", "enables debugging environment; does not affect optimization of bootstrapped code (use `--disable-optimize` for that)")
35 o("docs", "build.docs", "build standard library documentation")
36 o("compiler-docs", "build.compiler-docs", "build compiler documentation")
37 o("optimize-tests", "rust.optimize-tests", "build tests with optimizations")
38 o("parallel-compiler", "rust.parallel-compiler", "build a multi-threaded rustc")
39 o("verbose-tests", "rust.verbose-tests", "enable verbose output when running tests")
40 o("ccache", "llvm.ccache", "invoke gcc/clang via ccache to reuse object files between builds")
41 o("sccache", None, "invoke gcc/clang via sccache to reuse object files between builds")
42 o("local-rust", None, "use an installed rustc rather than downloading a snapshot")
43 v("local-rust-root", None, "set prefix for local rust binary")
44 o("local-rebuild", "build.local-rebuild", "assume local-rust matches the current version, for rebuilds; implies local-rust, and is implied if local-rust already matches the current version")
45 o("llvm-static-stdcpp", "llvm.static-libstdcpp", "statically link to libstdc++ for LLVM")
46 o("llvm-link-shared", "llvm.link-shared", "prefer shared linking to LLVM (llvm-config --link-shared)")
47 o("rpath", "rust.rpath", "build rpaths into rustc itself")
48 o("llvm-version-check", "llvm.version-check", "check if the LLVM version is supported, build anyway")
49 o("codegen-tests", "rust.codegen-tests", "run the src/test/codegen tests")
50 o("option-checking", None, "complain about unrecognized options in this configure script")
51 o("ninja", "llvm.ninja", "build LLVM using the Ninja generator (for MSVC, requires building in the correct environment)")
52 o("locked-deps", "build.locked-deps", "force Cargo.lock to be up to date")
53 o("vendor", "build.vendor", "enable usage of vendored Rust crates")
54 o("sanitizers", "build.sanitizers", "build the sanitizer runtimes (asan, lsan, msan, tsan, hwasan)")
55 o("dist-src", "rust.dist-src", "when building tarballs enables building a source tarball")
56 o("cargo-native-static", "build.cargo-native-static", "static native libraries in cargo")
57 o("profiler", "build.profiler", "build the profiler runtime")
58 o("full-tools", None, "enable all tools")
59 o("lld", "rust.lld", "build lld")
60 o("clang", "llvm.clang", "build clang")
61 o("missing-tools", "dist.missing-tools", "allow failures when building tools")
62 o("use-libcxx", "llvm.use-libcxx", "build LLVM with libc++")
63 o("control-flow-guard", "rust.control-flow-guard", "Enable Control Flow Guard")
64
65 v("llvm-cflags", "llvm.cflags", "build LLVM with these extra compiler flags")
66 v("llvm-cxxflags", "llvm.cxxflags", "build LLVM with these extra compiler flags")
67 v("llvm-ldflags", "llvm.ldflags", "build LLVM with these extra linker flags")
68
69 v("llvm-libunwind", "rust.llvm-libunwind", "use LLVM libunwind")
70
71 # Optimization and debugging options. These may be overridden by the release
72 # channel, etc.
73 o("optimize", "rust.optimize", "build optimized rust code")
74 o("optimize-llvm", "llvm.optimize", "build optimized LLVM")
75 o("llvm-assertions", "llvm.assertions", "build LLVM with assertions")
76 o("llvm-plugins", "llvm.plugins", "build LLVM with plugin interface")
77 o("debug-assertions", "rust.debug-assertions", "build with debugging assertions")
78 o("overflow-checks", "rust.overflow-checks", "build with overflow checks")
79 o("overflow-checks-std", "rust.overflow-checks-std", "build the standard library with overflow checks")
80 o("llvm-release-debuginfo", "llvm.release-debuginfo", "build LLVM with debugger metadata")
81 v("debuginfo-level", "rust.debuginfo-level", "debuginfo level for Rust code")
82 v("debuginfo-level-rustc", "rust.debuginfo-level-rustc", "debuginfo level for the compiler")
83 v("debuginfo-level-std", "rust.debuginfo-level-std", "debuginfo level for the standard library")
84 v("debuginfo-level-tools", "rust.debuginfo-level-tools", "debuginfo level for the tools")
85 v("debuginfo-level-tests", "rust.debuginfo-level-tests", "debuginfo level for the test suites run with compiletest")
86 v("save-toolstates", "rust.save-toolstates", "save build and test status of external tools into this file")
87
88 v("prefix", "install.prefix", "set installation prefix")
89 v("localstatedir", "install.localstatedir", "local state directory")
90 v("datadir", "install.datadir", "install data")
91 v("sysconfdir", "install.sysconfdir", "install system configuration files")
92 v("infodir", "install.infodir", "install additional info")
93 v("libdir", "install.libdir", "install libraries")
94 v("mandir", "install.mandir", "install man pages in PATH")
95 v("docdir", "install.docdir", "install documentation in PATH")
96 v("bindir", "install.bindir", "install binaries")
97
98 v("llvm-root", None, "set LLVM root")
99 v("llvm-config", None, "set path to llvm-config")
100 v("llvm-filecheck", None, "set path to LLVM's FileCheck utility")
101 v("python", "build.python", "set path to python")
102 v("android-cross-path", "target.arm-linux-androideabi.android-ndk",
103   "Android NDK standalone path (deprecated)")
104 v("i686-linux-android-ndk", "target.i686-linux-android.android-ndk",
105   "i686-linux-android NDK standalone path")
106 v("arm-linux-androideabi-ndk", "target.arm-linux-androideabi.android-ndk",
107   "arm-linux-androideabi NDK standalone path")
108 v("armv7-linux-androideabi-ndk", "target.armv7-linux-androideabi.android-ndk",
109   "armv7-linux-androideabi NDK standalone path")
110 v("thumbv7neon-linux-androideabi-ndk", "target.thumbv7neon-linux-androideabi.android-ndk",
111   "thumbv7neon-linux-androideabi NDK standalone path")
112 v("aarch64-linux-android-ndk", "target.aarch64-linux-android.android-ndk",
113   "aarch64-linux-android NDK standalone path")
114 v("x86_64-linux-android-ndk", "target.x86_64-linux-android.android-ndk",
115   "x86_64-linux-android NDK standalone path")
116 v("musl-root", "target.x86_64-unknown-linux-musl.musl-root",
117   "MUSL root installation directory (deprecated)")
118 v("musl-root-x86_64", "target.x86_64-unknown-linux-musl.musl-root",
119   "x86_64-unknown-linux-musl install directory")
120 v("musl-root-i586", "target.i586-unknown-linux-musl.musl-root",
121   "i586-unknown-linux-musl install directory")
122 v("musl-root-i686", "target.i686-unknown-linux-musl.musl-root",
123   "i686-unknown-linux-musl install directory")
124 v("musl-root-arm", "target.arm-unknown-linux-musleabi.musl-root",
125   "arm-unknown-linux-musleabi install directory")
126 v("musl-root-armhf", "target.arm-unknown-linux-musleabihf.musl-root",
127   "arm-unknown-linux-musleabihf install directory")
128 v("musl-root-armv5te", "target.armv5te-unknown-linux-musleabi.musl-root",
129   "armv5te-unknown-linux-musleabi install directory")
130 v("musl-root-armv7", "target.armv7-unknown-linux-musleabi.musl-root",
131   "armv7-unknown-linux-musleabi install directory")
132 v("musl-root-armv7hf", "target.armv7-unknown-linux-musleabihf.musl-root",
133   "armv7-unknown-linux-musleabihf install directory")
134 v("musl-root-aarch64", "target.aarch64-unknown-linux-musl.musl-root",
135   "aarch64-unknown-linux-musl install directory")
136 v("musl-root-mips", "target.mips-unknown-linux-musl.musl-root",
137   "mips-unknown-linux-musl install directory")
138 v("musl-root-mipsel", "target.mipsel-unknown-linux-musl.musl-root",
139   "mipsel-unknown-linux-musl install directory")
140 v("musl-root-mips64", "target.mips64-unknown-linux-muslabi64.musl-root",
141   "mips64-unknown-linux-muslabi64 install directory")
142 v("musl-root-mips64el", "target.mips64el-unknown-linux-muslabi64.musl-root",
143   "mips64el-unknown-linux-muslabi64 install directory")
144 v("qemu-armhf-rootfs", "target.arm-unknown-linux-gnueabihf.qemu-rootfs",
145   "rootfs in qemu testing, you probably don't want to use this")
146 v("qemu-aarch64-rootfs", "target.aarch64-unknown-linux-gnu.qemu-rootfs",
147   "rootfs in qemu testing, you probably don't want to use this")
148 v("qemu-riscv64-rootfs", "target.riscv64gc-unknown-linux-gnu.qemu-rootfs",
149   "rootfs in qemu testing, you probably don't want to use this")
150 v("experimental-targets", "llvm.experimental-targets",
151   "experimental LLVM targets to build")
152 v("release-channel", "rust.channel", "the name of the release channel to build")
153 v("release-description", "rust.description", "optional descriptive string for version output")
154 v("dist-compression-formats", None,
155   "comma-separated list of compression formats to use")
156
157 # Used on systems where "cc" is unavailable
158 v("default-linker", "rust.default-linker", "the default linker")
159
160 # Many of these are saved below during the "writing configuration" step
161 # (others are conditionally saved).
162 o("manage-submodules", "build.submodules", "let the build manage the git submodules")
163 o("full-bootstrap", "build.full-bootstrap", "build three compilers instead of two")
164 o("extended", "build.extended", "build an extended rust tool set")
165
166 v("tools", None, "List of extended tools will be installed")
167 v("codegen-backends", None, "List of codegen backends to build")
168 v("build", "build.build", "GNUs ./configure syntax LLVM build triple")
169 v("host", None, "GNUs ./configure syntax LLVM host triples")
170 v("target", None, "GNUs ./configure syntax LLVM target triples")
171
172 v("set", None, "set arbitrary key/value pairs in TOML configuration")
173
174
175 def p(msg):
176     print("configure: " + msg)
177
178
179 def err(msg):
180     print("configure: error: " + msg)
181     sys.exit(1)
182
183
184 if '--help' in sys.argv or '-h' in sys.argv:
185     print('Usage: ./configure [options]')
186     print('')
187     print('Options')
188     for option in options:
189         if 'android' in option.name:
190             # no one needs to know about these obscure options
191             continue
192         if option.value:
193             print('\t{:30} {}'.format('--{}=VAL'.format(option.name), option.desc))
194         else:
195             print('\t{:30} {}'.format('--enable-{}'.format(option.name), option.desc))
196     print('')
197     print('This configure script is a thin configuration shim over the true')
198     print('configuration system, `config.toml`. You can explore the comments')
199     print('in `config.toml.example` next to this configure script to see')
200     print('more information about what each option is. Additionally you can')
201     print('pass `--set` as an argument to set arbitrary key/value pairs')
202     print('in the TOML configuration if desired')
203     print('')
204     print('Also note that all options which take `--enable` can similarly')
205     print('be passed with `--disable-foo` to forcibly disable the option')
206     sys.exit(0)
207
208 # Parse all command line arguments into one of these three lists, handling
209 # boolean and value-based options separately
210 unknown_args = []
211 need_value_args = []
212 known_args = {}
213
214 p("processing command line")
215 i = 1
216 while i < len(sys.argv):
217     arg = sys.argv[i]
218     i += 1
219     if not arg.startswith('--'):
220         unknown_args.append(arg)
221         continue
222
223     found = False
224     for option in options:
225         value = None
226         if option.value:
227             keyval = arg[2:].split('=', 1)
228             key = keyval[0]
229             if option.name != key:
230                 continue
231
232             if len(keyval) > 1:
233                 value = keyval[1]
234             elif i < len(sys.argv):
235                 value = sys.argv[i]
236                 i += 1
237             else:
238                 need_value_args.append(arg)
239                 continue
240         else:
241             if arg[2:] == 'enable-' + option.name:
242                 value = True
243             elif arg[2:] == 'disable-' + option.name:
244                 value = False
245             else:
246                 continue
247
248         found = True
249         if option.name not in known_args:
250             known_args[option.name] = []
251         known_args[option.name].append((option, value))
252         break
253
254     if not found:
255         unknown_args.append(arg)
256 p("")
257
258 # Note: here and a few other places, we use [-1] to apply the *last* value
259 # passed.  But if option-checking is enabled, then the known_args loop will
260 # also assert that options are only passed once.
261 option_checking = ('option-checking' not in known_args
262                    or known_args['option-checking'][-1][1])
263 if option_checking:
264     if len(unknown_args) > 0:
265         err("Option '" + unknown_args[0] + "' is not recognized")
266     if len(need_value_args) > 0:
267         err("Option '{0}' needs a value ({0}=val)".format(need_value_args[0]))
268
269 # Parse all known arguments into a configuration structure that reflects the
270 # TOML we're going to write out
271 config = {}
272
273
274 def build():
275     if 'build' in known_args:
276         return known_args['build'][-1][1]
277     return bootstrap.default_build_triple(verbose=False)
278
279
280 def set(key, value):
281     s = "{:20} := {}".format(key, value)
282     if len(s) < 70:
283         p(s)
284     else:
285         p(s[:70] + " ...")
286
287     arr = config
288     parts = key.split('.')
289     for i, part in enumerate(parts):
290         if i == len(parts) - 1:
291             arr[part] = value
292         else:
293             if part not in arr:
294                 arr[part] = {}
295             arr = arr[part]
296
297
298 for key in known_args:
299     # The `set` option is special and can be passed a bunch of times
300     if key == 'set':
301         for option, value in known_args[key]:
302             keyval = value.split('=', 1)
303             if len(keyval) == 1 or keyval[1] == "true":
304                 value = True
305             elif keyval[1] == "false":
306                 value = False
307             else:
308                 value = keyval[1]
309             set(keyval[0], value)
310         continue
311
312     # Ensure each option is only passed once
313     arr = known_args[key]
314     if option_checking and len(arr) > 1:
315         err("Option '{}' provided more than once".format(key))
316     option, value = arr[-1]
317
318     # If we have a clear avenue to set our value in rustbuild, do so
319     if option.rustbuild is not None:
320         set(option.rustbuild, value)
321         continue
322
323     # Otherwise we're a "special" option and need some extra handling, so do
324     # that here.
325     if option.name == 'sccache':
326         set('llvm.ccache', 'sccache')
327     elif option.name == 'local-rust':
328         for path in os.environ['PATH'].split(os.pathsep):
329             if os.path.exists(path + '/rustc'):
330                 set('build.rustc', path + '/rustc')
331                 break
332         for path in os.environ['PATH'].split(os.pathsep):
333             if os.path.exists(path + '/cargo'):
334                 set('build.cargo', path + '/cargo')
335                 break
336     elif option.name == 'local-rust-root':
337         set('build.rustc', value + '/bin/rustc')
338         set('build.cargo', value + '/bin/cargo')
339     elif option.name == 'llvm-root':
340         set('target.{}.llvm-config'.format(build()), value + '/bin/llvm-config')
341     elif option.name == 'llvm-config':
342         set('target.{}.llvm-config'.format(build()), value)
343     elif option.name == 'llvm-filecheck':
344         set('target.{}.llvm-filecheck'.format(build()), value)
345     elif option.name == 'tools':
346         set('build.tools', value.split(','))
347     elif option.name == 'codegen-backends':
348         set('rust.codegen-backends', value.split(','))
349     elif option.name == 'host':
350         set('build.host', value.split(','))
351     elif option.name == 'target':
352         set('build.target', value.split(','))
353     elif option.name == 'full-tools':
354         set('rust.codegen-backends', ['llvm'])
355         set('rust.lld', True)
356         set('rust.llvm-tools', True)
357         set('build.extended', True)
358     elif option.name == 'option-checking':
359         # this was handled above
360         pass
361     elif option.name == 'dist-compression-formats':
362         set('dist.compression-formats', value.split(','))
363     else:
364         raise RuntimeError("unhandled option {}".format(option.name))
365
366 set('build.configure-args', sys.argv[1:])
367
368 # "Parse" the `config.toml.example` file into the various sections, and we'll
369 # use this as a template of a `config.toml` to write out which preserves
370 # all the various comments and whatnot.
371 #
372 # Note that the `target` section is handled separately as we'll duplicate it
373 # per configured target, so there's a bit of special handling for that here.
374 sections = {}
375 cur_section = None
376 sections[None] = []
377 section_order = [None]
378 targets = {}
379
380 for line in open(rust_dir + '/config.toml.example').read().split("\n"):
381     if line.startswith('['):
382         cur_section = line[1:-1]
383         if cur_section.startswith('target'):
384             cur_section = 'target'
385         elif '.' in cur_section:
386             raise RuntimeError("don't know how to deal with section: {}".format(cur_section))
387         sections[cur_section] = [line]
388         section_order.append(cur_section)
389     else:
390         sections[cur_section].append(line)
391
392 # Fill out the `targets` array by giving all configured targets a copy of the
393 # `target` section we just loaded from the example config
394 configured_targets = [build()]
395 if 'build' in config:
396     if 'host' in config['build']:
397         configured_targets += config['build']['host']
398     if 'target' in config['build']:
399         configured_targets += config['build']['target']
400 if 'target' in config:
401     for target in config['target']:
402         configured_targets.append(target)
403 for target in configured_targets:
404     targets[target] = sections['target'][:]
405     targets[target][0] = targets[target][0].replace("x86_64-unknown-linux-gnu", target)
406
407
408 def is_number(value):
409     try:
410         float(value)
411         return True
412     except ValueError:
413         return False
414
415
416 # Here we walk through the constructed configuration we have from the parsed
417 # command line arguments. We then apply each piece of configuration by
418 # basically just doing a `sed` to change the various configuration line to what
419 # we've got configure.
420 def to_toml(value):
421     if isinstance(value, bool):
422         if value:
423             return "true"
424         else:
425             return "false"
426     elif isinstance(value, list):
427         return '[' + ', '.join(map(to_toml, value)) + ']'
428     elif isinstance(value, str):
429         # Don't put quotes around numeric values
430         if is_number(value):
431             return value
432         else:
433             return "'" + value + "'"
434     else:
435         raise RuntimeError('no toml')
436
437
438 def configure_section(lines, config):
439     for key in config:
440         value = config[key]
441         found = False
442         for i, line in enumerate(lines):
443             if not line.startswith('#' + key + ' = '):
444                 continue
445             found = True
446             lines[i] = "{} = {}".format(key, to_toml(value))
447             break
448         if not found:
449             # These are used by rpm, but aren't accepted by x.py.
450             # Give a warning that they're ignored, but not a hard error.
451             if key in ["infodir", "localstatedir"]:
452                 print("warning: {} will be ignored".format(key))
453             else:
454                 raise RuntimeError("failed to find config line for {}".format(key))
455
456
457 for section_key in config:
458     section_config = config[section_key]
459     if section_key not in sections:
460         raise RuntimeError("config key {} not in sections".format(section_key))
461
462     if section_key == 'target':
463         for target in section_config:
464             configure_section(targets[target], section_config[target])
465     else:
466         configure_section(sections[section_key], section_config)
467
468 # Now that we've built up our `config.toml`, write it all out in the same
469 # order that we read it in.
470 p("")
471 p("writing `config.toml` in current directory")
472 with bootstrap.output('config.toml') as f:
473     for section in section_order:
474         if section == 'target':
475             for target in targets:
476                 for line in targets[target]:
477                     f.write(line + "\n")
478         else:
479             for line in sections[section]:
480                 f.write(line + "\n")
481
482 with bootstrap.output('Makefile') as f:
483     contents = os.path.join(rust_dir, 'src', 'bootstrap', 'mk', 'Makefile.in')
484     contents = open(contents).read()
485     contents = contents.replace("$(CFG_SRC_DIR)", rust_dir + '/')
486     contents = contents.replace("$(CFG_PYTHON)", sys.executable)
487     f.write(contents)
488
489 p("")
490 p("run `python {}/x.py --help`".format(rust_dir))
491 p("")