summaryrefslogtreecommitdiffstats
path: root/taskcluster/scripts/misc/repack_rust.py
blob: d2c3e431065ddb31bfb2011cfd646fb15132588e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
#!/usr/bin/env python3
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

"""
This script downloads and repacks official rust language builds
with the necessary tool and target support for the Firefox
build environment.
"""

import argparse
import errno
import glob
import hashlib
import os
import shutil
import subprocess
import tarfile
import textwrap
from contextlib import contextmanager

import requests
import toml
import zstandard


def log(msg):
    print("repack: %s" % msg, flush=True)


def fetch_file(url):
    """Download a file from the given url if it's not already present.

    Returns the SHA-2 256-bit hash of the received file."""
    filename = os.path.basename(url)
    sha = hashlib.sha256()
    size = 4096
    if os.path.exists(filename):
        with open(filename, "rb") as fd:
            while True:
                block = fd.read(size)
                if not block:
                    return sha.hexdigest()
                sha.update(block)
        log("Could not calculate checksum!")
        return None
    r = requests.get(url, stream=True)
    r.raise_for_status()
    with open(filename, "wb") as fd:
        for chunk in r.iter_content(size):
            fd.write(chunk)
            sha.update(chunk)
        return sha.hexdigest()


def check_call_with_input(cmd, input_data):
    """Invoke a command, passing the input String over stdin.

    This is like subprocess.check_call, but allows piping
    input to interactive commands."""
    p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
    p.communicate(input_data)
    if p.wait():
        raise subprocess.CalledProcessError(p.returncode, cmd)


def setup_gpg():
    """Add the signing key to the current gpg config.

    Import a hard-coded copy of the release signing public key
    and mark it trusted in the gpg database so subsequent
    signature checks can succeed or fail cleanly."""
    keyid = "0x85AB96E6FA1BE5FE"
    log("Importing signing key %s..." % keyid)
    key = b"""
-----BEGIN PGP PUBLIC KEY BLOCK-----

mQINBFJEwMkBEADlPACa2K7reD4x5zd8afKx75QYKmxqZwywRbgeICeD4bKiQoJZ
dUjmn1LgrGaXuBMKXJQhyA34e/1YZel/8et+HPE5XpljBfNYXWbVocE1UMUTnFU9
CKXa4AhJ33f7we2/QmNRMUifw5adPwGMg4D8cDKXk02NdnqQlmFByv0vSaArR5kn
gZKnLY6o0zZ9Buyy761Im/ShXqv4ATUgYiFc48z33G4j+BDmn0ryGr1aFdP58tHp
gjWtLZs0iWeFNRDYDje6ODyu/MjOyuAWb2pYDH47Xu7XedMZzenH2TLM9yt/hyOV
xReDPhvoGkaO8xqHioJMoPQi1gBjuBeewmFyTSPS4deASukhCFOcTsw/enzJagiS
ZAq6Imehduke+peAL1z4PuRmzDPO2LPhVS7CDXtuKAYqUV2YakTq8MZUempVhw5n
LqVaJ5/XiyOcv405PnkT25eIVVVghxAgyz6bOU/UMjGQYlkUxI7YZ9tdreLlFyPR
OUL30E8q/aCd4PGJV24yJ1uit+yS8xjyUiMKm4J7oMP2XdBN98TUfLGw7SKeAxyU
92BHlxg7yyPfI4TglsCzoSgEIV6xoGOVRRCYlGzSjUfz0bCMCclhTQRBkegKcjB3
sMTyG3SPZbjTlCqrFHy13e6hGl37Nhs8/MvXUysq2cluEISn5bivTKEeeQARAQAB
tERSdXN0IExhbmd1YWdlIChUYWcgYW5kIFJlbGVhc2UgU2lnbmluZyBLZXkpIDxy
dXN0LWtleUBydXN0LWxhbmcub3JnPokCOAQTAQIAIgUCUkTAyQIbAwYLCQgHAwIG
FQgCCQoLBBYCAwECHgECF4AACgkQhauW5vob5f5fYQ//b1DWK1NSGx5nZ3zYZeHJ
9mwGCftIaA2I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=5FXw
-----END PGP PUBLIC KEY BLOCK-----
"""
    check_call_with_input(["gpg", "--import"], key)
    check_call_with_input(
        ["gpg", "--command-fd", "0", "--edit-key", keyid], b"trust\n5\ny\n"
    )


