scripts/functions
author Johannes Stezenbach <js@sig21.net>
Tue Oct 30 00:36:20 2012 +0000 (2012-10-30)
changeset 3096 d1766c2273d1
parent 3085 0c3f8dd9d184
child 3097 5c67476c7342
permissions -rw-r--r--
scripts/functions: use patch -i instead of IO redirection

This makes the patch name show up on the command line
logged by CT_DoExecLog so it's easier to see
what is going on. The -i for patch is specified
by Posix and supported by GNU patch and busybox patch.

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