net-libs/gnutls: libressl fix
[gentoo.git] / eclass / toolchain-funcs.eclass
1 # Copyright 1999-2018 Gentoo Foundation
2 # Distributed under the terms of the GNU General Public License v2
3
4 # @ECLASS: toolchain-funcs.eclass
5 # @MAINTAINER:
6 # Toolchain Ninjas <toolchain@gentoo.org>
7 # @BLURB: functions to query common info about the toolchain
8 # @DESCRIPTION:
9 # The toolchain-funcs aims to provide a complete suite of functions
10 # for gleaning useful information about the toolchain and to simplify
11 # ugly things like cross-compiling and multilib.  All of this is done
12 # in such a way that you can rely on the function always returning
13 # something sane.
14
15 if [[ -z ${_TOOLCHAIN_FUNCS_ECLASS} ]]; then
16 _TOOLCHAIN_FUNCS_ECLASS=1
17
18 inherit multilib
19
20 # tc-getPROG <VAR [search vars]> <default> [tuple]
21 _tc-getPROG() {
22         local tuple=$1
23         local v var vars=$2
24         local prog=( $3 )
25
26         var=${vars%% *}
27         for v in ${vars} ; do
28                 if [[ -n ${!v} ]] ; then
29                         export ${var}="${!v}"
30                         echo "${!v}"
31                         return 0
32                 fi
33         done
34
35         local search=
36         [[ -n $4 ]] && search=$(type -p $4-${prog[0]})
37         [[ -z ${search} && -n ${!tuple} ]] && search=$(type -p ${!tuple}-${prog[0]})
38         [[ -n ${search} ]] && prog[0]=${search##*/}
39
40         export ${var}="${prog[*]}"
41         echo "${!var}"
42 }
43 tc-getBUILD_PROG() {
44         local vars="BUILD_$1 $1_FOR_BUILD HOST$1"
45         # respect host vars if not cross-compiling
46         # https://bugs.gentoo.org/630282
47         tc-is-cross-compiler || vars+=" $1"
48         _tc-getPROG CBUILD "${vars}" "${@:2}"
49 }
50 tc-getPROG() { _tc-getPROG CHOST "$@"; }
51
52 # @FUNCTION: tc-getAR
53 # @USAGE: [toolchain prefix]
54 # @RETURN: name of the archiver
55 tc-getAR() { tc-getPROG AR ar "$@"; }
56 # @FUNCTION: tc-getAS
57 # @USAGE: [toolchain prefix]
58 # @RETURN: name of the assembler
59 tc-getAS() { tc-getPROG AS as "$@"; }
60 # @FUNCTION: tc-getCC
61 # @USAGE: [toolchain prefix]
62 # @RETURN: name of the C compiler
63 tc-getCC() { tc-getPROG CC gcc "$@"; }
64 # @FUNCTION: tc-getCPP
65 # @USAGE: [toolchain prefix]
66 # @RETURN: name of the C preprocessor
67 tc-getCPP() { tc-getPROG CPP "${CC:-gcc} -E" "$@"; }
68 # @FUNCTION: tc-getCXX
69 # @USAGE: [toolchain prefix]
70 # @RETURN: name of the C++ compiler
71 tc-getCXX() { tc-getPROG CXX g++ "$@"; }
72 # @FUNCTION: tc-getLD
73 # @USAGE: [toolchain prefix]
74 # @RETURN: name of the linker
75 tc-getLD() { tc-getPROG LD ld "$@"; }
76 # @FUNCTION: tc-getSTRIP
77 # @USAGE: [toolchain prefix]
78 # @RETURN: name of the strip program
79 tc-getSTRIP() { tc-getPROG STRIP strip "$@"; }
80 # @FUNCTION: tc-getNM
81 # @USAGE: [toolchain prefix]
82 # @RETURN: name of the symbol/object thingy
83 tc-getNM() { tc-getPROG NM nm "$@"; }
84 # @FUNCTION: tc-getRANLIB
85 # @USAGE: [toolchain prefix]
86 # @RETURN: name of the archiver indexer
87 tc-getRANLIB() { tc-getPROG RANLIB ranlib "$@"; }
88 # @FUNCTION: tc-getOBJCOPY
89 # @USAGE: [toolchain prefix]
90 # @RETURN: name of the object copier
91 tc-getOBJCOPY() { tc-getPROG OBJCOPY objcopy "$@"; }
92 # @FUNCTION: tc-getOBJDUMP
93 # @USAGE: [toolchain prefix]
94 # @RETURN: name of the object dumper
95 tc-getOBJDUMP() { tc-getPROG OBJDUMP objdump "$@"; }
96 # @FUNCTION: tc-getF77
97 # @USAGE: [toolchain prefix]
98 # @RETURN: name of the Fortran 77 compiler
99 tc-getF77() { tc-getPROG F77 gfortran "$@"; }
100 # @FUNCTION: tc-getFC
101 # @USAGE: [toolchain prefix]
102 # @RETURN: name of the Fortran 90 compiler
103 tc-getFC() { tc-getPROG FC gfortran "$@"; }
104 # @FUNCTION: tc-getGCJ
105 # @USAGE: [toolchain prefix]
106 # @RETURN: name of the java compiler
107 tc-getGCJ() { tc-getPROG GCJ gcj "$@"; }
108 # @FUNCTION: tc-getGO
109 # @USAGE: [toolchain prefix]
110 # @RETURN: name of the Go compiler
111 tc-getGO() { tc-getPROG GO gccgo "$@"; }
112 # @FUNCTION: tc-getPKG_CONFIG
113 # @USAGE: [toolchain prefix]
114 # @RETURN: name of the pkg-config tool
115 tc-getPKG_CONFIG() { tc-getPROG PKG_CONFIG pkg-config "$@"; }
116 # @FUNCTION: tc-getRC
117 # @USAGE: [toolchain prefix]
118 # @RETURN: name of the Windows resource compiler
119 tc-getRC() { tc-getPROG RC windres "$@"; }
120 # @FUNCTION: tc-getDLLWRAP
121 # @USAGE: [toolchain prefix]
122 # @RETURN: name of the Windows dllwrap utility
123 tc-getDLLWRAP() { tc-getPROG DLLWRAP dllwrap "$@"; }
124
125 # @FUNCTION: tc-getBUILD_AR
126 # @USAGE: [toolchain prefix]
127 # @RETURN: name of the archiver for building binaries to run on the build machine
128 tc-getBUILD_AR() { tc-getBUILD_PROG AR ar "$@"; }
129 # @FUNCTION: tc-getBUILD_AS
130 # @USAGE: [toolchain prefix]
131 # @RETURN: name of the assembler for building binaries to run on the build machine
132 tc-getBUILD_AS() { tc-getBUILD_PROG AS as "$@"; }
133 # @FUNCTION: tc-getBUILD_CC
134 # @USAGE: [toolchain prefix]
135 # @RETURN: name of the C compiler for building binaries to run on the build machine
136 tc-getBUILD_CC() { tc-getBUILD_PROG CC gcc "$@"; }
137 # @FUNCTION: tc-getBUILD_CPP
138 # @USAGE: [toolchain prefix]
139 # @RETURN: name of the C preprocessor for building binaries to run on the build machine
140 tc-getBUILD_CPP() { tc-getBUILD_PROG CPP "$(tc-getBUILD_CC) -E" "$@"; }
141 # @FUNCTION: tc-getBUILD_CXX
142 # @USAGE: [toolchain prefix]
143 # @RETURN: name of the C++ compiler for building binaries to run on the build machine
144 tc-getBUILD_CXX() { tc-getBUILD_PROG CXX g++ "$@"; }
145 # @FUNCTION: tc-getBUILD_LD
146 # @USAGE: [toolchain prefix]
147 # @RETURN: name of the linker for building binaries to run on the build machine
148 tc-getBUILD_LD() { tc-getBUILD_PROG LD ld "$@"; }
149 # @FUNCTION: tc-getBUILD_STRIP
150 # @USAGE: [toolchain prefix]
151 # @RETURN: name of the strip program for building binaries to run on the build machine
152 tc-getBUILD_STRIP() { tc-getBUILD_PROG STRIP strip "$@"; }
153 # @FUNCTION: tc-getBUILD_NM
154 # @USAGE: [toolchain prefix]
155 # @RETURN: name of the symbol/object thingy for building binaries to run on the build machine
156 tc-getBUILD_NM() { tc-getBUILD_PROG NM nm "$@"; }
157 # @FUNCTION: tc-getBUILD_RANLIB
158 # @USAGE: [toolchain prefix]
159 # @RETURN: name of the archiver indexer for building binaries to run on the build machine
160 tc-getBUILD_RANLIB() { tc-getBUILD_PROG RANLIB ranlib "$@"; }
161 # @FUNCTION: tc-getBUILD_OBJCOPY
162 # @USAGE: [toolchain prefix]
163 # @RETURN: name of the object copier for building binaries to run on the build machine
164 tc-getBUILD_OBJCOPY() { tc-getBUILD_PROG OBJCOPY objcopy "$@"; }
165 # @FUNCTION: tc-getBUILD_PKG_CONFIG
166 # @USAGE: [toolchain prefix]
167 # @RETURN: name of the pkg-config tool for building binaries to run on the build machine
168 tc-getBUILD_PKG_CONFIG() { tc-getBUILD_PROG PKG_CONFIG pkg-config "$@"; }
169
170 # @FUNCTION: tc-getTARGET_CPP
171 # @USAGE: [toolchain prefix]
172 # @RETURN: name of the C preprocessor for the toolchain being built (or used)
173 tc-getTARGET_CPP() {
174         if [[ -n ${CTARGET} ]]; then
175                 _tc-getPROG CTARGET TARGET_CPP "gcc -E" "$@"
176         else
177                 tc-getCPP "$@"
178         fi
179 }
180
181 # @FUNCTION: tc-export
182 # @USAGE: <list of toolchain variables>
183 # @DESCRIPTION:
184 # Quick way to export a bunch of compiler vars at once.
185 tc-export() {
186         local var
187         for var in "$@" ; do
188                 [[ $(type -t "tc-get${var}") != "function" ]] && die "tc-export: invalid export variable '${var}'"
189                 "tc-get${var}" > /dev/null
190         done
191 }
192
193 # @FUNCTION: tc-is-cross-compiler
194 # @RETURN: Shell true if we are using a cross-compiler, shell false otherwise
195 tc-is-cross-compiler() {
196         [[ ${CBUILD:-${CHOST}} != ${CHOST} ]]
197 }
198
199 # @FUNCTION: tc-cpp-is-true
200 # @USAGE: <condition> [cpp flags]
201 # @RETURN: Shell true if the condition is true, shell false otherwise.
202 # @DESCRIPTION:
203 # Evaluate the given condition using the C preprocessor for CTARGET, if
204 # defined, or CHOST. Additional arguments are passed through to the cpp
205 # command. A typical condition would be in the form defined(__FOO__).
206 tc-cpp-is-true() {
207         local CONDITION=${1}
208         shift
209
210         local RESULT=$($(tc-getTARGET_CPP) "${@}" -P - <<-EOF 2>/dev/null
211                         #if ${CONDITION}
212                         true
213                         #endif
214                 EOF
215         )
216
217         [[ ${RESULT} == true ]]
218 }
219
220 # @FUNCTION: tc-detect-is-softfloat
221 # @RETURN:
222 # Shell true if (positive or negative) detection was possible, shell
223 # false otherwise. Also outputs a string when detection succeeds, see
224 # tc-is-softfloat for the possible values.
225 # @DESCRIPTION:
226 # Detect whether the CTARGET (or CHOST) toolchain is a softfloat based
227 # one by examining the toolchain's output, if possible.
228 tc-detect-is-softfloat() {
229         # If fetching CPP falls back to the default (gcc -E) then fail
230         # detection as this may not be the correct toolchain.
231         [[ $(tc-getTARGET_CPP) == "gcc -E" ]] && return 1
232
233         case ${CTARGET:-${CHOST}} in
234                 # Avoid autodetection for bare-metal targets. bug #666896
235                 *-newlib|*-elf|*-eabi)
236                         return 1 ;;
237
238                 # arm-unknown-linux-gnueabi is ambiguous. We used to treat it as
239                 # hardfloat but we now treat it as softfloat like most everyone
240                 # else. Check existing toolchains to respect existing systems.
241                 arm*)
242                         if tc-cpp-is-true "defined(__ARM_PCS_VFP)"; then
243                                 echo "no"
244                         else
245                                 # Confusingly __SOFTFP__ is defined only when
246                                 # -mfloat-abi is soft, not softfp.
247                                 if tc-cpp-is-true "defined(__SOFTFP__)"; then
248                                         echo "yes"
249                                 else
250                                         echo "softfp"
251                                 fi
252                         fi
253
254                         return 0 ;;
255                 *)
256                         return 1 ;;
257         esac
258 }
259
260 # @FUNCTION: tc-tuple-is-softfloat
261 # @RETURN: See tc-is-softfloat for the possible values.
262 # @DESCRIPTION:
263 # Determine whether the CTARGET (or CHOST) toolchain is a softfloat
264 # based one solely from the tuple.
265 tc-tuple-is-softfloat() {
266         local CTARGET=${CTARGET:-${CHOST}}
267         case ${CTARGET//_/-} in
268                 bfin*|h8300*)
269                         echo "only" ;;
270                 *-softfloat-*)
271                         echo "yes" ;;
272                 *-softfp-*)
273                         echo "softfp" ;;
274                 arm*-hardfloat-*|arm*eabihf)
275                         echo "no" ;;
276                 # bare-metal targets have their defaults. bug #666896
277                 *-newlib|*-elf|*-eabi)
278                         echo "no" ;;
279                 arm*)
280                         echo "yes" ;;
281                 *)
282                         echo "no" ;;
283         esac
284 }
285
286 # @FUNCTION: tc-is-softfloat
287 # @DESCRIPTION:
288 # See if this toolchain is a softfloat based one.
289 # @CODE
290 # The possible return values:
291 #  - only:   the target is always softfloat (never had fpu)
292 #  - yes:    the target should support softfloat
293 #  - softfp: (arm specific) the target should use hardfloat insns, but softfloat calling convention
294 #  - no:     the target doesn't support softfloat
295 # @CODE
296 # This allows us to react differently where packages accept
297 # softfloat flags in the case where support is optional, but
298 # rejects softfloat flags where the target always lacks an fpu.
299 tc-is-softfloat() {
300         tc-detect-is-softfloat || tc-tuple-is-softfloat
301 }
302
303 # @FUNCTION: tc-is-static-only
304 # @DESCRIPTION:
305 # Return shell true if the target does not support shared libs, shell false
306 # otherwise.
307 tc-is-static-only() {
308         local host=${CTARGET:-${CHOST}}
309
310         # *MiNT doesn't have shared libraries, only platform so far
311         [[ ${host} == *-mint* ]]
312 }
313
314 # @FUNCTION: tc-stack-grows-down
315 # @DESCRIPTION:
316 # Return shell true if the stack grows down.  This is the default behavior
317 # for the vast majority of systems out there and usually projects shouldn't
318 # care about such internal details.
319 tc-stack-grows-down() {
320         # List the few that grow up.
321         case ${ARCH} in
322         hppa|metag) return 1 ;;
323         esac
324
325         # Assume all others grow down.
326         return 0
327 }
328
329 # @FUNCTION: tc-export_build_env
330 # @USAGE: [compiler variables]
331 # @DESCRIPTION:
332 # Export common build related compiler settings.
333 tc-export_build_env() {
334         tc-export "$@"
335         if tc-is-cross-compiler; then
336                 # Some build envs will initialize vars like:
337                 # : ${BUILD_LDFLAGS:-${LDFLAGS}}
338                 # So make sure all variables are non-empty. #526734
339                 : ${BUILD_CFLAGS:=-O1 -pipe}
340                 : ${BUILD_CXXFLAGS:=-O1 -pipe}
341                 : ${BUILD_CPPFLAGS:= }
342                 : ${BUILD_LDFLAGS:= }
343         else
344                 # https://bugs.gentoo.org/654424
345                 : ${BUILD_CFLAGS:=${CFLAGS}}
346                 : ${BUILD_CXXFLAGS:=${CXXFLAGS}}
347                 : ${BUILD_CPPFLAGS:=${CPPFLAGS}}
348                 : ${BUILD_LDFLAGS:=${LDFLAGS}}
349         fi
350         export BUILD_{C,CXX,CPP,LD}FLAGS
351
352         # Some packages use XXX_FOR_BUILD.
353         local v
354         for v in BUILD_{C,CXX,CPP,LD}FLAGS ; do
355                 export ${v#BUILD_}_FOR_BUILD="${!v}"
356         done
357 }
358
359 # @FUNCTION: tc-env_build
360 # @USAGE: <command> [command args]
361 # @INTERNAL
362 # @DESCRIPTION:
363 # Setup the compile environment to the build tools and then execute the
364 # specified command.  We use tc-getBUILD_XX here so that we work with
365 # all of the semi-[non-]standard env vars like $BUILD_CC which often
366 # the target build system does not check.
367 tc-env_build() {
368         tc-export_build_env
369         CFLAGS=${BUILD_CFLAGS} \
370         CXXFLAGS=${BUILD_CXXFLAGS} \
371         CPPFLAGS=${BUILD_CPPFLAGS} \
372         LDFLAGS=${BUILD_LDFLAGS} \
373         AR=$(tc-getBUILD_AR) \
374         AS=$(tc-getBUILD_AS) \
375         CC=$(tc-getBUILD_CC) \
376         CPP=$(tc-getBUILD_CPP) \
377         CXX=$(tc-getBUILD_CXX) \
378         LD=$(tc-getBUILD_LD) \
379         NM=$(tc-getBUILD_NM) \
380         PKG_CONFIG=$(tc-getBUILD_PKG_CONFIG) \
381         RANLIB=$(tc-getBUILD_RANLIB) \
382         "$@"
383 }
384
385 # @FUNCTION: econf_build
386 # @USAGE: [econf flags]
387 # @DESCRIPTION:
388 # Sometimes we need to locally build up some tools to run on CBUILD because
389 # the package has helper utils which are compiled+executed when compiling.
390 # This won't work when cross-compiling as the CHOST is set to a target which
391 # we cannot natively execute.
392 #
393 # For example, the python package will build up a local python binary using
394 # a portable build system (configure+make), but then use that binary to run
395 # local python scripts to build up other components of the overall python.
396 # We cannot rely on the python binary in $PATH as that often times will be
397 # a different version, or not even installed in the first place.  Instead,
398 # we compile the code in a different directory to run on CBUILD, and then
399 # use that binary when compiling the main package to run on CHOST.
400 #
401 # For example, with newer EAPIs, you'd do something like:
402 # @CODE
403 # src_configure() {
404 #       ECONF_SOURCE=${S}
405 #       if tc-is-cross-compiler ; then
406 #               mkdir "${WORKDIR}"/${CBUILD}
407 #               pushd "${WORKDIR}"/${CBUILD} >/dev/null
408 #               econf_build --disable-some-unused-stuff
409 #               popd >/dev/null
410 #       fi
411 #       ... normal build paths ...
412 # }
413 # src_compile() {
414 #       if tc-is-cross-compiler ; then
415 #               pushd "${WORKDIR}"/${CBUILD} >/dev/null
416 #               emake one-or-two-build-tools
417 #               ln/mv build-tools to normal build paths in ${S}/
418 #               popd >/dev/null
419 #       fi
420 #       ... normal build paths ...
421 # }
422 # @CODE
423 econf_build() {
424         local CBUILD=${CBUILD:-${CHOST}}
425         tc-env_build econf --build=${CBUILD} --host=${CBUILD} "$@"
426 }
427
428 # @FUNCTION: tc-ld-is-gold
429 # @USAGE: [toolchain prefix]
430 # @DESCRIPTION:
431 # Return true if the current linker is set to gold.
432 tc-ld-is-gold() {
433         local out
434
435         # First check the linker directly.
436         out=$($(tc-getLD "$@") --version 2>&1)
437         if [[ ${out} == *"GNU gold"* ]] ; then
438                 return 0
439         fi
440
441         # Then see if they're selecting gold via compiler flags.
442         # Note: We're assuming they're using LDFLAGS to hold the
443         # options and not CFLAGS/CXXFLAGS.
444         local base="${T}/test-tc-gold"
445         cat <<-EOF > "${base}.c"
446         int main() { return 0; }
447         EOF
448         out=$($(tc-getCC "$@") ${CFLAGS} ${CPPFLAGS} ${LDFLAGS} -Wl,--version "${base}.c" -o "${base}" 2>&1)
449         rm -f "${base}"*
450         if [[ ${out} == *"GNU gold"* ]] ; then
451                 return 0
452         fi
453
454         # No gold here!
455         return 1
456 }
457
458 # @FUNCTION: tc-ld-disable-gold
459 # @USAGE: [toolchain prefix]
460 # @DESCRIPTION:
461 # If the gold linker is currently selected, configure the compilation
462 # settings so that we use the older bfd linker instead.
463 tc-ld-disable-gold() {
464         if ! tc-ld-is-gold "$@" ; then
465                 # They aren't using gold, so nothing to do!
466                 return
467         fi
468
469         ewarn "Forcing usage of the BFD linker instead of GOLD"
470
471         # Set up LD to point directly to bfd if it's available.
472         # We need to extract the first word in case there are flags appended
473         # to its value (like multilib).  #545218
474         local ld=$(tc-getLD "$@")
475         local bfd_ld="${ld%% *}.bfd"
476         local path_ld=$(which "${bfd_ld}" 2>/dev/null)
477         [[ -e ${path_ld} ]] && export LD=${bfd_ld}
478
479         # Set up LDFLAGS to select gold based on the gcc / clang version.
480         local fallback="true"
481         if tc-is-gcc; then
482                 local major=$(gcc-major-version "$@")
483                 local minor=$(gcc-minor-version "$@")
484                 if [[ ${major} -gt 4 ]] || [[ ${major} -eq 4 && ${minor} -ge 8 ]]; then
485                         # gcc-4.8+ supports -fuse-ld directly.
486                         export LDFLAGS="${LDFLAGS} -fuse-ld=bfd"
487                         fallback="false"
488                 fi
489         elif tc-is-clang; then
490                 local major=$(clang-major-version "$@")
491                 local minor=$(clang-minor-version "$@")
492                 if [[ ${major} -gt 3 ]] || [[ ${major} -eq 3 && ${minor} -ge 5 ]]; then
493                         # clang-3.5+ supports -fuse-ld directly.
494                         export LDFLAGS="${LDFLAGS} -fuse-ld=bfd"
495                         fallback="false"
496                 fi
497         fi
498         if [[ ${fallback} == "true" ]] ; then
499                 # <=gcc-4.7 and <=clang-3.4 require some coercion.
500                 # Only works if bfd exists.
501                 if [[ -e ${path_ld} ]] ; then
502                         local d="${T}/bfd-linker"
503                         mkdir -p "${d}"
504                         ln -sf "${path_ld}" "${d}"/ld
505                         export LDFLAGS="${LDFLAGS} -B${d}"
506                 else
507                         die "unable to locate a BFD linker to bypass gold"
508                 fi
509         fi
510 }
511
512 # @FUNCTION: tc-has-openmp
513 # @USAGE: [toolchain prefix]
514 # @DESCRIPTION:
515 # See if the toolchain supports OpenMP.
516 tc-has-openmp() {
517         local base="${T}/test-tc-openmp"
518         cat <<-EOF > "${base}.c"
519         #include <omp.h>
520         int main() {
521                 int nthreads, tid, ret = 0;
522                 #pragma omp parallel private(nthreads, tid)
523                 {
524                 tid = omp_get_thread_num();
525                 nthreads = omp_get_num_threads(); ret += tid + nthreads;
526                 }
527                 return ret;
528         }
529         EOF
530         $(tc-getCC "$@") -fopenmp "${base}.c" -o "${base}" >&/dev/null
531         local ret=$?
532         rm -f "${base}"*
533         return ${ret}
534 }
535
536 # @FUNCTION: tc-check-openmp
537 # @DESCRIPTION:
538 # Test for OpenMP support with the current compiler and error out with
539 # a clear error message, telling the user how to rectify the missing
540 # OpenMP support that has been requested by the ebuild. Using this function
541 # to test for OpenMP support should be preferred over tc-has-openmp and
542 # printing a custom message, as it presents a uniform interface to the user.
543 tc-check-openmp() {
544         if ! tc-has-openmp; then
545                 eerror "Your current compiler does not support OpenMP!"
546
547                 if tc-is-gcc; then
548                         eerror "Enable OpenMP support by building sys-devel/gcc with USE=\"openmp\"."
549                 elif tc-is-clang; then
550                         eerror "OpenMP support in sys-devel/clang is provided by sys-libs/libomp."
551                 fi
552
553                 die "Active compiler does not have required support for OpenMP"
554         fi
555 }
556
557 # @FUNCTION: tc-has-tls
558 # @USAGE: [-s|-c|-l] [toolchain prefix]
559 # @DESCRIPTION:
560 # See if the toolchain supports thread local storage (TLS).  Use -s to test the
561 # compiler, -c to also test the assembler, and -l to also test the C library
562 # (the default).
563 tc-has-tls() {
564         local base="${T}/test-tc-tls"
565         cat <<-EOF > "${base}.c"
566         int foo(int *i) {
567                 static __thread int j = 0;
568                 return *i ? j : *i;
569         }
570         EOF
571         local flags
572         case $1 in
573                 -s) flags="-S";;
574                 -c) flags="-c";;
575                 -l) ;;
576                 -*) die "Usage: tc-has-tls [-c|-l] [toolchain prefix]";;
577         esac
578         : ${flags:=-fPIC -shared -Wl,-z,defs}
579         [[ $1 == -* ]] && shift
580         $(tc-getCC "$@") ${flags} "${base}.c" -o "${base}" >&/dev/null
581         local ret=$?
582         rm -f "${base}"*
583         return ${ret}
584 }
585
586
587 # Parse information from CBUILD/CHOST/CTARGET rather than
588 # use external variables from the profile.
589 tc-ninja_magic_to_arch() {
590 ninj() { [[ ${type} == "kern" ]] && echo $1 || echo $2 ; }
591
592         local type=$1
593         local host=$2
594         [[ -z ${host} ]] && host=${CTARGET:-${CHOST}}
595
596         case ${host} in
597                 aarch64*)       echo arm64;;
598                 alpha*)         echo alpha;;
599                 arm*)           echo arm;;
600                 avr*)           ninj avr32 avr;;
601                 bfin*)          ninj blackfin bfin;;
602                 c6x*)           echo c6x;;
603                 cris*)          echo cris;;
604                 frv*)           echo frv;;
605                 hexagon*)       echo hexagon;;
606                 hppa*)          ninj parisc hppa;;
607                 i?86*)
608                         # Starting with linux-2.6.24, the 'x86_64' and 'i386'
609                         # trees have been unified into 'x86'.
610                         # FreeBSD still uses i386
611                         if [[ ${type} == "kern" && ${host} == *freebsd* ]] ; then
612                                 echo i386
613                         else
614                                 echo x86
615                         fi
616                         ;;
617                 ia64*)          echo ia64;;
618                 m68*)           echo m68k;;
619                 metag*)         echo metag;;
620                 microblaze*)    echo microblaze;;
621                 mips*)          echo mips;;
622                 nios2*)         echo nios2;;
623                 nios*)          echo nios;;
624                 or1k|or32*)     echo openrisc;;
625                 powerpc*)
626                         # Starting with linux-2.6.15, the 'ppc' and 'ppc64' trees
627                         # have been unified into simply 'powerpc', but until 2.6.16,
628                         # ppc32 is still using ARCH="ppc" as default
629                         if [[ ${type} == "kern" ]] ; then
630                                 echo powerpc
631                         elif [[ ${host} == powerpc64* ]] ; then
632                                 echo ppc64
633                         else
634                                 echo ppc
635                         fi
636                         ;;
637                 riscv*)         echo riscv;;
638                 s390*)          echo s390;;
639                 score*)         echo score;;
640                 sh64*)          ninj sh64 sh;;
641                 sh*)            echo sh;;
642                 sparc64*)       ninj sparc64 sparc;;
643                 sparc*)         [[ ${PROFILE_ARCH} == "sparc64" ]] \
644                                                 && ninj sparc64 sparc \
645                                                 || echo sparc
646                                         ;;
647                 tile*)          echo tile;;
648                 vax*)           echo vax;;
649                 x86_64*freebsd*) echo amd64;;
650                 x86_64*)
651                         # Starting with linux-2.6.24, the 'x86_64' and 'i386'
652                         # trees have been unified into 'x86'.
653                         if [[ ${type} == "kern" ]] ; then
654                                 echo x86
655                         else
656                                 echo amd64
657                         fi
658                         ;;
659                 xtensa*)        echo xtensa;;
660
661                 # since our usage of tc-arch is largely concerned with
662                 # normalizing inputs for testing ${CTARGET}, let's filter
663                 # other cross targets (mingw and such) into the unknown.
664                 *)                      echo unknown;;
665         esac
666 }
667 # @FUNCTION: tc-arch-kernel
668 # @USAGE: [toolchain prefix]
669 # @RETURN: name of the kernel arch according to the compiler target
670 tc-arch-kernel() {
671         tc-ninja_magic_to_arch kern "$@"
672 }
673 # @FUNCTION: tc-arch
674 # @USAGE: [toolchain prefix]
675 # @RETURN: name of the portage arch according to the compiler target
676 tc-arch() {
677         tc-ninja_magic_to_arch portage "$@"
678 }
679
680 tc-endian() {
681         local host=$1
682         [[ -z ${host} ]] && host=${CTARGET:-${CHOST}}
683         host=${host%%-*}
684
685         case ${host} in
686                 aarch64*be)     echo big;;
687                 aarch64)        echo little;;
688                 alpha*)         echo little;;
689                 arm*b*)         echo big;;
690                 arm*)           echo little;;
691                 cris*)          echo little;;
692                 hppa*)          echo big;;
693                 i?86*)          echo little;;
694                 ia64*)          echo little;;
695                 m68*)           echo big;;
696                 mips*l*)        echo little;;
697                 mips*)          echo big;;
698                 powerpc*le)     echo little;;
699                 powerpc*)       echo big;;
700                 s390*)          echo big;;
701                 sh*b*)          echo big;;
702                 sh*)            echo little;;
703                 sparc*)         echo big;;
704                 x86_64*)        echo little;;
705                 *)                      echo wtf;;
706         esac
707 }
708
709 # @FUNCTION: tc-get-compiler-type
710 # @RETURN: keyword identifying the compiler: gcc, clang, pathcc, unknown
711 tc-get-compiler-type() {
712         local code='
713 #if defined(__PATHSCALE__)
714         HAVE_PATHCC
715 #elif defined(__clang__)
716         HAVE_CLANG
717 #elif defined(__GNUC__)
718         HAVE_GCC
719 #endif
720 '
721         local res=$($(tc-getCPP "$@") -E -P - <<<"${code}")
722
723         case ${res} in
724                 *HAVE_PATHCC*)  echo pathcc;;
725                 *HAVE_CLANG*)   echo clang;;
726                 *HAVE_GCC*)             echo gcc;;
727                 *)                              echo unknown;;
728         esac
729 }
730
731 # @FUNCTION: tc-is-gcc
732 # @RETURN: Shell true if the current compiler is GCC, false otherwise.
733 tc-is-gcc() {
734         [[ $(tc-get-compiler-type) == gcc ]]
735 }
736
737 # @FUNCTION: tc-is-clang
738 # @RETURN: Shell true if the current compiler is clang, false otherwise.
739 tc-is-clang() {
740         [[ $(tc-get-compiler-type) == clang ]]
741 }
742
743 # Internal func.  The first argument is the version info to expand.
744 # Query the preprocessor to improve compatibility across different
745 # compilers rather than maintaining a --version flag matrix. #335943
746 _gcc_fullversion() {
747         local ver="$1"; shift
748         set -- $($(tc-getCPP "$@") -E -P - <<<"__GNUC__ __GNUC_MINOR__ __GNUC_PATCHLEVEL__")
749         eval echo "$ver"
750 }
751
752 # @FUNCTION: gcc-fullversion
753 # @RETURN: compiler version (major.minor.micro: [3.4.6])
754 gcc-fullversion() {
755         _gcc_fullversion '$1.$2.$3' "$@"
756 }
757 # @FUNCTION: gcc-version
758 # @RETURN: compiler version (major.minor: [3.4].6)
759 gcc-version() {
760         _gcc_fullversion '$1.$2' "$@"
761 }
762 # @FUNCTION: gcc-major-version
763 # @RETURN: major compiler version (major: [3].4.6)
764 gcc-major-version() {
765         _gcc_fullversion '$1' "$@"
766 }
767 # @FUNCTION: gcc-minor-version
768 # @RETURN: minor compiler version (minor: 3.[4].6)
769 gcc-minor-version() {
770         _gcc_fullversion '$2' "$@"
771 }
772 # @FUNCTION: gcc-micro-version
773 # @RETURN: micro compiler version (micro: 3.4.[6])
774 gcc-micro-version() {
775         _gcc_fullversion '$3' "$@"
776 }
777
778 # Internal func. Based on _gcc_fullversion() above.
779 _clang_fullversion() {
780         local ver="$1"; shift
781         set -- $($(tc-getCPP "$@") -E -P - <<<"__clang_major__ __clang_minor__ __clang_patchlevel__")
782         eval echo "$ver"
783 }
784
785 # @FUNCTION: clang-fullversion
786 # @RETURN: compiler version (major.minor.micro: [3.4.6])
787 clang-fullversion() {
788         _clang_fullversion '$1.$2.$3' "$@"
789 }
790 # @FUNCTION: clang-version
791 # @RETURN: compiler version (major.minor: [3.4].6)
792 clang-version() {
793         _clang_fullversion '$1.$2' "$@"
794 }
795 # @FUNCTION: clang-major-version
796 # @RETURN: major compiler version (major: [3].4.6)
797 clang-major-version() {
798         _clang_fullversion '$1' "$@"
799 }
800 # @FUNCTION: clang-minor-version
801 # @RETURN: minor compiler version (minor: 3.[4].6)
802 clang-minor-version() {
803         _clang_fullversion '$2' "$@"
804 }
805 # @FUNCTION: clang-micro-version
806 # @RETURN: micro compiler version (micro: 3.4.[6])
807 clang-micro-version() {
808         _clang_fullversion '$3' "$@"
809 }
810
811 # Returns the installation directory - internal toolchain
812 # function for use by _gcc-specs-exists (for flag-o-matic).
813 _gcc-install-dir() {
814         echo "$(LC_ALL=C $(tc-getCC) -print-search-dirs 2> /dev/null |\
815                 awk '$1=="install:" {print $2}')"
816 }
817 # Returns true if the indicated specs file exists - internal toolchain
818 # function for use by flag-o-matic.
819 _gcc-specs-exists() {
820         [[ -f $(_gcc-install-dir)/$1 ]]
821 }
822
823 # Returns requested gcc specs directive unprocessed - for used by
824 # gcc-specs-directive()
825 # Note; later specs normally overwrite earlier ones; however if a later
826 # spec starts with '+' then it appends.
827 # gcc -dumpspecs is parsed first, followed by files listed by "gcc -v"
828 # as "Reading <file>", in order.  Strictly speaking, if there's a
829 # $(gcc_install_dir)/specs, the built-in specs aren't read, however by
830 # the same token anything from 'gcc -dumpspecs' is overridden by
831 # the contents of $(gcc_install_dir)/specs so the result is the
832 # same either way.
833 _gcc-specs-directive_raw() {
834         local cc=$(tc-getCC)
835         local specfiles=$(LC_ALL=C ${cc} -v 2>&1 | awk '$1=="Reading" {print $NF}')
836         ${cc} -dumpspecs 2> /dev/null | cat - ${specfiles} | awk -v directive=$1 \
837 'BEGIN  { pspec=""; spec=""; outside=1 }
838 $1=="*"directive":"  { pspec=spec; spec=""; outside=0; next }
839         outside || NF==0 || ( substr($1,1,1)=="*" && substr($1,length($1),1)==":" ) { outside=1; next }
840         spec=="" && substr($0,1,1)=="+" { spec=pspec " " substr($0,2); next }
841         { spec=spec $0 }
842 END     { print spec }'
843         return 0
844 }
845
846 # Return the requested gcc specs directive, with all included
847 # specs expanded.
848 # Note, it does not check for inclusion loops, which cause it
849 # to never finish - but such loops are invalid for gcc and we're
850 # assuming gcc is operational.
851 gcc-specs-directive() {
852         local directive subdname subdirective
853         directive="$(_gcc-specs-directive_raw $1)"
854         while [[ ${directive} == *%\(*\)* ]]; do
855                 subdname=${directive/*%\(}
856                 subdname=${subdname/\)*}
857                 subdirective="$(_gcc-specs-directive_raw ${subdname})"
858                 directive="${directive//\%(${subdname})/${subdirective}}"
859         done
860         echo "${directive}"
861         return 0
862 }
863
864 # Returns true if gcc sets relro
865 gcc-specs-relro() {
866         local directive
867         directive=$(gcc-specs-directive link_command)
868         [[ "${directive/\{!norelro:}" != "${directive}" ]]
869 }
870 # Returns true if gcc sets now
871 gcc-specs-now() {
872         local directive
873         directive=$(gcc-specs-directive link_command)
874         [[ "${directive/\{!nonow:}" != "${directive}" ]]
875 }
876 # Returns true if gcc builds PIEs
877 gcc-specs-pie() {
878         local directive
879         directive=$(gcc-specs-directive cc1)
880         [[ "${directive/\{!nopie:}" != "${directive}" ]]
881 }
882 # Returns true if gcc builds with the stack protector
883 gcc-specs-ssp() {
884         local directive
885         directive=$(gcc-specs-directive cc1)
886         [[ "${directive/\{!fno-stack-protector:}" != "${directive}" ]]
887 }
888 # Returns true if gcc upgrades fstack-protector to fstack-protector-all
889 gcc-specs-ssp-to-all() {
890         local directive
891         directive=$(gcc-specs-directive cc1)
892         [[ "${directive/\{!fno-stack-protector-all:}" != "${directive}" ]]
893 }
894 # Returns true if gcc builds with fno-strict-overflow
895 gcc-specs-nostrict() {
896         local directive
897         directive=$(gcc-specs-directive cc1)
898         [[ "${directive/\{!fstrict-overflow:}" != "${directive}" ]]
899 }
900 # Returns true if gcc builds with fstack-check
901 gcc-specs-stack-check() {
902         local directive
903         directive=$(gcc-specs-directive cc1)
904         [[ "${directive/\{!fno-stack-check:}" != "${directive}" ]]
905 }
906
907
908 # @FUNCTION: tc-enables-pie
909 # @RETURN: Truth if the current compiler generates position-independent code (PIC) which can be linked into executables
910 # @DESCRIPTION:
911 # Return truth if the current compiler generates position-independent code (PIC)
912 # which can be linked into executables.
913 tc-enables-pie() {
914         tc-cpp-is-true "defined(__PIE__)" ${CPPFLAGS} ${CFLAGS}
915 }
916
917 # @FUNCTION: tc-enables-ssp
918 # @RETURN: Truth if the current compiler enables stack smashing protection (SSP) on at least minimal level
919 # @DESCRIPTION:
920 # Return truth if the current compiler enables stack smashing protection (SSP)
921 # on level corresponding to any of the following options:
922 #  -fstack-protector
923 #  -fstack-protector-strong
924 #  -fstack-protector-all
925 tc-enables-ssp() {
926         tc-cpp-is-true "defined(__SSP__) || defined(__SSP_STRONG__) || defined(__SSP_ALL__)" ${CPPFLAGS} ${CFLAGS}
927 }
928
929 # @FUNCTION: tc-enables-ssp-strong
930 # @RETURN: Truth if the current compiler enables stack smashing protection (SSP) on at least middle level
931 # @DESCRIPTION:
932 # Return truth if the current compiler enables stack smashing protection (SSP)
933 # on level corresponding to any of the following options:
934 #  -fstack-protector-strong
935 #  -fstack-protector-all
936 tc-enables-ssp-strong() {
937         tc-cpp-is-true "defined(__SSP_STRONG__) || defined(__SSP_ALL__)" ${CPPFLAGS} ${CFLAGS}
938 }
939
940 # @FUNCTION: tc-enables-ssp-all
941 # @RETURN: Truth if the current compiler enables stack smashing protection (SSP) on maximal level
942 # @DESCRIPTION:
943 # Return truth if the current compiler enables stack smashing protection (SSP)
944 # on level corresponding to any of the following options:
945 #  -fstack-protector-all
946 tc-enables-ssp-all() {
947         tc-cpp-is-true "defined(__SSP_ALL__)" ${CPPFLAGS} ${CFLAGS}
948 }
949
950
951 # @FUNCTION: gen_usr_ldscript
952 # @USAGE: [-a] <list of libs to create linker scripts for>
953 # @DESCRIPTION:
954 # This function generate linker scripts in /usr/lib for dynamic
955 # libs in /lib.  This is to fix linking problems when you have
956 # the .so in /lib, and the .a in /usr/lib.  What happens is that
957 # in some cases when linking dynamic, the .a in /usr/lib is used
958 # instead of the .so in /lib due to gcc/libtool tweaking ld's
959 # library search path.  This causes many builds to fail.
960 # See bug #4411 for more info.
961 #
962 # Note that you should in general use the unversioned name of
963 # the library (libfoo.so), as ldconfig should usually update it
964 # correctly to point to the latest version of the library present.
965 gen_usr_ldscript() {
966         local lib libdir=$(get_libdir) output_format="" auto=false suffix=$(get_libname)
967         [[ -z ${ED+set} ]] && local ED=${D%/}${EPREFIX}/
968
969         tc-is-static-only && return
970
971         # We only care about stuffing / for the native ABI. #479448
972         if [[ $(type -t multilib_is_native_abi) == "function" ]] ; then
973                 multilib_is_native_abi || return 0
974         fi
975
976         # Eventually we'd like to get rid of this func completely #417451
977         case ${CTARGET:-${CHOST}} in
978         *-darwin*) ;;
979         *-android*) return 0 ;;
980         *linux*|*-freebsd*|*-openbsd*|*-netbsd*)
981                 use prefix && return 0 ;;
982         *) return 0 ;;
983         esac
984
985         # Just make sure it exists
986         dodir /usr/${libdir}
987
988         if [[ $1 == "-a" ]] ; then
989                 auto=true
990                 shift
991                 dodir /${libdir}
992         fi
993
994         # OUTPUT_FORMAT gives hints to the linker as to what binary format
995         # is referenced ... makes multilib saner
996         local flags=( ${CFLAGS} ${LDFLAGS} -Wl,--verbose )
997         if $(tc-getLD) --version | grep -q 'GNU gold' ; then
998                 # If they're using gold, manually invoke the old bfd. #487696
999                 local d="${T}/bfd-linker"
1000                 mkdir -p "${d}"
1001                 ln -sf $(which ${CHOST}-ld.bfd) "${d}"/ld
1002                 flags+=( -B"${d}" )
1003         fi
1004         output_format=$($(tc-getCC) "${flags[@]}" 2>&1 | sed -n 's/^OUTPUT_FORMAT("\([^"]*\)",.*/\1/p')
1005         [[ -n ${output_format} ]] && output_format="OUTPUT_FORMAT ( ${output_format} )"
1006
1007         for lib in "$@" ; do
1008                 local tlib
1009                 if ${auto} ; then
1010                         lib="lib${lib}${suffix}"
1011                 else
1012                         # Ensure /lib/${lib} exists to avoid dangling scripts/symlinks.
1013                         # This especially is for AIX where $(get_libname) can return ".a",
1014                         # so /lib/${lib} might be moved to /usr/lib/${lib} (by accident).
1015                         [[ -r ${ED}/${libdir}/${lib} ]] || continue
1016                         #TODO: better die here?
1017                 fi
1018
1019                 case ${CTARGET:-${CHOST}} in
1020                 *-darwin*)
1021                         if ${auto} ; then
1022                                 tlib=$(scanmacho -qF'%S#F' "${ED}"/usr/${libdir}/${lib})
1023                         else
1024                                 tlib=$(scanmacho -qF'%S#F' "${ED}"/${libdir}/${lib})
1025                         fi
1026                         [[ -z ${tlib} ]] && die "unable to read install_name from ${lib}"
1027                         tlib=${tlib##*/}
1028
1029                         if ${auto} ; then
1030                                 mv "${ED}"/usr/${libdir}/${lib%${suffix}}.*${suffix#.} "${ED}"/${libdir}/ || die
1031                                 # some install_names are funky: they encode a version
1032                                 if [[ ${tlib} != ${lib%${suffix}}.*${suffix#.} ]] ; then
1033                                         mv "${ED}"/usr/${libdir}/${tlib%${suffix}}.*${suffix#.} "${ED}"/${libdir}/ || die
1034                                 fi
1035                                 rm -f "${ED}"/${libdir}/${lib}
1036                         fi
1037
1038                         # Mach-O files have an id, which is like a soname, it tells how
1039                         # another object linking against this lib should reference it.
1040                         # Since we moved the lib from usr/lib into lib this reference is
1041                         # wrong.  Hence, we update it here.  We don't configure with
1042                         # libdir=/lib because that messes up libtool files.
1043                         # Make sure we don't lose the specific version, so just modify the
1044                         # existing install_name
1045                         if [[ ! -w "${ED}/${libdir}/${tlib}" ]] ; then
1046                                 chmod u+w "${ED}${libdir}/${tlib}" # needed to write to it
1047                                 local nowrite=yes
1048                         fi
1049                         install_name_tool \
1050                                 -id "${EPREFIX}"/${libdir}/${tlib} \
1051                                 "${ED}"/${libdir}/${tlib} || die "install_name_tool failed"
1052                         [[ -n ${nowrite} ]] && chmod u-w "${ED}${libdir}/${tlib}"
1053                         # Now as we don't use GNU binutils and our linker doesn't
1054                         # understand linker scripts, just create a symlink.
1055                         pushd "${ED}/usr/${libdir}" > /dev/null
1056                         ln -snf "../../${libdir}/${tlib}" "${lib}"
1057                         popd > /dev/null
1058                         ;;
1059                 *)
1060                         if ${auto} ; then
1061                                 tlib=$(scanelf -qF'%S#F' "${ED}"/usr/${libdir}/${lib})
1062                                 [[ -z ${tlib} ]] && die "unable to read SONAME from ${lib}"
1063                                 mv "${ED}"/usr/${libdir}/${lib}* "${ED}"/${libdir}/ || die
1064                                 # some SONAMEs are funky: they encode a version before the .so
1065                                 if [[ ${tlib} != ${lib}* ]] ; then
1066                                         mv "${ED}"/usr/${libdir}/${tlib}* "${ED}"/${libdir}/ || die
1067                                 fi
1068                                 rm -f "${ED}"/${libdir}/${lib}
1069                         else
1070                                 tlib=${lib}
1071                         fi
1072                         cat > "${ED}/usr/${libdir}/${lib}" <<-END_LDSCRIPT
1073                         /* GNU ld script
1074                            Since Gentoo has critical dynamic libraries in /lib, and the static versions
1075                            in /usr/lib, we need to have a "fake" dynamic lib in /usr/lib, otherwise we
1076                            run into linking problems.  This "fake" dynamic lib is a linker script that
1077                            redirects the linker to the real lib.  And yes, this works in the cross-
1078                            compiling scenario as the sysroot-ed linker will prepend the real path.
1079
1080                            See bug https://bugs.gentoo.org/4411 for more info.
1081                          */
1082                         ${output_format}
1083                         GROUP ( ${EPREFIX}/${libdir}/${tlib} )
1084                         END_LDSCRIPT
1085                         ;;
1086                 esac
1087                 fperms a+x "/usr/${libdir}/${lib}" || die "could not change perms on ${lib}"
1088         done
1089 }
1090
1091 fi