def verify_sha(filename, sha):
    """Verify that the checksum file matches the given sha digest."""
    sha_filename = filename + ".sha256"
    with open(sha_filename) as f:
        # Older sha256 files would contain `sha filename`, but more recent
        # ones only contain `sha`.
        checksum = f.readline().split()[0]
        if checksum != sha:
            raise ValueError("Checksum mismatch in %s" % filename)
        return True
    log("No checksum file for %s!" % filename)
    return False


def fetch(url, validate=True):
    """Download and verify a package url."""
    base = os.path.basename(url)
    log("Fetching %s..." % base)
    if validate:
        fetch_file(url + ".asc")
        fetch_file(url + ".sha256")
    sha = fetch_file(url)
    if validate:
        log("Verifying %s..." % base)
        verify_sha(base, sha)
        subprocess.check_call(
            ["gpg", "--keyid-format", "0xlong", "--verify", base + ".asc", base]
        )
    return sha


def install(filename, target):
    """Run a package's installer script against the given target directory."""
    log("Unpacking %s..." % filename)
    subprocess.check_call(["tar", "xf", filename])
    basename = filename.split(".tar")[0]
    log("Installing %s..." % basename)
    install_cmd = [os.path.join(basename, "install.sh")]
    install_cmd += ["--prefix=" + os.path.abspath(target)]
    install_cmd += ["--disable-ldconfig"]
    subprocess.check_call(install_cmd)
    log("Cleaning %s..." % basename)
    shutil.rmtree(basename)


def package(manifest, pkg, target):
    """Pull out the package dict for a particular package and target
    from the given manifest."""
    version = manifest["pkg"][pkg]["version"]
    if target in manifest["pkg"][pkg]["target"]:
        info = manifest["pkg"][pkg]["target"][target]
    else:
        # rust-src is the same for all targets, and has a literal '*' in the
        # section key/name instead of a target
        info = manifest["pkg"][pkg]["target"]["*"]
    if "xz_url" in info:
        info["url"] = info.pop("xz_url")
        info["hash"] = info.pop("xz_hash")
    return (version, info)


def fetch_package(manifest, pkg, host):
    version, info = package(manifest, pkg, host)
    if not info["available"]:
        log("%s marked unavailable for %s" % (pkg, host))
        raise KeyError

    log("%s %s\n  %s\n  %s" % (pkg, version, info["url"], info["hash"]))
    sha = fetch(info["url"], info["hash"] is not None)
    if info["hash"] and sha != info["hash"]:
        log(
            "Checksum mismatch: package resource is different from manifest"
            "\n  %s" % sha
        )
        raise AssertionError
    return info


def fetch_std(manifest, targets):
    stds = []
    for target in targets:
        stds.append(fetch_package(manifest, "rust-std", target))
        # not available for i686
        if target != "i686-unknown-linux-musl":
            stds.append(fetch_package(manifest, "rust-analysis", target))
    return stds


def fetch_optional(manifest, pkg, host):
    try:
        return fetch_package(manifest, pkg, host)
    except KeyError:
        # The package is not available, oh well!
        return None


@contextmanager
def chdir(path):
    d = os.getcwd()
    log('cd "%s"' % path)
    os.chdir(path)
    try:
        yield
    finally:
        log('cd "%s"' % d)
        os.chdir(d)


def build_tar_package(name, base, directory):
    name = os.path.realpath(name)
    log("tarring {} from {}/{}".format(name, base, directory))
    assert name.endswith(".tar.zst")

    cctx = zstandard.ZstdCompressor()
    with open(name, "wb") as f, cctx.stream_writer(f) as z:
        with tarfile.open(mode="w|", fileobj=z) as tf:
            with chdir(base):
                tf.add(directory)


