scripts/functions
author "Yann E. MORIN" <yann.morin.1998@anciens.enib.fr>
Tue Jan 27 22:27:35 2009 +0000 (2009-01-27)
branch1.3
changeset 1165 a6433a0af46e
parent 1081 10d1270080e6
permissions -rw-r--r--
Backport #1288 from /trunk:
- Fix aborting when neither wget nor curl are present

/branches/1.3/scripts/functions | 2 1 1 0 +-
1 file changed, 1 insertion(+), 1 deletion(-)
     1 # This file contains some usefull common functions
     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     ret=$?
     8     # Bail out early in subshell, the upper level shell will act accordingly.
     9     [ ${BASH_SUBSHELL} -eq 0 ] || exit $ret
    10     CT_DoLog ERROR "Build failed in step '${CT_STEP_MESSAGE[${CT_STEP_COUNT}]}'"
    11     for((step=(CT_STEP_COUNT-1); step>1; step--)); do
    12         CT_DoLog ERROR "      called in step '${CT_STEP_MESSAGE[${step}]}'"
    13     done
    14     CT_DoLog ERROR "Error happened in '${BASH_SOURCE[1]}' in function '${FUNCNAME[1]}' (line unknown, sorry)"
    15     for((depth=2; ${BASH_LINENO[$((${depth}-1))]}>0; depth++)); do
    16         CT_DoLog ERROR "      called from '${BASH_SOURCE[${depth}]}' at line # ${BASH_LINENO[${depth}-1]} in function '${FUNCNAME[${depth}]}'"
    17     done
    18     [ "${CT_LOG_TO_FILE}" = "y" ] && CT_DoLog ERROR "Look at '${CT_LOG_FILE}' for more info on this error."
    19     CT_STEP_COUNT=1
    20     CT_DoEnd ERROR
    21     exit $ret
    22 }
    23 
    24 # Install the fault handler
    25 trap CT_OnError ERR
    26 
    27 # Inherit the fault handler in subshells and functions
    28 set -E
    29 
    30 # Make pipes fail on the _first_ failed command
    31 # Not supported on bash < 3.x, but we need it, so drop the obsoleting bash-2.x
    32 set -o pipefail
    33 
    34 # Don't hash commands' locations, and search every time it is requested.
    35 # This is slow, but needed because of the static/shared core gcc which shall
    36 # always match to shared if it exists, and only fallback to static if the
    37 # shared is not found
    38 set +o hashall
    39 
    40 # Log policy:
    41 #  - first of all, save stdout so we can see the live logs: fd #6
    42 exec 6>&1
    43 #  - then point stdout to the log file (temporary for now)
    44 tmp_log_file="${CT_TOP_DIR}/log.$$"
    45 exec >>"${tmp_log_file}"
    46 
    47 # The different log levels:
    48 CT_LOG_LEVEL_ERROR=0
    49 CT_LOG_LEVEL_WARN=1
    50 CT_LOG_LEVEL_INFO=2
    51 CT_LOG_LEVEL_EXTRA=3
    52 CT_LOG_LEVEL_DEBUG=4
    53 CT_LOG_LEVEL_ALL=5
    54 
    55 # Make it easy to use \n
    56 CR=$(printf "\n")
    57 
    58 # A function to log what is happening
    59 # Different log level are available:
    60 #   - ERROR:   A serious, fatal error occurred
    61 #   - WARN:    A non fatal, non serious error occurred, take your responsbility with the generated build
    62 #   - INFO:    Informational messages
    63 #   - EXTRA:   Extra informational messages
    64 #   - DEBUG:   Debug messages
    65 #   - ALL:     Component's build messages
    66 # Usage: CT_DoLog <level> [message]
    67 # If message is empty, then stdin will be logged.
    68 CT_DoLog() {
    69     local max_level LEVEL level cur_l cur_L
    70     local l
    71     eval max_level="\${CT_LOG_LEVEL_${CT_LOG_LEVEL_MAX}}"
    72     # Set the maximum log level to DEBUG if we have none
    73     [ -z "${max_level}" ] && max_level=${CT_LOG_LEVEL_DEBUG}
    74 
    75     LEVEL="$1"; shift
    76     eval level="\${CT_LOG_LEVEL_${LEVEL}}"
    77 
    78     if [ $# -eq 0 ]; then
    79         cat -
    80     else
    81         echo "${@}"
    82     fi |( IFS="${CR}" # We want the full lines, even leading spaces
    83           _prog_bar_cpt=0
    84           _prog_bar[0]='/'
    85           _prog_bar[1]='-'
    86           _prog_bar[2]='\'
    87           _prog_bar[3]='|'
    88           indent=$((2*CT_STEP_COUNT))
    89           while read line; do
    90               case "${CT_LOG_SEE_TOOLS_WARN},${line}" in
    91                 y,*"warning:"*)         cur_L=WARN; cur_l=${CT_LOG_LEVEL_WARN};;
    92                 y,*"WARNING:"*)         cur_L=WARN; cur_l=${CT_LOG_LEVEL_WARN};;
    93                 *"error:"*)             cur_L=ERROR; cur_l=${CT_LOG_LEVEL_ERROR};;
    94                 *"make["*"]: *** ["*)   cur_L=ERROR; cur_l=${CT_LOG_LEVEL_ERROR};;
    95                 *)                      cur_L="${LEVEL}"; cur_l="${level}";;
    96               esac
    97               # There will always be a log file (stdout, fd #1), be it /dev/null
    98               printf "[%-5s]%*s%s%s\n" "${cur_L}" "${indent}" " " "${line}"
    99               if [ ${cur_l} -le ${max_level} ]; then
   100                   # Only print to console (fd #6) if log level is high enough.
   101                   printf "\r[%-5s]%*s%s%s\n" "${cur_L}" "${indent}" " " "${line}" >&6
   102               fi
   103               if [ "${CT_LOG_PROGRESS_BAR}" = "y" ]; then
   104                   printf "\r[%02d:%02d] %s " $((SECONDS/60)) $((SECONDS%60)) "${_prog_bar[$((_prog_bar_cpt/10))]}" >&6
   105                   _prog_bar_cpt=$(((_prog_bar_cpt+1)%40))
   106               fi
   107           done
   108         )
   109 
   110     return 0
   111 }
   112 
   113 # Execute an action, and log its messages
   114 # Usage: CT_DoExecLog <level> <[VAR=val...] command [parameters...]>
   115 CT_DoExecLog() {
   116     local level="$1"
   117     shift
   118     CT_DoLog DEBUG "==> Executing: '${@}'"
   119     "${@}" 2>&1 |CT_DoLog "${level}"
   120 }
   121 
   122 # Tail message to be logged whatever happens
   123 # Usage: CT_DoEnd <level>
   124 CT_DoEnd()
   125 {
   126     local level="$1"
   127     CT_STOP_DATE=$(CT_DoDate +%s%N)
   128     CT_STOP_DATE_HUMAN=$(CT_DoDate +%Y%m%d.%H%M%S)
   129     if [ "${level}" != "ERROR" ]; then
   130         CT_DoLog "${level:-INFO}" "Build completed at ${CT_STOP_DATE_HUMAN}"
   131     fi
   132     elapsed=$((CT_STOP_DATE-CT_STAR_DATE))
   133     elapsed_min=$((elapsed/(60*1000*1000*1000)))
   134     elapsed_sec=$(printf "%02d" $(((elapsed%(60*1000*1000*1000))/(1000*1000*1000))))
   135     elapsed_csec=$(printf "%02d" $(((elapsed%(1000*1000*1000))/(10*1000*1000))))
   136     CT_DoLog ${level:-INFO} "(elapsed: ${elapsed_min}:${elapsed_sec}.${elapsed_csec})"
   137 }
   138 
   139 # Abort the execution with an error message
   140 # Usage: CT_Abort <message>
   141 CT_Abort() {
   142     CT_DoLog ERROR "$1"
   143     exit 1
   144 }
   145 
   146 # Test a condition, and print a message if satisfied
   147 # Usage: CT_Test <message> <tests>
   148 CT_Test() {
   149     local ret
   150     local m="$1"
   151     shift
   152     test "$@" && CT_DoLog WARN "$m"
   153     return 0
   154 }
   155 
   156 # Test a condition, and abort with an error message if satisfied
   157 # Usage: CT_TestAndAbort <message> <tests>
   158 CT_TestAndAbort() {
   159     local m="$1"
   160     shift
   161     test "$@" && CT_Abort "$m"
   162     return 0
   163 }
   164 
   165 # Test a condition, and abort with an error message if not satisfied
   166 # Usage: CT_TestAndAbort <message> <tests>
   167 CT_TestOrAbort() {
   168     local m="$1"
   169     shift
   170     test "$@" || CT_Abort "$m"
   171     return 0
   172 }
   173 
   174 # Test the presence of a tool, or abort if not found
   175 # Usage: CT_HasOrAbort <tool>
   176 CT_HasOrAbort() {
   177     CT_TestAndAbort "'${1}' not found and needed for successful toolchain build." -z "$(CT_Which "${1}")"
   178     return 0
   179 }
   180 
   181 # Search a program: wrap "which" for those system where
   182 # "which" verbosely says there is no match (Mdk are such
   183 # suckers...)
   184 # Usage: CT_Which <filename>
   185 CT_Which() {
   186   which "$1" 2>/dev/null || true
   187 }
   188 
   189 # Get current date with nanosecond precision
   190 # On those system not supporting nanosecond precision, faked with rounding down
   191 # to the highest entire second
   192 # Usage: CT_DoDate <fmt>
   193 CT_DoDate() {
   194     date "$1" |sed -r -e 's/%N$/000000000/;'
   195 }
   196 
   197 CT_STEP_COUNT=1
   198 CT_STEP_MESSAGE[${CT_STEP_COUNT}]="<none>"
   199 # Memorise a step being done so that any error is caught
   200 # Usage: CT_DoStep <loglevel> <message>
   201 CT_DoStep() {
   202     local start=$(CT_DoDate +%s%N)
   203     CT_DoLog "$1" "================================================================="
   204     CT_DoLog "$1" "$2"
   205     CT_STEP_COUNT=$((CT_STEP_COUNT+1))
   206     CT_STEP_LEVEL[${CT_STEP_COUNT}]="$1"; shift
   207     CT_STEP_START[${CT_STEP_COUNT}]="${start}"
   208     CT_STEP_MESSAGE[${CT_STEP_COUNT}]="$1"
   209     return 0
   210 }
   211 
   212 # End the step just being done
   213 # Usage: CT_EndStep
   214 CT_EndStep() {
   215     local stop=$(CT_DoDate +%s%N)
   216     local duration=$(printf "%032d" $((stop-${CT_STEP_START[${CT_STEP_COUNT}]})) |sed -r -e 's/([[:digit:]]{2})[[:digit:]]{7}$/\.\1/; s/^0+//; s/^\./0\./;')
   217     local elapsed=$(printf "%02d:%02d" $((SECONDS/60)) $((SECONDS%60)))
   218     local level="${CT_STEP_LEVEL[${CT_STEP_COUNT}]}"
   219     local message="${CT_STEP_MESSAGE[${CT_STEP_COUNT}]}"
   220     CT_STEP_COUNT=$((CT_STEP_COUNT-1))
   221     CT_DoLog "${level}" "${message}: done in ${duration}s (at ${elapsed})"
   222     return 0
   223 }
   224 
   225 # Pushes into a directory, and pops back
   226 CT_Pushd() {
   227     pushd "$1" >/dev/null 2>&1
   228 }
   229 CT_Popd() {
   230     popd >/dev/null 2>&1
   231 }
   232 
   233 # Makes a path absolute
   234 # Usage: CT_MakeAbsolutePath path
   235 CT_MakeAbsolutePath() {
   236     # Try to cd in that directory
   237     if [ -d "$1" ]; then
   238         CT_Pushd "$1"
   239         pwd
   240         CT_Popd
   241     else
   242         # No such directory, fail back to guessing
   243         case "$1" in
   244             /*)  echo "$1";;
   245             *)   echo "$(pwd)/$1";;
   246         esac
   247     fi
   248     
   249     return 0
   250 }
   251 
   252 # Creates a temporary directory
   253 # $1: variable to assign to
   254 # Usage: CT_MktempDir foo
   255 CT_MktempDir() {
   256     # Some mktemp do not allow more than 6 Xs
   257     eval "$1"=$(mktemp -q -d "${CT_BUILD_DIR}/.XXXXXX")
   258     CT_TestOrAbort "Could not make temporary directory" -n "${!1}" -a -d "${!1}"
   259     CT_DoLog DEBUG "Made temporary directory '${!1}'"
   260     return 0
   261 }
   262 
   263 # Echoes the specified string on stdout until the pipe breaks.
   264 # Doesn't fail
   265 # $1: string to echo
   266 # Usage: CT_DoYes "" |make oldconfig
   267 CT_DoYes() {
   268     yes "$1" || true
   269 }
   270 
   271 # Get the file name extension of a component
   272 # Usage: CT_GetFileExtension <component_name-component_version> [extension]
   273 # If found, echoes the extension to stdout
   274 # If not found, echoes nothing on stdout.
   275 CT_GetFileExtension() {
   276     local ext
   277     local file="$1"
   278     shift
   279     local first_ext="$1"
   280 
   281     CT_Pushd "${CT_TARBALLS_DIR}"
   282     # we need to also check for an empty extension for those very
   283     # peculiar components that don't have one (such as sstrip from
   284     # buildroot).
   285     for ext in ${first_ext} .tar.gz .tar.bz2 .tgz .tar ''; do
   286         if [ -f "${file}${ext}" ]; then
   287             echo "${ext}"
   288             break
   289         fi
   290     done
   291     CT_Popd
   292 
   293     return 0
   294 }
   295 
   296 # Set environment for proxy access
   297 # Usage: CT_DoSetProxy <proxy_type>
   298 # where proxy_type is one of 'http', 'sockssys', 'socks4' or 'socks5',
   299 # or empty (to not change proxy settings).
   300 CT_DoSetProxy() {
   301     case "${1}" in
   302         http)
   303             http_proxy="http://"
   304             case  "${CT_PROXY_USER}:${CT_PROXY_PASS}" in
   305                 :)      ;;
   306                 :*)     http_proxy="${http_proxy}:${CT_PROXY_PASS}@";;
   307                 *:)     http_proxy="${http_proxy}${CT_PROXY_USER}@";;
   308                 *:*)    http_proxy="${http_proxy}${CT_PROXY_USER}:${CT_PROXY_PASS}@";;
   309             esac
   310             export http_proxy="${http_proxy}${CT_PROXY_HOST}:${CT_PROXY_PORT}/"
   311             export https_proxy="${http_proxy}"
   312             export ftp_proxy="${http_proxy}"
   313             CT_DoLog DEBUG "http_proxy='${http_proxy}'"
   314             ;;
   315         sockssys)
   316             CT_HasOrAbort tsocks
   317             . tsocks -on
   318             ;;
   319         socks*)
   320             # Remove any lingering config file from any previous run
   321             rm -f "${CT_BUILD_DIR}/tsocks.conf"
   322             # Find all interfaces and build locally accessible networks
   323             server_ip=$(ping -c 1 -W 2 "${CT_PROXY_HOST}" |head -n 1 |sed -r -e 's/^[^\(]+\(([^\)]+)\).*$/\1/;' || true)
   324             CT_TestOrAbort "SOCKS proxy '${CT_PROXY_HOST}' has no IP." -n "${server_ip}"
   325             /sbin/ifconfig |gawk -v server_ip="${server_ip}" '
   326                 BEGIN {
   327                     split( server_ip, tmp, "\\." );
   328                     server_ip_num = tmp[1] * 2^24 + tmp[2] * 2^16 + tmp[3] * 2^8 + tmp[4] * 2^0;
   329                     pairs = 0;
   330                 }
   331 
   332                 $0 ~ /^[[:space:]]*inet addr:/ {
   333                     split( $2, tmp, ":|\\." );
   334                     if( ( tmp[2] == 127 ) && ( tmp[3] == 0 ) && ( tmp[4] == 0 ) && ( tmp[5] == 1 ) ) {
   335                         /* Skip 127.0.0.1, it'\''s taken care of by tsocks itself */
   336                         next;
   337                     }
   338                     ip_num = tmp[2] * 2^24 + tmp[3] * 2^16 + tmp[4] * 2 ^8 + tmp[5] * 2^0;
   339                     i = 32;
   340                     do {
   341                         i--;
   342                         mask = 2^32 - 2^i;
   343                     } while( (i!=0) && ( and( server_ip_num, mask ) == and( ip_num, mask ) ) );
   344                     mask = and( 0xFFFFFFFF, lshift( mask, 1 ) );
   345                     if( (i!=0) && (mask!=0) ) {
   346                         masked_ip = and( ip_num, mask );
   347                         for( i=0; i<pairs; i++ ) {
   348                             if( ( masked_ip == ips[i] ) && ( mask == masks[i] ) ) {
   349                                 next;
   350                             }
   351                         }
   352                         ips[pairs] = masked_ip;
   353                         masks[pairs] = mask;
   354                         pairs++;
   355                         printf( "local = %d.%d.%d.%d/%d.%d.%d.%d\n",
   356                                 and( 0xFF, masked_ip / 2^24 ),
   357                                 and( 0xFF, masked_ip / 2^16 ),
   358                                 and( 0xFF, masked_ip / 2^8 ),
   359                                 and( 0xFF, masked_ip / 2^0 ),
   360                                 and( 0xFF, mask / 2^24 ),
   361                                 and( 0xFF, mask / 2^16 ),
   362                                 and( 0xFF, mask / 2^8 ),
   363                                 and( 0xFF, mask / 2^0 ) );
   364                     }
   365                 }
   366             ' >"${CT_BUILD_DIR}/tsocks.conf"
   367             ( echo "server = ${server_ip}";
   368               echo "server_port = ${CT_PROXY_PORT}";
   369               [ -n "${CT_PROXY_USER}"   ] && echo "default_user=${CT_PROXY_USER}";
   370               [ -n "${CT_PROXY_PASS}" ] && echo "default_pass=${CT_PROXY_PASS}";
   371             ) >>"${CT_BUILD_DIR}/tsocks.conf"
   372             case "${CT_PROXY_TYPE/socks}" in
   373                 4|5) proxy_type="${CT_PROXY_TYPE/socks}";;
   374                 auto)
   375                     reply=$(inspectsocks "${server_ip}" "${CT_PROXY_PORT}" 2>&1 || true)
   376                     case "${reply}" in
   377                         *"server is a version 4 socks server") proxy_type=4;;
   378                         *"server is a version 5 socks server") proxy_type=5;;
   379                         *) CT_Abort "Unable to determine SOCKS proxy type for '${CT_PROXY_HOST}:${CT_PROXY_PORT}'"
   380                     esac
   381                     ;;
   382             esac
   383             echo "server_type = ${proxy_type}" >> "${CT_BUILD_DIR}/tsocks.conf"
   384             CT_HasOrAbort tsocks
   385             # If tsocks was found, then validateconf is present (distributed with tsocks).
   386             CT_DoExecLog DEBUG validateconf -f "${CT_BUILD_DIR}/tsocks.conf"
   387             export TSOCKS_CONF_FILE="${CT_BUILD_DIR}/tsocks.conf"
   388             . tsocks -on
   389             ;;
   390     esac
   391 }
   392 
   393 # Download an URL using wget
   394 # Usage: CT_DoGetFileWget <URL>
   395 CT_DoGetFileWget() {
   396     # Need to return true because it is legitimate to not find the tarball at
   397     # some of the provided URLs (think about snapshots, different layouts for
   398     # different gcc versions, etc...)
   399     # Some (very old!) FTP server might not support the passive mode, thus
   400     # retry without
   401     # With automated download as we are doing, it can be very dangerous to use
   402     # -c to continue the downloads. It's far better to simply overwrite the
   403     # destination file
   404     # Some company networks have firewalls to connect to the internet, but it's
   405     # not easy to detect them, and wget does not timeout by default  while
   406     # connecting, so force a global ${CT_CONNECT_TIMEOUT}-second timeout.
   407     wget -T ${CT_CONNECT_TIMEOUT} -nc --progress=dot:binary --tries=3 --passive-ftp "$1"    \
   408     || wget -T ${CT_CONNECT_TIMEOUT} -nc --progress=dot:binary --tries=3 "$1"               \
   409     || true
   410 }
   411 
   412 # Download an URL using curl
   413 # Usage: CT_DoGetFileCurl <URL>
   414 CT_DoGetFileCurl() {
   415     # Note: comments about wget method (above) are also valid here
   416     # Plus: no good progress indicator is available with curl,
   417     #       so output is consigned to oblivion
   418     curl --ftp-pasv -O --retry 3 "$1" --connect-timeout ${CT_CONNECT_TIMEOUT} >/dev/null    \
   419     || curl -O --retry 3 "$1" --connect-timeout ${CT_CONNECT_TIMEOUT} >/dev/null            \
   420     || true
   421 }
   422 
   423 _wget=$(CT_Which wget)
   424 _curl=$(CT_Which curl)
   425 # Wrapper function to call one of curl or wget
   426 # Usage: CT_DoGetFile <URL>
   427 CT_DoGetFile() {
   428     case "${_wget},${_curl}" in
   429         ,)  CT_Abort "Could find neither wget nor curl";;
   430         ,*) CT_DoExecLog ALL CT_DoGetFileCurl "$1" 2>&1;;
   431         *)  CT_DoExecLog ALL CT_DoGetFileWget "$1" 2>&1;;
   432     esac
   433 }
   434 
   435 # Download the file from one of the URLs passed as argument
   436 # Usage: CT_GetFile <filename> [extension] <url> [url ...]
   437 CT_GetFile() {
   438     local ext
   439     local url
   440     local file="$1"
   441     local first_ext=""
   442     shift
   443     # If next argument starts with a dot, then this is not an URL,
   444     # and we can consider that it is a preferred extension.
   445     case "$1" in
   446         .*) first_ext="$1"
   447             shift
   448             ;;
   449     esac
   450 
   451     # Do we already have it?
   452     ext=$(CT_GetFileExtension "${file}" ${first_ext})
   453     if [ -n "${ext}" ]; then
   454         CT_DoLog DEBUG "Already have '${file}'"
   455         return 0
   456     fi
   457 
   458     # Try to retrieve the file
   459     CT_DoLog EXTRA "Retrieving '${file}'"
   460     CT_Pushd "${CT_TARBALLS_DIR}"
   461 
   462     if [ -n "${CT_LOCAL_TARBALLS_DIR}" ]; then
   463         CT_DoLog DEBUG "Trying to retrieve an already downloaded copy of '${file}'"
   464         # We'd rather have a bzip2'ed tarball, then gzipped tarball, plain tarball,
   465         # or, as a failover, a file without extension.
   466         # Try local copy first, if it exists
   467         for ext in ${first_ext} .tar.bz2 .tar.gz .tgz .tar ''; do
   468             CT_DoLog DEBUG "Trying '${CT_LOCAL_TARBALLS_DIR}/${file}${ext}'"
   469             if [ -r "${CT_LOCAL_TARBALLS_DIR}/${file}${ext}" -a \
   470                  "${CT_FORCE_DOWNLOAD}" != "y" ]; then
   471                 CT_DoLog DEBUG "Got '${file}' from local storage"
   472                 CT_DoExecLog ALL ln -s "${CT_LOCAL_TARBALLS_DIR}/${file}${ext}" "${file}${ext}"
   473                 return 0
   474             fi
   475         done
   476     fi
   477 
   478     # Not found locally, try from the network
   479 
   480     # Add URLs on the LAN mirror
   481     LAN_URLS=
   482     if [ "${CT_USE_MIRROR}" = "y" ]; then
   483         CT_DoLog DEBUG "Trying to retrieve a copy of '${file}' from LAN mirror '${CT_MIRROR_HOSTNAME}'"
   484         CT_TestOrAbort "Please set the LAN mirror hostname" -n "${CT_MIRROR_HOSTNAME}"
   485         CT_TestOrAbort "Please tell me where to find tarballs on the LAN mirror '${CT_MIRROR_HOSTNAME}'" -n "${CT_MIRROR_BASE}"
   486         LAN_URLS="${LAN_URLS} ${CT_MIRROR_SCHEME}://${CT_MIRROR_HOSTNAME}/${CT_MIRROR_BASE}/${file%-*}"
   487         LAN_URLS="${LAN_URLS} ${CT_MIRROR_SCHEME}://${CT_MIRROR_HOSTNAME}/${CT_MIRROR_BASE}"
   488     fi
   489 
   490     if [ "${CT_PREFER_MIRROR}" = "y" ]; then
   491         URLS="${LAN_URLS} ${@}"
   492     else
   493         URLS="${@} ${LAN_URLS}"
   494     fi
   495 
   496     # Scan all URLs in turn, and try to grab a tarball from there
   497     CT_DoSetProxy ${CT_PROXY_TYPE}
   498     for ext in ${first_ext} .tar.bz2 .tar.gz .tgz .tar ''; do
   499         # Try all urls in turn
   500         for url in ${URLS}; do
   501             CT_DoLog DEBUG "Trying '${url}/${file}${ext}'"
   502             CT_DoGetFile "${url}/${file}${ext}"
   503             if [ -f "${file}${ext}" ]; then
   504                 CT_DoLog DEBUG "Got '${file}' from the Internet"
   505                 if [ "${CT_SAVE_TARBALLS}" = "y" ]; then
   506                     # The file may already exist if downloads are forced: remove it first
   507                     CT_DoLog EXTRA "Saving '${file}' to local storage"
   508                     CT_DoExecLog ALL rm -f "${CT_LOCAL_TARBALLS_DIR}/${file}${ext}"
   509                     CT_DoExecLog ALL mv -f "${file}${ext}" "${CT_LOCAL_TARBALLS_DIR}"
   510                     CT_DoExecLog ALL ln -s "${CT_LOCAL_TARBALLS_DIR}/${file}${ext}" "${file}${ext}"
   511                 fi
   512                 return 0
   513             fi
   514         done
   515     done
   516     CT_Popd
   517 
   518     CT_Abort "Could not retrieve '${file}'."
   519 }
   520 
   521 # Extract a tarball and patch the resulting sources if necessary.
   522 # Some tarballs need to be extracted in specific places. Eg.: glibc addons
   523 # must be extracted in the glibc directory; uCLibc locales must be extracted
   524 # in the extra/locale sub-directory of uClibc.
   525 CT_ExtractAndPatch() {
   526     local file="$1"
   527     local base_file=$(echo "${file}" |cut -d - -f 1)
   528     local ver_file=$(echo "${file}" |cut -d - -f 2-)
   529     local official_patch_dir
   530     local custom_patch_dir
   531     local libc_addon
   532     local ext=$(CT_GetFileExtension "${file}")
   533     CT_TestAndAbort "'${file}' not found in '${CT_TARBALLS_DIR}'" -z "${ext}"
   534     local full_file="${CT_TARBALLS_DIR}/${file}${ext}"
   535 
   536     CT_Pushd "${CT_SRC_DIR}"
   537 
   538     # Add-ons need a little love, really.
   539     case "${file}" in
   540         glibc-[a-z]*-*|eglibc-[a-z]*-*)
   541             CT_TestAndAbort "Trying to extract the C-library addon/locales '${file}' when C-library not yet extracted" ! -d "${CT_LIBC_FILE}"
   542             cd "${CT_LIBC_FILE}"
   543             libc_addon=y
   544             [ -f ".${file}.extracted" ] && return 0
   545             touch ".${file}.extracted"
   546             ;;
   547         uClibc-locale-*)
   548             CT_TestAndAbort "Trying to extract the C-library addon/locales '${file}' when C-library not yet extracted" ! -d "${CT_LIBC_FILE}"
   549             cd "${CT_LIBC_FILE}/extra/locale"
   550             libc_addon=y
   551             [ -f ".${file}.extracted" ] && return 0
   552             touch ".${file}.extracted"
   553             ;;
   554     esac
   555 
   556     # If the directory exists, then consider extraction and patching done
   557     if [ -d "${file}" ]; then
   558         CT_DoLog DEBUG "Already extracted '${file}'"
   559         return 0
   560     fi
   561 
   562     CT_DoLog EXTRA "Extracting and patching '${file}'"
   563     case "${ext}" in
   564         .tar.bz2)     CT_DoExecLog ALL tar xvjf "${full_file}";;
   565         .tar.gz|.tgz) CT_DoExecLog ALL tar xvzf "${full_file}";;
   566         .tar)         CT_DoExecLog ALL tar xvf  "${full_file}";;
   567         *)            CT_Abort "Don't know how to handle '${file}': unknown extension" ;;
   568     esac
   569 
   570     # Snapshots might not have the version number in the extracted directory
   571     # name. This is also the case for some (odd) packages, such as D.U.M.A.
   572     # Overcome this issue by symlink'ing the directory.
   573     if [ ! -d "${file}" -a "${libc_addon}" != "y" ]; then
   574         case "${ext}" in
   575             .tar.bz2)     base=$(tar tjf "${full_file}" |head -n 1 |cut -d / -f 1 || true);;
   576             .tar.gz|.tgz) base=$(tar tzf "${full_file}" |head -n 1 |cut -d / -f 1 || true);;
   577             .tar)         base=$(tar tf  "${full_file}" |head -n 1 |cut -d / -f 1 || true);;
   578         esac
   579         CT_TestOrAbort "There was a problem when extracting '${file}'" -d "${base}" -o "${base}" != "${file}"
   580         ln -s "${base}" "${file}"
   581     fi
   582 
   583     # Kludge: outside this function, we wouldn't know if we had just extracted
   584     # a libc addon, or a plain package. Apply patches now.
   585     if [ "${libc_addon}" = "y" ]; then
   586         # Some addon tarballs directly contain the correct addon directory,
   587         # while others have the addon directory named after the tarball.
   588         # Fix that by always using the short name (eg: linuxthreads, ports, etc...)
   589         addon_short_name=$(echo "${file}" |sed -r -e 's/^[^-]+-([^-]+)-.*$/\1/;')
   590         if [ ! -d "${addon_short_name}" ]; then
   591             mv "${file}" "${addon_short_name}"
   592             # Keep a symlink to avoid re-extracting later on.
   593             ln -s "${addon_short_name}" "${file}"
   594         fi
   595         # If libc addon, we're already in the correct place
   596     else
   597         cd "${file}"
   598     fi
   599 
   600     official_patch_dir=
   601     custom_patch_dir=
   602     [ "${CT_CUSTOM_PATCH_ONLY}" = "y" ] || official_patch_dir="${CT_LIB_DIR}/patches/${base_file}/${ver_file}"
   603     [ "${CT_CUSTOM_PATCH}" = "y" ] && custom_patch_dir="${CT_CUSTOM_PATCH_DIR}/${base_file}/${ver_file}"
   604     for patch_dir in "${official_patch_dir}" "${custom_patch_dir}"; do
   605         if [ -n "${patch_dir}" -a -d "${patch_dir}" ]; then
   606             for p in "${patch_dir}"/*.patch; do
   607                 if [ -f "${p}" ]; then
   608                     CT_DoLog DEBUG "Applying patch '${p}'"
   609                     CT_DoExecLog ALL patch -g0 -F1 -p1 -f <"${p}"
   610                     CT_TestAndAbort "Failed while applying patch file '${p}'" ${PIPESTATUS[0]} -ne 0
   611                 fi
   612             done
   613         fi
   614     done
   615 
   616     if [ "${CT_OVERIDE_CONFIG_GUESS_SUB}" = "y" ]; then
   617         CT_DoLog ALL "Overiding config.guess and config.sub"
   618         for cfg in config_guess config_sub; do
   619             eval ${cfg}="${CT_LIB_DIR}/tools/${cfg/_/.}"
   620             [ -e "${CT_TOP_DIR}/tools/${cfg/_/.}" ] && eval ${cfg}="${CT_TOP_DIR}/tools/${cfg/_/.}"
   621             # Can't use CT_DoExecLog because of the '{} \;' to be passed un-mangled to find
   622             find . -type f -name "${cfg/_/.}" -exec cp -v "${!cfg}" {} \; |CT_DoLog ALL
   623         done
   624     fi
   625 
   626     CT_Popd
   627 }
   628 
   629 # Two wrappers to call config.(guess|sub) either from CT_TOP_DIR or CT_LIB_DIR.
   630 # Those from CT_TOP_DIR, if they exist, will be be more recent than those from CT_LIB_DIR.
   631 CT_DoConfigGuess() {
   632     if [ -x "${CT_TOP_DIR}/tools/config.guess" ]; then
   633         "${CT_TOP_DIR}/tools/config.guess"
   634     else
   635         "${CT_LIB_DIR}/tools/config.guess"
   636     fi
   637 }
   638 
   639 CT_DoConfigSub() {
   640     if [ -x "${CT_TOP_DIR}/tools/config.sub" ]; then
   641         "${CT_TOP_DIR}/tools/config.sub" "$@"
   642     else
   643         "${CT_LIB_DIR}/tools/config.sub" "$@"
   644     fi
   645 }
   646 
   647 # Compute the target tuple from what is provided by the user
   648 # Usage: CT_DoBuildTargetTuple
   649 # In fact this function takes the environment variables to build the target
   650 # tuple. It is needed both by the normal build sequence, as well as the
   651 # sample saving sequence.
   652 CT_DoBuildTargetTuple() {
   653     # Set the endianness suffix, and the default endianness gcc option
   654     case "${CT_ARCH_BE},${CT_ARCH_LE}" in
   655         y,) target_endian_eb=eb
   656             target_endian_el=
   657             CT_ARCH_ENDIAN_CFLAG="-mbig-endian"
   658             CT_ARCH_ENDIAN_LDFLAG="-EB"
   659             ;;
   660         ,y) target_endian_eb=
   661             target_endian_el=el
   662             CT_ARCH_ENDIAN_CFLAG="-mlittle-endian"
   663             CT_ARCH_ENDIAN_LDFLAG="-EL"
   664             ;;
   665     esac
   666 
   667     # Build the default architecture tuple part
   668     CT_TARGET_ARCH="${CT_ARCH}"
   669 
   670     # Set defaults for the system part of the tuple. Can be overriden
   671     # by architecture-specific values.
   672     case "${CT_LIBC}" in
   673         none)   CT_TARGET_SYS=elf;;
   674         *glibc) CT_TARGET_SYS=gnu;;
   675         uClibc) CT_TARGET_SYS=uclibc;;
   676     esac
   677 
   678     # Transform the ARCH into a kernel-understandable ARCH
   679     CT_KERNEL_ARCH="${CT_ARCH}"
   680 
   681     # Set the default values for ARCH, ABI, CPU, TUNE, FPU and FLOAT
   682     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
   683     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
   684     [ "${CT_ARCH_ARCH}"     ] && { CT_ARCH_ARCH_CFLAG="-march=${CT_ARCH_ARCH}";  CT_ARCH_WITH_ARCH="--with-arch=${CT_ARCH_ARCH}"; }
   685     [ "${CT_ARCH_ABI}"      ] && { CT_ARCH_ABI_CFLAG="-mabi=${CT_ARCH_ABI}";     CT_ARCH_WITH_ABI="--with-abi=${CT_ARCH_ABI}";    }
   686     [ "${CT_ARCH_CPU}"      ] && { CT_ARCH_CPU_CFLAG="-mcpu=${CT_ARCH_CPU}";     CT_ARCH_WITH_CPU="--with-cpu=${CT_ARCH_CPU}";    }
   687     [ "${CT_ARCH_TUNE}"     ] && { CT_ARCH_TUNE_CFLAG="-mtune=${CT_ARCH_TUNE}";  CT_ARCH_WITH_TUNE="--with-tune=${CT_ARCH_TUNE}"; }
   688     [ "${CT_ARCH_FPU}"      ] && { CT_ARCH_FPU_CFLAG="-mfpu=${CT_ARCH_FPU}";     CT_ARCH_WITH_FPU="--with-fpu=${CT_ARCH_FPU}";    }
   689     [ "${CT_ARCH_FLOAT_SW}" ] && { CT_ARCH_FLOAT_CFLAG="-msoft-float";           CT_ARCH_WITH_FLOAT="--with-float=soft";          }
   690 
   691     # Build the default kernel tuple part
   692     CT_TARGET_KERNEL="${CT_KERNEL}"
   693 
   694     # Overide the default values with the components specific settings
   695     CT_DoArchTupleValues
   696     CT_DoKernelTupleValues
   697 
   698     # Finish the target tuple construction
   699     CT_TARGET=$(CT_DoConfigSub "${CT_TARGET_ARCH}-${CT_TARGET_VENDOR:-unknown}-${CT_TARGET_KERNEL}${CT_TARGET_KERNEL:+-}${CT_TARGET_SYS}")
   700 
   701     # Prepare the target CFLAGS
   702     CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_ENDIAN_CFLAG}"
   703     CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_ARCH_CFLAG}"
   704     CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_ABI_CFLAG}"
   705     CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_CPU_CFLAG}"
   706     CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_TUNE_CFLAG}"
   707     CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_FPU_CFLAG}"
   708     CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_FLOAT_CFLAG}"
   709 
   710     # Now on for the target LDFLAGS
   711     CT_ARCH_TARGET_LDFLAGS="${CT_ARCH_TARGET_LDFLAGS} ${CT_ARCH_ENDIAN_LDFLAG}"
   712 }
   713 
   714 # This function does pause the build until the user strikes "Return"
   715 # Usage: CT_DoPause [optional_message]
   716 CT_DoPause() {
   717     local foo
   718     local message="${1:-Pausing for your pleasure}"
   719     CT_DoLog INFO "${message}"
   720     read -p "Press 'Enter' to continue, or Ctrl-C to stop..." foo >&6
   721     return 0
   722 }
   723 
   724 # This function saves the state of the toolchain to be able to restart
   725 # at any one point
   726 # Usage: CT_DoSaveState <next_step_name>
   727 CT_DoSaveState() {
   728 	[ "${CT_DEBUG_CT_SAVE_STEPS}" = "y" ] || return 0
   729     local state_name="$1"
   730     local state_dir="${CT_STATE_DIR}/${state_name}"
   731 
   732     CT_DoLog DEBUG "Saving state to restart at step '${state_name}'..."
   733     rm -rf "${state_dir}"
   734     mkdir -p "${state_dir}"
   735 
   736     case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
   737         y)  tar_opt=z; tar_ext=.gz;;
   738         *)  tar_opt=;  tar_ext=;;
   739     esac
   740 
   741     CT_DoLog DEBUG "  Saving environment and aliases"
   742     # We must omit shell functions, and some specific bash variables
   743     # that break when restoring the environment, later. We could do
   744     # all the processing in the gawk script, but a sed is easier...
   745     set |gawk '
   746               BEGIN { _p = 1; }
   747               $0~/^[^ ]+ \(\)/ { _p = 0; }
   748               _p == 1
   749               $0 == "}" { _p = 1; }
   750               ' |sed -r -e '/^BASH_(ARGC|ARGV|LINENO|SOURCE|VERSINFO)=/d;
   751                            /^(UID|EUID)=/d;
   752                            /^(FUNCNAME|GROUPS|PPID|SHELLOPTS)=/d;' >"${state_dir}/env.sh"
   753 
   754     CT_DoLog DEBUG "  Saving CT_CC_CORE_STATIC_PREFIX_DIR='${CT_CC_CORE_STATIC_PREFIX_DIR}'"
   755     CT_Pushd "${CT_CC_CORE_STATIC_PREFIX_DIR}"
   756     CT_DoExecLog DEBUG tar cv${tar_opt}f "${state_dir}/cc_core_static_prefix_dir.tar${tar_ext}" .
   757     CT_Popd
   758 
   759     CT_DoLog DEBUG "  Saving CT_CC_CORE_SHARED_PREFIX_DIR='${CT_CC_CORE_SHARED_PREFIX_DIR}'"
   760     CT_Pushd "${CT_CC_CORE_SHARED_PREFIX_DIR}"
   761     CT_DoExecLog DEBUG tar cv${tar_opt}f "${state_dir}/cc_core_shared_prefix_dir.tar${tar_ext}" .
   762     CT_Popd
   763 
   764     CT_DoLog DEBUG "  Saving CT_PREFIX_DIR='${CT_PREFIX_DIR}'"
   765     CT_Pushd "${CT_PREFIX_DIR}"
   766     CT_DoExecLog DEBUG tar cv${tar_opt}f "${state_dir}/prefix_dir.tar${tar_ext}" --exclude '*.log' .
   767     CT_Popd
   768 
   769     if [ "${CT_LOG_TO_FILE}" = "y" ]; then
   770         CT_DoLog DEBUG "  Saving log file"
   771         exec >/dev/null
   772         case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
   773             y)  gzip -3 -c "${CT_LOG_FILE}"  >"${state_dir}/log.gz";;
   774             *)  cat "${CT_LOG_FILE}" >"${state_dir}/log";;
   775         esac
   776         exec >>"${CT_LOG_FILE}"
   777     fi
   778 }
   779 
   780 # This function restores a previously saved state
   781 # Usage: CT_DoLoadState <state_name>
   782 CT_DoLoadState(){
   783     local state_name="$1"
   784     local state_dir="${CT_STATE_DIR}/${state_name}"
   785     local old_RESTART="${CT_RESTART}"
   786     local old_STOP="${CT_STOP}"
   787 
   788     CT_TestOrAbort "The previous build did not reach the point where it could be restarted at '${CT_RESTART}'" -d "${state_dir}"
   789 
   790     # We need to do something special with the log file!
   791     if [ "${CT_LOG_TO_FILE}" = "y" ]; then
   792         exec >"${state_dir}/tail.log"
   793     fi
   794     CT_DoLog INFO "Restoring state at step '${state_name}', as requested."
   795 
   796     case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
   797         y)  tar_opt=z; tar_ext=.gz;;
   798         *)  tar_opt=;  tar_ext=;;
   799     esac
   800 
   801     CT_DoLog DEBUG "  Removing previous build directories"
   802     chmod -R u+rwX "${CT_PREFIX_DIR}" "${CT_CC_CORE_SHARED_PREFIX_DIR}" "${CT_CC_CORE_STATIC_PREFIX_DIR}"
   803     rm -rf         "${CT_PREFIX_DIR}" "${CT_CC_CORE_SHARED_PREFIX_DIR}" "${CT_CC_CORE_STATIC_PREFIX_DIR}"
   804     mkdir -p       "${CT_PREFIX_DIR}" "${CT_CC_CORE_SHARED_PREFIX_DIR}" "${CT_CC_CORE_STATIC_PREFIX_DIR}"
   805 
   806     CT_DoLog DEBUG "  Restoring CT_PREFIX_DIR='${CT_PREFIX_DIR}'"
   807     CT_Pushd "${CT_PREFIX_DIR}"
   808     CT_DoExecLog DEBUG tar xv${tar_opt}f "${state_dir}/prefix_dir.tar${tar_ext}"
   809     CT_Popd
   810 
   811     CT_DoLog DEBUG "  Restoring CT_CC_CORE_SHARED_PREFIX_DIR='${CT_CC_CORE_SHARED_PREFIX_DIR}'"
   812     CT_Pushd "${CT_CC_CORE_SHARED_PREFIX_DIR}"
   813     CT_DoExecLog DEBUG tar xv${tar_opt}f "${state_dir}/cc_core_shared_prefix_dir.tar${tar_ext}"
   814     CT_Popd
   815 
   816     CT_DoLog DEBUG "  Restoring CT_CC_CORE_STATIC_PREFIX_DIR='${CT_CC_CORE_STATIC_PREFIX_DIR}'"
   817     CT_Pushd "${CT_CC_CORE_STATIC_PREFIX_DIR}"
   818     CT_DoExecLog DEBUG tar xv${tar_opt}f "${state_dir}/cc_core_static_prefix_dir.tar${tar_ext}"
   819     CT_Popd
   820 
   821     # Restore the environment, discarding any error message
   822     # (for example, read-only bash internals)
   823     CT_DoLog DEBUG "  Restoring environment"
   824     . "${state_dir}/env.sh" >/dev/null 2>&1 || true
   825 
   826     # Restore the new RESTART and STOP steps
   827     CT_RESTART="${old_RESTART}"
   828     CT_STOP="${old_STOP}"
   829     unset old_stop old_restart
   830 
   831     if [ "${CT_LOG_TO_FILE}" = "y" ]; then
   832         CT_DoLog DEBUG "  Restoring log file"
   833         exec >/dev/null
   834         case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
   835             y)  zcat "${state_dir}/log.gz" >"${CT_LOG_FILE}";;
   836             *)  cat "${state_dir}/log" >"${CT_LOG_FILE}";;
   837         esac
   838         cat "${state_dir}/tail.log" >>"${CT_LOG_FILE}"
   839         exec >>"${CT_LOG_FILE}"
   840         rm -f "${state_dir}/tail.log"
   841     fi
   842 }