scripts/functions
author "Yann E. MORIN" <yann.morin.1998@free.fr>
Sat Oct 06 23:48:07 2012 +0200 (2012-10-06)
changeset 3083 3a7b2eee9dcd
parent 3082 39ec9e913d79
child 3084 95df9d32afd2
permissions -rw-r--r--
scripts: add option to start an interactive debug shell

Add an option that, when a command fails:
- starts an interactive shell with the failed command's environment
- attempts re-execution of the failed command, continues, or aborts
at user's whim.

Before starting the debug-shell, the backtrace is printed.
When exiting for an abort, the standard error message is printed.

Based on an idea and a patch from: Johannes Stezenbach <js@sig21.net>
http://sourceware.org/ml/crossgcc/2012-09/msg00144.html

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