def fetch_manifest(channel="stable", host=None, targets=()):
    if channel.startswith("bors-"):
        assert host
        rev = channel[len("bors-") :]
        base_url = "https://s3-us-west-1.amazonaws.com/rust-lang-ci2/rustc-builds"
        manifest = {
            "date": "some date",
            "pkg": {},
        }

        def target(url):
            return {
                "url": url,
                "hash": None,
                "available": requests.head(url).status_code == 200,
            }

        for pkg in (
            "cargo",
            "rustc",
            "rustfmt-preview",
            "clippy-preview",
            "rust-analyzer-preview",
        ):
            manifest["pkg"][pkg] = {
                "version": "bors",
                "target": {
                    host: target(
                        "{}/{}/{}-nightly-{}.tar.xz".format(base_url, rev, pkg, host)
                    ),
                },
            }
        manifest["pkg"]["rust-src"] = {
            "version": "bors",
            "target": {
                "*": target("{}/{}/rust-src-nightly.tar.xz".format(base_url, rev)),
            },
        }
        for pkg in ("rust-std", "rust-analysis"):
            manifest["pkg"][pkg] = {
                "version": "bors",
                "target": {
                    t: target(
                        "{}/{}/{}-nightly-{}.tar.xz".format(base_url, rev, pkg, t)
                    )
                    for t in sorted(set(targets) | set([host]))
                },
            }
        return manifest
    if "-" in channel:
        channel, date = channel.split("-", 1)
        prefix = "/" + date
    else:
        prefix = ""
    url = "https://static.rust-lang.org/dist%s/channel-rust-%s.toml" % (prefix, channel)
    req = requests.get(url)
    req.raise_for_status()
    manifest = toml.loads(req.text)
    if manifest["manifest-version"] != "2":
        raise NotImplementedError(
            "Unrecognized manifest version %s." % manifest["manifest-version"]
        )
    return manifest


def patch_src(patch, module):
    log("Patching Rust src... {} with {}".format(module, patch))
    patch = os.path.realpath(patch)
    subprocess.check_call(["patch", "-d", module, "-p1", "-i", patch, "--fuzz=0", "-s"])


def build_src(install_dir, host, targets, patches):
    install_dir = os.path.abspath(install_dir)
    fetches = os.environ["MOZ_FETCHES_DIR"]
    rust_dir = os.path.join(fetches, "rust")
    patch_dir = os.path.join(os.environ["GECKO_PATH"], "build", "build-rust")

    # Clear and remake any previous install directory.
    try:
        shutil.rmtree(install_dir)
    except OSError as e:
        if e.errno != errno.ENOENT:
            raise
    os.makedirs(install_dir)

    # Patch the src (see the --patch flag's description for details)
    for p in patches:
        module, colon, file = p.partition(":")
        if not colon:
            module, file = "", p
        patch_file = os.path.join(patch_dir, file)
        patch_module = os.path.join(rust_dir, module)
        patch_src(patch_file, patch_module)

    log("Building Rust...")

    # Rust builds are configured primarily through a config.toml file.
    #
    # `sysconfdir` is overloaded to be relative instead of absolute.
    # This is the default of `install.sh`, but for whatever reason
    # `x.py install` has its own default of `/etc` which we don't want.
    #
    # `missing-tools` is set so `rustfmt` is allowed to fail. This means
    # we can "succeed" at building Rust while failing to build, say, Cargo.
    # Ideally the build system would have better granularity:
    # https://github.com/rust-lang/rust/issues/79249
    base_config = textwrap.dedent(
        """
        [build]
        docs = false
        sanitizers = true
        extended = true
        tools = ["analysis", "cargo", "rustfmt", "clippy", "src", "rust-analyzer"]

        [rust]
        ignore-git = false
        use-lld = true

        [install]
        prefix = "{prefix}"
        sysconfdir = "etc"

        [dist]
        missing-tools = true

        """.format(
            prefix=install_dir
        )
    )

    # Rust requires these to be specified per-target
    target_config = textwrap.dedent(
        """
        [target.{target}]
        cc = "clang"
        cxx = "clang++"
        linker = "clang"

        """
    )

    final_config = base_config
    for target in sorted(set(targets) | set([host])):
        final_config = final_config + target_config.format(target=target)

    with open(os.path.join(rust_dir, "config.toml"), "w") as file:
        file.write(final_config)

    # Setup the env so compilers and toolchains are visible
    clang = os.path.join(fetches, "clang")
    clang_bin = os.path.join(clang, "bin")
    clang_lib = os.path.join(clang, "lib")

    env = os.environ.copy()
    env.update(
        {
            "PATH": os.pathsep.join((clang_bin, os.environ["PATH"])),
            "LD_LIBRARY_PATH": clang_lib,
        }
    )

    # x.py install does everything we need for us.
    # If you're running into issues, consider using `-vv` to debug it.
    command = ["python3", "x.py", "install", "-v", "--host", host]
    for target in targets:
        command.extend(["--target", target])

    subprocess.check_call(command, stderr=subprocess.STDOUT, env=env, cwd=rust_dir)


