scripts/functions
author Martin Guy <martinwguy@gmail.com>
Sun Mar 31 04:07:38 2013 +0000 (2013-03-31)
changeset 3203 74fd467be5aa
parent 3169 9d0b37f08a10
child 3205 30de175d3ed3
permissions -rw-r--r--
arch/avr32: Fix download of header files

This patch fixes the download of the avr32 headers in crosstool-ng by
fetching them directly from Atmel's web site instead of the now-broken URL
given by the original author of the avr32-header-fetching modification,
who fetched them from a copy on his own, now-defunct server.

It also adds the necessary logic to extract from a zip file, as that is
how the headers are packaged.

To configure it for avr32 after launching ct-ng menuconfig in an empty
directory:

Paths and misc options ->
Shell to use as CONFIG_SHELL = sh
Target options ->
Target Architecture = avr32
Toolchain options ->
Tuple's alias = avr32
Binary utilities ->
binutils version = 2.18a
C compiler
gcc version = 4.2.2
C-library
newlib version = 1.17.0
Enable IOs on long long = yes
Enable IOs on floats and doubles = yes
Disable the syscalls supplied with newlib = yes

CONFIG_SHELL is necessary to get round the "fragment: command not
found" bug when binutils-2.18 is configured using bash.

Prepared against crosstool-ng mercurial trunk on 31 March 2012.

