aboutsummaryrefslogtreecommitdiff
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2012, 2015, 2016, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2019 Ricardo Wurmus <rekado@elephly.net>
;;; Copyright © 2021 Maxim Cournoyer <maxim.cournoyer@gmail.com>
;;; Copyright © 2021 Maxime Devos <maximedevos@telenet.be>
;;; Copyright © 2021 Brendan Tildesley <mail@brendan.scot>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.


(define-module (test build-utils)
  #:use-module (guix tests)
  #:use-module (guix build utils)
  #:use-module ((guix utils)
                #:select (%current-system call-with-temporary-directory))
  #:use-module (gnu packages)
  #:use-module (gnu packages bootstrap)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-35)
  #:use-module (srfi srfi-64)
  #:use-module (rnrs io ports)
  #:use-module (ice-9 popen))


(test-begin "build-utils")

(test-equal "alist-cons-before"
  '((a . 1) (x . 42) (b . 2) (c . 3))
  (alist-cons-before 'b 'x 42 '((a . 1) (b . 2) (c . 3))))

(test-assert "alist-cons-before, reference not found"
  (not (false-if-exception
        (alist-cons-before 'z 'x 42 '((a . 1) (b . 2) (c . 3))))))

(test-equal "alist-cons-after"
  '((a . 1) (b . 2) (x . 42) (c . 3))
  (alist-cons-after 'b 'x 42 '((a . 1) (b . 2) (c . 3))))

(test-assert "alist-cons-after, reference not found"
  (not (false-if-exception
        (alist-cons-after 'z 'x 42 '((a . 1) (b . 2) (c . 3))))))

(test-equal "alist-replace"
  '((a . 1) (b . 77) (c . 3))
  (alist-replace 'b 77 '((a . 1) (b . 2) (c . 3))))

(test-assert "alist-replace, key not found"
  (not (false-if-exception
        (alist-replace 'z 77 '((a . 1) (b . 2) (c . 3))))))

(test-equal "fold-port-matches"
  (make-list 3 "Guix")
  (call-with-input-string "Guix is cool, Guix rocks, and it uses Guile, Guix!"
    (lambda (port)
      (fold-port-matches cons '() "Guix" port))))

(test-equal "fold-port-matches, trickier"
  (reverse '("Guix" "guix" "Guix" "guiX" "Guix"))
  (call-with-input-string "Guix, guix, GuiGuixguiX, Guix"
    (lambda (port)
      (fold-port-matches cons '()
                         (list (char-set #\G #\g)
                               (char-set #\u)
                               (char-set #\i)
                               (char-set #\x #\X))
                         port))))

(test-equal "fold-port-matches, with unmatched chars"
  '("Guix" #\, #\space
    "guix" #\, #\space
    #\G #\u #\i "Guix" "guiX" #\, #\space
    "Guix")
  (call-with-input-string "Guix, guix, GuiGuixguiX, Guix"
    (lambda (port)
      (reverse
       (fold-port-matches cons '()
                          (list (char-set #\G #\g)
                                (char-set #\u)
                                (char-set #\i)
                                (char-set #\x #\X))
                          port
                          cons)))))

(test-equal "wrap-program, one input, multiple calls"
  "hello world\n"
  (call-with-temporary-directory
   (lambda (directory)
     (let ((bash (search-bootstrap-binary "bash" (%current-system)))
           (foo  (string-append directory "/foo")))

       (call-with-output-file foo
         (lambda (p)
           (format p
                   "#!~a~%echo \"${GUIX_FOO} ${GUIX_BAR}\"~%"
                   bash)))
       (chmod foo #o777)

       ;; wrap-program uses `which' to find bash for the wrapper shebang, but
       ;; it can't know about the bootstrap bash in the store, since it's not
       ;; named "bash".  Help it out a bit by providing a symlink it this
       ;; package's output.
       (with-environment-variable "PATH" (dirname bash)
         (wrap-program foo `("GUIX_FOO" prefix ("hello")))
         (wrap-program foo `("GUIX_BAR" prefix ("world")))

         ;; The bootstrap Bash is linked against an old libc and would abort
         ;; with an assertion failure when trying to load incompatible locale
         ;; data.
         (unsetenv "LOCPATH")

         (let* ((pipe (open-input-pipe foo))
                (str  (get-string-all pipe)))
           (with-directory-excursion directory
             (for-each delete-file '("foo" ".foo-real")))
           (and (zero? (close-pipe pipe))
                str)))))))

(test-assert "invoke/quiet, success"
  (begin
    (invoke/quiet "true")
    #t))

(test-assert "invoke/quiet, failure"
  (guard (c ((message-condition? c)
             (string-contains (condition-message c) "This is an error.")))
    (invoke/quiet "sh" "-c" "echo This is an error. ; false")
    #f))

(test-assert "invoke/quiet, failure, message on stderr"
  (guard (c ((message-condition? c)
             (string-contains (condition-message c)
                              "This is another error.")))
    (invoke/quiet "sh" "-c" "echo This is another error. >&2 ; false")
    #f))

(let ((script-contents "\
#!/anything/cabbage-bash-1.2.3/bin/sh

echo hello world"))

  (test-equal "wrap-script, simple case"
    (string-append
     (format #f "\
#!~a --no-auto-compile
#!#; Guix wrapper
#\\-~s
#\\-~s
"
             (which "guile")
             '(begin (let ((current (getenv "GUIX_FOO")))
                       (setenv "GUIX_FOO"
                               (if current
                                   (string-append "/some/path:/some/other/path"
                                                  ":" current)
                                   "/some/path:/some/other/path"))))
             '(let ((cl (command-line)))
                (apply execl "/anything/cabbage-bash-1.2.3/bin/sh"
                       (car cl) (append (quote ()) cl))))
     script-contents)
    (call-with-temporary-directory
     (lambda (directory)
       (let ((script-file-name (string-append directory "/foo")))
         (call-with-output-file script-file-name
           (lambda (port)
             (display script-contents port)))
         (chmod script-file-name #o777)
         (wrap-script script-file-name
                      `("GUIX_FOO" prefix ("/some/path"
                                           "/some/other/path")))
         (let ((str (call-with-input-file script-file-name get-string-all)))
           (with-directory-excursion directory
             (delete-file "foo"))
           str))))))

(let ((script-contents "\
#!/anything/cabbage-bash-1.2.3/bin/python3 -and -args
# vim:fileencoding=utf-8
print('hello world')"))

  (test-equal "wrap-script, with encoding declaration"
    (string-append
     (format #f "\
#!MYGUILE --no-auto-compile
#!#; # vim:fileencoding=utf-8
#\\-~s
#\\-~s
"
             '(begin (let ((current (getenv "GUIX_FOO")))
                       (setenv "GUIX_FOO"
                               (if current
                                   (string-append "/some/path:/some/other/path"
                                                  ":" current)
                                   "/some/path:/some/other/path"))))
             `(let ((cl (command-line)))
                (apply execl "/anything/cabbage-bash-1.2.3/bin/python3"
                       (car cl)
                       (append '("-and" "-args") cl))))
     script-contents)
    (call-with-temporary-directory
     (lambda (directory)
       (let ((script-file-name (string-append directory "/foo")))
         (call-with-output-file script-file-name
           (lambda (port)
             (format port script-contents)))
         (chmod script-file-name #o777)

         (wrap-script script-file-name
                      #:guile "MYGUILE"
                      `("GUIX_FOO" prefix ("/some/path"
                                           "/some/other/path")))
         (let ((str (call-with-input-file script-file-name get-string-all)))
           (with-directory-excursion directory
             (delete-file "foo"))
           str))))))

(test-assert "wrap-script, raises condition"
  (call-with-temporary-directory
   (lambda (directory)
     (let ((script-file-name (string-append directory "/foo")))
       (call-with-output-file script-file-name
         (lambda (port)
           (format port "This is not a script")))
       (chmod script-file-name #o777)
       (guard (c ((wrap-error? c) #t))
         (wrap-script script-file-name
                      #:guile "MYGUILE"
                      `("GUIX_FOO" prefix ("/some/path"
                                           "/some/other/path")))
         #f)))))

(define (arg-test bash-args)
  (call-with-temporary-directory
   (lambda (directory)
     (let ((script-file-name (string-append directory "/bash-test.sh")))
       (call-with-output-file script-file-name
         (lambda (port)
           (display (string-append "\
#!" (which "bash") bash-args "
echo \"$#$0$*${A}\"")
                    port)))

       (display "Unwrapped script contents:\n")
       (call-with-input-file script-file-name
         (lambda (port) (display (get-string-all port))))
       (newline) (newline)
       (chmod script-file-name #o777)
       (setenv "A" "A")
       (let* ((run-script (lambda _
                            (open-pipe*
                             OPEN_READ
                             script-file-name "1" "2" "3 3" "4")))
              (pipe (run-script))
              (unwrapped-output (get-string-all pipe)))
         (close-pipe pipe)

         (wrap-script script-file-name `("A" = ("A\nA")))

         (display "Wrapped script contents:\n")
         (call-with-input-file script-file-name
           (lambda (port) (display (get-string-all port))))
         (newline) (newline)

         (let* ((pipe (run-script))
                (wrapped-output (get-string-all pipe)))
           (close-pipe pipe)
           (display "./bash-test.sh 1 2 3\\ 3 4 # Output:\n")
           (display unwrapped-output) (newline)
           (display "./bash-test.sh 1 2 3\\ 3 4 # Output (wrapped):\n")
           (display wrapped-output) (newline)
           (string=? (string-append unwrapped-output "A\n")
                     wrapped-output)))))))

(test-assert "wrap-script, argument handling"
  (arg-test ""))

(test-assert "wrap-script, argument handling, bash --norc"
  (arg-test " --norc"))

(test-equal "substitute*, text contains a NUL byte, UTF-8"
  "c\0d"
  (with-fluids ((%default-port-encoding "UTF-8")
                (%default-port-conversion-strategy 'error))
    ;; The GNU libc is locale sensitive.  Depending on the value of LANG, the
    ;; test could fail with "string contains #\\nul character: ~S" or "cannot
    ;; convert wide string to output locale".
    (setlocale LC_ALL "en_US.UTF-8")
    (call-with-temporary-output-file
     (lambda (file port)
       (format port "a\0b")
       (flush-output-port port)

       (substitute* file
         (("a") "c")
         (("b") "d"))

       (with-input-from-file file
         (lambda _
           (get-string-all (current-input-port))))))))

(test-equal "search-input-file: exception if not found"
  `((path)
    (file . "does-not-exist"))
  (guard (e ((search-error? e)
             `((path . ,(search-error-path e))
               (file . ,(search-error-file e)))))
    (search-input-file '() "does-not-exist")))

(test-equal "search-input-file: can find if existent"
  (which "guile")
  (search-input-file
    `(("guile/bin" . ,(dirname (which "guile"))))
    "guile"))

(test-equal "search-input-file: can search in multiple directories"
  (which "guile")
  (call-with-temporary-directory
    (lambda (directory)
      (search-input-file
        `(("irrelevant" . ,directory)
          ("guile/bin" . ,(dirname (which "guile"))))
        "guile"))))

(test-end)
='n401' href='#n401'>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 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2014, 2015 Mark H Weaver <mhw@netris.org>
;;; Copyright © 2014, 2015, 2016, 2017 Ricardo Wurmus <rekado@elephly.net>
;;; Copyright © 2015 Andreas Enge <andreas@enge.fr>
;;; Copyright © 2015, 2016, 2017 Efraim Flashner <efraim@flashner.co.il>
;;; Copyright © 2016 Carlos Sánchez de La Lama <csanchezdll@gmail.com>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.

(define-module (gnu packages gcc)
  #:use-module ((guix licenses)
                #:select (gpl3+ gpl2+ lgpl2.1+ lgpl2.0+ fdl1.3+))
  #:use-module (gnu packages)
  #:use-module (gnu packages bootstrap)
  #:use-module (gnu packages compression)
  #:use-module (gnu packages multiprecision)
  #:use-module (gnu packages texinfo)
  #:use-module (gnu packages dejagnu)
  #:use-module (gnu packages documentation)
  #:use-module (gnu packages xml)
  #:use-module (gnu packages docbook)
  #:use-module (gnu packages graphviz)
  #:use-module (gnu packages elf)
  #:use-module (gnu packages perl)
  #:use-module (guix packages)
  #:use-module (guix download)
  #:use-module (guix build-system gnu)
  #:use-module (guix build-system trivial)
  #:use-module (guix utils)
  #:use-module (srfi srfi-1)
  #:use-module (ice-9 regex))

(define %gcc-infrastructure
  ;; Base URL for GCC's infrastructure.
  "mirror://gcc/infrastructure/")

(define (gcc-configure-flags-for-triplet target)
  "Return a list of additional GCC `configure' flags for TARGET, a GNU triplet.

The purpose of this procedure is to translate extended GNU triplets---e.g.,
where the OS part is overloaded to denote a specific ABI---into GCC
`configure' options.  We take extended GNU triplets that glibc recognizes."
  (cond ((string-match "^mips64el.*gnuabin?64$" target)
         ;; Triplets recognized by glibc as denoting the N64 ABI; see
         ;; ports/sysdeps/mips/preconfigure.
         '("--with-abi=64"))

        ((string-match "^arm.*-gnueabihf$" target)
         '("--with-arch=armv7-a"
           "--with-float=hard"
           "--with-mode=thumb"
           "--with-fpu=neon"))

        (else
         ;; TODO: Add `arm.*-gnueabi', etc.
         '())))

(define-public gcc-4.7
  (let* ((stripped? #t)      ;whether to strip the compiler, not the libraries
         (maybe-target-tools
          (lambda ()
            ;; Return the `_FOR_TARGET' variables that are needed when
            ;; cross-compiling GCC.
            (let ((target (%current-target-system)))
              (if target
                  (map (lambda (var tool)
                         (string-append (string-append var "_FOR_TARGET")
                                        "=" target "-" tool))
                       '("CC"  "CXX" "LD" "AR" "NM" "RANLIB" "STRIP")
                       '("gcc" "g++" "ld" "ar" "nm" "ranlib" "strip"))
                  '()))))
         (libdir
          (let ((base '(or (assoc-ref outputs "lib")
                           (assoc-ref outputs "out"))))
            (lambda ()
              ;; Return the directory that contains lib/libgcc_s.so et al.
              (if (%current-target-system)
                  `(string-append ,base "/" ,(%current-target-system))
                  base))))
         (configure-flags
          (lambda ()
            ;; This is terrible.  Since we have two levels of quasiquotation,
            ;; we have to do this convoluted thing just so we can insert the
            ;; contents of (maybe-target-tools).
            (list 'quasiquote
                  (append
                   '("--enable-plugin"
                     "--enable-languages=c,c++"
                     "--disable-multilib"
                     "--with-system-zlib"

                     ;; No pre-compiled libstdc++ headers, to save space.
                     "--disable-libstdcxx-pch"

                     "--with-local-prefix=/no-gcc-local-prefix"

                     ;; With a separate "lib" output, the build system
                     ;; incorrectly guesses GPLUSPLUS_INCLUDE_DIR, so force
                     ;; it.  (Don't use a versioned sub-directory, that's
                     ;; unnecessary.)
                     ,(string-append "--with-gxx-include-dir="
                                     (assoc-ref %outputs "out")
                                     "/include/c++")

                     ,(let ((libc (assoc-ref %build-inputs "libc")))
                        (if libc
                            (string-append "--with-native-system-header-dir=" libc
                                           "/include")
                            "--without-headers")))

                   ;; Pass the right options for the target triplet.
                   (let ((triplet
                          (or (%current-target-system)
                              (nix-system->gnu-triplet (%current-system)))))
                     (gcc-configure-flags-for-triplet triplet))

                   (maybe-target-tools))))))
    (package
      (name "gcc")
      (version "4.7.4")
      (source (origin
               (method url-fetch)
               (uri (string-append "mirror://gnu/gcc/gcc-"
                                   version "/gcc-" version ".tar.bz2"))
               (sha256
                (base32
                 "10k2k71kxgay283ylbbhhs51cl55zn2q38vj5pk4k950qdnirrlj"))))
      (build-system gnu-build-system)

      ;; Separate out the run-time support libraries because all the
      ;; dynamic-linked objects depend on it.
      (outputs '("out"                    ;commands, etc. (60+ MiB)
                 "lib"                    ;libgcc_s, libgomp, etc. (15+ MiB)
                 "debug"))                ;debug symbols of run-time libraries

      (inputs `(("gmp" ,gmp)
                ("mpfr" ,mpfr)
                ("mpc" ,mpc)
                ("libelf" ,libelf)
                ("zlib" ,zlib)))

      ;; GCC < 5 is one of the few packages that doesn't ship .info files.
      ;; Newer texinfos fail to build the manual, so we use an older one.
      (native-inputs `(("texinfo" ,texinfo-5)))

      (arguments
       `(#:out-of-source? #t
         #:configure-flags ,(configure-flags)
         #:make-flags
         ;; None of the flags below are needed when doing a Canadian cross.
         ;; TODO: Simplify this.
         ,(if (%current-target-system)
              (if stripped?
                  ''("CFLAGS=-g0 -O2")
                  ''())
              `(let* ((libc        (assoc-ref %build-inputs "libc"))
                      (libc-native (or (assoc-ref %build-inputs "libc-native")
                                       libc)))
                 `(,@(if libc
                         (list (string-append "LDFLAGS_FOR_TARGET="
                                              "-B" libc "/lib "
                                              "-Wl,-dynamic-linker "
                                              "-Wl," libc
                                              ,(glibc-dynamic-linker)))
                         '())

                   ;; Native programs like 'genhooks' also need that right.
                   ,(string-append "LDFLAGS="
                                   "-Wl,-rpath=" libc-native "/lib "
                                   "-Wl,-dynamic-linker "
                                   "-Wl," libc-native ,(glibc-dynamic-linker))
                   ,(string-append "BOOT_CFLAGS=-O2 "
                                   ,(if stripped? "-g0" "-g")))))

         #:tests? #f

         #:phases
         (alist-cons-before
          'configure 'pre-configure
          (lambda* (#:key inputs outputs #:allow-other-keys)
            (let ((libdir ,(libdir))
                  (libc   (assoc-ref inputs "libc")))
              (when libc
                ;; The following is not performed for `--without-headers'
                ;; cross-compiler builds.

                ;; Join multi-line definitions of GLIBC_DYNAMIC_LINKER* into a
                ;; single line, to allow the next step to work properly.
                (for-each
                 (lambda (x)
                   (substitute* (find-files "gcc/config"
                                            "^(linux|gnu|sysv4)(64|-elf|-eabi)?\\.h$")
                     (("(#define (GLIBC|GNU_USER)_DYNAMIC_LINKER.*)\\\\\n$" _ line)
                      line)))
                 '(1 2 3))

                ;; Fix the dynamic linker's file name.
                (substitute* (find-files "gcc/config"
                                         "^(linux|gnu|sysv4)(64|-elf|-eabi)?\\.h$")
                  (("#define (GLIBC|GNU_USER)_DYNAMIC_LINKER([^ \t]*).*$"
                    _ gnu-user suffix)
                   (format #f "#define ~a_DYNAMIC_LINKER~a \"~a\"~%"
                           gnu-user suffix
                           (string-append libc ,(glibc-dynamic-linker)))))

                ;; Tell where to find libstdc++, libc, and `?crt*.o', except
                ;; `crt{begin,end}.o', which come with GCC.
                (substitute* (find-files "gcc/config"
                                         "^gnu-user.*\\.h$")
                  (("#define GNU_USER_TARGET_LIB_SPEC (.*)$" _ suffix)
                   ;; Help libgcc_s.so be found (see also below.)  Always use
                   ;; '-lgcc_s' so that libgcc_s.so is always found by those
                   ;; programs that use 'pthread_cancel' (glibc dlopens
                   ;; libgcc_s.so when pthread_cancel support is needed, but
                   ;; having it in the application's RUNPATH isn't enough; see
                   ;; <http://sourceware.org/ml/libc-help/2013-11/msg00023.html>.)
                   ;;
                   ;; NOTE: The '-lgcc_s' added below needs to be removed in a
                   ;; later phase of %gcc-static.  If you change the string
                   ;; below, make sure to update the relevant code in
                   ;; %gcc-static package as needed.
                   (format #f "#define GNU_USER_TARGET_LIB_SPEC \
\"-L~a/lib %{!static:-rpath=~a/lib %{!static-libgcc:-rpath=~a/lib -lgcc_s}} \" ~a"
                           libc libc libdir suffix))
                  (("#define GNU_USER_TARGET_STARTFILE_SPEC.*$" line)
                   (format #f "#define STANDARD_STARTFILE_PREFIX_1 \"~a/lib\"
#define STANDARD_STARTFILE_PREFIX_2 \"\"
~a"
                           libc line)))

              ;; The rs6000 (a.k.a. powerpc) config in GCC does not use
              ;; GNU_USER_* defines.  Do the above for this case.
              (substitute*
                  "gcc/config/rs6000/sysv4.h"
                (("#define LIB_LINUX_SPEC (.*)$" _ suffix)
                 (format #f "#define LIB_LINUX_SPEC \
\"-L~a/lib %{!static:-rpath=~a/lib %{!static-libgcc:-rpath=~a/lib -lgcc_s}} \" ~a"
                         libc libc libdir suffix))
                (("#define	STARTFILE_LINUX_SPEC.*$" line)
                 (format #f "#define STANDARD_STARTFILE_PREFIX_1 \"~a/lib\"
#define STANDARD_STARTFILE_PREFIX_2 \"\"
~a"
                         libc line))))

              ;; Don't retain a dependency on the build-time sed.
              (substitute* "fixincludes/fixincl.x"
                (("static char const sed_cmd_z\\[\\] =.*;")
                 "static char const sed_cmd_z[] = \"sed\";"))

              ;; Aarch64 support didn't land in GCC until the 4.8 series.
              (when (file-exists? "gcc/config/aarch64")
                ;; Force Aarch64 libdir to be /lib and not /lib64
                (substitute* "gcc/config/aarch64/t-aarch64-linux"
                  (("lib64") "lib")))

              (when (file-exists? "libbacktrace")
                ;; GCC 4.8+ comes with libbacktrace.  By default it builds
                ;; with -Werror, which fails with a -Wcast-qual error in glibc
                ;; 2.21's stdlib-bsearch.h.  Remove -Werror.
                (substitute* "libbacktrace/configure"
                  (("WARN_FLAGS=(.*)-Werror" _ flags)
                   (string-append "WARN_FLAGS=" flags)))

                (when (file-exists? "libsanitizer/libbacktrace")
                  ;; Same in libsanitizer's bundled copy (!) found in 4.9+.
                  (substitute* "libsanitizer/libbacktrace/Makefile.in"
                    (("-Werror")
                     ""))))

              ;; Add a RUNPATH to libstdc++.so so that it finds libgcc_s.
              ;; See <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=32354>
              ;; and <http://bugs.gnu.org/20358>.
              (substitute* "libstdc++-v3/src/Makefile.in"
                (("^OPT_LDFLAGS = ")
                 "OPT_LDFLAGS = -Wl,-rpath=$(libdir) "))

              ;; Move libstdc++*-gdb.py to the "lib" output to avoid a
              ;; circularity between "out" and "lib".  (Note:
              ;; --with-python-dir is useless because it imposes $(prefix) as
              ;; the parent directory.)
              (substitute* "libstdc++-v3/python/Makefile.in"
                (("pythondir = .*$")
                 (string-append "pythondir = " libdir "/share"
                                "/gcc-$(gcc_version)/python\n")))

              ;; Avoid another circularity between the outputs: this #define
              ;; ends up in auto-host.h in the "lib" output, referring to
              ;; "out".  (This variable is used to augment cpp's search path,
              ;; but there's nothing useful to look for here.)
              (substitute* "gcc/config.in"
                (("PREFIX_INCLUDE_DIR")
                 "PREFIX_INCLUDE_DIR_isnt_necessary_here"))))

          (alist-cons-after
           'configure 'post-configure
           (lambda _
             ;; Don't store configure flags, to avoid retaining references to
             ;; build-time dependencies---e.g., `--with-ppl=/gnu/store/xxx'.
             (substitute* "Makefile"
               (("^TOPLEVEL_CONFIGURE_ARGUMENTS=(.*)$" _ rest)
                "TOPLEVEL_CONFIGURE_ARGUMENTS=\n")))
           %standard-phases))))

      (native-search-paths
       ;; Use the language-specific variables rather than 'CPATH' because they
       ;; are equivalent to '-isystem' whereas 'CPATH' is equivalent to '-I'.
       ;; The intent is to allow headers that are in the search path to be
       ;; treated as "system headers" (headers exempt from warnings) just like
       ;; the typical /usr/include headers on an FHS system.
       (list (search-path-specification
              (variable "C_INCLUDE_PATH")
              (files '("include")))
             (search-path-specification
              (variable "CPLUS_INCLUDE_PATH")
              (files '("include")))
             (search-path-specification
              (variable "LIBRARY_PATH")
              (files '("lib" "lib64")))))

      (properties `((gcc-libc . ,(assoc-ref inputs "libc"))))
      (synopsis "GNU Compiler Collection")
      (description
       "GCC is the GNU Compiler Collection.  It provides compiler front-ends
for several languages, including C, C++, Objective-C, Fortran, Java, Ada, and
Go.  It also includes runtime support libraries for these languages.")
      (license gpl3+)
      (supported-systems (delete "aarch64-linux" %supported-systems))
      (home-page "https://gcc.gnu.org/"))))

(define-public gcc-4.8
  (package (inherit gcc-4.7)
    (version "4.8.5")
    (source (origin
              (method url-fetch)
              (uri (string-append "mirror://gnu/gcc/gcc-"
                                  version "/gcc-" version ".tar.bz2"))
              (sha256
               (base32
                "08yggr18v373a1ihj0rg2vd6psnic42b518xcgp3r9k81xz1xyr2"))
              (patches (search-patches "gcc-arm-link-spec-fix.patch"))))
    (supported-systems %supported-systems)
    (inputs
     `(("isl" ,isl-0.11)
       ("cloog" ,cloog)
       ,@(package-inputs gcc-4.7)))))

(define-public gcc-4.9
  (package (inherit gcc-4.8)
    (version "4.9.4")
    (source (origin
              (method url-fetch)
              (uri (string-append "mirror://gnu/gcc/gcc-"
                                  version "/gcc-" version ".tar.bz2"))
              (sha256
               (base32
                "14l06m7nvcvb0igkbip58x59w3nq6315k6jcz3wr9ch1rn9d44bc"))
              (patches (search-patches "gcc-arm-bug-71399.patch"
                                       "gcc-libvtv-runpath.patch"))))
    (native-inputs `(("texinfo" ,texinfo)))))

(define-public gcc-5
  ;; Note: GCC >= 5 ships with .info files but 'make install' fails to install
  ;; them in a VPATH build.
  (package (inherit gcc-4.9)
    (version "5.4.0")
    (source (origin
              (method url-fetch)
              (uri (string-append "mirror://gnu/gcc/gcc-"
                                  version "/gcc-" version ".tar.bz2"))
              (sha256
               (base32
                "0fihlcy5hnksdxk0sn6bvgnyq8gfrgs8m794b1jxwd1dxinzg3b0"))
              (patches (search-patches "gcc-arm-bug-71399.patch"
                                       "gcc-strmov-store-file-names.patch"
                                       "gcc-asan-powerpc-missing-include.patch"
                                       "gcc-5.0-libvtv-runpath.patch"
                                       "gcc-5-source-date-epoch-1.patch"
                                       "gcc-5-source-date-epoch-2.patch"))))))
    ;; TODO: gcc-5 doesn't need cloog.
    ;;(inputs
    ;; `(("isl" ,isl)
    ;;   ,@(package-inputs gcc-4.7)))))

(define-public gcc-6
  (package
    (inherit gcc-5)
    (version "6.4.0")
    (source (origin
              (method url-fetch)
              (uri (string-append "mirror://gnu/gcc/gcc-"
                                  version "/gcc-" version ".tar.xz"))
              (sha256
               (base32
                "1m0lr7938lw5d773dkvwld90hjlcq2282517d1gwvrfzmwgg42w5"))
              (patches (search-patches "gcc-strmov-store-file-names.patch"
                                       "gcc-5.0-libvtv-runpath.patch"))))
    (inputs
     `(("isl" ,isl)
       ,@(package-inputs gcc-4.7)))))

(define-public gcc-7
  (package
    (inherit gcc-6)
    (version "7.2.0")
    (source (origin
              (method url-fetch)
              (uri (string-append "mirror://gnu/gcc/gcc-"
                                  version "/gcc-" version ".tar.xz"))
              (sha256
               (base32
                "16j7i0888j2f1yp9l0nhji6cq65dy6y4nwy8868a8njbzzwavxqw"))
              (patches (search-patches "gcc-strmov-store-file-names.patch"
                                       "gcc-5.0-libvtv-runpath.patch"))))
    (description
     "GCC is the GNU Compiler Collection.  It provides compiler front-ends
for several languages, including C, C++, Objective-C, Fortran, Ada, and Go.
It also includes runtime support libraries for these languages.")))

;; Note: When changing the default gcc version, update
;;       the gcc-toolchain-* definitions and the gfortran definition
;;       accordingly.
(define-public gcc gcc-5)

(define-public (make-libstdc++ gcc)
  "Return a libstdc++ package based on GCC.  The primary use case is when
using compilers other than GCC."
  (package
    (inherit gcc)
    (name "libstdc++")
    (arguments
     `(#:out-of-source? #t
       #:phases (alist-cons-before
                 'configure 'chdir
                 (lambda _
                   (chdir "libstdc++-v3"))
                 %standard-phases)
       #:configure-flags `("--disable-libstdcxx-pch"
                           ,(string-append "--with-gxx-include-dir="
                                           (assoc-ref %outputs "out")
                                           "/include"))))
    (outputs '("out" "debug"))
    (inputs '())
    (native-inputs '())
    (propagated-inputs '())
    (synopsis "GNU C++ standard library")))

(define-public libstdc++-4.9
  (make-libstdc++ gcc-4.9))

(define (make-libiberty gcc)
  "Return a libiberty package based on GCC."
  (package
    (inherit gcc)
    (name "libiberty")
    (arguments
     `(#:out-of-source? #t
       #:phases
       (modify-phases %standard-phases
         (add-before 'configure 'chdir
                     (lambda _
                       (chdir "libiberty")
                       #t))
         (replace
          'install
          (lambda* (#:key outputs #:allow-other-keys)
            (let* ((out     (assoc-ref outputs "out"))
                   (lib     (string-append out "/lib/"))
                   (include (string-append out "/include/")))
              (mkdir-p lib)
              (mkdir-p include)
              (copy-file "libiberty.a"
                         (string-append lib "libiberty.a"))
              (copy-file "../include/libiberty.h"
                         (string-append include "libiberty.h"))
              #t))))))
    (inputs '())
    (outputs '("out"))
    (native-inputs '())
    (propagated-inputs '())
    (synopsis "Collection of subroutines used by various GNU programs")))

(define-public libiberty
  (make-libiberty gcc))

(define* (custom-gcc gcc name languages
                     #:optional
                     (search-paths (package-native-search-paths gcc))
                     #:key (separate-lib-output? #t))
  "Return a custom version of GCC that supports LANGUAGES.  Use SEARCH-PATHS
as the 'native-search-paths' field."
  (package (inherit gcc)
    (name name)
    (outputs (if separate-lib-output?
                 (package-outputs gcc)
                 (delete "lib" (package-outputs gcc))))
    (native-search-paths search-paths)
    (arguments
     (substitute-keyword-arguments `(#:modules ((guix build gnu-build-system)
                                                (guix build utils)
                                                (ice-9 regex)
                                                (srfi srfi-1)
                                                (srfi srfi-26))
                                               ,@(package-arguments gcc))
       ((#:configure-flags flags)
        `(cons (string-append "--enable-languages="
                              ,(string-join languages ","))
               (remove (cut string-match "--enable-languages.*" <>)
                       ,flags)))
       ((#:phases phases)
        `(modify-phases ,phases
           (add-after 'install 'remove-broken-or-conflicting-files
             (lambda* (#:key outputs #:allow-other-keys)
               (for-each delete-file
                         (find-files (string-append (assoc-ref outputs "out") "/bin")
                                     ".*(c\\+\\+|cpp|g\\+\\+|gcov|gcc.*)"))
               #t))))))))

(define %generic-search-paths
  ;; This is the language-neutral search path for GCC.  Entries in $CPATH are
  ;; not considered "system headers", which means GCC can raise warnings for
  ;; issues in those headers.  'CPATH' is the only one that works for
  ;; front-ends not in the C family.
  (list (search-path-specification
         (variable "CPATH")
         (files '("include")))
        (search-path-specification
         (variable "LIBRARY_PATH")
         (files '("lib" "lib64")))))

(define-public gfortran-4.8
  (custom-gcc gcc-4.8 "gfortran" '("fortran")
              %generic-search-paths))

(define-public gfortran-4.9
  (custom-gcc gcc-4.9 "gfortran" '("fortran")
              %generic-search-paths))

(define-public gfortran-5
  (custom-gcc gcc-5 "gfortran" '("fortran")
              %generic-search-paths))

(define-public gfortran-6
  (custom-gcc gcc-6 "gfortran" '("fortran")
              %generic-search-paths))

(define-public gfortran-7
  (custom-gcc gcc-7 "gfortran" '("fortran")
              %generic-search-paths))

(define-public gfortran
  ;; Note: Update this when GCC changes!  We cannot use
  ;; (custom-gcc gcc "fortran" …) because that would lead to a package object
  ;; that is not 'eq?' with GFORTRAN-5, and thus 'fold-packages' would
  ;; report two gfortran@5 that are in fact identical.
  gfortran-5)

(define-public gccgo-4.9
  (custom-gcc gcc-4.9 "gccgo" '("go")
              %generic-search-paths
              ;; Suppress the separate "lib" output, because otherwise the
              ;; "lib" and "out" outputs would refer to each other, creating
              ;; a cyclic dependency.  <http://debbugs.gnu.org/18101>
              #:separate-lib-output? #f))

(define-public gcc-objc-4.8
  (custom-gcc gcc-4.8 "gcc-objc" '("objc")
              (list (search-path-specification
                     (variable "OBJC_INCLUDE_PATH")
                     (files '("include")))
                    (search-path-specification
                     (variable "LIBRARY_PATH")
                     (files '("lib" "lib64"))))))

(define-public gcc-objc-4.9
  (custom-gcc gcc-4.9 "gcc-objc" '("objc")
              (list (search-path-specification
                     (variable "OBJC_INCLUDE_PATH")
                     (files '("include")))
                    (search-path-specification
                     (variable "LIBRARY_PATH")
                     (files '("lib" "lib64"))))))

(define-public gcc-objc-5
  (custom-gcc gcc-5 "gcc-objc" '("objc")
              (list (search-path-specification
                     (variable "OBJC_INCLUDE_PATH")
                     (files '("include")))
                    (search-path-specification
                     (variable "LIBRARY_PATH")
                     (files '("lib" "lib64"))))))

(define-public gcc-objc-6
  (custom-gcc gcc-6 "gcc-objc" '("objc")
              (list (search-path-specification
                     (variable "OBJC_INCLUDE_PATH")
                     (files '("include")))
                    (search-path-specification
                     (variable "LIBRARY_PATH")
                     (files '("lib" "lib64"))))))

(define-public gcc-objc-7
  (custom-gcc gcc-7 "gcc-objc" '("objc")
              (list (search-path-specification
                     (variable "OBJC_INCLUDE_PATH")
                     (files '("include")))
                    (search-path-specification
                     (variable "LIBRARY_PATH")
                     (files '("lib" "lib64"))))))

(define-public gcc-objc gcc-objc-5)

(define-public gcc-objc++-4.8
  (custom-gcc gcc-4.8 "gcc-objc++" '("obj-c++")
              (list (search-path-specification
                     (variable "OBJCPLUS_INCLUDE_PATH")
                     (files '("include")))
                    (search-path-specification
                     (variable "LIBRARY_PATH")
                     (files '("lib" "lib64"))))))

(define-public gcc-objc++-4.9
  (custom-gcc gcc-4.9 "gcc-objc++" '("obj-c++")
              (list (search-path-specification
                     (variable "OBJCPLUS_INCLUDE_PATH")
                     (files '("include")))
                    (search-path-specification
                     (variable "LIBRARY_PATH")
                     (files '("lib" "lib64"))))))

(define-public gcc-objc++-5
  (custom-gcc gcc-5 "gcc-objc++" '("obj-c++")
              (list (search-path-specification
                     (variable "OBJCPLUS_INCLUDE_PATH")
                     (files '("include")))
                    (search-path-specification
                     (variable "LIBRARY_PATH")
                     (files '("lib" "lib64"))))))

(define-public gcc-objc++-6
  (custom-gcc gcc-6 "gcc-objc++" '("obj-c++")
              (list (search-path-specification
                     (variable "OBJCPLUS_INCLUDE_PATH")
                     (files '("include")))
                    (search-path-specification
                     (variable "LIBRARY_PATH")
                     (files '("lib" "lib64"))))))

(define-public gcc-objc++-7
  (custom-gcc gcc-7 "gcc-objc++" '("obj-c++")
              (list (search-path-specification
                     (variable "OBJCPLUS_INCLUDE_PATH")
                     (files '("include")))
                    (search-path-specification
                     (variable "LIBRARY_PATH")
                     (files '("lib" "lib64"))))))

(define-public gcc-objc++ gcc-objc++-5)

(define (make-libstdc++-doc gcc)
  "Return a package with the libstdc++ documentation for GCC."
  (package
    (inherit gcc)
    (name "libstdc++-doc")
    (version (package-version gcc))
    (synopsis "GNU libstdc++ documentation")
    (outputs '("out"))
    (native-inputs `(("doxygen" ,doxygen)
                     ("texinfo" ,texinfo)
                     ("libxml2" ,libxml2)
                     ("libxslt" ,libxslt)
                     ("docbook-xml" ,docbook-xml)
                     ("docbook-xsl" ,docbook-xsl)
                     ("graphviz" ,graphviz))) ;for 'dot', invoked by 'doxygen'
    (inputs '())
    (propagated-inputs '())
    (arguments
     '(#:out-of-source? #t
       #:tests? #f                                ;it's just documentation
       #:phases (modify-phases %standard-phases
                  (add-before 'configure 'chdir
                              (lambda _
                                (chdir "libstdc++-v3")))
                  (add-before 'configure 'set-xsl-directory
                              (lambda* (#:key inputs #:allow-other-keys)
                                (let ((docbook (assoc-ref inputs "docbook-xsl")))
                                  (substitute* (find-files "doc"
                                                           "^Makefile\\.in$")
                                    (("@XSL_STYLE_DIR@")
                                     (string-append
                                      docbook "/xml/xsl/"
                                      (strip-store-file-name docbook)))))))
                  (replace 'build
                           (lambda _
                             ;; XXX: There's also a 'doc-info' target, but it
                             ;; relies on docbook2X, which itself relies on
                             ;; DocBook 4.1.2, which is not really usable
                             ;; (lacks a catalog.xml.)
                             (zero? (system* "make"
                                             "doc-html"
                                             "doc-man"))))
                  (replace 'install
                           (lambda* (#:key outputs #:allow-other-keys)
                             (let ((out (assoc-ref outputs "out")))
                               (zero? (system* "make"
                                               "doc-install-html"
                                               "doc-install-man"))))))))))

(define-public libstdc++-doc-4.9
  (make-libstdc++-doc gcc-4.9))

(define-public libstdc++-doc-5
  (make-libstdc++-doc gcc-5))

(define-public isl
  (package
    (name "isl")
    (version "0.18")
    (source (origin
             (method url-fetch)
             (uri (list (string-append
                         "http://isl.gforge.inria.fr/isl-"
                         version
                         ".tar.bz2")
                        (string-append %gcc-infrastructure
                                       name "-" version ".tar.gz")))
             (sha256
              (base32
               "06ybml6llhi4i56q90jnimbcgk1lpcdwhy9nxdxra2hxz3bhz2vb"))))
    (build-system gnu-build-system)
    (inputs `(("gmp" ,gmp)))
    (home-page "http://isl.gforge.inria.fr/")
    (synopsis
     "Manipulating sets and relations of integer points \
bounded by linear constraints")
    (description
     "isl is a library for manipulating sets and relations of integer points
bounded by linear constraints.  Supported operations on sets include
intersection, union, set difference, emptiness check, convex hull, (integer)
affine hull, integer projection, computing the lexicographic minimum using
parametric integer programming, coalescing and parametric vertex
enumeration.  It also includes an ILP solver based on generalized basis
reduction, transitive closures on maps (which may encode infinite graphs),
dependence analysis and bounds on piecewise step-polynomials.")
    (license lgpl2.1+)))

(define-public isl-0.11
  (package
    (inherit isl)
    (name "isl")
    (version "0.11.1")
    (source (origin
             (method url-fetch)
             (uri (list (string-append
                         "http://isl.gforge.inria.fr/isl-"
                         version
                         ".tar.bz2")
                        (string-append %gcc-infrastructure
                                       name "-" version ".tar.gz")))
             (sha256
              (base32
               "13d9cqa5rzhbjq0xf0b2dyxag7pqa72xj9dhsa03m8ccr1a4npq9"))
             (patches (search-patches "isl-0.11.1-aarch64-support.patch"))))))

(define-public cloog
  (package
    (name "cloog")
    (version "0.18.0")
    (source
     (origin
      (method url-fetch)
      (uri (list (string-append
                  "http://www.bastoul.net/cloog/pages/download/count.php3?url=cloog-"
                  version
                  ".tar.gz")
                 (string-append %gcc-infrastructure
                                name "-" version ".tar.gz")))
      (sha256
       (base32
        "0a12rwfwp22zd0nlld0xyql11cj390rrq1prw35yjsw8wzfshjhw"))
      (file-name (string-append name "-" version ".tar.gz"))))
    (build-system gnu-build-system)
    (inputs `(("gmp" ,gmp)
              ("isl" ,isl-0.11)))
    (arguments '(#:configure-flags '("--with-isl=system")))
    (home-page "http://www.cloog.org/")
    (synopsis "Library to generate code for scanning Z-polyhedra")
    (description
     "CLooG is a free software library to generate code for scanning
Z-polyhedra.  That is, it finds a code (e.g., in C, FORTRAN...) that
reaches each integral point of one or more parameterized polyhedra.
CLooG has been originally written to solve the code generation problem
for optimizing compilers based on the polytope model.  Nevertheless it
is used now in various area e.g., to build control automata for
high-level synthesis or to find the best polynomial approximation of a
function.  CLooG may help in any situation where scanning polyhedra
matters.  While the user has full control on generated code quality,
CLooG is designed to avoid control overhead and to produce a very
effective code.")
    (license gpl2+)))

(define-public gnu-c-manual
  (package
    (name "gnu-c-manual")
    (version "0.2.5")
    (source (origin
              (method url-fetch)
              (uri (string-append "mirror://gnu/gnu-c-manual/gnu-c-manual-"
                                  version ".tar.gz"))
              (sha256
               (base32
                "1sfsj9256w18qzylgag2h5h377aq8in8929svblfnj9svfriqcys"))))
    (build-system gnu-build-system)
    (native-inputs `(("texinfo" ,texinfo)))
    (arguments
     '(#:phases (modify-phases %standard-phases
                  (delete 'configure)
                  (delete 'check)
                  (replace 'build
                           (lambda _
                             (zero? (system* "make"
                                             "gnu-c-manual.info"
                                             "gnu-c-manual.html"))))
                  (replace 'install
                           (lambda* (#:key outputs #:allow-other-keys)
                             (let* ((out (assoc-ref outputs "out"))
                                    (info (string-append out "/share/info"))
                                    (html (string-append
                                           out "/share/doc/gnu-c-manual")))
                               (mkdir-p info)
                               (mkdir-p html)

                               (for-each (lambda (file)
                                           (copy-file file
                                                      (string-append info "/"
                                                                     file)))
                                         (find-files "." "\\.info(-[0-9])?$"))
                               (for-each (lambda (file)
                                           (copy-file file
                                                      (string-append html "/"
                                                                     file)))
                                         (find-files "." "\\.html$"))
                               #t))))))
    (synopsis "Reference manual for the C programming language")
    (description
     "This is a reference manual for the C programming language, as
implemented by the GNU C Compiler (gcc).  As a reference, it is not intended
to be a tutorial of the language.  Rather, it outlines all of the constructs
of the language.  Library functions are not included.")
    (home-page "https://www.gnu.org/software/gnu-c-manual/")
    (license fdl1.3+)))