1 # Copyright 1999-2020 Gentoo Authors
2 # Distributed under the terms of the GNU General Public License v2
4 # @ECLASS: flag-o-matic.eclass
7 # @BLURB: common functions to manipulate and query toolchain flags
9 # This eclass contains a suite of functions to help developers sanely
10 # and safely manage toolchain flags in their builds.
12 if [[ -z ${_FLAG_O_MATIC_ECLASS} ]]; then
13 _FLAG_O_MATIC_ECLASS=1
15 inherit eutils toolchain-funcs multilib
17 # Return all the flag variables that our high level funcs operate on.
19 echo {ADA,C,CPP,CXX,CCAS,F,FC,LD}FLAGS
22 # {C,CPP,CXX,CCAS,F,FC,LD}FLAGS that we allow in strip-flags
23 # Note: shell globs and character lists are allowed
24 setup-allowed-flags() {
26 -pipe -O '-O[12sg]' -mcpu -march -mtune
27 '-fstack-protector*' '-fsanitize*' '-fstack-check*' -fno-stack-check
28 -fbounds-check -fbounds-checking -fno-strict-overflow
29 -fno-PIE -fno-pie -nopie -no-pie -fno-unit-at-a-time
30 -g '-g[0-9]' -ggdb '-ggdb[0-9]' '-gdwarf-*' gstabs -gstabs+ -gz
31 -fno-ident -fpermissive -frecord-gcc-switches
32 '-fdiagnostics*' '-fplugin*'
35 # CPPFLAGS and LDFLAGS
42 # allow a bunch of flags that negate features / control ABI
44 '-fno-stack-protector*' '-fabi-version=*'
45 -fno-strict-aliasing -fno-bounds-check -fno-bounds-checking -fstrict-overflow
46 -fno-omit-frame-pointer '-fno-builtin*'
49 -mregparm -mno-app-regs -mapp-regs -mno-mmx -mno-sse
50 -mno-sse2 -mno-sse3 -mno-ssse3 -mno-sse4 -mno-sse4.1 -mno-sse4.2
51 -mno-avx -mno-aes -mno-pclmul -mno-sse4a -mno-3dnow -mno-popcnt
52 -mno-abm -mips1 -mips2 -mips3 -mips4 -mips32 -mips64 -mips16 -mplt
53 -msoft-float -mno-soft-float -mhard-float -mno-hard-float -mfpu
54 -mieee -mieee-with-inexact -mschedule -mfloat-gprs -mspe -mno-spe
55 -mtls-direct-seg-refs -mno-tls-direct-seg-refs -mflat -mno-flat
56 -mno-faster-structs -mfaster-structs -m32 -m64 -mx32 -mabi
57 -mlittle-endian -mbig-endian -EL -EB -fPIC -mlive-g0 -mcmodel
58 -mstack-bias -mno-stack-bias -msecure-plt '-m*-toc' -mfloat-abi
59 -mfix-r10000 -mno-fix-r10000 -mthumb -marm
62 -mno-fma4 -mno-movbe -mno-xop -mno-lwp
64 -mno-fsgsbase -mno-rdrnd -mno-f16c -mno-bmi -mno-tbm
66 -mno-avx2 -mno-bmi2 -mno-fma -mno-lzcnt
68 -mno-fxsr -mno-hle -mno-rtm -mno-xsave -mno-xsaveopt
70 -mno-avx512cd -mno-avx512er -mno-avx512f -mno-avx512pf -mno-sha
73 # Allow some safe individual flags. Should come along with the bug reference.
75 # Allow explicit stack realignment to run non-conformant
76 # binaries: bug #677852
81 # inverted filters for hardened compiler. This is trying to unpick
82 # the hardened compiler defaults.
87 # Ideally we should only concern ourselves with PIE flags,
88 # not -fPIC or -fpic, but too many places filter -fPIC without
89 # thinking about -fPIE.
90 -fPIC|-fpic|-fPIE|-fpie|-Wl,pie|-pie)
91 gcc-specs-pie || continue
92 if ! is-flagq -nopie && ! is-flagq -no-pie ; then
93 # Support older Gentoo form first (-nopie) before falling
94 # back to the official gcc-6+ form (-no-pie).
95 if test-flags -nopie >/dev/null ; then
103 gcc-specs-ssp || continue
104 is-flagq -fno-stack-protector || append-flags $(test-flags -fno-stack-protector);;
105 -fstack-protector-all)
106 gcc-specs-ssp-to-all || continue
107 is-flagq -fno-stack-protector-all || append-flags $(test-flags -fno-stack-protector-all);;
108 -fno-strict-overflow)
109 gcc-specs-nostrict || continue
110 is-flagq -fstrict-overflow || append-flags $(test-flags -fstrict-overflow);;
115 # Remove occurrences of strings from variable given in $1
116 # Strings removed are matched as globs, so for example
117 # '-O*' would remove -O1, -O2 etc.
119 local f x var=$1 new=()
122 for f in ${!var} ; do
124 # Note this should work with globs like -O*
125 [[ ${f} == ${x} ]] && continue 2
129 export ${var}="${new[*]}"
132 # @FUNCTION: filter-flags
135 # Remove particular <flags> from {C,CPP,CXX,CCAS,F,FC,LD}FLAGS. Accepts shell globs.
137 _filter-hardened "$@"
139 for v in $(all-flag-vars) ; do
140 _filter-var ${v} "$@"
145 # @FUNCTION: filter-lfs-flags
147 # Remove flags that enable Large File Support.
149 [[ $# -ne 0 ]] && die "filter-lfs-flags takes no arguments"
150 # http://www.gnu.org/s/libc/manual/html_node/Feature-Test-Macros.html
151 # _LARGEFILE_SOURCE: enable support for new LFS funcs (ftello/etc...)
152 # _LARGEFILE64_SOURCE: enable support for 64bit variants (off64_t/fseeko64/etc...)
153 # _FILE_OFFSET_BITS: default to 64bit variants (off_t is defined as off64_t)
154 filter-flags -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE
157 # @FUNCTION: filter-ldflags
160 # Remove particular <flags> from LDFLAGS. Accepts shell globs.
162 _filter-var LDFLAGS "$@"
166 # @FUNCTION: append-cppflags
169 # Add extra <flags> to the current CPPFLAGS.
171 [[ $# -eq 0 ]] && return 0
172 export CPPFLAGS+=" $*"
176 # @FUNCTION: append-cflags
179 # Add extra <flags> to the current CFLAGS. If a flag might not be supported
180 # with different compilers (or versions), then use test-flags-CC like so:
182 # append-cflags $(test-flags-CC -funky-flag)
185 [[ $# -eq 0 ]] && return 0
186 # Do not do automatic flag testing ourselves. #417047
191 # @FUNCTION: append-cxxflags
194 # Add extra <flags> to the current CXXFLAGS. If a flag might not be supported
195 # with different compilers (or versions), then use test-flags-CXX like so:
197 # append-cxxflags $(test-flags-CXX -funky-flag)
200 [[ $# -eq 0 ]] && return 0
201 # Do not do automatic flag testing ourselves. #417047
202 export CXXFLAGS+=" $*"
206 # @FUNCTION: append-fflags
209 # Add extra <flags> to the current {F,FC}FLAGS. If a flag might not be supported
210 # with different compilers (or versions), then use test-flags-F77 like so:
212 # append-fflags $(test-flags-F77 -funky-flag)
215 [[ $# -eq 0 ]] && return 0
216 # Do not do automatic flag testing ourselves. #417047
218 export FCFLAGS+=" $*"
222 # @FUNCTION: append-lfs-flags
224 # Add flags that enable Large File Support.
226 [[ $# -ne 0 ]] && die "append-lfs-flags takes no arguments"
227 # see comments in filter-lfs-flags func for meaning of these
228 append-cppflags -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE
231 # @FUNCTION: append-ldflags
234 # Add extra <flags> to the current LDFLAGS.
236 [[ $# -eq 0 ]] && return 0
239 [[ ${flag} == -l* ]] && \
240 eqawarn "Appending a library link instruction (${flag}); libraries to link to should not be passed through LDFLAGS"
243 export LDFLAGS="${LDFLAGS} $*"
247 # @FUNCTION: append-flags
250 # Add extra <flags> to your current {C,CXX,F,FC}FLAGS.
252 [[ $# -eq 0 ]] && return 0
254 *' '-[DIU]*) eqawarn 'please use append-cppflags for preprocessor flags' ;;
256 *' '-Wl,*) eqawarn 'please use append-ldflags for linker flags' ;;
264 # @FUNCTION: replace-flags
265 # @USAGE: <old> <new>
267 # Replace the <old> flag with <new>. Accepts shell globs for <old>.
269 [[ $# != 2 ]] && die "Usage: replace-flags <old flag> <new flag>"
272 for var in $(all-flag-vars) ; do
273 # Looping over the flags instead of using a global
274 # substitution ensures that we're working with flag atoms.
275 # Otherwise globs like -O* have the potential to wipe out the
278 for f in ${!var} ; do
279 # Note this should work with globs like -O*
280 [[ ${f} == ${1} ]] && f=${2}
283 export ${var}="${new[*]}"
289 # @FUNCTION: replace-cpu-flags
290 # @USAGE: <old> <new>
292 # Replace cpu flags (like -march/-mcpu/-mtune) that select the <old> cpu
293 # with flags that select the <new> cpu. Accepts shell globs for <old>.
294 replace-cpu-flags() {
295 local newcpu="$#" ; newcpu="${!newcpu}"
296 while [ $# -gt 1 ] ; do
297 # quote to make sure that no globbing is done (particularly on
298 # ${oldcpu}) prior to calling replace-flags
299 replace-flags "-march=${1}" "-march=${newcpu}"
300 replace-flags "-mcpu=${1}" "-mcpu=${newcpu}"
301 replace-flags "-mtune=${1}" "-mtune=${newcpu}"
309 for x in ${!var} ; do
310 [[ ${x} == $2 ]] && return 0
315 # @FUNCTION: is-flagq
318 # Returns shell true if <flag> is in {C,CXX,F,FC}FLAGS, else returns shell false. Accepts shell globs.
320 [[ -n $2 ]] && die "Usage: is-flag <flag>"
323 for var in $(all-flag-vars) ; do
324 _is_flagq ${var} "$1" && return 0
332 # Echo's "true" if flag is set in {C,CXX,F,FC}FLAGS. Accepts shell globs.
334 is-flagq "$@" && echo true
337 # @FUNCTION: is-ldflagq
340 # Returns shell true if <flag> is in LDFLAGS, else returns shell false. Accepts shell globs.
342 [[ -n $2 ]] && die "Usage: is-ldflag <flag>"
346 # @FUNCTION: is-ldflag
349 # Echo's "true" if flag is set in LDFLAGS. Accepts shell globs.
351 is-ldflagq "$@" && echo true
354 # @FUNCTION: filter-mfpmath
355 # @USAGE: <math types>
357 # Remove specified math types from the fpmath flag. For example, if the user
358 # has -mfpmath=sse,386, running `filter-mfpmath sse` will leave the user with
361 local orig_mfpmath new_math prune_math
363 # save the original -mfpmath flag
364 orig_mfpmath=$(get-flag -mfpmath)
365 # get the value of the current -mfpmath flag
366 new_math=$(get-flag mfpmath)
367 # convert "both" to something we can filter
368 new_math=${new_math/both/387,sse}
369 new_math=" ${new_math//[,+]/ } "
370 # figure out which math values are to be removed
372 for prune_math in "$@" ; do
373 new_math=${new_math/ ${prune_math} / }
375 new_math=$(echo ${new_math})
376 new_math=${new_math// /,}
378 if [[ -z ${new_math} ]] ; then
379 # if we're removing all user specified math values are
380 # slated for removal, then we just filter the flag
381 filter-flags ${orig_mfpmath}
383 # if we only want to filter some of the user specified
384 # math values, then we replace the current flag
385 replace-flags ${orig_mfpmath} -mfpmath=${new_math}
390 # @FUNCTION: strip-flags
392 # Strip *FLAGS of everything except known good/safe flags. This runs over all
393 # flags returned by all_flag_vars().
395 [[ $# -ne 0 ]] && die "strip-flags takes no arguments"
401 set -f # disable pathname expansion
403 for var in $(all-flag-vars) ; do
406 for x in ${!var} ; do
408 for y in "${ALLOWED_FLAGS[@]}" ; do
409 if [[ -z ${flag%%${y}} ]] ; then
416 # In case we filtered out all optimization flags fallback to -O2
417 if _is_flagq ${var} "-O*" && ! _is_flagq new "-O*" ; then
421 if [[ ${!var} != "${new[*]}" ]] ; then
422 einfo "strip-flags: ${var}: changed '${!var}' to '${new[*]}'"
424 export ${var}="${new[*]}"
427 set +f # re-enable pathname expansion
437 if [[ -z ${comp} ]]; then
444 # verify selected compiler exists before using it
445 comp=($(tc-get${comp}))
446 # 'comp' can already contain compiler options.
447 # 'type' needs a binary name
448 if ! type -p ${comp[0]} >/dev/null; then
453 local in_src in_ext cmdline_extra=()
455 # compiler/assembler only
458 in_src='int main(void) { return 0; }'
459 cmdline_extra+=(-xc -c)
463 in_src='int main(void) { return 0; }'
464 cmdline_extra+=(-xc++ -c)
470 cmdline_extra+=(-xf77 -c)
475 cmdline_extra+=(-xf95 -c)
478 # C compiler/assembler/linker
481 in_src='int main(void) { return 0; }'
485 local test_in=${T}/test-flag.${in_ext}
486 local test_out=${T}/test-flag.exe
488 printf "%s\n" "${in_src}" > "${test_in}" || die "Failed to create '${test_in}'"
492 # Clang will warn about unknown gcc flags but exit 0.
493 # Need -Werror to force it to exit non-zero.
496 # -x<lang> options need to go before first source file
497 "${cmdline_extra[@]}"
499 "${test_in}" -o "${test_out}"
502 if ! "${cmdline[@]}" &>/dev/null; then
503 # -Werror makes clang bail out on unused arguments as well;
504 # try to add -Qunused-arguments to work-around that
505 # other compilers don't support it but then, it's failure like
507 cmdline+=( -Qunused-arguments )
508 "${cmdline[@]}" &>/dev/null
512 # @FUNCTION: test-flag-CC
515 # Returns shell true if <flag> is supported by the C compiler, else returns shell false.
516 test-flag-CC() { test-flag-PROG "CC" c "$@"; }
518 # @FUNCTION: test-flag-CXX
521 # Returns shell true if <flag> is supported by the C++ compiler, else returns shell false.
522 test-flag-CXX() { test-flag-PROG "CXX" c++ "$@"; }
524 # @FUNCTION: test-flag-F77
527 # Returns shell true if <flag> is supported by the Fortran 77 compiler, else returns shell false.
528 test-flag-F77() { test-flag-PROG "F77" f77 "$@"; }
530 # @FUNCTION: test-flag-FC
533 # Returns shell true if <flag> is supported by the Fortran 90 compiler, else returns shell false.
534 test-flag-FC() { test-flag-PROG "FC" f95 "$@"; }
536 # @FUNCTION: test-flag-CCLD
539 # Returns shell true if <flag> is supported by the C compiler and linker, else returns shell false.
540 test-flag-CCLD() { test-flag-PROG "CC" c+ld "$@"; }
549 [[ -z ${comp} ]] && return 1
553 # '-B /foo': bug # 687198
555 if test-flag-${comp} "$1" "$2"; then
561 if test-flag-${comp} "$1"; then
571 # Just bail if we dont have any flags
572 [[ ${#flags[@]} -gt 0 ]]
575 # @FUNCTION: test-flags-CC
578 # Returns shell true if <flags> are supported by the C compiler, else returns shell false.
579 test-flags-CC() { test-flags-PROG "CC" "$@"; }
581 # @FUNCTION: test-flags-CXX
584 # Returns shell true if <flags> are supported by the C++ compiler, else returns shell false.
585 test-flags-CXX() { test-flags-PROG "CXX" "$@"; }
587 # @FUNCTION: test-flags-F77
590 # Returns shell true if <flags> are supported by the Fortran 77 compiler, else returns shell false.
591 test-flags-F77() { test-flags-PROG "F77" "$@"; }
593 # @FUNCTION: test-flags-FC
596 # Returns shell true if <flags> are supported by the Fortran 90 compiler, else returns shell false.
597 test-flags-FC() { test-flags-PROG "FC" "$@"; }
599 # @FUNCTION: test-flags-CCLD
602 # Returns shell true if <flags> are supported by the C compiler and default linker, else returns shell false.
603 test-flags-CCLD() { test-flags-PROG "CCLD" "$@"; }
605 # @FUNCTION: test-flags
608 # Short-hand that should hopefully work for both C and C++ compiler, but
609 # its really only present due to the append-flags() abomination.
610 test-flags() { test-flags-CC "$@"; }
612 # @FUNCTION: test_version_info
615 # Returns shell true if the current C compiler version matches <version>, else returns shell false.
616 # Accepts shell globs.
617 test_version_info() {
618 if [[ $($(tc-getCC) --version 2>&1) == *$1* ]]; then
625 # @FUNCTION: strip-unsupported-flags
627 # Strip {C,CXX,F,FC}FLAGS of any flags not supported by the active toolchain.
628 strip-unsupported-flags() {
629 [[ $# -ne 0 ]] && die "strip-unsupported-flags takes no arguments"
630 export CFLAGS=$(test-flags-CC ${CFLAGS})
631 export CXXFLAGS=$(test-flags-CXX ${CXXFLAGS})
632 export FFLAGS=$(test-flags-F77 ${FFLAGS})
633 export FCFLAGS=$(test-flags-FC ${FCFLAGS})
634 export LDFLAGS=$(test-flags-CCLD ${LDFLAGS})
637 # @FUNCTION: get-flag
640 # Find and echo the value for a particular flag. Accepts shell globs.
642 [[ $# -ne 1 ]] && die "usage: <flag>"
643 local f var findflag="$1"
645 # this code looks a little flaky but seems to work for
646 # everything we want ...
647 # for example, if CFLAGS="-march=i686":
648 # `get-flag -march` == "-march=i686"
649 # `get-flag march` == "i686"
650 for var in $(all-flag-vars) ; do
651 for f in ${!var} ; do
652 if [ "${f/${findflag}}" != "${f}" ] ; then
653 printf "%s\n" "${f/-${findflag}=}"
661 # @FUNCTION: replace-sparc64-flags
663 # Sets mcpu to v8 and uses the original value as mtune if none specified.
664 replace-sparc64-flags() {
665 [[ $# -ne 0 ]] && die "replace-sparc64-flags takes no arguments"
666 local SPARC64_CPUS="ultrasparc3 ultrasparc v9"
668 if [ "${CFLAGS/mtune}" != "${CFLAGS}" ]; then
669 for x in ${SPARC64_CPUS}; do
670 CFLAGS="${CFLAGS/-mcpu=${x}/-mcpu=v8}"
673 for x in ${SPARC64_CPUS}; do
674 CFLAGS="${CFLAGS/-mcpu=${x}/-mcpu=v8 -mtune=${x}}"
678 if [ "${CXXFLAGS/mtune}" != "${CXXFLAGS}" ]; then
679 for x in ${SPARC64_CPUS}; do
680 CXXFLAGS="${CXXFLAGS/-mcpu=${x}/-mcpu=v8}"
683 for x in ${SPARC64_CPUS}; do
684 CXXFLAGS="${CXXFLAGS/-mcpu=${x}/-mcpu=v8 -mtune=${x}}"
688 export CFLAGS CXXFLAGS
691 # @FUNCTION: append-libs
694 # Add extra <libs> to the current LIBS. All arguments should be prefixed with
695 # either -l or -L. For compatibility, if arguments are not prefixed as
696 # options, they are given a -l prefix automatically.
698 [[ $# -eq 0 ]] && return 0
701 if [[ -z "${flag// }" ]]; then
702 eqawarn "Appending an empty argument to LIBS is invalid! Skipping."
707 export LIBS="${LIBS} ${flag}"
710 eqawarn "Appending non-library to LIBS (${flag}); Other linker flags should be passed via LDFLAGS"
711 export LIBS="${LIBS} ${flag}"
714 export LIBS="${LIBS} -l${flag}"
721 # @FUNCTION: raw-ldflags
724 # Turn C style ldflags (-Wl,-foo) into straight ldflags - the results
725 # are suitable for passing directly to 'ld'; note LDFLAGS is usually passed
726 # to gcc where it needs the '-Wl,'.
728 # If no flags are specified, then default to ${LDFLAGS}.
731 [[ -z ${input} ]] && input=${LDFLAGS}
733 for x in ${input} ; do
737 set -- "$@" ${x//,/ }
739 *) # Assume it's a compiler driver flag, so throw it away #441808
746 # @FUNCTION: no-as-needed
747 # @RETURN: Flag to disable asneeded behavior for use with append-ldflags.
749 [[ $# -ne 0 ]] && die "no-as-needed takes no arguments"
750 case $($(tc-getLD) -v 2>&1 </dev/null) in
752 echo "-Wl,--no-as-needed" ;;