def repack(
    host,
    targets,
    channel="stable",
    cargo_channel=None,
    compiler_builtins_hack=False,
    patches=[],
):
    install_dir = "rustc"
    if channel == "dev":
        build_src(install_dir, host, targets, patches)
    else:
        if patches:
            raise ValueError(
                'Patch specified, but channel "%s" is not "dev"!'
                "\nPatches are only for building from source." % channel
            )
        log("Repacking rust for %s supporting %s..." % (host, targets))
        manifest = fetch_manifest(channel, host, targets)
        log("Using manifest for rust %s as of %s." % (channel, manifest["date"]))
        if cargo_channel == channel:
            cargo_manifest = manifest
        else:
            cargo_manifest = fetch_manifest(cargo_channel, host, targets)
            log(
                "Using manifest for cargo %s as of %s."
                % (cargo_channel, cargo_manifest["date"])
            )

        log("Fetching packages...")
        rustc = fetch_package(manifest, "rustc", host)
        cargo = fetch_package(cargo_manifest, "cargo", host)
        stds = fetch_std(manifest, targets)
        rustsrc = fetch_package(manifest, "rust-src", host)
        rustfmt = fetch_optional(manifest, "rustfmt-preview", host)
        clippy = fetch_optional(manifest, "clippy-preview", host)
        rust_analyzer = fetch_optional(manifest, "rust-analyzer-preview", host)

        log("Installing packages...")

        # Clear any previous install directory.
        try:
            shutil.rmtree(install_dir)
        except OSError as e:
            if e.errno != errno.ENOENT:
                raise
        install(os.path.basename(rustc["url"]), install_dir)
        install(os.path.basename(cargo["url"]), install_dir)
        install(os.path.basename(rustsrc["url"]), install_dir)
        if rustfmt:
            install(os.path.basename(rustfmt["url"]), install_dir)
        if clippy:
            install(os.path.basename(clippy["url"]), install_dir)
        if rust_analyzer:
            install(os.path.basename(rust_analyzer["url"]), install_dir)
        for std in stds:
            install(os.path.basename(std["url"]), install_dir)
            pass
    # Workaround for https://github.com/rust-lang/rust/issues/98746:
    # Remove debug symbols from the compiler_builtins rlib.
    hack_targets = ()
    if compiler_builtins_hack:
        hack_targets = (
            "x86_64-unknown-linux-gnu",
            "i686-unknown-linux-gnu",
            "x86_64-linux-android",
            "i686-linux-android",
            "thumbv7neon-linux-androideabi",
            "aarch64-linux-android",
        )
        llvm_bin = os.path.join(os.environ["MOZ_FETCHES_DIR"], "clang", "bin")
    for t in hack_targets:
        if t not in targets:
            continue
        for lib in glob.glob(
            os.path.join(
                install_dir, "lib", "rustlib", t, "lib", "libcompiler_builtins*"
            )
        ):
            log("Strip debuginfo from %s" % lib)
            subprocess.check_call(
                [os.path.join(llvm_bin, "llvm-strip"), "-d", os.path.abspath(lib)],
            )

    log("Creating archive...")
    tar_file = install_dir + ".tar.zst"
    build_tar_package(tar_file, ".", install_dir)
    shutil.rmtree(install_dir)
    log("%s is ready." % tar_file)

    upload_dir = os.environ.get("UPLOAD_DIR")
    if upload_dir:
        # Create the upload directory if it doesn't exist.
        try:
            log("Creating upload directory in %s..." % os.path.abspath(upload_dir))
            os.makedirs(upload_dir)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
        # Move the tarball to the output directory for upload.
        log("Moving %s to the upload directory..." % tar_file)
        shutil.move(tar_file, upload_dir)


