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