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