def expand_platform(name):
    """Expand a shortcut name to a full Rust platform string."""
    platforms = {
        "android": "armv7-linux-androideabi",
        "android_x86": "i686-linux-android",
        "android_x86-64": "x86_64-linux-android",
        "android_aarch64": "aarch64-linux-android",
        "linux64": "x86_64-unknown-linux-gnu",
        "linux32": "i686-unknown-linux-gnu",
        "mac": "x86_64-apple-darwin",
        "macos": "x86_64-apple-darwin",
        "mac64": "x86_64-apple-darwin",
        "mac32": "i686-apple-darwin",
        "win64": "x86_64-pc-windows-msvc",
        "win32": "i686-pc-windows-msvc",
        "mingw32": "i686-pc-windows-gnu",
    }
    return platforms.get(name, name)


def validate_channel(channel):
    """Require a specific release version.

    Packaging from meta-channels, like `stable`, `beta`, or `nightly`
    doesn't give repeatable output. Reject such channels."""
    channel_prefixes = ("stable", "beta", "nightly")
    if any([channel.startswith(c) for c in channel_prefixes]):
        if "-" not in channel:
            raise ValueError(
                'Generic channel "%s" specified!'
                "\nPlease give a specific release version"
                ' like "1.24.0" or "beta-2018-02-20".' % channel
            )


def args():
    """Read command line arguments and return options."""
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--channel",
        help="Release channel to use:"
        " 1.xx.y, beta-yyyy-mm-dd,"
        " nightly-yyyy-mm-dd,"
        " bors-$rev (grab a build from rust's CI),"
        " or dev (build from source).",
        required=True,
    )
    parser.add_argument(
        "--patch",
        dest="patches",
        action="append",
        default=[],
        help="apply the given patch file to a dev build."
        " Patch files should be placed in /build/build-rust."
        " Patches can be prefixed with `module-path:` to specify they"
        " apply to that git submodule in the Rust source."
        " e.g. `src/llvm-project:mypatch.diff` patches rust's llvm."
        " Can be given more than once.",
    )
    parser.add_argument(
        "--cargo-channel",
        help="Release channel version to use for cargo."
        " Defaults to the same as --channel.",
    )
    parser.add_argument(
        "--compiler-builtins-hack",
        action="store_true",
        help="Enable workaround for " "https://github.com/rust-lang/rust/issues/98746.",
    )
    parser.add_argument(
        "--host",
        help="Host platform for the toolchain executable:"
        " e.g. linux64 or aarch64-linux-android."
        " Defaults to linux64.",
    )
    parser.add_argument(
        "--target",
        dest="targets",
        action="append",
        default=[],
        help="Additional target platform to support:"
        " e.g. linux32 or i686-pc-windows-gnu."
        " can be given more than once.",
    )
    args = parser.parse_args()
    if not args.cargo_channel:
        args.cargo_channel = args.channel
    validate_channel(args.channel)
    validate_channel(args.cargo_channel)
    if not args.host:
        args.host = "linux64"
    args.host = expand_platform(args.host)
    args.targets = [expand_platform(t) for t in args.targets]

    return args


if __name__ == "__main__":
    args = vars(args())
    setup_gpg()
    repack(**args)