Signed-off-by: Martin Guy <martinwguy@gmail.com>
[yann.morin.1998@free.fr: update bundles sample accordingly]
Signed-off-by: "Yann E. MORIN" <yann.morin.1998@free.fr>
Message-Id: <CAL4-wQrg_NQ7jm-NCADqeyQr9twyhtx42OUGNThP6gWeqZc=kw@mail.gmail.com>
Patchwork-Id: 232612
     1 # This file contains some usefull common functions -*- sh -*-
     2 # Copyright 2007 Yann E. MORIN
     3 # Licensed under the GPL v2. See COPYING in the root of this package
     4 
     5 # Prepare the fault handler
     6 CT_OnError() {
     7     local ret=$?
     8     local result
     9     local old_trap
    10     local intro
    11     local file line func
    12     local step step_depth
    13 
    14     # To avoid printing the backtace for each sub-shell
    15     # up to the top-level, just remember we've dumped it
    16     if [ ! -f "${CT_WORK_DIR}/backtrace" ]; then
    17         touch "${CT_WORK_DIR}/backtrace"
    18 
    19         # Print steps backtrace
    20         step_depth=${CT_STEP_COUNT}
    21         CT_STEP_COUNT=1     # To have a zero-indentation
    22         CT_DoLog ERROR ""
    23         CT_DoLog ERROR ">>"
    24         intro="Build failed"
    25         for((step=step_depth; step>0; step--)); do
    26             CT_DoLog ERROR ">>  ${intro} in step '${CT_STEP_MESSAGE[${step}]}'"
    27             intro="      called"
    28         done
    29 
    30         # Print functions backtrace
    31         intro="Error happened in"
    32         CT_DoLog ERROR ">>"
    33         for((depth=1; ${BASH_LINENO[$((${depth}-1))]}>0; depth++)); do
    34             file="${BASH_SOURCE[${depth}]#${CT_LIB_DIR}/}"
    35             func="${FUNCNAME[${depth}]}"
    36             line="@${BASH_LINENO[${depth}-1]:-?}"
    37             CT_DoLog ERROR ">>  ${intro}: ${func}[${file}${line}]"
    38             intro="      called from"
    39         done
    40 
    41         # If the user asked for interactive debugging, dump him/her to a shell
    42         if [ "${CT_DEBUG_INTERACTIVE}" = "y" ]; then
    43             # We do not want this sub-shell exit status to be caught, because
    44             # it is absolutely legit that it exits with non-zero.
    45             # Save the trap handler to restore it after our debug-shell
    46             old_trap="$(trap -p ERR)"
    47             trap -- ERR
    48             (
    49                 exec >&6 2>&7 <&8
    50                 printf "\r         \n\nCurrent command"
    51                 if [ -n "${cur_cmd}" ]; then
    52                     printf ":\n  %s\n" "${cur_cmd}"
    53                 else
    54                     printf " (unknown), "
    55                 fi
    56                 printf "exited with error code: %d\n" ${ret}
    57                 printf "Please fix it up and finish by exiting the shell with one of these values:\n"
    58                 printf "    1  fixed, continue with next build command\n"
    59                 if [ -n "${cur_cmd}" ]; then
    60                     printf "    2  repeat this build command\n"
    61                 fi
    62                 printf "    3  abort build\n\n"
    63                 while true; do
    64                     ${bash} --rcfile <(printf "PS1='ct-ng:\w> '\nPROMPT_COMMAND=''\n") -i
    65                     result=$?
    66                     case $result in
    67                         1)  printf "\nContinuing past the failed command.\n\n"
    68                             break
    69                             ;;
    70                         2)  if [ -n "${cur_cmd}" ]; then
    71                                 printf "\nRe-trying last command.\n\n"
    72                                 break
    73                             fi
    74                             ;;
    75                         3)  break;;
    76                     esac
    77                     printf "\nPlease exit with one of these values:\n"
    78                     printf "    1  fixed, continue with next build command\n"
    79                     if [ -n "${cur_cmd}" ]; then
    80                         printf "    2  repeat this build command\n"
    81                     fi
    82                     printf "    3  abort build\n"
    83                 done
    84                 exit $result
    85             )
    86             result=$?
    87             # Restore the trap handler
    88             eval "${old_trap}"
    89             case "${result}" in
    90                 1)  rm -f "${CT_WORK_DIR}/backtrace"; touch "${CT_BUILD_DIR}/skip"; return;;
    91                 2)  rm -f "${CT_WORK_DIR}/backtrace"; touch "${CT_BUILD_DIR}/repeat"; return;;
    92                 # 3 is an abort, continue...
    93             esac
    94         fi
    95     fi
    96 
    97     # And finally, in top-level shell, print some hints
    98     if [ ${BASH_SUBSHELL} -eq 0 ]; then
    99         # Help diagnose the error
   100         CT_STEP_COUNT=1     # To have a zero-indentation
   101         CT_DoLog ERROR ">>"
   102         if [ "${CT_LOG_TO_FILE}" = "y" ]; then
   103             CT_DoLog ERROR ">>  For more info on this error, look at the file: '${tmp_log_file#${CT_TOP_DIR}/}'"
   104         fi
   105         CT_DoLog ERROR ">>  There is a list of known issues, some with workarounds, in:"
   106         CT_DoLog ERROR ">>      '${CT_DOC_DIR#${CT_TOP_DIR}/}/B - Known issues.txt'"
   107 
   108         CT_DoLog ERROR ""
   109         CT_DoEnd ERROR
   110         rm -f "${CT_WORK_DIR}/backtrace"
   111     fi
   112     exit $ret
   113 }
   114 
   115 # Install the fault handler
   116 trap CT_OnError ERR
   117 
   118 # Inherit the fault handler in subshells and functions
   119 set -E
   120 
   121 # Make pipes fail on the _first_ failed command
   122 # Not supported on bash < 3.x, but we need it, so drop the obsoleting bash-2.x
   123 set -o pipefail
   124 
   125 # Don't hash commands' locations, and search every time it is requested.
   126 # This is slow, but needed because of the static/shared core gcc which shall
   127 # always match to shared if it exists, and only fallback to static if the
   128 # shared is not found
   129 set +o hashall
   130 
   131 # Log policy:
   132 #  - first of all, save stdout so we can see the live logs: fd #6
   133 # (also save stdin and stderr for use by CT_DEBUG_INTERACTIVE)
   134 exec 6>&1 7>&2 8<&0
   135 #  - then point stdout to the log file
   136 tmp_log_file="${CT_TOP_DIR}/build.log"
   137 rm -f "${tmp_log_file}"
   138 exec >>"${tmp_log_file}"
   139 
   140 # The different log levels:
   141 CT_LOG_LEVEL_ERROR=0
   142 CT_LOG_LEVEL_WARN=1
   143 CT_LOG_LEVEL_INFO=2
   144 CT_LOG_LEVEL_EXTRA=3
   145 CT_LOG_LEVEL_CFG=4
   146 CT_LOG_LEVEL_FILE=5
   147 CT_LOG_LEVEL_STATE=6
   148 CT_LOG_LEVEL_ALL=7
   149 CT_LOG_LEVEL_DEBUG=8
   150 
   151 # Make it easy to use \n and !
   152 CR=$(printf "\n")
   153 BANG='!'
   154 
   155 # A function to log what is happening
   156 # Different log level are available:
   157 #   - ERROR:   A serious, fatal error occurred
   158 #   - WARN:    A non fatal, non serious error occurred, take your responsbility with the generated build
   159 #   - INFO:    Informational messages
   160 #   - EXTRA:   Extra informational messages
   161 #   - CFG:     Output of various "./configure"-type scripts
   162 #   - FILE:    File / archive unpacking.
   163 #   - STATE:   State save & restore
   164 #   - ALL:     Component's build messages
   165 #   - DEBUG:   Internal debug messages
   166 # Usage: CT_DoLog <level> [message]
   167 # If message is empty, then stdin will be logged.
   168 CT_DoLog() {
   169     local max_level LEVEL level cur_l cur_L
   170     local l
   171     eval max_level="\${CT_LOG_LEVEL_${CT_LOG_LEVEL_MAX}}"
   172     # Set the maximum log level to DEBUG if we have none
   173     [ -z "${max_level}" ] && max_level=${CT_LOG_LEVEL_DEBUG}
   174 
   175     LEVEL="$1"; shift
   176     eval level="\${CT_LOG_LEVEL_${LEVEL}}"
   177 
   178     if [ $# -eq 0 ]; then
   179         cat -
   180     else
   181         printf "%s\n" "${*}"
   182     fi |( IFS="${CR}" # We want the full lines, even leading spaces
   183           _prog_bar_cpt=0
   184           _prog_bar[0]='/'
   185           _prog_bar[1]='-'
   186           _prog_bar[2]='\'
   187           _prog_bar[3]='|'
   188           indent=$((2*CT_STEP_COUNT))
   189           while read line; do
   190               case "${CT_LOG_SEE_TOOLS_WARN},${line}" in
   191                 y,*"warning:"*)         cur_L=WARN; cur_l=${CT_LOG_LEVEL_WARN};;
   192                 y,*"WARNING:"*)         cur_L=WARN; cur_l=${CT_LOG_LEVEL_WARN};;
   193                 *"error:"*)             cur_L=ERROR; cur_l=${CT_LOG_LEVEL_ERROR};;
   194                 *"make["*"]: *** ["*)   cur_L=ERROR; cur_l=${CT_LOG_LEVEL_ERROR};;
   195                 *)                      cur_L="${LEVEL}"; cur_l="${level}";;
   196               esac
   197               # There will always be a log file (stdout, fd #1), be it /dev/null
   198               printf "[%-5s]%*s%s%s\n" "${cur_L}" "${indent}" " " "${line}"
   199               if [ ${cur_l} -le ${max_level} ]; then
   200                   # Only print to console (fd #6) if log level is high enough.
   201                   printf "${CT_LOG_PROGRESS_BAR:+\r}[%-5s]%*s%s%s\n" "${cur_L}" "${indent}" " " "${line}" >&6
   202               fi
   203               if [ "${CT_LOG_PROGRESS_BAR}" = "y" ]; then
   204                   printf "\r[%02d:%02d] %s " $((SECONDS/60)) $((SECONDS%60)) "${_prog_bar[$((_prog_bar_cpt/10))]}" >&6
   205                   _prog_bar_cpt=$(((_prog_bar_cpt+1)%40))
   206               fi
   207           done
   208         )
   209 
   210     return 0
   211 }
   212 
   213 # Execute an action, and log its messages
   214 # It is possible to even log local variable assignments (a-la: var=val ./cmd opts)
   215 # Usage: CT_DoExecLog <level> [VAR=val...] <command> [parameters...]
   216 CT_DoExecLog() {
   217     local level="$1"
   218     local cur_cmd
   219     local ret
   220     shift
   221     (
   222     for i in "$@"; do
   223         cur_cmd+="'${i}' "
   224     done
   225     while true; do
   226         case "${1}" in
   227             *=*)    eval export "'${1}'"; shift;;
   228             *)      break;;
   229         esac
   230     done
   231     # This while-loop goes hand-in-hand with the ERR trap handler:
   232     # - if the command terminates successfully, then we hit the break
   233     #   statement, and we exit the loop
   234     # - if the command terminates in error, then the ERR handler kicks
   235     #   in, then:
   236     #     - if the user did *not* ask for interactive debugging, the ERR
   237     #       handler exits, and we hit the end of the sub-shell
   238     #     - if the user did ask for interactive debugging, the ERR handler
   239     #       spawns a shell. Upon termination of this shell, the ERR handler
   240     #       examines the exit status of the shell:
   241     #         - if 1, the ERR handler returns; then we hit the else statement,
   242     #           then the break, and we exit the 'while' loop, to continue the
   243     #           build;
   244     #         - if 2, the ERR handler touches the repeat file, and returns;
   245     #           then we hit the if statement, and we loop for one more
   246     #           iteration;
   247     #         - if 3, the ERR handler exits with the command's exit status,
   248     #           and we're dead;
   249     #         - for any other exit status of the shell, the ERR handler
   250     #           prints an informational message, and respawns the shell
   251     #
   252     # This allows a user to get an interactive shell that has the same
   253     # environment (PATH and so on) that the failed command was ran with.
   254     while true; do
   255         rm -f "${CT_BUILD_DIR}/repeat"
   256         CT_DoLog DEBUG "==> Executing: ${cur_cmd}"
   257         "${@}" 2>&1 |CT_DoLog "${level}"
   258         ret="${?}"
   259         if [ -f "${CT_BUILD_DIR}/repeat" ]; then
   260             rm -f "${CT_BUILD_DIR}/repeat"
   261             continue
   262         elif [ -f "${CT_BUILD_DIR}/skip" ]; then
   263             rm -f "${CT_BUILD_DIR}/skip"
   264             ret=0
   265             break
   266         else
   267             break
   268         fi
   269     done
   270     exit ${ret}
   271     )
   272     # Catch failure of the sub-shell
   273     [ $? -eq 0 ]
   274 }
   275 
   276 # Tail message to be logged whatever happens
   277 # Usage: CT_DoEnd <level>
   278 CT_DoEnd()
   279 {
   280     local level="$1"
   281     CT_STOP_DATE=$(CT_DoDate +%s%N)
   282     CT_STOP_DATE_HUMAN=$(CT_DoDate +%Y%m%d.%H%M%S)
   283     if [ "${level}" != "ERROR" ]; then
   284         CT_DoLog "${level:-INFO}" "Build completed at ${CT_STOP_DATE_HUMAN}"
   285     fi
   286     elapsed=$((CT_STOP_DATE-CT_STAR_DATE))
   287     elapsed_min=$((elapsed/(60*1000*1000*1000)))
   288     elapsed_sec=$(printf "%02d" $(((elapsed%(60*1000*1000*1000))/(1000*1000*1000))))
   289     elapsed_csec=$(printf "%02d" $(((elapsed%(1000*1000*1000))/(10*1000*1000))))
   290     CT_DoLog ${level:-INFO} "(elapsed: ${elapsed_min}:${elapsed_sec}.${elapsed_csec})"
   291 }
   292 
   293 # Remove entries referring to . and other relative paths
   294 # Usage: CT_SanitizePath
   295 CT_SanitizePath() {
   296     local new
   297     local p
   298     local IFS=:
   299     for p in $PATH; do
   300         # Only accept absolute paths;
   301         # Note: as a special case the empty string in PATH is equivalent to .
   302         if [ -n "${p}" -a -z "${p%%/*}" ]; then
   303             new="${new}${new:+:}${p}"
   304         fi
   305     done
   306     PATH="${new}"
   307 }
   308 
   309 # Sanitise the directory name contained in the variable passed as argument:
   310 # - remove duplicate /
   311 # Usage: CT_SanitiseVarDir CT_PREFIX_DIR
   312 CT_SanitiseVarDir() {
   313     local var
   314     local old_dir
   315     local new_dir
   316 
   317     for var in "$@"; do
   318         eval "old_dir=\"\${${var}}\""
   319         new_dir="$( printf "${old_dir}"     \
   320                     |sed -r -e 's:/+:/:g;'  \
   321                   )"
   322         eval "${var}=\"${new_dir}\""
   323         CT_DoLog DEBUG "Sanitised '${var}': '${old_dir}' -> '${new_dir}'"
   324     done
   325 }
   326 
   327 # Abort the execution with an error message
   328 # Usage: CT_Abort <message>
   329 CT_Abort() {
   330     CT_DoLog ERROR "$1"
   331     false
   332 }
   333 
   334 # Test a condition, and print a message if satisfied
   335 # Usage: CT_Test <message> <tests>
   336 CT_Test() {
   337     local ret
   338     local m="$1"
   339     shift
   340     CT_DoLog DEBUG "Testing '! ( $* )'"
   341     test "$@" && CT_DoLog WARN "$m"
   342     return 0
   343 }
   344 
   345 # Test a condition, and abort with an error message if satisfied
   346 # Usage: CT_TestAndAbort <message> <tests>
   347 CT_TestAndAbort() {
   348     local m="$1"
   349     shift
   350     CT_DoLog DEBUG "Testing '! ( $* )'"
   351     test "$@" && CT_Abort "$m"
   352     return 0
   353 }
   354 
   355 # Test a condition, and abort with an error message if not satisfied
   356 # Usage: CT_TestAndAbort <message> <tests>
   357 CT_TestOrAbort() {
   358     local m="$1"
   359     shift
   360     CT_DoLog DEBUG "Testing '$*'"
   361     test "$@" || CT_Abort "$m"
   362     return 0
   363 }
   364 
   365 # Test the presence of a tool, or abort if not found
   366 # Usage: CT_HasOrAbort <tool>
   367 CT_HasOrAbort() {
   368     CT_TestAndAbort "'${1}' not found and needed for successful toolchain build." -z "$(CT_Which "${1}")"
   369     return 0
   370 }
   371 
   372 # Search a program: wrap "which" for those system where "which"
   373 # verbosely says there is no match (such as on Mandriva).
   374 # Usage: CT_Which <filename>
   375 CT_Which() {
   376   which "$1" 2>/dev/null || true
   377 }
   378 
   379 # Get current date with nanosecond precision
   380 # On those system not supporting nanosecond precision, faked with rounding down
   381 # to the highest entire second
   382 # Usage: CT_DoDate <fmt>
   383 CT_DoDate() {
   384     date "$1" |sed -r -e 's/%?N$/000000000/;'
   385 }
   386 
   387 CT_STEP_COUNT=1
   388 CT_STEP_MESSAGE[${CT_STEP_COUNT}]="(top-level)"
   389 # Memorise a step being done so that any error is caught
   390 # Usage: CT_DoStep <loglevel> <message>
   391 CT_DoStep() {
   392     local start=$(CT_DoDate +%s%N)
   393     CT_DoLog "$1" "================================================================="
   394     CT_DoLog "$1" "$2"
   395     CT_STEP_COUNT=$((CT_STEP_COUNT+1))
   396     CT_STEP_LEVEL[${CT_STEP_COUNT}]="$1"; shift
   397     CT_STEP_START[${CT_STEP_COUNT}]="${start}"
   398     CT_STEP_MESSAGE[${CT_STEP_COUNT}]="$1"
   399     return 0
   400 }
   401 
   402 # End the step just being done
   403 # Usage: CT_EndStep
   404 CT_EndStep() {
   405     local stop=$(CT_DoDate +%s%N)
   406     local duration=$(printf "%032d" $((stop-${CT_STEP_START[${CT_STEP_COUNT}]})) |sed -r -e 's/([[:digit:]]{2})[[:digit:]]{7}$/\.\1/; s/^0+//; s/^\./0\./;')
   407     local elapsed=$(printf "%02d:%02d" $((SECONDS/60)) $((SECONDS%60)))
   408     local level="${CT_STEP_LEVEL[${CT_STEP_COUNT}]}"
   409     local message="${CT_STEP_MESSAGE[${CT_STEP_COUNT}]}"
   410     CT_STEP_COUNT=$((CT_STEP_COUNT-1))
   411     CT_DoLog "${level}" "${message}: done in ${duration}s (at ${elapsed})"
   412     return 0
   413 }
   414 
   415 # Pushes into a directory, and pops back
   416 CT_Pushd() {
   417     pushd "$1" >/dev/null 2>&1
   418 }
   419 CT_Popd() {
   420     popd >/dev/null 2>&1
   421 }
   422 
   423 # Create a dir and cd or pushd into it
   424 # Usage: CT_mkdir_cd <dir/to/create>
   425 #        CT_mkdir_pushd <dir/to/create>
   426 CT_mkdir_cd() {
   427     local dir="${1}"
   428 
   429     mkdir -p "${dir}"
   430     cd "${dir}"
   431 }
   432 CT_mkdir_pushd() {
   433     local dir="${1}"
   434 
   435     mkdir -p "${dir}"
   436     CT_Pushd "${dir}"
   437 }
   438 
   439 # Creates a temporary directory
   440 # $1: variable to assign to
   441 # Usage: CT_MktempDir foo
   442 CT_MktempDir() {
   443     # Some mktemp do not allow more than 6 Xs
   444     eval "$1"=$(mktemp -q -d "${CT_BUILD_DIR}/tmp.XXXXXX")
   445     CT_TestOrAbort "Could not make temporary directory" -n "${!1}" -a -d "${!1}"
   446     CT_DoLog DEBUG "Made temporary directory '${!1}'"
   447     return 0
   448 }
   449 
   450 # Removes one or more directories, even if it is read-only, or its parent is
   451 # Usage: CT_DoForceRmdir dir [...]
   452 CT_DoForceRmdir() {
   453     local dir
   454     local mode
   455     for dir in "${@}"; do
   456         [ -d "${dir}" ] || continue
   457         case "$CT_SYS_OS" in
   458             Linux|CYGWIN*)
   459                 mode="$(stat -c '%a' "$(dirname "${dir}")")"
   460                 ;;
   461             Darwin|*BSD)
   462                 mode="$(stat -f '%Lp' "$(dirname "${dir}")")"
   463                 ;;
   464             *)
   465                 CT_Abort "Unhandled host OS $CT_SYS_OS"
   466                 ;;
   467         esac
   468         CT_DoExecLog ALL chmod u+w "$(dirname "${dir}")"
   469         CT_DoExecLog ALL chmod -R u+w "${dir}"
   470         CT_DoExecLog ALL rm -rf "${dir}"
   471         CT_DoExecLog ALL chmod ${mode} "$(dirname "${dir}")"
   472     done
   473 }
   474 
   475 # Echoes the specified string on stdout until the pipe breaks.
   476 # Doesn't fail
   477 # $1: string to echo
   478 # Usage: CT_DoYes "" |make oldconfig
   479 CT_DoYes() {
   480     yes "$1" || true
   481 }
   482 
   483 # Add the specified directory to LD_LIBRARY_PATH, and export it
   484 # If the specified patch is already present, just export
   485 # $1: path to add
   486 # $2: add as 'first' or 'last' path, 'first' is assumed if $2 is empty
   487 # Usage CT_SetLibPath /some/where/lib [first|last]
   488 CT_SetLibPath() {
   489     local path="$1"
   490     local pos="$2"
   491 
   492     case ":${LD_LIBRARY_PATH}:" in
   493         *:"${path}":*)  ;;
   494         *)  case "${pos}" in
   495                 last)
   496                     CT_DoLog DEBUG "Adding '${path}' at end of LD_LIBRARY_PATH"
   497                     LD_LIBRARY_PATH="${LD_LIBRARY_PATH:+${LD_LIBRARY_PATH}:}${path}"
   498                     ;;
   499                 first|"")
   500                     CT_DoLog DEBUG "Adding '${path}' at start of LD_LIBRARY_PATH"
   501                     LD_LIBRARY_PATH="${path}${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}"
   502                     ;;
   503                 *)
   504                     CT_Abort "Incorrect position '${pos}' to add '${path}' to LD_LIBRARY_PATH"
   505                     ;;
   506             esac
   507             ;;
   508     esac
   509     CT_DoLog DEBUG "==> LD_LIBRARY_PATH='${LD_LIBRARY_PATH}'"
   510     export LD_LIBRARY_PATH
   511 }
   512 
   513 # Build up the list of allowed tarball extensions
   514 # Add them in the prefered order; most preferred comes first
   515 CT_DoListTarballExt() {
   516     if [ "${CT_CONFIGURE_has_xz}" = "y" ]; then
   517         printf ".tar.xz\n"
   518     fi
   519     if [    "${CT_CONFIGURE_has_lzma}" = "y"    \
   520          -o "${CT_CONFIGURE_has_xz}" = "y" ]; then
   521         printf ".tar.lzma\n"
   522     fi
   523     printf ".tar.bz2\n"
   524     printf ".tar.gz\n.tgz\n"
   525     printf ".tar\n"
   526     printf ".zip\n"
   527 }
   528 
   529 # Get the file name extension of a component
   530 # Usage: CT_GetFileExtension <component_name-component_version> [extension]
   531 # If found, echoes the extension to stdout, and return 0
   532 # If not found, echoes nothing on stdout, and return !0.
   533 CT_GetFileExtension() {
   534     local ext
   535     local file="$1"
   536     shift
   537     local first_ext="$1"
   538 
   539     # we need to also check for an empty extension for those very
   540     # peculiar components that don't have one (such as sstrip from
   541     # buildroot).
   542     for ext in ${first_ext} $(CT_DoListTarballExt) /.git ''; do
   543         if [ -e "${CT_TARBALLS_DIR}/${file}${ext}" ]; then
   544             echo "${ext}"
   545             exit 0
   546         fi
   547     done
   548 
   549     exit 1
   550 }
   551 
   552 # Try to retrieve the specified URL (HTTP or FTP)
   553 # Usage: CT_DoGetFile <URL>
   554 # This functions always returns true (0), as it can be legitimate not
   555 # to find the requested URL (think about snapshots, different layouts
   556 # for different gcc versions, etc...).
   557 CT_DoGetFile() {
   558     local url="${1}"
   559     local dest="${CT_TARBALLS_DIR}/${url##*/}"
   560     local tmp="${dest}.tmp-dl"
   561 
   562     # Remove potential left-over from a previous run
   563     rm -f "${tmp}"
   564 
   565     # We also retry a few times, in case there is a transient error (eg. behind
   566     # a dynamic IP that changes during the transfer...)
   567     # With automated download as we are doing, it can be very dangerous to
   568     # continue the downloads. It's far better to simply overwrite the
   569     # destination file.
   570     # Some company networks have firewalls to connect to the internet, but it's
   571     # not easy to detect them, so force a global ${CT_CONNECT_TIMEOUT}-second
   572     # timeout.
   573     # For curl, no good progress indicator is available. So, be silent.
   574     if CT_DoExecLog ALL wget --passive-ftp --tries=3 -nc    \
   575                              --progress=dot:binary          \
   576                              -T ${CT_CONNECT_TIMEOUT}       \
   577                              -O "${tmp}"                    \
   578                              "${url}"
   579     then
   580         # Success, we got it, good!
   581         mv "${tmp}" "${dest}"
   582         CT_DoLog DEBUG "Got it from: \"${url}\""
   583     else
   584         # Woops...
   585         rm -f "${tmp}"
   586         CT_DoLog DEBUG "Not at this location: \"${url}\""
   587     fi
   588 }
   589 
   590 # This function tries to retrieve a tarball form a local directory
   591 # Usage: CT_GetLocal <basename> [.extension]
   592 CT_GetLocal() {
   593     local basename="$1"
   594     local first_ext="$2"
   595     local ext
   596 
   597     # Do we already have it in *our* tarballs dir?
   598     if ext="$( CT_GetFileExtension "${basename}" ${first_ext} )"; then
   599         CT_DoLog DEBUG "Already have '${basename}'"
   600         return 0
   601     fi
   602 
   603     if [ -n "${CT_LOCAL_TARBALLS_DIR}" ]; then
   604         CT_DoLog DEBUG "Trying to retrieve an already downloaded copy of '${basename}'"
   605         # We'd rather have a bzip2'ed tarball, then gzipped tarball, plain tarball,
   606         # or, as a failover, a file without extension.
   607         for ext in ${first_ext} $(CT_DoListTarballExt) ''; do
   608             CT_DoLog DEBUG "Trying '${CT_LOCAL_TARBALLS_DIR}/${basename}${ext}'"
   609             if [ -r "${CT_LOCAL_TARBALLS_DIR}/${basename}${ext}" -a \
   610                  "${CT_FORCE_DOWNLOAD}" != "y" ]; then
   611                 CT_DoLog DEBUG "Got '${basename}' from local storage"
   612                 CT_DoExecLog ALL ln -s "${CT_LOCAL_TARBALLS_DIR}/${basename}${ext}" "${CT_TARBALLS_DIR}/${basename}${ext}"
   613                 return 0
   614             fi
   615         done
   616     fi
   617     return 1
   618 }
   619 
   620 # This function gets the custom source from either a tarball or directory
   621 # Usage: CT_GetCustom <component> <custom_version> <custom_location>
   622 CT_GetCustom() {
   623     local custom_component="$1"
   624     local custom_version="$2"
   625     local custom_location="$3"
   626     local custom_name="${custom_component}-${custom_version}"
   627 
   628     CT_TestAndAbort "${custom_name}: CT_CUSTOM_LOCATION_ROOT_DIR or ${custom_component}'s CUSTOM_LOCATION must be set." \
   629                     -z "${CT_CUSTOM_LOCATION_ROOT_DIR}" -a -z "${custom_location}"
   630 
   631     if [ -n "${CT_CUSTOM_LOCATION_ROOT_DIR}" \
   632          -a -z "${custom_location}"          ]; then
   633         custom_location="${CT_CUSTOM_LOCATION_ROOT_DIR}/${custom_component}"
   634     fi
   635 
   636     CT_DoLog EXTRA "Using '${custom_name}' from custom location"
   637     if [ ! -d "${custom_location}" ]; then
   638         # We need to know the custom tarball extension,
   639         # so we can create a properly-named symlink, which
   640         # we use later on in 'extract'
   641         case "${custom_location}" in
   642             *.tar.bz2)      custom_name="${custom_name}.tar.bz2";;
   643             *.tar.gz|*.tgz) custom_name="${custom_name}.tar.gz";;
   644             *.tar)          custom_name="${custom_name}.tar";;
   645             *)  CT_Abort "Unknown extension for custom tarball '${custom_location}'";;
   646         esac
   647         CT_DoExecLog DEBUG ln -sf "${custom_location}"  \
   648                                   "${CT_TARBALLS_DIR}/${custom_name}"
   649     else
   650         CT_DoExecLog DEBUG ln -snf "${custom_location}" \
   651                                    "${CT_SRC_DIR}/${custom_name}"
   652     fi
   653 }
   654 
   655 # This function saves the specified to local storage if possible,
   656 # and if so, symlinks it for later usage
   657 # Usage: CT_SaveLocal </full/path/file.name>
   658 CT_SaveLocal() {
   659     local file="$1"
   660     local basename="${file##*/}"
   661 
   662     if [ "${CT_SAVE_TARBALLS}" = "y" ]; then
   663         CT_DoLog EXTRA "Saving '${basename}' to local storage"
   664         # The file may already exist if downloads are forced: remove it first
   665         CT_DoExecLog ALL rm -f "${CT_LOCAL_TARBALLS_DIR}/${basename}"
   666         CT_DoExecLog ALL mv -f "${file}" "${CT_LOCAL_TARBALLS_DIR}"
   667         CT_DoExecLog ALL ln -s "${CT_LOCAL_TARBALLS_DIR}/${basename}" "${file}"
   668     fi
   669 }
   670 
   671 # Download the file from one of the URLs passed as argument
   672 # Usage: CT_GetFile <basename> [.extension] <url> [url ...]
   673 CT_GetFile() {
   674     local ext
   675     local -a URLS
   676     local url
   677     local file="$1"
   678     local first_ext
   679     shift
   680     # If next argument starts with a dot, then this is not an URL,
   681     # and we can consider that it is a preferred extension.
   682     case "$1" in
   683         .*) first_ext="$1"
   684             shift
   685             ;;
   686     esac
   687 
   688     # Does it exist localy?
   689     if CT_GetLocal "${file}" ${first_ext}; then
   690         return 0
   691     fi
   692     # No, it does not...
   693 
   694     # If not allowed to download from the Internet, don't
   695     if [ "${CT_FORBID_DOWNLOAD}" = "y" ]; then
   696         CT_DoLog DEBUG "Not allowed to download from the Internet, aborting ${file} download"
   697         return 1
   698     fi
   699 
   700     # Try to retrieve the file
   701     CT_DoLog EXTRA "Retrieving '${file}'"
   702 
   703     # Add URLs on the LAN mirror
   704     if [ "${CT_USE_MIRROR}" = "y" ]; then
   705         CT_TestOrAbort "Please set the mirror base URL" -n "${CT_MIRROR_BASE_URL}"
   706         URLS+=( "${CT_MIRROR_BASE_URL}/${file%-*}" )
   707         URLS+=( "${CT_MIRROR_BASE_URL}" )
   708     fi
   709 
   710     if [ "${CT_FORCE_MIRROR}" != "y" ]; then
   711         URLS+=( "${@}" )
   712     fi
   713 
   714     # Scan all URLs in turn, and try to grab a tarball from there
   715     # Do *not* try git trees (ext=/.git), this is handled in a specific
   716     # wrapper, below
   717     for ext in ${first_ext} $(CT_DoListTarballExt) ''; do
   718         # Try all urls in turn
   719         for url in "${URLS[@]}"; do
   720             [ -n "${url}" ] || continue
   721             CT_DoLog DEBUG "Trying '${url}/${file}${ext}'"
   722             CT_DoGetFile "${url}/${file}${ext}"
   723             if [ -f "${CT_TARBALLS_DIR}/${file}${ext}" ]; then
   724                 CT_DoLog DEBUG "Got '${file}' from the Internet"
   725                 CT_SaveLocal "${CT_TARBALLS_DIR}/${file}${ext}"
   726                 return 0
   727             fi
   728         done
   729     done
   730 
   731     # Just return error, someone may want to catch and handle the error
   732     # (eg. glibc/eglibc add-ons can be missing).
   733     return 1
   734 }
   735 
   736 # Checkout from CVS, and build the associated tarball
   737 # The tarball will be called ${basename}.tar.bz2
   738 # Prerequisite: either the server does not require password,
   739 # or the user must already be logged in.
   740 # 'tag' is the tag to retrieve. Must be specified, but can be empty.
   741 # If dirname is specified, then module will be renamed to dirname
   742 # prior to building the tarball.
   743 # Usage: CT_GetCVS <basename> <url> <module> <tag> [dirname[=subdir]]
   744 # Note: if '=subdir' is given, then it is used instead of 'module'.
   745 CT_GetCVS() {
   746     local basename="$1"
   747     local uri="$2"
   748     local module="$3"
   749     local tag="${4:+-r ${4}}"
   750     local dirname="$5"
   751     local tmp_dir
   752 
   753     # First try locally, then the mirror
   754     if CT_GetFile "${basename}"; then
   755         # Got it! Return early! :-)
   756         return 0
   757     fi
   758 
   759     if [ "${CT_FORBID_DOWNLOAD}" = "y" ]; then
   760         CT_DoLog WARN "Downloads forbidden, not trying cvs retrieval"
   761         return 1
   762     fi
   763 
   764     CT_MktempDir tmp_dir
   765     CT_Pushd "${tmp_dir}"
   766 
   767     CT_DoExecLog ALL cvs -z 9 -d "${uri}" co -P ${tag} "${module}"
   768     if [ -n "${dirname}" ]; then
   769         case "${dirname}" in
   770             *=*)
   771                 CT_DoExecLog DEBUG mv "${dirname#*=}" "${dirname%%=*}"
   772                 CT_DoExecLog ALL tar cjf "${CT_TARBALLS_DIR}/${basename}.tar.bz2" "${dirname%%=*}"
   773                 ;;
   774             *)
   775                 CT_DoExecLog ALL mv "${module}" "${dirname}"
   776                 CT_DoExecLog ALL tar cjf "${CT_TARBALLS_DIR}/${basename}.tar.bz2" "${dirname:-${module}}"
   777                 ;;
   778         esac
   779     fi
   780     CT_SaveLocal "${CT_TARBALLS_DIR}/${basename}.tar.bz2"
   781 
   782     CT_Popd
   783     CT_DoExecLog ALL rm -rf "${tmp_dir}"
   784 }
   785 
   786 # Check out from SVN, and build the associated tarball
   787 # The tarball will be called ${basename}.tar.bz2
   788 # Prerequisite: either the server does not require password,
   789 # or the user must already be logged in.
   790 # 'rev' is the revision to retrieve
   791 # Usage: CT_GetSVN <basename> <url> [rev]
   792 CT_GetSVN() {
   793     local basename="$1"
   794     local uri="$2"
   795     local rev="$3"
   796 
   797     # First try locally, then the mirror
   798     if CT_GetFile "${basename}"; then
   799         # Got it! Return early! :-)
   800         return 0
   801     fi
   802 
   803     if [ "${CT_FORBID_DOWNLOAD}" = "y" ]; then
   804         CT_DoLog WARN "Downloads forbidden, not trying svn retrieval"
   805         return 1
   806     fi
   807 
   808     CT_MktempDir tmp_dir
   809     CT_Pushd "${tmp_dir}"
   810 
   811     if ! CT_DoExecLog ALL svn export ${rev:+-r ${rev}} "${uri}" "${basename}"; then
   812         CT_DoLog WARN "Could not retrieve '${basename}'"
   813         return 1
   814     fi
   815     CT_DoExecLog ALL tar cjf "${CT_TARBALLS_DIR}/${basename}.tar.bz2" "${basename}"
   816     CT_SaveLocal "${CT_TARBALLS_DIR}/${basename}.tar.bz2"
   817 
   818     CT_Popd
   819     CT_DoExecLog ALL rm -rf "${tmp_dir}"
   820 }
   821 
   822 # Clone a git tree
   823 # Tries the given URLs in turn until one can get cloned. No tarball will be created.
   824 # Prerequisites: either the server does not require password,
   825 # or the user has already taken any action to authenticate to the server.
   826 # The cloned tree will *not* be stored in the local tarballs dir!
   827 # Usage: CT_GetGit <basename> <url [url ...]>
   828 CT_GetGit() {
   829     local basename="$1"; shift
   830     local url
   831     local cloned=0
   832 
   833     if [ "${CT_FORBID_DOWNLOAD}" = "y" ]; then
   834         CT_DoLog WARN "Downloads forbidden, not trying git retrieval"
   835         return 1
   836     fi
   837 
   838     # Do we have it in our tarballs dir?
   839     if [ -d "${CT_TARBALLS_DIR}/${basename}/.git" ]; then
   840         CT_DoLog EXTRA "Updating git tree '${basename}'"
   841         CT_Pushd "${CT_TARBALLS_DIR}/${basename}"
   842         CT_DoExecLog ALL git pull
   843         CT_Popd
   844     else
   845         CT_DoLog EXTRA "Retrieving git tree '${basename}'"
   846         for url in "${@}"; do
   847             CT_DoLog ALL "Trying to clone from '${url}'"
   848             CT_DoForceRmdir "${CT_TARBALLS_DIR}/${basename}"
   849             if git clone "${url}" "${CT_TARBALLS_DIR}/${basename}" 2>&1 |CT_DoLog ALL; then
   850                 cloned=1
   851                 break
   852             fi
   853         done
   854         CT_TestOrAbort "Could not clone '${basename}'" ${cloned} -ne 0
   855     fi
   856 }
   857 
   858 # Extract a tarball
   859 # Some tarballs need to be extracted in specific places. Eg.: glibc addons
   860 # must be extracted in the glibc directory; uCLibc locales must be extracted
   861 # in the extra/locale sub-directory of uClibc. This is taken into account
   862 # by the caller, that did a 'cd' into the correct path before calling us
   863 # and sets nochdir to 'nochdir'.
   864 # Note also that this function handles the git trees!
   865 # Usage: CT_Extract [nochdir] <basename> [options]
   866 # where 'options' are dependent on the source (eg. git branch/tag...)
   867 CT_Extract() {
   868     local nochdir="$1"
   869     local basename
   870     local ext
   871     local lzma_prog
   872     local -a tar_opts
   873 
   874     if [ "${nochdir}" = "nochdir" ]; then
   875         shift
   876         nochdir="$(pwd)"
   877     else
   878         nochdir="${CT_SRC_DIR}"
   879     fi
   880 
   881     basename="$1"
   882     shift
   883 
   884     if ! ext="$(CT_GetFileExtension "${basename}")"; then
   885         CT_DoLog WARN "'${basename}' not found in '${CT_TARBALLS_DIR}'"
   886         return 1
   887     fi
   888     local full_file="${CT_TARBALLS_DIR}/${basename}${ext}"
   889 
   890     # Check if already extracted
   891     if [ -e "${CT_SRC_DIR}/.${basename}.extracted" ]; then
   892         CT_DoLog DEBUG "Already extracted '${basename}'"
   893         return 0
   894     fi
   895 
   896     # Check if previously partially extracted
   897     if [ -e "${CT_SRC_DIR}/.${basename}.extracting" ]; then
   898         CT_DoLog ERROR "The '${basename}' sources were partially extracted."
   899         CT_DoLog ERROR "Please remove first:"
   900         CT_DoLog ERROR " - the source dir for '${basename}', in '${CT_SRC_DIR}'"
   901         CT_DoLog ERROR " - the file '${CT_SRC_DIR}/.${basename}.extracting'"
   902         CT_Abort "I'll stop now to avoid any carnage..."
   903     fi
   904     CT_DoExecLog DEBUG touch "${CT_SRC_DIR}/.${basename}.extracting"
   905 
   906     CT_Pushd "${nochdir}"
   907 
   908     CT_DoLog EXTRA "Extracting '${basename}'"
   909     CT_DoExecLog FILE mkdir -p "${basename}"
   910     tar_opts=( "--strip-components=1" )
   911     tar_opts+=( "-C" "${basename}" )
   912     tar_opts+=( "-xv" )
   913 
   914     # One note here:
   915     # - lzma can be handled either with 'xz' or 'lzma'
   916     # - we get lzma tarball only if either or both are available
   917     # - so, if we get an lzma tarball, and either 'xz' or 'lzma' is
   918     #   missing, we can assume the other is available
   919     if [ "${CT_CONFIGURE_has_lzma}" = "y" ]; then
   920         lzma_prog="lzma -fdc"
   921     else
   922         lzma_prog="xz -fdc"
   923     fi
   924     case "${ext}" in
   925         .tar.xz)      xz -fdc "${full_file}" | CT_DoExecLog FILE tar "${tar_opts[@]}" -f -;;
   926         .tar.lzma)    ${lzma_prog} "${full_file}" | CT_DoExecLog FILE tar "${tar_opts[@]}" -f -;;
   927         .tar.bz2)     bzip2 -dc "${full_file}" | CT_DoExecLog FILE tar "${tar_opts[@]}" -f -;;
   928         .tar.gz|.tgz) gzip -dc "${full_file}" | CT_DoExecLog FILE tar "${tar_opts[@]}" -f -;;
   929         .tar)         CT_DoExecLog FILE tar "${tar_opts[@]}" -f "${full_file}";;
   930         .zip)         CT_DoExecLog FILE unzip "${@}" "${full_file}";;
   931         /.git)        CT_ExtractGit "${basename}" "${@}";;
   932         *)            CT_DoLog WARN "Don't know how to handle '${basename}${ext}': unknown extension"
   933                       return 1
   934                       ;;
   935     esac
   936 
   937     # Don't mark as being extracted for git
   938     case "${ext}" in
   939         /.git)  ;;
   940         *)      CT_DoExecLog DEBUG touch "${CT_SRC_DIR}/.${basename}.extracted";;
   941     esac
   942     CT_DoExecLog DEBUG rm -f "${CT_SRC_DIR}/.${basename}.extracting"
   943 
   944     CT_Popd
   945 }
   946 
   947 # Create a working git clone of a local git repository
   948 # Usage: CT_ExtractGit <basename> [ref]
   949 # where 'ref' is the reference to use:
   950 #   the full name of a branch, like "remotes/origin/branch_name"
   951 #   a date as understandable by git, like "YYYY-MM-DD[ hh[:mm[:ss]]]"
   952 #   a tag name
   953 # If 'ref' is not given, the current repository HEAD will be used
   954 CT_ExtractGit() {
   955     local basename="${1}"
   956     local ref="${2}"
   957     local repo
   958     local ref_type
   959 
   960     # pushd now to be able to get git revlist in case ref is a date
   961     repo="${CT_TARBALLS_DIR}/${basename}"
   962     CT_Pushd "${repo}"
   963 
   964     # What kind of reference is ${ref} ?
   965     if [ -z "${ref}" ]; then
   966         ref_type=head
   967         ref=$(git rev-list -n1 HEAD)
   968     elif git tag |grep -E "^${ref}$" >/dev/null 2>&1; then
   969         ref_type=tag
   970     elif git branch -a --no-color |grep -E "^. ${ref}$" >/dev/null 2>&1; then
   971         ref_type=branch
   972     elif date -d "${ref}" >/dev/null 2>&1; then
   973         ref_type=date
   974         ref=$(git rev-list -n1 --before="${ref}")
   975     else
   976         CT_Abort "Reference '${ref}' is an incorrect git reference: neither tag, branch nor date"
   977     fi
   978 
   979     CT_Popd
   980 
   981     CT_DoExecLog FILE rmdir "${basename}"
   982     case "${ref_type}" in
   983         branch) CT_DoExecLog FILE git clone -b "${ref}" "${repo}" "${basename}" ;;
   984         *)      CT_DoExecLog FILE git clone "${repo}" "${basename}"
   985                 CT_Pushd "${basename}"
   986                 CT_DoExecLog FILE git checkout "${ref}"
   987                 CT_Popd
   988                 ;;
   989     esac
   990 }
   991 
   992 # Patches the specified component
   993 # See CT_Extract, above, for explanations on 'nochdir'
   994 # Usage: CT_Patch [nochdir] <packagename> <packageversion>
   995 # If the package directory is *not* packagename-packageversion, then
   996 # the caller must cd into the proper directory first, and call us
   997 # with nochdir
   998 CT_Patch() {
   999     local nochdir="$1"
  1000     local pkgname
  1001     local version
  1002     local pkgdir
  1003     local base_file
  1004     local ver_file
  1005     local d
  1006     local -a patch_dirs
  1007     local bundled_patch_dir
  1008     local local_patch_dir
  1009 
  1010     if [ "${nochdir}" = "nochdir" ]; then
  1011         shift
  1012         pkgname="$1"
  1013         version="$2"
  1014         pkgdir="${pkgname}-${version}"
  1015         nochdir="$(pwd)"
  1016     else
  1017         pkgname="$1"
  1018         version="$2"
  1019         pkgdir="${pkgname}-${version}"
  1020         nochdir="${CT_SRC_DIR}/${pkgdir}"
  1021     fi
  1022 
  1023     # Check if already patched
  1024     if [ -e "${CT_SRC_DIR}/.${pkgdir}.patched" ]; then
  1025         CT_DoLog DEBUG "Already patched '${pkgdir}'"
  1026         return 0
  1027     fi
  1028 
  1029     # Check if already partially patched
  1030     if [ -e "${CT_SRC_DIR}/.${pkgdir}.patching" ]; then
  1031         CT_DoLog ERROR "The '${pkgdir}' sources were partially patched."
  1032         CT_DoLog ERROR "Please remove first:"
  1033         CT_DoLog ERROR " - the source dir for '${pkgdir}', in '${CT_SRC_DIR}'"
  1034         CT_DoLog ERROR " - the file '${CT_SRC_DIR}/.${pkgdir}.extracted'"
  1035         CT_DoLog ERROR " - the file '${CT_SRC_DIR}/.${pkgdir}.patching'"
  1036         CT_Abort "I'll stop now to avoid any carnage..."
  1037     fi
  1038     touch "${CT_SRC_DIR}/.${pkgdir}.patching"
  1039 
  1040     CT_Pushd "${nochdir}"
  1041 
  1042     CT_DoLog EXTRA "Patching '${pkgdir}'"
  1043 
  1044     bundled_patch_dir="${CT_LIB_DIR}/patches/${pkgname}/${version}"
  1045     local_patch_dir="${CT_LOCAL_PATCH_DIR}/${pkgname}/${version}"
  1046 
  1047     case "${CT_PATCH_ORDER}" in
  1048         bundled)        patch_dirs=("${bundled_patch_dir}");;
  1049         local)          patch_dirs=("${local_patch_dir}");;
  1050         bundled,local)  patch_dirs=("${bundled_patch_dir}" "${local_patch_dir}");;
  1051         local,bundled)  patch_dirs=("${local_patch_dir}" "${bundled_patch_dir}");;
  1052         none)           patch_dirs=;;
  1053     esac
  1054 
  1055     for d in "${patch_dirs[@]}"; do
  1056         CT_DoLog DEBUG "Looking for patches in '${d}'..."
  1057         if [ -n "${d}" -a -d "${d}" ]; then
  1058             for p in "${d}"/*.patch; do
  1059                 if [ -f "${p}" ]; then
  1060                     CT_DoExecLog ALL patch --no-backup-if-mismatch -g0 -F1 -p1 -f -i "${p}"
  1061                 fi
  1062             done
  1063             if [ "${CT_PATCH_SINGLE}" = "y" ]; then
  1064                 break
  1065             fi
  1066         fi
  1067     done
  1068 
  1069     if [ "${CT_OVERIDE_CONFIG_GUESS_SUB}" = "y" ]; then
  1070         CT_DoLog ALL "Overiding config.guess and config.sub"
  1071         for cfg in config_guess config_sub; do
  1072             eval ${cfg}="${CT_LIB_DIR}/scripts/${cfg/_/.}"
  1073             [ -e "${CT_TOP_DIR}/scripts/${cfg/_/.}" ] && eval ${cfg}="${CT_TOP_DIR}/scripts/${cfg/_/.}"
  1074             # Can't use CT_DoExecLog because of the '{} \;' to be passed un-mangled to find
  1075             find . -type f -name "${cfg/_/.}" -exec cp -v "${!cfg}" {} \; |CT_DoLog ALL
  1076         done
  1077     fi
  1078 
  1079     CT_DoExecLog DEBUG touch "${CT_SRC_DIR}/.${pkgdir}.patched"
  1080     CT_DoExecLog DEBUG rm -f "${CT_SRC_DIR}/.${pkgdir}.patching"
  1081 
  1082     CT_Popd
  1083 }
  1084 
  1085 # Two wrappers to call config.(guess|sub) either from CT_TOP_DIR or CT_LIB_DIR.
  1086 # Those from CT_TOP_DIR, if they exist, will be be more recent than those from CT_LIB_DIR.
  1087 CT_DoConfigGuess() {
  1088     if [ -x "${CT_TOP_DIR}/scripts/config.guess" ]; then
  1089         "${CT_TOP_DIR}/scripts/config.guess"
  1090     else
  1091         "${CT_LIB_DIR}/scripts/config.guess"
  1092     fi
  1093 }
  1094 
  1095 CT_DoConfigSub() {
  1096     if [ -x "${CT_TOP_DIR}/scripts/config.sub" ]; then
  1097         "${CT_TOP_DIR}/scripts/config.sub" "$@"
  1098     else
  1099         "${CT_LIB_DIR}/scripts/config.sub" "$@"
  1100     fi
  1101 }
  1102 
  1103 # Compute the target tuple from what is provided by the user
  1104 # Usage: CT_DoBuildTargetTuple
  1105 # In fact this function takes the environment variables to build the target
  1106 # tuple. It is needed both by the normal build sequence, as well as the
  1107 # sample saving sequence.
  1108 CT_DoBuildTargetTuple() {
  1109     # Set the endianness suffix, and the default endianness gcc option
  1110     case "${CT_ARCH_ENDIAN}" in
  1111         big)
  1112             target_endian_eb=eb
  1113             target_endian_el=
  1114             CT_ARCH_ENDIAN_CFLAG="-mbig-endian"
  1115             CT_ARCH_ENDIAN_LDFLAG="-Wl,-EB"
  1116             ;;
  1117         little)
  1118             target_endian_eb=
  1119             target_endian_el=el
  1120             CT_ARCH_ENDIAN_CFLAG="-mlittle-endian"
  1121             CT_ARCH_ENDIAN_LDFLAG="-Wl,-EL"
  1122             ;;
  1123     esac
  1124 
  1125     # Build the default architecture tuple part
  1126     CT_TARGET_ARCH="${CT_ARCH}${CT_ARCH_SUFFIX}"
  1127 
  1128     # Set defaults for the system part of the tuple. Can be overriden
  1129     # by architecture-specific values.
  1130     case "${CT_LIBC}" in
  1131         *glibc) CT_TARGET_SYS=gnu;;
  1132         uClibc) CT_TARGET_SYS=uclibc;;
  1133         *)      CT_TARGET_SYS=elf;;
  1134     esac
  1135 
  1136     # Set the default values for ARCH, ABI, CPU, TUNE, FPU and FLOAT
  1137     unset CT_ARCH_ARCH_CFLAG CT_ARCH_ABI_CFLAG CT_ARCH_CPU_CFLAG CT_ARCH_TUNE_CFLAG CT_ARCH_FPU_CFLAG CT_ARCH_FLOAT_CFLAG
  1138     unset CT_ARCH_WITH_ARCH CT_ARCH_WITH_ABI CT_ARCH_WITH_CPU CT_ARCH_WITH_TUNE CT_ARCH_WITH_FPU CT_ARCH_WITH_FLOAT
  1139     [ "${CT_ARCH_ARCH}"     ] && { CT_ARCH_ARCH_CFLAG="-march=${CT_ARCH_ARCH}";  CT_ARCH_WITH_ARCH="--with-arch=${CT_ARCH_ARCH}"; }
  1140     [ "${CT_ARCH_ABI}"      ] && { CT_ARCH_ABI_CFLAG="-mabi=${CT_ARCH_ABI}";     CT_ARCH_WITH_ABI="--with-abi=${CT_ARCH_ABI}";    }
  1141     [ "${CT_ARCH_CPU}"      ] && { CT_ARCH_CPU_CFLAG="-mcpu=${CT_ARCH_CPU}";     CT_ARCH_WITH_CPU="--with-cpu=${CT_ARCH_CPU}";    }
  1142     [ "${CT_ARCH_TUNE}"     ] && { CT_ARCH_TUNE_CFLAG="-mtune=${CT_ARCH_TUNE}";  CT_ARCH_WITH_TUNE="--with-tune=${CT_ARCH_TUNE}"; }
  1143     [ "${CT_ARCH_FPU}"      ] && { CT_ARCH_FPU_CFLAG="-mfpu=${CT_ARCH_FPU}";     CT_ARCH_WITH_FPU="--with-fpu=${CT_ARCH_FPU}";    }
  1144 
  1145     case "${CT_ARCH_FLOAT}" in
  1146         hard)
  1147             CT_ARCH_FLOAT_CFLAG="-mhard-float"
  1148             CT_ARCH_WITH_FLOAT="--with-float=hard"
  1149             ;;
  1150         soft)
  1151             CT_ARCH_FLOAT_CFLAG="-msoft-float"
  1152             CT_ARCH_WITH_FLOAT="--with-float=soft"
  1153             ;;
  1154         softfp)
  1155             CT_ARCH_FLOAT_CFLAG="-mfloat-abi=softfp"
  1156             CT_ARCH_WITH_FLOAT="--with-float=softfp"
  1157             ;;
  1158     esac
  1159 
  1160     # Build the default kernel tuple part
  1161     CT_TARGET_KERNEL="${CT_KERNEL}"
  1162 
  1163     # Overide the default values with the components specific settings
  1164     CT_DoArchTupleValues
  1165     CT_DoKernelTupleValues
  1166 
  1167     # Finish the target tuple construction
  1168     CT_TARGET="${CT_TARGET_ARCH}"
  1169     CT_TARGET="${CT_TARGET}${CT_TARGET_VENDOR:+-${CT_TARGET_VENDOR}}"
  1170     CT_TARGET="${CT_TARGET}${CT_TARGET_KERNEL:+-${CT_TARGET_KERNEL}}"
  1171     CT_TARGET="${CT_TARGET}${CT_TARGET_SYS:+-${CT_TARGET_SYS}}"
  1172 
  1173     # Sanity checks
  1174     __sed_alias=""
  1175     if [ -n "${CT_TARGET_ALIAS_SED_EXPR}" ]; then
  1176         __sed_alias=$(echo "${CT_TARGET}" |sed -r -e "${CT_TARGET_ALIAS_SED_EXPR}")
  1177     fi
  1178     case ":${CT_TARGET_VENDOR}:${CT_TARGET_ALIAS}:${__sed_alias}:" in
  1179       :*" "*:*:*:) CT_Abort "Don't use spaces in the vendor string, it breaks things.";;
  1180       :*"-"*:*:*:) CT_Abort "Don't use dashes in the vendor string, it breaks things.";;
  1181       :*:*" "*:*:) CT_Abort "Don't use spaces in the target alias, it breaks things.";;
  1182       :*:*:*" "*:) CT_Abort "Don't use spaces in the target sed transform, it breaks things.";;
  1183     esac
  1184 
  1185     # Canonicalise it
  1186     CT_TARGET=$(CT_DoConfigSub "${CT_TARGET}")
  1187     # Prepare the target CFLAGS
  1188     CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_ENDIAN_CFLAG}"
  1189     CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_ARCH_CFLAG}"
  1190     CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_ABI_CFLAG}"
  1191     CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_CPU_CFLAG}"
  1192     CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_TUNE_CFLAG}"
  1193     CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_FPU_CFLAG}"
  1194     CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_FLOAT_CFLAG}"
  1195 
  1196     # Now on for the target LDFLAGS
  1197     CT_ARCH_TARGET_LDFLAGS="${CT_ARCH_TARGET_LDFLAGS} ${CT_ARCH_ENDIAN_LDFLAG}"
  1198 }
  1199 
  1200 # This function does pause the build until the user strikes "Return"
  1201 # Usage: CT_DoPause [optional_message]
  1202 CT_DoPause() {
  1203     local foo
  1204     local message="${1:-Pausing for your pleasure}"
  1205     CT_DoLog INFO "${message}"
  1206     read -p "Press 'Enter' to continue, or Ctrl-C to stop..." foo >&6
  1207     return 0
  1208 }
  1209 
  1210 # This function creates a tarball of the specified directory, but
  1211 # only if it exists
  1212 # Usage: CT_DoTarballIfExists <dir> <tarball_basename> [extra_tar_options [...]]
  1213 CT_DoTarballIfExists() {
  1214     local dir="$1"
  1215     local tarball="$2"
  1216     shift 2
  1217     local -a extra_tar_opts=( "$@" )
  1218     local -a compress
  1219 
  1220     case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
  1221         y)  compress=( gzip -c -3 - ); tar_ext=.gz;;
  1222         *)  compress=( cat - );        tar_ext=;;
  1223     esac
  1224 
  1225     if [ -d "${dir}" ]; then
  1226         CT_DoLog DEBUG "  Saving '${dir}'"
  1227         { tar c -C "${dir}" -v -f - "${extra_tar_opts[@]}" .    \
  1228           |"${compress[@]}" >"${tarball}.tar${tar_ext}"         ;
  1229         } 2>&1 |sed -r -e 's/^/    /;' |CT_DoLog STATE
  1230     else
  1231         CT_DoLog STATE "  Not saving '${dir}': does not exist"
  1232     fi
  1233 }
  1234 
  1235 # This function extracts a tarball to the specified directory, but
  1236 # only if the tarball exists
  1237 # Usage: CT_DoExtractTarballIfExists <tarball_basename> <dir> [extra_tar_options [...]]
  1238 CT_DoExtractTarballIfExists() {
  1239     local tarball="$1"
  1240     local dir="$2"
  1241     shift 2
  1242     local -a extra_tar_opts=( "$@" )
  1243     local -a uncompress
  1244 
  1245     case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
  1246         y)  uncompress=( gzip -c -d ); tar_ext=.gz;;
  1247         *)  uncompress=( cat );        tar_ext=;;
  1248     esac
  1249 
  1250     if [ -f "${tarball}.tar${tar_ext}" ]; then
  1251         CT_DoLog DEBUG "  Restoring '${dir}'"
  1252         CT_DoForceRmdir "${dir}"
  1253         CT_DoExecLog DEBUG mkdir -p "${dir}"
  1254         { "${uncompress[@]}" "${tarball}.tar${tar_ext}"     \
  1255           |tar x -C "${dir}" -v -f - "${extra_tar_opts[@]}" ;
  1256         } 2>&1 |sed -r -e 's/^/    /;' |CT_DoLog STATE
  1257     else
  1258         CT_DoLog STATE "  Not restoring '${dir}': does not exist"
  1259     fi
  1260 }
  1261 
  1262 # This function saves the state of the toolchain to be able to restart
  1263 # at any one point
  1264 # Usage: CT_DoSaveState <next_step_name>
  1265 CT_DoSaveState() {
  1266 	[ "${CT_DEBUG_CT_SAVE_STEPS}" = "y" ] || return 0
  1267     local state_name="$1"
  1268     local state_dir="${CT_STATE_DIR}/${state_name}"
  1269 
  1270     # Log this to the log level required by the user
  1271     CT_DoLog ${CT_LOG_LEVEL_MAX} "Saving state to restart at step '${state_name}'..."
  1272 
  1273     rm -rf "${state_dir}"
  1274     mkdir -p "${state_dir}"
  1275 
  1276     CT_DoLog STATE "  Saving environment and aliases"
  1277     # We must omit shell functions, and some specific bash variables
  1278     # that break when restoring the environment, later. We could do
  1279     # all the processing in the awk script, but a sed is easier...
  1280     set |awk '
  1281               BEGIN { _p = 1; }
  1282               $0~/^[^ ]+ \(\)/ { _p = 0; }
  1283               _p == 1
  1284               $0 == "}" { _p = 1; }
  1285               ' |sed -r -e '/^BASH_(ARGC|ARGV|LINENO|SOURCE|VERSINFO)=/d;
  1286                            /^(UID|EUID)=/d;
  1287                            /^(FUNCNAME|GROUPS|PPID|SHELLOPTS)=/d;' >"${state_dir}/env.sh"
  1288 
  1289     CT_DoTarballIfExists "${CT_BUILDTOOLS_PREFIX_DIR}" "${state_dir}/buildtools_dir"
  1290     CT_DoTarballIfExists "${CT_CONFIG_DIR}" "${state_dir}/config_dir"
  1291     CT_DoTarballIfExists "${CT_PREFIX_DIR}" "${state_dir}/prefix_dir" --exclude '*.log'
  1292 
  1293     CT_DoLog STATE "  Saving log file"
  1294     exec >/dev/null
  1295     case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
  1296         y)  gzip -3 -c "${tmp_log_file}"  >"${state_dir}/log.gz";;
  1297         *)  cat "${tmp_log_file}" >"${state_dir}/log";;
  1298     esac
  1299     exec >>"${tmp_log_file}"
  1300 }
  1301 
  1302 # This function restores a previously saved state
  1303 # Usage: CT_DoLoadState <state_name>
  1304 CT_DoLoadState(){
  1305     local state_name="$1"
  1306     local state_dir="${CT_STATE_DIR}/${state_name}"
  1307     local old_RESTART="${CT_RESTART}"
  1308     local old_STOP="${CT_STOP}"
  1309 
  1310     CT_TestOrAbort "The previous build did not reach the point where it could be restarted at '${CT_RESTART}'" -d "${state_dir}"
  1311 
  1312     # We need to do something special with the log file!
  1313     if [ "${CT_LOG_TO_FILE}" = "y" ]; then
  1314         exec >"${state_dir}/tail.log"
  1315     fi
  1316 
  1317     # Log this to the log level required by the user
  1318     CT_DoLog ${CT_LOG_LEVEL_MAX} "Restoring state at step '${state_name}', as requested."
  1319 
  1320     CT_DoExtractTarballIfExists "${state_dir}/prefix_dir" "${CT_PREFIX_DIR}"
  1321     CT_DoExtractTarballIfExists "${state_dir}/config_dir" "${CT_CONFIG_DIR}"
  1322     CT_DoExtractTarballIfExists "${state_dir}/buildtools_dir" "${CT_BUILDTOOLS_PREFIX_DIR}"
  1323 
  1324     # Restore the environment, discarding any error message
  1325     # (for example, read-only bash internals)
  1326     CT_DoLog STATE "  Restoring environment"
  1327     . "${state_dir}/env.sh" >/dev/null 2>&1 || true
  1328 
  1329     # Restore the new RESTART and STOP steps
  1330     CT_RESTART="${old_RESTART}"
  1331     CT_STOP="${old_STOP}"
  1332     unset old_stop old_restart
  1333 
  1334     CT_DoLog STATE "  Restoring log file"
  1335     exec >/dev/null
  1336     case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
  1337         y)  zcat "${state_dir}/log.gz" >"${tmp_log_file}";;
  1338         *)  cat "${state_dir}/log" >"${tmp_log_file}";;
  1339     esac
  1340     cat "${state_dir}/tail.log" >>"${tmp_log_file}"
  1341     exec >>"${tmp_log_file}"
  1342     rm -f "${state_dir}/tail.log"
  1343 }